File: DataTableExtensions.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (280 lines) | stat: -rw-r--r-- 12,034 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//------------------------------------------------------------------------------
// <copyright file="DataTableExtenstions.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Linq.Expressions;
using System.Globalization;
using System.Diagnostics;
using System.Data.DataSetExtensions;

namespace System.Data
{

    /// <summary>
    /// This static class defines the DataTable extension methods.
    /// </summary>
    public static class DataTableExtensions
    {

        /// <summary>
        ///   This method returns a IEnumerable of Datarows.
        /// </summary>
        /// <param name="source">
        ///   The source DataTable to make enumerable.
        /// </param>
        /// <returns>
        ///   IEnumerable of datarows.
        /// </returns>
        public static EnumerableRowCollection<DataRow> AsEnumerable(this DataTable source)
        {
            DataSetUtil.CheckArgumentNull(source, "source");
            return new EnumerableRowCollection<DataRow>(source);
        }

        /// <summary>
        ///   This method takes an input sequence of DataRows and produces a DataTable object
        ///   with copies of the source rows.
        ///   Also note that this will cause the rest of the query to execute at this point in time
        ///   (e.g. there is no more delayed execution after this sequence operator).
        /// </summary>
        /// <param name="source">
        ///   The input sequence of DataRows
        /// </param>
        /// <returns>
        ///   DataTable containing copies of the source DataRows.
        ///   Properties for the DataTable table will be taken from first DataRow in the source.
        /// </returns>
        /// <exception cref="ArgumentNullException">if source is null</exception>
        /// <exception cref="InvalidOperationException">if source is empty</exception>
        public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
            where T : DataRow
        {
            DataSetUtil.CheckArgumentNull(source, "source");
            return LoadTableFromEnumerable(source, null, null, null);
        }

        /// <summary>
        ///   delegates to other CopyToDataTable overload with a null FillErrorEventHandler.
        /// </summary>
        public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options)
            where T : DataRow
        {
            DataSetUtil.CheckArgumentNull(source, "source");
            DataSetUtil.CheckArgumentNull(table, "table");
            LoadTableFromEnumerable(source, table, options, null);
        }


        /// <summary>
        ///   This method takes an input sequence of DataRows and produces a DataTable object
        ///   with copies of the source rows.
        ///   Also note that this will cause the rest of the query to execute at this point in time
        ///   (e.g. there is no more delayed execution after this sequence operator).
        /// </summary>
        /// <param name="source">
        ///   The input sequence of DataRows
        ///
        ///   CopyToDataTable uses DataRowVersion.Default when retrieving values from source DataRow
        ///   which will include proposed values for DataRow being edited.
        ///
        ///   Null DataRow in the sequence are skipped.
        /// </param>
        /// <param name="table">
        ///   The target DataTable to load.
        /// </param>
        /// <param name="options">
        ///   The target DataTable to load.
        /// </param>
        /// <param name="errorHandler">
        /// Error handler for recoverable errors.
        /// Recoverable errors include:
        ///     A source DataRow is in the deleted or detached state state.
        ///     DataTable.LoadDataRow threw an exception, i.e. wrong # of columns in source row
        /// Unrecoverable errors include:
        ///     exceptions from IEnumerator, DataTable.BeginLoadData or DataTable.EndLoadData
        /// </param>
        /// <returns>
        ///   DataTable containing copies of the source DataRows.
        /// </returns>
        /// <exception cref="ArgumentNullException">if source is null</exception>
        /// <exception cref="ArgumentNullException">if table is null</exception>
        /// <exception cref="InvalidOperationException">if source DataRow is in Deleted or Detached state</exception>
        public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options, FillErrorEventHandler errorHandler)
            where T : DataRow
        {
            DataSetUtil.CheckArgumentNull(source, "source");
            DataSetUtil.CheckArgumentNull(table, "table");
            LoadTableFromEnumerable(source, table, options, errorHandler);
        }

        private static DataTable LoadTableFromEnumerable<T>(IEnumerable<T> source, DataTable table, LoadOption? options, FillErrorEventHandler errorHandler)
            where T : DataRow
        {
            if (options.HasValue) {
                switch(options.Value) {
                    case LoadOption.OverwriteChanges:
                    case LoadOption.PreserveChanges:
                    case LoadOption.Upsert:
                        break;
                    default:
                        throw DataSetUtil.InvalidLoadOption(options.Value);
                }
            }


            using (IEnumerator<T> rows = source.GetEnumerator())
            {
                // need to get first row to create table
                if (!rows.MoveNext())
                {
                    if (table == null)
                    {
                        throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_EmptyDataRowSource);
                    }
                    else
                    {
                        return table;
                    }
                }

                DataRow current;
                if (table == null)
                {
                    current = rows.Current;
                    if (current == null)
                    {
                        throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_NullDataRow);
                    }

                    table = new DataTable();
                    table.Locale = CultureInfo.CurrentCulture;
                    // We do not copy the same properties that DataView.ToTable does.
                    // If user needs that functionality, use other CopyToDataTable overloads.
                    // The reasoning being, the IEnumerator<DataRow> can be sourced from
                    // different DataTable, so we just use the "Default" instead of resolving the difference.

                    foreach (DataColumn column in current.Table.Columns)
                    {
                        table.Columns.Add(column.ColumnName, column.DataType);
                    }
                }

                table.BeginLoadData();
                try
                {
                    do
                    {
                        current = rows.Current;
                        if (current == null)
                        {
                            continue;
                        }

                        object[] values = null;
                        try
                        {   // 'recoverable' error block
                            switch(current.RowState)
                            {
                                case DataRowState.Detached:
                                    if (!current.HasVersion(DataRowVersion.Proposed))
                                    {
                                        throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotLoadDetachedRow);
                                    }
                                    goto case DataRowState.Added;
                                case DataRowState.Unchanged:
                                case DataRowState.Added:
                                case DataRowState.Modified:
                                    values = current.ItemArray;
                                    if (options.HasValue)
                                    {
                                        table.LoadDataRow(values, options.Value);
                                    }
                                    else
                                    {
                                        table.LoadDataRow(values, true);
                                    }
                                    break;
                                case DataRowState.Deleted:
                                    throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotLoadDeletedRow);
                                default:
                                    throw DataSetUtil.InvalidDataRowState(current.RowState);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!DataSetUtil.IsCatchableExceptionType(e))
                            {
                                throw;
                            }

                            FillErrorEventArgs fillError = null;
                            if (null != errorHandler)
                            {
                                fillError = new FillErrorEventArgs(table, values);
                                fillError.Errors = e;
                                errorHandler.Invoke(rows, fillError);
                            }
                            if (null == fillError) {
                                throw;
                            }
                            else if (!fillError.Continue)
                            {
                                if (Object.ReferenceEquals(fillError.Errors ?? e, e))
                                {   // if user didn't change exception to throw (or set it to null)
                                    throw;
                                }
                                else
                                {   // user may have changed exception to throw in handler
                                    throw fillError.Errors;
                                }
                            }
                        }
                    } while (rows.MoveNext());
                }
                finally
                {
                    table.EndLoadData();
                }
            }
            Debug.Assert(null != table, "null DataTable");
            return table;
        }

        #region Methods to Create LinqDataView

        /// <summary>
        /// Creates a LinkDataView of DataRow over the input table.
        /// </summary>
        /// <param name="table">DataTable that the view is over.</param>
        /// <returns>An instance of LinkDataView.</returns>
        public static DataView AsDataView(this DataTable table)
        {
            DataSetUtil.CheckArgumentNull<DataTable>(table, "table");
            return new LinqDataView(table, null);
        }


        /// <summary>
        /// Creates a LinqDataView from EnumerableDataTable
        /// </summary>
        /// <typeparam name="T">Type of the row in the table. Must inherit from DataRow</typeparam>
        /// <param name="source">The enumerable-datatable over which view must be created.</param>
        /// <returns>Generated LinkDataView of type T</returns>
        public static DataView AsDataView<T>(this EnumerableRowCollection<T> source) where T : DataRow
        {
            DataSetUtil.CheckArgumentNull<EnumerableRowCollection<T>>(source, "source");
            return source.GetLinqDataView();
        }

        #endregion LinqDataView

    }
}