예제 #1
0
        private static string GetExpectedString(bool prettyPrint, bool isUtf8, int[] data)
        {
            MemoryStream ms           = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true);

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

            TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter;

            var json = new Newtonsoft.Json.JsonTextWriter(writer)
            {
                Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None
            };

            json.WriteStartObject();
            json.WritePropertyName("age");
            json.WriteValue(42);
            json.WritePropertyName("first");
            json.WriteValue("John");
            json.WritePropertyName("last");
            json.WriteValue("Smith");
            json.WritePropertyName("phoneNumbers");
            json.WriteStartArray();
            json.WriteValue("425-000-1212");
            json.WriteValue("425-000-1213");
            json.WriteEnd();
            json.WritePropertyName("address");
            json.WriteStartObject();
            json.WritePropertyName("street");
            json.WriteValue("1 Microsoft Way");
            json.WritePropertyName("city");
            json.WriteValue("Redmond");
            json.WritePropertyName("zip");
            json.WriteValue(98052);
            json.WriteEnd();

            // Add a large array of values
            json.WritePropertyName("ExtraArray");
            json.WriteStartArray();
            for (var i = 0; i < ExtraArraySize; i++)
            {
                json.WriteValue(data[i]);
            }
            json.WriteEnd();

            json.WriteEnd();

            json.Flush();

            return(isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString());
        }
예제 #2
0
파일: Protocol.cs 프로젝트: cunchy0/avro-1
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names)
        {
            writer.WriteStartObject();

            JsonHelper.writeIfNotNullOrEmpty(writer, "protocol", this.Name);
            JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Namespace);
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

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

            foreach (Schema type in this.Types)
            {
                type.WriteJson(writer, names, this.Namespace);
            }

            writer.WriteEndArray();

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

            foreach (KeyValuePair <string, Message> message in this.Messages)
            {
                writer.WritePropertyName(message.Key);
                message.Value.writeJson(writer, names, this.Namespace);
            }

            writer.WriteEndObject();
            writer.WriteEndObject();
        }
예제 #3
0
        } // WriteAssociativeArray

        private static void WriteComplexArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, RenderType_t renderType)
        {
            //jsonWriter.WriteStartObject();
            jsonWriter.WriteStartArray();

            for (int i = 0; i <= dr.FieldCount - 1; i++)
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue(dr.GetName(i));

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

                if (renderType.HasFlag(RenderType_t.WithDetail))
                {
                    jsonWriter.WritePropertyName("fieldType");
                    //jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                    jsonWriter.WriteValue(GetTypeName(dr.GetFieldType(i), renderType));
                }

                jsonWriter.WriteEndObject();
            }

            // jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
        } // WriteAssociativeArray
예제 #4
0
 /// <summary>
 /// Writes union schema in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schemas already written</param>
 /// <param name="encspace">enclosing namespace of the schema</param>
 protected internal override void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
 {
     writer.WriteStartArray();
     foreach (Schema schema in this.Schemas)
     {
         schema.WriteJson(writer, names, encspace);
     }
     writer.WriteEndArray();
 }
예제 #5
0
        } // WriteAssociativeArray

        private static void WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr)
        {
            jsonWriter.WriteStartArray();
            for (int i = 0; i <= dr.FieldCount - 1; i++)
            {
                jsonWriter.WriteValue(dr.GetName(i));
            }

            jsonWriter.WriteEndArray();
        } // End Sub WriteArray
예제 #6
0
 /// <summary>
 /// Writes enum schema in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schema already written</param>
 /// <param name="encspace">enclosing namespace of the enum schema</param>
 protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer,
                                                  SchemaNames names, string encspace)
 {
     base.WriteJsonFields(writer, names, encspace);
     writer.WritePropertyName("symbols");
     writer.WriteStartArray();
     foreach (string s in this.Symbols)
     {
         writer.WriteValue(s);
     }
     writer.WriteEndArray();
 }
예제 #7
0
        private static void WriterNewtonsoftBasic(bool formatted, StreamWriter writer)
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
            {
                json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("age");
                json.WriteValue(42);
                json.WritePropertyName("first");
                json.WriteValue("John");
                json.WritePropertyName("last");
                json.WriteValue("Smith");
                json.WritePropertyName("phoneNumbers");
                json.WriteStartArray();
                json.WriteValue("425-000-1212");
                json.WriteValue("425-000-1213");
                json.WriteEnd();
                json.WritePropertyName("address");
                json.WriteStartObject();
                json.WritePropertyName("street");
                json.WriteValue("1 Microsoft Way");
                json.WritePropertyName("city");
                json.WriteValue("Redmond");
                json.WritePropertyName("zip");
                json.WriteValue(98052);
                json.WriteEnd();

                // Add a large array of values
                json.WritePropertyName("ExtraArray");
                json.WriteStartArray();
                for (var i = 0; i < ExtraArraySize; i++)
                {
                    json.WriteValue(i);
                }
                json.WriteEnd();

                json.WriteEnd();
            }
        }
예제 #8
0
        private static void WriterNewtonsoftBasic(bool formatted, TextWriter writer, ReadOnlySpan <int> data)
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
            {
                json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("age");
                json.WriteValue(42);
                json.WritePropertyName("first");
                json.WriteValue("John");
                json.WritePropertyName("last");
                json.WriteValue("Smith");
                json.WritePropertyName("phoneNumbers");
                json.WriteStartArray();
                json.WriteValue("425-000-1212");
                json.WriteValue("425-000-1213");
                json.WriteEnd();
                json.WritePropertyName("address");
                json.WriteStartObject();
                json.WritePropertyName("street");
                json.WriteValue("1 Microsoft Way");
                json.WritePropertyName("city");
                json.WriteValue("Redmond");
                json.WritePropertyName("zip");
                json.WriteValue(98052);
                json.WriteEnd();

                json.WritePropertyName("ExtraArray");
                json.WriteStartArray();
                for (var i = 0; i < data.Length; i++)
                {
                    json.WriteValue(data[i]);
                }
                json.WriteEnd();

                json.WriteEnd();
            }
        }
예제 #9
0
        /// <summary>
        /// Writes named schema in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        /// <param name="encspace">enclosing namespace of the named schema</param>
        protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            this.SchemaName.WriteJson(writer, names, encspace);

            if (null != aliases)
            {
                writer.WritePropertyName("aliases");
                writer.WriteStartArray();
                foreach (SchemaName name in aliases)
                {
                    string fullname = (null != name.Space) ? name.Space + "." + name.Name : name.Name;
                    writer.WriteValue(fullname);
                }
                writer.WriteEndArray();
            }
        }
예제 #10
0
        //[Benchmark]
        public void WriteArrayNewtonsoft()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("message");
                json.WriteStartArray();
                for (var i = 0; i < _longs.Length; i++)
                {
                    json.WriteValue(_longs[i]);
                }
                json.WriteEnd();
                json.WriteEnd();
            }
        }
예제 #11
0
 public static void Serialize(Newtonsoft.Json.JsonTextWriter Writer, TimingDebugger TimingDebuggerObj)
 {
     Writer.WritePropertyName("TimingGroup");
     Writer.WriteStartArray();
     foreach (var t in TimingDebuggerObj)
     {
         var timing = t.Where(tt => tt.Name == t.Name).First();
         Writer.WriteStartObject();
         Writer.WritePropertyName("Name");
         Writer.WriteValue(t.Name);
         Writer.WritePropertyName("ExecutionTime");
         Writer.WriteValue(timing.ExecutionTime);
         Timing.Serialize(Writer, t);
         Writer.WriteEndObject();
     }
     Writer.WriteEndArray();
 }
예제 #12
0
        /// <summary>
        /// 返回结果的存储过程
        /// </summary>
        /// <param name="strSql">任何SQL语句</param>
        /// <param name="parameters">参数值</param>
        /// <returns></returns>
        public override string ExecuteJson(string strSql, params DbParameter[] parameters)
        {
            try
            {
                DbCommand cmd = BuilderQueryCommand(strSql, parameters);

                System.IO.StringWriter     sw     = null;
                Newtonsoft.Json.JsonWriter writer = null;

                sw     = new System.IO.StringWriter();
                writer = new Newtonsoft.Json.JsonTextWriter(sw);

                writer.WriteStartArray();
                using (DbDataReader dr = cmd.ExecuteReader())
                {
                    do
                    {
                        while (dr.Read())
                        {
                            writer.WriteStartObject();
                            for (int i = 0; i < dr.FieldCount; i++)
                            {
                                writer.WritePropertyName(dr.GetName(i));
                                writer.WriteValue(Convert.ToString(dr[i]));
                            }
                            writer.WriteEndObject();
                        }
                    }while (dr.NextResult());
                }

                writer.WriteEndArray();
                writer.Flush();
                return(sw.GetStringBuilder().ToString());
            }
            catch (DbException ex)
            {
                throw ex;
            }
            catch
            {
                throw;
            }
        }
예제 #13
0
        public System.ServiceModel.Channels.Message OrleanStats()
        {
            if (Orleans.GrainClient.IsInitialized == false)
                return WebOperationContext.Current.CreateTextResponse("Error: Client not initialised", "text/plain", Encoding.UTF8);

            IManagementGrain systemManagement = GrainClient.GrainFactory.GetGrain<IManagementGrain>(RuntimeInterfaceConstants.SYSTEM_MANAGEMENT_ID);

            if (systemManagement == null)
                return WebOperationContext.Current.CreateTextResponse("Error: System management not found", "text/plain", Encoding.UTF8);

            var stats = systemManagement.GetSimpleGrainStatistics().Result;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
            writer.Formatting = Newtonsoft.Json.Formatting.Indented;

            writer.WriteStartObject();
            writer.WritePropertyName("stats");
            writer.WriteStartArray();

            foreach (var s in stats)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("activations");
                writer.WriteValue(s.ActivationCount);
                writer.WritePropertyName("address");
                writer.WriteValue(s.SiloAddress.ToString());
                writer.WritePropertyName("type");
                writer.WriteValue(s.GrainType);
                writer.WriteEndObject();

            }

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

            string ret = sb.ToString();
            return WebOperationContext.Current.CreateTextResponse(ret, "text/plain", Encoding.UTF8);
        }
        } // End Sub WriteAssociativeArray

        private static void WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr)
        {
            jsonWriter.WriteStartArray();

            for (int i = 0; i < dr.FieldCount; ++i)
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

                jsonWriter.WritePropertyName("columnName");
                jsonWriter.WriteValue(dr.GetName(i));

                jsonWriter.WritePropertyName("fieldType");
                jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));

                jsonWriter.WriteEndObject();
            } // Next i

            jsonWriter.WriteEndArray();
        } // End Sub WriteArray
예제 #15
0
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            System.Web.HttpResponseBase response = context.HttpContext.Response;
            response.ContentType     = "application/json";
            response.ContentEncoding = System.Text.Encoding.UTF8;

            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(response.OutputStream))
            {
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    writer.WriteStartArray();
                    foreach (object item in itemsToSerialize)
                    {
                        Newtonsoft.Json.Linq.JObject obj =
                            Newtonsoft.Json.Linq.JObject.FromObject(item, serializer);
                        obj.WriteTo(writer);
                        writer.Flush();
                    } // Next item
                    writer.WriteEndArray();
                }     // End using writer
            }         // End Using sw
        }
예제 #16
0
        /// <summary>
        /// Writes the records schema in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        /// <param name="encspace">enclosing namespace of the record schema</param>
        protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            base.WriteJsonFields(writer, names, encspace);

            // we allow reading for empty fields, so writing of records with empty fields are allowed as well
            if (request)
            {
                writer.WritePropertyName("request");
            }
            else
            {
                writer.WritePropertyName("fields");
            }
            writer.WriteStartArray();

            if (null != this.Fields && this.Fields.Count > 0)
            {
                foreach (Field field in this)
                {
                    field.writeJson(writer, names, this.Namespace); // use the namespace of the record for the fields
                }
            }
            writer.WriteEndArray();
        }
예제 #17
0
        public void Run()
        {
            var resultsFile = Path.Combine(Params.TestFileRoot, string.Format("XbimRegression_{0:yyyyMMdd-hhmmss}.csv", DateTime.Now));

            var di = new DirectoryInfo(Params.TestFileRoot);

            using (var writer = new StreamWriter(resultsFile))
            {
                writer.WriteLine(ProcessResult.CsvHeader);
                // ParallelOptions opts = new ParallelOptions() { MaxDegreeOfParallelism = 12 };
                var toProcess = di.GetFiles("*.IFC", SearchOption.AllDirectories);
                // Parallel.ForEach<FileInfo>(toProcess, opts, file =>
                foreach (var file in toProcess)
                {
                    //set up a  log file for this file run
                    var           logFile = Path.ChangeExtension(file.FullName, "log");
                    ProcessResult result;
                    using (var loggerFactory = new LoggerFactory())
                    {
                        XbimLogging.LoggerFactory = loggerFactory;
                        loggerFactory.AddConsole(LogLevel.Error);
                        loggerFactory.AddProvider(new NReco.Logging.File.FileLoggerProvider(logFile, false)
                        {
                            FormatLogEntry = (msg) =>
                            {
                                var sb          = new System.Text.StringBuilder();
                                StringWriter sw = new StringWriter(sb);
                                var jsonWriter  = new Newtonsoft.Json.JsonTextWriter(sw);
                                jsonWriter.WriteStartArray();
                                jsonWriter.WriteValue(DateTime.Now.ToString("o"));
                                jsonWriter.WriteValue(msg.LogLevel.ToString());
                                jsonWriter.WriteValue(msg.EventId.Id);
                                jsonWriter.WriteValue(msg.Message);
                                jsonWriter.WriteValue(msg.Exception?.ToString());
                                jsonWriter.WriteEndArray();
                                return(sb.ToString());
                            }
                        });
                        var logger = loggerFactory.CreateLogger <BatchProcessor>();
                        Console.WriteLine($"Processing {file}");
                        result = ProcessFile(file.FullName, writer, logger);
                    }
                    XbimLogging.LoggerFactory = null; // uses a default loggerFactory

                    var txt = File.ReadAllText(logFile);
                    if (string.IsNullOrEmpty(txt))
                    {
                        File.Delete(logFile);
                        result.Errors      = 0;
                        result.Warnings    = 0;
                        result.Information = 0;
                    }
                    else
                    {
                        var tokens = txt.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        result.Errors      = tokens.Count(t => t == "\"Error\"");
                        result.Warnings    = tokens.Count(t => t == "\"Warning\"");
                        result.Information = Math.Max(0, tokens.Count(t => t == "\"Information\"") - 2); //we always get 2
                    }
                    if (result != null && !result.Failed)
                    {
                        Console.WriteLine($"Processed {file} : {result.Errors} Errors, {result.Warnings} Warnings, {result.Information} Informational in {result.TotalTime}ms. {result.Entities} IFC Elements & {result.GeometryEntries} Geometry Nodes.");
                    }
                    else
                    {
                        Console.WriteLine("Processing failed for {0} after {1}ms.", file, result.TotalTime);
                    }
                    result.FileName = file.Name;
                    writer.WriteLine(result.ToCsv());
                    writer.Flush();
                }

                writer.Close();
            }
            Console.WriteLine("Finished. Press Enter to continue...");

            Console.ReadLine();
        }
예제 #18
0
        /// <summary>
        /// For the specified response processes any associated tracking table documents, converting from csv to json array.
        /// The json array is set on the ResponseData property of the response, save is _not_ called.
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public async Task Process(Response response)
        {
            Guid[] trackingTableDocuments = await _db.Documents.AsNoTracking().Where(d => d.ItemID == response.ID && d.Kind == TrackingTableDocumentKind).Select(d => d.ID).ToArrayAsync();

            if (trackingTableDocuments.Length == 0)
            {
                return;
            }

            StringBuilder buffer = new StringBuilder();

            string[] tableHeader;
            string[] currentLine;

            using (var writer = new Newtonsoft.Json.JsonTextWriter(new StringWriter(buffer)))
            {
                writer.QuoteName = true;

                writer.WriteStartArray();

                foreach (Guid trackingTableDocumentID in trackingTableDocuments)
                {
                    //read the tracking table csv into a dictionary, each dictionary represents a row in the csv document
                    using (var dsDataContext = new DataContext())
                        using (var reader = new StreamReader(new Data.Documents.DocumentStream(dsDataContext, trackingTableDocumentID)))
                            using (var csv = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
                            {
                                csv.SetDelimiters(",");
                                csv.TrimWhiteSpace = true;

                                tableHeader = csv.ReadFields();

                                while (csv.EndOfData == false)
                                {
                                    currentLine = csv.ReadFields();
                                    if (currentLine.Length == 0)
                                    {
                                        continue;
                                    }

                                    writer.WriteStartObject();

                                    for (int i = 0; i < currentLine.Length; i++)
                                    {
                                        writer.WritePropertyName(tableHeader[i]);
                                        writer.WriteValue(currentLine[i]);
                                    }

                                    writer.WriteEndObject();
                                }

                                reader.Close();
                            }
                }

                writer.WriteEndArray();
                writer.Flush();

                response.ResponseData = buffer.ToString();
            }
        }
예제 #19
0
        } // End Sub SerializeLargeDataset

        public void SerializeLargeTable(HttpContext context)
        {
            Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();

            using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.Response.Output))
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;

                jsonWriter.WriteStartObject();


                using (System.Data.Common.DbConnection con = SQL.CreateConnection())
                {
                    if (con.State != System.Data.ConnectionState.Open)
                    {
                        con.Open();
                    }

                    using (System.Data.Common.DbCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT TOP 10000 * FROM T_LOG_SAP_Interface";

                        using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess
                                                                                      | System.Data.CommandBehavior.CloseConnection
                                                                                      ))
                        {
                            jsonWriter.WritePropertyName("Columns");
                            jsonWriter.WriteStartArray();



                            for (int i = 0; i < dr.FieldCount; i++)
                            {
                                string      colName = dr.GetName(i);
                                System.Type t       = dr.GetFieldType(i);

                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName("ColumnName");
                                jsonWriter.WriteValue(colName);

                                jsonWriter.WritePropertyName("DataType");
                                jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(t));

                                // jsonWriter.WritePropertyName("DateTimeMode");
                                // jsonWriter.WriteValue(column.DateTimeMode.ToString());

                                jsonWriter.WriteEndObject();
                            }


                            jsonWriter.WriteEndArray();


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


                            if (dr.HasRows)
                            {
                                int fieldCount = dr.FieldCount;

                                while (dr.Read())
                                {
                                    jsonWriter.WriteStartArray();

                                    for (int i = 0; i < fieldCount; ++i)
                                    {
                                        object obj = dr.GetValue(i);
                                        jsonWriter.WriteValue(obj);
                                    } // Next i

                                    jsonWriter.WriteEndArray();

                                    jsonWriter.Flush();
                                    context.Response.Output.Flush();
                                    context.Response.Flush();
                                } // Whend while (dr.Read())
                            }     // End if (dr.HasRows)

                            dr.Close();
                            jsonWriter.WriteEndArray();
                        } // End using dr
                    }     // End using cmd

                    if (con.State != System.Data.ConnectionState.Closed)
                    {
                        con.Close();
                    }
                } // End using con


                jsonWriter.WriteEndObject();

                jsonWriter.Flush();
                context.Response.Output.Flush();
                context.Response.OutputStream.Flush();
                context.Response.Flush();
            } // End Using jsonWriter
        }     // End Sub SerializeLargeTable
예제 #20
0
        public void SerializeLargeDataset(HttpContext context)
        {
            string strSQL = @"
SELECT TOP 10 * FROM T_Benutzer; 
SELECT TOP 10 * FROM T_Benutzergruppen; 

-- SELECT * FROM T_Benutzer LIMIT 10; 
-- SELECT * FROM T_Benutzergruppen LIMIT 10; 

-- SELECT * FROM T_Benutzer OFFSET 0 FETCH NEXT 10 ROWS ONLY;
-- SELECT * FROM T_Benutzergruppen OFFSET 0 FETCH NEXT 10 ROWS ONLY; 
";

            Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();

            using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.Response.Output))
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;


                jsonWriter.WriteStartObject();

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


                using (System.Data.Common.DbConnection con = SQL.CreateConnection())
                {
                    if (con.State != System.Data.ConnectionState.Open)
                    {
                        con.Open();
                    }

                    using (System.Data.Common.DbCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = strSQL;

                        using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess
                                                                                      | System.Data.CommandBehavior.CloseConnection
                                                                                      ))
                        {
                            do
                            {
                                jsonWriter.WriteStartObject(); // tbl = new Table();

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


                                for (int i = 0; i < dr.FieldCount; ++i)
                                {
                                    jsonWriter.WriteStartObject();

                                    jsonWriter.WritePropertyName("ColumnName");
                                    jsonWriter.WriteValue(dr.GetName(i));

                                    jsonWriter.WritePropertyName("FieldType");
                                    jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));

                                    jsonWriter.WriteEndObject();
                                } // Next i
                                jsonWriter.WriteEndArray();

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

                                if (dr.HasRows)
                                {
                                    while (dr.Read())
                                    {
                                        object[] thisRow = new object[dr.FieldCount];

                                        jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount];
                                        for (int i = 0; i < dr.FieldCount; ++i)
                                        {
                                            jsonWriter.WriteValue(dr.GetValue(i));
                                        } // Next i
                                        jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow);
                                    }     // Whend
                                }         // End if (dr.HasRows)

                                jsonWriter.WriteEndArray();

                                jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl);
                            } while (dr.NextResult());
                        } // End using dr
                    } // End using cmd


                    if (con.State != System.Data.ConnectionState.Closed)
                    {
                        con.Close();
                    }
                } // End using con

                jsonWriter.WriteEndArray();

                jsonWriter.WriteEndObject();
                jsonWriter.Flush();
            } // End Using jsonWriter

            context.Response.Output.Flush();
            context.Response.OutputStream.Flush();
            context.Response.Flush();
        } // End Sub SerializeLargeDataset
예제 #21
0
파일: Program.cs 프로젝트: dterziev/elk
        private static ArraySegment <byte> GenerateEvents(ref long sequence, int eventCount)
        {
            using (MemoryStream buffer = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(buffer, new UTF8Encoding(false), 4096, true))
                    using (Newtonsoft.Json.JsonTextWriter w = new Newtonsoft.Json.JsonTextWriter(writer))
                    {
                        w.WriteStartArray();

                        for (int i = 0; i < eventCount; i++)
                        {
                            var sequenceNo = Interlocked.Increment(ref sequence);
                            w.WriteStartObject();

                            w.WritePropertyName("@timestamp");
                            w.WriteValue(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));

                            w.WritePropertyName("logger");
                            w.WriteValue("Program.GridLogger");

                            w.WritePropertyName("level");
                            w.WriteValue("INFO");

                            w.WritePropertyName("hostname");
                            w.WriteValue(Environment.MachineName);

                            w.WritePropertyName("taskId");
                            w.WriteValue(1);

                            w.WritePropertyName("jobId");
                            w.WriteValue(3);

                            w.WritePropertyName("thread");
                            w.WriteValue("4");

                            w.WritePropertyName("message");
                            w.WriteValue($"log message sequence {sequenceNo}");

                            w.WritePropertyName("eventSequence");
                            w.WriteValue(sequenceNo);

                            w.WritePropertyName("metrics");
                            w.WriteStartObject();

                            w.WritePropertyName("metric1");
                            w.WriteValue(4.3);

                            w.WritePropertyName("metric2");
                            w.WriteValue(5.3);

                            w.WritePropertyName("metric3");
                            w.WriteValue(0.3 * sequenceNo);

                            w.WritePropertyName("seq");
                            w.WriteValue(sequenceNo);

                            w.WriteEndObject();


                            w.WriteEndObject();
                        }

                        w.WriteEndArray();
                    }

                buffer.TryGetBuffer(out var result);
                return(result);
            }
        }
예제 #22
0
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            context.HttpContext.Response.ContentType     = "application/json";
            context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;


            using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.HttpContext.Response.Output))
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;


                jsonWriter.WriteStartObject();

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


                using (System.Data.Common.DbConnection con = SQL.CreateConnection())
                {
                    if (con.State != System.Data.ConnectionState.Open)
                    {
                        con.Open();
                    }

                    using (System.Data.Common.DbCommand cmd = this.GetCommand(con))
                    {
                        using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess
                                                                                      | System.Data.CommandBehavior.CloseConnection
                                                                                      ))
                        {
                            do
                            {
                                jsonWriter.WriteStartObject(); // tbl = new Table();

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


                                for (int i = 0; i < dr.FieldCount; ++i)
                                {
                                    jsonWriter.WriteStartObject();

                                    jsonWriter.WritePropertyName("ColumnName");
                                    jsonWriter.WriteValue(dr.GetName(i));

                                    jsonWriter.WritePropertyName("FieldType");
                                    jsonWriter.WriteValue(SQL.GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));

                                    jsonWriter.WriteEndObject();
                                } // Next i
                                jsonWriter.WriteEndArray();

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

                                if (dr.HasRows)
                                {
                                    while (dr.Read())
                                    {
                                        object[] thisRow = new object[dr.FieldCount];

                                        jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount];
                                        for (int i = 0; i < dr.FieldCount; ++i)
                                        {
                                            jsonWriter.WriteValue(dr.GetValue(i));
                                        } // Next i
                                        jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow);
                                    }     // Whend
                                }         // End if (dr.HasRows)

                                jsonWriter.WriteEndArray();

                                jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl);
                            } while (dr.NextResult());
                        } // End using dr
                    } // End using cmd


                    if (con.State != System.Data.ConnectionState.Closed)
                    {
                        con.Close();
                    }
                } // End using con

                jsonWriter.WriteEndArray();

                jsonWriter.WriteEndObject();
                jsonWriter.Flush();
            } // End Using jsonWriter

            context.HttpContext.Response.Output.Flush();
            context.HttpContext.Response.OutputStream.Flush();
            context.HttpContext.Response.Flush();
        } // End Sub SerializeLargeDataset
        /// <summary>
        /// Convert the sql results to UtilityResponce
        /// </summary>
        /// <param name="sqlReadResults">the source</param>
        /// <param name="result">the target.</param>
        public static void ConvertReadResultsToResponce(List <SqlReadResult> sqlReadResults, UtilityResponce result)
        {
            int kind          = 0;
            var stringBuilder = new System.Text.StringBuilder();

            if (sqlReadResults.Count > 0)
            {
                var sqlReadResult = sqlReadResults[0];
                if ((sqlReadResult.FieldCount == 1) &&
                    (sqlReadResult.Rows.Count > 0) &&
                    ((string.Equals(sqlReadResult.FieldNames[0], "kind", StringComparison.OrdinalIgnoreCase)) ||
                     (string.Equals(sqlReadResult.FieldNames[0], "mimetype", StringComparison.OrdinalIgnoreCase))))
                {
                    var cell00 = sqlReadResult.Rows[0][0] as string;
                    if ((string.Equals(cell00, "text", StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(cell00, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(cell00, Consts.MimeTypeJavascript, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeText;
                        kind        = 1;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, "html", StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeHTML;
                        kind        = 2;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, "json", StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeJSON;
                        kind        = 3;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = cell00;
                        kind        = 4;
                        sqlReadResults.RemoveAt(0);
                    }
                    else
                    {
                        result.Kind = cell00;
                        kind        = 1;
                    }
                }
                else if (sqlReadResult.FieldCount >= 1)
                {
                    var fieldName0 = sqlReadResult.FieldNames[0] as string;
                    if ((string.Equals(fieldName0, "text", StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(fieldName0, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeText;
                        kind        = 1;
                    }
                    else if ((string.Equals(fieldName0, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, "html", StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeHTML;
                        kind        = 2;
                    }
                    else if ((string.Equals(fieldName0, "json", StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeJSON;
                        kind        = 3;
                    }
                    else if ((string.Equals(fieldName0, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = fieldName0;
                        kind        = 4;
                    }
                    else
                    {
                        result.Kind = "application/json";
                        kind        = 3;
                    }
                }
            }
            if (kind == 1)
            {
                foreach (var sqlReadResult in sqlReadResults)
                {
                    foreach (var row in sqlReadResult.Rows)
                    {
                        for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                        {
                            var value = row[fieldIndex];
                            if (value == null)
                            {
                                continue;
                            }
                            stringBuilder.Append(value);
                        }
                    }
                }
            }
            else if (kind == 2)
            {
                foreach (var sqlReadResult in sqlReadResults)
                {
                    foreach (var row in sqlReadResult.Rows)
                    {
                        for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                        {
                            var value = row[fieldIndex];
                            if (value == null)
                            {
                                continue;
                            }
                            stringBuilder.Append(value);
                        }
                    }
                }
            }
            else if (kind == 3)
            {
                using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) {
                    using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) {
                        jsonTextWriter.WriteStartArray();
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            jsonTextWriter.WriteStartArray();
                            foreach (var row in sqlReadResult.Rows)
                            {
                                jsonTextWriter.WriteStartObject();
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    jsonTextWriter.WritePropertyName(fieldName);
                                    jsonTextWriter.WriteValue(value);
                                }
                                jsonTextWriter.WriteEndObject();
                            }
                            jsonTextWriter.WriteEndArray();
                            if ((sqlReadResult.MeassureMessage.Count > 0) && (sqlReadResult.MeassureError.Count > 0))
                            {
                                if (sqlReadResult.MeassureMessage.Count > 0)
                                {
                                    jsonTextWriter.WriteStartArray();
                                    foreach (var meassureMessage in sqlReadResult.MeassureMessage)
                                    {
                                        jsonTextWriter.WriteStartObject();
                                        jsonTextWriter.WritePropertyName("MeassureMessage");
                                        jsonTextWriter.WriteValue(meassureMessage);
                                        jsonTextWriter.WriteEndObject();
                                    }
                                    jsonTextWriter.WriteEndArray();
                                }
                                if (sqlReadResult.MeassureError.Count > 0)
                                {
                                    jsonTextWriter.WriteStartArray();
                                    foreach (var meassureError in sqlReadResult.MeassureError)
                                    {
                                        jsonTextWriter.WriteStartObject();
                                        jsonTextWriter.WritePropertyName("MeassureError");
                                        jsonTextWriter.WriteValue(meassureError);
                                        jsonTextWriter.WriteEndObject();
                                    }
                                    jsonTextWriter.WriteEndArray();
                                }
                            }
                        }
                        jsonTextWriter.WriteEndArray();
                    }
                }
            }
            else if (kind == 4)
            {
                using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) {
                    using (var xmlWriter = new System.Xml.XmlTextWriter(stringWriter)) {
                        xmlWriter.Formatting = System.Xml.Formatting.None;
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("data");
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            xmlWriter.WriteStartElement("result");
                            foreach (var row in sqlReadResult.Rows)
                            {
                                xmlWriter.WriteStartElement("row");
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    xmlWriter.WriteStartElement(fieldName);
                                    if (value == null)
                                    {
                                        // ignore
                                    }
                                    else if (value == DBNull.Value)
                                    {
                                        // ignore
                                    }
                                    else if (value is string)
                                    {
                                        xmlWriter.WriteValue((string)value);
                                    }
                                    else if (value is bool)
                                    {
                                        xmlWriter.WriteValue((bool)value);
                                    }
                                    else if (value is DateTime)
                                    {
                                        xmlWriter.WriteValue((DateTime)value);
                                    }
                                    else if (value is decimal)
                                    {
                                        xmlWriter.WriteValue((decimal)value);
                                    }
                                    else if (value is float)
                                    {
                                        xmlWriter.WriteValue((float)value);
                                    }
                                    else if (value is double)
                                    {
                                        xmlWriter.WriteValue((double)value);
                                    }
                                    else if (value is int)
                                    {
                                        xmlWriter.WriteValue((int)value);
                                    }
                                    else if (value is long)
                                    {
                                        xmlWriter.WriteValue((long)value);
                                    }
                                    else
                                    {
                                        xmlWriter.WriteElementString(fieldName, value.ToString());
                                    }
                                    xmlWriter.WriteEndElement(/*fieldName*/);
                                }
                                xmlWriter.WriteEndElement(/*row*/);
                            }
                            xmlWriter.WriteEndElement(/*result*/);
                        }
                        xmlWriter.WriteEndElement(/*data*/);
                        xmlWriter.WriteEndDocument();
                    }
                    using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) {
                        jsonTextWriter.WriteStartArray();
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            jsonTextWriter.WriteStartArray();
                            foreach (var row in sqlReadResult.Rows)
                            {
                                jsonTextWriter.WriteStartObject();
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    jsonTextWriter.WritePropertyName(fieldName);
                                    jsonTextWriter.WriteValue(value);
                                }
                                jsonTextWriter.WriteEndObject();
                            }
                            jsonTextWriter.WriteEndArray();
                        }
                        jsonTextWriter.WriteEndArray();
                    }
                }
            }
            result.Value = stringBuilder.ToString();
        }
예제 #24
0
        }// End Sub

        public static void SerializeDataTableAsAssociativeJsonArray(
            System.Data.Common.DbCommand cmd
            , Microsoft.AspNetCore.Http.HttpContext context
            , bool pretty
            , System.Text.Encoding enc)
        {
            SqlService service = (SqlService)context.RequestServices.GetService(typeof(SqlService));

            using (System.IO.TextWriter sw = new System.IO.StreamWriter(context.Response.Body, enc))
            {
                using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    if (pretty)
                    {
                        jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                    }

                    // jsonWriter.WriteStartObject();
                    // jsonWriter.WritePropertyName("tables");
                    // jsonWriter.WriteStartArray();

                    using (System.Data.Common.DbConnection con = service.Connection)
                    {
                        cmd.Connection = con;

                        if (con.State != System.Data.ConnectionState.Open)
                        {
                            con.Open();
                        }

                        try
                        {
                            using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess
                                                                                          | System.Data.CommandBehavior.CloseConnection
                                                                                          ))
                            {
                                do
                                {
                                    // jsonWriter.WriteStartObject(); // tbl = new Table();

                                    //jsonWriter.WritePropertyName("columns");

                                    //// WriteArray(jsonWriter, dr);
                                    //WriteAssociativeArray(jsonWriter, dr);

                                    //jsonWriter.WritePropertyName("rows");
                                    jsonWriter.WriteStartArray();

                                    if (dr.HasRows)
                                    {
                                        string[] columns = new string[dr.FieldCount];

                                        for (int i = 0; i < dr.FieldCount; i++)
                                        {
                                            columns[i] = dr.GetName(i);
                                        } // Next i

                                        while (dr.Read())
                                        {
                                            // jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount];
                                            jsonWriter.WriteStartObject(); // tbl = new Table();

                                            for (int i = 0; i < dr.FieldCount; ++i)
                                            {
                                                jsonWriter.WritePropertyName(columns[i]);

                                                object obj = dr.GetValue(i);
                                                if (obj == System.DBNull.Value)
                                                {
                                                    obj = null;
                                                }

                                                jsonWriter.WriteValue(obj);
                                            } // Next i

                                            // jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow);
                                            jsonWriter.WriteEndObject();
                                        } // Whend
                                    }     // End if (dr.HasRows)

                                    jsonWriter.WriteEndArray();

                                    // jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl);
                                } while (dr.NextResult());
                            } // End using dr
                        }
                        catch (System.Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                            throw;
                        }

                        if (con.State != System.Data.ConnectionState.Closed)
                        {
                            con.Close();
                        }
                    } // End using con

                    // jsonWriter.WriteEndArray();

                    // jsonWriter.WriteEndObject();
                    jsonWriter.Flush();
                } // End Using jsonWriter
            }     // End Using sw
        }         // End Sub SerializeDataTableAsAssociativeJsonArray
예제 #25
0
        public static void ToJson(this Method method, System.IO.Stream target)
        {
            using (var sw = new System.IO.StreamWriter(target, System.Text.Encoding.UTF8, 4 * 1024, true))
                using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    jw.Formatting = Newtonsoft.Json.Formatting.Indented;

                    foreach (var _ in method.All((item, action) =>
                    {
                        if (item == method)
                        {
                            if (action == VisitorState.Enter)
                            {
                                jw.WriteStartArray();
                            }
                            else if (action == VisitorState.Leave)
                            {
                                jw.WriteEndArray();
                            }

                            return(true);
                        }
                        else if (item is Statement)
                        {
                            if (action == VisitorState.Enter)
                            {
                                var stm = item as Statement;

                                jw.WriteStartObject();

                                jw.WritePropertyName("type");
                                jw.WriteValue(stm.GetType().FullName);

                                if (!string.IsNullOrWhiteSpace(stm.Name))
                                {
                                    jw.WritePropertyName("name");
                                    jw.WriteValue(stm.Name);
                                }

                                jw.WritePropertyName("children");
                                jw.WriteStartArray();
                            }
                            else if (action == VisitorState.Leave)
                            {
                                jw.WriteEndArray();
                                jw.WriteEndObject();
                            }

                            return(true);
                        }
                        else if (item is Expression)
                        {
                            if (action == VisitorState.Enter)
                            {
                                var expr = item as Expression;

                                jw.WriteStartObject();

                                jw.WritePropertyName("type");
                                jw.WriteValue(expr.GetType().FullName);

                                if (!string.IsNullOrWhiteSpace(expr.Name))
                                {
                                    jw.WritePropertyName("name");
                                    jw.WriteValue(expr.Name);
                                }

                                if (expr.SourceExpression != null)
                                {
                                    jw.WritePropertyName("source");
                                    jw.WriteValue(expr.SourceExpression.ToString());
                                }

                                jw.WritePropertyName("children");
                                jw.WriteStartArray();
                            }
                            else if (action == VisitorState.Leave)
                            {
                                jw.WriteEndArray();
                                jw.WriteEndObject();
                            }

                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }))
                    {
                    }
                }
        }
예제 #26
0
        } // End Sub WriteArray

        public static void AnyDataReaderToAnyJson(
            string sql
            , SqlService service
            , System.Collections.Generic.Dictionary <string, object> pars
            , System.Web.HttpContext context
            , RenderType_t format)
        {
            using (System.Data.Common.DbConnection con = service.Connection)
            {
                using (System.Data.Common.DbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sql;
                    service.AddParameterList(pars, cmd);

                    // cmd.ExecuteNonQuery
                    // cmd.ExecuteReader
                    // cmd.ExecuteScalar

                    using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(
                               System.Data.CommandBehavior.SequentialAccess
                               | System.Data.CommandBehavior.CloseConnection))
                    {
                        using (System.IO.StreamWriter output = new System.IO.StreamWriter(context.Response.OutputStream))
                        {
                            using (Newtonsoft.Json.JsonTextWriter jsonWriter =
                                       new Newtonsoft.Json.JsonTextWriter(output)) // context.Response.Output)
                            {
                                if (format.HasFlag(RenderType_t.Indented))
                                {
                                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                                }

                                context.Response.StatusCode  = (int)System.Net.HttpStatusCode.OK;
                                context.Response.ContentType = "application/json";


                                jsonWriter.WriteStartObject();

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

                                do
                                {
                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        jsonWriter.WriteStartObject();
                                        jsonWriter.WritePropertyName("columns");

                                        if (format.HasFlag(RenderType_t.Columns_Associative))
                                        {
                                            WriteAssociativeColumnsArray(jsonWriter, dr, format);
                                        }
                                        else if (format.HasFlag(RenderType_t.Columns_ObjectArray))
                                        {
                                            WriteComplexArray(jsonWriter, dr, format);
                                        }
                                        else // (format.HasFlag(RenderType_t.Array))
                                        {
                                            WriteArray(jsonWriter, dr);
                                        }
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only))



                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        jsonWriter.WritePropertyName("rows");
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only))

                                    jsonWriter.WriteStartArray();

                                    if (dr.HasRows)
                                    {
                                        string[] columns = null;
                                        if (format.HasFlag(RenderType_t.DataTable))
                                        {
                                            columns = new string[dr.FieldCount];
                                            for (int i = 0; i < dr.FieldCount; i++)
                                            {
                                                columns[i] = dr.GetName(i);
                                            } // Next i
                                        }     // End if (format.HasFlag(RenderType_t.DataTable))

                                        while (dr.Read())
                                        {
                                            if (format.HasFlag(RenderType_t.DataTable))
                                            {
                                                jsonWriter.WriteStartObject();
                                            }
                                            else
                                            {
                                                jsonWriter.WriteStartArray();
                                            }

                                            for (int i = 0; i <= dr.FieldCount - 1; i++)
                                            {
                                                object obj = dr.GetValue(i);
                                                if (obj == System.DBNull.Value)
                                                {
                                                    obj = null;
                                                }

                                                if (columns != null && format.HasFlag(RenderType_t.DataTable))
                                                {
                                                    jsonWriter.WritePropertyName(columns[i]);
                                                }

                                                jsonWriter.WriteValue(obj);
                                            } // Next i

                                            if (format.HasFlag(RenderType_t.DataTable))
                                            {
                                                jsonWriter.WriteEndObject();
                                            }
                                            else
                                            {
                                                jsonWriter.WriteEndArray();
                                            }
                                        } // Whend
                                    }     // End if (dr.HasRows)

                                    jsonWriter.WriteEndArray();

                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        jsonWriter.WriteEndObject();
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only))
                                } while (dr.NextResult());

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

                                jsonWriter.Flush();
                                output.Flush();
                            } // jsonWriter
                        }     // output
                    }         // dr
                }             // End Using cmd

                if (con.State != System.Data.ConnectionState.Closed)
                {
                    con.Close();
                }
            } // con
        }     // End Sub WriteArray
예제 #27
0
        } // End Sub MultipleLargeDataSets

        public static void MultipleLargeDataSets(System.IO.Stream strm, string strSQL)
        {
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();

            using (System.IO.StreamWriter output = new System.IO.StreamWriter(strm))
            {
                using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(output))
                {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;

                    jsonWriter.WriteStartObject();

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


                    using (System.Data.Common.DbDataReader dr = SQL.ExecuteReader(strSQL
                                                                                  , System.Data.CommandBehavior.CloseConnection
                                                                                  | System.Data.CommandBehavior.SequentialAccess
                                                                                  ))
                    {
                        do
                        {
                            jsonWriter.WriteStartObject(); // tbl = new Table();

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


                            for (int i = 0; i < dr.FieldCount; ++i)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName("ColumnName");
                                jsonWriter.WriteValue(dr.GetName(i));

                                jsonWriter.WritePropertyName("FieldType");
                                jsonWriter.WriteValue(dr.GetFieldType(i).AssemblyQualifiedName);


                                jsonWriter.WriteEndObject();
                            } // Next i
                            jsonWriter.WriteEndArray();

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

                            if (dr.HasRows)
                            {
                                while (dr.Read())
                                {
                                    object[] thisRow = new object[dr.FieldCount];

                                    jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount];
                                    for (int i = 0; i < dr.FieldCount; ++i)
                                    {
                                        jsonWriter.WriteValue(dr.GetValue(i));
                                    } // Next i
                                    jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow);
                                }     // Whend
                            }         // End if (dr.HasRows)

                            jsonWriter.WriteEndArray();

                            jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl);
                        } while (dr.NextResult());
                    } // End Using dr

                    jsonWriter.WriteEndArray();

                    jsonWriter.WriteEndObject();

                    jsonWriter.Flush();
                    output.Flush();
                    output.BaseStream.Flush();

                    output.Close();

                    // context.Response.Output.Flush();
                    // context.Reponse.OutputStream.Flush();
                    // context.Response.Flush();
                } // End Using jsonWriter
            }     // End using output
        }         // End Sub MultipleLargeDataSets