} // End Sub WriteAssociativeArray

        private static void WriteAssociativeArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, bool dataType)
        {
            // JSON:
            //{
            //     "column_1":{ "index":0,"fieldType":"int"}
            //    ,"column_2":{ "index":1,"fieldType":"int"}
            //}

            jsonWriter.WriteStartObject();

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

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

#if false
                jsonWriter.WritePropertyName("columnName");
                jsonWriter.WriteValue(dr.GetName(i));
#endif

                if (dataType)
                {
                    jsonWriter.WritePropertyName("fieldType");
                    jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                } // End if (dataType)

                jsonWriter.WriteEndObject();
            } // Next i

            jsonWriter.WriteEndObject();
        } // End Sub WriteAssociativeArray
Exemplo n.º 2
0
        } // GetAssemblyQualifiedNoVersionName

        private static async System.Threading.Tasks.Task WriteAssociativeColumnsArray(
            Newtonsoft.Json.JsonTextWriter jsonWriter
            , System.Data.Common.DbDataReader dr, RenderType_t renderType)
        {
            //await jsonWriter.WriteStartObjectAsync();
            await jsonWriter.WriteStartObjectAsync();

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

                await jsonWriter.WriteStartObjectAsync();

                await jsonWriter.WritePropertyNameAsync("index");

                await jsonWriter.WriteValueAsync(i);

                if (renderType.HasFlag(RenderType_t.WithDetail))
                {
                    await jsonWriter.WritePropertyNameAsync("fieldType");

                    // await jsonWriter.WriteValueAsync(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                    await jsonWriter.WriteValueAsync(GetTypeName(dr.GetFieldType(i), renderType));
                }

                await jsonWriter.WriteEndObjectAsync();
            } // Next i

            await jsonWriter.WriteEndObjectAsync();
        } // WriteAssociativeArray
Exemplo n.º 3
0
        private static void WriteCSV(System.Data.Common.DbDataReader reader, TextWriter writer)
        {
            Action <string> logBadData = s =>
            {
                Log.Logger.Warning(s);
                Console.Error.WriteLine("Unable to write record: {0}", s);
            };

            using (var csv = new CsvHelper.CsvWriter(writer))
            {
                csv.Configuration.TrimOptions = CsvHelper.Configuration.TrimOptions.None;

                int length = reader.FieldCount;

                for (var i = 0; i < length; i++)
                {
                    csv.WriteField(reader.GetName(i));
                }
                csv.NextRecord();

                while (reader.Read())
                {
                    for (var i = 0; i < length; i++)
                    {
                        csv.WriteField(reader[i]);
                    }
                    csv.NextRecord();
                }
            }
        }
Exemplo n.º 4
0
        public static dynamic consulta(string query, bool tipoSelect = false, bool eliminando = false)
        {
            var consulta = new List <Dictionary <string, object> >();

            try
            {
                conexion.Open();
                NpgsqlCommand cmd = new NpgsqlCommand(query, conexion);
                if (!tipoSelect)
                {
                    System.Data.Common.DbDataReader datos = cmd.ExecuteReader();

                    while (datos.Read())
                    {
                        Dictionary <string, object> objeto = new Dictionary <string, object>();
                        for (int x = 0; x < datos.FieldCount; x++)
                        {
                            objeto.Add(datos.GetName(x), datos.GetValue(x));
                        }
                        consulta.Add(objeto);
                    }
                    // consulta.Clear();
                    //  consulta = new List<Dictionary<string, object>>();
                }
                else
                {
                    try
                    {
                        cmd.ExecuteNonQuery();
                        conexion.Close();
                        cmd.Dispose();
                        return(true);
                    }

                    catch (Exception e)
                    {
                        if (eliminando)
                        {
                            return(false);
                        }
                        MessageBox.Show(e.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        conexion.Close();
                        return(false);
                    }
                }
                conexion.Close();
            }
            catch (Exception e)
            {
                if (eliminando)
                {
                    return(false);
                }
                MessageBox.Show(e.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                conexion.Close();
            }


            return(consulta);
        }
Exemplo n.º 5
0
        public void AddSheet(System.Data.Common.DbDataReader reader, string?name = null)
        {
            NewSheet(name);

            // Write headers
            for (int i = 0; i < reader.FieldCount; i++)
            {
                WriteData(reader.GetName(i));
            }
            NewLine();

            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    var value = reader.GetValue(i);
                    if (value == null || value == DBNull.Value)
                    {
                        value = "";
                    }
                    WriteData(value);
                }
                NewLine();
            }
        }
Exemplo n.º 6
0
        public static List <dynamic> DataReaderToDynamic(System.Data.Common.DbDataReader reader, out double runTime)
        {
            var            time    = DateTime.Now;
            List <dynamic> list    = new List <dynamic>();
            var            columns = new List <string>();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns.Add(reader.GetName(i));
            }
            try
            {
                #region while
                while (reader.Read())
                {
                    object[] values = new object[columns.Count];
                    reader.GetValues(values);
                    var d = getRow(columns, values);
                    list.Add(d);
                }
                #endregion
            }
            catch (Exception ero)
            {
                reader.Close();
                throw new CRLException("读取数据时发生错误:" + ero.Message);
            }
            reader.Close();
            runTime = (DateTime.Now - time).TotalMilliseconds;
            return(list);
        }
                public DeserializerKey(int hashCode, int startBound, int length, bool returnNullIfFirstMissing, IDataReader reader, bool copyDown)
                {
                    this.hashCode   = hashCode;
                    this.startBound = startBound;
                    this.length     = length;
                    this.returnNullIfFirstMissing = returnNullIfFirstMissing;

                    if (copyDown)
                    {
                        this.reader = null;
                        names       = new string[length];
                        types       = new Type[length];
                        int index = startBound;
                        for (int i = 0; i < length; i++)
                        {
                            names[i] = reader.GetName(index);
                            types[i] = reader.GetFieldType(index++);
                        }
                    }
                    else
                    {
                        this.reader = reader;
                        names       = null;
                        types       = null;
                    }
                }
Exemplo n.º 8
0
        /// <summary>
        /// 返回匿名类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="reader"></param>
        /// <param name="resultSelector"></param>
        /// <param name="runTime"></param>
        /// <returns></returns>
        public static List <TResult> DataReaderToDynamic <T, TResult>(System.Data.Common.DbDataReader reader, Expression <Func <T, TResult> > resultSelector, out double runTime) where T : IModel, new()
        {
            var            time     = DateTime.Now;
            List <TResult> list     = new List <TResult>();
            var            typeArry = TypeCache.GetProperties(typeof(T), true).Values;
            var            columns  = new Dictionary <string, int>();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns.Add(reader.GetName(i).ToLower(), i);
            }
            var reflection = ReflectionHelper.GetInfo <T>();
            var actions    = new List <CRL.ObjectConvert.ActionItem <T> >();
            var first      = true;

            //var objOrigin = new T();
            while (reader.Read())
            {
                object objInstance = reflection.CreateObjectInstance();

                object[] values = new object[columns.Count];
                reader.GetValues(values);
                var detailItem = ObjectConvert.DataReaderToObj <T>(columns, values, reflection, true, objInstance, typeArry, actions, first) as T;
                var result     = resultSelector.Compile()(detailItem);
                list.Add(result);
                first = false;
            }
            reader.Close();
            runTime = (DateTime.Now - time).TotalMilliseconds;
            return(list);
        }
Exemplo n.º 9
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
Exemplo n.º 10
0
 public BuilderKey(Type destinationType, IDataRecord record)
 {
     _destinationType = destinationType;
     _dataRecordNames = new List <string>(record.FieldCount);
     for (int i = 0; i < record.FieldCount; i++)
     {
         _dataRecordNames.Add(record.GetName(i));
     }
 }
Exemplo n.º 11
0
        } // WriteAssociativeArray


        private static async System.Threading.Tasks.Task WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter,
            System.Data.Common.DbDataReader dr)
        {
            await jsonWriter.WriteStartArrayAsync();
            for (int i = 0; i <= dr.FieldCount - 1; i++)
                await jsonWriter.WriteValueAsync(dr.GetName(i));

            await jsonWriter.WriteEndArrayAsync();
        } // End Sub WriteArray 
Exemplo n.º 12
0
        public static dynamic consulta2(string query, bool tipoSelect = false)
        {
            string host     = SISPE_MIGRACION.Properties.Resources.servidor;
            string usuario  = SISPE_MIGRACION.Properties.Resources.usuario;
            string password = SISPE_MIGRACION.Properties.Resources.password;
            string database = "archivos";
            string port     = SISPE_MIGRACION.Properties.Resources.puerto;

            string queryConexion = string.Format("Host={0};Username={1};Password={2};Database={3};port={4}Timeout=300;CommandTimeout = 300", host, usuario, password, database, port);

            realizarConexion2(queryConexion);


            var consulta = new List <Dictionary <string, object> >();

            try
            {
                conexion2.Open();
                NpgsqlCommand cmd = new NpgsqlCommand(query, conexion2);
                if (!tipoSelect)
                {
                    System.Data.Common.DbDataReader datos = cmd.ExecuteReader();

                    while (datos.Read())
                    {
                        Dictionary <string, object> objeto = new Dictionary <string, object>();
                        for (int x = 0; x < datos.FieldCount; x++)
                        {
                            objeto.Add(datos.GetName(x), datos.GetValue(x));
                        }
                        consulta.Add(objeto);
                    }
                }
                else
                {
                    try
                    {
                        cmd.ExecuteNonQuery();
                        conexion2.Close();
                        return(true);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        conexion2.Close();
                        return(false);
                    }
                }
                conexion2.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                conexion2.Close();
            }
            return(consulta);
        }
Exemplo n.º 13
0
        public static Row FullFromReader(string name, System.Data.Common.DbDataReader reader)
        {
            Row m = new Row(name);

            for (int i = 0; i < reader.FieldCount; i++)
            {
                m[reader.GetName(i)] = reader.GetValue(i);
            }
            return(m);
        }
Exemplo n.º 14
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
Exemplo n.º 15
0
        } // End Function Sql2DataTableTest

        public static DataTable Sql2DataTableTest(System.Data.Common.DbCommand cmd, DataTable dt)
        {
            if (dt == null)
            {
                dt = new DataTable();
            }
            //else dt.Clear();

            using (System.Data.Common.DbDataReader rdr = CoinBaseSharp.SQL.ExecuteReader(cmd, System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.CloseConnection))
            {
                int fieldCount = rdr.FieldCount;

                string[]      fieldNames = new string[fieldCount];
                System.Type[] fieldTypes = new System.Type[fieldCount];
                object[]      objs       = new object[fieldCount];

                for (int i = 0; i < fieldCount; ++i)
                {
                    fieldNames[i] = rdr.GetName(i);
                    fieldTypes[i] = rdr.GetFieldType(i);
                    dt.Columns.Add(fieldNames[i], fieldTypes[i]);
                } // Next i


                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        DataRow dr = dt.NewRow();

                        for (int i = 0; i < fieldCount; ++i)
                        {
                            object obj = rdr.GetValue(i);

                            if (obj == null)
                            {
                                dr[fieldNames[i]] = System.DBNull.Value;
                            }
                            else
                            {
                                dr[fieldNames[i]] = obj;
                            }
                        } // Next i

                        dt.Rows.Add(dr);
                    } // Whend
                }     // End if (rdr.HasRows)
            }         // End Using rdr

            // string str = dt.ToHtml();
            // System.Console.WriteLine(str);
            // System.Console.WriteLine(dt.Rows.Count);
            return(dt);
        } // End Function Sql2DataTableTest
Exemplo n.º 16
0
        public static void MultipleDataSets(string strSQL)
        {
            DataSetSerialization ser = new DataSetSerialization();

            using (System.Data.Common.DbDataReader dr = SQL.ExecuteReader(strSQL
                                                                          , System.Data.CommandBehavior.CloseConnection
                                                                          | System.Data.CommandBehavior.SequentialAccess
                                                                          )
                   )
            {
                Table tbl = null;

                do
                {
                    tbl = new Table();

                    for (int i = 0; i < dr.FieldCount; ++i)
                    {
                        tbl.Columns.Add(
                            new ColumnInfo()
                        {
                            ColumnName = dr.GetName(i),
                            FieldType  = dr.GetFieldType(i)
                        }
                            );
                    } // Next i

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

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

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

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

            string str = EasyJSON.JsonHelper.SerializePretty(ser);

            System.Console.WriteLine(str);

            DataSetSerialization ser2 = EasyJSON.JsonHelper.Deserialize <DataSetSerialization>(str);

            System.Console.WriteLine(ser2);
        } // End Sub MultipleDataSets
Exemplo n.º 17
0
        static dynamic getDataRow(System.Data.Common.DbDataReader reader)
        {
            dynamic obj  = new System.Dynamic.ExpandoObject();
            var     dict = obj as IDictionary <string, object>;

            for (int i = 0; i < reader.FieldCount; i++)
            {
                string columnName = reader.GetName(i);
                object value      = reader[columnName];
                dict.Add(columnName, value);
            }
            return(obj);
        }
Exemplo n.º 18
0
        static string AsCSVDif(System.Data.Common.DbDataReader srcVals, System.Data.Common.DbDataReader destVals, int idOrdinal)
        {
            var sb = new System.Text.StringBuilder("Field\tSource\tDestination\r\n");
            for (int i = 0; i < srcVals.FieldCount; i++)
            {
                object oldRes = srcVals.GetValue(i);
                object newRes = destVals.GetValue(i);
                if (i == idOrdinal || oldRes != newRes)
                {
                    sb.AppendFormat("{0}\t{1}\t{2}\r\n",srcVals.GetName(i), oldRes,newRes);
                }

            }
            return sb.ToString();
        }
Exemplo n.º 19
0
        static string AsSqlInsert(System.Data.Common.DbDataReader result, string tableName)
        {
            var sb = new System.Text.StringBuilder();
            sb.AppendFormat ("INSERT INTO {0} (",tableName);

            for (int i = 0; i < result.FieldCount; i++)
            {
                sb.Append('\t' + result.GetName(i) + ",\r\n");
            }
            sb.Length -= 3; // remove last comma
            sb.Append(") VALUES (\r\n\t");
            object[] vals = new object[result.FieldCount];
            result.GetValues(vals);
            sb.Append(string.Join(",\r\n\t", vals.Select(ValueToSqlString)));
            sb.Append(')');
            return sb.ToString();
        }
Exemplo n.º 20
0
        public dynamic consulta(string query, bool tipoSelect = false)
        {
            dynamic consulta = null;

            try
            {
                conexion.Open();
                cmd = new NpgsqlCommand(query, conexion, transaccion);
                if (!tipoSelect)
                {
                    consulta = new List <Dictionary <string, object> >();
                    System.Data.Common.DbDataReader datos = cmd.ExecuteReader();
                    while (datos.Read())
                    {
                        Dictionary <string, object> objeto = new Dictionary <string, object>();
                        for (int x = 0; x < datos.FieldCount; x++)
                        {
                            objeto.Add(datos.GetName(x), datos.GetValue(x));
                        }
                        consulta.Add(objeto);
                    }
                }
                else
                {
                    cmd.ExecuteNonQuery();
                    transaccion.Rollback();
                    consulta = true;
                }
            }
            catch {
                if (transactionActivada)
                {
                    transactionActivada = false;
                    transaccion.Rollback();
                }
                conexion.Close();
                consulta = false;
            }
            conexion.Close();
            return(consulta);
        }
Exemplo n.º 21
0
        public List <string> getColumnas(string tabla)
        {
            List <string>   res            = new List <string>();
            string          consultaSelect = "SELECT TOP 1 * FROM " + tabla + ";";
            MySqlConnection conexion       = new MySqlConnection();

            conexion.ConnectionString = cadenaConexion;
            MySqlCommand comando = new MySqlCommand(consultaSelect, conexion);

            conexion.Open();
            System.Data.Common.DbDataReader reader = comando.ExecuteReader();

            reader.Read();
            for (int i = 0; i < reader.FieldCount; ++i)
            {
                res.Add(reader.GetName(i));
            }

            conexion.Close();
            return(res);
        }
Exemplo n.º 22
0
        private void AddReaderToGrid(BasePopupViewModel viewModel, System.Data.Common.DbDataReader dataReader)
        {
            DataTable dtSource = new DataTable();

            dtSource.TableName = "Data";

            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                DataColumn col = new DataColumn(dataReader.GetName(i), dataReader.GetFieldType(i));
                dtSource.Columns.Add(col);
            }
            while (dataReader.Read())
            {
                object[] values = new object[dataReader.FieldCount];
                dataReader.GetValues(values);
                dtSource.LoadDataRow(values, false);
            }
            dataReader.Close();

            AddControlsToGrid(viewModel, dtSource, "");
        }
Exemplo n.º 23
0
 static string AsSqlUpdate(System.Data.Common.DbDataReader result, string tableName)
 {
     var sb = new System.Text.StringBuilder();
     sb.AppendFormat("UPDATE {0} SET", tableName);
     int id=0;
     for (int i=0; i < result.FieldCount; i++)
     {
         string name = result.GetName(i);
         if (name=="Id")
         {
             id = result.GetInt32(i);
         }
         else
         {
             sb.AppendFormat("\r\n\t{0} = {1},", name, ValueToSqlString(result.GetValue(i)));
         }
         
     }
     sb.Length -= 1; // remove last comma
     sb.AppendFormat("\r\nWHERE Id = {0}\r\nGO\r\n", id);
     return sb.ToString();
 }
Exemplo n.º 24
0
        } // End Function responsiveTable

        public static void responsiveTable(string id, System.Data.Common.DbDataReader reader, System.Text.StringBuilder sb)
        {
            sb.AppendLine(@"<div id=""" + System.Web.HttpUtility.HtmlAttributeEncode(id) + @""" class=""table"">");
            sb.AppendLine(@"<div class=""Table-row Table-header"">");


            string[] columns = new string[reader.FieldCount];

            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns[i] = reader.GetName(i);

                sb.Append(@"<div class=""Table-row-item"">");
                sb.Append(System.Web.HttpUtility.HtmlEncode(columns[i]));
                sb.AppendLine("</div>"); // End Header-Cell
            } // Next i
            sb.AppendLine("</div>");     // End Header-Row


            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    sb.AppendLine(@"<div class=""Table-row"">");

                    //foreach (string columnName in columns)
                    for (int i = 0; i < columns.Length; ++i)
                    {
                        sb.Append(@"<div class=""Table-row-item"" data-header=""" + System.Web.HttpUtility.HtmlAttributeEncode(columns[i]) + @""">");
                        sb.Append(System.Web.HttpUtility.HtmlEncode(System.Convert.ToString(reader.GetValue(i))));
                        sb.AppendLine("</div>"); // End Cell
                    } // Next dc

                    sb.AppendLine("</div>"); // End Row
                } // Whend
            } // End if (reader.HasRows)

            sb.AppendLine("</div>"); // End Table
        } // End Sub responsiveTable
 public override string ToString()
 { // only used in the debugger
     if (names != null)
     {
         return(string.Join(", ", names));
     }
     if (reader != null)
     {
         var sb    = new StringBuilder();
         int index = startBound;
         for (int i = 0; i < length; i++)
         {
             if (i != 0)
             {
                 sb.Append(", ");
             }
             sb.Append(reader.GetName(index++));
         }
         return(sb.ToString());
     }
     return(base.ToString());
 }
        } // 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
Exemplo n.º 27
0
        public virtual QueryData Query(string query)
        {
            QueryData data = new QueryData();

            _command.CommandText = query;
            System.Data.Common.DbDataReader reader = _command.ExecuteReader();

            while (reader.Read())
            {
                Objects.DbObject row = new Objects.RowObject();
                for (int loop = 0; loop < reader.FieldCount; loop++)
                {
                    string name = reader.GetName(loop);
                    row.Data.Add(name, reader[loop]);
                }

                data.Add(row);
            }

            reader.Close();
            return(data);
        }
Exemplo n.º 28
0
        public static List <dynamic> DataReaderToDynamic(System.Data.Common.DbDataReader reader, out double runTime)
        {
            var            time    = DateTime.Now;
            List <dynamic> list    = new List <dynamic>();
            var            columns = new List <string>();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                columns.Add(reader.GetName(i));
            }

            while (reader.Read())
            {
                object[] values = new object[columns.Count];
                reader.GetValues(values);
                var d = getDataRow(columns, values);
                list.Add(d);
            }
            reader.Close();
            runTime = (DateTime.Now - time).TotalMilliseconds;
            return(list);
        }
Exemplo n.º 29
0
        }         // End Sub DataToXML

        public static void LargeDataToXML()
        {
            string table_schema = "geoip";
            string table_name   = "geoip_blocks_temp";

            // table_schema = "public";
            // table_name = "t_sys_language_monthnames";


            System.Xml.XmlWriterSettings xs = new System.Xml.XmlWriterSettings();
            xs.Indent             = true;
            xs.IndentChars        = "    ";
            xs.NewLineChars       = System.Environment.NewLine;
            xs.OmitXmlDeclaration = false; // // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            // xs.Encoding = System.Text.Encoding.UTF8; // doesn't work with pgsql
            xs.Encoding = new System.Text.UTF8Encoding(false);

            string exportFilename = System.IO.Path.Combine(@"d:\", table_name + ".xml");

            // System.Text.StringBuilder builder = new System.Text.StringBuilder();
            // using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(builder, xs))
            using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(exportFilename, xs))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement(table_name);

                writer.WriteAttributeString("xmlns", "xsi", null, System.Xml.Schema.XmlSchema.InstanceNamespace);
                // writer.WriteAttributeString("xsi", "schemaLocation", null, System.Xml.Schema.XmlSchema.InstanceNamespace);



                using (System.Data.Common.DbConnection con = Npgsql.NpgsqlFactory.Instance.CreateConnection())
                {
                    con.ConnectionString = GetCS();

                    using (System.Data.Common.DbCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT * FROM " + table_schema + "." + table_name;


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

                        using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
                        {
                            if (dr.HasRows)
                            {
                                int fc = dr.FieldCount;

                                string[] columnNames = new string[fc];
                                // System.Type[] columnTypes = new System.Type[fc];

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

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

                                    writer.WriteStartElement("record");

                                    for (int i = 0; i < fc; ++i)
                                    {
                                        writer.WriteStartElement(columnNames[i]);
                                        object obj = dr.GetValue(i);

                                        if (obj != System.DBNull.Value)
                                        {
                                            writer.WriteValue(obj);
                                        }
                                        else
                                        {
                                            writer.WriteAttributeString("xsi", "nil", System.Xml.Schema.XmlSchema.InstanceNamespace, "true");
                                        }

                                        writer.WriteEndElement();
                                    } // Next i

                                    writer.WriteEndElement();
                                } // Whend
                            }     // End if (dr.HasRows)
                        }         // End Using dr

                        if (con.State != System.Data.ConnectionState.Open)
                        {
                            con.Close();
                        }
                    } // End Using cmd
                }     // End Using con

                writer.WriteEndElement();
            } // ENd Using writer
        }     // End Sub LargeDataToXML
Exemplo n.º 30
0
        public static void LinqTest()
        {
            System.Collections.Generic.List <string> ls = new System.Collections.Generic.List <string>();
            ls.Add("foo");
            ls.Add("bar");
            ls.Add("foobar");

            int    oobj    = 123;
            Person someOne = new Person()
            {
                Name = "foo", Email = "*****@*****.**", SnailMail = "Snail"
            };
            // object inexistant = GetProperty(someOne, "Inexistant");

            object myName       = GetProperty(someOne, "Name");
            string myNameString = GetProperty <Person, string>(someOne, "Name");

            int?nullMe = GetProperty <Person, int?>(someOne, "NullableNumber");


            object nullNumObj = GetProperty(someOne, "NullableNumber");
            int?   nullNum    = GetProperty <Person, int?>(someOne, "NullableNumber");

            System.Console.WriteLine(nullNum);

            SetProperty(someOne, "NullableNumber", null);
            System.Console.WriteLine(someOne);

            SetProperty(someOne, "NullableNumber", -123);
            System.Console.WriteLine(someOne);

            SetProperty(someOne, "NullableNumber", "-123");
            System.Console.WriteLine(someOne);

            SetProperty(someOne, "NullableNumber", System.DBNull.Value);
            System.Console.WriteLine(someOne);


            // object obj = System.DBNull.Value;
            // SetProperty(someOne, "NullableNumber", obj);


            System.Console.WriteLine(myName);
            System.Console.WriteLine(myNameString);
            // SetProperty(someOne, "Anumber", oobj);
            // SetProperty(someOne, "SnailMail", "Turtle Mail");
            // SetProperty(someOne, "Email", "SpamMail");
            T_User ben = new T_User();

            int    cnt      = GetProperty <System.Collections.Generic.List <string>, int>(ls, "cOuNt");
            object objCount = GetProperty(ls, "cOuNt");

            System.Console.WriteLine(cnt);


            // b15186d6-adb1-4c8a-bbfa-830b24417e8b
            string SQL = @"SELECT 'B15186D6-ADB1-4C8A-BBFA-830B24417E8B' AS BE_UID, '123' AS BE_ID, 'Carbon Unit' AS BE_Name, '*****@*****.**' AS EMail, 'omg' AS SnailMail, CAST(NULL AS integer) AS NullableNumber;";

            // SQL = @"SELECT CAST(NULL AS uniqueidentifier) AS BE_UID"; // Test NULLing non-null type error message...

            using (System.Data.Common.DbDataReader rdr = null) // CoinBaseSharp.SQL.ExecuteReader(SQL))
            {
                do
                {
                    int           fieldCount = rdr.FieldCount;
                    System.Type[] ts         = new System.Type[fieldCount];
                    string[]      fieldNames = new string[fieldCount];
                    System.Action <T_User, object>[] fieldSetters = new System.Action <T_User, object> [fieldCount];

                    for (int i = 0; i < fieldCount; ++i)
                    {
                        ts[i]           = rdr.GetFieldType(i);
                        fieldNames[i]   = rdr.GetName(i);
                        fieldSetters[i] = GetSetter <T_User>(fieldNames[i]);
                    } // Next i


                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            for (int i = 0; i < fieldCount; ++i)
                            {
                                object objValue = rdr.GetValue(i);
                                // if (object.ReferenceEquals(objValue, System.DBNull.Value)) objValue = null;

                                System.Console.WriteLine(ts[i]);
                                //int abc = 123;
                                // SetProperty(ben, fieldNames[i], abc);
                                // SetProperty(ben, fieldNames[i], objValue);
                                fieldSetters[i](ben, objValue);
                                System.Console.WriteLine(objValue);
                            } // Next i
                        }     // Whend
                    }         // End if (rdr.HasRows)
                } while (rdr.NextResult());
            }                 // End Using rdr


            System.Console.WriteLine(ben.BE_UID);
        } // End Sub LinqTest