// Token: 0x060002C9 RID: 713
 // RVA: 0x000079B8 File Offset: 0x00005BB8
 public TraceJsonReader(JsonReader innerReader)
 {
     this._innerReader = innerReader;
     this._sw = new StringWriter(CultureInfo.InvariantCulture);
     this._textWriter = new JsonTextWriter(this._sw);
     this._textWriter.Formatting = Formatting.Indented;
 }
        public void ArrayBasicValidation_Pass()
        {
            JSchema schema = new JSchema();
            schema.Type = JSchemaType.Array;
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer
            });

            SchemaValidationEventArgs a = null;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = schema;
            validatingWriter.ValidationEventHandler += (sender, args) => { a = args; };

            validatingWriter.WriteStartArray();
            validatingWriter.WriteValue(10);
            validatingWriter.WriteValue(10);
            validatingWriter.WriteEndArray();

            Assert.IsNull(a);

            Assert.AreEqual("[10,10]", sw.ToString());
        }
 private static string Format(object o)
 {
     JsonTextWriter writer = new JsonTextWriter();
     writer.ValueFormatter = new DateTimeFormatter();
     writer.WriteValue(o);
     return writer.ToString();
 }
Example #4
0
    public void EntitiesTest()
    {
      Purchase purchase = new Purchase() { Id = 1 };
      purchase.PurchaseLine.Add(new PurchaseLine() { Id = 1, Purchase = purchase });
      purchase.PurchaseLine.Add(new PurchaseLine() { Id = 2, Purchase = purchase });

      StringWriter sw = new StringWriter();
      JsonSerializer serializer = new JsonSerializer();
      serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

      using (JsonWriter jw = new JsonTextWriter(sw))
      {
        jw.Formatting = Formatting.Indented;

        serializer.Serialize(jw, purchase);
      }

      string json = sw.ToString();

      Assert.AreEqual(@"{
  ""Id"": 1,
  ""PurchaseLine"": [
    {
      ""Id"": 1,
      ""PurchaseReference"": {
        ""EntityKey"": null,
        ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"",
        ""SourceRoleName"": ""PurchaseLine"",
        ""TargetRoleName"": ""Purchase"",
        ""RelationshipSet"": null,
        ""IsLoaded"": false
      },
      ""EntityState"": 1,
      ""EntityKey"": null
    },
    {
      ""Id"": 2,
      ""PurchaseReference"": {
        ""EntityKey"": null,
        ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"",
        ""SourceRoleName"": ""PurchaseLine"",
        ""TargetRoleName"": ""Purchase"",
        ""RelationshipSet"": null,
        ""IsLoaded"": false
      },
      ""EntityState"": 1,
      ""EntityKey"": null
    }
  ],
  ""EntityState"": 1,
  ""EntityKey"": null
}", json);

      Purchase newPurchase = JsonConvert.DeserializeObject<Purchase>(json);
      Assert.AreEqual(1, newPurchase.Id);

      Assert.AreEqual(2, newPurchase.PurchaseLine.Count);
      Assert.AreEqual(1, newPurchase.PurchaseLine.ElementAt(0).Id);
      Assert.AreEqual(2, newPurchase.PurchaseLine.ElementAt(1).Id);
    }
Example #5
0
        //IEnumerable<T> WhereActiveOrderBy(
        //REFACTOR: we're building things up in memory, and inefficiently as well...
        //MESS: NAIVE: these are nasty messes of code as well.
        public ActionResult Contracts()
        {
            //get a list with the newest employees/offices for each employee/office code.
            var newestOffices = db.newestOffices();
            var newestEmployees = db.newestEmployees();

            return authenticatedAction(new String[] { "UT", "UR" }, () => {
                content:
                var result = makeJSONResult();
                using (JsonTextWriter w = new JsonTextWriter()) {
                    w.WriteStartArray();
                    foreach (Contract c in db.Contracts.WAOBTL()) {
                        w.writeSharedJSONMembers(c);
                        w.writeSharedJSONProlog();
                        foreach (Company co in db.Companies.Where(tco => tco.contractCode == c.code).WAOBTL()) {
                            w.writeSharedJSONMembers(co);
                            w.WriteMember("offices");
                            w.WriteStartArray();
                            foreach (Office o in newestOffices
                                .Where(o => o.companyCode == co.code)
                                .Where(o => o.contractCode == c.code)
                                .WAOBTL()
                                 ) {
                                w.WriteStartObject();
                                //LOOK AT THIS! WE'RE NOT JUST SENDING OVER THE CODE, BUT THE VERSION AS WELL!
                                w.WriteMember("code");
                                w.WriteString(o.code + "?" + o.version.ToString());
                                w.WriteMember("description");
                                w.WriteString(o.description);
                                w.WriteEndObject();
                            }
                            w.WriteEndArray();
                            w.WriteMember("employees");
                            w.WriteStartArray();
                            foreach (Employee e in newestEmployees
                                .Where(e => e.companyCode == co.code)
                                .Where(e => e.contractCode == c.code)
                                .WAOBTL()) {
                                w.WriteStartObject();
                                //LOOK AT THIS! WE'RE NOT JUST SENDING OVER THE CODE, BUT THE VERSION AS WELL!
                                w.WriteMember("code");
                                w.WriteString(e.code + "?" + e.version.ToString());
                                w.WriteMember("description");
                                w.WriteString(e.firstName + " " + e.lastName);
                                w.WriteEndObject();
                            }
                            w.WriteEndArray();
                            w.WriteEndObject();
                        }
                        w.writeSharedJSONEpilog();
                    }
                    w.WriteEndArray();
                    result.Content = w.ToString();
                }
                logger.Debug("TreesController.Contracts accessed.");
                return result;
            });
        }
Example #6
0
 public void Export()
 {
     ControlExporter exporter = new ControlExporter();
     JsonTextWriter writer = new JsonTextWriter();
     HtmlGenericControl span = new HtmlGenericControl("span");
     span.InnerText = "Happy & shiny people!";
     exporter.Export(new ExportContext(), span, writer);
     Assert.AreEqual("[\"<span>Happy &amp; shiny people!<\\/span>\"]", writer.ToString());
 }
 public void ExactSelection()
 {
     JsonTextWriter writer = new JsonTextWriter();
     CompositeFormatter compositeFormatter = new CompositeFormatter();
     compositeFormatter.AddFormatter(typeof(object), new TestFormatter());
     IJsonFormatter formatter = compositeFormatter.SelectFormatter(typeof(object));
     formatter.Format(new object(), writer);
     Assert.AreEqual("\"(object)\"", writer.ToString());
 }
 public void Formatting()
 {
     ControlFormatter formatter = new ControlFormatter();
     JsonTextWriter writer = new JsonTextWriter();
     HtmlGenericControl span = new HtmlGenericControl("span");
     span.InnerText = "Happy & shiny people!";
     formatter.Format(span, writer);
     Assert.AreEqual("\"<span\\>Happy &amp; shiny people!</span\\>\"", writer.ToString());
 }
        public void Example()
        {
            #region Usage
            string schemaJson = @"{
              'description': 'A person',
              'type': 'object',
              'properties': {
                'name': {'type':'string'},
                'hobbies': {
                  'type': 'array',
                  'items': {'type':'string'}
                }
              }
            }";

            Person p = new Person
            {
                Name = "James",
                Hobbies = new List<string>
                {
                    ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
                }
            };

            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);
            writer.Formatting = Formatting.Indented;

            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = JSchema.Parse(schemaJson);

            IList<string> messages = new List<string>();
            validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);

            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(validatingWriter, p);

            Console.WriteLine(stringWriter);
            // {
            //   "Name": "James",
            //   "Hobbies": [
            //     ".NET",
            //     "Blogging",
            //     "Reading",
            //     "Xbox",
            //     "LOLCATS"
            //   ]
            // }

            bool isValid = (messages.Count == 0);

            Console.WriteLine(isValid);
            // true
            #endregion

            Assert.IsTrue(isValid);
        }
Example #10
0
 /// <summary>
 /// Creates an instance of <see cref="JRaw"/> with the content of the reader's current token.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <returns>An instance of <see cref="JRaw"/> with the content of the reader's current token.</returns>
 public static JRaw Create(JsonReader reader)
 {
     using (var sw = new StringWriter(CultureInfo.InvariantCulture))
     using (var jsonWriter = new JsonTextWriter(sw))
     {
         jsonWriter.WriteToken(reader);
         return new JRaw(sw.ToString());
     }
 }
Example #11
0
        public TraceJsonReader(JsonReader innerReader)
        {
            _innerReader = innerReader;

            _sw = new StringWriter(CultureInfo.InvariantCulture);
            // prefix the message in the stringwriter to avoid concat with a potentially large JSON string
            _sw.Write("Deserialized JSON: " + Environment.NewLine);

            _textWriter = new JsonTextWriter(_sw);
            _textWriter.Formatting = Formatting.Indented;
        }
 // Token: 0x060002DC RID: 732
 // RVA: 0x0002F550 File Offset: 0x0002D750
 public TraceJsonWriter(JsonWriter innerWriter)
 {
     this._innerWriter = innerWriter;
     this._sw = new StringWriter(CultureInfo.InvariantCulture);
     this._textWriter = new JsonTextWriter(this._sw);
     this._textWriter.Formatting = Formatting.Indented;
     this._textWriter.Culture = innerWriter.Culture;
     this._textWriter.DateFormatHandling = innerWriter.DateFormatHandling;
     this._textWriter.DateFormatString = innerWriter.DateFormatString;
     this._textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling;
     this._textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling;
 }
Example #13
0
		// Token: 0x060005D8 RID: 1496
		// RVA: 0x00035994 File Offset: 0x00033B94
		public static JRaw Create(JsonReader reader)
		{
			JRaw result;
			using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
			{
				using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
				{
					jsonTextWriter.WriteToken(reader);
					result = new JRaw(stringWriter.ToString());
				}
			}
			return result;
		}
        private static string Format(object o)
        {
            ComponentFormatter componentFormatter = new ComponentFormatter();

            CompositeFormatter compositeFormatter = new CompositeFormatter();
            compositeFormatter.AddFormatter(typeof(Car), componentFormatter);
            compositeFormatter.AddFormatter(typeof(Person), componentFormatter);

            JsonTextWriter writer = new JsonTextWriter();
            writer.ValueFormatter = compositeFormatter;

            writer.WriteValue(o);
            return writer.ToString();
        }
    public void Example()
    {
      JsonSchema schema = JsonSchema.Parse(@"{'type': 'object'}");

      // serialize JsonSchema to a string and then write string to a file
      File.WriteAllText(@"c:\schema.json", schema.ToString());

      // serialize JsonSchema directly to a file
      using (StreamWriter file = File.CreateText(@"c:\schema.json"))
      using (JsonTextWriter writer = new JsonTextWriter(file))
      {
        schema.WriteTo(writer);
      }
    }
        public void Example()
        {
            #region Usage
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("CPU");
                writer.WriteValue("Intel");
                writer.WritePropertyName("PSU");
                writer.WriteValue("500W");
                writer.WritePropertyName("Drives");
                writer.WriteStartArray();
                writer.WriteValue("DVD read/writer");
                writer.WriteComment("(broken)");
                writer.WriteValue("500 gigabyte hard drive");
                writer.WriteValue("200 gigabype hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            Console.WriteLine(sb.ToString());
            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion

            Assert.AreEqual(@"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabype hard drive""
  ]
}", sb.ToString());
        }
        public override void EndRequest()
        {
            base.EndRequest();

            Context.Response.ContentType = "application/json";
            
            using (var streamWriter = new StreamWriter(Context.Response.OutputStream))
            using (var writer = new JsonTextWriter(streamWriter))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("c");
                writer.WriteValue(_channelId);
                writer.WriteEndObject();
            }
        }
Example #18
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;
        }
        public TraceJsonWriter(JsonWriter innerWriter)
        {
            _innerWriter = innerWriter;

            _sw = new StringWriter(CultureInfo.InvariantCulture);
            // prefix the message in the stringwriter to avoid concat with a potentially large JSON string
            _sw.Write("Serialized JSON: " + Environment.NewLine);

            _textWriter = new JsonTextWriter(_sw);
            _textWriter.Formatting = Formatting.Indented;
            _textWriter.Culture = innerWriter.Culture;
            _textWriter.DateFormatHandling = innerWriter.DateFormatHandling;
            _textWriter.DateFormatString = innerWriter.DateFormatString;
            _textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling;
            _textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling;
        }
    public void Example()
    {
      JObject videogameRatings = new JObject(
        new JProperty("Halo", 9),
        new JProperty("Starcraft", 9),
        new JProperty("Call of Duty", 7.5));

      File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());

      // write JSON directly to a file
      using (StreamWriter file = File.CreateText(@"c:\videogames.json"))
      using (JsonTextWriter writer = new JsonTextWriter(file))
      {
        videogameRatings.WriteTo(writer);
      }
    }
Example #21
0
        public void Example()
        {
            #region Usage
            JsonSchema schema = new JsonSchema
            {
                Type = JsonSchemaType.Object
            };

            // serialize JsonSchema to a string and then write string to a file
            File.WriteAllText(@"c:\schema.json", schema.ToString());

            // serialize JsonSchema directly to a file
            using (StreamWriter file = File.CreateText(@"c:\schema.json"))
            using (JsonTextWriter writer = new JsonTextWriter(file))
            {
                schema.WriteTo(writer);
            }
            #endregion
        }
    public void WriteJson()
    {
      JsonObject o = JsonObject.Parse(@"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}");

      StringWriter sw = new StringWriter();
      JsonTextWriter writer = new JsonTextWriter(sw);

      JsonValueConverter converter = new JsonValueConverter();
      converter.WriteJson(writer, o, null);

      string json = sw.ToString();

      Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json);
    }
        public void ArrayBasicValidation_Fail()
        {
            JSchema schema = new JSchema();
            schema.Type = JSchemaType.Array;
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer
            });

            SchemaValidationEventArgs a = null;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = schema;
            validatingWriter.ValidationEventHandler += (sender, args) =>
            {
                a = args;
            };

            validatingWriter.WriteStartArray();

            validatingWriter.WriteValue("string");
            Assert.IsNotNull(a);
            StringAssert.AreEqual("Invalid type. Expected Integer but got String. Path '[0]'.", a.Message);
            Assert.AreEqual("string", a.ValidationError.Value);
            a = null;

            validatingWriter.WriteValue(true);
            Assert.IsNotNull(a);
            StringAssert.AreEqual("Invalid type. Expected Integer but got Boolean. Path '[1]'.", a.Message);
            Assert.AreEqual(true, a.ValidationError.Value);
            a = null;

            validatingWriter.WriteEndArray();
            Assert.IsNull(a);

            Assert.AreEqual(@"[""string"",true]", sw.ToString());
        }
Example #24
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType)
              ? ContentType
              : "application/json";

            if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                using (var writer = new JsonTextWriter(response.Output) { Formatting = Formatting })
                {
                    var serializer = JsonSerializer.Create(SerializerSettings);

                    serializer.Serialize(writer, Data);
                    writer.Flush();
                }
            }
        }
        public void DoNotIndentPrimitiveArray()
        {
            dynamic d = new JObject();
            d.name = "T'om";
            d.items = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
            d.items2 = new JArray("a", "bc",
                new JObject() { new JProperty("aa", "bb"), new JProperty("aa2", "bb"), new JProperty("aa3", "bb") },
                "def");

            JsonSerializer js = new JsonSerializer();
            StringBuilder sb = new StringBuilder();
            using (var stringW = new StringWriter(sb))
            using (var jw = new JsonTextWriter(stringW))
            {
                jw.DollarTag = "";
                jw.Formatting = Formatting.Indented;
                jw.IsIndentPrimitiveArray = false;
                js.Serialize(jw, d);
                var str = sb.ToString().Replace(Environment.NewLine, "\n");
                var expected = @"{
  ""name"": ``T'om``,
  ""items"": [
    1, 2, 3, 4, 5, 6, 7, 8, 9
  ],
  ""items2"": [
    ``a``, ``bc``,
    {
      ""aa"": ``bb``,
      ""aa2"": ``bb``,
      ""aa3"": ``bb``
    },
    ``def``
  ]
}".Replace(Environment.NewLine,"\n");
                Assert.AreEqual(expected, str);
            }
        }
        public void ReadingAndWritingJsonText()
        {
            #region ReadingAndWritingJsonText
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("CPU");
                writer.WriteValue("Intel");
                writer.WritePropertyName("PSU");
                writer.WriteValue("500W");
                writer.WritePropertyName("Drives");
                writer.WriteStartArray();
                writer.WriteValue("DVD read/writer");
                writer.WriteComment("(broken)");
                writer.WriteValue("500 gigabyte hard drive");
                writer.WriteValue("200 gigabype hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion
        }
Example #27
0
        public string ReadJson(JsonReader reader)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw))
            {
                if (reader.TokenType == JsonToken.StartObject)
                {
                    int depth = 1;
                    writer.WriteStartObject();

                    while (depth > 0)
                    {
                        if (!TryRead(reader))
                        {
                            break;
                        }
                        switch (reader.TokenType)
                        {
                        case JsonToken.PropertyName:
                            writer.WritePropertyName(reader.Value.ToString());
                            break;

                        case JsonToken.StartArray:
                            writer.WriteStartArray();
                            break;

                        case JsonToken.Boolean:
                        case JsonToken.Integer:
                        case JsonToken.Float:
                        case JsonToken.String:
                        case JsonToken.Date:
                        case JsonToken.Null:
                            writer.WriteValue(reader.Value);
                            break;

                        case JsonToken.EndArray:
                            writer.WriteEndArray();
                            break;

                        case JsonToken.StartObject:
                            writer.WriteStartObject();
                            depth++;
                            break;

                        case JsonToken.EndObject:
                            writer.WriteEndObject();
                            depth--;
                            break;
                        }
                    }
                    while (depth > 0)
                    {
                        depth--;
                        writer.WriteEndObject();
                    }
                }
            }
            return(sb.ToString());
        }
Example #28
0
        public void Extends_Multiple()
        {
            string json = @"{
  ""type"":""object"",
  ""extends"":{""type"":""string""},
  ""additionalProperties"":{""type"":""string""}
}";

            JsonSchema s = JsonSchema.Parse(json);

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            string newJson = s.ToString();

            Assert.AreEqual(@"{
  ""type"": ""object"",
  ""additionalProperties"": {
    ""type"": ""string""
  },
  ""extends"": {
    ""type"": ""string""
  }
}", newJson);


            json = @"{
  ""type"":""object"",
  ""extends"":[{""type"":""string""}],
  ""additionalProperties"":{""type"":""string""}
}";

            s = JsonSchema.Parse(json);

            writer                = new StringWriter();
            jsonWriter            = new JsonTextWriter(writer);
            jsonWriter.Formatting = Formatting.Indented;

            newJson = s.ToString();

            Assert.AreEqual(@"{
  ""type"": ""object"",
  ""additionalProperties"": {
    ""type"": ""string""
  },
  ""extends"": {
    ""type"": ""string""
  }
}", newJson);


            json = @"{
  ""type"":""object"",
  ""extends"":[{""type"":""string""},{""type"":""object""}],
  ""additionalProperties"":{""type"":""string""}
}";

            s = JsonSchema.Parse(json);

            writer                = new StringWriter();
            jsonWriter            = new JsonTextWriter(writer);
            jsonWriter.Formatting = Formatting.Indented;

            newJson = s.ToString();

            Assert.AreEqual(@"{
  ""type"": ""object"",
  ""additionalProperties"": {
    ""type"": ""string""
  },
  ""extends"": [
    {
      ""type"": ""string""
    },
    {
      ""type"": ""object""
    }
  ]
}", newJson);
        }
Example #29
0
        public void WriteReadWrite()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter jsonWriter = new JsonTextWriter(sw)
            {
                Formatting = Formatting.Indented
            })
            {
                jsonWriter.WriteStartArray();
                jsonWriter.WriteValue(true);

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("integer");
                jsonWriter.WriteValue(99);
                jsonWriter.WritePropertyName("string");
                jsonWriter.WriteValue("how now brown cow?");
                jsonWriter.WritePropertyName("array");

                jsonWriter.WriteStartArray();
                for (int i = 0; i < 5; i++)
                {
                    jsonWriter.WriteValue(i);
                }

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("decimal");
                jsonWriter.WriteValue(990.00990099m);
                jsonWriter.WriteEndObject();

                jsonWriter.WriteValue(5);
                jsonWriter.WriteEndArray();

                jsonWriter.WriteEndObject();

                jsonWriter.WriteValue("This is a string.");
                jsonWriter.WriteNull();
                jsonWriter.WriteNull();
                jsonWriter.WriteEndArray();
            }

            string json = sb.ToString();

            JsonSerializer serializer = new JsonSerializer();

            object jsonObject = serializer.Deserialize(new JsonTextReader(new StringReader(json)));

            sb = new StringBuilder();
            sw = new StringWriter(sb);

            using (JsonWriter jsonWriter = new JsonTextWriter(sw)
            {
                Formatting = Formatting.Indented
            })
            {
                serializer.Serialize(jsonWriter, jsonObject);
            }

            Assert.AreEqual(json, sb.ToString());
        }
Example #30
0
        static async void bar(JObject o2, int i, int num)
        {
            var price = 300;

            if (Convert.ToInt32(o2["Seat" + i][0]["flag"]) == 0)
            {
                var flag = Convert.ToInt32(o2["Seat" + i][0]["flag"]);
                flag = 1;
                o2["Seat" + i][0]["flag"] = flag;

                o2["Seat" + i][0]["price"] = price;

                File.WriteAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json", o2.ToString());

                // write JSON directly to a file
                using (StreamWriter file1 = File.CreateText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                    using (JsonTextWriter writer = new JsonTextWriter(file1))
                    {
                        o2.WriteTo(writer);
                    }
                await Task.Delay(10000);

                JObject o1 = JObject.Parse(File.ReadAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"));
                // read JSON directly from a file
                using (StreamReader file = File.OpenText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        o2 = (JObject)JToken.ReadFrom(reader);
                    }



                var clicks = Convert.ToInt32(o2["Seat" + i][0]["clicks"]);
                if (clicks > 1)
                {
                    price = clicks * price;
                }
                if (Convert.ToInt32(o2["Seat" + i][0]["deselected"]) != 0)
                {
                    var desel = Convert.ToInt32(o2["Seat" + i][0]["deselected"]);
                    price = (price / clicks) * (clicks - desel);
                }
                o2["Seat" + i][0]["clicks"] = 0;
                o2["Seat" + i][0]["price"]  = price;

                o2["Seat" + i][0]["flag"]    = 0;
                o2["Seat" + i][0]["blocked"] = "true";
                File.WriteAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json", o2.ToString());

                // write JSON directly to a file
                using (StreamWriter file1 = File.CreateText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                    using (JsonTextWriter writer = new JsonTextWriter(file1))
                    {
                        o2.WriteTo(writer);
                    }
                Console.WriteLine("{0}", price);
            }

            else
            {
                await Task.Delay(10000);

                JObject o1 = JObject.Parse(File.ReadAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"));
                // read JSON directly from a file
                using (StreamReader file = File.OpenText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        o2 = (JObject)JToken.ReadFrom(reader);
                    }

                price = Convert.ToInt32(o2["Seat" + i][0]["price"]);
                Console.WriteLine("{0}", price);
            }
        }
        public async Task Test_CollectionShowObjectJsonWriter_WriteObject_JsonWriter_Only_CollectionSeasons_Property()
        {
            ITraktCollectionShow traktCollectionShow = new TraktCollectionShow
            {
                CollectionSeasons = new List <ITraktCollectionShowSeason>
                {
                    new TraktCollectionShowSeason
                    {
                        Number   = 1,
                        Episodes = new List <ITraktCollectionShowEpisode>
                        {
                            new TraktCollectionShowEpisode
                            {
                                Number      = 1,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            },
                            new TraktCollectionShowEpisode
                            {
                                Number      = 2,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            }
                        }
                    },
                    new TraktCollectionShowSeason
                    {
                        Number   = 2,
                        Episodes = new List <ITraktCollectionShowEpisode>
                        {
                            new TraktCollectionShowEpisode
                            {
                                Number      = 1,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            },
                            new TraktCollectionShowEpisode
                            {
                                Number      = 2,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            }
                        }
                    }
                }
            };

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    var traktJsonWriter = new CollectionShowObjectJsonWriter();
                    await traktJsonWriter.WriteObjectAsync(jsonWriter, traktCollectionShow);

                    stringWriter.ToString().Should().Be(@"{""seasons"":[{""number"":1,""episodes"":[{""number"":1," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}," +
                                                        @"{""number"":2," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}]}," +
                                                        @"{""number"":2,""episodes"":[{""number"":1," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}," +
                                                        @"{""number"":2," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}]}]}");
                }
        }
        private async Task <string> SerializeJsonNetManualAsync(TestClass c, Formatting formatting)
        {
            StringWriter   sw     = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);

            writer.Formatting = formatting;

            await writer.WriteStartObjectAsync();

            await writer.WritePropertyNameAsync("strings");

            await writer.WriteStartArrayAsync();

            foreach (string s in c.strings)
            {
                await writer.WriteValueAsync(s);
            }
            await writer.WriteEndArrayAsync();

            await writer.WritePropertyNameAsync("dictionary");

            await writer.WriteStartObjectAsync();

            foreach (KeyValuePair <string, int> keyValuePair in c.dictionary)
            {
                await writer.WritePropertyNameAsync(keyValuePair.Key);

                await writer.WriteValueAsync(keyValuePair.Value);
            }
            await writer.WriteEndObjectAsync();

            await writer.WritePropertyNameAsync("Name");

            await writer.WriteValueAsync(c.Name);

            await writer.WritePropertyNameAsync("Now");

            await writer.WriteValueAsync(c.Now);

            await writer.WritePropertyNameAsync("BigNumber");

            await writer.WriteValueAsync(c.BigNumber);

            await writer.WritePropertyNameAsync("Address1");

            await writer.WriteStartObjectAsync();

            await writer.WritePropertyNameAsync("Street");

            await writer.WriteValueAsync(c.BigNumber);

            await writer.WritePropertyNameAsync("Street");

            await writer.WriteValueAsync(c.BigNumber);

            await writer.WritePropertyNameAsync("Street");

            await writer.WriteValueAsync(c.BigNumber);

            await writer.WriteEndObjectAsync();

            await writer.WritePropertyNameAsync("Addresses");

            await writer.WriteStartArrayAsync();

            foreach (Address address in c.Addresses)
            {
                await writer.WriteStartObjectAsync();

                await writer.WritePropertyNameAsync("Street");

                await writer.WriteValueAsync(address.Street);

                await writer.WritePropertyNameAsync("Phone");

                await writer.WriteValueAsync(address.Phone);

                await writer.WritePropertyNameAsync("Entered");

                await writer.WriteValueAsync(address.Entered);

                await writer.WriteEndObjectAsync();
            }
            await writer.WriteEndArrayAsync();

            await writer.WriteEndObjectAsync();

            await writer.FlushAsync();

            return(sw.ToString());
        }
        private async Task <bool> InvokeUserinfoEndpointAsync()
        {
            OpenIdConnectMessage request;

            if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
            {
                request = new OpenIdConnectMessage(Request.Query);
            }

            else if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
            {
                // See http://openid.net/specs/openid-connect-core-1_0.html#FormSerialization
                if (string.IsNullOrWhiteSpace(Request.ContentType))
                {
                    Options.Logger.LogError("The userinfo request was rejected because " +
                                            "the mandatory 'Content-Type' header was missing.");

                    return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "A malformed userinfo request has been received: " +
                                           "the mandatory 'Content-Type' header was missing from the POST request."
                    }));
                }

                // May have media/type; charset=utf-8, allow partial match.
                if (!Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                {
                    Options.Logger.LogError("The userinfo request was rejected because an invalid 'Content-Type' " +
                                            "header was received: {ContentType}.", Request.ContentType);

                    return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "A malformed userinfo request has been received: " +
                                           "the 'Content-Type' header contained an unexcepted value. " +
                                           "Make sure to use 'application/x-www-form-urlencoded'."
                    }));
                }

                request = new OpenIdConnectMessage(await Request.ReadFormAsync());
            }

            else
            {
                Options.Logger.LogError("The userinfo request was rejected because an invalid " +
                                        "HTTP method was received: {Method}.", Request.Method);

                return(await SendErrorPageAsync(new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = "A malformed userinfo request has been received: " +
                                       "make sure to use either GET or POST."
                }));
            }

            // Insert the userinfo request in the OWIN context.
            Context.SetOpenIdConnectRequest(request);

            string token;

            if (!string.IsNullOrEmpty(request.AccessToken))
            {
                token = request.AccessToken;
            }

            else
            {
                var header = Request.Headers.Get("Authorization");
                if (string.IsNullOrEmpty(header))
                {
                    Options.Logger.LogError("The userinfo request was rejected because " +
                                            "the 'Authorization' header was missing.");

                    return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "A malformed userinfo request has been received."
                    }));
                }

                if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                {
                    Options.Logger.LogError("The userinfo request was rejected because the " +
                                            "'Authorization' header was invalid: {Header}.", header);

                    return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "A malformed userinfo request has been received."
                    }));
                }

                token = header.Substring("Bearer ".Length);
                if (string.IsNullOrEmpty(token))
                {
                    Options.Logger.LogError("The userinfo request was rejected because access token was missing.");

                    return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "A malformed userinfo request has been received."
                    }));
                }
            }

            var ticket = await DeserializeAccessTokenAsync(token, request);

            if (ticket == null)
            {
                Options.Logger.LogError("The userinfo request was rejected because access token was invalid.");

                // Note: an invalid token should result in an unauthorized response
                // but returning a 401 status would invoke the previously registered
                // authentication middleware and potentially replace it by a 302 response.
                // To work around this limitation, a 400 error is returned instead.
                // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoError
                return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "Invalid token."
                }));
            }

            if (!ticket.Properties.ExpiresUtc.HasValue ||
                ticket.Properties.ExpiresUtc < Options.SystemClock.UtcNow)
            {
                Options.Logger.LogError("The userinfo request was rejected because access token was expired.");

                // Note: an invalid token should result in an unauthorized response
                // but returning a 401 status would invoke the previously registered
                // authentication middleware and potentially replace it by a 302 response.
                // To work around this limitation, a 400 error is returned instead.
                // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoError
                return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "Expired token."
                }));
            }

            var validatingContext = new ValidateUserinfoRequestContext(Context, Options, request);
            await Options.Provider.ValidateUserinfoRequest(validatingContext);

            // Stop processing the request if Validated was not called.
            if (!validatingContext.IsValidated)
            {
                Options.Logger.LogInformation("The userinfo request was rejected by application code.");

                return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                    Error = validatingContext.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = validatingContext.ErrorDescription,
                    ErrorUri = validatingContext.ErrorUri
                }));
            }

            var notification = new HandleUserinfoRequestContext(Context, Options, request, ticket);

            notification.Subject = ticket.Identity.GetClaim(ClaimTypes.NameIdentifier);
            notification.Issuer  = Context.GetIssuer(Options);

            // Note: when receiving an access token, its audiences list cannot be used for the "aud" claim
            // as the client application is not the intented audience but only an authorized presenter.
            // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
            foreach (var presenter in ticket.GetPresenters())
            {
                notification.Audiences.Add(presenter);
            }

            // The following claims are all optional and should be excluded when
            // no corresponding value has been found in the authentication ticket.
            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Profile))
            {
                notification.FamilyName = ticket.Identity.GetClaim(ClaimTypes.Surname);
                notification.GivenName  = ticket.Identity.GetClaim(ClaimTypes.GivenName);
                notification.BirthDate  = ticket.Identity.GetClaim(ClaimTypes.DateOfBirth);
            }

            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Email))
            {
                notification.Email = ticket.Identity.GetClaim(ClaimTypes.Email);
            }
            ;

            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Phone))
            {
                notification.PhoneNumber = ticket.Identity.GetClaim(ClaimTypes.HomePhone) ??
                                           ticket.Identity.GetClaim(ClaimTypes.MobilePhone) ??
                                           ticket.Identity.GetClaim(ClaimTypes.OtherPhone);
            }
            ;

            await Options.Provider.HandleUserinfoRequest(notification);

            if (notification.HandledResponse)
            {
                return(true);
            }

            else if (notification.Skipped)
            {
                return(false);
            }

            // Ensure the "sub" claim has been correctly populated.
            if (string.IsNullOrEmpty(notification.Subject))
            {
                Options.Logger.LogError("The mandatory 'sub' claim was missing from the userinfo response.");

                Response.StatusCode = 500;

                return(await SendErrorPayloadAsync(new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "The mandatory 'sub' claim was missing."
                }));
            }

            var payload = new JObject {
                [JwtRegisteredClaimNames.Sub] = notification.Subject
            };

            if (notification.Address != null)
            {
                payload[OpenIdConnectConstants.Claims.Address] = notification.Address;
            }

            if (!string.IsNullOrEmpty(notification.BirthDate))
            {
                payload[JwtRegisteredClaimNames.Birthdate] = notification.BirthDate;
            }

            if (!string.IsNullOrEmpty(notification.Email))
            {
                payload[JwtRegisteredClaimNames.Email] = notification.Email;
            }

            if (notification.EmailVerified.HasValue)
            {
                payload[OpenIdConnectConstants.Claims.EmailVerified] = notification.EmailVerified.Value;
            }

            if (!string.IsNullOrEmpty(notification.FamilyName))
            {
                payload[JwtRegisteredClaimNames.FamilyName] = notification.FamilyName;
            }

            if (!string.IsNullOrEmpty(notification.GivenName))
            {
                payload[JwtRegisteredClaimNames.GivenName] = notification.GivenName;
            }

            if (!string.IsNullOrEmpty(notification.Issuer))
            {
                payload[JwtRegisteredClaimNames.Iss] = notification.Issuer;
            }

            if (!string.IsNullOrEmpty(notification.PhoneNumber))
            {
                payload[OpenIdConnectConstants.Claims.PhoneNumber] = notification.PhoneNumber;
            }

            if (notification.PhoneNumberVerified.HasValue)
            {
                payload[OpenIdConnectConstants.Claims.PhoneNumberVerified] = notification.PhoneNumberVerified.Value;
            }

            if (!string.IsNullOrEmpty(notification.PreferredUsername))
            {
                payload[OpenIdConnectConstants.Claims.PreferredUsername] = notification.PreferredUsername;
            }

            if (!string.IsNullOrEmpty(notification.Profile))
            {
                payload[OpenIdConnectConstants.Claims.Profile] = notification.Profile;
            }

            if (!string.IsNullOrEmpty(notification.Website))
            {
                payload[OpenIdConnectConstants.Claims.Website] = notification.Website;
            }

            switch (notification.Audiences.Count)
            {
            case 0: break;

            case 1:
                payload.Add(JwtRegisteredClaimNames.Aud, notification.Audiences[0]);
                break;

            default:
                payload.Add(JwtRegisteredClaimNames.Aud, JArray.FromObject(notification.Audiences));
                break;
            }

            foreach (var claim in notification.Claims)
            {
                // Ignore claims whose value is null.
                if (claim.Value == null)
                {
                    continue;
                }

                payload.Add(claim.Key, claim.Value);
            }

            var context = new ApplyUserinfoResponseContext(Context, Options, request, payload);
            await Options.Provider.ApplyUserinfoResponse(context);

            if (context.HandledResponse)
            {
                return(true);
            }

            else if (context.Skipped)
            {
                return(false);
            }

            using (var buffer = new MemoryStream())
                using (var writer = new JsonTextWriter(new StreamWriter(buffer))) {
                    payload.WriteTo(writer);
                    writer.Flush();

                    Response.ContentLength = buffer.Length;
                    Response.ContentType   = "application/json;charset=UTF-8";

                    Response.Headers.Set("Cache-Control", "no-cache");
                    Response.Headers.Set("Pragma", "no-cache");
                    Response.Headers.Set("Expires", "-1");

                    buffer.Seek(offset: 0, loc: SeekOrigin.Begin);
                    await buffer.CopyToAsync(Response.Body, 4096, Request.CallCancelled);
                }

            return(true);
        }
        public void JSchemaValidatingWriter()
        {
            string schemaJson = "{}";

            #region JSchemaValidatingWriter
            Person person = new Person
            {
                Name = "James",
                Hobbies = new List<string>
                {
                    ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
                }
            };

            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);

            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = JSchema.Parse(schemaJson);

            IList<string> messages = new List<string>();
            validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);

            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(validatingWriter, person);
            #endregion

            Assert.AreEqual(0, messages.Count);
        }
Example #35
0
 /// <summary>
 /// Writes primitive schema in JSON format
 /// </summary>
 /// <param name="w"></param>
 /// <param name="names"></param>
 /// <param name="encspace"></param>
 protected internal override void WriteJson(JsonTextWriter w, SchemaNames names, string encspace)
 {
     w.WriteValue(Name);
 }
Example #36
0
        protected virtual async Task WriteCommentObjectAsync(JsonTextWriter jsonWriter, TCommentObjectType obj, CancellationToken cancellationToken = default)
        {
            await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_ID, cancellationToken).ConfigureAwait(false);

            await jsonWriter.WriteValueAsync(obj.Id, cancellationToken).ConfigureAwait(false);

            if (obj.ParentId.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_PARENT_ID, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.ParentId, cancellationToken).ConfigureAwait(false);
            }

            await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_CREATED_AT, cancellationToken).ConfigureAwait(false);

            await jsonWriter.WriteValueAsync(obj.CreatedAt.ToTraktLongDateTimeString(), cancellationToken).ConfigureAwait(false);

            if (obj.UpdatedAt.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_UPDATED_AT, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.UpdatedAt.Value.ToTraktLongDateTimeString(), cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Comment))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_COMMENT, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Comment, cancellationToken).ConfigureAwait(false);
            }

            await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_SPOILER, cancellationToken).ConfigureAwait(false);

            await jsonWriter.WriteValueAsync(obj.Spoiler, cancellationToken).ConfigureAwait(false);

            await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_REVIEW, cancellationToken).ConfigureAwait(false);

            await jsonWriter.WriteValueAsync(obj.Review, cancellationToken).ConfigureAwait(false);

            if (obj.Replies.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_REPLIES, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Replies, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Likes.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_LIKES, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Likes, cancellationToken).ConfigureAwait(false);
            }

            if (obj.UserRating.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_USER_RATING, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.UserRating, cancellationToken).ConfigureAwait(false);
            }

            if (obj.User != null)
            {
                var userObjectJsonWriter = new UserObjectJsonWriter();
                await jsonWriter.WritePropertyNameAsync(JsonProperties.COMMENT_PROPERTY_NAME_USER, cancellationToken).ConfigureAwait(false);

                await userObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.User, cancellationToken).ConfigureAwait(false);
            }
        }
        public IReadOnlyDictionary <string, object> ToDictionary()
        {
            var d = new Dictionary <string, object>();

            var payload = new Dictionary <string, object>();
            var message = new Dictionary <string, object>();

            payload["name"] = Title;
            payload["auto_archive_duration"] = ArchiveDuration;

            if (Slowmode.IsSpecified)
            {
                payload["rate_limit_per_user"] = Slowmode.Value;
            }

            // message
            if (Content.IsSpecified)
            {
                message["content"] = Content.Value;
            }
            if (Embeds.IsSpecified)
            {
                message["embeds"] = Embeds.Value;
            }
            if (AllowedMentions.IsSpecified)
            {
                message["allowed_mentions"] = AllowedMentions.Value;
            }
            if (MessageComponent.IsSpecified)
            {
                message["components"] = MessageComponent.Value;
            }
            if (Stickers.IsSpecified)
            {
                message["sticker_ids"] = Stickers.Value;
            }
            if (Flags.IsSpecified)
            {
                message["flags"] = Flags.Value;
            }

            List <object> attachments = new();

            for (int n = 0; n != Files.Length; n++)
            {
                var attachment = Files[n];

                var filename = attachment.FileName ?? "unknown.dat";
                if (attachment.IsSpoiler && !filename.StartsWith(AttachmentExtensions.SpoilerPrefix))
                {
                    filename = filename.Insert(0, AttachmentExtensions.SpoilerPrefix);
                }
                d[$"files[{n}]"] = new MultipartFile(attachment.Stream, filename);

                attachments.Add(new
                {
                    id          = (ulong)n,
                    filename    = filename,
                    description = attachment.Description ?? Optional <string> .Unspecified
                });
            }

            message["attachments"] = attachments;

            payload["message"] = message;

            var json = new StringBuilder();

            using (var text = new StringWriter(json))
                using (var writer = new JsonTextWriter(text))
                    _serializer.Serialize(writer, payload);

            d["payload_json"] = json.ToString();

            return(d);
        }
Example #38
0
        private async Task <bool> SendPayloadAsync(OpenIdConnectResponse response)
        {
            using (var buffer = new MemoryStream())
                using (var writer = new JsonTextWriter(new StreamWriter(buffer)))
                {
                    var serializer = JsonSerializer.CreateDefault();
                    serializer.Serialize(writer, response);

                    writer.Flush();

                    if (!string.IsNullOrEmpty(response.Error))
                    {
                        // When client authentication is made using basic authentication, the authorization server MUST return
                        // a 401 response with a valid WWW-Authenticate header containing the Basic scheme and a non-empty realm.
                        // A similar error MAY be returned even when basic authentication is not used and MUST also be returned
                        // when an invalid token is received by the userinfo endpoint using the Bearer authentication scheme.
                        // To simplify the logic, a 401 response with the Bearer scheme is returned for invalid_token errors
                        // and a 401 response with the Basic scheme is returned for invalid_client, even if the credentials
                        // were specified in the request form instead of the HTTP headers, as allowed by the specification.
                        string GetAuthenticationScheme()
                        {
                            switch (response.Error)
                            {
                            case OpenIdConnectConstants.Errors.InvalidClient: return(OpenIdConnectConstants.Schemes.Basic);

                            case OpenIdConnectConstants.Errors.InvalidToken:  return(OpenIdConnectConstants.Schemes.Bearer);

                            default:                                          return(null);
                            }
                        }

                        var scheme = GetAuthenticationScheme();
                        if (!string.IsNullOrEmpty(scheme))
                        {
                            Response.StatusCode = 401;

                            Response.Headers[HeaderNames.WWWAuthenticate] = new StringBuilder()
                                                                            .Append(scheme)
                                                                            .Append(' ')
                                                                            .Append(OpenIdConnectConstants.Parameters.Realm)
                                                                            .Append("=\"")
                                                                            .Append(Context.GetIssuer(Options))
                                                                            .Append('"')
                                                                            .ToString();
                        }

                        else
                        {
                            Response.StatusCode = 400;
                        }
                    }

                    Response.ContentLength = buffer.Length;
                    Response.ContentType   = "application/json;charset=UTF-8";

                    switch (response.GetProperty <string>(OpenIdConnectConstants.Properties.MessageType))
                    {
                    // Discovery, userinfo and introspection responses can be cached by the client
                    // or the intermediate proxies. To allow the developer to set up his own response
                    // caching policy, don't override the Cache-Control, Pragma and Expires headers.
                    case OpenIdConnectConstants.MessageTypes.ConfigurationResponse:
                    case OpenIdConnectConstants.MessageTypes.CryptographyResponse:
                    case OpenIdConnectConstants.MessageTypes.IntrospectionResponse:
                    case OpenIdConnectConstants.MessageTypes.UserinfoResponse:
                        break;

                    // Prevent the other responses from being cached.
                    default:
                        Response.Headers[HeaderNames.CacheControl] = "no-cache";
                        Response.Headers[HeaderNames.Pragma]       = "no-cache";
                        Response.Headers[HeaderNames.Expires]      = "Thu, 01 Jan 1970 00:00:00 GMT";

                        break;
                    }

                    buffer.Seek(offset: 0, loc: SeekOrigin.Begin);
                    await buffer.CopyToAsync(Response.Body, 4096, Context.RequestAborted);

                    // Return true to stop processing the request.
                    return(true);
                }
        }
Example #39
0
 internal override void ToJsonSafe(JsonTextWriter writer, HashSet <NamedSchema> seenSchemas)
 {
     writer.WriteStartArray();
     this.schemas.ForEach(_ => _.ToJson(writer, seenSchemas));
     writer.WriteEndArray();
 }
Example #40
0
        public override async Task WriteObjectAsync(JsonTextWriter jsonWriter, ITraktMovie obj, CancellationToken cancellationToken = default)
        {
            if (jsonWriter == null)
            {
                throw new ArgumentNullException(nameof(jsonWriter));
            }

            await jsonWriter.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(obj.Title))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_TITLE, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Title, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Year.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_YEAR, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Year, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Ids != null)
            {
                var movieIdsObjectJsonWriter = new MovieIdsObjectJsonWriter();
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_IDS, cancellationToken).ConfigureAwait(false);

                await movieIdsObjectJsonWriter.WriteObjectAsync(jsonWriter, obj.Ids, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Tagline))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_TAGLINE, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Tagline, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Overview))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_OVERVIEW, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Overview, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Released.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_RELEASED, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Released.Value.ToTraktLongDateTimeString(), cancellationToken).ConfigureAwait(false);
            }

            if (obj.Runtime.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_RUNTIME, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Runtime, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Trailer))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_TRAILER, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Trailer, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Homepage))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_HOMEPAGE, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Homepage, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Rating.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_RATING, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Rating, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Votes.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_VOTES, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Votes, cancellationToken).ConfigureAwait(false);
            }

            if (obj.UpdatedAt.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_UPDATED_AT, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.UpdatedAt.Value.ToTraktLongDateTimeString(), cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.LanguageCode))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_LANGUAGE, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.LanguageCode, cancellationToken).ConfigureAwait(false);
            }

            if (obj.AvailableTranslationLanguageCodes != null)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_AVAILABLE_TRANSLATIONS, cancellationToken).ConfigureAwait(false);

                await JsonWriterHelper.WriteStringArrayAsync(jsonWriter, obj.AvailableTranslationLanguageCodes, cancellationToken).ConfigureAwait(false);
            }

            if (obj.Genres != null)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_GENRES, cancellationToken).ConfigureAwait(false);

                await JsonWriterHelper.WriteStringArrayAsync(jsonWriter, obj.Genres, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.Certification))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_CERTIFICATION, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.Certification, cancellationToken).ConfigureAwait(false);
            }

            if (!string.IsNullOrEmpty(obj.CountryCode))
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_COUNTRY, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.CountryCode, cancellationToken).ConfigureAwait(false);
            }

            if (obj.CommentCount.HasValue)
            {
                await jsonWriter.WritePropertyNameAsync(JsonProperties.MOVIE_PROPERTY_NAME_COMMENT_COUNT, cancellationToken).ConfigureAwait(false);

                await jsonWriter.WriteValueAsync(obj.CommentCount, cancellationToken).ConfigureAwait(false);
            }

            await jsonWriter.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false);
        }
        public async Task Test_CollectionShowObjectJsonWriter_WriteObject_JsonWriter_Complete()
        {
            ITraktCollectionShow traktCollectionShow = new TraktCollectionShow
            {
                LastCollectedAt = LAST_COLLECTED_AT,
                LastUpdatedAt   = LAST_UPDATED_AT,
                Show            = new TraktShow
                {
                    Title = "Game of Thrones",
                    Year  = 2011,
                    Ids   = new TraktShowIds
                    {
                        Trakt  = 1390U,
                        Slug   = "game-of-thrones",
                        Tvdb   = 121361U,
                        Imdb   = "tt0944947",
                        Tmdb   = 1399U,
                        TvRage = 24493U
                    }
                },
                CollectionSeasons = new List <ITraktCollectionShowSeason>
                {
                    new TraktCollectionShowSeason
                    {
                        Number   = 1,
                        Episodes = new List <ITraktCollectionShowEpisode>
                        {
                            new TraktCollectionShowEpisode
                            {
                                Number      = 1,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            },
                            new TraktCollectionShowEpisode
                            {
                                Number      = 2,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            }
                        }
                    },
                    new TraktCollectionShowSeason
                    {
                        Number   = 2,
                        Episodes = new List <ITraktCollectionShowEpisode>
                        {
                            new TraktCollectionShowEpisode
                            {
                                Number      = 1,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            },
                            new TraktCollectionShowEpisode
                            {
                                Number      = 2,
                                CollectedAt = COLLECTED_AT,
                                Metadata    = new TraktMetadata
                                {
                                    MediaType        = TraktMediaType.Digital,
                                    MediaResolution  = TraktMediaResolution.HD_720p,
                                    Audio            = TraktMediaAudio.AAC,
                                    AudioChannels    = TraktMediaAudioChannel.Channels_5_1,
                                    ThreeDimensional = true
                                }
                            }
                        }
                    }
                }
            };

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    var traktJsonWriter = new CollectionShowObjectJsonWriter();
                    await traktJsonWriter.WriteObjectAsync(jsonWriter, traktCollectionShow);

                    stringWriter.ToString().Should().Be($"{{\"last_collected_at\":\"{LAST_COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        $"\"last_updated_at\":\"{LAST_UPDATED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""show"":{""title"":""Game of Thrones"",""year"":2011," +
                                                        @"""ids"":{""trakt"":1390,""slug"":""game-of-thrones""," +
                                                        @"""tvdb"":121361,""imdb"":""tt0944947""," +
                                                        @"""tmdb"":1399,""tvrage"":24493}}," +
                                                        @"""seasons"":[{""number"":1,""episodes"":[{""number"":1," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}," +
                                                        @"{""number"":2," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}]}," +
                                                        @"{""number"":2,""episodes"":[{""number"":1," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}," +
                                                        @"{""number"":2," +
                                                        $"\"collected_at\":\"{COLLECTED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""metadata"":{""media_type"":""digital"",""resolution"":""hd_720p""," +
                                                        @"""audio"":""aac"",""audio_channels"":""5.1"",""3d"":true}}]}]}");
                }
        }
Example #42
0
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <param name="output">Stream to save to</param>
        private void GenerateOutput(IGraph g, TextWriter output)
        {
            //Get a Blank Node Output Mapper
            BlankNodeOutputMapper bnodeMapper = new BlankNodeOutputMapper(WriterHelper.IsValidBlankNodeID);

            //Get the Writer and Configure Options
            JsonTextWriter writer = new JsonTextWriter(output);

            if (this._prettyprint)
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
            }
            else
            {
                writer.Formatting = Newtonsoft.Json.Formatting.None;
            }

            //Start the overall Object which represents the Graph
            writer.WriteStartObject();

            //Get the Triples as a Sorted List
            List <Triple> ts = g.Triples.ToList();

            ts.Sort();

            //Variables we need to track our writing
            INode lastSubj, lastPred;

            lastSubj = lastPred = null;

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    //Terminate previous Triples
                    if (lastSubj != null)
                    {
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }

                    //Start a new set of Triples
                    //Validate Subject
                    switch (t.Subject.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        break;

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write out the Subject
                    if (t.Subject.NodeType != NodeType.Blank)
                    {
                        writer.WritePropertyName(t.Subject.ToString());
                    }
                    else
                    {
                        //Remap Blank Node IDs as appropriate
                        writer.WritePropertyName("_:" + bnodeMapper.GetOutputID(((IBlankNode)t.Subject).InternalID));
                    }

                    //Start an Object for the Subject
                    writer.WriteStartObject();

                    lastSubj = t.Subject;

                    //Write the first Predicate
                    //Validate Predicate
                    switch (t.Predicate.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        throw new RdfOutputException(WriterErrorMessages.BlankPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write the Predicate
                    writer.WritePropertyName(t.Predicate.ToString());

                    //Create an Array for the Objects
                    writer.WriteStartArray();

                    lastPred = t.Predicate;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    //Terminate previous Predicate Object list
                    writer.WriteEndArray();

                    //Write the next Predicate
                    //Validate Predicate
                    switch (t.Predicate.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                    case NodeType.Blank:
                        throw new RdfOutputException(WriterErrorMessages.BlankPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralPredicatesUnserializable("RDF/JSON"));

                    case NodeType.Uri:
                        //OK
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                    }

                    //Write the Predicate
                    writer.WritePropertyName(t.Predicate.ToString());

                    //Create an Array for the Objects
                    writer.WriteStartArray();

                    lastPred = t.Predicate;
                }

                //Write the Object
                //Create an Object for the Object
                INode obj = t.Object;
                writer.WriteStartObject();
                writer.WritePropertyName("value");
                switch (obj.NodeType)
                {
                case NodeType.Blank:
                    //Remap Blank Node IDs as appropriate
                    writer.WriteValue("_:" + bnodeMapper.GetOutputID(((IBlankNode)obj).InternalID));
                    writer.WritePropertyName("type");
                    writer.WriteValue("bnode");
                    break;

                case NodeType.GraphLiteral:
                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/JSON"));

                case NodeType.Literal:
                    ILiteralNode lit = (ILiteralNode)obj;
                    writer.WriteValue(lit.Value);

                    if (!lit.Language.Equals(String.Empty))
                    {
                        writer.WritePropertyName("lang");
                        writer.WriteValue(lit.Language);
                    }
                    else if (lit.DataType != null)
                    {
                        writer.WritePropertyName("datatype");
                        writer.WriteValue(lit.DataType.ToString());
                    }
                    writer.WritePropertyName("type");
                    writer.WriteValue("literal");
                    break;

                case NodeType.Uri:
                    writer.WriteValue(obj.ToString());
                    writer.WritePropertyName("type");
                    writer.WriteValue("uri");
                    break;

                default:
                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/JSON"));
                }
                writer.WriteEndObject();
            }

            //Terminate the Object which represents the Graph
            writer.WriteEndObject();
        }
Example #43
0
 void Write(JsonTextWriter writer, string name, object value)
 {
     writer.WritePropertyName(name);
     writer.WriteRawValue(JsonConvert.SerializeObject(value));
 }
Example #44
0
        private static void Go(Engine engine)
        {
            var travelStationDefinitionClass      = engine.GetClass("WillowGame.TravelStationDefinition");
            var fastTravelStationDefinitionClass  = engine.GetClass("WillowGame.FastTravelStationDefinition");
            var levelTravelStationDefinitionClass = engine.GetClass("WillowGame.LevelTravelStationDefinition");

            if (travelStationDefinitionClass == null ||
                fastTravelStationDefinitionClass == null ||
                levelTravelStationDefinitionClass == null)
            {
                throw new System.InvalidOperationException();
            }

            using (var output = new StreamWriter("Travel Stations.json", false, Encoding.Unicode))
                using (var writer = new JsonTextWriter(output))
                {
                    writer.Indentation = 2;
                    writer.IndentChar  = ' ';
                    writer.Formatting  = Formatting.Indented;

                    writer.WriteStartObject();

                    var travelStationDefinitions = engine.Objects
                                                   .Where(o =>
                                                          (o.IsA(travelStationDefinitionClass) == true ||
                                                           o.IsA(fastTravelStationDefinitionClass) == true ||
                                                           o.IsA(levelTravelStationDefinitionClass) == true) &&
                                                          o.GetName().StartsWith("Default__") == false)
                                                   .OrderBy(o => o.GetPath());
                    foreach (dynamic travelStationDefinition in travelStationDefinitions)
                    {
                        UnrealClass uclass = travelStationDefinition.GetClass();
                        if (uclass.Path != "WillowGame.FastTravelStationDefinition" &&
                            uclass.Path != "WillowGame.LevelTravelStationDefinition")
                        {
                            throw new System.InvalidOperationException();
                        }

                        writer.WritePropertyName(travelStationDefinition.GetPath());
                        writer.WriteStartObject();

                        if (uclass.Path != "WillowGame.TravelStationDefinition")
                        {
                            writer.WritePropertyName("$type");
                            writer.WriteValue(uclass.Name);
                        }

                        string stationLevelName = travelStationDefinition.StationLevelName;
                        if (string.IsNullOrEmpty(stationLevelName) == false)
                        {
                            writer.WritePropertyName("level_name");
                            writer.WriteValue(stationLevelName);
                        }

                        var dlcExpansion = travelStationDefinition.DlcExpansion;
                        if (dlcExpansion != null)
                        {
                            writer.WritePropertyName("dlc_expansion");
                            writer.WriteValue(dlcExpansion.GetPath());
                        }

                        if (travelStationDefinition.PreviousStation != null)
                        {
                            writer.WritePropertyName("previous_station");
                            writer.WriteValue(travelStationDefinition.PreviousStation.GetPath());
                        }

                        string stationDisplayName = travelStationDefinition.StationDisplayName;
                        if (string.IsNullOrEmpty(stationDisplayName) == false)
                        {
                            writer.WritePropertyName("display_name");
                            writer.WriteValue(stationDisplayName);
                        }

                        var missionDependencies = ((IEnumerable <dynamic>)travelStationDefinition.MissionDependencies)
                                                  .Where(md => md.MissionDefinition != null)
                                                  .OrderBy(md => md.MissionDefinition.GetPath())
                                                  .ToArray();
                        if (missionDependencies.Length > 0)
                        {
                            writer.WritePropertyName("mission_dependencies");
                            writer.WriteStartArray();

                            foreach (var missionDependency in missionDependencies)
                            {
                                writer.WriteStartObject();

                                writer.WritePropertyName("mission_definition");
                                writer.WriteValue(missionDependency.MissionDefinition.GetPath());

                                writer.WritePropertyName("mission_status");
                                writer.WriteValue(((MissionStatus)missionDependency.MissionStatus).ToString());

                                if ((bool)missionDependency.bIsObjectiveSpecific == true)
                                {
                                    writer.WritePropertyName("is_objective_specific");
                                    writer.WriteValue(true);

                                    if (missionDependency.MissionObjective != null)
                                    {
                                        writer.WritePropertyName("objective_definition");
                                        writer.WriteValue(missionDependency.MissionObjective.GetPath());
                                    }

                                    writer.WritePropertyName("objective_status");
                                    writer.WriteValue(
                                        ((ObjectiveDependencyStatus)missionDependency.ObjectiveStatus).ToString());
                                }

                                writer.WriteEndObject();
                            }

                            writer.WriteEndArray();
                        }

                        if (uclass == fastTravelStationDefinitionClass)
                        {
                            writer.WritePropertyName("initially_active");
                            writer.WriteValue((bool)travelStationDefinition.bInitiallyActive);

                            writer.WritePropertyName("send_only");
                            writer.WriteValue((bool)travelStationDefinition.bSendOnly);

                            string stationDescription = travelStationDefinition.StationDescription;
                            if (string.IsNullOrEmpty(stationDescription) == false &&
                                stationDescription != "No Description" &&
                                stationDescription != stationDisplayName)
                            {
                                writer.WritePropertyName("description");
                                writer.WriteValue(stationDescription);
                            }

                            string stationSign = travelStationDefinition.StationSign;
                            if (string.IsNullOrEmpty(stationSign) == false &&
                                stationSign != stationDisplayName)
                            {
                                writer.WritePropertyName("sign");
                                writer.WriteValue(stationSign);
                            }

                            if (travelStationDefinition.InaccessibleObjective != null)
                            {
                                writer.WritePropertyName("inaccessible_objective");
                                writer.WriteValue(travelStationDefinition.InaccessibleObjective.GetPath());
                            }

                            if (travelStationDefinition.AccessibleObjective != null)
                            {
                                writer.WritePropertyName("accessible_objective");
                                writer.WriteValue(travelStationDefinition.AccessibleObjective.GetPath());
                            }
                        }

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
Example #45
0
        static void Main(string[] args)
        {
            int i   = 1;
            int num = 1;
            //            string json = @"{
            //    'CPU': 'Intel',
            //    'PSU': '500W',
            //    'Drives': [
            //      'DVD read/writer'
            //      /*(broken)*/,
            //      '500 gigabyte hard drive',
            //      '200 gigabype hard drive'
            //    ]
            //}";
            //sample s = new sample();
            //seats s1 = new seats();
            //sample seat = new sample();
            //string js = File.ReadAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json");

            ////Deserialize from file to object:
            //JsonConvert.PopulateObject(js, s1);
            //var a = s1.Seat1;
            //Console.WriteLine("{0}", s1.Seat1.flag);
            ////Change Value
            //s.CallofDuty = 8;

            //// serialize JSON directly to a file again
            //using (StreamWriter file = File.CreateText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
            //{
            //    JsonSerializer serializer = new JsonSerializer();
            //    serializer.Serialize(file, s);
            //}



            JObject o2 = new JObject();
            JObject o1 = JObject.Parse(File.ReadAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"));

            // read JSON directly from a file
            using (StreamReader file = File.OpenText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    o2 = (JObject)JToken.ReadFrom(reader);

                    if (Convert.ToString(o2["Seat" + i][0]["blocked"]) == "true")
                    {
                        Console.WriteLine("SEAT IS BOOKED");
                        goto Booked;
                    }
                    var s = o2["Seat" + i][0]["clicks"];

                    var w = Convert.ToInt32(s);
                    w += 1;
                    o2["Seat" + i][0]["no.ofseats"] = num;

                    o2["Seat" + i][0]["clicks"] = w;
                    Console.WriteLine("{0}", o2["Seat" + i][0]["clicks"]);
                }
            File.WriteAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json", o2.ToString());

            // write JSON directly to a file
            using (StreamWriter file1 = File.CreateText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
                using (JsonTextWriter writer = new JsonTextWriter(file1))
                {
                    o2.WriteTo(writer);
                }
            bar(o2, i, num);
            goto Finish;

Booked:
            Console.WriteLine("exit now");



            //    JsonReader reader1 = o2.CreateReader();
            //    Console.WriteLine("{0}", reader1);
            //    while (reader1.Read())
            //    {

            //        if (reader1.Value != null)
            //        {
            //            Console.WriteLine("{0}", reader1.Value);
            //        }

            //    }



            //            JObject videogameRatings = new JObject(
            //    new JProperty("Halo", 9),
            //    new JProperty("Starcraft", 9),
            //    new JProperty("Call of Duty", 7.5));

            //File.WriteAllText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json", videogameRatings.ToString());

            //// write JSON directly to a file
            //using(StreamWriter file = File.CreateText(@"d:\users\h224169\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\sample.json"))
            //using(JsonTextWriter writer = new JsonTextWriter(file))
            //{
            //                    videogameRatings.WriteTo(writer);
            //                }



            //        JsonTextReader reader = new JsonTextReader(new StringReader(json));
            //        while (reader.Read())
            //            {
            //                if (reader.Value != null)
            //                  {
            //                        Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
            //                    }
            //               else
            //{
            //                        Console.WriteLine("Token: {0}", reader.TokenType);
            //                    }
            //            }
Finish:
            Console.ReadLine();
        }
Example #46
0
        /// <summary>
        /// 각종 기능을 테스트합니다.
        /// </summary>
        /// <param name="args"></param>
        static void ProcessTest(string[] args)
        {
            switch (args[0].ToInt32())
            {
            //
            //  Save and beautify metadatas
            //
            case 0:
            {
                var hiddendata = JsonConvert.DeserializeObject <List <HitomiArticle> >(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "hiddendata.json")));
                Func <HitomiArticle, NHitomiArticle> r2n = (ha) =>
                {
                    return(new NHitomiArticle
                        {
                            Artists = ha.Artists,
                            Characters = ha.Characters,
                            Groups = ha.Groups,
                            Language = ha.Language,
                            Tags = ha.Tags,
                            Type = ha.Type,
                            DateTime = ha.DateTime,
                            Thumbnail = ha.Thumbnail,
                            Magic = ha.Magic,
                            Title = ha.Title
                        });
                };

                var jj   = hiddendata.Select(x => r2n(x));
                var json = JsonConvert.SerializeObject(jj, Formatting.Indented);
                using (var fs = new StreamWriter(new FileStream("hiddendata_beautify.json", FileMode.Create, FileAccess.Write)))
                {
                    fs.Write(json);
                }

                var json2 = JsonConvert.SerializeObject(jj, Formatting.None);
                using (var fs = new StreamWriter(new FileStream("hiddendata_nonbeautify.json", FileMode.Create, FileAccess.Write)))
                {
                    var bytes = json2.Zip();
                    fs.BaseStream.Write(json2.Zip(), 0, bytes.Length);
                }
            }
            break;

            //
            //  Load metadatas
            //
            case 1:
            {
                var bytes = File.ReadAllBytes("hiddendata_nonbeautify.json");
                var json  = JsonConvert.DeserializeObject <List <NHitomiArticle> >(bytes.Unzip());
                Console.Instance.Write($"{json.Count}");
            }
            break;

            case 2:
            {
                var str = File.ReadAllText("hiddendata.json");
                File.WriteAllBytes("hiddendata.compress", str.Zip());
            }
            break;

            case 3:
            {
                var str = File.ReadAllText("metadata.json");
                File.WriteAllBytes("metadata.compress", str.Zip());
            }
            break;

            case 4:
            {
                var str = JsonConvert.DeserializeObject <List <HitomiArticle> >(File.ReadAllText("hiddendata.json"));
                using (var fs = new StreamWriter(new FileStream("hiddendata.json", FileMode.Create, FileAccess.Write)))
                {
                    fs.Write(JsonConvert.SerializeObject(str, Formatting.None));
                }
            }
            break;

            case 5:
            {
                var bytes = File.ReadAllBytes("metadata.compress");
                File.WriteAllText("metadata.json", bytes.Unzip());
            }
            break;

            case 6:
            {
                var bytes = File.ReadAllBytes("hiddendata.compress");
                File.WriteAllText("hiddendata.json", bytes.Unzip());
            }
            break;

            case 7:
            {
                HitomiExplore.exploreNullSpace().ForEach(x => Console.Instance.WriteLine($"{x.Item1} {x.Item2} {x.Item3}"));
            }
            break;

            case 8:
            {
                // Update index-metadata.json
                HitomiData.Instance.LoadMetadataJson();
                HitomiData.Instance.LoadHiddendataJson();
                HitomiIndex.MakeIndex();
                var str = File.ReadAllBytes("index-metadata.json");
                File.WriteAllBytes("index-metadata.compress", str.ZipByte());
            }
            break;

            case 9:
            {
                //var hidden = JsonConvert.DeserializeObject<List<HitomiArticle>>(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "hiddendata.json")));
                //var gall = JsonConvert.DeserializeObject<List<HitomiArticle>>(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "galleries.json")));


                //for (int i = 0; i < gall.Count; i++)
                //    for (int j = 0; j < hidden.Count; j++)
                //        if (gall[i].Magic == hidden[j].Magic)
                //        {
                //            hidden[j].Groups = gall[i].Groups;
                //            hidden[j].Characters = gall[i].Characters;
                //        }

                //JsonSerializer serializer = new JsonSerializer();
                //serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
                //serializer.NullValueHandling = NullValueHandling.Ignore;

                //using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "hiddendata2.json")))
                //using (JsonWriter writer = new JsonTextWriter(sw))
                //{
                //    serializer.Serialize(writer, hidden);
                //}

                var x = new HitomiIndexDataModel();
                x.index    = HitomiIndex.Instance.index;
                x.metadata = HitomiIndex.Instance.metadata_collection;
                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
                serializer.NullValueHandling = NullValueHandling.Ignore;

                Monitor.Instance.Push("Write file: metadata-index.json");
                using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "metadata-index.json")))
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        serializer.Serialize(writer, x);
                    }

                HitomiData.Instance.LoadMetadataJson();
                HitomiData.Instance.LoadHiddendataJson();
                Monitor.Instance.Push("Write file: metadata-noptimized.json");
                using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "metadametadata-noptimizedta.json")))
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        serializer.Serialize(writer, HitomiData.Instance.metadata_collection);
                    }
            }
            break;

            case 10:

            {
                foreach (var x in HitomiIndex.Instance.tagdata_collection.artist)
                {
                    Console.Instance.Write(x.Tag + ", ");
                }
            }

            break;

            case 11:
            {
                HitomiData.Instance.LoadMetadataJson();
                HitomiData.Instance.LoadHiddendataJson();
                HitomiData.Instance.RebuildTagData();
            }
            break;

            case 12:
            {
                // Update HitomiTitle
                for (int i = 0; i < 50; i++)
                {
                    try
                    {
                        var url3 = $"https://exhentai.org/?page={i}&f_doujinshi=on&f_manga=on&f_artistcg=on&f_gamecg=on&&f_cats=0&f_sname=on&f_stags=on&f_sh=on&advsearch=1&f_srdd=2&f_sname=on&f_stags=on&f_sdesc=on&f_sh=on";
                        var html = NetCommon.DownloadExHentaiString(url3);
                        File.WriteAllText($"exhentai-page/exhentai-{i}.html", html);
                        Monitor.Instance.Push($"[Paging] {i + 1}/1457");
                    }
                    catch (Exception e)
                    {
                        Console.Instance.WriteErrorLine($"[Error] {i} {e.Message}");
                    }
                    Thread.Sleep(100);
                }
                {
                    const string archive = @"C:\Tools\koromo-copy\Koromo Copy UX\bin\Debug\exhentai-page";
                    var          htmls   = new List <string>();

                    foreach (var file in Directory.GetFiles(archive))
                    {
                        htmls.Add(File.ReadAllText(file));
                    }

                    var result = new List <EHentaiResultArticle>();

                    using (var progressBar = new Console.ConsoleProgressBar())
                    {
                        int x = 0;
                        foreach (var html in htmls)
                        {
                            var content = html;
                            try
                            {
                                var exh = ExHentaiParser.ParseResultPageExtendedListView(content);
                                //Console.Instance.WriteLine("[GET] " + exh.Count + " Articles! - " + html);
                                result.AddRange(exh);
                                if (exh.Count != 25)
                                {
                                    Console.Instance.WriteLine("[Miss] " + html);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.Instance.WriteLine("[Fail] " + html);
                            }
                            x++;
                            progressBar.SetProgress(x / (float)htmls.Count * 100);
                        }
                    }

                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;

                    Monitor.Instance.Push("Write file: ex-hentai-archive.json");
                    using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "ex-hentai-archive2.json")))
                        using (JsonWriter writer = new JsonTextWriter(sw))
                        {
                            serializer.Serialize(writer, result);
                        }
                }
                {
                    var xxx = JsonConvert.DeserializeObject <List <EHentaiResultArticle> >(File.ReadAllText("ex-hentai-archive.json"));
                    var zzz = JsonConvert.DeserializeObject <List <EHentaiResultArticle> >(File.ReadAllText("ex-hentai-archive2.json"));

                    var exists = new HashSet <int>();
                    xxx.ForEach(x => exists.Add(x.URL.Split('/')[4].ToInt32()));

                    foreach (var z in zzz)
                    {
                        var nn = z.URL.Split('/')[4].ToInt32();

                        if (exists.Contains(nn))
                        {
                            Console.Instance.WriteLine("[Duplicate] " + nn);
                        }
                        else
                        {
                            xxx.Add(z);
                        }
                    }

                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;

                    Monitor.Instance.Push("Write file: ex-hentai-archive3.json");
                    using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "ex-hentai-archive3.json")))
                        using (JsonWriter writer = new JsonTextWriter(sw))
                        {
                            serializer.Serialize(writer, xxx);
                        }
                }

                HitomiTitle.MakeTitle();
            }
            break;

            case 13:
                // Fill type
            {
                var md = JsonConvert.DeserializeObject <List <HitomiArticle> >(File.ReadAllText("hiddendata.json"));

                var xxx = JsonConvert.DeserializeObject <List <EHentaiResultArticle> >(File.ReadAllText("ex-hentai-archive.json"));
                //var md = JsonConvert.DeserializeObject<List<HitomiMetadata>>(File.ReadAllText("metadata.json"));

                var types = new Dictionary <string, string>();

                foreach (var xx in xxx)
                {
                    try
                    {
                        types.Add(xx.URL.Split('/')[4], xx.Type.ToLower());
                    }
                    catch (Exception e)
                    {
                        //Console.Instance.WriteLine("[??] " + xx.URL);
                    }
                }

                //for (int i = 0; i < md.Count; i++)
                //{
                //    if (md[i].Type  == null || md[i].Type.Trim() == "")
                //    {
                //        if (types.ContainsKey(md[i].ID.ToString()))
                //        {
                //            var x = md[i];
                //            x.Type = types[md[i].ID.ToString()];
                //            md[i] = x;
                //        }
                //        else
                //        {
                //            Console.Instance.WriteLine("[Fail] " + md[i].ID.ToString());
                //        }
                //    }
                //}

                for (int i = 0; i < md.Count; i++)
                {
                    if (md[i].Type == null || md[i].Type.Trim() == "")
                    {
                        if (types.ContainsKey(md[i].Magic.ToString()))
                        {
                            var x = md[i];
                            x.Type = types[md[i].Magic.ToString()];
                            md[i]  = x;
                        }
                        else
                        {
                            Console.Instance.WriteLine("[Fail] " + md[i].Magic.ToString());
                        }
                    }
                }

                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new JavaScriptDateTimeConverter());
                serializer.NullValueHandling = NullValueHandling.Ignore;

                Monitor.Instance.Push("Write file: metadata.json");
                using (StreamWriter sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "hiddendata2.json")))
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        serializer.Serialize(writer, md);
                    }
            }
            break;
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// Writes this class as json using <code>generator</code>.
        /// This method is valid only in an array context or in no context (see <see cref="M:Newtonsoft.Json.JsonTextWriter.WriteStartObject" />.
        /// Requires the current objects list to be correctly sorted, otherwise the written
        /// <see cref="T:SavegameToolkit.Types.ObjectReference" /> might be broken.
        /// </summary>
        /// <param name="writer"><see cref="T:Newtonsoft.Json.JsonTextWriter" /> to write with</param>
        /// <param name="writingOptions"></param>
        public void WriteJson(JsonTextWriter writer, WritingOptions writingOptions)
        {
            writer.WriteStartObject();

            writer.WriteField("saveVersion", SaveVersion);
            writer.WriteField("gameTime", GameTime);

            writer.WriteField("saveCount", SaveCount);

            if (!writingOptions.Compact && OldNameList != null && OldNameList.Any())
            {
                writer.WriteArrayFieldStart("preservedNames");

                foreach (string oldName in OldNameList)
                {
                    writer.WriteValue(oldName);
                }

                writer.WriteEndArray();
            }

            if (!writingOptions.Compact && DataFiles.Any())
            {
                writer.WriteArrayFieldStart("dataFiles");

                foreach (string dataFile in DataFiles)
                {
                    writer.WriteValue(dataFile);
                }

                writer.WriteEndArray();
            }

            if (!writingOptions.Compact && EmbeddedData.Any())
            {
                writer.WriteArrayFieldStart("embeddedData");

                foreach (EmbeddedData data in EmbeddedData)
                {
                    data.WriteJson(writer);
                }

                writer.WriteEndArray();
            }

            if (DataFilesObjectMap.Any())
            {
                writer.WriteObjectFieldStart("dataFilesObjectMap");

                foreach (KeyValuePair <int, List <string[]> > entry in DataFilesObjectMap)
                {
                    writer.WriteArrayFieldStart(entry.Key.ToString());
                    foreach (string[] namesList in entry.Value)
                    {
                        writer.WriteStartArray();
                        foreach (string name in namesList)
                        {
                            writer.WriteValue(name);
                        }

                        writer.WriteEndArray();
                    }

                    writer.WriteEndArray();
                }

                writer.WriteEndObject();
            }

            if (Objects.Any())
            {
                writer.WriteArrayFieldStart("objects");

                foreach (GameObject gameObject in Objects)
                {
                    gameObject.WriteJson(writer, writingOptions);
                }

                writer.WriteEndArray();
            }

            writer.WriteObjectFieldStart("hibernation");

            if (!writingOptions.Compact)
            {
                writer.WriteField("v8Unknown1", hibernationV8Unknown1);
                writer.WriteField("v8Unknown2", hibernationV8Unknown2);
                writer.WriteField("v8Unknown3", hibernationV8Unknown3);
                writer.WriteField("v8Unknown4", hibernationV8Unknown4);

                writer.WriteField("unknown1", hibernationUnknown1);
                writer.WriteField("unknown2", hibernationUnknown2);
            }

            if (!writingOptions.Compact && hibernationClasses.Any())
            {
                writer.WriteArrayFieldStart("classes");

                foreach (string hibernationClass in hibernationClasses)
                {
                    writer.WriteValue(hibernationClass);
                }

                writer.WriteEndArray();
            }

            if (!writingOptions.Compact && hibernationIndices.Any())
            {
                writer.WriteArrayFieldStart("indices");

                foreach (int hibernationIndex in hibernationIndices)
                {
                    writer.WriteValue(hibernationIndex);
                }

                writer.WriteEndArray();
            }

            if (HibernationEntries.Any())
            {
                writer.WriteArrayFieldStart("entries");

                foreach (HibernationEntry hibernationEntry in HibernationEntries)
                {
                    hibernationEntry.WriteJson(writer, writingOptions);
                }

                writer.WriteEndArray();
            }

            writer.WriteEndObject();

            writer.WriteEndObject();
        }
Example #48
0
        public override int Analyze()
        {
            Console.WriteLine("Writing failed pip info to '{0}'.", OutputFilePath);
            using (var streamWriter = new StreamWriter(OutputFilePath))
                using (JsonWriter writer = new JsonTextWriter(streamWriter))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("Mounts");
                    {
                        writer.WriteStartObject();

                        var mountPathExpander = m_mountPathExpander ?? CachedGraph.MountPathExpander;
                        foreach (var mountRoot in mountPathExpander.GetAllRoots())
                        {
                            var mount = mountPathExpander.GetSemanticPathInfo(mountRoot);
                            writer.WritePropertyName(mount.RootName.ToString(StringTable));
                            writer.WriteValue(mountRoot.ToString(PathTable));
                        }

                        writer.WriteEndObject();
                    }

                    writer.WritePropertyName("FileInfo");
                    {
                        writer.WriteStartObject();

                        foreach (var fileEntry in m_fileToConsumerMap)
                        {
                            var file      = fileEntry.Key;
                            var consumers = fileEntry.Value;
                            var path      = ToDisplayFilePath(file);
                            if (path != null)
                            {
                                writer.WritePropertyName(path, true);
                                {
                                    writer.WriteStartArray();

                                    foreach (var consumer in consumers)
                                    {
                                        writer.WriteValue(ToDisplayString(consumer));
                                    }

                                    writer.WriteEndArray();
                                }
                            }
                        }

                        writer.WriteEndObject();
                    }

                    writer.WritePropertyName("PipGraph");
                    {
                        writer.WriteStartObject();

                        m_failedPipsClosure.UnsafeReset();
                        writer.WritePropertyName("root");
                        {
                            writer.WriteStartArray();

                            foreach (var failedPip in m_failedPips)
                            {
                                writer.WriteValue(ToDisplayString(failedPip));
                            }

                            writer.WriteEndArray();
                        }

                        List <NodeId> dependencyBuffer = new List <NodeId>();

                        nodeVisitor.VisitTransitiveDependencies(m_failedPips.Select(p => p.ToNodeId()), m_failedPipsClosure, visitNode: node =>
                        {
                            dependencyBuffer.Clear();
                            foreach (var dependencyEdge in DirectedGraph.GetIncomingEdges(node))
                            {
                                if (PipTable.GetPipType(dependencyEdge.OtherNode.ToPipId()) != PipType.HashSourceFile)
                                {
                                    dependencyBuffer.Add(dependencyEdge.OtherNode);
                                }
                            }

                            if (dependencyBuffer.Count != 0)
                            {
                                writer.WritePropertyName(ToDisplayString(node.ToPipId()));
                                {
                                    writer.WriteStartArray();

                                    foreach (var dependencyNode in dependencyBuffer)
                                    {
                                        writer.WriteValue(ToDisplayString(dependencyNode.ToPipId()));
                                    }

                                    writer.WriteEndArray();
                                }
                            }

                            return(true);
                        });

                        writer.WriteEndObject();
                    }

                    writer.WritePropertyName("TopFilesConsumedByFailedPips");
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName("FailedPipsConsumedDirectly");
                        WriteConsumerMap(writer, failedPipDirectDepsOnly: true);

                        writer.WritePropertyName("ConsumedByFailedAndFailedDependencies");
                        WriteConsumerMap(writer, failedPipDirectDepsOnly: false);
                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }

            return(0);
        }
Example #49
0
        public void Extends()
        {
            string             json;
            JsonSchemaResolver resolver = new JsonSchemaResolver();

            json = @"{
  ""id"":""first"",
  ""type"":""object"",
  ""additionalProperties"":{}
}";

            JsonSchema first = JsonSchema.Parse(json, resolver);

            json =
                @"{
  ""id"":""second"",
  ""type"":""object"",
  ""extends"":{""$ref"":""first""},
  ""additionalProperties"":{""type"":""string""}
}";

            JsonSchema second = JsonSchema.Parse(json, resolver);

            Assert.AreEqual(first, second.Extends[0]);

            json =
                @"{
  ""id"":""third"",
  ""type"":""object"",
  ""extends"":{""$ref"":""second""},
  ""additionalProperties"":false
}";

            JsonSchema third = JsonSchema.Parse(json, resolver);

            Assert.AreEqual(second, third.Extends[0]);
            Assert.AreEqual(first, third.Extends[0].Extends[0]);

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            third.WriteTo(jsonWriter, resolver);

            string writtenJson = writer.ToString();

            Assert.AreEqual(@"{
  ""id"": ""third"",
  ""type"": ""object"",
  ""additionalProperties"": false,
  ""extends"": {
    ""$ref"": ""second""
  }
}", writtenJson);

            StringWriter   writer1     = new StringWriter();
            JsonTextWriter jsonWriter1 = new JsonTextWriter(writer1);

            jsonWriter1.Formatting = Formatting.Indented;

            third.WriteTo(jsonWriter1);

            writtenJson = writer1.ToString();
            Assert.AreEqual(@"{
  ""id"": ""third"",
  ""type"": ""object"",
  ""additionalProperties"": false,
  ""extends"": {
    ""id"": ""second"",
    ""type"": ""object"",
    ""additionalProperties"": {
      ""type"": ""string""
    },
    ""extends"": {
      ""id"": ""first"",
      ""type"": ""object"",
      ""additionalProperties"": {}
    }
  }
}", writtenJson);
        }
Example #50
0
 private static void WriteMessageType(JsonTextWriter writer, int type)
 {
     writer.WritePropertyName(TypePropertyName);
     writer.WriteValue(type);
 }
Example #51
0
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Response.ContentType = @"application/json";

            JToken jt;
            JArray products       = null;
            var    productsOffers = new List <BidProductUI>();
            Dictionary <Int64, int> lstProduct = new Dictionary <Int64, int>();

            Int64 AppUserId;

            IsAuthorizedRequest(Request, Response, false, out AppUserId);

            Int64 TempAppUserId = 0;

            if (inputData.TryGetValue(@"temp_app_user_id", out jt))
            {
                TempAppUserId = jt.Value <Int64>();
            }
            if (AppUserId == 0 && TempAppUserId == 0)
            {
                RespondError(Response, HttpStatusCode.Forbidden, @"authorization-error");
                return;
            }
            var user     = AppUser.FetchByID(AppUserId);
            var tempUser = TempAppUser.FetchByID(TempAppUserId);

            if (user == null && tempUser == null)
            {
                RespondError(Response, HttpStatusCode.Forbidden, @"authorization-error");
                return;
            }

            long cityId = 0;

            if (user != null)
            {
                bool _locked = user.IsLocked;
                if (_locked)
                {
                    RespondError(Response, HttpStatusCode.BadRequest, @"appuser-locked");
                    return;
                }
                cityId = user.CityId;
            }
            else if (tempUser != null)
            {
                cityId = tempUser.CityId;
            }

            if (inputData.TryGetValue(@"products", out jt))
            {
                products = jt.Value <JArray>();
            }
            foreach (JObject obj in products.Children <JObject>())
            {
                Int64 product_id = 0;
                int   amount     = 1;
                if (obj.TryGetValue(@"product_id", out jt))
                {
                    product_id = jt.Value <Int64>();
                }
                if (obj.TryGetValue(@"amount", out jt))
                {
                    amount = jt.Value <int>();
                }
                lstProduct.Add(product_id, amount);
            }

            var  lstOfferUI      = OfferController.GetAllOfferByProductIds(lstProduct, cityId);
            var  now             = DateTime.Now;
            bool isCallAvailable = BIdMessageController.IsSystemActive(now);

            Response.ContentType = @"application/json";
            using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
            {
                using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                {
                    jsonWriter.WriteStartObject();


                    jsonWriter.WritePropertyName(@"is_call_available");
                    jsonWriter.WriteValue(isCallAvailable);

                    jsonWriter.WritePropertyName(@"offers");
                    jsonWriter.WriteStartArray();
                    if (lstOfferUI != null)
                    {
                        foreach (OfferUI item in lstOfferUI)
                        {
                            jsonWriter.WriteStartObject();

                            jsonWriter.WritePropertyName(@"offer_id");
                            jsonWriter.WriteValue(item.OfferId);
                            jsonWriter.WritePropertyName(@"supplier_id");
                            jsonWriter.WriteValue(item.SupplierId);
                            jsonWriter.WritePropertyName(@"mastercard_code");
                            if (item.MastercardCode == "")
                            {
                                jsonWriter.WriteValue((-1).ToString());
                            }
                            else
                            {
                                jsonWriter.WriteValue(item.MastercardCode);
                            }
                            jsonWriter.WritePropertyName(@"avg_rate");
                            jsonWriter.WriteValue(item.AvgRate);
                            jsonWriter.WritePropertyName(@"comments_number");
                            jsonWriter.WriteValue(item.NumberOfComments);
                            jsonWriter.WritePropertyName(@"supplier_name");
                            jsonWriter.WriteValue(item.SupplierName);
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(item.TotalPrice);
                            jsonWriter.WritePropertyName(@"gift");
                            jsonWriter.WriteValue("");

                            jsonWriter.WritePropertyName(@"products");
                            jsonWriter.WriteStartArray();
                            foreach (var product in item.Products) /* TODO: should be deleted*/
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName(@"product_id");
                                jsonWriter.WriteValue(product.ProductId);
                                jsonWriter.WritePropertyName(@"product_price");
                                jsonWriter.WriteValue(product.ProductPrice);
                                jsonWriter.WritePropertyName(@"product_amount");
                                jsonWriter.WriteValue(product.Amount);

                                jsonWriter.WriteEndObject();
                            }

                            jsonWriter.WriteEndArray();

                            jsonWriter.WriteEndObject();
                        }
                    }

                    jsonWriter.WriteEndArray();

                    jsonWriter.WriteEndObject();
                }
            }
        }
        private static void Go(Engine engine)
        {
            var playerClassDefinitionClass = engine.GetClass("WillowGame.PlayerClassDefinition");

            if (playerClassDefinitionClass == null)
            {
                throw new InvalidOperationException();
            }

            Directory.CreateDirectory("dumps");

            using (var output = new StreamWriter(Path.Combine("dumps", "Player Classes.json"), false, Encoding.Unicode))
                using (var writer = new JsonTextWriter(output))
                {
                    writer.Indentation = 2;
                    writer.IndentChar  = ' ';
                    writer.Formatting  = Formatting.Indented;

                    writer.WriteStartObject();

                    var playerClassDefinitionClasses = engine.Objects
                                                       .Where(o => o.IsA(playerClassDefinitionClass) &&
                                                              o.GetName().StartsWith("Default__") ==
                                                              false)
                                                       .OrderBy(o => o.GetPath());
                    foreach (dynamic playerClassDefinition in playerClassDefinitionClasses)
                    {
                        writer.WritePropertyName(playerClassDefinition.GetPath());
                        writer.WriteStartObject();

                        var characterNameId = playerClassDefinition.CharacterNameId;
                        if (characterNameId == null)
                        {
                            throw new InvalidOperationException();
                        }

                        var characterClassId = characterNameId.CharacterClassId;
                        if (characterClassId == null)
                        {
                            throw new InvalidOperationException();
                        }

                        writer.WritePropertyName("name");
                        writer.WriteValue(characterNameId.LocalizedCharacterName);

                        writer.WritePropertyName("class");
                        writer.WriteValue(characterClassId.LocalizedClassNameNonCaps);

                        writer.WritePropertyName("sort_order");
                        writer.WriteValue(characterNameId.UISortOrder);

                        if (characterClassId.DlcCharacterDef != null)
                        {
                            writer.WritePropertyName("dlc");
                            writer.WriteValue(characterClassId.DlcCharacterDef.GetPath());
                        }

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
Example #53
0
 private void WritePingMessage(PingMessage m, JsonTextWriter writer)
 {
     writer.WriteStartObject();
     WriteMessageType(writer, HubProtocolConstants.PingMessageType);
     writer.WriteEndObject();
 }
Example #54
0
 private void WriteCancelInvocationMessage(CancelInvocationMessage message, JsonTextWriter writer)
 {
     writer.WriteStartObject();
     WriteHubInvocationMessageCommon(message, writer, HubProtocolConstants.CancelInvocationMessageType);
     writer.WriteEndObject();
 }
Example #55
0
        internal static void LoadSettings()
        {
            if (!File.Exists(SettingsFile))
            {
                CurrentOptions.Color      = Theme.Zerg;
                CurrentOptions.AppsFolder = Path.Combine(Application.StartupPath, "Optimizer Downloads");
                Directory.CreateDirectory(Options.CurrentOptions.AppsFolder);

                CurrentOptions.EnablePerformanceTweaks       = false;
                CurrentOptions.DisableNetworkThrottling      = false;
                CurrentOptions.DisableWindowsDefender        = false;
                CurrentOptions.DisableSystemRestore          = false;
                CurrentOptions.DisablePrintService           = false;
                CurrentOptions.DisableMediaPlayerSharing     = false;
                CurrentOptions.DisableErrorReporting         = false;
                CurrentOptions.DisableHomeGroup              = false;
                CurrentOptions.DisableSuperfetch             = false;
                CurrentOptions.DisableTelemetryTasks         = false;
                CurrentOptions.DisableOffice2016Telemetry    = false;
                CurrentOptions.DisableCompatibilityAssistant = false;
                CurrentOptions.DisableFaxService             = false;
                CurrentOptions.DisableSmartScreen            = false;
                CurrentOptions.DisableStickyKeys             = false;

                CurrentOptions.EnableLegacyVolumeSlider  = false;
                CurrentOptions.EnableTaskbarColor        = false;
                CurrentOptions.DisableQuickAccessHistory = false;
                CurrentOptions.DisableStartMenuAds       = false;
                CurrentOptions.EnableDarkTheme           = false;
                CurrentOptions.UninstallOneDrive         = false;
                CurrentOptions.DisableMyPeople           = false;
                CurrentOptions.DisableAutomaticUpdates   = false;
                CurrentOptions.ExcludeDrivers            = false;
                CurrentOptions.DisableTelemetryServices  = false;
                CurrentOptions.DisablePrivacyOptions     = false;
                CurrentOptions.DisableCortana            = false;
                CurrentOptions.DisableSensorServices     = false;
                CurrentOptions.DisableWindowsInk         = false;
                CurrentOptions.DisableSpellingTyping     = false;
                CurrentOptions.DisableXboxLive           = false;
                CurrentOptions.DisableGameBar            = false;
                CurrentOptions.DisableInsiderService     = false;
                CurrentOptions.DisableFeatureUpdates     = false;
                CurrentOptions.DisableCloudClipboard     = false;
                CurrentOptions.EnableLongPaths           = false;
                CurrentOptions.RemoveCastToDevice        = false;
                CurrentOptions.DisableActionCenter       = false;

                CurrentOptions.DisableOneDrive = false;

                using (FileStream fs = File.Open(SettingsFile, FileMode.CreateNew))
                    using (StreamWriter sw = new StreamWriter(fs))
                        using (JsonWriter jw = new JsonTextWriter(sw))
                        {
                            jw.Formatting = Formatting.Indented;

                            JsonSerializer serializer = new JsonSerializer();
                            serializer.Serialize(jw, CurrentOptions);
                        }
            }
            else
            {
                CurrentOptions = JsonConvert.DeserializeObject <SettingsJson>(File.ReadAllText(SettingsFile));
            }
        }
Example #56
0
 private static void WriteHubInvocationMessageCommon(HubInvocationMessage message, JsonTextWriter writer, int type)
 {
     if (!string.IsNullOrEmpty(message.InvocationId))
     {
         writer.WritePropertyName(InvocationIdPropertyName);
         writer.WriteValue(message.InvocationId);
     }
     WriteMessageType(writer, type);
     WriteMessageMetadata(writer, message.Metadata);
 }
    public void ToStringJsonConverter()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
          new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      JsonSerializer serializer = new JsonSerializer();
      serializer.Converters.Add(new JavaScriptDateTimeConverter());
      StringWriter sw = new StringWriter();
      JsonWriter writer = new JsonTextWriter(sw);
      writer.Formatting = Formatting.Indented;
      serializer.Serialize(writer, o);

      string json = sw.ToString();

      Assert.AreEqual(@"{
  ""Test1"": new Date(
    971586305000
  ),
  ""Test2"": new Date(
    971546045000
  ),
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", json);
    }
        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
              JsonTextWriter jsonWriter = new JsonTextWriter(writer);
              jsonWriter.Formatting = Formatting.Indented;

              WriteTo(jsonWriter);

              return writer.ToString();
        }
Example #59
0
        public async Task Test_EpisodeObjectJsonWriter_WriteObject_JsonWriter_Complete()
        {
            ITraktEpisode traktEpisode = new TraktEpisode
            {
                SeasonNumber = 1,
                Number       = 1,
                Title        = "title",
                Ids          = new TraktEpisodeIds
                {
                    Trakt  = 123456,
                    Tvdb   = 234567,
                    Imdb   = "345678",
                    Tmdb   = 456789,
                    TvRage = 567890
                },
                NumberAbsolute = 1,
                Overview       = "overview",
                Runtime        = 60,
                Rating         = 8.45672f,
                Votes          = 8925,
                FirstAired     = FIRST_AIRED,
                UpdatedAt      = UPDATED_AT,
                AvailableTranslationLanguageCodes = new List <string>
                {
                    "en",
                    "de"
                },
                Translations = new List <TraktEpisodeTranslation>
                {
                    new TraktEpisodeTranslation
                    {
                        Title        = "german title",
                        Overview     = "german overview",
                        LanguageCode = "de"
                    },
                    new TraktEpisodeTranslation
                    {
                        Title        = "english title",
                        Overview     = "english overview",
                        LanguageCode = "en"
                    }
                }
            };

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    var traktJsonWriter = new EpisodeObjectJsonWriter();
                    await traktJsonWriter.WriteObjectAsync(jsonWriter, traktEpisode);

                    stringWriter.ToString().Should().Be(@"{""season"":1,""number"":1,""title"":""title""," +
                                                        @"""ids"":{""trakt"":123456,""tvdb"":234567,""imdb"":""345678"",""tmdb"":456789,""tvrage"":567890}," +
                                                        @"""number_abs"":1,""overview"":""overview""," +
                                                        @"""runtime"":60,""rating"":8.45672,""votes"":8925," +
                                                        $"\"first_aired\":\"{FIRST_AIRED.ToTraktLongDateTimeString()}\"," +
                                                        $"\"updated_at\":\"{UPDATED_AT.ToTraktLongDateTimeString()}\"," +
                                                        @"""available_translations"":[""en"",""de""]," +
                                                        @"""translations"":[{""title"":""german title"",""overview"":""german overview"",""language"":""de""}," +
                                                        @"{""title"":""english title"",""overview"":""english overview"",""language"":""en""}]}");
                }
        }
Example #60
-1
 public ActionResult Sources()
 {
     return authenticatedAction(new String[] { "UT", "UR" }, () => {
         var result = makeJSONResult();
         using (JsonTextWriter w = new JsonTextWriter()) {
             w.WriteStartArray();
             foreach (IssueSourceLvl1 i in db.IssueSourceLvl1s.WAOBTL()) {
                 w.writeSharedJSONMembers(i);
                 w.writeSharedJSONProlog();
                 foreach (IssueSourceLvl2 i2 in db.IssueSourceLvl2s.Where(ti2 => ti2.parentCode == i.code).WAOBTL()) {
                     w.writeSharedJSONMembers(i2);
                     w.writeSharedJSONProlog();
                     foreach (IssueSourceLvl3 i3 in db.IssueSourceLvl3s
                         .Where(ti3 => ti3.grandparentCode == i.code)
                         .Where(ti3 => ti3.parentCode == i2.code)
                         .WAOBTL()) {
                         w.writeSharedJSONMembers(i3);
                         w.WriteEndObject();
                     }
                     w.writeSharedJSONEpilog();
                 }
                 w.writeSharedJSONEpilog();
             }
             w.WriteEndArray();
             result.Content = w.ToString();
         }
         logger.Debug("TreesController.Sources accessed.");
         return result;
     });
 }