Beispiel #1
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;
            });
        }
        private void BuildResponseJson(StringBuilder sb, PendingDownstreamMessage message)
        {
            using (var stringWriter = new StringWriter(sb))
            using (var writer = new JsonTextWriter(stringWriter))
            {
                if (message == null)
                {
                    writer.WriteStartArray();
                    writer.WriteValue("noop");
                    writer.WriteEndArray();
                }
                else
                {
                    var responseType = message.Message.GetType();
                    var responseServiceType = ServiceRegistry.GetAssembly(responseType.Assembly).TypesByType[responseType];

                    writer.WriteStartObject();
                    writer.WritePropertyName("r");
                    writer.WriteValue((int)message.Kind);
                    writer.WritePropertyName("a");
                    writer.WriteValue((int)message.AssociationId);
                    writer.WritePropertyName("t");
                    writer.WriteValue(responseServiceType.Message.Id);
                    writer.WritePropertyName("p");

                    JsonUtil.SerializeMessage(writer, responseServiceType, message.Message);

                    writer.WriteEndObject();
                }
            }
        }
Beispiel #3
0
        private void SalvaAssistenciaTecnica(Domain.Model.Conta assistencia)
        {
            StringBuilder sb = null;
            StringWriter  sw = null;
            JsonWriter    wt = null;

            try
            {
                var reqInserir = new RestRequest();

                reqInserir.AddHeader("Content-Type", "application/json");
                reqInserir.AddHeader("Accept", "application/json");
                reqInserir.AddHeader("accept-language", "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2");
                reqInserir.AddHeader("Cookie", token);
                reqInserir.AddHeader("X-CSRF-Token", csrf_token);
                reqInserir.Resource      = "/api/auth/technical-support/{crm_id}";
                reqInserir.Method        = Method.PUT;
                reqInserir.RequestFormat = DataFormat.Json;
                reqInserir.AddParameter("crm_id", assistencia.CodigoMatriz, ParameterType.UrlSegment);

                reqInserir.OnBeforeDeserialization = resp =>
                {
                    resp.ContentType = "application/json";
                };

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

                wt = new JsonTextWriter(sw);

                wt.Formatting = Formatting.Indented;
                wt.WriteStartObject();
                wt.WritePropertyName("title");
                wt.WriteValue(assistencia.NomeFantasia);

                wt.WritePropertyName("field_email");
                wt.WriteStartObject();
                wt.WritePropertyName("und");
                wt.WriteStartArray();
                wt.WriteStartObject();
                wt.WritePropertyName("email");
                wt.WriteValue(assistencia.Email);
                wt.WriteEndObject();
                wt.WriteEndArray();
                wt.WriteEndObject();

                wt.WritePropertyName("field_address");
                wt.WriteStartObject();
                wt.WritePropertyName("und");
                wt.WriteStartArray();
                wt.WriteStartObject();
                wt.WritePropertyName("organisation_name");
                wt.WriteValue(assistencia.Nome);
                wt.WritePropertyName("country");
                wt.WriteValue("BR");
                wt.WritePropertyName("administrative_area");
                var estado = (new Domain.Servicos.RepositoryService()).Estado.ObterPor(assistencia.Endereco1Estadoid.Id);
                wt.WriteValue(estado.SiglaUF);

                wt.WritePropertyName("locality");
                wt.WriteValue(assistencia.Endereco1Municipioid.Name);
                wt.WritePropertyName("postal_code");
                wt.WriteValue(assistencia.Endereco1CEP);
                wt.WritePropertyName("thoroughfare");
                wt.WriteValue(assistencia.Endereco1Rua + ", " + assistencia.Endereco1Numero + " " + assistencia.Endereco1Complemento);
                wt.WritePropertyName("premise");
                wt.WriteValue(assistencia.Endereco1Bairro);
                wt.WritePropertyName("phone_number");
                wt.WriteValue(assistencia.Telefone);
                wt.WriteEndObject();
                wt.WriteEndArray();
                wt.WriteEndObject();

                #region products_related

                List <Product> produtos = ObterProtutos(assistencia);

                wt.WritePropertyName("products_related");
                wt.WriteStartArray();


                foreach (Product item in produtos.Take(10000))
                {
                    wt.WriteValue(item.Codigo);
                }

                wt.WriteEnd();

                #endregion

                wt.WriteEndObject();

                reqInserir.AddParameter("application/json", sw.ToString(), ParameterType.RequestBody);

                CreateLog("Enviado JSON de ATUALIZACAO \n" + sw.ToString());

                var resultado = ClienteRest.Execute <RespostaPut>(reqInserir);


                if (resultado == null)
                {
                    throw new ApplicationException("[Incluir Assistencia Tecnica] Mensagem de Retorno esta vazia!");
                }

                if (resultado.ErrorException != null)
                {
                    throw new ApplicationException("[Incluir Assistencia Tecnica] Mensagem de Retorno: " + resultado.ErrorException
                                                   + " \nRequest: " + sw.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            finally
            {
                sb = null;

                wt.Close();

                sw.Close();
                sw.Dispose();
            }
        }
Beispiel #4
0
 private static void ExportData(string instanceUrl, string file)
 {
     using (var streamWriter = new StreamWriter(new GZipStream(File.Create(file), CompressionMode.Compress)))
     {
         var jsonWriter = new JsonTextWriter(streamWriter)
         {
             Formatting = Formatting.Indented
         };
         jsonWriter.WriteStartObject();
         jsonWriter.WritePropertyName("Indexes");
         jsonWriter.WriteStartArray();
         using (var webClient = new WebClient())
         {
             int totalCount = 0;
             while (true)
             {
                 var documents = Encoding.UTF8.GetString(webClient.DownloadData(instanceUrl + "indexes?pageSize=128&start=" + totalCount));
                 var array     = JArray.Parse(documents);
                 if (array.Count == 0)
                 {
                     Console.WriteLine("Done with reading indexes, total: {0}", totalCount);
                     break;
                 }
                 totalCount += array.Count;
                 Console.WriteLine("Reading batch of {0,3} indexes, read so far: {1,10:#,#}", array.Count,
                                   totalCount);
                 foreach (JToken item in array)
                 {
                     item.WriteTo(jsonWriter);
                 }
             }
         }
         jsonWriter.WriteEndArray();
         jsonWriter.WritePropertyName("Docs");
         jsonWriter.WriteStartArray();
         using (var webClient = new WebClient())
         {
             var lastEtag   = Guid.Empty;
             int totalCount = 0;
             while (true)
             {
                 var documents = Encoding.UTF8.GetString(webClient.DownloadData(instanceUrl + "docs?pageSize=128&etag=" + lastEtag));
                 var array     = JArray.Parse(documents);
                 if (array.Count == 0)
                 {
                     Console.WriteLine("Done with reading documents, total: {0}", totalCount);
                     break;
                 }
                 totalCount += array.Count;
                 Console.WriteLine("Reading batch of {0,3} documents, read so far: {1,10:#,#}", array.Count,
                                   totalCount);
                 foreach (JToken item in array)
                 {
                     item.WriteTo(jsonWriter);
                 }
                 lastEtag = new Guid(array.Last.Value <JObject>("@metadata").Value <string>("@etag"));
             }
         }
         jsonWriter.WriteEndArray();
         jsonWriter.WriteEndObject();
         streamWriter.Flush();
     }
 }
Beispiel #5
0
        private static void Go(Engine engine)
        {
            var weaponPartDefinitionClass        = engine.GetClass("WillowGame.WeaponPartDefinition");
            var itemPartDefinitionClass          = engine.GetClass("WillowGame.ItemPartDefinition");
            var artifactPartDefinitionClass      = engine.GetClass("WillowGame.ArtifactPartDefinition");
            var classModPartDefinitionClass      = engine.GetClass("WillowGame.ClassModPartDefinition");
            var equipableItemPartDefinitionClass = engine.GetClass("WillowGame.EquipableItemPartDefinition");
            var grenadeModPartDefinitionClass    = engine.GetClass("WillowGame.GrenadeModPartDefinition");
            var missionItemPartDefinitionClass   = engine.GetClass("WillowGame.MissionItemPartDefinition");
            var shieldPartDefinitionClass        = engine.GetClass("WillowGame.ShieldPartDefinition");
            var usableItemPartDefinitionClass    = engine.GetClass("WillowGame.UsableItemPartDefinition");

            if (weaponPartDefinitionClass == null ||
                itemPartDefinitionClass == null ||
                artifactPartDefinitionClass == null ||
                classModPartDefinitionClass == null ||
                equipableItemPartDefinitionClass == null ||
                grenadeModPartDefinitionClass == null ||
                missionItemPartDefinitionClass == null ||
                shieldPartDefinitionClass == null ||
                usableItemPartDefinitionClass == null)
            {
                throw new InvalidOperationException();
            }

            var weaponNamePartDefinitionClass = engine.GetClass("WillowGame.WeaponNamePartDefinition");
            var itemNamePartDefinitionClass   = engine.GetClass("WillowGame.ItemNamePartDefinition");

            if (weaponNamePartDefinitionClass == null ||
                itemNamePartDefinitionClass == null)
            {
                throw new InvalidOperationException();
            }

            Directory.CreateDirectory("dumps");

            var weaponParts = engine.Objects
                              .Where(o => o.IsA(weaponPartDefinitionClass) == true && o.GetName().StartsWith("Default__") == false)
                              .Distinct()
                              .OrderBy(o => o.GetPath());

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

                    writer.WriteStartObject();

                    foreach (dynamic weaponPart in weaponParts)
                    {
                        UnrealClass uclass = weaponPart.GetClass();
                        if (uclass != weaponPartDefinitionClass)
                        {
                            throw new InvalidOperationException();
                        }

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

                        if (weaponPart.TitleList != null &&
                            weaponPart.TitleList.Length > 0)
                        {
                            writer.WritePropertyName("titles");
                            writer.WriteStartArray();
                            IEnumerable <dynamic> titleList = weaponPart.TitleList;
                            foreach (var title in titleList
                                     .Where(tp => tp != null)
                                     .OrderBy(tp => tp.GetPath()))
                            {
                                writer.WriteValue(title.GetPath());
                            }
                            writer.WriteEndArray();
                        }

                        if (weaponPart.PrefixList != null &&
                            weaponPart.PrefixList.Length > 0)
                        {
                            writer.WritePropertyName("prefixes");
                            writer.WriteStartArray();
                            IEnumerable <dynamic> prefixList = weaponPart.PrefixList;
                            foreach (var prefix in prefixList
                                     .Where(pp => pp != null)
                                     .OrderBy(pp => pp.GetPath()))
                            {
                                writer.WriteValue(prefix.GetPath());
                            }
                            writer.WriteEndArray();
                        }

                        writer.WritePropertyName("type");
                        writer.WriteValue(((WeaponPartType)weaponPart.PartType).ToString());

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }

            var weaponNameParts = engine.Objects
                                  .Where(o => o.IsA(weaponNamePartDefinitionClass) == true && o.GetName().StartsWith("Default__") == false)
                                  .Distinct()
                                  .OrderBy(o => o.GetPath());

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

                    writer.WriteStartObject();

                    foreach (dynamic weaponNamePart in weaponNameParts)
                    {
                        UnrealClass uclass = weaponNamePart.GetClass();
                        if (uclass != weaponNamePartDefinitionClass)
                        {
                            throw new InvalidOperationException();
                        }

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

                        if (weaponNamePart.AttributeSlotEffects != null &&
                            weaponNamePart.AttributeSlotEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.AttributeSlotUpgrades != null &&
                            weaponNamePart.AttributeSlotUpgrades.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.ExternalAttributeEffects != null &&
                            weaponNamePart.ExternalAttributeEffects.Length > 0)
                        {
                            IEnumerable <dynamic> externalAttributeEffects = weaponNamePart.ExternalAttributeEffects;
                            foreach (var externalAttributeEffect in externalAttributeEffects)
                            {
                                if (externalAttributeEffect.AttributeToModify != null &&
                                    externalAttributeEffect.AttributeToModify.GetPath() !=
                                    "GD_Shields.Attributes.Attr_LawEquipped")
                                {
                                    throw new InvalidOperationException();
                                }
                            }
                        }

                        if (weaponNamePart.WeaponAttributeEffects != null &&
                            weaponNamePart.WeaponAttributeEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.ZoomExternalAttributeEffects != null &&
                            weaponNamePart.ZoomExternalAttributeEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.ZoomWeaponAttributeEffects != null &&
                            weaponNamePart.ZoomWeaponAttributeEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.WeaponCardAttributes != null &&
                            weaponNamePart.WeaponCardAttributes.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.CustomPresentations != null &&
                            weaponNamePart.CustomPresentations.Length > 0)
                        {
                            IEnumerable <dynamic> customPresentations = weaponNamePart.CustomPresentations;
                            foreach (var customPresentation in customPresentations)
                            {
                                if (string.IsNullOrEmpty((string)customPresentation.Suffix) == false)
                                {
                                    throw new InvalidOperationException();
                                }

                                if (string.IsNullOrEmpty((string)customPresentation.Prefix) == false)
                                {
                                    throw new InvalidOperationException();
                                }
                            }
                        }

                        if (weaponNamePart.TitleList != null &&
                            weaponNamePart.TitleList.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (weaponNamePart.PrefixList != null &&
                            weaponNamePart.PrefixList.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        var type = (WeaponPartType)weaponNamePart.PartType;
                        if (type != WeaponPartType.Body)
                        {
                            throw new InvalidOperationException();
                        }

                        if ((bool)weaponNamePart.bNameIsUnique != false)
                        {
                            writer.WritePropertyName("unique");
                            writer.WriteValue((bool)weaponNamePart.bNameIsUnique);
                        }

                        string partName = weaponNamePart.PartName;
                        if (string.IsNullOrEmpty(partName) == false)
                        {
                            writer.WritePropertyName("name");
                            writer.WriteValue(partName);
                        }

                        if (weaponNamePart.Expressions != null &&
                            weaponNamePart.Expressions.Length > 0)
                        {
                            /*
                             * writer.WritePropertyName("expressions");
                             * writer.WriteStartArray();
                             *
                             * foreach (var expression in weaponNamePart.Expressions)
                             * {
                             *  writer.WriteStartObject();
                             *
                             *  if (expression.AttributeOperand1 != null)
                             *  {
                             *      writer.WritePropertyName("operand1_attribute");
                             *      writer.WriteValue(expression.AttributeOperand1.GetPath());
                             *  }
                             *
                             *  var comparisonOperator = (ComparisonOperator)expression.ComparisonOperator;
                             *  writer.WritePropertyName("comparison_operator");
                             *  writer.WriteValue(comparisonOperator.ToString());
                             *
                             *  var operand2Usage = (OperandUsage)expression.Operand2Usage;
                             *  writer.WritePropertyName("operand2_usage");
                             *  writer.WriteValue(operand2Usage.ToString());
                             *
                             *  if (expression.AttributeOperand2 != null)
                             *  {
                             *      writer.WritePropertyName("operand2_attribute");
                             *      writer.WriteValue(expression.AttributeOperand2.GetPath());
                             *  }
                             *
                             *  float constantOperand2 = expression.ConstantOperand2;
                             *  if (constantOperand2.Equals(0.0f) == false)
                             *  {
                             *      writer.WritePropertyName("operand2_constant");
                             *      writer.WriteValue(constantOperand2);
                             *  }
                             *
                             *  writer.WriteEndObject();
                             * }
                             *
                             * writer.WriteEndArray();
                             */
                        }

                        if (weaponNamePart.MinExpLevelRequirement != 1)
                        {
                            /*
                             * writer.WritePropertyName("min_exp_level_required");
                             * writer.WriteValue(weaponNamePart.MinExpLevelRequirement);
                             */
                        }

                        if (weaponNamePart.MaxExpLevelRequirement != 100)
                        {
                            /*
                             * writer.WritePropertyName("max_exp_level_required");
                             * writer.WriteValue(weaponNamePart.MaxExpLevelRequirement);
                             */
                        }

                        /*
                         * writer.WritePropertyName("priority");
                         * writer.WriteValue(weaponNamePart.Priority);
                         */

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }

            var itemParts = engine.Objects
                            .Where(o => (o.IsA(itemPartDefinitionClass) == true ||
                                         o.IsA(artifactPartDefinitionClass) == true ||
                                         o.IsA(classModPartDefinitionClass) == true ||
                                         o.IsA(equipableItemPartDefinitionClass) == true ||
                                         o.IsA(grenadeModPartDefinitionClass) == true ||
                                         o.IsA(missionItemPartDefinitionClass) == true ||
                                         o.IsA(shieldPartDefinitionClass) == true ||
                                         o.IsA(usableItemPartDefinitionClass) == true) &&
                                   o.GetName().StartsWith("Default__") == false)
                            .Distinct()
                            .OrderBy(o => o.GetPath());

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

                    writer.WriteStartObject();

                    foreach (dynamic itemPart in itemParts)
                    {
                        UnrealClass uclass = itemPart.GetClass();
                        if (uclass != artifactPartDefinitionClass &&
                            uclass != classModPartDefinitionClass &&
                            uclass != grenadeModPartDefinitionClass &&
                            uclass != shieldPartDefinitionClass &&
                            uclass != usableItemPartDefinitionClass)
                        {
                            throw new InvalidOperationException();
                        }

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

                        writer.WritePropertyName("type");
                        writer.WriteValue(((ItemPartType)itemPart.PartType).ToString());

                        if (itemPart.TitleList != null &&
                            itemPart.TitleList.Length > 0)
                        {
                            writer.WritePropertyName("titles");
                            writer.WriteStartArray();
                            IEnumerable <dynamic> titleList = itemPart.TitleList;
                            foreach (var title in titleList
                                     .Where(tp => tp != null)
                                     .OrderBy(tp => tp.GetPath()))
                            {
                                writer.WriteValue(title.GetPath());
                            }
                            writer.WriteEndArray();
                        }

                        if (itemPart.PrefixList != null &&
                            itemPart.PrefixList.Length > 0)
                        {
                            writer.WritePropertyName("prefixes");
                            writer.WriteStartArray();
                            IEnumerable <dynamic> prefixList = itemPart.PrefixList;
                            foreach (var prefix in prefixList
                                     .Where(pp => pp != null)
                                     .OrderBy(pp => pp.GetPath()))
                            {
                                writer.WriteValue(prefix.GetPath());
                            }
                            writer.WriteEndArray();
                        }

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }

            var itemNameParts = engine.Objects
                                .Where(o => o.IsA(itemNamePartDefinitionClass) == true && o.GetName().StartsWith("Default__") == false)
                                .Distinct()
                                .OrderBy(o => o.GetPath());

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

                    writer.WriteStartObject();

                    foreach (dynamic itemNamePart in itemNameParts)
                    {
                        UnrealClass uclass = itemNamePart.GetClass();
                        if (uclass != itemNamePartDefinitionClass)
                        {
                            throw new InvalidOperationException();
                        }

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

                        if (itemNamePart.AttributeSlotEffects != null &&
                            itemNamePart.AttributeSlotEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (itemNamePart.AttributeSlotUpgrades != null &&
                            itemNamePart.AttributeSlotUpgrades.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (itemNamePart.ExternalAttributeEffects != null &&
                            itemNamePart.ExternalAttributeEffects.Length > 0)
                        {
                            IEnumerable <dynamic> externalAttributeEffects = itemNamePart.ExternalAttributeEffects;
                            foreach (var externalAttributeEffect in externalAttributeEffects)
                            {
                                if (externalAttributeEffect.AttributeToModify != null &&
                                    externalAttributeEffect.AttributeToModify.GetPath() !=
                                    "GD_Shields.Attributes.Attr_LawEquipped")
                                {
                                    throw new InvalidOperationException();
                                }
                            }
                        }

                        if (itemNamePart.ItemAttributeEffects != null &&
                            itemNamePart.ItemAttributeEffects.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (itemNamePart.ItemCardAttributes != null &&
                            itemNamePart.ItemCardAttributes.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (itemNamePart.CustomPresentations != null &&
                            itemNamePart.CustomPresentations.Length > 0)
                        {
                            IEnumerable <dynamic> customPresentations = itemNamePart.CustomPresentations;
                            foreach (var customPresentation in customPresentations)
                            {
                                if (string.IsNullOrEmpty((string)customPresentation.Suffix) == false)
                                {
                                    throw new InvalidOperationException();
                                }

                                if (string.IsNullOrEmpty((string)customPresentation.Prefix) == false)
                                {
                                    throw new InvalidOperationException();
                                }
                            }
                        }

                        if (itemNamePart.TitleList != null &&
                            itemNamePart.TitleList.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        if (itemNamePart.PrefixList != null &&
                            itemNamePart.PrefixList.Length > 0)
                        {
                            throw new InvalidOperationException();
                        }

                        var type = (ItemPartType)itemNamePart.PartType;
                        if (type != ItemPartType.Alpha)
                        {
                            throw new InvalidOperationException();
                        }

                        if ((bool)itemNamePart.bNameIsUnique != false)
                        {
                            writer.WritePropertyName("unique");
                            writer.WriteValue((bool)itemNamePart.bNameIsUnique);
                        }

                        string partName = itemNamePart.PartName;
                        if (string.IsNullOrEmpty(partName) == false)
                        {
                            writer.WritePropertyName("name");
                            writer.WriteValue(partName);
                        }

                        if (itemNamePart.Expressions != null &&
                            itemNamePart.Expressions.Length > 0)
                        {
                            /*
                             * writer.WritePropertyName("expressions");
                             * writer.WriteStartArray();
                             *
                             * foreach (var expression in itemNamePart.Expressions)
                             * {
                             *  writer.WriteStartObject();
                             *
                             *  if (expression.AttributeOperand1 != null)
                             *  {
                             *      writer.WritePropertyName("operand1_attribute");
                             *      writer.WriteValue(expression.AttributeOperand1.GetPath());
                             *  }
                             *
                             *  var comparisonOperator = (ComparisonOperator)expression.ComparisonOperator;
                             *  writer.WritePropertyName("comparison_operator");
                             *  writer.WriteValue(comparisonOperator.ToString());
                             *
                             *  var operand2Usage = (OperandUsage)expression.Operand2Usage;
                             *  writer.WritePropertyName("operand2_usage");
                             *  writer.WriteValue(operand2Usage.ToString());
                             *
                             *  if (expression.AttributeOperand2 != null)
                             *  {
                             *      writer.WritePropertyName("operand2_attribute");
                             *      writer.WriteValue(expression.AttributeOperand2.GetPath());
                             *  }
                             *
                             *  float constantOperand2 = expression.ConstantOperand2;
                             *  if (constantOperand2.Equals(0.0f) == false)
                             *  {
                             *      writer.WritePropertyName("operand2_constant");
                             *      writer.WriteValue(constantOperand2);
                             *  }
                             *
                             *  writer.WriteEndObject();
                             * }
                             *
                             * writer.WriteEndArray();
                             */
                        }

                        if (itemNamePart.MinExpLevelRequirement != 1)
                        {
                            /*
                             * writer.WritePropertyName("min_exp_level_required");
                             * writer.WriteValue(itemNamePart.MinExpLevelRequirement);
                             */
                        }

                        if (itemNamePart.MaxExpLevelRequirement != 100)
                        {
                            /*
                             * writer.WritePropertyName("max_exp_level_required");
                             * writer.WriteValue(itemNamePart.MaxExpLevelRequirement);
                             */
                        }

                        /*
                         * writer.WritePropertyName("priority");
                         * writer.WriteValue(itemNamePart.Priority);
                         */

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }
        }
Beispiel #6
0
        public override bool Read()
        {
            if (m_reader.Read())
            {
                ReadOtherReader();
                switch (m_otherReader.TokenType)
                {
                case JsonToken.Boolean:
                case JsonToken.Bytes:
                case JsonToken.Date:
                case JsonToken.String:
                case JsonToken.Integer:
                case JsonToken.Float:
                    m_writer.WriteValue(m_otherReader.Value);
                    break;

                case JsonToken.Comment:
                    m_writer.WriteComment((string)m_otherReader.Value);
                    break;

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

                case JsonToken.EndConstructor:
                    m_writer.WriteEndConstructor();
                    break;

                case JsonToken.EndObject:
                    m_writer.WriteEndObject();
                    break;

                case JsonToken.Null:
                    m_writer.WriteNull();
                    break;

                case JsonToken.Raw:
                    break;

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

                case JsonToken.StartConstructor:
                    m_writer.WriteStartConstructor((string)m_otherReader.Value);
                    break;

                case JsonToken.StartObject:
                    m_writer.WriteStartObject();
                    break;

                case JsonToken.PropertyName:
                    // Property names will be handled when value is written
                    break;

                default:
                    Contract.Assert(false, "unhandled token type");
                    break;
                }

                return(true);
            }

            return(false);
        }
Beispiel #7
0
 void SaveConfigInternalHashTags(JsonTextWriter writer)
 {
     writer.WriteStartArray ();
     for (int i = 1; i < _hashTags.Count; i ++)
         writer.WriteString (_hashTags[i]);
     writer.WriteEndArray ();
 }
Beispiel #8
0
        internal async Task WriteDiagnosticLog()
        {
            string agentError = null;

            try
            {
                var success = await _agentWriter.Ping().ConfigureAwait(false);

                if (!success)
                {
                    agentError = "An error occurred while sending traces to the agent";
                }
            }
            catch (Exception ex)
            {
                agentError = ex.Message;
            }

            try
            {
                var frameworkDescription = FrameworkDescription.Create();

                var stringWriter = new StringWriter();

                using (var writer = new JsonTextWriter(stringWriter))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("date");
                    writer.WriteValue(DateTime.Now);

                    writer.WritePropertyName("os_name");
                    writer.WriteValue(frameworkDescription.OSPlatform);

                    writer.WritePropertyName("os_version");
                    writer.WriteValue(Environment.OSVersion.ToString());

                    writer.WritePropertyName("version");
                    writer.WriteValue(typeof(Tracer).Assembly.GetName().Version.ToString());

                    writer.WritePropertyName("platform");
                    writer.WriteValue(frameworkDescription.ProcessArchitecture);

                    writer.WritePropertyName("lang");
                    writer.WriteValue(frameworkDescription.Name);

                    writer.WritePropertyName("lang_version");
                    writer.WriteValue(frameworkDescription.ProductVersion);

                    writer.WritePropertyName("env");
                    writer.WriteValue(Settings.Environment);

                    writer.WritePropertyName("enabled");
                    writer.WriteValue(Settings.TraceEnabled);

                    writer.WritePropertyName("service");
                    writer.WriteValue(DefaultServiceName);

                    writer.WritePropertyName("agent_url");
                    writer.WriteValue(Settings.AgentUri);

                    writer.WritePropertyName("debug");
                    writer.WriteValue(GlobalSettings.Source.DebugEnabled);

                    writer.WritePropertyName("analytics_enabled");
                    writer.WriteValue(Settings.AnalyticsEnabled);

                    writer.WritePropertyName("sample_rate");
                    writer.WriteValue(Settings.GlobalSamplingRate);

                    writer.WritePropertyName("sampling_rules");
                    writer.WriteValue(Settings.CustomSamplingRules);

                    writer.WritePropertyName("tags");

                    writer.WriteStartArray();

                    foreach (var entry in Settings.GlobalTags)
                    {
                        writer.WriteValue(string.Concat(entry.Key, ":", entry.Value));
                    }

                    writer.WriteEndArray();

                    writer.WritePropertyName("log_injection_enabled");
                    writer.WriteValue(Settings.LogsInjectionEnabled);

                    writer.WritePropertyName("runtime_metrics_enabled");
                    writer.WriteValue(Settings.TracerMetricsEnabled);

                    writer.WritePropertyName("disabled_integrations");
                    writer.WriteStartArray();

                    foreach (var integration in Settings.DisabledIntegrationNames)
                    {
                        writer.WriteValue(integration);
                    }

                    writer.WriteEndArray();

                    writer.WritePropertyName("agent_reachable");
                    writer.WriteValue(agentError == null);

                    writer.WritePropertyName("agent_error");
                    writer.WriteValue(agentError ?? string.Empty);

                    writer.WriteEndObject();
                }

                Log.Information("DATADOG TRACER CONFIGURATION - {0}", stringWriter.ToString());
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "DATADOG TRACER DIAGNOSTICS - Error fetching configuration");
            }
        }
Beispiel #9
0
        public String ToJSONRepresentation()
        {
            StringBuilder sb = new StringBuilder();
            JsonWriter    jw = new JsonTextWriter(new StringWriter(sb));


            string sCote  = string.Empty;
            string sCote2 = string.Empty;

            if (PNPUTools.ParamAppli.SimpleCotesReport == false)
            {
                sCote  = "'";
                sCote2 = "*";
            }

            jw.Formatting = Formatting.Indented;
            jw.WriteStartArray();
            jw.WriteStartObject();
            jw.WritePropertyName("id");
            jw.WriteValue("1");
            jw.WritePropertyName("name");
            jw.WriteValue(sCote + this.name + sCote);

            /*jw.WritePropertyName("id-client");
             * jw.WriteValue(this.IdClient);*/
            jw.WritePropertyName("result");
            jw.WriteValue(sCote + this.result + sCote);
            jw.WritePropertyName("debut");
            jw.WriteValue(sCote + this.Debut.ToString("dd/MM/yy H:mm:ss") + sCote);
            jw.WritePropertyName("fin");
            jw.WriteValue(sCote + this.Fin.ToString("dd/MM/yy H:mm:ss") + sCote);

            jw.WritePropertyName("children");
            jw.WriteStartArray();

            for (int i = 0; i < Source.Count; i++)
            {
                string sIDSource;
                sIDSource = (i + 2).ToString(DetermineFormat(Source.Count + 1));
                jw.WriteStartObject();
                jw.WritePropertyName("id");
                jw.WriteValue(sIDSource);
                jw.WritePropertyName("name");
                jw.WriteValue(sCote + Source[i].Name + sCote);
                jw.WritePropertyName("result");
                jw.WriteValue(sCote + Source[i].Result + sCote);


                // Cas particulier des dépedances
                if (Source[i].Name == "Contrôle des dépendances inter packages")
                {
                    jw.WritePropertyName("children");
                    jw.WriteStartArray();
                    jw.WriteEndArray();
                }


                if (Source[i].Controle.Count > 0)
                {
                    jw.WritePropertyName("children");
                    jw.WriteStartArray();
                    for (int j = 0; j < Source[i].Controle.Count; j++)
                    {
                        string sIDControle;
                        sIDControle = sIDSource + (j + 1).ToString(DetermineFormat(Source[i].Controle.Count));
                        jw.WriteStartObject();
                        jw.WritePropertyName("id");
                        jw.WriteValue(sIDControle);
                        jw.WritePropertyName("name");
                        jw.WriteValue(sCote2 + Source[i].Controle[j].Name + sCote2);
                        jw.WritePropertyName("Tooltip");
                        jw.WriteValue(sCote2 + Source[i].Controle[j].Tooltip + sCote2);
                        jw.WritePropertyName("result");
                        jw.WriteValue(sCote + Source[i].Controle[j].Result + sCote);

                        if (Source[i].Controle[j].Message.Count > 0)
                        {
                            jw.WritePropertyName("message");
                            jw.WriteStartArray();
                            for (int k = 0; k < Source[i].Controle[j].Message.Count; k++)
                            {
                                string sIDMessage;
                                sIDMessage = sIDControle + (k + 1).ToString(DetermineFormat(Source[i].Controle[j].Message.Count));
                                jw.WriteStartObject();
                                jw.WritePropertyName("id");
                                jw.WriteValue(sIDMessage);
                                jw.WritePropertyName("name");
                                jw.WriteValue(sCote + Source[i].Controle[j].Message[k] + sCote);
                                jw.WriteEndObject();
                            }
                            jw.WriteEndArray();
                        }
                        jw.WriteEndObject();
                    }
                    jw.WriteEndArray();
                }
                jw.WriteEndObject();
            }

            jw.WriteEndArray();

            jw.WriteEndObject();

            jw.WriteEndArray();

            if (PNPUTools.ParamAppli.SimpleCotesReport == false)
            {
                sb = sb.Replace("\"", "");
                sb = sb.Replace(sCote2, "\"");
            }
            return(sb.ToString());
        }
Beispiel #10
0
        private void PopulateControls()
        {
            string featuredImageUrl = string.Empty;
            string markupTop        = string.Empty;
            string markupBottom     = string.Empty;

            featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage;
            markupTop        = displaySettings.ModuleInstanceMarkupTop;
            markupBottom     = displaySettings.ModuleInstanceMarkupBottom;

            strOutput.Append(markupTop);

            if (config.UseHeader && config.HeaderLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.Append(string.Format(displaySettings.HeaderContentFormat, config.HeaderContent));
                }
                catch (FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "HeaderContentFormat", moduleTitle, ex);
                }
            }
            StringBuilder  jsonString   = new StringBuilder();
            StringWriter   stringWriter = new StringWriter(jsonString);
            JsonTextWriter jsonWriter   = new JsonTextWriter(stringWriter);

            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm
            jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm
            jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            string jsonObjName = "sflexi" + module.ModuleId.ToString() + (config.IsGlobalView ? "Modules" : "Items");

            if (config.RenderJSONOfData)
            {
                jsonWriter.WriteRaw("var " + jsonObjName + " = ");
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteStartObject();
                }
                else
                {
                    jsonWriter.WriteStartArray();
                }
            }

            List <IndexedStringBuilder> itemsMarkup = new List <IndexedStringBuilder>();
            //List<Item> categorizedItems = new List<Item>();
            bool usingGlobalViewMarkup = !String.IsNullOrWhiteSpace(displaySettings.GlobalViewMarkup);
            int  currentModuleID       = -1;

            foreach (Item item in items)
            {
                bool itemIsEditable = isEditable || WebUser.IsInRoles(item.EditRoles);
                bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable;
                if (!itemIsViewable)
                {
                    continue;
                }

                //int itemCount = 0;
                //StringBuilder content = new StringBuilder();
                IndexedStringBuilder content = new IndexedStringBuilder();

                ModuleConfiguration itemModuleConfig = config;

                if (config.IsGlobalView)
                {
                    itemModuleConfig   = new ModuleConfiguration(module);
                    content.SortOrder1 = itemModuleConfig.GlobalViewSortOrder;
                    content.SortOrder2 = item.SortOrder;
                }
                else
                {
                    content.SortOrder1 = item.SortOrder;
                }

                item.ModuleFriendlyName = itemModuleConfig.ModuleFriendlyName;
                if (String.IsNullOrWhiteSpace(itemModuleConfig.ModuleFriendlyName))
                {
                    Module itemModule = new Module(item.ModuleGuid);
                    if (itemModule != null)
                    {
                        item.ModuleFriendlyName = itemModule.ModuleTitle;
                    }
                }

                //List<ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid);

                //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id.
                string itemEditUrl  = WebUtils.GetSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID;
                string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty;

                if (config.RenderJSONOfData)
                {
                    if (config.IsGlobalView)
                    {
                        if (currentModuleID != item.ModuleID)
                        {
                            if (currentModuleID != -1)
                            {
                                jsonWriter.WriteEndObject();
                                jsonWriter.WriteEndObject();
                            }

                            currentModuleID = item.ModuleID;

                            //always label objects in globalview
                            jsonWriter.WritePropertyName("m" + currentModuleID.ToString());
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("Module");
                            jsonWriter.WriteValue(item.ModuleFriendlyName);
                            jsonWriter.WritePropertyName("Items");
                            jsonWriter.WriteStartObject();
                        }
                    }
                    if (config.JsonLabelObjects || config.IsGlobalView)
                    {
                        jsonWriter.WritePropertyName("i" + item.ItemID.ToString());
                    }
                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName("ItemId");
                    jsonWriter.WriteValue(item.ItemID.ToString());
                    jsonWriter.WritePropertyName("SortOrder");
                    jsonWriter.WriteValue(item.SortOrder.ToString());
                    if (IsEditable)
                    {
                        jsonWriter.WritePropertyName("EditUrl");
                        jsonWriter.WriteValue(itemEditUrl);
                    }
                }
                content.Append(displaySettings.ItemMarkup);

                foreach (Field field in fields)
                {
                    if (String.IsNullOrWhiteSpace(field.Token))
                    {
                        field.Token = "$_NONE_$";                                         //just in case someone has loaded the database with fields without using a source file.
                    }
                    bool fieldValueFound = false;

                    foreach (ItemFieldValue fieldValue in fieldValues.Where(fv => fv.ItemGuid == item.ItemGuid))
                    {
                        if (field.FieldGuid == fieldValue.FieldGuid)
                        {
                            fieldValueFound = true;

                            if (String.IsNullOrWhiteSpace(fieldValue.FieldValue) ||
                                fieldValue.FieldValue.StartsWith("&deleted&") ||
                                fieldValue.FieldValue.StartsWith("&amp;deleted&amp;") ||
                                fieldValue.FieldValue.StartsWith("<p>&deleted&</p>") ||
                                fieldValue.FieldValue.StartsWith("<p>&amp;deleted&amp;</p>"))
                            {
                                content.Replace("^" + field.Token + "^", string.Empty);
                                content.Replace("^" + field.Token, string.Empty);
                                content.Replace(field.Token + "^", string.Empty);
                                content.Replace(field.Token, string.Empty);
                            }
                            else
                            {
                                if (IsDateField(field))
                                {
                                    DateTime dateTime = new DateTime();
                                    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                    {
                                        /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used
                                        content.Replace("^" + field.Token + "^", dateTime.ToString(field.DateFormat));
                                        content.Replace("^" + field.Token, dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                        content.Replace(field.Token + "^", field.PreTokenString + dateTime.ToString(field.DateFormat));
                                        content.Replace(field.Token, field.PreTokenString + dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                    }
                                }

                                if (IsCheckBoxListField(field) || IsRadioButtonListField(field))
                                {
                                    foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
                                    {
                                        if (cblm.Field == field.Name)
                                        {
                                            StringBuilder cblmContent = new StringBuilder();

                                            List <string> values = fieldValue.FieldValue.SplitOnCharAndTrim(';');
                                            if (values.Count > 0)
                                            {
                                                foreach (string value in values)
                                                {
                                                    //why did we use _ValueItemID_ here instead of _ItemID_?
                                                    cblmContent.Append(cblm.Markup.Replace(field.Token, value).Replace("$_ValueItemID_$", item.ItemID.ToString()) + cblm.Separator);
                                                    cblm.SelectedValues.Add(new CheckBoxListMarkup.SelectedValue {
                                                        Value = value, ItemID = item.ItemID
                                                    });
                                                    //cblm.SelectedValues.Add(fieldValue);
                                                }
                                            }
                                            cblmContent.Length -= cblm.Separator.Length;
                                            content.Replace(cblm.Token, cblmContent.ToString());
                                        }
                                    }
                                }

                                if (field.ControlType == "CheckBox")
                                {
                                    string checkBoxContent = string.Empty;

                                    if (fieldValue.FieldValue == field.CheckBoxReturnValueWhenTrue)
                                    {
                                        content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                        content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenTrue);
                                        content.Replace(field.Token + "^", field.PreTokenString + field.PreTokenStringWhenTrue + fieldValue.FieldValue);
                                        content.Replace(field.Token, field.PreTokenString + field.PreTokenStringWhenTrue + fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenTrue);
                                    }

                                    else if (fieldValue.FieldValue == field.CheckBoxReturnValueWhenFalse)
                                    {
                                        content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                        content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenFalse);
                                        content.Replace(field.Token + "^", field.PreTokenString + field.PreTokenStringWhenFalse + fieldValue.FieldValue);
                                        content.Replace(field.Token, field.PreTokenString + field.PreTokenStringWhenFalse + fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenFalse);
                                    }
                                }

                                //else
                                //{
                                /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used


                                content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString);
                                content.Replace(field.Token + "^", field.PreTokenString + fieldValue.FieldValue);
                                content.Replace(field.Token, field.PreTokenString + fieldValue.FieldValue + field.PostTokenString);
                                //}
                            }
                            //if (!String.IsNullOrWhiteSpace(field.LinkedField))
                            //{
                            //    Field linkedField = fields.Find(delegate(Field f) { return f.Name == field.LinkedField; });
                            //    if (linkedField != null)
                            //    {
                            //        ItemFieldValue linkedValue = fieldValues.Find(delegate(ItemFieldValue fv) { return fv.FieldGuid == linkedField.FieldGuid; });
                            //        content.Replace(linkedField.Token, linkedValue.FieldValue);
                            //    }
                            //}

                            if (config.RenderJSONOfData)
                            {
                                jsonWriter.WritePropertyName(field.Name);
                                //if (IsDateField(field))
                                //{
                                //    DateTime dateTime = new DateTime();
                                //    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                //    {
                                //        jsonWriter.WriteValue(dateTime);
                                //    }

                                //}
                                //else
                                //{
                                jsonWriter.WriteValue(fieldValue.FieldValue);
                                //}
                            }
                        }
                    }

                    if (!fieldValueFound)
                    {
                        content.Replace(field.Token, field.DefaultValue);
                    }
                }

                if (config.RenderJSONOfData)
                {
                    //if (config.IsGlobalView)
                    //{
                    //    jsonWriter.WriteEndObject();
                    //}
                    jsonWriter.WriteEndObject();
                }

                content.Replace("$_EditLink_$", itemEditLink);
                content.Replace("$_ItemID_$", item.ItemID.ToString());
                content.Replace("$_SortOrder_$", item.SortOrder.ToString());

                if (!String.IsNullOrWhiteSpace(content))
                {
                    itemsMarkup.Add(content);
                }
            }
            if (config.DescendingSort)
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = b.SortOrder1.CompareTo(a.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(b.SortOrder2.CompareTo(a.SortOrder2));
                    }
                });
            }
            else
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(a.SortOrder2.CompareTo(b.SortOrder2));
                    }
                });
            }
            StringBuilder allItems = new StringBuilder();

            if (displaySettings.ItemsPerGroup == -1)
            {
                foreach (IndexedStringBuilder sb in itemsMarkup)
                {
                    //allItems.Append(displaySettings.GlobalViewModuleGroupMarkup.Replace("$_ModuleGroupName_$", sb.GroupName));
                    allItems.Append(sb.ToString());
                }
                if (usingGlobalViewMarkup)
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, displaySettings.GlobalViewMarkup.Replace("$_ModuleGroups_$", allItems.ToString()));
                }
                else
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, allItems.ToString());
                }
            }
            else
            {
                int itemIndex = 0;

                decimal totalGroupCount = Math.Ceiling(itemsMarkup.Count / Convert.ToDecimal(displaySettings.ItemsPerGroup));

                if (totalGroupCount < 1 && itemsMarkup.Count > 0)
                {
                    totalGroupCount = 1;
                }

                int currentGroup            = 1;
                List <StringBuilder> groups = new List <StringBuilder>();
                while (currentGroup <= totalGroupCount && itemIndex < itemsMarkup.Count)
                {
                    StringBuilder group = new StringBuilder();
                    group.Append(displaySettings.ItemsRepeaterMarkup);
                    //group.SortOrder1 = itemsMarkup[itemIndex].SortOrder1;
                    //group.SortOrder2 = itemsMarkup[itemIndex].SortOrder2;
                    //group.GroupName = itemsMarkup[itemIndex].GroupName;
                    for (int i = 0; i < displaySettings.ItemsPerGroup; i++)
                    {
                        if (itemIndex < itemsMarkup.Count)
                        {
                            group.Replace("$_Items[" + i.ToString() + "]_$", itemsMarkup[itemIndex].ToString());
                            itemIndex++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    groups.Add(group);
                    currentGroup++;
                }

                //groups.Sort(delegate (IndexedStringBuilder a, IndexedStringBuilder b) {
                //    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                //    if (xdiff != 0) return xdiff;
                //    else return a.SortOrder2.CompareTo(b.SortOrder2);
                //});

                foreach (StringBuilder group in groups)
                {
                    allItems.Append(group.ToString());
                }

                strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, Regex.Replace(allItems.ToString(), @"(\$_Items\[[0-9]+\]_\$)", string.Empty, RegexOptions.Multiline));
            }



            //strOutput.Append(displaySettings.ItemListMarkupBottom);
            if (config.RenderJSONOfData)
            {
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteEndObject();

                    if (config.IsGlobalView)
                    {
                        jsonWriter.WriteEndObject();
                        jsonWriter.WriteEnd();
                    }
                }
                else
                {
                    jsonWriter.WriteEndArray();
                }

                MarkupScript jsonScript = new MarkupScript();

                jsonWriter.Close();
                stringWriter.Close();

                jsonScript.RawScript  = stringWriter.ToString();
                jsonScript.Position   = config.JsonRenderLocation;
                jsonScript.ScriptName = "sflexi" + module.ModuleId.ToString() + config.MarkupDefinitionName.ToCleanFileName() + "-JSON";

                List <MarkupScript> scripts = new List <MarkupScript>();
                scripts.Add(jsonScript);

                SuperFlexiHelpers.SetupScripts(scripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this);
            }

            if (config.UseFooter && config.FooterLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent);
                }
                catch (System.FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "FooterContentFormat", moduleTitle, ex);
                }
            }

            strOutput.Append(markupBottom);

            SuperFlexiHelpers.ReplaceStaticTokens(strOutput, config, isEditable, displaySettings, module.ModuleId, pageSettings, siteSettings, out strOutput);

            //this is for displaying all of the selected values from the items outside of the items themselves
            foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
            {
                StringBuilder cblmContent = new StringBuilder();

                if (fields.Count > 0 && cblm.SelectedValues.Count > 0)
                {
                    Field theField = fields.Where(field => field.Name == cblm.Field).Single();
                    if (theField != null)
                    {
                        List <CheckBoxListMarkup.SelectedValue> distinctSelectedValues = new List <CheckBoxListMarkup.SelectedValue>();
                        foreach (CheckBoxListMarkup.SelectedValue selectedValue in cblm.SelectedValues)
                        {
                            CheckBoxListMarkup.SelectedValue match = distinctSelectedValues.Find(i => i.Value == selectedValue.Value);
                            if (match == null)
                            {
                                distinctSelectedValues.Add(selectedValue);
                            }
                            else
                            {
                                match.Count++;
                            }
                        }
                        //var selectedValues = cblm.SelectedValues.GroupBy(selectedValue => selectedValue.Value)
                        //    .Select(distinctSelectedValue => new { Value = distinctSelectedValue.Key, Count = distinctSelectedValue.Count(), ItemID = distinctSelectedValue.ItemID })
                        //    .OrderBy(x => x.Value);
                        foreach (CheckBoxListMarkup.SelectedValue value in distinctSelectedValues)
                        {
                            cblmContent.Append(cblm.Markup.Replace(theField.Token, value.Value).Replace("$_ValueItemID_$", value.ItemID.ToString()) + cblm.Separator);
                            cblmContent.Replace("$_CBLValueCount_$", value.Count.ToString());
                        }
                    }

                    if (cblmContent.Length >= cblm.Separator.Length)
                    {
                        cblmContent.Length -= cblm.Separator.Length;
                    }

                    strOutput.Replace(cblm.Token, cblmContent.ToString());
                }

                strOutput.Replace(cblm.Token, string.Empty);
            }
            theLit.Text = strOutput.ToString();
        }
 //-----------------------------------------------------------------------------------------------------
 public void cshot_Shot(object o, ShotEventArgs e)
 {
     try
     {
         StringBuilder sb = new StringBuilder();
         StringWriter  sw = new StringWriter(sb);
         using (JsonWriter writer = new JsonTextWriter(sw))
         {
             writer.Formatting = Formatting.None;
             writer.WriteStartArray();
             writer.WriteValue((int)ServerOpcode.play); //8
             writer.WriteStartArray();
             if (e.User.Position == 0)
             {
                 writer.WriteValue(1); //2 - next_turn_number
             }
             else
             {
                 writer.WriteValue(0);           //2 - next_turn_number
             }
             writer.WriteValue(e.User.Position); //0 - player_number
             writer.WriteValue(e.xb);            //1022 - x
             writer.WriteValue(e.yb);            //121 - y
             writer.WriteValue(e.look);          //1 - look
             writer.WriteValue(1);               //845 - delay
             //writer.WriteValue(0); //1 - next_turn_of_player
             if (e.User.Position == 0)
             {
                 writer.WriteValue(1); //2 - next_turn_of_player
             }
             else
             {
                 writer.WriteValue(0); //2 - next_turn_of_player
             }
             writer.WriteStartArray();
             writer.WriteEndArray();
             writer.WriteValue(799);  //799 - thor_x
             writer.WriteValue(-420); //-420 - thor_y
             writer.WriteValue(0);    //24 - thor_angle
             writer.WriteValue(40);   //0 - thor_damage
             writer.WriteValue(1);    //33
             writer.WriteValue(0);    //0
             writer.WriteValue(234);  //326
             writer.WriteStartArray();
             writer.WriteStartObject();
             writer.WritePropertyName("start");
             writer.WriteStartObject();
             writer.WritePropertyName("x");
             writer.WriteValue(e.xf);    //1042
             writer.WritePropertyName("y");
             writer.WriteValue(e.yf);    //95
             writer.WritePropertyName("ang");
             writer.WriteValue(e.angle); //24
             writer.WritePropertyName("power");
             writer.WriteValue(e.power); //101
             writer.WritePropertyName("ax");
             writer.WriteValue(e.ax);    //0
             writer.WritePropertyName("ay");
             writer.WriteValue(e.ay);    //398
             writer.WriteEndObject();
             writer.WritePropertyName("exp");
             writer.WriteValue(0);      //0
             writer.WritePropertyName("img");
             writer.WriteValue(0);      //0
             writer.WritePropertyName("time");
             writer.WriteValue(e.time); //1340
             //"hole":[887,95,60,40],"damages":[]}],150]
             if (e.col == true)
             {
                 writer.WritePropertyName("hole");
                 writer.WriteStartArray();
                 writer.WriteValue(e.cx);  //x hole
                 writer.WriteValue(e.cy);  //y hole
                 writer.WriteValue(36);    //w
                 writer.WriteValue(40);    //h
                 writer.WriteEndArray();
                 writer.WritePropertyName("damages");
                 writer.WriteStartArray();
                 writer.WriteEndArray();
             }
             writer.WriteEndObject();
             writer.WriteEndArray();
             writer.WriteValue(150);
             writer.WriteEndArray();
             writer.WriteEndArray();
         }
         SendAll(sb.ToString());
     }
     catch (Exception ex)
     {
         LogConsole.Show(LogType.ERROR, ex.ToString());
     }
 }
        //-----------------------------------------------------------------------------------------------------
        public void GameStart()
        {
            try
            {
                if (this._channel_map < 0)
                {
                    Random rand = new Random();
                    this._channel_map = 0;//rand.Next(0, 11);
                }

                if (UserInSala.Count() <= 1)
                {
                    ChatInfo("Error ", "", 6);
                    return;
                }
                _map_data   = Program.RMaps.Single(a => a.id == this._channel_map);
                cshot       = new CShot(_map_data.ground);
                cshot.Shot += cshot_Shot;
            }
            catch
            {
                LogConsole.Show(LogType.ERROR, "Map: {0} no Found", this._channel_map);
            }
            //[4,[[
            //[0,146634,"Carlos 22",null,0,377,134,1000,0,0,10,55,-8,0,[1,2,0,0,0,0],52,33,52,33,52,33],
            //[1,151426,"Bil Board",null,13,20,35,1800,250,30,15,65,-7,5,[12,30],    68,45,68,45,68,45]
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.game_start);
                writer.WriteStartArray();
                writer.WriteStartArray();
                int c = 0;
                foreach (UserManager.UserClass usp in UserInSala)
                {
                    Point pt = _map_data.pos[c];
                    usp.x = pt.X;
                    usp.y = pt.Y;
                    writer.WriteStartArray();
                    writer.WriteValue(usp.Position);
                    writer.WriteValue(usp.user_id);
                    writer.WriteValue(usp.Name);
                    string dsd = null;
                    writer.WriteValue(dsd);
                    writer.WriteValue(usp.rank);
                    writer.WriteValue(usp.x);
                    writer.WriteValue(usp.y);
                    writer.WriteValue(1000);
                    writer.WriteValue(0);
                    writer.WriteValue(0);
                    writer.WriteValue(10);
                    writer.WriteValue(55);
                    writer.WriteValue(-8);
                    writer.WriteValue(usp.mobil);
                    writer.WriteStartArray();
                    writer.WriteValue(usp.head);
                    writer.WriteValue(usp.body);
                    if (usp.Is_Bot != 1)
                    {
                        writer.WriteValue(usp.eyes);
                        writer.WriteValue(usp.flag);
                        writer.WriteValue(usp.foreground);
                        writer.WriteValue(usp.background);
                    }
                    writer.WriteEndArray();
                    writer.WriteValue(52);
                    writer.WriteValue(33);
                    writer.WriteValue(52);
                    writer.WriteValue(33);
                    writer.WriteValue(52);
                    writer.WriteValue(33);
                    writer.WriteEndArray();
                    c++;
                }
                //],0,562,-452,0,0,[2,2,0,0,3],0,257,7,null]]
                writer.WriteEndArray();
                writer.WriteValue(0);
                writer.WriteValue(562);
                writer.WriteValue(-452);
                writer.WriteValue(0);
                writer.WriteValue(0);
                writer.WriteStartArray();
                writer.WriteValue(2);
                writer.WriteValue(2);
                writer.WriteValue(0);
                writer.WriteValue(0);
                writer.WriteValue(3);
                writer.WriteEndArray();
                writer.WriteValue(0);
                writer.WriteValue(257);
                writer.WriteValue(_channel_map);
                string xdd = null;
                writer.WriteValue(xdd);
                writer.WriteEndArray();
                writer.WriteEndArray();
                SendAll(sb.ToString());
            }
        }
        /// <summary>
        /// Copies the selected items.
        /// </summary>
        public void Copy()
        {
            var selection = SelectedControls;

            if (selection.Count == 0)
            {
                Application.ClipboardText = string.Empty;
                return;
            }

            StringBuilder sb = new StringBuilder(256);
            StringWriter  sw = new StringWriter(sb, CultureInfo.InvariantCulture);

            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("Nodes");
                jsonWriter.WriteStartArray();

                for (int i = 0; i < selection.Count; i++)
                {
                    var node = selection[i] as SurfaceNode;
                    if (node == null)
                    {
                        continue;
                    }

                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("GroupID");
                    jsonWriter.WriteValue(node.GroupArchetype.GroupID);

                    jsonWriter.WritePropertyName("TypeID");
                    jsonWriter.WriteValue(node.Archetype.TypeID);

                    jsonWriter.WritePropertyName("ID");
                    jsonWriter.WriteValue(node.ID);

                    jsonWriter.WritePropertyName("X");
                    jsonWriter.WriteValue(node.Location.X);

                    jsonWriter.WritePropertyName("Y");
                    jsonWriter.WriteValue(node.Location.Y);

                    if (node.Values != null && node.Values.Length > 0)
                    {
                        jsonWriter.WritePropertyName("Values");
                        jsonWriter.WriteStartArray();

                        for (int j = 0; j < node.Values.Length; j++)
                        {
                            Utilities.Utils.WriteCommonValue(jsonWriter, node.Values[j]);
                        }

                        jsonWriter.WriteEndArray();
                    }

                    if (node.Elements != null && node.Elements.Count > 0)
                    {
                        jsonWriter.WritePropertyName("Boxes");
                        jsonWriter.WriteStartArray();

                        for (int j = 0; j < node.Elements.Count; j++)
                        {
                            if (node.Elements[j] is Box box)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName("ID");
                                jsonWriter.WriteValue(box.ID);

                                jsonWriter.WritePropertyName("NodeIDs");
                                jsonWriter.WriteStartArray();

                                for (int k = 0; k < box.Connections.Count; k++)
                                {
                                    var target = box.Connections[k];
                                    jsonWriter.WriteValue(target.ParentNode.ID);
                                }

                                jsonWriter.WriteEndArray();

                                jsonWriter.WritePropertyName("BoxIDs");
                                jsonWriter.WriteStartArray();

                                for (int k = 0; k < box.Connections.Count; k++)
                                {
                                    var target = box.Connections[k];
                                    jsonWriter.WriteValue(target.ID);
                                }

                                jsonWriter.WriteEndArray();

                                jsonWriter.WriteEndObject();
                            }
                        }

                        jsonWriter.WriteEndArray();
                    }

                    jsonWriter.WriteEndObject();
                }

                jsonWriter.WriteEndArray();

                jsonWriter.WritePropertyName("Comments");
                jsonWriter.WriteStartArray();

                for (int i = 0; i < selection.Count; i++)
                {
                    var comment = selection[i] as SurfaceComment;
                    if (comment == null)
                    {
                        continue;
                    }

                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("Title");
                    jsonWriter.WriteValue(comment.Title);

                    jsonWriter.WritePropertyName("Color");
                    Utilities.Utils.WriteCommonValue(jsonWriter, comment.Color);

                    jsonWriter.WritePropertyName("Bounds");
                    Utilities.Utils.WriteCommonValue(jsonWriter, comment.Bounds);

                    jsonWriter.WriteEndObject();
                }

                jsonWriter.WriteEndArray();

                jsonWriter.WriteEnd();
            }

            Application.ClipboardText = sw.ToString();
        }
Beispiel #14
0
        public override string ToJSON()
        {
            MemoryStream   str = new MemoryStream();
            StreamWriter   tw  = new StreamWriter(str);
            JsonTextWriter w   = new JsonTextWriter(tw);
            StreamReader   rdr;

            List <string> dateResult = Values.SelectMany(v => v.Value.Select(v2 => v2.TimeStamp.ToString())).ToList();

            dateResult = dateResult.OrderBy(d => d).Distinct().ToList();

            w.WriteStartObject();
            w.WritePropertyName("labels");
            w.WriteStartArray();

            foreach (string dateVal in dateResult)
            {
                DateTimeStamp dtstamp = DateTimeStamp.Parse(dateVal);
                w.WriteValue(string.Format("{0}", dtstamp.ToStandardString()));
            }

            w.WriteEndArray();



            w.WritePropertyName("datasets");
            w.WriteStartArray();

            int colorIncrementer = 0;

            foreach (var key in Values.Keys)
            {
                w.WriteStartObject();

                w.WritePropertyName("label");
                w.WriteValue(string.Format("{0}", key.Name));

                w.WritePropertyName("fillColor");
                w.WriteValue(GetArgb(colorIncrementer, 0.2f));

                w.WritePropertyName("strokeColor");
                w.WriteValue(GetArgb(colorIncrementer, 0.7f));

                w.WritePropertyName("pointColor");
                w.WriteValue(GetArgb(colorIncrementer, 1.0f));

                w.WritePropertyName("data");

                w.WriteStartArray();
                foreach (string dt in dateResult)
                {
                    var    DevLog = Values[key].Where(v => v.TimeStamp.ToString() == dt).FirstOrDefault();
                    string value  = null;
                    if (DevLog != null)
                    {
                        value = DevLog.Value;
                    }

                    w.WriteValue(value);
                }
                w.WriteEndArray();


                w.WriteEndObject();

                colorIncrementer++;
            }
            w.WriteEndArray();
            w.WriteEndObject();

            w.Flush();
            str.Flush();

            str.Position = 0;

            rdr = new StreamReader(str);
            return(rdr.ReadToEnd());
        }
    public static object Getdata(string i, string j, string k, string n)
    {
        string connectStr = "Data Source=tcp:163.18.21.223;Persist Security Info=True;Password=GhOst1945;User ID=sa;Initial Catalog=Knight_Tour_3D";
        string state      = ConnectToSql(connectStr);

        if (state == "OK")
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = conn;


            cmd.Parameters.Clear();
            cmd.CommandType = CommandType.StoredProcedure; //指定要做StoredProcedure型態
            cmd.CommandText = "Knight_tour_boostversion";


            try
            {
                cmd.Parameters.Add("@i", SqlDbType.Int).Value      = int.Parse(i);
                cmd.Parameters.Add("@j", SqlDbType.Int).Value      = int.Parse(j);
                cmd.Parameters.Add("@k", SqlDbType.Int).Value      = int.Parse(k);
                cmd.Parameters.Add("@n", SqlDbType.Int).Value      = int.Parse(n);
                cmd.Parameters.Add("@rState", SqlDbType.Int).Value = -1;
                cmd.Parameters["@rState"].Direction = ParameterDirection.ReturnValue;

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

                if ((int)cmd.Parameters["@rState"].Value == 0)
                {
                    cmd             = new SqlCommand();
                    cmd.CommandText = "SELECT * FROM Board order by Step_No";
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection  = conn;
                    SqlDataReader reader;
                    conn.Open();

                    reader = cmd.ExecuteReader();

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

                    using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                    {
                        jsonWriter.WriteStartArray();

                        while (reader.Read())
                        {
                            jsonWriter.WriteStartObject();

                            int fields = reader.FieldCount;

                            for (int r = 0; r < fields; r++)
                            {
                                jsonWriter.WritePropertyName(reader.GetName(r));
                                jsonWriter.WriteValue(reader[r]);
                            }

                            jsonWriter.WriteEndObject();
                        }
                        jsonWriter.WriteEndArray();
                    }

                    return(sb.ToString());
                }
                else
                {
                    return("StoredProcedure error");
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            finally
            {
                cmd.Cancel();
                conn.Close();
                conn.Dispose();
            }
        }
        else
        {
            return(state);
        }
    }
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

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

                foreach (var doc in inputs)
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("type");
                    writer.WriteValue("add");

                    writer.WritePropertyName("id");
                    writer.WriteValue(
                        _idMetaKey != null ? doc.String(_idMetaKey) : doc.Id
                        );

                    writer.WritePropertyName("fields");
                    writer.WriteStartObject();

                    if (_bodyField != null)
                    {
                        writer.WritePropertyName(_bodyField);
                        writer.WriteValue(doc.Content);
                    }

                    foreach (var field in _fields)
                    {
                        var value = field.GetValue(doc);
                        if (value == null)
                        {
                            // Null fields are not written
                            continue;
                        }

                        writer.WritePropertyName(field.FieldName);
                        writer.WriteRawValue(
                            JsonConvert.SerializeObject(value)
                            );
                    }

                    foreach (var field in _metaFields)
                    {
                        if (!doc.ContainsKey(field.MetaKey))
                        {
                            continue;
                        }

                        var value = doc.Get(field.MetaKey);
                        if (value == null)
                        {
                            // Null fields are not written
                            continue;
                        }

                        value = field.Transformer.Invoke(value.ToString());
                        if (value == null)
                        {
                            // If the transformer function returns null, we'll not writing this either
                            continue;
                        }

                        writer.WritePropertyName(field.FieldName);
                        writer.WriteRawValue(
                            JsonConvert.SerializeObject(value)
                            );
                    }

                    writer.WriteEndObject();

                    writer.WriteEndObject();
                }

                writer.WriteEndArray();

                return(new[] { context.GetDocument(sw.ToString()) });
            }
        }
Beispiel #17
0
 public void Dispose()
 {
     _jsonTextWriter.WriteWhitespace(Environment.NewLine);
     _jsonTextWriter.WriteEndArray();
     _jsonTextWriter.Close();
 }
Beispiel #18
0
        public void Path()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            string text = "Hello world.";

            byte[] data = Encoding.UTF8.GetBytes(text);

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

                writer.WriteStartArray();
                Assert.AreEqual("", writer.Path);
                writer.WriteStartObject();
                Assert.AreEqual("[0]", writer.Path);
                writer.WritePropertyName("Property1");
                Assert.AreEqual("[0].Property1", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1", writer.Path);
                writer.WriteValue(1);
                Assert.AreEqual("[0].Property1[0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1][0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1][0][0]", writer.Path);
                writer.WriteEndObject();
                Assert.AreEqual("[0]", writer.Path);
                writer.WriteStartObject();
                Assert.AreEqual("[1]", writer.Path);
                writer.WritePropertyName("Property2");
                Assert.AreEqual("[1].Property2", writer.Path);
                writer.WriteStartConstructor("Constructor1");
                Assert.AreEqual("[1].Property2", writer.Path);
                writer.WriteNull();
                Assert.AreEqual("[1].Property2[0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[1].Property2[1]", writer.Path);
                writer.WriteValue(1);
                Assert.AreEqual("[1].Property2[1][0]", writer.Path);
                writer.WriteEnd();
                Assert.AreEqual("[1].Property2[1]", writer.Path);
                writer.WriteEndObject();
                Assert.AreEqual("[1]", writer.Path);
                writer.WriteEndArray();
                Assert.AreEqual("", writer.Path);
            }

            Assert.AreEqual(@"[
  {
    ""Property1"": [
      1,
      [
        [
          []
        ]
      ]
    ]
  },
  {
    ""Property2"": new Constructor1(
      null,
      [
        1
      ]
    )
  }
]", sb.ToString());
        }
Beispiel #19
0
        public async Task ListInstalledAppsAsync(JsonTextWriter jsonWriter)
        {
            List <string> apps = new List <string>(_dnsWebService.DnsServer.DnsApplicationManager.Applications.Keys);

            apps.Sort();

            dynamic jsonStoreAppsArray = null;

            if (apps.Count > 0)
            {
                try
                {
                    string storeAppsJsonData = await GetStoreAppsJsonData().WithTimeout(5000);

                    jsonStoreAppsArray = JsonConvert.DeserializeObject(storeAppsJsonData);
                }
                catch
                { }
            }

            jsonWriter.WritePropertyName("apps");
            jsonWriter.WriteStartArray();

            foreach (string app in apps)
            {
                if (_dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(app, out DnsApplication application))
                {
                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("name");
                    jsonWriter.WriteValue(application.Name);

                    jsonWriter.WritePropertyName("version");
                    jsonWriter.WriteValue(DnsWebService.GetCleanVersion(application.Version));

                    if (jsonStoreAppsArray != null)
                    {
                        foreach (dynamic jsonStoreApp in jsonStoreAppsArray)
                        {
                            string name = jsonStoreApp.name.Value;
                            if (name.Equals(application.Name))
                            {
                                string version = jsonStoreApp.version.Value;
                                string url     = jsonStoreApp.url.Value;

                                jsonWriter.WritePropertyName("updateVersion");
                                jsonWriter.WriteValue(version);

                                jsonWriter.WritePropertyName("updateUrl");
                                jsonWriter.WriteValue(url);

                                jsonWriter.WritePropertyName("updateAvailable");
                                jsonWriter.WriteValue(new Version(version) > application.Version);
                                break;
                            }
                        }
                    }

                    jsonWriter.WritePropertyName("dnsApps");
                    {
                        jsonWriter.WriteStartArray();

                        foreach (KeyValuePair <string, IDnsApplication> dnsApp in application.DnsApplications)
                        {
                            jsonWriter.WriteStartObject();

                            jsonWriter.WritePropertyName("classPath");
                            jsonWriter.WriteValue(dnsApp.Key);

                            jsonWriter.WritePropertyName("description");
                            jsonWriter.WriteValue(dnsApp.Value.Description);

                            if (dnsApp.Value is IDnsAppRecordRequestHandler appRecordHandler)
                            {
                                jsonWriter.WritePropertyName("isAppRecordRequestHandler");
                                jsonWriter.WriteValue(true);

                                jsonWriter.WritePropertyName("recordDataTemplate");
                                jsonWriter.WriteValue(appRecordHandler.ApplicationRecordDataTemplate);
                            }
                            else
                            {
                                jsonWriter.WritePropertyName("isAppRecordRequestHandler");
                                jsonWriter.WriteValue(false);
                            }

                            jsonWriter.WritePropertyName("isRequestController");
                            jsonWriter.WriteValue(dnsApp.Value is IDnsRequestController);

                            jsonWriter.WritePropertyName("isAuthoritativeRequestHandler");
                            jsonWriter.WriteValue(dnsApp.Value is IDnsAuthoritativeRequestHandler);

                            jsonWriter.WritePropertyName("isQueryLogger");
                            jsonWriter.WriteValue(dnsApp.Value is IDnsQueryLogger);

                            jsonWriter.WriteEndObject();
                        }

                        jsonWriter.WriteEndArray();
                    }

                    jsonWriter.WriteEndObject();
                }
            }

            jsonWriter.WriteEndArray();
        }
Beispiel #20
0
        public static string SerializeObjects(IEnumerable <TabularObject> objects
                                              , bool includeTranslations = true
                                              , bool includePerspectives = true
                                              , bool includeRLS          = true
                                              , bool includeOLS          = true
                                              , bool includeInstanceID   = false
                                              )
        {
            var model = objects.FirstOrDefault()?.Model;

            if (model == null)
            {
                return("[]");
            }

            if (includeTranslations)
            {
                foreach (var obj in objects.OfType <ITranslatableObject>())
                {
                    obj.SaveTranslations(true);
                }
            }
            if (includePerspectives)
            {
                foreach (var obj in objects.OfType <ITabularPerspectiveObject>())
                {
                    obj.SavePerspectives(true);
                }
            }
            if (includeRLS)
            {
                foreach (var obj in objects.OfType <Table>())
                {
                    obj.SaveRLS();
                }
            }
            if (includeOLS && model.Handler.CompatibilityLevel >= 1400)
            {
                foreach (var obj in objects.OfType <Table>())
                {
                    obj.SaveOLS(true);
                }
                foreach (var obj in objects.OfType <Column>())
                {
                    obj.SaveOLS();
                }
            }

            var byType = objects.GroupBy(obj => obj.GetType(), obj => TOM.JsonSerializer.SerializeObject(obj.MetadataObject));

            using (var sw = new StringWriter())
            {
                using (var jw = new JsonTextWriter(sw))
                {
                    jw.Formatting = Formatting.Indented;
                    jw.WriteStartObject();

                    if (includeInstanceID)
                    {
                        jw.WritePropertyName("InstanceID");
                        jw.WriteValue(model.Handler.InstanceID);
                    }

                    foreach (var type in byType)
                    {
                        jw.WritePropertyName(TypeToJson(type.Key));
                        jw.WriteStartArray();
                        foreach (var obj in type)
                        {
                            jw.WriteRawValue(obj);
                        }
                        jw.WriteEndArray();
                    }

                    jw.WriteEndObject();
                }

                foreach (var obj in objects.OfType <IAnnotationObject>())
                {
                    obj.ClearTabularEditorAnnotations();
                }

                return(sw.ToString());
            }
        }
Beispiel #21
0
        void IResultWriter.WriteTableEnd()
        {
            _logResultWriter.WriteTableEnd();

            if (isJsonAuto)
            {
                _textWriter.Close();
                _textWriter = null;

                using (var streamReader = new StreamReader(_path))
                {
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                    {
                        using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(_formattedPath)))
                        {
                            jsonTextWriter.Formatting = Formatting.Indented;
                            while (true)
                            {
                                var read = jsonTextReader.Read();
                                if (!read)
                                {
                                    break;
                                }

                                switch (jsonTextReader.TokenType)
                                {
                                case JsonToken.None:
                                    break;

                                case JsonToken.StartObject:
                                    jsonTextWriter.WriteStartObject();
                                    break;

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

                                case JsonToken.StartConstructor:
                                    break;

                                case JsonToken.PropertyName:
                                    var propertyName = (string)jsonTextReader.Value;
                                    jsonTextWriter.WritePropertyName(propertyName);
                                    break;

                                case JsonToken.Comment:
                                    break;

                                case JsonToken.Raw:
                                    break;

                                case JsonToken.Integer:
                                {
                                    var value = jsonTextReader.Value;
                                    jsonTextWriter.WriteValue(value);
                                }
                                break;

                                case JsonToken.Float:
                                {
                                    var value = jsonTextReader.Value;
                                    jsonTextWriter.WriteValue(value);
                                }
                                break;

                                case JsonToken.String:
                                {
                                    var value = jsonTextReader.Value;
                                    jsonTextWriter.WriteValue(value);
                                }
                                break;

                                case JsonToken.Boolean:
                                {
                                    var value = jsonTextReader.Value;
                                    jsonTextWriter.WriteValue(value);
                                }
                                break;

                                case JsonToken.Null:
                                    break;

                                case JsonToken.Undefined:
                                    break;

                                case JsonToken.EndObject:
                                    jsonTextWriter.WriteEndObject();
                                    break;

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

                                case JsonToken.EndConstructor:
                                    break;

                                case JsonToken.Date:
                                {
                                    var value = jsonTextReader.Value;
                                    jsonTextWriter.WriteValue(value);
                                }
                                break;

                                case JsonToken.Bytes:
                                    break;

                                default:
                                    throw new ArgumentOutOfRangeException();
                                }
                            }
                        }
                    }
                }
            }
        }
        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);
            }

            try
            {
                Int64 AppUserId;
                if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
                {
                    JToken  jt;
                    string  specialInstruction = null, masterCardNumber = null, cardToken = null, cardExp = null;
                    JArray  products         = null;
                    Int64   supplierId       = 0;
                    int     numberOfPayments = 1;
                    decimal totalPrice       = 0;
                    var     lstProduct       = new Dictionary <Int64, int>();

                    if (inputData.TryGetValue(@"products", out jt))
                    {
                        products = jt.Value <JArray>();
                    }
                    if (inputData.TryGetValue(@"supplier_id", out jt))
                    {
                        supplierId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"total_price", out jt) && jt != null)
                    {
                        totalPrice = jt.Value <decimal>();
                    }
                    if (inputData.TryGetValue(@"special_instructions", out jt) && jt != null)
                    {
                        specialInstruction = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"mastercardCode", out jt) && jt != null)
                    {
                        masterCardNumber = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"num_of_payments", out jt) && jt != null)
                    {
                        numberOfPayments = jt.Value <int>();
                    }
                    if (inputData.TryGetValue(@"card_token", out jt) && jt != null)
                    {
                        cardToken = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"card_exp", out jt) && jt != null)
                    {
                        cardExp = jt.Value <string>();
                    }

                    bool isNumberOfPaymentsValid = numberOfPayments == 3 && totalPrice > 239 ||
                                                   numberOfPayments == 2 && totalPrice >= 150 ||
                                                   totalPrice / 100 / numberOfPayments > 1;
                    if (!isNumberOfPaymentsValid)
                    {
                        RespondError(Response, HttpStatusCode.OK, @"num-of-payments-not-valid");
                    }

                    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);
                    }
                    string token        = Request.Headers["Authorization"].Substring(6);
                    bool   isPriceValid = false;

                    if (supplierId > 0 && totalPrice > 0)
                    {
                        isPriceValid = OfferController.IsOfferStillValid(lstProduct, supplierId, totalPrice);
                    }
                    if (!isPriceValid)
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"price-not-valid");
                    }

                    string gifts;
                    Random rand     = new Random();
                    long   uniqueID = DateTime.Now.Ticks + rand.Next(0, 1000);
                    string tansactionId;
                    var    results = CreditGuardManager.ProcessSavedCard(AppUserId, totalPrice, numberOfPayments, masterCardNumber, specialInstruction, cardToken, cardExp, out tansactionId);
                    if (results.ResultCode != "000")
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"failed");
                    }


                    results.SpecialInstructions = specialInstruction;
                    results.NumOfPayments       = numberOfPayments;
                    var bidId          = BidController.CreateBidProduct(AppUserId, supplierId, lstProduct, true, out gifts);
                    var order          = OrderController.GenerateNewOrder(results, AppUserId, bidId, gifts, supplierId, totalPrice, core.DAL.Source.WebSite);
                    var productsParams = ProductController.GetProductsWithIds(lstProduct.Select(x => x.Key));
                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"isSuccess");
                            jsonWriter.WriteValue(results != null);
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(totalPrice);
                            jsonWriter.WritePropertyName(@"bid_id");
                            jsonWriter.WriteValue(bidId);


                            jsonWriter.WritePropertyName(@"products");
                            jsonWriter.WriteStartArray();
                            foreach (var product in productsParams)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName(@"product_id");
                                jsonWriter.WriteValue(product.ProductId);
                                jsonWriter.WritePropertyName(@"product_name");
                                jsonWriter.WriteValue(product.ProductName);
                                jsonWriter.WritePropertyName(@"product_category");
                                jsonWriter.WriteValue(product.CategoryName);
                                jsonWriter.WritePropertyName(@"product_sub_category");
                                jsonWriter.WriteValue(product.SubCategoryName);
                                jsonWriter.WritePropertyName(@"product_animal_name");
                                jsonWriter.WriteValue(product.AnimalName);
                                jsonWriter.WritePropertyName(@"product_quentity");
                                jsonWriter.WriteValue(lstProduct[product.ProductId]);
                                jsonWriter.WriteEndObject();
                            }

                            jsonWriter.WriteEndArray();

                            jsonWriter.WriteEndObject();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.LogProcessing("SavedCardProcessingHandler - ex -", "\n exception: " + ex.ToString(), true);
            }
        }
Beispiel #23
0
        public void Serialize(TextWriter textWriter)
        {
            JsonWriter jsonWriter = new JsonTextWriter(textWriter);

            // modify by egret
            if (Egret3DExportTools.ExportSetting.instance.common.jsonFormatting)
            {
                jsonWriter.Formatting = Formatting.Indented;
            }
            else
            {
                jsonWriter.Formatting = Formatting.None;
            }

            jsonWriter.WriteStartObject();

            if (ExtensionsUsed != null && ExtensionsUsed.Count > 0)
            {
                jsonWriter.WritePropertyName("extensionsUsed");
                jsonWriter.WriteStartArray();
                foreach (var extension in ExtensionsUsed)
                {
                    jsonWriter.WriteValue(extension);
                }
                jsonWriter.WriteEndArray();
            }

            if (ExtensionsRequired != null && ExtensionsRequired.Count > 0)
            {
                jsonWriter.WritePropertyName("extensionsRequired");
                jsonWriter.WriteStartArray();
                foreach (var extension in ExtensionsRequired)
                {
                    jsonWriter.WriteValue(extension);
                }
                jsonWriter.WriteEndArray();
            }

            if (Accessors != null && Accessors.Count > 0)
            {
                jsonWriter.WritePropertyName("accessors");
                jsonWriter.WriteStartArray();
                foreach (var accessor in Accessors)
                {
                    accessor.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Animations != null && Animations.Count > 0)
            {
                jsonWriter.WritePropertyName("animations");
                jsonWriter.WriteStartArray();
                foreach (var animation in Animations)
                {
                    animation.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            jsonWriter.WritePropertyName("asset");
            Asset.Serialize(jsonWriter);

            if (Buffers != null && Buffers.Count > 0)
            {
                jsonWriter.WritePropertyName("buffers");
                jsonWriter.WriteStartArray();
                foreach (var buffer in Buffers)
                {
                    buffer.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (BufferViews != null && BufferViews.Count > 0)
            {
                jsonWriter.WritePropertyName("bufferViews");
                jsonWriter.WriteStartArray();
                foreach (var bufferView in BufferViews)
                {
                    bufferView.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Cameras != null && Cameras.Count > 0)
            {
                jsonWriter.WritePropertyName("cameras");
                jsonWriter.WriteStartArray();
                foreach (var camera in Cameras)
                {
                    camera.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Images != null && Images.Count > 0)
            {
                jsonWriter.WritePropertyName("images");
                jsonWriter.WriteStartArray();
                foreach (var image in Images)
                {
                    image.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Materials != null && Materials.Count > 0)
            {
                jsonWriter.WritePropertyName("materials");
                jsonWriter.WriteStartArray();
                foreach (var material in Materials)
                {
                    material.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Meshes != null && Meshes.Count > 0)
            {
                jsonWriter.WritePropertyName("meshes");
                jsonWriter.WriteStartArray();
                foreach (var mesh in Meshes)
                {
                    mesh.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Nodes != null && Nodes.Count > 0)
            {
                jsonWriter.WritePropertyName("nodes");
                jsonWriter.WriteStartArray();
                foreach (var node in Nodes)
                {
                    node.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Samplers != null && Samplers.Count > 0)
            {
                jsonWriter.WritePropertyName("samplers");
                jsonWriter.WriteStartArray();
                foreach (var sampler in Samplers)
                {
                    sampler.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Scene != null)
            {
                jsonWriter.WritePropertyName("scene");
                Scene.Serialize(jsonWriter);
            }

            if (Scenes != null && Scenes.Count > 0)
            {
                jsonWriter.WritePropertyName("scenes");
                jsonWriter.WriteStartArray();
                foreach (var scene in Scenes)
                {
                    scene.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Skins != null && Skins.Count > 0)
            {
                jsonWriter.WritePropertyName("skins");
                jsonWriter.WriteStartArray();
                foreach (var skin in Skins)
                {
                    skin.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            if (Textures != null && Textures.Count > 0)
            {
                jsonWriter.WritePropertyName("textures");
                jsonWriter.WriteStartArray();
                foreach (var texture in Textures)
                {
                    texture.Serialize(jsonWriter);
                }
                jsonWriter.WriteEndArray();
            }

            base.Serialize(jsonWriter);

            jsonWriter.WriteEndObject();
        }
Beispiel #24
0
        public static void JsonCreate(Dictionary <string, object> jsonNodes, JsonTextWriter jw)
        {
            //todo: проверку на пустой dictionary;
            //string json = "{'tracker': {'id':'557'}, 'values': [{'field_id':22456,'value':'asfasdf'}, {} ]}";
            //StringBuilder sb = new StringBuilder();
            //using (StringWriter sw = new StringWriter(sb))
            //using (JsonTextWriter jw = new JsonTextWriter(sw))
            {
                jw.WriteStartObject();
                foreach (var j in jsonNodes)
                {
                    jw.WritePropertyName(j.Key, true);
                    if (!(j.Value is string) && !(j.Value is int))
                    {
                        if (j.Value is Array)
                        {
                            Type t2 = j.Value.GetType().GetElementType();
                            jw.WriteStartArray();
                            foreach (var el in (Array)j.Value)
                            {
                                jw.WriteValue(el);
                            }
                            jw.WriteEndArray();
                        }

                        //else if (j.Value is IEnumerable)
                        //{ }

                        else
                        {
                            Type valueType = j.Value.GetType();
                            if (valueType.IsGenericType)
                            {
                                var baseType = valueType.GetGenericTypeDefinition();
                                //{Name = "Dictionary`2" FullName = "System.Collections.Generic.Dictionary`2"}	System.Type {System.RuntimeType}

                                if (baseType == typeof(Dictionary <,>))
                                {
                                    JsonCreate((Dictionary <string, object>)j.Value, jw);
                                }

                                if (baseType == typeof(KeyValuePair <,>))
                                {
                                    //jw.WriteStartObject();

                                    //Type t1 = j.Value.GetType().GetProperty("Key").PropertyType;
                                    //Type t2 = j.Value.GetType().GetProperty("Value").PropertyType;
                                    Type    t1 = j.Value.GetType().GenericTypeArguments[0];
                                    Type    t2 = j.Value.GetType().GenericTypeArguments[1];
                                    var     kvpPropertyType   = typeof(KeyValuePair <,>);
                                    var     myKvpPropertyType = kvpPropertyType.MakeGenericType(t1, t2);
                                    dynamic v1 = myKvpPropertyType.GetProperty("Key").GetValue(j.Value, null);
                                    dynamic v2 = myKvpPropertyType.GetProperty("Value").GetValue(j.Value, null);

                                    var dict = new Dictionary <string, object>();
                                    dict.Add(v1.ToString(), v2);
                                    JsonCreate(dict, jw);

                                    //jw.WritePropertyName(v1, true);
                                    //jw.WriteValue(v2);
                                    //jw.WriteEndObject();
                                }

                                else if (baseType == typeof(List <>))
                                {
                                    Type t = j.Value.GetType().GenericTypeArguments[0];

                                    //dynamic val3 = props[2].GetValue(j.Value);

                                    if (t == typeof(int) || t == typeof(String))
                                    {
                                        var     listPropertyType   = typeof(List <>);
                                        var     myListPropertyType = listPropertyType.MakeGenericType(t);
                                        var     props = myListPropertyType.GetProperties();
                                        dynamic count = props[1].GetValue(j.Value);

                                        jw.WriteStartArray();
                                        foreach (var val in (j.Value as List <object>))
                                        {
                                            jw.WriteValue(val);
                                        }
                                        jw.WriteEndArray();
                                    }

                                    if (t.Name == "FieldValues")
                                    {
                                        var     listPropertyType   = typeof(List <>);
                                        var     myListPropertyType = listPropertyType.MakeGenericType(t);
                                        var     props = myListPropertyType.GetProperties();
                                        dynamic count = props[1].GetValue(j.Value);

                                        jw.WriteStartArray();
                                        foreach (var fieldvalue in (j.Value as List <TuleapClasses.FieldValues>))
                                        {
                                            jw.WriteValue(fieldvalue.id.ToString());
                                        }
                                        jw.WriteEndArray();
                                    }
                                    else
                                    {
                                        var     listPropertyType   = typeof(List <>);
                                        var     myListPropertyType = listPropertyType.MakeGenericType(t);
                                        var     props = myListPropertyType.GetProperties();
                                        dynamic count = props[1].GetValue(j.Value);

                                        jw.WriteStartArray();
                                        foreach (var dict in (j.Value as List <object>))
                                        {
                                            JsonCreate((Dictionary <string, object>)dict, jw);
                                        }
                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        jw.WriteValue(j.Value);
                    }
                }
                jw.WriteEndObject();
            }
            //return sb.ToString();
        }
Beispiel #25
0
        public static void DumpConf(ConfBase conf, Record record)
        {
            // Logger.Debug($"{conf.confName}, {record}");
            var confPath = Path.Combine(Env.BaseConfPath, $"{conf.confName}.json");

            using (var writer = new JsonTextWriter(new StreamWriter(confPath))
            {
                Indentation = 2,
                Formatting = Formatting.Indented
            })
            {
                writer.WriteStartArray();

                foreach (var item in conf.allConfBase)
                {
                    if (item == null)
                    {
                        // TODO: Find out why item could be null
                        continue;
                    }

                    // Narrowing to subtype
                    var it = Il2CppHelper.Il2CppObjectPtrToIl2CppObjectByType(item.Pointer, record.ItemType);

                    writer.WriteStartObject();

                    // `id` is a special case FieldsInfo missed
                    writer.WritePropertyName("id");
                    writer.WriteValue(item.id);
                    foreach (var p in record.FieldsInfo)
                    {
                        var field = p.Item1;

                        writer.WritePropertyName(field.Name);

                        var v = field.GetValue(it);
                        // FIXME: It's a temporarily way and should be fixed later
                        if (field.PropertyType == typeof(Il2CppStructArray <int>))
                        {
                            writer.WriteStartArray();
                            foreach (var n in (Il2CppStructArray <int>)v)
                            {
                                writer.WriteValue(n);
                            }
                            writer.WriteEndArray();
                        }
                        else if (field.PropertyType == typeof(Il2CppStringArray))
                        {
                            writer.WriteStartArray();
                            foreach (var str in (Il2CppStringArray)v)
                            {
                                writer.WriteValue(str);
                            }
                            writer.WriteEndArray();
                        }
                        else if (field.PropertyType == typeof(Il2CppReferenceArray <Il2CppStructArray <float> >))
                        {
                            writer.WriteStartArray();
                            foreach (var a in (Il2CppReferenceArray <Il2CppStructArray <float> >)v)
                            {
                                writer.WriteStartArray();
                                foreach (var f in a)
                                {
                                    writer.WriteValue(f);
                                }
                                writer.WriteEndArray();
                            }
                            writer.WriteEndArray();
                        }
                        else if (field.PropertyType == typeof(Il2CppReferenceArray <Il2CppStructArray <int> >))
                        {
                            writer.WriteStartArray();
                            foreach (var ia in (Il2CppReferenceArray <Il2CppStructArray <int> >)v)
                            {
                                writer.WriteStartArray();
                                foreach (var i in ia)
                                {
                                    writer.WriteValue(i);
                                }
                                writer.WriteEndArray();
                            }
                            writer.WriteEndArray();
                        }
                        else if (field.PropertyType == typeof(Il2CppReferenceArray <Il2CppStringArray>))
                        {
                            writer.WriteStartArray();
                            foreach (var sa in (Il2CppReferenceArray <Il2CppStringArray>)v)
                            {
                                writer.WriteStartArray();
                                foreach (var s in sa)
                                {
                                    writer.WriteValue(s);
                                }
                                writer.WriteEndArray();
                            }
                            writer.WriteEndArray();
                        }
                        else
                        {
                            writer.WriteValue(v);
                        }
                    }

                    writer.WriteEndObject();
                }

                writer.WriteEndArray();
            }
        }
Beispiel #26
0
        IEnumerable <Task> ExportData(SaveFileDialog saveFile, bool indexesOnly)
        {
            Output("Exporting to {0}", saveFile.SafeFileName);
            Output("- Indexes only, documents will be excluded");

            var stream             = saveFile.OpenFile();
            var jsonRequestFactory = new HttpJsonRequestFactory();
            var baseUrl            = Server.CurrentDatabaseAddress;
            var credentials        = new NetworkCredential();
            var convention         = new DocumentConvention();

            var streamWriter = new StreamWriter(new GZipStream(stream, CompressionMode.Compress));
            var jsonWriter   = new JsonTextWriter(streamWriter)
            {
                Formatting = Formatting.Indented
            };

            Output("Begin reading indexes");

            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("Indexes");
            jsonWriter.WriteStartArray();

            int       totalCount = 0;
            const int batchSize  = 128;
            var       completed  = false;

            while (!completed)
            {
                var url      = (baseUrl + "/indexes/?start=" + totalCount + "&pageSize=" + batchSize).NoCache();
                var request  = jsonRequestFactory.CreateHttpJsonRequest(this, url, "GET", credentials, convention);
                var response = request.ReadResponseStringAsync();
                yield return(response);

                var documents = response.Result;
                var array     = JArray.Parse(documents);
                if (array.Count == 0)
                {
                    Output("Done with reading indexes, total: {0}", totalCount);
                    completed = true;
                }
                else
                {
                    totalCount += array.Count;
                    Output("Reading batch of {0,3} indexes, read so far: {1,10:#,#}", array.Count, totalCount);
                    foreach (JToken item in array)
                    {
                        item.WriteTo(jsonWriter);
                    }
                }
            }

            jsonWriter.WriteEndArray();
            jsonWriter.WritePropertyName("Docs");
            jsonWriter.WriteStartArray();

            if (indexesOnly)
            {
                Output("Skipping documents");
            }
            else
            {
                Output("Begin reading documents");

                var lastEtag = Guid.Empty;
                totalCount = 0;
                completed  = false;
                while (!completed)
                {
                    var url      = (baseUrl + "/docs/?pageSize=" + batchSize + "&etag=" + lastEtag).NoCache();
                    var request  = jsonRequestFactory.CreateHttpJsonRequest(this, url, "GET", credentials, convention);
                    var response = request.ReadResponseStringAsync();
                    yield return(response);

                    var array = JArray.Parse(response.Result);
                    if (array.Count == 0)
                    {
                        Output("Done with reading documents, total: {0}", totalCount);
                        completed = true;
                    }
                    else
                    {
                        totalCount += array.Count;
                        Output("Reading batch of {0,3} documents, read so far: {1,10:#,#}", array.Count,
                               totalCount);
                        foreach (JToken item in array)
                        {
                            item.WriteTo(jsonWriter);
                        }
                        lastEtag = new Guid(array.Last.Value <JObject>("@metadata").Value <string>("@etag"));
                    }
                }
            }

            Execute.OnUIThread(() =>
            {
                jsonWriter.WriteEndArray();
                jsonWriter.WriteEndObject();
                streamWriter.Flush();
                streamWriter.Dispose();
                stream.Dispose();
            });
            Output("Export complete");
        }
Beispiel #27
0
        protected override void WriteContent(JsonTextWriter writer, Transaction tx)
        {
            WritePropertyValue(writer, "txid", tx.GetHash().ToString());
            WritePropertyValue(writer, "version", tx.Version);
            WritePropertyValue(writer, "locktime", tx.LockTime.Value);

            writer.WritePropertyName("vin");
            writer.WriteStartArray();
            foreach (var txin in tx.Inputs)
            {
                writer.WriteStartObject();

                if (txin.PrevOut.Hash == uint256.Zero)
                {
                    WritePropertyValue(writer, "coinbase", Encoders.Hex.EncodeData(txin.ScriptSig.ToBytes()));
                }
                else
                {
                    WritePropertyValue(writer, "txid", txin.PrevOut.Hash.ToString());
                    WritePropertyValue(writer, "vout", txin.PrevOut.N);
                    writer.WritePropertyName("scriptSig");
                    writer.WriteStartObject();

                    WritePropertyValue(writer, "asm", txin.ScriptSig.ToString());
                    WritePropertyValue(writer, "hex", Encoders.Hex.EncodeData(txin.ScriptSig.ToBytes()));

                    writer.WriteEndObject();
                }
                WritePropertyValue(writer, "sequence", (uint)txin.Sequence);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            writer.WritePropertyName("vout");
            writer.WriteStartArray();

            int i = 0;

            foreach (var txout in tx.Outputs)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("value");
                writer.WriteRawValue(ValueFromAmount(txout.Value));
                WritePropertyValue(writer, "n", i);

                writer.WritePropertyName("scriptPubKey");
                writer.WriteStartObject();

                WritePropertyValue(writer, "asm", txout.ScriptPubKey.ToString());
                WritePropertyValue(writer, "hex", Encoders.Hex.EncodeData(txout.ScriptPubKey.ToBytes()));

                var destinations = new List <TxDestination>()
                {
                    txout.ScriptPubKey.GetDestination()
                };
                if (destinations[0] == null)
                {
                    destinations = txout.ScriptPubKey.GetDestinationPublicKeys()
                                   .Select(p => p.Hash)
                                   .ToList <TxDestination>();
                }
                if (destinations.Count == 1)
                {
                    WritePropertyValue(writer, "reqSigs", 1);
                    WritePropertyValue(writer, "type", GetScriptType(txout.ScriptPubKey.FindTemplate()));
                    writer.WritePropertyName("addresses");
                    writer.WriteStartArray();
                    writer.WriteValue(destinations[0].GetAddress(Network).ToString());
                    writer.WriteEndArray();
                }
                else
                {
                    var multi = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(txout.ScriptPubKey);
                    WritePropertyValue(writer, "reqSigs", multi.SignatureCount);
                    WritePropertyValue(writer, "type", GetScriptType(txout.ScriptPubKey.FindTemplate()));
                    writer.WritePropertyName("addresses");
                    writer.WriteStartArray();
                    foreach (var key in multi.PubKeys)
                    {
                        writer.WriteValue(key.Hash.GetAddress(Network).ToString());
                    }
                    writer.WriteEndArray();
                }

                writer.WriteEndObject();                 //endscript
                writer.WriteEndObject();                 //in out
                i++;
            }
            writer.WriteEndArray();
        }
Beispiel #28
0
 public override void WriteEndArray()
 {
     _textWriter.WriteEndArray();
     _innerWriter.WriteEndArray();
     base.WriteEndArray();
 }
Beispiel #29
0
        /// <summary>
        /// On the click of the Save Button we translate the data grid view into a JSON file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.DataGridView grid = uxEventList; //The grid we need to save
            string path = "";                                     //Holds the path to the file we will edit.

            //We need to find the correct Data grid to save and the correct paths to the file
            switch (uxTabs.SelectedIndex)
            {
            case 0:     // Events
                grid = uxEventList;
                path = "../application/src/Components/Calendar/EventList.json";
                break;

            case 1:     // Situations
                grid = uxSituationsList;
                path = "../application/src/Components/Calendar/Situations.json";
                break;

            case 2:     // Echos
                grid = uxEchosList;
                path = "../application/src/Components/Echo/echo.json";
                break;

            case 3:     // Email
                grid = uxEmailList;
                path = "../application/src/Components/Email/EmailList.json";
                break;

            case 4:     // Quiz Questions
                grid = uxQuizList;
                path = "../application/src/Components/Calendar/VideoGame/TypeType/codingChallenges.json";
                break;
            }



            //The string builder and String Writer are used by the JsonWriter
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented; //Formatting for the JSON File

                //All normal JSON files are stored in an array
                if (grid == uxEchosList || grid == uxEmailList || grid == uxQuizList)
                {
                    writer.WriteStartArray();
                }
                else
                {
                    //JSON files that are represented as elements of an array start with the index as the first object
                    writer.WriteStartObject();
                }

                //Go through each row in the grid
                for (int rowCount = 0; rowCount < grid.Rows.Count - 1; rowCount++)
                {
                    DataGridViewRow row = grid.Rows[rowCount];

                    if (row.Cells.Count > 0)
                    {
                        //Check to see if the grid we are looking at needs to get the array index or is a normal JSON file
                        if ((grid == uxEventList || grid == uxSituationsList))
                        {
                            //If the first cell in the array is null set it to the default value.
                            if (row.Cells[1].Value == null || row.Cells[1].Value.ToString().Length <= 0)
                            {
                                row.Cells[1].Value = row.Cells[1].OwningColumn.DefaultCellStyle.NullValue;
                            }

                            //The arry id is hidden and updates itself to the ID of the row.
                            row.Cells[0].Value = row.Cells[1].Value;


                            //Writes the JSON variable name to the file
                            writer.WritePropertyName(row.Cells[0].Value.ToString());
                        }

                        //Adds a JSON object
                        writer.WriteStartObject();

                        //Goes through each cell in the grid (even the hidden ones)
                        foreach (DataGridViewCell cell in row.Cells)
                        {
                            //If this is not a JSON file that uses array Index we add the files to the JSON object
                            if (!((grid == uxEventList || grid == uxSituationsList) && cell.ColumnIndex == 0))
                            {
                                //If the cell value is null or empty change it to the default value.
                                if (cell.Value == null || cell.Value.ToString().Length <= 0)
                                {
                                    cell.Value = cell.OwningColumn.DefaultCellStyle.NullValue;
                                }

                                //Writes the JSON variable and its data to the writer object.
                                writer.WritePropertyName(grid.Columns[cell.ColumnIndex].HeaderText);
                                writer.WriteValue(cell.Value);
                            }
                        }

                        //Finish the creation of the JSON object
                        writer.WriteEndObject();
                    }
                }

                //The array for the JSON has been completed
                if (grid == uxEchosList || grid == uxEmailList)
                {
                    writer.WriteEndArray();
                }

                //Close JSON writer
                writer.Close();
            }

            //Close Stream Writer
            sw.Close();

            //Save the file using the sb that holds the JSON data we created and save it to the file path
            SaveFile(sb, path);
        }
Beispiel #30
0
        public void WriteShapesets(Dictionary <string, ShapeSet> shapeSets)
        {
            Dictionary <Guid, ShapeSet> definedParts = new Dictionary <Guid, ShapeSet>();

            // Check for overwrites and overwrite violations
            foreach (ShapeSet s in shapeSets.Values)
            {
                foreach (Part p in s.Parts.Values)
                {
                    if (definedParts.ContainsKey(p.ItemUuid))
                    {
                        ShapeSet overwrites = definedParts[p.ItemUuid];
                        if (s.Overwrites.Contains(overwrites.Name))
                        {
                            overwrites.Parts[p.ItemUuid] = p;
                            s.Parts.Remove(p.ItemUuid);
                        }
                        else
                        {
                            throw new Exception("Part from ShapeSet " + s.Name + " overwrites part from " + overwrites.Name + " without specifying an 'overwrites' declaration for it.");
                        }
                    }
                }
            }

            using (StreamWriter wr = new StreamWriter(Path.Combine(this.GameDir, "Data", "Objects", "Database", "shapesets.json")))
            {
                using (JsonWriter writer = new JsonTextWriter(wr))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartObject();
                    writer.WritePropertyName("shapeSetList");
                    writer.WriteStartArray();
                    foreach (ShapeSet s in shapeSets.Values)
                    {
                        writer.WriteValue(s.Name);
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
            }

            foreach (ShapeSet s in shapeSets.Values)
            {
                using (StreamWriter wr = new StreamWriter(Path.Combine(this.GameDir, "Data", "Objects", "Database", "ShapeSets", s.Name)))
                {
                    using (JsonWriter writer = new JsonTextWriter(wr))
                    {
                        writer.Formatting = Formatting.Indented;
                        writer.WriteStartObject();
                        writer.WritePropertyName("itemlist");
                        writer.WriteStartArray();
                        foreach (Part p in s.Parts.Values)
                        {
                            p.WriteToJson(writer);
                        }
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }
                }
            }
        }
Beispiel #31
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 (_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(new FullTripleComparer(new FastNodeComparer()));

            // 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.AbsoluteUri);
                    }
                    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();
        }
Beispiel #32
0
        public void Save(ConfigSaveDelegate save)
        {
            using (StreamWriter streamWriter = new StreamWriter (ConfigFilePath, false, System.Text.Encoding.UTF8))
            using (JsonTextWriter writer = new JsonTextWriter (streamWriter)) {
                writer.WriteStartObject ();

                writer.WriteKey ("accounts");
                writer.WriteStartArray ();
                for (int i = 0; i < _accounts.Length; i ++)
                    WriteAccount (writer, _accounts[i]);
                writer.WriteEndArray ();

                writer.WriteKey ("searches");
                writer.WriteStartArray ();
                for (int i = 0; i < _searches.Length; i ++)
                    WriteSearch (writer, _searches[i]);
                writer.WriteEndArray ();

                writer.WriteKey ("lists");
                writer.WriteStartArray ();
                for (int i = 0; i < _lists.Length; i++)
                    WriteList (writer, _lists[i]);
                writer.WriteEndArray ();

                save (writer);
                writer.WriteEndObject ();
            }
        }
Beispiel #33
0
        private void StreamToClient(Stream stream, string startsWith, int start, int pageSize, Etag etag, string matches, int nextPageStart, string skipAfter,
                                    Lazy <NameValueCollection> headers, IPrincipal user)
        {
            var old     = CurrentOperationContext.Headers.Value;
            var oldUser = CurrentOperationContext.User.Value;

            try
            {
                CurrentOperationContext.Headers.Value = headers;
                CurrentOperationContext.User.Value    = user;


                var bufferStream = new BufferedStream(stream, 1024 * 64);
                using (var cts = new CancellationTokenSource())
                    using (var timeout = cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
                        using (var writer = new JsonTextWriter(new StreamWriter(bufferStream)))
                        {
                            writer.WriteStartObject();
                            writer.WritePropertyName("Results");
                            writer.WriteStartArray();

                            Action <JsonDocument> addDocument = doc =>
                            {
                                timeout.Delay();
                                doc.ToJson().WriteTo(writer);
                                writer.WriteRaw(Environment.NewLine);
                            };

                            Database.TransactionalStorage.Batch(accessor =>
                            {
                                // we may be sending a LOT of documents to the user, and most
                                // of them aren't going to be relevant for other ops, so we are going to skip
                                // the cache for that, to avoid filling it up very quickly
                                using (DocumentCacher.SkipSetAndGetDocumentsInDocumentCache())
                                {
                                    if (string.IsNullOrEmpty(startsWith))
                                    {
                                        Database.Documents.GetDocuments(start, pageSize, etag, cts.Token, addDocument);
                                    }
                                    else
                                    {
                                        var nextPageStartInternal = nextPageStart;

                                        Database.Documents.GetDocumentsWithIdStartingWith(startsWith, matches, null, start, pageSize, cts.Token, ref nextPageStartInternal, addDocument, skipAfter: skipAfter);

                                        nextPageStart = nextPageStartInternal;
                                    }
                                }
                            });

                            writer.WriteEndArray();
                            writer.WritePropertyName("NextPageStart");
                            writer.WriteValue(nextPageStart);
                            writer.WriteEndObject();
                            writer.Flush();
                            bufferStream.Flush();
                        }
            }
            finally
            {
                CurrentOperationContext.Headers.Value = old;
                CurrentOperationContext.User.Value    = oldUser;
            }
        }
        public static string ToJson(this Person p)
        {
            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);

            // {
            writer.WriteStartObject();

            // "name" : "Jerry"
            writer.WritePropertyName("name");
            writer.WriteValue(p.Name);

            // "likes": ["Comedy", "Superman"]
            writer.WritePropertyName("likes");
            writer.WriteStartArray();
            foreach (string like in p.Likes)
            {
                writer.WriteValue(like);
            }
            writer.WriteEndArray();

            // }
            writer.WriteEndObject();

            return sw.ToString();
        }
Beispiel #35
0
 void SaveConfigInternal(JsonTextWriter writer, TimelineBase timelines)
 {
     foreach (object item in timelines.TimeLines) {
         writer.WriteStartObject ();
         writer.WriteKey ("type");
         TimelineInfo tl = item as TimelineInfo;
         TabInfo tb = item as TabInfo;
         if (tl != null) {
             if (tl.Search != null) {
                 writer.WriteString ("search");
                 writer.WriteKey ("keywords");
                 writer.WriteString (tl.Search.Keyword);
             } else if (tl.List != null) {
                 writer.WriteString ("list");
                 writer.WriteKey ("id");
                 writer.WriteNumber (tl.List.List.ID);
             } else {
                 writer.WriteString ("account");
                 writer.WriteKey ("subtype");
                 if (tl.Statuses == tl.RestAccount.HomeTimeline)
                     writer.WriteString ("home");
                 else if (tl.Statuses == tl.RestAccount.Mentions)
                     writer.WriteString ("mentions");
                 else if (tl.Statuses == tl.RestAccount.DirectMessages)
                     writer.WriteString ("directmessages");
                 writer.WriteKey ("name");
                 writer.WriteString (tl.RestAccount.ScreenName);
             }
         } else if (tb != null) {
             writer.WriteString ("tab");
             writer.WriteKey ("title");
             writer.WriteString (tb.Title);
             writer.WriteKey ("windows");
             writer.WriteStartArray ();
             SaveConfigInternal (writer, tb);
             writer.WriteEndArray ();
         } else {
             writer.WriteNull ();
         }
         writer.WriteEndObject ();
     }
 }
Beispiel #36
0
        public static void SerializeMessage(JsonTextWriter writer, ServiceType type, object message)
        {
            Require.NotNull(writer, "writer");
            Require.NotNull(type, "type");
            Require.NotNull(message, "message");

            writer.WriteStartObject();

            foreach (var field in type.Fields.Values)
            {
                if (
                    field.ShouldSerializeMethod != null &&
                    !field.ShouldSerializeMethod(message)
                )
                    continue;

                writer.WritePropertyName(field.Tag.ToString(CultureInfo.InvariantCulture));

                object value = field.Getter(message);

                if (value == null)
                {
                    writer.WriteNull();
                }
                else if (field.CollectionType != null)
                {
                    writer.WriteStartArray();

                    foreach (object item in (IEnumerable)value)
                    {
                        if (field.ServiceType != null && !field.ServiceType.Type.IsEnum)
                            SerializeMessage(writer, field.ServiceType, item);
                        else
                            writer.WriteValue(item);
                    }

                    writer.WriteEndArray();
                }
                else 
                {
                    if (field.ServiceType != null && !field.ServiceType.Type.IsEnum)
                        SerializeMessage(writer, field.ServiceType, value);
                    else
                        writer.WriteValue(value);
                }
            }

            writer.WriteEndObject();
        }
Beispiel #37
0
 public void Dispose()
 {
     _jsonTextWriter?.WriteEndArray();
     _jsonTextWriter?.Flush();
     _jsonTextWriter?.Close();
 }
Beispiel #38
-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;
     });
 }