コード例 #1
0
        public void SendJoinToGame(string token)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("game_token");
            writer.WriteValue(token);
            writer.WritePropertyName("user_name");
            writer.WriteValue(context.gameCtrl.UserName);
            writer.WriteEndObject();
            SendJsonData("POST", "/join_game", null, writer.Token.ToString());
        }
コード例 #2
0
        public static JObject GetAccTransByAccId(string accId, string fromDate = null, string toDate = null)
        {
            List <AccountSummary>     accSummary = new List <AccountSummary>();
            ReportsAccountingEntities db         = new ReportsAccountingEntities();
            var spResult = db.GetAccountDetailsByAccId(accId, fromDate == "" ? null : fromDate, toDate == "" ? null : toDate).ToList();

            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();
            foreach (var item in spResult)
            {
                pJTokenWriter.WriteStartObject();
                pJTokenWriter.WritePropertyName("AccountId");
                pJTokenWriter.WriteValue(item.AccountId);

                pJTokenWriter.WritePropertyName("CreateDate");
                pJTokenWriter.WriteValue(item.CreateDate.ToString("dd/MM/yyyy"));

                pJTokenWriter.WritePropertyName("CreateBy");
                pJTokenWriter.WriteValue(item.UserName);

                pJTokenWriter.WritePropertyName("DebitAmount");
                pJTokenWriter.WriteValue(item.DebitAmount);

                pJTokenWriter.WritePropertyName("CreditAmount");
                pJTokenWriter.WriteValue(item.CreditAmount);

                pJTokenWriter.WritePropertyName("CurrencySign");
                pJTokenWriter.WriteValue(item.CurrencySign);

                pJTokenWriter.WritePropertyName("TransactionName");
                pJTokenWriter.WriteValue(item.TransactionName);

                pJTokenWriter.WritePropertyName("TransactionNameAr");
                pJTokenWriter.WriteValue(item.TransactionNameAr);

                pJTokenWriter.WritePropertyName("ReceiptNotes");
                //pJTokenWriter.WriteValue(item.ReceiptNotes);
                pJTokenWriter.WriteValue("");

                pJTokenWriter.WriteEndObject();
            }

            pJTokenWriter.WriteEndArray();
            pJTokenWriter.WriteEndObject();
            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #3
0
        internal static JObject GetCarrierRates(System.Web.Mvc.FormCollection form)
        {
            List <CarrierRateVm> carrRateList = CarrierRateHelper.GetCarrierRatesInquiry(form);

            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();

            foreach (var item in carrRateList)
            {
                pJTokenWriter.WriteStartObject();

                pJTokenWriter.WritePropertyName("CarrierRateId");
                pJTokenWriter.WriteValue(item.CarrierRateId);

                pJTokenWriter.WritePropertyName("CarrierName");
                pJTokenWriter.WriteValue(item.CarrierName);

                pJTokenWriter.WritePropertyName("ContainerTypeName");
                pJTokenWriter.WriteValue(item.ContainerTypeName);

                pJTokenWriter.WritePropertyName("FromPort");
                pJTokenWriter.WriteValue(item.FromCountryName + " / " + item.FromPortName);

                pJTokenWriter.WritePropertyName("ToPort");
                pJTokenWriter.WriteValue(item.ToCountryName + " / " + item.ToPortName);

                pJTokenWriter.WritePropertyName("FreightCost");
                pJTokenWriter.WriteValue(item.FreightCostAmount + "  " + item.FreighCurrencySign);

                pJTokenWriter.WritePropertyName("ThcCost");
                pJTokenWriter.WriteValue(item.ThcCostAmount + "  " + item.ThcCurrencySign);

                pJTokenWriter.WritePropertyName("ValidToDate");
                pJTokenWriter.WriteValue(item.ValidToDate == null ? "" : item.ValidToDate.Value.ToString("dd/MM/yyyy"));

                pJTokenWriter.WritePropertyName("CarrierId");
                pJTokenWriter.WriteValue(item.CarrierId);

                pJTokenWriter.WriteEndObject();
            }

            pJTokenWriter.WriteEndArray();
            pJTokenWriter.WriteEndObject();
            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #4
0
        private JToken GetConnectionItem(string connectionString, string providerName)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("ConnectionStrings");
            writer.WriteStartObject();
            writer.WritePropertyName(Cms.Core.Constants.System.UmbracoConnectionName);
            writer.WriteValue(connectionString);
            writer.WriteEndObject();
            writer.WriteEndObject();

            return(writer.Token);
        }
コード例 #5
0
ファイル: XMLHelpers.cs プロジェクト: mdobler/insight2019
        public static JObject StoredProcXMLToJObject(string xml)
        {
            XDocument xmlContent;

            try
            {
                xmlContent = XDocument.Load(new System.IO.StringReader(xml));
            }
            catch (Exception)
            {
                return(new JObject());
            }

            if (xmlContent.ElementExists("NewDataSet"))
            {
                JTokenWriter jWriter = new JTokenWriter();
                jWriter.WriteStartObject();
                int    i         = 0;
                string tableName = "Table";
                while (xmlContent.Element("NewDataSet").ElementExists(tableName))
                {
                    //write a property for each table
                    jWriter.WritePropertyName(tableName);
                    //write an array for each collection of table entities
                    jWriter.WriteStartArray();

                    foreach (XElement item in xmlContent.Element("NewDataSet").Elements(tableName))
                    {
                        jWriter.WriteStartObject();
                        foreach (XElement prop in item.Elements())
                        {
                            jWriter.WritePropertyName(prop.Name.LocalName);
                            jWriter.WriteValue(prop.Value);
                        }
                        jWriter.WriteEndObject();
                    }
                    jWriter.WriteEndArray();

                    i++;
                    tableName = $"Table{i}";
                }

                jWriter.WriteEndObject();

                return((JObject)jWriter.Token);
            }

            return(new JObject());
        }
コード例 #6
0
        public void Coercion_Coerce_JToken()
        {
            ICoercion coercion = new Coercion();
            var       writer   = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue("request");
            writer.WritePropertyName("command");
            writer.WriteValue("launch");
            writer.WriteEndObject();

            var result = coercion.Coerce(writer.Token, typeof(JToken));

            Assert.Equal(writer.Token, result);
        }
コード例 #7
0
        private List <byte> CreateBrowserStateJsonString(string bookmarkUrl, [Optional] string oldBrowserState)
        {
            JObject browserState   = new JObject();
            JArray  bookmarksArray = new JArray();

            if (!string.IsNullOrEmpty(oldBrowserState))
            {
                browserState   = JObject.Parse(oldBrowserState);
                bookmarksArray = (JArray)browserState["bookmarks"];
                browserState.Remove("bookmarks");
            }

            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("url");
            writer.WriteValue(bookmarkUrl);
            writer.WriteEndObject();

            JObject newBookmarksJObject = (JObject)writer.Token;

            bookmarksArray.Add(newBookmarksJObject);
            browserState.Add("bookmarks", bookmarksArray);
            var newbrowserState = JsonConvert.SerializeObject(browserState);

            return(newbrowserState.ToUtfBytes());
        }
コード例 #8
0
        private List <dynamic> Execute(ConfigurationEntry config, string sql)
        {
            using (var ds = _dataRetriever.RetrieveData(_dataCreator, config.ConnectionString, config.DatabaseType, sql, config.CommandTimeout))
            {
                if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                {
                    return(new List <dynamic>());
                }

                var rows = new List <dynamic>();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var writer = new JTokenWriter();
                    writer.WriteStartObject();

                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        writer.WritePropertyName(col.ColumnName);
                        writer.WriteValue(row[col.ColumnName]);
                    }

                    writer.WriteEndObject();

                    rows.Add(writer.Token);
                }

                return(rows);
            }
        }
コード例 #9
0
        private static JToken WriteToJToken(List <Dictionary <string, dynamic> > data, CultureInfo culture)
        {
            using (var writer = new JTokenWriter())
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                writer.Culture    = culture;

                writer.WriteStartArray(); // root start

                foreach (var row in data)
                {
                    writer.WriteStartObject(); // start row object
                    foreach (var key in row.Keys)
                    {
                        writer.WritePropertyName(key);
                        // null check
                        if (row[key] != null)
                        {
                            writer.WriteValue(row[key]);
                        }
                        else //write empty string value for null fields
                        {
                            writer.WriteValue("");
                        }
                    }

                    writer.WriteEndObject(); // end row
                }

                writer.WriteEndArray(); // root array end

                return(writer.Token);
            }
        }
コード例 #10
0
        private JToken?GetConnectionItem(string connectionString, string?providerName)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("ConnectionStrings");
            writer.WriteStartObject();
            writer.WritePropertyName(Constants.System.UmbracoConnectionName);
            writer.WriteValue(connectionString);
            writer.WritePropertyName($"{Constants.System.UmbracoConnectionName}{ConnectionStrings.ProviderNamePostfix}");
            writer.WriteValue(providerName);
            writer.WriteEndObject();
            writer.WriteEndObject();

            return(writer.Token);
        }
コード例 #11
0
        public async Task <List <ContasReceber> > GetContasReceberResultSet(NpgsqlCommand command)
        {
            List <ContasReceber> list = new List <ContasReceber>();

            command.ExecuteNonQuery();

            using var reader = await command.ExecuteReaderAsync();

            while (await reader.ReadAsync())
            {
                DataTable schemaTable = reader.GetSchemaTable();

                JTokenWriter writer = new JTokenWriter();
                writer.WriteStartObject();

                foreach (DataRow row in schemaTable.Rows)
                {
                    writer.WritePropertyName(row[0].ToString());
                    writer.WriteValue(reader[row[0].ToString()]);
                }
                writer.WriteEndObject();
                JObject       o          = (JObject)writer.Token;
                var           stringJson = o.ToString();
                ContasReceber p          = JsonConvert.DeserializeObject <ContasReceber>(stringJson);
                list.Add(p);
            }
            return(list);
        }
コード例 #12
0
        public static string ToJson(this OracleDataReader reader, string cultureInfo)
        {
            var culture = String.IsNullOrWhiteSpace(cultureInfo) ? CultureInfo.InvariantCulture : new CultureInfo(cultureInfo);

            // create json result
            using (var writer = new JTokenWriter())
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                writer.Culture    = culture;

                // start array
                writer.WriteStartArray();

                while (reader.Read())
                {
                    // start row object
                    writer.WriteStartObject();
                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        // add row element name
                        writer.WritePropertyName(reader.GetName(i));
                        // add row element value
                        writer.WriteValue(reader.GetValue(i) ?? string.Empty);
                    }
                    writer.WriteEndObject(); // end row object
                }
                // end array
                writer.WriteEndArray();

                return(writer.Token.ToString());
            }
        }
コード例 #13
0
        /// <summary>
        /// Use this to get json format for Pie chat used in charts.js
        /// </summary>
        /// <param name="chartData">Dictionary string "For Label Name", int "For Label count"</param>
        /// <returns>Json</returns>
        public static JObject GetPieChartData(Dictionary <string, int> chartData)
        {
            if (chartData == null || chartData.Count == 0)
            {
                return(null);
            }

            Random       randomGen     = new Random();
            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("labels");
            pJTokenWriter.WriteStartArray();
            foreach (var item in chartData)
            {
                pJTokenWriter.WriteValue(item.Key);
            }
            pJTokenWriter.WriteEndArray();

            pJTokenWriter.WritePropertyName("datasets");
            pJTokenWriter.WriteStartArray();  //datasets array
            pJTokenWriter.WriteStartObject(); //datasets Object
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();  //data array
            foreach (var item in chartData)
            {
                pJTokenWriter.WriteValue(item.Value);
            }
            pJTokenWriter.WriteEndArray();//data array

            pJTokenWriter.WritePropertyName("backgroundColor");
            pJTokenWriter.WriteStartArray(); //backgroundColor array
            foreach (var item in chartData)
            {
                pJTokenWriter.WriteValue("rgb(" + randomGen.Next(256) + "," + randomGen.Next(256) + "," + randomGen.Next(256) + ")");
            }
            pJTokenWriter.WriteEndArray();  //backgroundColor array

            pJTokenWriter.WriteEndObject(); //datasets Object
            pJTokenWriter.WriteEndArray();  //datasets array

            pJTokenWriter.WriteEndObject();

            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #14
0
        public static JToken GetFileInfoFromResponseXml(string applicationResponseXml)
        {
            string resp = applicationResponseXml;

            // Select only the nodes that may be of interest
            using (var writer = new JTokenWriter())
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                writer.Culture    = CultureInfo.InvariantCulture;

                writer.WriteStartObject();
                writer.WritePropertyName("CustomerId");
                writer.WriteValue(FindElement(resp, "CustomerId")?.Value);
                writer.WritePropertyName("Timestamp");
                writer.WriteValue(FindElement(resp, "Timestamp")?.Value);
                writer.WritePropertyName("ResponseCode");
                writer.WriteValue(FindElement(resp, "ResponseCode")?.Value);
                writer.WritePropertyName("Encrypted");
                writer.WriteValue(FindElement(resp, "Encrypted")?.Value);
                writer.WritePropertyName("Compressed");
                writer.WriteValue(FindElement(resp, "Compressed")?.Value);
                writer.WritePropertyName("AmountTotal");
                writer.WriteValue(FindElement(resp, "AmountTotal")?.Value);
                writer.WritePropertyName("TransactionCount");
                writer.WriteValue(FindElement(resp, "TransactionCount")?.Value);
                writer.WriteEndObject();

                return(writer.Token);
            }
        }
コード例 #15
0
        private string AssembleChickenNugetProject(IProjectFile[] packageConfigs, IProjectFile[] nuspecs)
        {
            var writer = new JTokenWriter();

            // main obj
            writer.WriteStartObject();

            // files obj
            writer.WritePropertyName("files");
            writer.WriteStartObject();

            if (packageConfigs.Length > 0)
            {
                // packages-config array
                writer.WritePropertyName("packages-config");
                writer.WriteStartArray();
                foreach (var packageConfig in packageConfigs)
                {
                    writer.WriteValue(packageConfig.FilePath());
                }

                writer.WriteEndArray();
            }

            if (nuspecs.Length > 0)
            {
                // packages-config array
                writer.WritePropertyName("package-nuspec");
                writer.WriteStartArray();
                foreach (var projectFile in nuspecs)
                {
                    writer.WriteValue(projectFile.FilePath());
                }

                writer.WriteEndArray();
            }

            // files obj
            writer.WriteEndObject();

            // main obj
            writer.WriteEndObject();

            return(writer.Token.ToString(Formatting.Indented));
        }
コード例 #16
0
        private object GetGlobalIdItem(string id)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("Umbraco");
            writer.WriteStartObject();
            writer.WritePropertyName("CMS");
            writer.WriteStartObject();
            writer.WritePropertyName("Global");
            writer.WriteStartObject();
            writer.WritePropertyName("Id");
            writer.WriteValue(id);
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();

            return(writer.Token);
        }
コード例 #17
0
        private JToken GetDisableRedirectUrlItem(bool value)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("Umbraco");
            writer.WriteStartObject();
            writer.WritePropertyName("CMS");
            writer.WriteStartObject();
            writer.WritePropertyName("WebRouting");
            writer.WriteStartObject();
            writer.WritePropertyName("DisableRedirectUrlTracking");
            writer.WriteValue(value);
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();

            return(writer.Token);
        }
コード例 #18
0
        public void WriteDuplicatePropertyName()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();

            writer.WritePropertyName("prop1");
            writer.WriteStartObject();
            writer.WriteEndObject();

            writer.WritePropertyName("prop1");
            writer.WriteStartArray();
            writer.WriteEndArray();

            writer.WriteEndObject();

            StringAssert.AreEqual(@"{
  ""prop1"": []
}", writer.Token.ToString());
        }
コード例 #19
0
        private void SetPostedTransaction(HttpClient http, List <string> lstParameter)
        {
            string metodo         = "api/v1/jobs/Transactions/SetPosted";
            int    page           = 1;
            int    totalPages     = (int)Decimal.Ceiling(lstParameter.Count / 100);
            int    posicaoLista   = 0;
            int    registrosLidos = 1;

            do
            {
                JTokenWriter writerJson = new JTokenWriter();

                writerJson.WriteStartObject();
                writerJson.WritePropertyName("Assignments");
                writerJson.WriteStartArray();

                for (int index = posicaoLista; index < lstParameter.Count; index++)
                {
                    writerJson.WriteStartObject();
                    writerJson.WritePropertyName("TransactionId");
                    writerJson.WriteValue(lstParameter[index]);
                    writerJson.WritePropertyName("PostedDate");
                    writerJson.WriteValue(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:sszzz"));
                    writerJson.WriteEndObject();
                    registrosLidos++;
                    if (registrosLidos > 100)
                    {
                        posicaoLista += (registrosLidos - 1);
                        break;
                    }
                }
                writerJson.WriteEndArray();
                writerJson.WriteEndObject();

                JObject json = (JObject)writerJson.Token;
                PostSyncApi(metodo, http, json);
                page++;
            } while (page <= totalPages);
        }
コード例 #20
0
        public void State()
        {
            using (JsonWriter jsonWriter = new JTokenWriter())
            {
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);

                jsonWriter.WriteStartObject();
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WritePropertyName("CPU");
                Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

                jsonWriter.WriteValue("Intel");
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WritePropertyName("Drives");
                Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

                jsonWriter.WriteStartArray();
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

                jsonWriter.WriteValue("DVD read/writer");
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
                jsonWriter.WriteValue(new BigInteger(123));
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif

                jsonWriter.WriteValue(new byte[0]);
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

                jsonWriter.WriteEnd();
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

                jsonWriter.WriteEndObject();
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
            }
        }
コード例 #21
0
ファイル: MtSQLite.cs プロジェクト: imtect/Revit_FloorTag
        public static JToken readerToJson(SQLiteDataReader reader)
        {
            JTokenWriter jwrite = new JTokenWriter();

            jwrite.WriteStartObject();
            for (int i = 0; i < reader.FieldCount; ++i)
            {
                jwrite.WritePropertyName(reader.GetName(i));
                jwrite.WriteValue(reader.GetValue(i));
            }
            jwrite.WriteEndObject();
            return(jwrite.Token);
        }
コード例 #22
0
        public string ToJson()
        {
            var writer = new JTokenWriter();

            writer.WriteStartObject();

            writer.WritePropertyName("result");
            writer.WriteValue(Result);

            if (Result == JsonValues.Authenticated)
            {
                writer.WritePropertyName("jwt");
                writer.WriteValue(Jwt);
            }
            else if (Result == JsonValues.Error)
            {
                writer.WritePropertyName("errordetails");
                writer.WriteValue(ErrorDetails);
            }

            writer.WriteEndObject();
            return(writer.Token.ToString(Formatting.None));
        }
コード例 #23
0
        public void Example()
        {
            #region Usage
            JTokenWriter writer = new JTokenWriter();
            writer.WriteStartObject();
            writer.WritePropertyName("name1");
            writer.WriteValue("value1");
            writer.WritePropertyName("name2");
            writer.WriteStartArray();
            writer.WriteValue(1);
            writer.WriteValue(2);
            writer.WriteEndArray();
            writer.WriteEndObject();

            JObject o = (JObject)writer.Token;

            Console.WriteLine(o.ToString());
            // {
            //   "name1": "value1",
            //   "name2": [
            //     1,
            //     2
            //   ]
            // }
            #endregion

            StringAssert.AreEqual(
                @"{
  ""name1"": ""value1"",
  ""name2"": [
    1,
    2
  ]
}",
                o.ToString()
                );
        }
コード例 #24
0
        public void WriteTokenWithPropertyParent()
        {
            JValue v = new JValue(1);

            JTokenWriter writer = new JTokenWriter();

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

            writer.WriteToken(v.CreateReader());

            Assert.AreEqual(WriteState.Object, writer.WriteState);

            writer.WriteEndObject();

            StringAssert.AreEqual(@"{
  ""Prop1"": 1
}", writer.Token.ToString());
        }
コード例 #25
0
        private static object WriteJToken(IEnumerable <List <object> > data, IReadOnlyList <string> headers)
        {
            using (var writer = new JTokenWriter())
            {
                writer.Formatting = Formatting.Indented;
                writer.Culture    = _culture;
                writer.WriteStartArray();
                foreach (var row in data)
                {
                    writer.WriteStartObject();

                    for (var i = 0; i < headers.Count; i++)
                    {
                        writer.WritePropertyName(headers[i]);
                        writer.WriteValue(row[i]);
                    }
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                return(writer.Token);
            }
        }
コード例 #26
0
        public JToken WriteJson(IRow row, CatalogDefinition catalogDefinition)
        {
            ICell cell          = row.GetCell(0);
            var   tempCellValue = GetValue(cell)?.ToString();

            if (string.IsNullOrEmpty(tempCellValue))
            {
                return(null);
            }

            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            foreach (var rowDefinition in catalogDefinition.Columns)
            {
                cell = row.GetCell(rowDefinition.Index);
                var cellValue = GetValue(cell);
                if (cellValue == null && rowDefinition.Index == 0)
                {
                    break;
                }

                writer.WritePropertyName(rowDefinition.PropertyName);
                if (string.IsNullOrWhiteSpace(rowDefinition.Mask))
                {
                    writer.WriteValue(cellValue ?? string.Empty);
                }
                else
                {
                    writer.WriteValue(string.Format($"{{{rowDefinition.Mask}}}", cellValue));
                }
            }

            writer.WriteEndObject();
            return(writer.Token);
        }
コード例 #27
0
        // This transforms file descriptions from XML format to JSON
        private static void WriteNordeaFileInfo(this JTokenWriter writer, XmlNode node)
        {
            var children = node.ChildNodes.Cast <XmlNode>().ToList();

            writer.WriteStartObject();
            writer.WritePropertyName("FileReference");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:FileReference")?.InnerText);
            writer.WritePropertyName("TargetId");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:TargetId")?.InnerText);
            writer.WritePropertyName("ParentFileReference");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:ParentFileReference")?.InnerText);
            writer.WritePropertyName("FileType");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:FileType")?.InnerText);
            writer.WritePropertyName("FileTimestamp");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:FileTimestamp")?.InnerText);
            writer.WritePropertyName("Status");
            writer.WriteValue(children.FirstOrDefault(n => n.Name == "c2b:Status")?.InnerText);
            writer.WriteEndObject();
        }
コード例 #28
0
ファイル: EmployeeHelper.cs プロジェクト: amorsi/EasyFreight
        public static JObject GetEmpList(System.Web.Mvc.FormCollection form)
        {
            HREntities   db            = new HREntities();
            var          empListDb     = db.Employees.Include("Department").OrderBy(x => x.EmpNameEn).ToList();
            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();

            foreach (var item in empListDb)
            {
                pJTokenWriter.WriteStartObject();

                pJTokenWriter.WritePropertyName("EmpId");
                pJTokenWriter.WriteValue(item.EmpId);

                pJTokenWriter.WritePropertyName("EmpCode");
                pJTokenWriter.WriteValue(item.EmpCode);

                pJTokenWriter.WritePropertyName("EmpNameEn");
                pJTokenWriter.WriteValue(item.EmpNameEn);

                pJTokenWriter.WritePropertyName("EmpNameAr");
                pJTokenWriter.WriteValue(item.EmpNameAr);

                pJTokenWriter.WritePropertyName("DepNameEn");
                pJTokenWriter.WriteValue(item.Department.DepNameEn);

                pJTokenWriter.WriteEndObject();
            }
            pJTokenWriter.WriteEndArray();
            pJTokenWriter.WriteEndObject();
            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #29
0
        public static string ExportJson(string project, string module, List <string> languages, string exportPath,
                                        bool withDefaultValue = true, bool withStructurJson = true)
        {
            var filter = new ResCurrent
            {
                Project = new ResProject {
                    Name = project
                },
                Module = new ResModule {
                    Name = module
                }
            };

            var zipDirectory = Directory.CreateDirectory(exportPath + module);

            foreach (var language in languages)
            {
                filter.Language = new ResCulture {
                    Title = language
                };

                var words =
                    ResourceData.GetListResWords(filter, string.Empty).GroupBy(x => x.ResFile.FileID).ToList();
                if (!words.Any())
                {
                    Console.WriteLine("Error!!! Can't find appropriate project and module. Possibly wrong names!");
                    return(null);
                }

                foreach (var fileWords in words)
                {
                    var wordsDictionary = new Dictionary <string, string>();
                    foreach (
                        var word in
                        fileWords.OrderBy(x => x.Title).Where(word => !wordsDictionary.ContainsKey(word.Title)))
                    {
                        if (string.IsNullOrEmpty(word.ValueTo) && !withDefaultValue)
                        {
                            continue;
                        }

                        wordsDictionary[word.Title] = word.ValueTo ?? word.ValueFrom;
                        if (!string.IsNullOrEmpty(wordsDictionary[word.Title]))
                        {
                            wordsDictionary[word.Title] = wordsDictionary[word.Title].TrimEnd('\n').TrimEnd('\r');
                        }
                    }

                    if (!wordsDictionary.Any())
                    {
                        continue;
                    }

                    var firstWord = fileWords.FirstOrDefault();
                    var fileName  = firstWord == null
                        ? module
                        : Path.GetFileNameWithoutExtension(firstWord.ResFile.FileName);
                    var ext = Path.GetExtension(firstWord.ResFile.FileName);

                    var zipFileName = zipDirectory.FullName + "\\" + fileName +
                                      (language == "Neutral" ? string.Empty : "." + language) + ext;
                    using (TextWriter writer = new StreamWriter(zipFileName))
                    {
                        if (ext == ".json")
                        {
                            if (withStructurJson)
                            {
                                var     collectionNames = new List <string>();
                                var     wrOrder         = 0;
                                JObject jObject         = null;
                                var     writeJtoken     = new JTokenWriter();

                                writeJtoken.WriteStartObject();
                                foreach (var vordsKV in wordsDictionary)
                                {
                                    var strNameSplit = vordsKV.Key.Split('.');

                                    for (var a = 0; a < strNameSplit.Length; a++)
                                    {
                                        while (collectionNames.Count < a + 1)
                                        {
                                            collectionNames.Add("");
                                        }

                                        if (collectionNames[a] != null && collectionNames[a] == strNameSplit[a])
                                        {
                                            continue;
                                        }
                                        if (wrOrder > a)
                                        {
                                            for (var b = a; b < collectionNames.Count; b++)
                                            {
                                                collectionNames[b] = null;
                                            }
                                            while (wrOrder > a)
                                            {
                                                writeJtoken.WriteEndObject();
                                                wrOrder--;
                                            }
                                        }
                                        writeJtoken.WritePropertyName(strNameSplit[a]);
                                        if (a < strNameSplit.Length - 1)
                                        {
                                            writeJtoken.WriteStartObject();
                                            wrOrder++;
                                            collectionNames[a] = strNameSplit[a];
                                        }
                                        else
                                        {
                                            writeJtoken.WriteValue(vordsKV.Value);
                                        }
                                    }
                                }
                                jObject = (JObject)writeJtoken.Token;
                                writer.Write(jObject);
                            }
                            else
                            {
                                var obj = JsonConvert.SerializeObject(wordsDictionary, Formatting.Indented);
                                writer.Write(obj);
                            }
                        }
                        else
                        {
                            var data      = new XmlDocument();
                            var resources = data.CreateElement("resources");

                            foreach (var ind in wordsDictionary)
                            {
                                var stringAttr = data.CreateAttribute("name");
                                stringAttr.Value = ind.Key;

                                var child = data.CreateElement("string");
                                child.Attributes.Append(stringAttr);
                                child.InnerText = ind.Value;

                                resources.AppendChild(child);
                            }

                            data.AppendChild(resources);

                            var settings = new XmlWriterSettings
                            {
                                Indent             = true,
                                IndentChars        = "  ",
                                NewLineChars       = Environment.NewLine,
                                NewLineHandling    = NewLineHandling.Replace,
                                OmitXmlDeclaration = false,
                                ConformanceLevel   = ConformanceLevel.Fragment
                            };

                            using (var xmlTextWriter = XmlWriter.Create(writer, settings))
                            {
                                data.WriteTo(xmlTextWriter);
                                xmlTextWriter.Flush();
                            }
                        }
                    }
                }
            }

            var zipPath = zipDirectory.FullName + ".zip";
            var fastZip = new FastZip();

            fastZip.CreateEmptyDirectories = true;
            fastZip.CreateZip(zipPath, zipDirectory.FullName, true, null);
            zipDirectory.Delete(true);

            return(zipPath);
        }
コード例 #30
0
        internal static JObject GetExpensesCashOutJson(System.Web.Mvc.FormCollection form)
        {
            AccountingEntities db = new AccountingEntities();
            //Get Only cash out receipts for expenses
            var receiptIds = db.CashOutReceiptExpenses.Select(x => x.ReceiptId).Distinct();


            var receiptList = (from c in db.CashOutReceipts
                               join u in db.AspNetUserAccs
                               on c.CreateBy equals u.Id
                               join cu in db.CurrencyAccs
                               on c.CurrencyId equals cu.CurrencyId
                               where receiptIds.Contains(c.ReceiptId) && c.IsDeleted == false
                               select new
            {
                c.ReceiptId,
                c.ReceiptDate,
                c.ReceiptCode,
                c.ReceiptAmount,
                c.Notes,
                c.CreateDate,
                c.CreateBy,
                cu.CurrencySign,
                u.UserName
            }).ToList();

            if (!string.IsNullOrEmpty(form["ReceiptDateStart"]))
            {
                DateTime date = DateTime.Parse(form["ReceiptDateStart"]);
                receiptList = receiptList.Where(x => x.ReceiptDate >= date).ToList();
            }

            if (!string.IsNullOrEmpty(form["ReceiptDateEnd"]))
            {
                DateTime date = DateTime.Parse(form["ReceiptDateEnd"]);
                receiptList = receiptList.Where(x => x.ReceiptDate <= date).ToList();
            }

            if (!string.IsNullOrEmpty(form["CreateDateStart"]))
            {
                DateTime date = DateTime.Parse(form["CreateDateStart"]);
                receiptList = receiptList.Where(x => x.CreateDate >= date).ToList();
            }

            if (!string.IsNullOrEmpty(form["CreateDateEnd"]))
            {
                DateTime date = DateTime.Parse(form["CreateDateEnd"]);
                receiptList = receiptList.Where(x => x.CreateDate <= date).ToList();
            }

            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();

            foreach (var item in receiptList)
            {
                pJTokenWriter.WriteStartObject();

                pJTokenWriter.WritePropertyName("ReceiptId");
                pJTokenWriter.WriteValue(item.ReceiptId);

                pJTokenWriter.WritePropertyName("ReceiptCode");
                pJTokenWriter.WriteValue(item.ReceiptCode);

                pJTokenWriter.WritePropertyName("ReceiptDate");
                pJTokenWriter.WriteValue(item.ReceiptDate.ToString("dd/MM/yyyy"));

                pJTokenWriter.WritePropertyName("ReceiptAmount");
                pJTokenWriter.WriteValue(item.ReceiptAmount.ToString() + " " + item.CurrencySign);

                pJTokenWriter.WritePropertyName("Notes");
                pJTokenWriter.WriteValue(item.Notes);

                pJTokenWriter.WritePropertyName("CreateDate");
                pJTokenWriter.WriteValue(item.CreateDate.ToString("dd/MM/yyyy"));

                pJTokenWriter.WritePropertyName("UserName");
                pJTokenWriter.WriteValue(item.UserName);

                pJTokenWriter.WriteEndObject();
            }

            pJTokenWriter.WriteEndArray();
            pJTokenWriter.WriteEndObject();
            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #31
0
        private JToken CreateJObject(JsonReader reader)
        {
            ValidationUtils.ArgumentNotNull(reader, "reader");

            // this is needed because we've already read inside the object, looking for metadata properties
            using (JTokenWriter writer = new JTokenWriter())
            {
                writer.WriteStartObject();

                do
                {
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        string propertyName = (string)reader.Value;
                        do
                        {
                            if (!reader.Read())
                                break;
                        } while (reader.TokenType == JsonToken.Comment);

                        if (CheckPropertyName(reader, propertyName))
                            continue;

                        writer.WritePropertyName(propertyName);
                        writer.WriteToken(reader, true, true);
                    }
                    else if (reader.TokenType == JsonToken.Comment)
                    {
                        // eat
                    }
                    else
                    {
                        writer.WriteEndObject();
                        return writer.Token;
                    }
                } while (reader.Read());

                throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
            }
        }