Exemplo n.º 1
0
        public void DisplayRows(DbDataReader nt)
        {
            this.listView1.Clear();

            for (int i = 0; i < nt.FieldCount; i++)
            {
                listView1.Columns.Add(nt.GetName(i));
            }
            int rowCount = 0;
            while (nt.NextResult())
            {
                rowCount++;
                string contents = "";

                if (nt[0] != null)
                {
                    contents = nt[0].ToString();
                }

                ListViewItem lvi = new ListViewItem(contents);
                for (int i = 1; i < nt.FieldCount; i++)
                {
                    contents = "";
                    if (nt[i] != null)
                    {
                        contents = nt[i].ToString();
                    }
                    lvi.SubItems.Add(contents);
                }
                this.listView1.Items.Add(lvi);
            }
            this.toolStripStatusLabel1.Text = rowCount.ToString() + " row(s) returned.";
        }
        protected override void Consume(DbDataReader reader)
        {
            Debug.Assert(CommandResultSet.Count == ModificationCommands.Count);
            var commandIndex = 0;

            try
            {
                var actualResultSetCount = 0;
                do
                {
                    while (commandIndex < CommandResultSet.Count
                           && CommandResultSet[commandIndex] == ResultSetMapping.NoResultSet)
                    {
                        commandIndex++;
                    }

                    if (commandIndex < CommandResultSet.Count)
                    {
                        commandIndex = ModificationCommands[commandIndex].RequiresResultPropagation
                            ? ConsumeResultSetWithPropagation(commandIndex, reader)
                            : ConsumeResultSetWithoutPropagation(commandIndex, reader);
                        actualResultSetCount++;
                    }
                }
                while (commandIndex < CommandResultSet.Count
                       && reader.NextResult());

#if DEBUG
                while (commandIndex < CommandResultSet.Count
                       && CommandResultSet[commandIndex] == ResultSetMapping.NoResultSet)
                {
                    commandIndex++;
                }

                Debug.Assert(commandIndex == ModificationCommands.Count,
                    "Expected " + ModificationCommands.Count + " results, got " + commandIndex);

                var expectedResultSetCount = CommandResultSet.Count(e => e == ResultSetMapping.LastInResultSet);

                Debug.Assert(actualResultSetCount == expectedResultSetCount,
                    "Expected " + expectedResultSetCount + " result sets, got " + actualResultSetCount);
#endif
            }
            catch (DbUpdateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DbUpdateException(
                    RelationalStrings.UpdateStoreException,
                    ex,
                    ModificationCommands[commandIndex].Entries);
            }
        }
Exemplo n.º 3
0
 /// <summary>
 ///     Consumes all rows and result sets from the reader. This allows client to retrieve
 ///     parameter values and intercept any store exceptions.
 /// </summary>
 /// <param name="reader"> Reader to consume. </param>
 internal static void ConsumeReader(DbDataReader reader)
 {
     if (null != reader
         && !reader.IsClosed)
     {
         while (reader.NextResult())
         {
             // Note that we only walk through the result sets. We don't need
             // to walk through individual rows (though underlying provider
             // implementation may do so)
         }
     }
 }
Exemplo n.º 4
0
 private static IEnumerable <T> ExecuteReaderSync <T>(IDataReader reader, Func <IDataReader, object> func, object parameters)
 {
     using (reader)
     {
         while (reader.Read())
         {
             yield return((T)func(reader));
         }
         while (reader.NextResult())
         {
         }
         (parameters as IParameterCallbacks)?.OnCompleted();
     }
 }
Exemplo n.º 5
0
 static int NextResult(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Data.Common.DbDataReader obj = (System.Data.Common.DbDataReader)ToLua.CheckObject(L, 1, typeof(System.Data.Common.DbDataReader));
         bool o = obj.NextResult();
         LuaDLL.lua_pushboolean(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
        protected override void Consume(DbDataReader reader, DbContext context)
        {
            Debug.Assert(ResultSetEnds.Count == ModificationCommands.Count);
            var commandIndex = 0;

            try
            {
                var actualResultSetCount = 0;
                do
                {
                    commandIndex = ModificationCommands[commandIndex].RequiresResultPropagation
                        ? ConsumeResultSetWithPropagation(commandIndex, reader, context)
                        : ConsumeResultSetWithoutPropagation(commandIndex, reader, context);
                    actualResultSetCount++;
                }
                while (commandIndex < ResultSetEnds.Count
                       && reader.NextResult());

                Debug.Assert(commandIndex == ModificationCommands.Count,
                    "Expected " + ModificationCommands.Count + " results, got " + commandIndex);
#if DEBUG
                var expectedResultSetCount = 1 + ResultSetEnds.Count(e => e);
                expectedResultSetCount += ResultSetEnds[ResultSetEnds.Count - 1] ? -1 : 0;

                Debug.Assert(actualResultSetCount == expectedResultSetCount,
                    "Expected " + expectedResultSetCount + " result sets, got " + actualResultSetCount);
#endif
            }
            catch (DbUpdateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DbUpdateException(
                    Strings.UpdateStoreException,
                    ex,
                    ModificationCommands[commandIndex].Entries);
            }
        }
Exemplo n.º 7
0
		ProfileInfoCollection BuildProfileInfoCollection (DbDataReader reader, out int totalRecords)
		{
			ProfileInfoCollection pic = new ProfileInfoCollection ();
			while (reader.Read ()) {
				ProfileInfo pi = ReadProfileInfo (reader);
				if (pi != null)
					pic.Add (pi);
			}
			totalRecords = 0;
			if (reader.NextResult ()) {
				if (reader.Read ())
					totalRecords = reader.GetInt32 (0);
			}
			return pic;
		}
        static void ReadDataMulti(DbDataReader reader)
        {
            var ctr = 1;
            while (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine(ctr == 1
                        ? string.Format("\nExpected - {0} , Got - {1}", "sfk shan", reader.Get<string>("Name")) //First result set - Employee
                        : string.Format("\nExpected - {0} , Got - {1}", "HR", reader.Get<string>("name")));//Second Result set - Department

                    break;
                }
                ctr++;
                reader.NextResult();
            }
            //Note : for test purpose it is skipped to iterate the rest rows
        }
        private void Convert_Facet_Tables_To_Facet_Lists(DbDataReader Reader, List<short> Facet_Types)
        {
            // Go to the next table
            if (!Reader.NextResult())
                return;

            // Incrementor going through tables (and skipping aggregation table maybe)
            if (Reader.FieldCount > 2)
            {
                // Read all the aggregation fields
                while (Reader.Read())
                {
                    Aggregation_Facets.Add(new Search_Facet_Aggregation(Reader.GetString(1), Reader.GetInt32(2), Reader.GetString(0)));
                }

                if (!Reader.NextResult())
                    return;
            }

            // Add all the other facets, reading each subsequent table in the results
            int current_facet_index = 0;
            do
            {
                // Build this facet list
                if ((Reader.FieldCount == 2) && (Facet_Types.Count > current_facet_index))
                {
                    // Create the collection and and assifn the metadata type id
                    Search_Facet_Collection thisCollection = new Search_Facet_Collection(Facet_Types[current_facet_index]);

                    // Read all the individual facet values
                    while (Reader.Read())
                    {
                        thisCollection.Facets.Add(new Search_Facet(Reader.GetString(0), Reader.GetInt32(1)));
                    }

                    // If there was an id and facets added, save this to the search statistics
                    if ((thisCollection.MetadataTypeID > 0) && (thisCollection.Facets.Count > 0))
                    {
                        Facet_Collections.Add(thisCollection);
                    }
                }

                current_facet_index++;
            } while (Reader.NextResult());
        }
Exemplo n.º 10
0
		/// <summary>
		/// Execute a command against a data source, mapping the data reader GetSchemaTable() result to an enumerable of resultsets, each with an enumerable of records dictionaries.
		/// This method perfoms LAZY LOADING/DEFERRED EXECUTION.
		/// </summary>
		/// <param name="dbDataReader"> The target data reader. </param>
		/// <returns> An enumerable of resultset instances, each containing an enumerable of dictionaries with record key/value pairs of schema metadata. </returns>
		public IEnumerable<IResultset> GetSchemaResultsetsFromReader(DbDataReader dbDataReader)
		{
			int resultsetIndex = 0;

			OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): enter", typeof(AdoNetStreamingFascade).Name));

			if ((object)dbDataReader == null)
				throw new ArgumentNullException(nameof(dbDataReader));

			OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): before yield", typeof(AdoNetStreamingFascade).Name));

			using (dbDataReader)
			{
				OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): use reader", typeof(AdoNetStreamingFascade).Name));

				do
				{
					Resultset resultset = new Resultset(resultsetIndex++); // prevent modified closure
					resultset.Records = this.GetSchemaRecordsFromReader(dbDataReader, (ra) => resultset.RecordsAffected = ra);

					OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): on yield", typeof(AdoNetStreamingFascade).Name));

					yield return resultset; // LAZY PROCESSING INTENT HERE / DO NOT FORCE EAGER LOAD
				}
				while (dbDataReader.NextResult());

				OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): dispose reader", typeof(AdoNetStreamingFascade).Name));
			}

			OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): after yield", typeof(AdoNetStreamingFascade).Name));

			OnlyWhen._PROFILE_ThenPrint(string.Format("{0}::GetSchemaResultsetsFromReader(...): leave", typeof(AdoNetStreamingFascade).Name));
		}
        private static List<iSearch_Title_Result> DataReader_To_Simple_Result_List2(DbDataReader Reader, List<string> MetadataFieldNames)
        {
            // Create return list
            List<iSearch_Title_Result> returnValue = new List<iSearch_Title_Result>();

            // Create some lists used during the construction
            Dictionary<int, Database_Title_Result> titleLookupByRowNumber = new Dictionary<int, Database_Title_Result>();
            Dictionary<int, Database_Item_Result> itemLookupByItemID = new Dictionary<int, Database_Item_Result>();
            Dictionary<int, int> rowNumberLookupByItemID = new Dictionary<int, int>();

            // May have not values returned
            if (Reader.FieldCount < 5)
                return null;

            // Get all the main title values first
            int minimumRownumber = -1;
            while (Reader.Read())
            {
                // Create new database title object for this
                Database_Title_Result result = new Database_Title_Result
                {
                    RowNumber = Reader.GetInt32(0),
                    BibID = Reader.GetString(1),
                    GroupTitle = Reader.GetString(2),
                    OPAC_Number = Reader.GetInt32(3),
                    OCLC_Number = Reader.GetInt64(4),
                    GroupThumbnail = Reader.GetString(5),
                    MaterialType = Reader.GetString(6),
                    Primary_Identifier_Type = Reader.GetString(7),
                    Primary_Identifier = Reader.GetString(8)
                };

                titleLookupByRowNumber.Add(result.RowNumber, result);

                if (minimumRownumber == -1)
                {
                    minimumRownumber = result.RowNumber;
                }
            }

            // Move to the item system-required information table
            Reader.NextResult();

            // If there were no titles, then there are no results
            if (titleLookupByRowNumber.Count == 0)
                return returnValue;

            // Step through all the item rows, build the item, and add to the title
            Database_Title_Result titleResult = titleLookupByRowNumber[minimumRownumber];
            returnValue.Add(titleResult);
            int lastRownumber = titleResult.RowNumber;
            while (Reader.Read())
            {
                // Ensure this is the right title for this item
                int thisRownumber = Reader.GetInt32(0);
                if (thisRownumber != lastRownumber)
                {
                    titleResult = titleLookupByRowNumber[thisRownumber];
                    lastRownumber = thisRownumber;

                    // Add this title to the list
                    returnValue.Add(titleResult);
                }

                // Create new database item object for this
                Database_Item_Result result = new Database_Item_Result
                {
                    ItemID = Reader.GetInt32(1),
                    VID = Reader.GetString(2),
                    Title = Reader.GetString(3),
                    IP_Restriction_Mask = Reader.GetInt16(4),
                    MainThumbnail = Reader.GetString(5),
                    Level1_Index = (short)Reader.GetInt32(6),
                    Level1_Text = Reader.GetString(7),
                    Level2_Index = (short)Reader.GetInt32(8),
                    Level2_Text = Reader.GetString(9),
                    Level3_Index = (short)Reader.GetInt32(10),
                    Level3_Text = Reader.GetString(11),
                    PubDate = Reader.GetString(12),
                    PageCount = Reader.GetInt32(13),
                    Link = Reader.GetString(14),
                    Spatial_KML = Reader.GetString(15),
                    COinS_OpenURL = Reader.GetString(16)
                };

                // Save to the hash lookup for adding display metadata
                itemLookupByItemID[result.ItemID] = result;
                rowNumberLookupByItemID[result.ItemID] = thisRownumber;

                // Add this to the title object
                titleResult.Add_Item_Result(result);
            }

            // Move to the item aggregation-configured display information table
            Reader.NextResult();

            // Set some values for checking for uniformity of values
            const int ITEMS_TO_CHECK_IN_EACH_TITLE = 20;
            bool first_item_analyzed = true;
            List<bool> checking_fields = new List<bool>();
            int display_fields_count = 0;
            int itemcount = 0;
            int lastRowNumber = -1;
            while (Reader.Read())
            {
                // Get the item id and then work back to the local title id
                int itemId = Reader.GetInt32(0);
                int rowNumber = rowNumberLookupByItemID[itemId];

                // If this is the very first item analyzed, need to do some work first
                if (first_item_analyzed)
                {
                    // Save the number of display fields
                    display_fields_count = Reader.FieldCount - 1;

                    // Add a boolean for each display field
                    for (int i = 0; i < display_fields_count; i++)
                    {
                        // Add the default boolean value here
                        checking_fields.Add(true);

                        // Save the metadata label
                        MetadataFieldNames.Add(Reader.GetName(i + 1));
                    }

                    // Done with the first row analysis, so ensure it does not repeat
                    first_item_analyzed = false;
                }

                // Is this is the start of a new title row?
                if (lastRowNumber != rowNumber)
                {
                    // Get this title object
                    titleResult = titleLookupByRowNumber[rowNumber];

                    // Set items analyzed for this title to zero
                    itemcount = 0;

                    // Back to checking each metadata field since this is a new title
                    for (int i = 0; i < display_fields_count; i++)
                        checking_fields[i] = true;

                    // Save this row numbe as the last row number analyzed
                    lastRowNumber = rowNumber;
                }

                if (itemcount == 0)
                {
                    // Set all the initial display values (at the title level) from
                    // this item's display information
                    titleResult.Metadata_Display_Values = new string[display_fields_count];
                    for (int i = 0; i < display_fields_count; i++)
                    {
                        titleResult.Metadata_Display_Values[i] = Reader.GetString(i + 1);
                    }
                }
                else if (itemcount < ITEMS_TO_CHECK_IN_EACH_TITLE)
                {
                    // Compare the values attached with each display piece of metadata
                    // from the title with this additional, individual item.  If the
                    // values are the same, it should display at the title level, but
                    // if they are different, we will not display the values at that level
                    for (int i = 0; i < display_fields_count; i++)
                    {
                        // If we already found a mismatch for this metadata field, then
                        // no need to continue checking
                        if (checking_fields[i])
                        {
                            if (String.Compare(titleResult.Metadata_Display_Values[i], Reader.GetString(i + 1), StringComparison.InvariantCultureIgnoreCase) != 0)
                            {
                                titleResult.Metadata_Display_Values[i] = "*";
                                checking_fields[i] = false;
                            }
                        }
                    }
                }
            }

            return returnValue;
        }
        private static List<Private_Items_List_Title> DataReader_To_Private_Items_List(DbDataReader Reader)
        {
            // Create return list
            List<Private_Items_List_Title> returnValue = new List<Private_Items_List_Title>();

            Dictionary<int, int> lookup = new Dictionary<int, int>();

            // Get all the main title values first
            while (Reader.Read())
            {
                // Create new database title object for this
                Private_Items_List_Title result = new Private_Items_List_Title
                {
                    RowNumber = Reader.GetInt32(0),
                    BibID = Reader.GetString(1),
                    Group_Title = Reader.GetString(2),
                    Type = Reader.GetString(3),
                    LastActivityDate = Reader.GetDateTime(6),
                    LastMilestoneDate = Reader.GetDateTime(7),
                    CompleteItemCount = Reader.GetInt32(8),
                    PrimaryIdentifierType = Reader.GetString(9),
                    PrimaryIdentifier = Reader.GetString(10)
                };

                returnValue.Add(result);

                lookup.Add(result.RowNumber, returnValue.Count - 1);
            }

            // Move to the item table
            Reader.NextResult();

            // If there were no titles, then there are no results
            if (returnValue.Count == 0)
                return returnValue;

            // Step through all the item rows, build the item, and add to the title
            Private_Items_List_Title titleResult = returnValue[0];
            int lastRownumber = titleResult.RowNumber;
            while (Reader.Read())
            {
                // Ensure this is the right title for this item
                int thisRownumber = Reader.GetInt32(0);
                if (thisRownumber != lastRownumber)
                {
                    titleResult = returnValue[lookup[thisRownumber]];
                    lastRownumber = thisRownumber;
                }

                // Create new database item object for this
                Private_Items_List_Item result = new Private_Items_List_Item
                {
                    VID = Reader.GetString(1),
                    Title = Reader.GetString(2),
                    LocallyArchived = Reader.GetBoolean(5),
                    RemotelyArchived = Reader.GetBoolean(6),
                    AggregationCodes = Reader.GetString(7),
                    LastActivityDate = Reader.GetDateTime(8),
                    LastActivityType = Reader.GetString(9),
                    LastMilestone = Reader.GetInt32(10),
                    LastMilestoneDate = Reader.GetDateTime(11)
                };

                // Pull the values that are nullable
                string comments = Reader.GetString(3);
                string pubdate = Reader.GetString(4);

                string creator = Reader.GetString(19);

                // Assign the values if there are values
                if (comments.Length > 0) result.Internal_Comments = comments;
                if (pubdate.Length > 0) result.PubDate = pubdate;
                if (creator.Length > 0) result.Creator = creator;

                // Assign the embargo end
                if (!Reader.IsDBNull(18))
                {
                    DateTime embargoEnd = Reader.GetDateTime(18);
                    if (embargoEnd.Year < 9999)
                        result.EmbargoDate = embargoEnd;
                }

                // Add this to the title object
                titleResult.Add_Item_Result(result);
            }

            return returnValue;
        }
Exemplo n.º 13
0
        // 输出 RML 格式的表格
        // 本函数负责写入 <table> 元素
        // parameters:
        //      nTopLines   顶部预留多少行
        void OutputRmlTable(
            DbDataReader data_reader,
            XmlTextWriter writer,
            int nMaxLines = -1)
        {
            // StringBuilder strResult = new StringBuilder(4096);
            int i, j;

#if NO
            if (nMaxLines == -1)
                nMaxLines = table.Count;
#endif

            writer.WriteStartElement("table");
            WriteAttributeString(writer, "class", "table");

            writer.WriteStartElement("thead");
            writer.WriteStartElement("tr");

            int nEvalCount = 0; // 具有 eval 的栏目个数
            for (j = 0; j < this.Columns.Count; j++)
            {
                PrintColumn000 column = this.Columns[j];
                if (column.Colspan == 0)
                    continue;

                if (string.IsNullOrEmpty(column.Eval) == false)
                    nEvalCount++;

                writer.WriteStartElement("th");
                if (string.IsNullOrEmpty(column.CssClass) == false)
                    WriteAttributeString(writer, "class", column.CssClass);
                if (column.Colspan > 1)
                    WriteAttributeString(writer, "colspan", column.Colspan.ToString());

                WriteString(writer, column.Title);
                writer.WriteEndElement();   // </th>
            }

            writer.WriteEndElement();   // </tr>
            writer.WriteEndElement();   // </thead>

            // 合计数组
            object[] sums = null;   // 2008/12/1 new changed

            if (this.SumLine)
            {
                sums = new object[this.Columns.Count];
                for (i = 0; i < sums.Length; i++)
                {
                    sums[i] = null;
                }
            }

            NumberFormatInfo nfi = new CultureInfo("zh-CN", false).NumberFormat;
            nfi.NumberDecimalDigits = 2;

            writer.WriteStartElement("tbody");

            // Jurassic.ScriptEngine engine = null;
            if (nEvalCount > 0 && engine == null)
            {
                engine = new Jurassic.ScriptEngine();
                engine.EnableExposedClrTypes = true;
            }

            int nLineCount = 0;

            // 内容行循环
            for (i = 0; ; i++)  // i < Math.Min(nMaxLines, table.Count)
            {
                if (data_reader.Read() == false)
                {
                    if (data_reader.NextResult() == false)
                        break;

                    if (data_reader.Read() == false)
                        break;
                }

                nLineCount++;
#if NO
                if (table.HasRows == false)
                    break;
#endif
                // Line line = table[i];

                if (engine != null)
                {
                    engine.SetGlobalValue("line", data_reader);
                }

                string strLineCssClass = "content";
#if NO
                if (report.OutputLine != null)
                {
                    OutputLineEventArgs e = new OutputLineEventArgs();
                    e.Line = line;
                    e.Index = i;
                    e.LineCssClass = strLineCssClass;
                    report.OutputLine(this, e);
                    if (e.Output == false)
                        continue;

                    strLineCssClass = e.LineCssClass;
                }
#endif

                // strResult.Append("<tr class='" + strLineCssClass + "'>\r\n");
                writer.WriteStartElement("tr");
                WriteAttributeString(writer, "class", strLineCssClass);

                // 列循环
                for (j = 0; j < this.Columns.Count; j++)
                {
                    PrintColumn000 column = this.Columns[j];

                    if (column.ColumnNumber < -1)
                    {
                        throw (new Exception("PrintColumn对象ColumnNumber列尚未初始化,位置" + Convert.ToString(j)));
                    }

                    string strText = "";
                    if (column.ColumnNumber != -1)
                    {
                        // Debug.Assert(column.ColumnNumber < data_reader.FieldCount, "");

                        if (string.IsNullOrEmpty(column.Eval) == false)
                        {
                            // engine.SetGlobalValue("cell", line.GetObject(column.ColumnNumber));
                            engine.SetGlobalValue("rowNumber", nLineCount.ToString());
                            engine.SetGlobalValue("currency", new PriceUtil());
                            strText = engine.Evaluate(column.Eval).ToString();
                        }
                        else if (column.DataType == ColumnDataType.PriceDouble)
                        {
                            if (data_reader.IsDBNull(column.ColumnNumber) == true)
                                strText = column.DefaultValue;
                            else
                            {
                                double v = data_reader.GetDouble(column.ColumnNumber);
                                /*
                                NumberFormatInfo provider = new NumberFormatInfo();
                                provider.NumberDecimalDigits = 2;
                                provider.NumberGroupSeparator = ".";
                                provider.NumberGroupSizes = new int[] { 3 };
                                strText = Convert.ToString(v, provider);
                                 * */
                                strText = v.ToString("N", nfi);
                            }
                        }
                        else if (column.DataType == ColumnDataType.PriceDecimal)
                        {
                            if (data_reader.IsDBNull(column.ColumnNumber) == true)
                                strText = column.DefaultValue;
                            else
                            {
                                decimal v = data_reader.GetDecimal(column.ColumnNumber);
                                strText = v.ToString("N", nfi);
                            }
                        }
                        else if (column.DataType == ColumnDataType.PriceDecimal)
                        {
                            if (data_reader.IsDBNull(column.ColumnNumber) == true)
                                strText = column.DefaultValue;
                            else
                            {
                                decimal v = data_reader.GetDecimal(column.ColumnNumber);
                                strText = v.ToString("N", nfi);
                            }
                        }
                        else if (column.DataType == ColumnDataType.Price)
                        {
                            // Debug.Assert(false, "");
                            if (data_reader.IsDBNull(column.ColumnNumber) == true)
                                strText = column.DefaultValue;	// 2005/5/26
                            else
                                strText = data_reader.GetString(column.ColumnNumber);    // 
                        }
                        else if (column.DataType == ColumnDataType.String)
                        {
                            // strText = data_reader.GetString(column.ColumnNumber/*, column.DefaultValue*/);
                            // 2014/8/28
                            object o = data_reader.GetValue(column.ColumnNumber);
                            if (o != null)
                                strText = o.ToString();
                            else
                                strText = "";
                        }
                        else
                        {
                            object o = data_reader.GetValue(column.ColumnNumber);
                            if (o != null)
                                strText = o.ToString();
                            else
                                strText = "";
                        }
                    }
                    else
                    {
                        strText = data_reader.GetString(0);   // line.Entry;
                    }

                    writer.WriteStartElement(j == 0 ? "th" : "td");
                    if (string.IsNullOrEmpty(column.CssClass) == false)
                        WriteAttributeString(writer, "class", column.CssClass);
                    WriteString(writer, strText);
                    writer.WriteEndElement();   // </td>

                    if (this.SumLine == true
                        && column.Sum == true
                        && column.ColumnNumber != -1)
                    {
                        try
                        {
                            // if (column.DataType != DataType.Currency)
                            {
                                object v = null;

                                if (column.ColumnNumber < data_reader.FieldCount)
                                    v = data_reader.GetValue(column.ColumnNumber);
#if NO
                                if (report.SumCell != null)
                                {
                                    SumCellEventArgs e = new SumCellEventArgs();
                                    e.DataType = column.DataType;
                                    e.ColumnNumber = column.ColumnNumber;
                                    e.LineIndex = i;
                                    e.Line = line;
                                    e.Value = v;
                                    report.SumCell(this, e);
                                    if (e.Value == null)
                                        continue;

                                    v = e.Value;
                                }
#endif

                                if (sums[j] == null)
                                    sums[j] = v;
                                else
                                {
                                    sums[j] = AddValue(column.DataType,
            sums[j],
            v);
                                    // sums[j] = ((decimal)sums[j]) + v;
                                }
                            }
                        }
                        catch (Exception ex)	// 俘获可能因字符串转换为整数抛出的异常
                        {
                            throw new Exception("在累加 行 " + i.ToString() + " 列 " + column.ColumnNumber.ToString() + " 值的时候,出现异常: " + ExceptionUtil.GetAutoText(ex));
                        }
                    }
                }

                // strResult.Append("</tr>\r\n");
                writer.WriteEndElement();   // </tr>
            }

            writer.WriteEndElement();   // </tbody>

            if (this.SumLine == true)
            {
                SumLineReader sum_line = null;
                if (engine != null)
                {
                    // 准备 Line 对象
                    sum_line = new SumLineReader();
                    sum_line.FieldValues = sums;
                    sum_line.Read();
#if NO
                    for (j = 1; j < this.Columns.Count; j++)
                    {
                        PrintColumn000 column = this.Columns[j];
                        if (column.Sum == true
                            && sums[j] != null)
                        {
                            sum_line.SetValue(j - 1, sums[j]);
                        }
                    }
#endif
                    engine.SetGlobalValue("line", sum_line);
                    engine.SetGlobalValue("rowNumber", "");
                }

                // strResult.Append("<tr class='sum'>\r\n");
                writer.WriteStartElement("tfoot");
                writer.WriteStartElement("tr");
                WriteAttributeString(writer, "class", "sum");

                for (j = 0; j < this.Columns.Count; j++)
                {
                    PrintColumn000 column = this.Columns[j];
                    string strText = "";

                    if (j == 0)
                        strText = "合计(" + nLineCount.ToString() + "行)";
                    else if (column.Sum == true)
                    {
                        if (string.IsNullOrEmpty(column.Eval) == false)
                        {
                            engine.SetGlobalValue("currency", new PriceUtil());
                            strText = engine.Evaluate(column.Eval).ToString();
                        }
                        else if (column.Sum == true
                            && sums[j] != null)
                        {
                            if (column.DataType == ColumnDataType.PriceDouble)
                                strText = ((double)sums[j]).ToString("N", nfi);
                            else if (column.DataType == ColumnDataType.PriceDecimal)
                                strText = ((decimal)sums[j]).ToString("N", nfi);
                            else if (column.DataType == ColumnDataType.Price)
                            {
                                strText = StatisUtil.Int64ToPrice((Int64)sums[j]);
                            }
                            else
                                strText = Convert.ToString(sums[j]);

                            if (column.DataType == ColumnDataType.Currency)
                            {
                                string strSomPrice = "";
                                string strError = "";
                                // 汇总价格
                                int nRet = PriceUtil.SumPrices(strText,
                out strSomPrice,
                out strError);
                                if (nRet == -1)
                                    strText = strError;
                                else
                                    strText = strSomPrice;
                            }
                        }
                        else
                            strText = column.DefaultValue;  //  "&nbsp;";

                    }

#if NO
                    doc.WriteExcelCell(
    _lineIndex,
    j,
    strText,
    true);
#endif
                    writer.WriteStartElement(j == 0 ? "th" : "td");
                    if (string.IsNullOrEmpty(column.CssClass) == false)
                        WriteAttributeString(writer, "class", column.CssClass);
                    WriteString(writer, strText);
                    writer.WriteEndElement();   // </td>
                }

                // strResult.Append("</tr>\r\n");
                writer.WriteEndElement();   // </tr>
                writer.WriteEndElement();   // </tfoot>
            }

            writer.WriteEndElement();   // </table>
        }
        private static void WriteResult(XmlWriter writer, DbDataReader reader)
        {
            string ns = AdoNetAdapter.MESSAGENAMESPACE;

            writer.WriteStartElement("InboundData", ns);

            do
            {
                writer.WriteStartElement("ResultSet", ns);

                while (reader.Read())
                {
                    writer.WriteStartElement("Row", ns);

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        if (!reader.IsDBNull(i))
                        {
                            writer.WriteStartElement(reader.GetName(i), ns);

                            object value = reader[i];
                            var serializer = new DataContractSerializer(value.GetType());
                            objectSerializer.WriteObjectContent(writer, value);

                            writer.WriteEndElement();
                        }
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            } while (reader.NextResult());

            writer.WriteEndElement();
        }
Exemplo n.º 15
0
        /// <summary>
        /// 由于DataSet得灵活性,提供了一个将DataReader转换为DataSet的工具方法
        /// </summary>
        /// <param name="reader">DbDataReader对象</param>
        /// <returns>DataSet</returns>
        public static DataSet ConvertDataReaderToDataSet(DbDataReader reader)
        {
			ExceptionHelper.TrueThrow<ArgumentNullException>(reader == null, "reader");

            DataSet dataSet = new DataSet();
			dataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;

            do
            {
				DataTable schemaTable = reader.GetSchemaTable();
                DataTable dataTable = new DataTable();

                if (schemaTable != null)
                {
                    // A query returning records was executed
                    for (int i = 0; i < schemaTable.Rows.Count; i++)
                    {
                        DataRow dataRow = schemaTable.Rows[i];
                        // Create a column name that is unique in the data table
                        string columnName = (string)dataRow["ColumnName"]; //+ "<C" + i + "/>";
                        // Add the column definition to the data table
                        DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                        dataTable.Columns.Add(column);
                    }
                    dataSet.Tables.Add(dataTable);
                    // Fill the data table we just created
                    //try
                    //{
                        while (reader.Read())
                        {
                            DataRow dataRow = dataTable.NewRow();
                            for (int i = 0; i < reader.FieldCount; i++)
                                dataRow[i] = reader.GetValue(i);
                            dataTable.Rows.Add(dataRow);
                        }
                    //}
                    //catch(Exception exception)
                    //{
                    //    TraceException(exception);
                    //}
                }
                else
                {
                    // No records were returned
                    DataColumn column = new DataColumn("RowsAffected");
                    dataTable.Columns.Add(column);
                    dataSet.Tables.Add(dataTable);
                    DataRow dataRow = dataTable.NewRow();
                    dataRow[0] = reader.RecordsAffected;
                    dataTable.Rows.Add(dataRow);
                }
            }
            while (reader.NextResult());
            return dataSet;
        }