System.Data.DataTable.NewRow()

Here are the examples of the csharp api System.Data.DataTable.NewRow() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

564 Examples 7

19 Source : DataCubeParameter.cs
with GNU General Public License v3.0
from DeepHydro

public override DataTable ToDataTable()
        {
            DataTable dt = new DataTable();
            if (Dimension == 1)
            {
                DataColumn dc = new DataColumn(this.Name, typeof(T));
                dt.Columns.Add(dc);
                for (int i = 0; i < Size[1]; i++)
                {
                    var dr = dt.NewRow();
                    dr[0] = this[0, i, 0];
                    dt.Rows.Add(dr);
                }
            }
            else if (Dimension == 2)
            {
                for (int i = 0; i < Size[2]; i++)
                {
                    DataColumn dc = new DataColumn(DimensionNames[1] + (i + 1), typeof(T));
                    dt.Columns.Add(dc);
                }
                for (int i = 0; i < Size[1]; i++)
                {
                    var dr = dt.NewRow();
                    for (int j = 0; j < Size[2]; j++)
                    {
                        dr[j] = this[0, i, j];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

19 Source : SingleParam.cs
with GNU General Public License v3.0
from DeepHydro

public override System.Data.DataTable ToDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn(Name, typeof(T));
            dt.Columns.Add(dc);

            var dr = dt.NewRow();
            dr[0] = Value;
            dt.Rows.Add(dr);

            return dt;
        }

19 Source : BasinBudgetMonitor.cs
with GNU General Public License v3.0
from DeepHydro

public override DataTable Balance(ref string report)
        {
            if (DataSource != null)
            {
                _EntireBudgereplacedems.Clear();

                var len = DataSource.Values[0].Count;
                if (EndStep <= 0)
                    EndStep = len;

                if (EndStep > len)
                    EndStep = len;

                if (StartStep > len)
                    StartStep = len;

                if (StartStep >= EndStep)
                    StartStep = 0;

                report = "SUMMARY VOLUMETRIC BUDGET";
                DataTable dt = new DataTable();
                double nsteps = EndStep - StartStep + 1;
                double factor = Intevals / nsteps;
                double total_in = 0;
                double total_out = 0;
                double total_ds = 0;
                double total_diff = 0;
                double total_error = 0;
              
                string equal = " = ";
                int width_term = 30;
                int width_number = 30;
                var scale = Intevals / ModelService.BasinArea * 1000;

                DataColumn dc = new DataColumn("ID", Type.GetType("System.Int32"));
                dt.Columns.Add(dc);
                dc = new DataColumn("ParentID", Type.GetType("System.Int32"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Item", Type.GetType("System.String"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Volumetric_Flow", Type.GetType("System.Double"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Water_Depth", Type.GetType("System.Double"));
                dt.Columns.Add(dc);

                var items = (from item in _Roots[0].Children where item.Group == _In_Group select item).ToArray();
                report += "\r\nIN TERMS";
                report += "\r\n------------";

                foreach (var item in items)
                {
                    var flow = Math.Round((DataSource.Values[item.VariableIndex][EndStep - 1] - DataSource.Values[item.VariableIndex][StartStep - 1]) * factor, DecimalDigit);
                    var dr = dt.NewRow();
                    dr[0] = item.VariableIndex;
                    dr[1] = 100;
                    dr[2] = item.Name;
                    dr[3] = flow;
                    var wd = Math.Round(flow / ModelService.BasinArea * 1000, DecimalDigit);
                    dr[4] = wd;
                    dt.Rows.Add(dr);
                    total_in += flow;
                    _EntireBudgereplacedems.Add(item.Name, wd);
                }

                report += "\r\n-";
                report += "\r\n-";
                items = (from item in _Roots[0].Children where item.Group == _Out_Group select item).ToArray();
                report += "\r\nOUT TERMS";
                report += "\r\n-----------------";
                foreach (var item in items)
                {
                    var flow = Math.Round((DataSource.Values[item.VariableIndex][EndStep - 1] - DataSource.Values[item.VariableIndex][StartStep - 1]) * factor, DecimalDigit);
                    var dr = dt.NewRow();
                    dr[0] = item.VariableIndex;
                    dr[1] = 200;
                    dr[2] = item.Name;
                    dr[3] = flow;
                    var wd = Math.Round(flow / ModelService.BasinArea * 1000, DecimalDigit);
                    dr[4] = wd;
                    dt.Rows.Add(dr);
                    total_out += flow;
                    _EntireBudgereplacedems.Add(item.Name, wd);
                }

                report += "\r\n-";
                report += "\r\n-";
                items = (from item in _Roots[0].Children where item.Group == _Ds_Group select item).ToArray();
                report += "\r\nSTORAGE CHANGE TERMS";
                report += "\r\n------------------------------------";
                var uzf_ds = 0.0;
                foreach (var item in items)
                {
                    var flow = Math.Round((DataSource.Values[item.VariableIndex][EndStep - 1] - DataSource.Values[item.VariableIndex][StartStep - 1]) * factor, DecimalDigit);
                    var dr = dt.NewRow();
                    dr[0] = item.VariableIndex;
                    dr[1] = 300;
                    dr[2] = item.Name;
                    dr[3] = flow;
                    var wd = Math.Round(flow / ModelService.BasinArea * 1000, DecimalDigit);
                    dr[4] = wd;
                    dt.Rows.Add(dr);

                    total_ds += flow;
                    if (item.Name == Unsaturated_Zone_DS)
                        uzf_ds = flow;

                    _EntireBudgereplacedems.Add(item.Name, wd);
                }

                total_diff = total_in - total_out;
                total_error = total_diff - total_ds;

                total_discrepancy = Math.Round((total_in - total_out - total_ds) / (total_in + total_out + Math.Abs(total_ds)) * 2 * 100, DecimalDigit);

                var dr_totalin = dt.NewRow();
                dr_totalin[0] = 100;
                dr_totalin[1] = 9999;
                dr_totalin[2] = "Total In";
                dr_totalin[3] = total_in;
                dr_totalin[4] = Math.Round(total_in / ModelService.BasinArea * 1000, DecimalDigit);
                dt.Rows.Add(dr_totalin);

                var dr_totalout = dt.NewRow();
                dr_totalout[0] = 200;
                dr_totalout[1] = 9999;
                dr_totalout[2] = "Total Out";
                dr_totalout[3] = total_out;
                dr_totalout[4] = Math.Round(total_out / ModelService.BasinArea * 1000, DecimalDigit);
                dt.Rows.Add(dr_totalout);

                var dr_totalds = dt.NewRow();
                dr_totalds[0] = 300;
                dr_totalds[1] = 9999;
                dr_totalds[2] = Total_Storage_Change;
                dr_totalds[3] = total_ds;
                dr_totalds[4] = Math.Round(total_ds / ModelService.BasinArea * 1000, DecimalDigit);
                dt.Rows.Add(dr_totalds);


                var dr_total_error = dt.NewRow();
                dr_total_error[0] = 400;
                dr_total_error[1] = 9999;
                dr_total_error[2] = "Budget Error";
                dr_total_error[3] = total_discrepancy;
                dt.Rows.Add(dr_total_error);

                var dr_in_out_diff = dt.NewRow();
                dr_in_out_diff[0] = 401;
                dr_in_out_diff[1] = 400;
                dr_in_out_diff[2] = "Inflows - Outflows";
                dr_in_out_diff[3] = total_diff;
                dr_in_out_diff[4] = Math.Round(total_diff / ModelService.BasinArea * 1000, DecimalDigit);
                dt.Rows.Add(dr_in_out_diff);

                var dr_error = dt.NewRow();
                dr_error[0] = 402;
                dr_error[1] = 400;
                dr_error[2] = "Overall Budget Error";
                dr_error[3] = total_error;
                dr_error[4] = Math.Round(total_error / ModelService.BasinArea * 1000, DecimalDigit);
                dt.Rows.Add(dr_error);

                var dr_percent = dt.NewRow();
                dr_percent[0] = 403;
                dr_percent[1] = 400;
                dr_percent[2] = "Percent Discrepancy";
                dr_percent[3] = total_discrepancy;
                dt.Rows.Add(dr_percent);

                var wd_ds = Math.Round(total_ds / ModelService.BasinArea * 1000, DecimalDigit);
                _EntireBudgereplacedems.Add(Total_Storage_Change, wd_ds);
                report += "\r\nBUDGET SUMMERY";
                report += "\r\n--------------";
                report += "\r\nTOTAL IN".PadLeft(width_term, ' ') + equal + total_in.ToString().PadLeft(width_number, ' ');
                report += "\r\nTOTAL OUT".PadLeft(width_term, ' ') + equal + total_out.ToString().PadLeft(width_number, ' ');
                report += "\r\nTOTAL STORAGE CHANGE".PadLeft(width_term, ' ') + equal + total_ds.ToString().PadLeft(width_number, ' ');

                report += "\r\nBUDGET ERROR";
                report += "\r\n--------------";
                report += "\r\nINFLOWS - OUTFLOWS".PadLeft(width_term, ' ') + equal + total_diff.ToString().PadLeft(width_number, ' ');
                report += "\r\nOVERALL BUDGET ERROR".PadLeft(width_term, ' ') + equal + total_error.ToString().PadLeft(width_number, ' ');
                report += "\r\nPERCENT DISCREPANCY".PadLeft(width_term, ' ') + equal + total_discrepancy.ToString().PadLeft(width_number, ' ');


                return dt;
            }
            else
            {
                return null;
            }
        }

19 Source : TxtFileStream.cs
with GNU General Public License v3.0
from DeepHydro

public DataTable LoadAsTable()
        {
            DataTable dt = new DataTable();
            StreamReader sr = new StreamReader(_Filename);
            var datatype = Type.GetType("System.Single");
            string line = sr.ReadLine().Trim();
            var buf = TypeConverterEx.Split<string>(line);
            if (buf != null)
            {
                if (TypeConverterEx.IsNumeric(buf[0]))
                {
                    for (int i = 0; i < buf.Length; i++)
                    {
                        DataColumn dc = new DataColumn("A" + i, datatype);
                        dt.Columns.Add(dc);
                    }
                }
                else
                {
                    for (int i = 0; i < buf.Length; i++)
                    {
                        DataColumn dc = new DataColumn(buf[i], datatype);
                        dt.Columns.Add(dc);
                    }
                }
                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine().Trim();
                    if (!TypeConverterEx.IsNull(line))
                    {
                        var dr = dt.NewRow();
                        var vec = TypeConverterEx.Split<float>(line);
                        if(vec.Length == dt.Columns.Count)
                        {
                            for(int i=0; i<vec.Length;i++)
                            {
                                dr[i] = vec[i];
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

19 Source : ArrayParam.cs
with GNU General Public License v3.0
from DeepHydro

public override System.Data.DataTable ToDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn(Name, typeof(T));
            dt.Columns.Add(dc);
            for (int i = 0; i < ValueCount; i++)
            {
                var dr = dt.NewRow();
                dr[0] = Values[i];
                dt.Rows.Add(dr);
            }
            return dt;
        }

19 Source : PackageCoverage.cs
with GNU General Public License v3.0
from DeepHydro

public void LoadLookTable()
        {
            if (File.Exists(FullLookupTableFileName))
            {
                NewLookupTable();
                _RowIndex.Clear();
                LookupTable<float> lt = new LookupTable<float>();
                lt.NoValue = -9999;
                lt.FromTextFile(FullLookupTableFileName);
                for (int i = 0; i < lt.RowNames.Length; i++)
                {
                    var dr = LookupTable.NewRow();
                    dr[_ID_COL_NAME] = lt.RowNames[i];
                    foreach (var ap in ArealProperties)
                    {
                        if (lt.ColNames.Contains(ap.AliasName))
                        {
                            dr[ap.AliasName] = lt.GetValue(ap.AliasName, i);
                        }
                        else
                        {
                            dr[ap.AliasName] = ap.DefaultValue;
                        }
                    }
                    _RowIndex.Add(double.Parse(lt.RowNames[i]), i);
                    LookupTable.Rows.Add(dr);
                }
            }
        }

19 Source : CSVFileStream.cs
with GNU General Public License v3.0
from DeepHydro

public DataTable Load()
        {
            DataTable dtCsv = new DataTable();
            using (StreamReader sr = new StreamReader(_Filename))
            {
                var line = sr.ReadLine();
                string[] rowValues = line.Split(','); //split each row with comma to get individual values  
                for (int j = 0; j < rowValues.Count(); j++)
                {
                    dtCsv.Columns.Add(rowValues[j]); //add headers  
                }
                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                    if (TypeConverterEx.IsNotNull(line))
                    {
                        rowValues = line.Split(','); //split each row with comma to get individual values  
                        DataRow dr = dtCsv.NewRow();
                        for (int k = 0; k < rowValues.Count(); k++)
                        {
                            dr[k] = rowValues[k].ToString();
                        }
                        dtCsv.Rows.Add(dr); //add other rows  
                    }
                }
            }

            return dtCsv;
        }

19 Source : MonitorItem.cs
with GNU General Public License v3.0
from DeepHydro

public virtual DataTable ToDataTable(ListTimeSeries<double> sourcedata)
        {
            DataTable dt = new DataTable();
            DataColumn date_col = new DataColumn("Date", Type.GetType("System.DateTime"));
            dt.Columns.Add(date_col);
            DataColumn value_col = new DataColumn(this.Name, Type.GetType("System.Double"));
            dt.Columns.Add(value_col);
            double[] buf = null;
            if (Derivable)
            {
                if (this.DerivedValues == null)
                    this.DerivedValues = this.Derive(sourcedata);
                buf = this.DerivedValues;
            }
            else
            {
                buf = sourcedata.Values[this.VariableIndex].ToArray();
            }
            for (int i = 0; i < buf.Length; i++)
            {
                var dr = dt.NewRow();
                dr[0] = sourcedata.Dates[i];
                dr[1] = buf[i];
                dt.Rows.Add(dr);
            }
            return dt;
        }

19 Source : MonitorItemCollection.cs
with GNU General Public License v3.0
from DeepHydro

public override System.Data.DataTable ToDataTable(ListTimeSeries<double> sourcedata)
        {
            int c = 0;
            DataTable dt = new DataTable();
            DataColumn date_col = new DataColumn("Date", Type.GetType("System.DateTime"));
            dt.Columns.Add(date_col);
            foreach(var item in Children)
            {
                DataColumn value_col = new DataColumn(item.Name, Type.GetType("System.Double"));
                dt.Columns.Add(value_col);
                if (item.Derivable && item.DerivedValues == null)
                    item.DerivedValues = item.Derive(sourcedata);
            }

            for (int i = 0; i < sourcedata.Dates.Count; i++)
            {                
                var dr = dt.NewRow();
                dr[0] = sourcedata.Dates[i];
                c = 1;
                foreach (var item in Children)
                {
                    if (item.Derivable)
                        dr[c] = item.DerivedValues[i];
                    else
                        dr[c] = sourcedata.Values[item.VariableIndex][i];  
                    c++;
                }
           
                dt.Rows.Add(dr);
            }
            return dt;
        }

19 Source : DataCubeWorkspace.cs
with GNU General Public License v3.0
from DeepHydro

public DataTable ToDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("ID", Type.GetType("System.Int32"));
            dt.Columns.Add(dc);
            dc = new DataColumn("ParentID", Type.GetType("System.Int32"));
            dt.Columns.Add(dc);
            dc = new DataColumn("Name", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("Size", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("Owner", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("ImageName", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("DataCubeObject", typeof(IDataCubeObject));
            dt.Columns.Add(dc);
            int i = 100;
            foreach (var ds in DataSources)
            {
                int j = 0;
                DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = 9999;
                dr[2] = ds.Name;
                dr[3] = ds.SizeString();
                dr[4] = ds.OwnerName;
                dr[5] = "ready";
                dr[6] = ds;
                dt.Rows.Add(dr);
                
                foreach (var vv in ds.Variables)
                {
                    DataRow dr1 = dt.NewRow();
                    dr1[0] = j;
                    dr1[1] = i;
                    dr1[2] = vv;
                    dr1[3] = string.Format("[1][{0}][{1}]", ds.Size[1], ds.Size[2]);// TODO
                    dr1[4] = ds.OwnerName;
                    dr1[5] = ds.IsAllocated(j) ? "ready" : "standby";
                    dr1[6] = ds;
                    dt.Rows.Add(dr1);
                    j++;
                }
                i++;
            }
            return dt;
        }

19 Source : TemporalSimpleStatistics.cs
with GNU General Public License v3.0
from DeepHydro

public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int var_index = 0;
            var mat = Get3DMat(Source, ref var_index);
            double prg = 0;
            int count = 1;
            if (mat != null)
            {
                DataTable dt = new DataTable();

                DataColumn dc_time = new DataColumn("DateTime", Type.GetType("System.DateTime"));
                dt.Columns.Add(dc_time);
                DataColumn dc = new DataColumn("Mean", Type.GetType("System.Double"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Variance", Type.GetType("System.Double"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Skewness", Type.GetType("System.Double"));
                dt.Columns.Add(dc);
                dc = new DataColumn("Kurtosis", Type.GetType("System.Double"));
                dt.Columns.Add(dc);

                int nstep = mat.Size[1];
                double mean = 0, variance = 0, skewness = 0, kurtosis = 0;
                List<int> list_selected = new List<int>();
                bool use_selected = false;
                //   selected_index = null;

                if (BaseTimeStep >= 0 && BaseTimeStep < mat.Size[0])
                {
                    var vec = mat[var_index, BaseTimeStep.ToString(), ":"];
                    for (int i = 0; i < vec.Length; i++)
                    {
                        if (vec[i] != NoDataValue)
                            list_selected.Add(i);
                    }
                    use_selected = true;
                }
                for (int i = 0; i < nstep; i++)
                {
                    var dr = dt.NewRow();
                    var vec = mat[var_index, i.ToString(), ":"];
                    double[] vec_selected = null;
                    if (use_selected)
                    {
                        vec_selected = new double[list_selected.Count];
                        for(int  j=0;j<list_selected.Count;j++)
                        {
                            vec_selected[j] = vec[list_selected[j]];
                        }
                    }
                    else
                    {
                        var dou_vec = Array.ConvertAll<float, double>(vec, s => s);
                        vec_selected = dou_vec.Where(s => s != NoDataValue).ToArray();
                    }
                    Heiflow.Core.Alglib.alglib.basestat.samplemoments(vec_selected, vec_selected.Length, ref mean, ref variance, ref skewness, ref kurtosis);
                    dr[0] = DateTime.Now;
                    dr[1] = mean;
                    dr[2] = variance;
                    dr[3] = skewness;
                    dr[4] = kurtosis;
                    dt.Rows.Add(dr);
                    prg = (i + 1) * 100.0 / nstep;
                    if (prg > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", (int)prg, "Time Step:" + dr[0].ToString());
                        count++;
                    }
                }

                if (mat.DateTimes != null)
                {
                    for (int i = 0; i < nstep; i++)
                    {
                        dt.Rows[i][0] = mat.DateTimes[i];
                    }
                }
                else
                {
                    for (int i = 0; i < nstep; i++)
                    {
                        dt.Rows[i][0] = DateTime.Now.AddDays(i);
                    }
                }
                WorkspaceView.OutputTo(dt);
                return true;
            }
            else
            {

                return false;
            }
        }

19 Source : DashboardStorageWithAccessRules.cs
with Apache License 2.0
from DevExpress

string AddDashboardCore(XDoreplacedent dashboard, string dashboardName) {
            DataRow newRow = dashboards.Tables[0].NewRow();
            newRow[nameColumn] = dashboardName;
            newRow[dashboardLayoutColumn] = dashboard; 
            dashboards.Tables[0].Rows.Add(newRow);
            return newRow[dashboardIDColumn].ToString();
        }

19 Source : DataSetReader.cs
with MIT License
from DevZest

private static DataTable GetSchemaTableFromDataSet(DataSet dataSet)
        {
            Debug.replacedert(dataSet != null);

            DataTable dataTable = new DataTable("SchemaTable");
            dataTable.Locale = CultureInfo.InvariantCulture;
            DataColumn columnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(string));
            DataColumn columnOrdinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int));
            DataColumn columnSize = new DataColumn(SchemaTableColumn.ColumnSize, typeof(int));
            DataColumn numericPrecision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short));
            DataColumn numericScale = new DataColumn(SchemaTableColumn.NumericScale, typeof(short));
            DataColumn dataType = new DataColumn(SchemaTableColumn.DataType, typeof(Type));
            DataColumn providerType = new DataColumn(SchemaTableColumn.ProviderType, typeof(int));
            DataColumn isLong = new DataColumn(SchemaTableColumn.IsLong, typeof(bool));
            DataColumn allowDbNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool));
            DataColumn isReadOnly = new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool));
            DataColumn isUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(bool));
            DataColumn isKey = new DataColumn(SchemaTableColumn.IsKey, typeof(bool));
            DataColumn isAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool));
            DataColumn baseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string));
            DataColumn baseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(string));
            DataColumn baseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string));
            DataColumn autoIncrementSeed = new DataColumn(SchemaTableOptionalColumn.AutoIncrementSeed, typeof(long));
            DataColumn autoIncrementStep = new DataColumn(SchemaTableOptionalColumn.AutoIncrementStep, typeof(long));
            DataColumn defaultValue = new DataColumn(SchemaTableOptionalColumn.DefaultValue, typeof(object));
            columnSize.DefaultValue = -1;
            isLong.DefaultValue = false;
            isReadOnly.DefaultValue = false;
            isKey.DefaultValue = false;
            isAutoIncrement.DefaultValue = false;
            autoIncrementSeed.DefaultValue = 0;
            autoIncrementStep.DefaultValue = 1;
            dataTable.Columns.Add(columnName);
            dataTable.Columns.Add(columnOrdinal);
            dataTable.Columns.Add(columnSize);
            dataTable.Columns.Add(numericPrecision);
            dataTable.Columns.Add(numericScale);
            dataTable.Columns.Add(dataType);
            dataTable.Columns.Add(providerType);
            dataTable.Columns.Add(isLong);
            dataTable.Columns.Add(allowDbNull);
            dataTable.Columns.Add(isReadOnly);
            dataTable.Columns.Add(isUnique);
            dataTable.Columns.Add(isKey);
            dataTable.Columns.Add(isAutoIncrement);
            dataTable.Columns.Add(baseSchemaName);
            dataTable.Columns.Add(baseTableName);
            dataTable.Columns.Add(baseColumnName);
            dataTable.Columns.Add(autoIncrementSeed);
            dataTable.Columns.Add(autoIncrementStep);
            dataTable.Columns.Add(defaultValue);

            var model = dataSet.Model;
            foreach (var column in model.Columns)
            {
                var dataRow = dataTable.NewRow();
                dataRow[columnName] = column.Name;
                dataRow[columnOrdinal] = column.Ordinal;
                dataRow[dataType] = GetFieldType(column);
                dataRow[allowDbNull] = column.IsNullable;
                dataRow[isReadOnly] = column.IsExpression || column.IsIdenreplacedy;
                dataRow[isUnique] = column.IsUnique;
                if (column.IsIdenreplacedy)
                {
                    dataRow[isAutoIncrement] = true;
                    var idenreplacedy = column.GetIdenreplacedy(false);
                    Debug.replacedert(idenreplacedy != null);
                    dataRow[autoIncrementSeed] = idenreplacedy.Seed;
                    dataRow[autoIncrementStep] = idenreplacedy.Increment;
                }
                var columnDefaultValue = column.GetDefaultValue();
                if (columnDefaultValue != null)
                    dataRow[defaultValue] = columnDefaultValue;
                dataRow[baseColumnName] = column.Name;
                dataTable.Rows.Add(dataRow);
            }

            IReadOnlyList<Column> primaryKey = model.PrimaryKey;
            if (primaryKey != null)
            {
                foreach (var column in primaryKey)
                    dataTable.Rows[column.Ordinal][isKey] = true;
            }
            dataTable.AcceptChanges();
            return dataTable;
        }

19 Source : Util.cs
with GNU General Public License v3.0
from DineshSolanki

public static void AddToPickedListDataTable(DataTable dataTable, string poster, string replacedle, string rating,
            string fullFolderPath, string folderName, string year = "")
        {
            if (rating == "0")
            {
                rating = "";
            }

            var nRow = dataTable.NewRow();
            nRow["Poster"] = poster;
            nRow["replacedle"] = replacedle;
            nRow["Year"] = year;
            nRow["Rating"] = rating;
            nRow["Folder"] = fullFolderPath;
            nRow["FolderName"] = folderName;
            dataTable.Rows.Add(nRow);
        }

19 Source : XMLLayer.cs
with MIT License
from Dirkster99

private DataSet ConvertFromModelToDataSet(IEngine engine)
		{
			DataSet mDataSet = new DataSet();
			DataTable dataTable = null;
			AlternativeDataTypeHandler handle = new AlternativeDataTypeHandler();

			foreach (var optionsGroup in engine.GetOptionGroups())
			{
				// Create a new table (per Option group) and add a data row
				dataTable = CreateTable(optionsGroup);

				mDataSet.Tables.Add(dataTable);
				DataRow row = dataTable.NewRow();

				// Fill data row with data to be stored
				foreach (var optionDefinition in optionsGroup.GetOptionDefinitions())
				{
					var handler = handle.FindHandler(optionDefinition.TypeOfValue);

					if (optionDefinition.SchemaType == OptionSchemaType.SingleValue)
					{
						if (handler != null)
							row[optionDefinition.OptionName] = handler.Convert(optionDefinition.Value as SecureString);
						else
							row[optionDefinition.OptionName] = optionDefinition.Value;
					}
					else
					{
						// Create a unique id-able name for this list item and then create the list item table with that name
						var tableName = CreateLisreplacedemTableName(optionsGroup, optionDefinition);
						var listTable = CreateListTable(tableName, optionDefinition, handler, row);

						mDataSet.Tables.Add(listTable);

						////ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint(optionsGroup.Name + "_" + optionDefinition.OptionName + "_FK",
						////                                                            listTable.Columns[optionDefinition.OptionName],
						////                                                            dataTable.Columns[optionDefinition.OptionName]);
						////custOrderFK.DeleteRule = Rule.None;
						////
						////// Cannot delete a customer value that has replacedociated existing orders.
						////dataTable.Constraints.Add(custOrderFK);
					}
				}

				// Check if last data row has data and add it with table in collection, if so
				if (row.ItemArray.Count() > 0)
				{
					dataTable.Rows.Add(row);
				}
			}

			return mDataSet;
		}

19 Source : XMLLayer.cs
with MIT License
from Dirkster99

private static DataTable CreateListTable(string tableName,
												 IOptionsSchema columnSchema,
												 IAlternativeDataTypeHandler handler,
												 DataRow masterRow)
		{
			DataTable dataTable = new DataTable(tableName);

			DataColumn col = new DataColumn(columnSchema.OptionName,
											(columnSchema.TypeOfValue == typeof(SecureString) ? typeof(string) :
																								columnSchema.TypeOfValue));

			col.AllowDBNull = columnSchema.IsOptional;
			dataTable.Columns.Add(col);

			////var list = columnSchema.Value as IEnumerable<object>;

			bool IsFirstRow = true;

			foreach (var item in columnSchema.List_GetListOfValues())
			{
				if (IsFirstRow == true)
				{
					IsFirstRow = false;

					// Initialize row for caller this must be non-null to make it storeable
					if (handler != null)
						masterRow[columnSchema.OptionName] = handler.Convert(item as SecureString);
					else
						masterRow[columnSchema.OptionName] = item;
				}


				var row = dataTable.NewRow();

				if (handler != null)
					row[columnSchema.OptionName] = handler.Convert(item as SecureString);
				else
					row[columnSchema.OptionName] = item;

				dataTable.Rows.Add(row);
			}

			return dataTable;
		}

19 Source : XMLLayer.cs
with MIT License
from Dirkster99

private DataSet ConvertFromModelToDataSet(IEngine engine)
        {
            DataSet mDataSet = new DataSet();
            DataTable dataTable = null;
            AlternativeDataTypeHandler handle = new AlternativeDataTypeHandler();

            foreach (var optionsGroup in engine.GetOptionGroups())
            {
                // Create a new table (per Option group) and add a data row
                dataTable = CreateTable(optionsGroup);

                mDataSet.Tables.Add(dataTable);
                DataRow row = dataTable.NewRow();

                // Fill data row with data to be stored
                foreach (var optionDefinition in optionsGroup.GetOptionDefinitions())
                {
                    var handler = handle.FindHandler(optionDefinition.TypeOfValue);

                    if (optionDefinition.SchemaType == OptionSchemaType.SingleValue)
                    {
                        if (handler != null)
                            row[optionDefinition.OptionName] = handler.Convert(optionDefinition.Value as SecureString);
                        else
                            row[optionDefinition.OptionName] = optionDefinition.Value;
                    }
                    else
                    {
                        // Create a unique id-able name for this list item and then create the list item table with that name
                        var tableName = CreateLisreplacedemTableName(optionsGroup, optionDefinition);
                        var listTable = CreateListTable(tableName, optionDefinition, handler, row);

                        mDataSet.Tables.Add(listTable);

                        ////ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint(optionsGroup.Name + "_" + optionDefinition.OptionName + "_FK",
                        ////                                                            listTable.Columns[optionDefinition.OptionName],
                        ////                                                            dataTable.Columns[optionDefinition.OptionName]);
                        ////custOrderFK.DeleteRule = Rule.None;
                        ////
                        ////// Cannot delete a customer value that has replacedociated existing orders.
                        ////dataTable.Constraints.Add(custOrderFK);
                    }
                }

                // Check if last data row has data and add it with table in collection, if so
                if (row.ItemArray.Count() > 0)
                {
                    dataTable.Rows.Add(row);
                }
            }

            return mDataSet;
        }

19 Source : XMLLayer.cs
with MIT License
from Dirkster99

private static DataTable CreateListTable(string tableName,
                                                 IOptionsSchema columnSchema,
                                                 IAlternativeDataTypeHandler handler,
                                                 DataRow masterRow)
        {
            DataTable dataTable = new DataTable(tableName);

            DataColumn col = new DataColumn(columnSchema.OptionName,
                                            (columnSchema.TypeOfValue == typeof(SecureString) ? typeof(string) :
                                                                                                columnSchema.TypeOfValue));

            col.AllowDBNull = columnSchema.IsOptional;
            dataTable.Columns.Add(col);

            ////var list = columnSchema.Value as IEnumerable<object>;

            bool IsFirstRow = true;

            foreach (var item in columnSchema.List_GetListOfValues())
	        {
                if (IsFirstRow == true)
                {
                    IsFirstRow = false;

                    // Initialize row for caller this must be non-null to make it storeable
                    if (handler != null)
                        masterRow[columnSchema.OptionName] = handler.Convert(item as SecureString);
                    else
                        masterRow[columnSchema.OptionName] = item;
                }
                
                
                var row = dataTable.NewRow();

                    if (handler != null)
                        row[columnSchema.OptionName] = handler.Convert(item as SecureString);
                    else
                        row[columnSchema.OptionName] = item;

                    dataTable.Rows.Add(row);
	        }

            return dataTable;
        }

19 Source : XMLLayer.cs
with MIT License
from Dirkster99

private static DataTable CreateListTable(string tableName,
												 IOptionsSchema columnSchema,
												 IAlternativeDataTypeHandler handler,
												 DataRow masterRow)
		{
			DataTable dataTable = new DataTable(tableName);

			DataColumn col = new DataColumn(columnSchema.OptionName,
											(columnSchema.TypeOfValue == typeof(SecureString) ? typeof(string) :
																								columnSchema.TypeOfValue));

			col.AllowDBNull = columnSchema.IsOptional;
			dataTable.Columns.Add(col);

			////var list = columnSchema.Value as IEnumerable<object>;

			bool IsFirstRow = true;

			foreach (var item in columnSchema.List_GetListOfValues())
			{
				if (IsFirstRow == true)
				{
					IsFirstRow = false;

					// Initialize row for caller this must be non-null to make it storeable
					if (handler != null)
						masterRow[columnSchema.OptionName] = handler.Convert(item as SecureString);
					else
						masterRow[columnSchema.OptionName] = item;
				}

				var row = dataTable.NewRow();

				if (handler != null)
					row[columnSchema.OptionName] = handler.Convert(item as SecureString);
				else
					row[columnSchema.OptionName] = item;

				dataTable.Rows.Add(row);
			}

			return dataTable;
		}

19 Source : DataControls.cs
with MIT License
from dotnet

private void DataControls_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Id");
            dt.Columns.Add("Desc");
            for (int i = 0; i < 20; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "Jack" + i.ToString();
                dr[1] = i * 10;
                dr[2] = "I like" + i.ToString();
                dt.Rows.Add(dr);
            }

            //this.dataGridView2.DataSource = dt;

            bindingSource1.DataSource = dt;
            dataGridView2.DataSource = bindingSource1;
            bindingNavigator1.BindingSource = bindingSource1;

            dataGridView1.Rows[0].Cells[0].Value = "Rose";
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.BeginEdit(false);
            DataGridViewComboBoxEditingControl cbox = dataGridView1.EditingControl as DataGridViewComboBoxEditingControl;
            if (cbox != null)
                cbox.DroppedDown = true;
        }

19 Source : DataBindingExample.cs
with MIT License
from dotnet

public DataSet CreateDataSet()
        {
            DataSet stuDS = new DataSet();
            DataTable stuTable = new DataTable("Students");

            stuTable.Columns.Add("StuName", typeof(string));
            stuTable.Columns.Add("StuSex", typeof(string));
            stuTable.Columns.Add("StuAge", typeof(int));

            DataRow stuRow = stuTable.NewRow();
            stuRow["StuName"] = "sofie";
            stuRow["StuSex"] = "male";
            stuRow["StuAge"] = 21;
            stuTable.Rows.Add(stuRow);

            stuRow = stuTable.NewRow();
            stuRow["StuName"] = "Jrain";
            stuRow["StuSex"] = "Female";
            stuRow["StuAge"] = 21;
            stuTable.Rows.Add(stuRow);

            stuRow = stuTable.NewRow();
            stuRow["StuName"] = "Lida";
            stuRow["StuSex"] = "male";
            stuRow["StuAge"] = 21;
            stuTable.Rows.Add(stuRow);
            stuDS.Tables.Add(stuTable);

            return stuDS;
        }

19 Source : BindingNavigatorTests.cs
with MIT License
from dotnet

private BindingSource GetTestBindingSource(int rowsCount)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");

            for (int i = 0; i < rowsCount; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = $"User{i}";
                dr[1] = i * 3;
                dt.Rows.Add(dr);
            }

            return new() { DataSource = dt };
        }

19 Source : ExcelExporter_Tests.cs
with MIT License
from dotnetcore

private static DataTable EnreplacedyToDataTable<T>(DataTable dt, IEnumerable<T> enreplacedies)
        {
            if (!enreplacedies.Any()) return dt;

            var properties = typeof(T).GetProperties();

            foreach (var enreplacedy in enreplacedies)
            {
                var dr = dt.NewRow();

                foreach (var property in properties)
                    if (dt.Columns.Contains(property.Name))
                        dr[property.Name] = property.GetValue(enreplacedy, null);

                dt.Rows.Add(dr);
            }

            return dt;
        }

19 Source : BulkExtensions.cs
with Apache License 2.0
from dotnetcore

public static DataTable ToDataTable<TEnreplacedy>(this IEnumerable<TEnreplacedy> list)
        {
            var tableName = EnreplacedyMetaDataCache<TEnreplacedy>.TableName;
            var dataTable = new DataTable(tableName);
            foreach (var columnIndex in EnreplacedyMetaDataCache<TEnreplacedy>.IndexColumnMaps)
            {
                if (columnIndex.Value.GetPropertyValue == null)
                {
                    continue;
                }

                DataColumn dataColumn = new DataColumn(columnIndex.Value.Name, columnIndex.Value.FieldType);
                dataTable.Columns.Add(dataColumn);
            }

            foreach (var enreplacedy in list)
            {
                var dataRow = dataTable.NewRow();
                foreach (var columnIndex in EnreplacedyMetaDataCache<TEnreplacedy>.IndexColumnMaps)
                {
                    if (columnIndex.Value.GetPropertyValue == null)
                    {
                        continue;
                    }
                    var propertyVal = columnIndex.Value.GetPropertyValue(enreplacedy);
                    if (columnIndex.Value.Handler != null)
                    {
                        dataRow[columnIndex.Key] = columnIndex.Value.Handler.GetSetParameterValue(propertyVal);
                    }
                    else
                    {
                        dataRow[columnIndex.Key] = propertyVal ?? DBNull.Value;
                    }
                }

                dataTable.Rows.Add(dataRow);
            }

            return dataTable;
        }

19 Source : ParseGroupByCount.cs
with Apache License 2.0
from eaglet2006

private Hubble.Framework.Data.DataTable GroupByFromDatabase()
        {
            string whereSql;

            if (_ExpressionTree == null)
            {
                whereSql = "";
            }
            else
            {
                whereSql = "where " + _ExpressionTree.SqlText;
            }

            StringBuilder sb = new StringBuilder();

            string fields = "";
            int i = 0;

            foreach(Field field in _GroupByFields)
            {
                if (i++ == 0)
                {
                    fields += field.Name;
                }
                else
                {
                    fields += "," + field.Name;
                }
            }

            string sql = string.Format("select {0} , count(*) as Count from {1} {2} group by {0} order by count desc",
                fields, _DBProvider.Table.DBTableName, whereSql);

            System.Data.DataTable src = _DBProvider.DBAdapter.QuerySql(sql).Tables[0];
            System.Data.DataTable table = src.Clone();

            table.MinimumCapacity = src.Rows.Count;
            int top = _Top;

            if (top < 0)
            {
                top = int.MaxValue;
            }

            i = 0;
            while (top > 0 && i < src.Rows.Count)
            {
                System.Data.DataRow row = table.NewRow();

                for (int j = 0; j < table.Columns.Count; j++)
                {
                    row[j] = src.Rows[i][j];
                }

                table.Rows.Add(row);

                i++;
                top--;
            }

            table.TableName = "GroupByCount_" + _GroupByFieldsString;
            

            return new Hubble.Framework.Data.DataTable(table);
        }

19 Source : DataTable.cs
with Apache License 2.0
from eaglet2006

public System.Data.DataTable ConvertToSystemDataTable()
        {
            System.Data.DataTable result = new System.Data.DataTable(this.TableName);
            result.MinimumCapacity = this.MinimumCapacity;

            foreach (DataColumn col in this.Columns)
            {
                result.Columns.Add(new System.Data.DataColumn(col.ColumnName, col.DataType));
            }

            foreach (DataRow hRow in this.Rows)
            {
                System.Data.DataRow row = result.NewRow();

                for (int i = 0; i < this.Columns.Count; i++)
                {
                    row[i] = hRow[i];
                }

                result.Rows.Add(row);
            }

            return result;
        }

19 Source : SQLite3Adapter.cs
with Apache License 2.0
from eaglet2006

public void Insert1(IList<Hubble.Core.Data.Doreplacedent> docs)
        {
            if (docs.Count <= 0)
            {
                return;
            }

            System.Data.DataTable table = new System.Data.DataTable();

            using (SQLiteDataProvider sqlData = new SQLiteDataProvider())
            {
                sqlData.Connect(Table.ConnectionString);

                System.Data.DataColumn col = new System.Data.DataColumn("DocId", typeof(int));
                table.Columns.Add(col);

                foreach (Data.FieldValue fv in docs[0].FieldValues)
                {
                    col = new System.Data.DataColumn(fv.FieldName, DataTypeConvert.GetClrType(fv.Type));

                    table.Columns.Add(col);
                }


                foreach (Hubble.Core.Data.Doreplacedent doc in docs)
                {
                    System.Data.DataRow row = table.NewRow();

                    row[0] = doc.DocId;

                    int i = 1;

                    foreach (Data.FieldValue fv in doc.FieldValues)
                    {
                        row[i] = System.ComponentModel.TypeDescriptor.GetConverter(table.Columns[i].DataType).ConvertFrom(fv.Value);
                        i++;
                    }

                    table.Rows.Add(row);
                }

                table.TableName = _Table.DBTableName;

                sqlData.SaveDataTable(table);
            }
        }

19 Source : DirFileHelper.cs
with MIT License
from ecjtuseclab

public static DataRow[] GetFilesByTime(string path, string Extension)
        {
            if (Directory.Exists(path))
            {
                string fielExts = string.Format("*{0}", Extension);
                string[] files = Directory.GetFiles(path, fielExts);
                if (files.Length > 0)
                {
                    DataTable table = new DataTable();
                    table.Columns.Add(new DataColumn("filename", Type.GetType("System.String")));
                    table.Columns.Add(new DataColumn("createtime", Type.GetType("System.DateTime")));
                    for (int i = 0; i < files.Length; i++)
                    {
                        DataRow row = table.NewRow();
                        DateTime creationTime = System.IO.File.GetCreationTime(files[i]);
                        string fileName = Path.GetFileName(files[i]);
                        row["filename"] = fileName;
                        row["createtime"] = creationTime;
                        table.Rows.Add(row);
                    }
                    return table.Select(string.Empty, "createtime desc");
                }
            }
            return new DataRow[0];
        }

19 Source : FileHelper.cs
with MIT License
from ecjtuseclab

public static DataRow[] GetFilesByTime(string path, string Extension)
        {
            if (Directory.Exists(path))
            {
                string fielExts = string.Format("*{0}", Extension);
                string[] files = Directory.GetFiles(path, fielExts);
                if (files.Length > 0)
                {
                    DataTable table = new DataTable();
                    table.Columns.Add(new DataColumn("filename", Type.GetType("System.String")));
                    table.Columns.Add(new DataColumn("createtime", Type.GetType("System.DateTime")));
                    for (int i = 0; i < files.Length; i++)
                    {
                        DataRow row = table.NewRow();
                        DateTime creationTime = File.GetCreationTime(files[i]);
                        string fileName = Path.GetFileName(files[i]);
                        row["filename"] = fileName;
                        row["createtime"] = creationTime;
                        table.Rows.Add(row);
                    }
                    return table.Select(string.Empty, "createtime desc");
                }
            }
            return new DataRow[0];
        }

19 Source : XMLFuncs.cs
with GNU Lesser General Public License v3.0
from Edgar077

public static void CreateColumn(DataTable t, Control c)
    {
      if (t.Rows.Count == 0)
      {
        DataRow row = t.NewRow();
        t.Rows.Add(row);
      }
      if (c.Name.StartsWith("txt"))
      {
        TextBox textBox = (TextBox) c;
        if (t.Columns.IndexOf(c.Name) < 0)
        {
          t.Columns.Add(new DataColumn(c.Name)
          {
            DataType = !c.Name.EndsWith("Name") ? (!c.Name.StartsWith("txtInt") ? System.Type.GetType("System.double") : System.Type.GetType("System.Int32")) : System.Type.GetType("System.String")
          });
          DataRow dataRow = t.Rows[0];
          if (textBox.Text.Trim() != "")
            dataRow[c.Name] = (object) textBox.Text;
        }
        textBox.DataBindings.Clear();
        textBox.DataBindings.Add("Text", (object) t, c.Name, true, DataSourceUpdateMode.OnPropertyChanged);
      }
      else if (c.Name.StartsWith("radio"))
      {
        if (t.Columns.IndexOf(c.Name) < 0)
          t.Columns.Add(new DataColumn(c.Name)
          {
            DataType = System.Type.GetType("System.Boolean")
          });
        RadioButton radioButton = (RadioButton) c;
        radioButton.DataBindings.Clear();
        radioButton.DataBindings.Add("Checked", (object) t, c.Name, true, DataSourceUpdateMode.OnPropertyChanged);
      }
      else if (c.Name.StartsWith("chk"))
      {
        if (t.Columns.IndexOf(c.Name) < 0)
          t.Columns.Add(new DataColumn(c.Name)
          {
            DataType = System.Type.GetType("System.Boolean")
          });
        CheckBox checkBox = (CheckBox) c;
        checkBox.DataBindings.Clear();
        checkBox.DataBindings.Add("Checked", (object) t, c.Name, true, DataSourceUpdateMode.OnPropertyChanged);
      }
      else
      {
        if (!c.Name.StartsWith("cmb"))
          return;
        if (t.Columns.IndexOf(c.Name) < 0)
          t.Columns.Add(new DataColumn(c.Name)
          {
            DataType = System.Type.GetType("System.String")
          });
        ComboBox comboBox = (ComboBox) c;
        comboBox.DataBindings.Clear();
        comboBox.DataBindings.Add("Text", (object) t, c.Name, true, DataSourceUpdateMode.OnPropertyChanged);
      }
    }

19 Source : Matrix3Extension.cs
with GNU Lesser General Public License v3.0
from Edgar077

public static DataTable ToDataTable(this Matrix3 mat)
        {
            DataTable dt = new DataTable();
            for (int i = 0; i < mat.ColumnLength(); i++)
            {
                dt.Columns.Add("col" + i, typeof(float));
            }
            for (int iRow = 0; iRow < 3; iRow++)
            {
                DataRow dr = dt.NewRow();

                for (int iCol = 0; iCol < mat.ColumnLength(); iCol++)
                {
                    dr[iCol] = (float)mat[iCol, iRow];
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

19 Source : Matrix3dExtension.cs
with GNU Lesser General Public License v3.0
from Edgar077

public static DataTable ToDataTable(this Matrix3d mat)
        {
            DataTable dt = new DataTable();
            for (int i = 0; i < mat.ColumnLength(); i++)
            {
                dt.Columns.Add("col" + i, typeof(double));
            }
            for (int iRow = 0; iRow < 3; iRow++)
            {
                DataRow dr = dt.NewRow();

                for (int iCol = 0; iCol < mat.ColumnLength(); iCol++)
                {
                    dr[iCol] = (double)mat[iCol, iRow];
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

19 Source : SQLiteDataSourceEnumerator.cs
with Mozilla Public License 2.0
from ehsan2022002

public override DataTable GetDataSources()
        {
            DataTable dt = new DataTable();
            DataColumn col;

            col = new DataColumn("ServerName", typeof(string));
            dt.Columns.Add(col);

            col = new DataColumn("InstanceName", typeof(string));
            dt.Columns.Add(col);

            col = new DataColumn("IsClustered", typeof(bool));
            dt.Columns.Add(col);

            col = new DataColumn("Version", typeof(string));
            dt.Columns.Add(col);

            col = new DataColumn("FactoryName", typeof(string));
            dt.Columns.Add(col);

            DataRow dr = dt.NewRow();
            dr[0] = "Sqlite Embedded Database";
            dr[1] = "Sqlite Default Instance";
            dr[2] = false;
            dr[3] = "?";
            dr[4] = "System.Data.SQLite.SqliteConnectionFactory";
            dt.Rows.Add(dr);

            return dt;
        }

19 Source : SQLiteDataReader.cs
with Mozilla Public License 2.0
from ehsan2022002

public override DataTable GetSchemaTable()
        {
            DataTable dataTableSchema = new DataTable();

            dataTableSchema.Columns.Add("ColumnName", typeof(String));
            dataTableSchema.Columns.Add("ColumnOrdinal", typeof(Int32));
            dataTableSchema.Columns.Add("ColumnSize", typeof(Int32));
            dataTableSchema.Columns.Add("NumericPrecision", typeof(Int32));
            dataTableSchema.Columns.Add("NumericScale", typeof(Int32));
            dataTableSchema.Columns.Add("IsUnique", typeof(Boolean));
            dataTableSchema.Columns.Add("IsKey", typeof(Boolean));
            dataTableSchema.Columns.Add("BaseCatalogName", typeof(String));
            dataTableSchema.Columns.Add("BaseColumnName", typeof(String));
            dataTableSchema.Columns.Add("BaseSchemaName", typeof(String));
            dataTableSchema.Columns.Add("BaseTableName", typeof(String));
            dataTableSchema.Columns.Add("DataType", typeof(Type));
            dataTableSchema.Columns.Add("AllowDBNull", typeof(Boolean));
            dataTableSchema.Columns.Add("ProviderType", typeof(Int32));
            dataTableSchema.Columns.Add("IsAliased", typeof(Boolean));
            dataTableSchema.Columns.Add("IsExpression", typeof(Boolean));
            dataTableSchema.Columns.Add("IsIdenreplacedy", typeof(Boolean));
            dataTableSchema.Columns.Add("IsAutoIncrement", typeof(Boolean));
            dataTableSchema.Columns.Add("IsRowVersion", typeof(Boolean));
            dataTableSchema.Columns.Add("IsHidden", typeof(Boolean));
            dataTableSchema.Columns.Add("IsLong", typeof(Boolean));
            dataTableSchema.Columns.Add("IsReadOnly", typeof(Boolean));

            dataTableSchema.BeginLoadData();
            for (int i = 0; i < this.FieldCount; i += 1)
            {

                DataRow schemaRow = dataTableSchema.NewRow();

                schemaRow["ColumnName"] = columns[i];
                schemaRow["ColumnOrdinal"] = i;
                schemaRow["ColumnSize"] = 0;
                schemaRow["NumericPrecision"] = 0;
                schemaRow["NumericScale"] = 0;
                schemaRow["IsUnique"] = false;
                schemaRow["IsKey"] = false;
                schemaRow["BaseCatalogName"] = "";
                schemaRow["BaseColumnName"] = columns[i];
                schemaRow["BaseSchemaName"] = "";
                schemaRow["BaseTableName"] = "";
                schemaRow["DataType"] = typeof(string);
                schemaRow["AllowDBNull"] = true;
                schemaRow["ProviderType"] = 0;
                schemaRow["IsAliased"] = false;
                schemaRow["IsExpression"] = false;
                schemaRow["IsIdenreplacedy"] = false;
                schemaRow["IsAutoIncrement"] = false;
                schemaRow["IsRowVersion"] = false;
                schemaRow["IsHidden"] = false;
                schemaRow["IsLong"] = false;
                schemaRow["IsReadOnly"] = false;

                dataTableSchema.Rows.Add(schemaRow);
                schemaRow.AcceptChanges();
            }
            dataTableSchema.EndLoadData();

            return dataTableSchema;
        }

19 Source : TableEditor.xaml.cs
with MIT License
from ekblom

private void AddRowBefore(object sender, RoutedEventArgs e)
        {
            var firstCell = GridTable.SelectedCells.FirstOrDefault();
            if (firstCell.IsValid)
            {
                var dr = firstCell.Item as DataRowView;
                if (dr == null)
                    return;

                var rowIndex = _currentTable.Rows.IndexOf(dr.Row);
                var newRow = _currentTable.NewRow();
                _currentTable.Rows.InsertAt(newRow, rowIndex);
            }
        }

19 Source : TableEditor.xaml.cs
with MIT License
from ekblom

private void AddRowAfter(object sender, RoutedEventArgs e)
        {
            var firstCell = GridTable.SelectedCells.FirstOrDefault();
            if (firstCell.IsValid)
            {
                var dr = firstCell.Item as DataRowView;
                if (dr == null)
                    return;

                var rowIndex = _currentTable.Rows.IndexOf(dr.Row);
                if (_currentTable.Rows.Count == rowIndex + 1)
                {
                    _currentTable.Rows.Add();
                }
                else
                {
                    var newRow = _currentTable.NewRow();
                    _currentTable.Rows.InsertAt(newRow, rowIndex + 1);
                }
            }
        }

19 Source : ToDataTable.cs
with GNU General Public License v2.0
from ensoulsharp-io

public static TTable ToDataTable<T, TTable>(
            this IEnumerable<T> source,
            TTable table,
            params Expression<Func<T, object>>[] expressions) where TTable : DataTable
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }

            var members = PrepareMemberInfos(expressions).ToArray();
            members = BuildOrBindSchema(table, members);
            var shredder = CreateShredder<T>(members);

            //
            // Builds rows out of elements in the sequence and
            // add them to the table.
            //

            table.BeginLoadData();

            try
            {
                foreach (var element in source)
                {
                    var row = table.NewRow();
                    row.ItemArray = shredder(element);
                    table.Rows.Add(row);
                }
            }
            finally
            {
                table.EndLoadData();
            }

            return table;
        }

19 Source : Frequency.cs
with Apache License 2.0
from Epi-Info

public void Execute()
        {
            Dictionary<string,string> config = this.Context.SetProperties;
            System.Collections.Generic.Dictionary<string, System.Data.DataTable> Freq_ListSet = new Dictionary<string, System.Data.DataTable>();
            
            DataTable DT = new DataTable();
            DT.CaseSensitive = true;
            DataTable OutDataTable = new DataTable();

            foreach (DataColumn column in this.Context.Columns)
            {
                DataColumn newColumn = new DataColumn(column.ColumnName);
                newColumn.DataType = column.DataType;
                DT.Columns.Add(newColumn);
            }

            // **** Get Participating Variables Start
            List<string> ParticipatingVariables = new List<string>();
            /*
            if (this.IdentifierList[0] == "*")
            {
                foreach (System.Data.DataColumn C in this.Context.Columns)
                {
                    //ParticipatingVariables.Add(C.ColumnName);
                }
            }
            else
            {
                foreach (string Key in IdentifierList)
                {
                    //ParticipatingVariables.Add(Key);
                }
            }*/

            if(!string.IsNullOrEmpty(this.WeightVar) && this.WeightVar != "")
            {
                ParticipatingVariables.Add(this.WeightVar);
            }

            if (this.StratvarList != null) // PATCH; improve later
            {
                foreach (string stratavar in this.StratvarList)
                {
                    ParticipatingVariables.Add(stratavar);
                }
            }

            // **** Get Participating Variables End
            foreach (DataRow row in this.Context.GetDataRows(ParticipatingVariables))
            {
                DT.ImportRow(row); 
            }

            Frequency.PermutationList = new Dictionary<string, List<object>>();
            CreatePermutaionList(this.StratvarList);


            List<string> RemoveList = new List<string>();
            if (!this.config.Settings.IncludeMissingValues)
            {
                foreach (string s in Frequency.SelectClauses)
                {
                    if (s.EndsWith(" is Null", StringComparison.OrdinalIgnoreCase))
                    {
                        RemoveList.Add(s);
                    }
                }
            }

            foreach (string s in RemoveList)
            {
                Frequency.SelectClauses.Remove(s);
            }

            StringBuilder HTMLString = new StringBuilder();
            System.Collections.Generic.Dictionary<string, string> KeyList = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(this.OutTable))
            {
                OutDataTable.TableName = this.OutTable;
                if (this.StratvarList != null)
                {
                    foreach (string stratavar in this.StratvarList)
                    {
                        DataColumn newColumn = new DataColumn(stratavar);
                        newColumn.DataType = this.Context.Columns[stratavar].DataType;
                        OutDataTable.Columns.Add(newColumn);
                    }
                }
                foreach (string freqitem in this.IdentifierList)
                {
                    DataColumn newColumn = new DataColumn(freqitem);
                    newColumn.DataType = this.Context.Columns[freqitem].DataType;
                    OutDataTable.Columns.Add(newColumn);
                }
                DataColumn varCol = new DataColumn("VARNAME");
                varCol.DataType = typeof(string);
                OutDataTable.Columns.Add(varCol);

                DataColumn percentCol = new DataColumn("PERCENT");
                percentCol.DataType = typeof(double);
                OutDataTable.Columns.Add(percentCol);

                DataColumn countCol = new DataColumn("COUNT");
                countCol.DataType = typeof(int);
                OutDataTable.Columns.Add(countCol);
            }

            foreach (string SelectClause in Frequency.SelectClauses)
            {
                Freq_ListSet.Clear();
                KeyList.Clear();

                if (this.IdentifierList[0] == "*")
                {
                    foreach (System.Data.DataColumn C in this.Context.Columns)
                    {
                        string Key = C.ColumnName;
                        if (!Freq_ListSet.ContainsKey(Key))
                        {
                            Freq_ListSet.Add(Key, CreateDataTable(Key));
                            KeyList.Add(Key, Key);
                        }
                    }
                }
                else
                {
                    foreach (string Key in IdentifierList)
                    {
                        if (!Freq_ListSet.ContainsKey(Key))
                        {
                            if (GetColumnDataType(Key) != null)
                            {
                            Freq_ListSet.Add(Key, CreateDataTable(Key));
                            KeyList.Add(Key, Key);
                            }
                        }
                    }
                }

                foreach (System.Data.DataRow R in DT.Select(SelectClause))
                {
                    foreach (System.Collections.Generic.KeyValuePair<string, System.Data.DataTable> KeyP in Freq_ListSet)
                    {
                        string Key = KeyP.Key;
                        foreach (System.Data.DataColumn C in DT.Columns)
                        {
                            string ColumnKey = C.ColumnName;
                            if (ColumnKey.ToUpperInvariant() == Key.ToUpperInvariant())
                            {
                                bool RowIsFound = false;

                                foreach (System.Data.DataRow R2 in KeyP.Value.Rows)
                                {
                                    if (R[C.ColumnName].ToString() == R2["value"].ToString())
                                    {
                                        RowIsFound = true;
                                        if (string.IsNullOrEmpty(this.WeightVar))
                                        {
                                            R2["count"] = int.Parse(R2["count"].ToString()) + 1;
                                        }
                                        else
                                        {
                                            double temp = 0.0;

                                            if (double.TryParse(R[this.WeightVar].ToString(), out temp))
                                            {
                                                R2["count"] = double.Parse(R2["count"].ToString()) + temp;
                                            }
                                        }
                                        break;
                                    }
                                }

                                if (!RowIsFound)
                                {
                                    System.Data.DataRow R3;
                                    if (string.IsNullOrEmpty(this.WeightVar))
                                    {
                                        R3 = Freq_ListSet[Key].NewRow();
                                        R3["value"] = R[C.ColumnName];
                                        R3["count"] = 1;
                                        if (this.StratvarList != null)
                                        {
                                            foreach (string strata in this.StratvarList)
                                            {
                                                R3[strata] = R[strata];
                                            }
                                        }
                                        KeyP.Value.Rows.Add(R3);
                                    }
                                    else
                                    {
                                        double temp = 0;
                                        if (double.TryParse(R[this.WeightVar].ToString(), out temp))
                                        {
                                            R3 = Freq_ListSet[Key].NewRow();
                                            R3["value"] = R[C.ColumnName];
                                            R3["count"] = temp;
                                            if (this.StratvarList != null)
                                            {
                                                foreach (string strata in this.StratvarList)
                                                {
                                                    R3[strata] = R[strata];
                                                }
                                            }
                                            KeyP.Value.Rows.Add(R3);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }

                string[] tmpString2 = null;
                tmpString2 = SelectClause.ToString().Split(new string[] { " AND " }, StringSplitOptions.None);
                bool appendWithAND = false;
                HTMLString.Append("<p><b>");
                if (!(tmpString2.Length == 1 && tmpString2[0] == ""))
                {
                    foreach (string tempString in tmpString2)
                    {
                        string[] tmpString = null;

                        tmpString = tempString.ToString().Split('=');
                        if (tmpString.Length == 1)
                        {
                            tmpString = tempString.ToString().Split(new string[] { " is " }, StringSplitOptions.None);
                        }
                        string newSelectClause = string.Empty;

                        bool variableExists = this.Context.EpiViewVariableList.ContainsKey(tmpString[0].Trim());
                        string dataType = DT.Columns[tmpString[0].Trim()].DataType.ToString();
                        bool isByte = dataType.Equals("System.Byte");
                        bool isBool = dataType.Equals("System.Boolean");

                        if (variableExists && (isByte || isBool))
                        {
                            if (tmpString[1].ToUpperInvariant().Contains("FALSE"))
                            {
                                tmpString[1] = this.config.Settings.RepresentationOfNo;
                            }
                            else if (tmpString[1].ToUpperInvariant().Contains("TRUE"))
                            {
                                tmpString[1] = this.config.Settings.RepresentationOfYes;
                            }

                            if (tmpString[1].Contains("1"))
                            {
                                tmpString[1] = this.config.Settings.RepresentationOfYes;
                            }
                            else if (tmpString[1].Contains("0"))
                            {
                                tmpString[1] = this.config.Settings.RepresentationOfNo;
                            }
                            else if (tmpString[1].ToLowerInvariant().Contains("null"))
                            {
                                tmpString[1] = this.config.Settings.RepresentationOfMissing;
                            }
                            newSelectClause = tmpString[0] + "=" + tmpString[1].ToString();
                        }
                        else
                        {
                            newSelectClause = tempString;
                        }

                        if (appendWithAND)
                        {
                            HTMLString.Append(" AND " + newSelectClause.Replace("''", "'"));
                        }
                        else
                        {
                            HTMLString.Append(newSelectClause.Replace("''", "'"));
                        }

                        appendWithAND = true;
                    }
                }
                HTMLString.Append("</b></p>");    

                foreach (System.Collections.Generic.KeyValuePair<string, System.Data.DataTable> Key in Freq_ListSet)
                {
                    double Mode = 0.0;
                    double ModeCount = 0.0;
                    double mean = 0.0;
                    double variance = 0.0;

                    System.Data.DataRow[] tempRows = Key.Value.Select("", "value");

                    if (config["include-missing"].ToUpperInvariant() == "FALSE")
                    {
                        tempRows = Key.Value.Select(string.Format(" varname='{0}' and [value] is NOT NULL ", Key.Key), "value");
                    }
                    else
                    {
                        tempRows = Key.Value.Select("", "value");
                    }

                    //var Rows = tempRows.OrderByDescending(item => item["count"]);

                    int n = 0;
                    double std_dev = 0.0;
                    double Sum = 0.0;
                    double Sum_Sqr = 0.0;

                    double Total = 0;
                    double Min = 0.0;
                    double Max = 0.0;

                    foreach (System.Data.DataRow R in tempRows)
                    {
                        double temp;
                        double.TryParse(R["count"].ToString(), out temp);
                        Total += temp;
                    }

                    foreach (System.Data.DataRow R in tempRows)
                    {
                        if (!string.IsNullOrEmpty(this.OutTable))
                        {
                            DataRow newRow = OutDataTable.NewRow();
                            if (this.StratvarList != null)
                            {
                                foreach (string stratavar in this.StratvarList)
                                {
                                    newRow[stratavar] = R[stratavar];
                                }
                            }
                            newRow[Key.Key] = R["value"];
                            newRow["VARNAME"] = Key.Key ;
                            newRow["PERCENT"] = (((double)R["count"]) / Total) * 100.0;
                            newRow["COUNT"] = R["count"];
                            OutDataTable.Rows.Add(newRow);
                        }
                    }

                    HTMLString.Append("<table cellpadding=\"2\">");
                    HTMLString.Append("<tr><th>");
                    if (this.Context.EpiViewVariableList.ContainsKey(Key.Key) && this.config.Settings.ShowCompletePrompt)
                        HTMLString.Append(this.Context.EpiViewVariableList[Key.Key].Prompt);
                    else
                        HTMLString.Append(Key.Key);
                    HTMLString.Append("</th><th>Frequency</th><th>Percent</th><th>replaced. Percent</th><th style=\"width:100px\"> </th></tr>");
                    double AcreplacedulatedTotal = 0;
                    List<ConfLimit> confLimits = new List<ConfLimit>();
                    int obs = 0;
                    foreach (System.Data.DataRow R in tempRows)
                    {
                        double x;

                        Double.TryParse(R["value"].ToString(), out x);

                        if (obs == 0)
                        {
                            Max = Min = x;
                        }
                        else
                        {
                            Max = x;
                        }

                        obs++;
                        n++;
                        Sum += x;
                        Sum_Sqr += x * x;

                        double currrentCount;
                        double.TryParse(R["count"].ToString(), out currrentCount);

                        if (currrentCount > ModeCount)
                        {
                            ModeCount = currrentCount;
                            Mode = x;
                        }

                        AcreplacedulatedTotal += currrentCount;

                        HTMLString.Append("<tr>");
                        HTMLString.Append("<td><strong>");

                        if (Context.EpiViewVariableList.ContainsKey(Key.Key))
                        {
                            int dataTypeCode = Context.EpiViewVariableList[Key.Key].DataType.GetHashCode();
                            DataType dataType = (DataType)dataTypeCode;
                            GetPrintValue(Key.Key, R["value"], config, HTMLString, dataType);
                        }
                        else
                        { 
                            GetPrintValue(Key.Key, R["value"], config, HTMLString);
                        }

                        HTMLString.Append("</strong></td>");
                        HTMLString.Append("<td align=\"right\">");
                        HTMLString.Append(currrentCount.ToString());
                        HTMLString.Append("</td>");
                        HTMLString.Append("<td align=\"right\">");
                        HTMLString.Append(ConvertToPercent(currrentCount / Total));
                        HTMLString.Append("</td>");
                        HTMLString.Append("<td align=\"right\">");
                        HTMLString.Append(ConvertToPercent(AcreplacedulatedTotal / Total));
                        HTMLString.Append("</td><td><div clreplaced=PercentBar_Summary style=\"width:" + ConvertToPixelLength(currrentCount / Total) + "\"> </div></td>");
                        HTMLString.Append("</tr>");
                        confLimits.Add(GetConfLimit(GetPrintValue(Key.Key,R["value"], config), (float)currrentCount, (float)Total));
                    }

                    mean = Sum / n;
                    variance = (Sum_Sqr - Sum * mean) / (n - 1);
                    std_dev = calcStd_Dev(tempRows, mean);

                    HTMLString.Append("<tr>");
                    HTMLString.Append("<td><strong>Total</strong></td><td align=\"right\">");
                    HTMLString.Append(Total.ToString());
                    HTMLString.Append("</td><td align=\"right\">" + ConvertToPercent(1) + "</td><td align=\"right\">" + ConvertToPercent(1) + "</td><td><div clreplaced=PercentBar_Totals style=\"width:100%\"> </div></td><tr>");

                    HTMLString.Append("</table>");

                    HTMLString.Append("<BR CLEAR=ALL/>");
                    if (Total < 300)
                        HTMLString.Append("<TABLE> <TD Clreplaced='Stats' ColSpan=\"3\"><B>Exact 95% Conf Limits</B></TD>");
                    else
                        HTMLString.Append("<TABLE> <TD Clreplaced='Stats' ColSpan=\"3\"><B>Wilson 95% Conf Limits</B></TD>");
                    foreach (ConfLimit cl in confLimits)
                    {
                        HTMLString.Append("<TR><TD Clreplaced='Stats'>" + cl.Value + "</TD><TD Clreplaced='Stats'>" + ConvertToPercent(cl.Lower) + "</TD><TD Clreplaced='Stats'>" + ConvertToPercent(cl.Upper) + "</TD></TR>");
                    }
                    HTMLString.Append("</TABLE>");
                }
            }
            if (!string.IsNullOrEmpty(this.OutTable))
            {
                this.Context.OutTable(OutDataTable);
            }

            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("COMMANDNAME", "FREQ");
            args.Add("COMMANDTEXT", commandText.Trim());
            args.Add("HTMLRESULTS", HTMLString.ToString());

            this.Context.Display(args);
        }

19 Source : cWorkingTable.cs
with Apache License 2.0
from Epi-Info

public static DataTable CreateWorkingTable(string pNumericVariable, string pCrossTabVariable, Dictionary<string, string> config, DataTable DT, List<string> pStratavar, List<string> pStrataValue, string pWeightVariable)
        {
            DataTable result = new DataTable();
            result.CaseSensitive = true;


            DataTable RowValues = new DataTable();
            DataTable ColumnValues = new DataTable();

            /*
            Produce Table with rows = number of distinct values in main_variable
                if no cross _tab_variable then columns = 2
                else columns = 2 + number of values in cross_tab_variable

            For each strata 
                get distinct values of the strata
                for each distinct value
                    produce the following table
            */

            cDataSetHelper ds = new cDataSetHelper();

            ColumnValues = ds.SelectDistinct("ColumnValues", DT, pNumericVariable);
            
            result.Columns.Add(new DataColumn("__Values__", ColumnValues.Columns[pNumericVariable].DataType));
            result.Columns.Add(new DataColumn("__Count__", typeof(double)));


            if (!string.IsNullOrEmpty(pCrossTabVariable))
            {
                RowValues = ds.SelectDistinct("RowValues", DT, pCrossTabVariable);
                foreach (DataRow R in RowValues.Select("", pCrossTabVariable))
                {
                    if (R[0] == DBNull.Value || string.IsNullOrEmpty(R[0].ToString()))
                    {
                        if (config["include-missing"].ToUpperInvariant() != "FALSE")
                        {
                            DataColumn dataColumn = new DataColumn(config["RepresentationOfMissing"], typeof(double));
                            dataColumn.ExtendedProperties.Add("Value", R[0]);
                            bool isFound = false;

                            for (int i = 0; i < result.Columns.Count; i++)
                            {
                                if (dataColumn.ColumnName == result.Columns[i].ColumnName)
                                {
                                    isFound = true;
                                    break;
                                }
                            }

                            if (!isFound)
                            {
                                result.Columns.Add(dataColumn);
                            }
                            else
                            {

                            }
                        }
                    }
                    else
                    {
                        DataColumn dataColumn = new DataColumn(R[0].ToString(), typeof(double));
                        dataColumn.ExtendedProperties.Add("Value", R[0]);

                        bool isFound = false;

                        for (int i = 0; i < result.Columns.Count; i++)
                        {
                            if (dataColumn.ColumnName == result.Columns[i].ColumnName)
                            {
                                isFound = true;
                                break;
                            }
                        }

                        if (!isFound)
                        {
                            result.Columns.Add(dataColumn);
                        }
                        else
                        {

                        }
                    }
                }
            }

            Dictionary<string, DataRow> RowList = new Dictionary<string, DataRow>();
            DataRow newRow = null;
            // initialize table
            foreach (DataRow R in ColumnValues.Select("", "[" + pNumericVariable + "]"))
            {
                string RowKey = null;

                if (R[0] is DateTime)
                {
                    RowKey = ((DateTime)R[0]).ToString("MM/dd/yyyy hh:mm:ss.fff tt");
                }
                else
                {
                    RowKey  = R[0].ToString();
                    
                }

                if (!RowList.ContainsKey(RowKey))
                {
                    newRow = result.NewRow();
                    foreach (DataColumn C in result.Columns)
                    {
                        if (C.ColumnName.Equals("__Values__"))
                        {
                            newRow[C.ColumnName] = R[0];
                        }
                        else
                        {
                            newRow[C.ColumnName] = 0;
                        }
                    }
                    RowList.Add(RowKey, newRow);
                    result.Rows.Add(newRow);
                }
            }

            DataRow[] workingRows = null;
            if (pStratavar == null || pStratavar.Count == 0 || string.IsNullOrEmpty(pStratavar[0]))
            {
                workingRows = DT.Select("", "[" +  pNumericVariable + "]");
            }
            else
            {
                StringBuilder WhereClause = new StringBuilder();
                for(int i = 0; i < pStratavar.Count; i++)
                {
                    string CurrentStratavar = pStratavar[i];
                    string CurrentValue = pStrataValue[i];

                    DataColumn column = DT.Columns[CurrentStratavar];
                    switch (column.DataType.Name)
                    {
                        case "Byte":
                        case "Boolean":
                        case "Double":
                        case "Float":
                        case "Integer":
                        case "Int16":
                        case "Short":
                        case "Int32":
                        case "Int64":
                            if (CurrentValue.Equals("NULL"))
                                WhereClause.Append(string.Format("[{0}] IS {1} And ", CurrentStratavar, CurrentValue));
                            else
                                WhereClause.Append(string.Format("[{0}] = {1} And ", CurrentStratavar, CurrentValue));
                            break;
                        case "String":
                        default:
                            WhereClause.Append(string.Format("[{0}] = '{1}' And ", CurrentStratavar, CurrentValue));
                            break;
                    }
                }

                WhereClause.Length = WhereClause.Length - 4;
                workingRows = DT.Select(WhereClause.ToString(), "[" + pNumericVariable + "]");
            }

            if (string.IsNullOrEmpty(pCrossTabVariable))
            {
                foreach (DataRow R in workingRows)
                {
                    DataRow Dest;

                    if (R[pNumericVariable] is DateTime)
                    {
                        Dest = RowList[((DateTime)R[pNumericVariable]).ToString("MM/dd/yyyy hh:mm:ss.fff tt")];
                    }
                    else
                    {
                        Dest = RowList[R[pNumericVariable].ToString()];
                    }

                    if (string.IsNullOrEmpty(pWeightVariable))
                    {
                        Dest["__Count__"] = (double)Dest["__Count__"] + 1;
                    }
                    else
                    {
                        if (R[pWeightVariable] != DBNull.Value && ((R[pWeightVariable] is String) == false))
                        {
                            Dest["__Count__"] = (double)Dest["__Count__"] + Convert.ToDouble(R[pWeightVariable]);
                        }
                        else
                        {
                            if (config["include-missing"].ToUpperInvariant() != "FALSE")
                            {
                                Dest["__Count__"] = (double)Dest["__Count__"] + 1;
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (DataRow R in workingRows)
                {
                    DataRow Dest;

                    if (R[pNumericVariable] is DateTime)
                    {
                        Dest = RowList[((DateTime)R[pNumericVariable]).ToString("MM/dd/yyyy hh:mm:ss.fff tt")];
                    }
                    else
                    {
                        Dest = RowList[R[pNumericVariable].ToString()];
                    }

                    double rowWeightValue = 0;
                    double rowCrossTabValue = 0;

                    if (string.IsNullOrEmpty(pCrossTabVariable) == false)
                    {
                        if (R[pCrossTabVariable] != System.DBNull.Value && !string.IsNullOrEmpty(R[pCrossTabVariable].ToString()))
                        {
                            rowCrossTabValue = (double)Dest[R[pCrossTabVariable].ToString()];
                        }
                        else
                        {
                            if (config["include-missing"].ToUpperInvariant() != "FALSE")
                            {
                               rowCrossTabValue =  (double) Dest[config["RepresentationOfMissing"]];
                            }
                        }
                    }

                    if(string.IsNullOrEmpty(pWeightVariable))
                    {
                        Dest["__Count__"] = (double)Dest["__Count__"] + 1;

                        if (R[pCrossTabVariable] != System.DBNull.Value && !string.IsNullOrEmpty(R[pCrossTabVariable].ToString()))
                        {
                            Dest[R[pCrossTabVariable].ToString()] = rowCrossTabValue + 1;
                        }
                        else
                        {
                            if (config["include-missing"].ToUpperInvariant() != "FALSE")
                            {
                                Dest[config["RepresentationOfMissing"]] = rowCrossTabValue + 1;
                            }
                        }
                    }
                    else
                    {
                        if (R[pWeightVariable] != System.DBNull.Value && !string.IsNullOrEmpty(R[pWeightVariable].ToString()))
                        {
                            rowWeightValue = Convert.ToDouble(R[pWeightVariable]);
                            Dest["__Count__"] = (double)Dest["__Count__"] + rowWeightValue;
                        }
                        else
                        {
                            if (config["include-missing"].ToUpperInvariant() != "FALSE")
                            {
                                Dest["__Count__"] = (double)Dest["__Count__"] + rowWeightValue;
                            }
                        }

                        if (R[pCrossTabVariable] != System.DBNull.Value && !string.IsNullOrEmpty(R[pCrossTabVariable].ToString()))
                        {
                            if (R[pNumericVariable] is DateTime)
                            {
                                string replacedtring = ((DateTime)R[pNumericVariable]).ToString("MM/dd/yyyy hh:mm:ss.fff tt");
                                bool containsColumn = Dest.Table.Columns.Contains(replacedtring);
                                if(containsColumn)
                                {
                                    Dest[replacedtring] = rowCrossTabValue + rowWeightValue;
                                }
                            }
                            else
                            {
                                Dest[R[pCrossTabVariable].ToString()] = rowCrossTabValue + rowWeightValue;
                            }
                        }
                        else
                        {
                            if (config["include-missing"].ToUpperInvariant() != "FALSE")
                            {
                                Dest[config["RepresentationOfMissing"]] = rowCrossTabValue + 1;
                            }
                        }
                    }
                }
            }

            return result;
        }

19 Source : Graph.cs
with Apache License 2.0
from Epi-Info

public void Execute()
        {
            _regressionTable = new DataTable();
            _regressionTable.Columns.Add("SeriesName", typeof(string));
            _regressionTable.Columns.Add("Predictor", typeof(object));
            _regressionTable.Columns.Add("Response", typeof(double));
            
            Dictionary<string, string> config = Context.SetProperties;
            StringBuilder HTMLString = new StringBuilder();

            System.Data.DataTable sourceTable = BuildTempContextTable();
            cDataSetHelper dsHelper = new cDataSetHelper();

            Dictionary<string, string> args = new Dictionary<string, string>();

            string strataVarValue = string.Empty;
            string objectElement = string.Empty;

            SilverlightMarkup silverlight = new SilverlightMarkup();

            DataTable Strata_ValueList;

            if (string.IsNullOrEmpty(_strataVar))
            {
                Strata_ValueList = sourceTable.Clone();
                Strata_ValueList.Rows.Add(Strata_ValueList.NewRow());
            }
            else
            {
                Strata_ValueList = dsHelper.SelectDistinct("", sourceTable, _strataVar);
            }

            FilterStruct filter = new FilterStruct();
            filter.strataVarName = _strataVar;
            
            _independentValueTypesSame = true;
            if(_independentVariableArray.Length > 1)
            {
                for(int i = 0; (i + 1) < _independentVariableArray.Length ; i++)
                {
                    if (sourceTable.Columns[_independentVariableArray[i]].DataType != sourceTable.Columns[_independentVariableArray[i+1]].DataType )
                    {
                        _independentValueTypesSame = false;
                        break;
                    }
                }
            }

            _independentValuesAllBool = true;
            for (int i = 0; i < _independentVariableArray.Length; i++)
            {
                string indepVar = _independentVariableArray[i];

                if (sourceTable.Columns.Contains(indepVar))
                {
                    if (sourceTable.Columns[indepVar].DataType.Name != "Byte")
                    {
                        _independentValuesAllBool = false;
                        break;
                    }
                }
                else
                {
                    return;
                }
            }

            foreach (DataRow strataRow in Strata_ValueList.Rows)
            {
                if (string.IsNullOrEmpty(_strataVar) || strataRow[_strataVar] == DBNull.Value)
                {
                    filter.strataVarValue = "null";
                }
                else
                {
                    filter.strataVarValue = strataRow[_strataVar].ToString();
                }

                if (_graphType == SilverlightStatics.Scatter)
                {
                    if (_independentVariableArray.Length < 2)
                    {
                        throw new Exception("Scatter graphs must contain two (2) main variables.");
                    }
                    
                    string categoryName = string.Empty;
                    Dictionary<object, double> indDepValuePairCollection = new Dictionary<object, double>();

                    List<string> StrataVarNameList = new List<string>();
                    List<string> StrataVarValueList = new List<string>();

                    string regressor = _independentVariableArray[0];
                    string regressand = _independentVariableArray[1];

                    StrataVarNameList.Add(filter.strataVarName);
                    StrataVarValueList.Add(filter.strataVarValue);

                    DataTable table = new DataTable();
                    table.Columns.Add(new DataColumn(sourceTable.Columns[regressor].ColumnName, sourceTable.Columns[regressor].DataType));
                    table.Columns.Add(new DataColumn(sourceTable.Columns[regressand].ColumnName, sourceTable.Columns[regressand].DataType));

                    foreach (DataRow row in sourceTable.Rows)
                    {
                        table.Rows.Add(row[regressor], row[regressand]);
                    }

                    foreach (DataRow row in table.Rows)
                    {
                        if (row[regressor] != DBNull.Value)
                        {
                            string seriesName = string.Empty;
                            object independentValue = new object();

                            if (_independentValuesAllBool)
                            {
                                independentValue = regressor;
                                byte value = (byte)(row[regressor]);
                            }
                            else
                            {
                                independentValue = GetValue(regressor, row, config);
                            }

                            seriesName = string.Format("{0} x {1}", sourceTable.Columns[regressor].ColumnName, sourceTable.Columns[regressand].ColumnName);

                            if (string.IsNullOrEmpty(_weightVar))
                            {
                                double dependentVal;

                                if (double.TryParse(row[regressand].ToString(), out dependentVal))
                                {
                                    _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                }
                            }
                            else
                            {
                                filter.independentVarValue = row[regressor];
                                filter.independentVarName = regressor;
                                filter.weightVarName = _weightVar;
                                double dependentVal = GetAggregateValue(sourceTable, filter);

                                _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                            }
                        }
                    }
                }
                else if (sourceTable.Columns.Contains(_graphCrossTab))
                {
                    string categoryName = string.Empty;
                    Dictionary<object, double> indDepValuePairCollection = new Dictionary<object, double>();

                    List<string> StrataVarNameList = new List<string>();
                    List<string> StrataVarValueList = new List<string>();

                    foreach (string independentVariableName in _independentVariableArray)
                    {
                        StrataVarNameList.Add(filter.strataVarName);
                        StrataVarValueList.Add(filter.strataVarValue);

                        DataTable workingTable = cWorkingTable.CreateWorkingTable(
                            independentVariableName, 
                            _graphCrossTab, 
                            config,
                            sourceTable,
                            StrataVarNameList,
                            StrataVarValueList,
                            _weightVar);

                        foreach (DataColumn crossTabCandidate in workingTable.Columns)
                        {
                            if (crossTabCandidate.ColumnName != "__Values__" && crossTabCandidate.ColumnName != "__Count__")
                            {
                                Type crossTabDataType = sourceTable.Columns[_graphCrossTab].DataType;

                                string crossTabValue = crossTabCandidate.ColumnName;

                                if (crossTabDataType.Name == "Byte")
                                {
                                    if (crossTabCandidate.ColumnName == "0")
                                    {
                                        crossTabValue = config["RepresentationOfNo"];
                                    }
                                    else if (crossTabCandidate.ColumnName == "1")
                                    {
                                        crossTabValue = config["RepresentationOfYes"];
                                    }
                                }

                                string seriesName = string.Format("{0}={1}", _graphCrossTab, crossTabValue);

                                foreach (DataRow row in workingTable.Rows)
                                {
                                    double dependentVal;
                                    
                                    if (double.TryParse(row[crossTabCandidate.ColumnName].ToString(), out dependentVal))
                                    {
                                        if (row["__Values__"] != DBNull.Value)
                                        {
                                            string independentVariableTypeName = string.Empty;

                                            if (sourceTable.Columns.Contains(independentVariableName))
                                            {
                                                independentVariableTypeName = sourceTable.Columns[independentVariableName].DataType.Name;
                                            }

                                            categoryName = BuildCategoryName(independentVariableName, independentVariableTypeName, row, config);

                                            object independentValue = row["__Values__"];

                                            if (string.IsNullOrEmpty(_weightVar))
                                            {
                                                if (double.TryParse(row[crossTabCandidate.ColumnName].ToString(), out dependentVal))
                                                {
                                                    _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                                }
                                            }
                                            else
                                            {
                                                object independentVariableValue = row["__Values__"];

                                                bool isValue = false;

                                                if (independentVariableValue != null)
                                                {
                                                    isValue = true;

                                                    if (independentVariableValue is string)
                                                    {
                                                        string candidate = ((string)independentVariableValue).Trim();
                                                        isValue = candidate != string.Empty;
                                                    }
                                                }

                                                if (isValue)
                                                { 
                                                    filter.crossTabName = _graphCrossTab;
                                                    filter.crossTabValue = crossTabCandidate.ColumnName;
                                                    filter.independentVarName = independentVariableName;
                                                    filter.independentVarValue = independentVariableValue;
                                                    filter.weightVarName = _weightVar;
                                                    dependentVal = GetAggregateValue(sourceTable, filter);
                                                    _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (_graphType == "EPICURVE" && _graphIntervalUnits != "")
                {
                    string categoryName = string.Empty;
                    Dictionary<object, double> indDepValuePairCollection = new Dictionary<object, double>();

                    List<string> StrataVarNameList = new List<string>();
                    List<string> StrataVarValueList = new List<string>();

                    foreach (string independentVariable in _independentVariableArray)
                    {
                        StrataVarNameList.Add(filter.strataVarName);
                        StrataVarValueList.Add(filter.strataVarValue);

                        DataTable workingTable = cWorkingTable.CreateWorkingTable(
                            independentVariable, 
                            "", 
                            config, 
                            sourceTable,
                            StrataVarNameList,
                            StrataVarValueList,
                            _weightVar);

                        DateTime intervalStart = DateTime.MinValue;
                        DateTime intervalEnd = DateTime.MinValue;
                        DateTime dateTimeValue = DateTime.MinValue;
                        intervalStart = _graphStartFrom;

                        double givenInterval = 1;
                        int days = 0, hours = 0, minutes = 0, seconds = 0; 
                        TimeSpan period = new TimeSpan(days, hours, minutes, seconds);

                        if (_graphInterval != "")
                        {
                            double.TryParse(_graphInterval, out givenInterval);
                        }

                        if (_graphIntervalUnits == "")
                        {
                            _graphIntervalUnits = "Hours";
                        }

                        foreach (DataRow row in workingTable.Rows)
                        {
                            if (row["__Values__"] != DBNull.Value)
                            {
                                dateTimeValue = (DateTime)row["__Values__"];

                                //if (intervalStart == DateTime.MinValue)
                                //{
                                //    intervalStart = dateTimeValue;
                                //    _graphStartFrom = dateTimeValue;
                                //}

                                while ( dateTimeValue >= intervalEnd)
                                {
                                    if (intervalEnd != DateTime.MinValue)
                                    { 
                                        intervalStart = intervalEnd;
                                    }

                                    switch (_graphIntervalUnits)
                                    {
                                        case "Years":
                                            intervalEnd = intervalStart.AddYears((int)givenInterval);
                                            break;
                                        case "Quarters":
                                            intervalEnd = intervalStart.AddDays(givenInterval * 365.25 / 4.0);
                                            break;
                                        case "Weeks":
                                            intervalEnd = intervalStart.AddDays(givenInterval * 7);
                                            break;
                                        case "Days":
                                            intervalEnd = intervalStart.AddDays(givenInterval);
                                            break;
                                        case "Hours":
                                            intervalEnd = intervalStart.AddHours(givenInterval);
                                            break;
                                        case "Minutes":
                                            intervalEnd = intervalStart.AddMinutes(givenInterval);
                                            break;
                                        case "Seconds":
                                            intervalEnd = intervalStart.AddSeconds(givenInterval);
                                            break;
                                    }
                                }

                                string seriesName = string.Empty;
                                object independentValue = new object();

                                independentValue = BuildIndependentValue(independentVariable, row, config);

                                if (string.IsNullOrEmpty(seriesName))
                                {
                                    seriesName = SilverlightStatics.COUNT;

                                    if (_independentVariableArray.Length > 1)
                                    {
                                        seriesName = independentVariable;
                                    }

                                    if(string.IsNullOrEmpty(_aggregateFunction) == false)
                                    {
                                        seriesName = _aggregateFunction;
                                    }
                                }

                                if (string.IsNullOrEmpty(_weightVar))
                                {
                                    double dependentVal;

                                    if (double.TryParse(row["__Count__"].ToString(), out dependentVal))
                                    {
                                        if ((dateTimeValue >= intervalStart) && (dateTimeValue < intervalEnd))
                                        {
                                            string expression = "Predictor = #" + intervalStart.ToString() + "#";
                                            DataRow[] foundRows = _regressionTable.Select(expression);

                                            if (foundRows.Length == 0)
                                            {
                                                _regressionTable.Rows.Add(seriesName, intervalStart, dependentVal);
                                            }
                                            else
                                            {
                                                foundRows[0]["Response"] = (double)foundRows[0]["Response"] + dependentVal;
                                                _regressionTable.AcceptChanges();
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    filter.independentVarValue = row["__Values__"];
                                    filter.independentVarName = independentVariable;
                                    filter.weightVarName = _weightVar;
                                    double dependentVal = GetAggregateValue(sourceTable, filter);
                                    _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                }
                            }
                        }
                    }
                }
                else
                {
                    string categoryName = string.Empty;
                    Dictionary<object, double> indDepValuePairCollection = new Dictionary<object, double>();

                    List<string> StrataVarNameList = new List<string>();
                    List<string> StrataVarValueList = new List<string>();

                    foreach (string independentVariable in _independentVariableArray)
                    {
                        StrataVarNameList.Add(filter.strataVarName);
                        StrataVarValueList.Add(filter.strataVarValue);

                        DataTable workingTable = cWorkingTable.CreateWorkingTable(
                            independentVariable, 
                            "", 
                            config, 
                            sourceTable,
                            StrataVarNameList,
                            StrataVarValueList,
                            _weightVar);

                        foreach (DataRow row in workingTable.Rows)
                        {
                            if (row["__Values__"] != DBNull.Value)
                            {
                                string seriesName = string.Empty;
                                object independentValue = new object();

                                if (!_independentValueTypesSame || _graphType == SilverlightStatics.Pie )
                                {
                                    independentValue = BuildIndependentValue(independentVariable, row, config);
                                }
                                else if (_independentValuesAllBool)
                                {
                                    independentValue = independentVariable;
                                    byte value = (byte)(row["__Values__"]);

                                    seriesName = row["__Values__"].ToString();

                                    if (value == 0)
                                    {
                                        seriesName = config["RepresentationOfNo"];
                                    }
                                    else if (value == 1)
                                    {
                                        seriesName = config["RepresentationOfYes"];
                                    }
                                }
                                else
                                {
                                    independentValue = BuildIndependentValue(independentVariable, row, config);
                                }

                                if (string.IsNullOrEmpty(seriesName))
                                {
                                    seriesName = SilverlightStatics.COUNT;

                                    if (_independentVariableArray.Length > 1)
                                    {
                                        seriesName = independentVariable;
                                    }

                                    if(string.IsNullOrEmpty(_aggregateFunction) == false)
                                    {
                                        seriesName = _aggregateFunction;
                                    }
                                }

                                if (string.IsNullOrEmpty(_weightVar))
                                {
                                    //
                                    if (independentValue.ToString().ToUpperInvariant() == "TRUE")
                                    {
                                        independentValue = config["RepresentationOfYes"];
                                    }
                                    if (independentValue.ToString().ToUpperInvariant() == "FALSE")
                                    {

                                        independentValue = config["RepresentationOfNo"]; 
                                    }
                                    //
                                    double dependentVal;

                                    if (double.TryParse(row["__Count__"].ToString(), out dependentVal))
                                    {
                                        if ((_graphType == "EPICURVE" && independentValue is DateTime && ((DateTime)independentValue) <= _graphStartFrom) == false)
                                        {
                                            _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                        }
                                    }
                                }
                                else
                                {
                                    //
                                    if (independentValue.ToString().ToUpperInvariant() == "TRUE")
                                    {
                                        independentValue = config["RepresentationOfYes"];
                                    }
                                    if (independentValue.ToString().ToUpperInvariant() == "FALSE")
                                    {

                                        independentValue = config["RepresentationOfNo"]; 
                                    }
                                    //
                                    filter.independentVarValue = row["__Values__"];
                                    filter.independentVarName = independentVariable;
                                    filter.weightVarName = _weightVar;
                                    double dependentVal = GetAggregateValue(sourceTable, filter);
                                    _regressionTable.Rows.Add(seriesName, independentValue, dependentVal);
                                }
                            }
                        }
                    }
                }

                string graphreplacedle = _graphreplacedle;

                if (sourceTable.Columns.Contains(filter.strataVarName))
                {
                    Type _strataVarDataType = sourceTable.Columns[filter.strataVarName].DataType;
                    string strataVarText = filter.strataVarValue;

                    strataVarText = GetPrintValue(filter.strataVarName, _strataVarDataType.Name, filter.strataVarValue, config);

                    if (string.IsNullOrEmpty(_strataVar) == false)
                    {
                        graphreplacedle = string.Format("{0} {1}={2}", _graphreplacedle, filter.strataVarName, strataVarText);
                    }
                }

                DataView view = new DataView(_regressionTable);
                DataTable distinctValues = new DataTable();
                distinctValues = view.ToTable(true, "SeriesName");

                bool hideLegend = false;

                if (distinctValues.Rows.Count == 1 && distinctValues.Rows[0][0].ToString() == "COUNT")
                {
                    hideLegend = true;
                }

                objectElement = objectElement
                    + silverlight.Graph
                    (
                        _graphType,
                        graphreplacedle,
                        _graphIndependentAxisLabel,
                        _graphDependentAxisLabel,
                        "",
                        "",
                        _graphInterval,
                        _graphIntervalUnits,
                        _graphStartFrom,
                        _regressionTable,
                        hideLegend
                    );

                _regressionTable.Rows.Clear();
            }

            string data = string.Empty;

            if (objectElement != "")
            {
                data = objectElement + @"<hr/>";
            }
            else
            {
                data = SharedStrings.UNABLE_CREATE_GRAPH;
            }
            
            args.Add("COMMANDNAME", CommandNames.GRAPH);
            args.Add("DATA", data);
            args.Add("COMMANDTEXT", _commandText.Trim());
            Context.Display(args);
        }

19 Source : TabOrder.Designer.cs
with Apache License 2.0
from Epi-Info

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
            public TabOrderRow AddTabOrderRow(int FieldId, string Name, string PromptText, int TabIndex, bool HasTabStop) {
                TabOrderRow rowTabOrderRow = ((TabOrderRow)(this.NewRow()));
                object[] columnValuesArray = new object[] {
                        FieldId,
                        Name,
                        PromptText,
                        TabIndex,
                        HasTabStop};
                rowTabOrderRow.ItemArray = columnValuesArray;
                this.Rows.Add(rowTabOrderRow);
                return rowTabOrderRow;
            }

19 Source : Rule_Read.cs
with Apache License 2.0
from Epi-Info

public DataTable JoinTables(DataTable parentTable, DataTable childTable)
        {
            DataTable result = new DataTable("Output");

            using (DataSet dataset = new DataSet())
            {
                dataset.Tables.AddRange(new DataTable[] { parentTable.Copy(), childTable.Copy() });
                DataColumn parentColumn = dataset.Tables[0].Columns["GlobalRecordId"];
                DataColumn childColumn = dataset.Tables[1].Columns["GlobalRecordId"];
                DataRelation dataRelation = new DataRelation(string.Empty, parentColumn, childColumn, false);
                dataset.Relations.Add(dataRelation);

                for (int i = 0; i < parentTable.Columns.Count; i++)
                {
                    result.Columns.Add(parentTable.Columns[i].ColumnName, parentTable.Columns[i].DataType);
                }

                for (int i = 0; i < childTable.Columns.Count; i++)
                {
                    if (false == (childTable.Columns[i].ColumnName.Equals("RecStatus", StringComparison.CurrentCultureIgnoreCase) || childTable.Columns[i].ColumnName.Equals("FKey", StringComparison.CurrentCultureIgnoreCase) || childTable.Columns[i].ColumnName.Equals("GlobalRecordId", StringComparison.CurrentCultureIgnoreCase)))
                    {
                        if (!result.Columns.Contains(childTable.Columns[i].ColumnName))
                        {
                            result.Columns.Add(childTable.Columns[i].ColumnName, childTable.Columns[i].DataType);
                        }
                        else
                        {
                            int count = 0;
                            foreach (DataColumn column in result.Columns)
                            {
                                if (column.ColumnName.StartsWith(childTable.Columns[i].ColumnName))
                                {
                                    count++;
                                }
                            }
                            result.Columns.Add(childTable.Columns[i].ColumnName + count.ToString(), childTable.Columns[i].DataType);
                        }
                    }
                }

                foreach (DataRow parentRow in dataset.Tables[0].Rows)
                {
                    DataRow resultRow = result.NewRow();
                    DataRow[] childRow = parentRow.GetChildRows(dataRelation);

                    if (childRow != null && childRow.Length > 0)
                    {
                        foreach (DataColumn dataColumn in childTable.Columns)
                        {
                            resultRow[dataColumn.ColumnName] = childRow[0][dataColumn.ColumnName];
                        }

                        foreach (DataColumn dataColumn in parentTable.Columns)
                        {
                            resultRow[dataColumn.ColumnName] = parentRow[dataColumn.ColumnName];
                        }

                        result.Rows.Add(resultRow);
                    }
                }
                result.AcceptChanges();
            }

            return result;
        }

19 Source : Rule_Define.cs
with Apache License 2.0
from Epi-Info

public override object Execute()
        {
            try
            {
                IVariable var = null;

                #region Preconditions
                //zack check reserved word /11/16/09
                AppData appdata = new AppData();
                /*
                if (appdata.IsReservedWord(Identifier))
                {
                    throw new GeneralException(string.Format(SharedStrings.RESERVED_WORD, Identifier.ToUpperInvariant()));
                }*/

                if (this.Context.MemoryRegion.IsVariableInScope(Identifier))
                {

                    if (this.Context.MemoryRegion.TryGetVariable(this.Identifier, out var))
                    {
                        if (var.VarType != VariableType.Permanent)
                        {
                            this.Context.replacedysisCheckCodeInterface.Dialog(SharedStrings.DUPLICATE_VARIABLE_DEFINITION + StringLiterals.COLON + Identifier, CommandNames.DEFINE);
                        }

                    }
                    else
                    {
                        this.Context.replacedysisCheckCodeInterface.Dialog(SharedStrings.DUPLICATE_VARIABLE_DEFINITION + StringLiterals.COLON + Identifier, CommandNames.DEFINE);
                    }
                    
                }
                else if(this.Context.GroupVariableList.ContainsKey(this.Identifier))
                {
                    this.Context.replacedysisCheckCodeInterface.Dialog(SharedStrings.DUPLICATE_VARIABLE_DEFINITION + StringLiterals.COLON + Identifier, CommandNames.DEFINE);
                }
                #endregion Preconditions

                CommandProcessorResults results = new CommandProcessorResults();
                string dataTypeName = VariableTypeIndicator.Trim().ToUpperInvariant();
                DataType type = GetDataType(dataTypeName);
                string variableScope = Variable_Scope.Trim().ToUpperInvariant();
                VariableType vt = VariableType.Standard;
                if (!string.IsNullOrEmpty(variableScope))
                {
                    vt = this.GetVariableScopeIdByName(variableScope);
                }

                var = new Variable(Identifier, type, vt);
                string promptString = Define_Prompt.Trim().Replace("\"", string.Empty);
                if (!string.IsNullOrEmpty(promptString))
                {
                    promptString = promptString.Replace("(", string.Empty).Replace(")", string.Empty);
                    promptString.Replace("\"", string.Empty);
                }
                var.PromptText = promptString;
                this.Context.MemoryRegion.DefineVariable(var);

                if (var.VarType == VariableType.Standard || var.VarType == VariableType.Global)
                {
                    if (this.Context.VariableValueList.ContainsKey(var.Name.ToUpperInvariant()))
                    {
                        this.Context.VariableValueList.Remove(var.Name.ToUpperInvariant());
                    }
                    
                        
                    
                    DataTable dataTable;

                    if(!this.Context.DataSet.Tables.Contains("variables"))
                    {
                        this.Context.DataSet.Tables.Add(new DataTable("variables"));
                    }

                    dataTable = this.Context.DataSet.Tables["variables"];
                    DataColumn C = new DataColumn(var.Name);
                    
                    switch (var.DataType)
                    {
                        case DataType.Boolean:
                        case DataType.YesNo:
                            C.DataType = typeof(bool);
                            this.Context.VariableValueList.Add(var.Name.ToUpperInvariant(), false);
                            break;
                        case DataType.Date:
                        case DataType.DateTime:
                            C.DataType = typeof(DateTime);
                            this.Context.VariableValueList.Add(var.Name.ToUpperInvariant(), DateTime.Now);
                            break;
                        case DataType.Number:
                            C.DataType = typeof(double);
                            this.Context.VariableValueList.Add(var.Name.ToUpperInvariant(), 0.0);
                            break;
                        case DataType.Time:
                            C.DataType = typeof(System.TimeSpan);
                            this.Context.VariableValueList.Add(var.Name.ToUpperInvariant(), new TimeSpan());
                            break;

                        case DataType.PhoneNumber:
                        case DataType.Text:
                        case DataType.Unknown:
                        case DataType.Object:
                        default:
                            C.DataType = typeof(string);
                            this.Context.VariableValueList.Add(var.Name.ToUpperInvariant(), "");
                            break;
                    }

                    if (dataTable.Columns.Contains(C.ColumnName))
                    {
                        dataTable.Columns.Remove(C.ColumnName);
                    }
                    dataTable.Columns.Add(C);

                    this.Context.SyncVariableAndOutputTable();

                    if (this.Expression != null)
                    {
                        object vresult = null;
                        if (this.Context.VariableExpressionList.ContainsKey(this.Identifier.ToUpperInvariant()))
                        {
                            this.Context.VariableExpressionList[this.Identifier.ToUpperInvariant()] = this.Expression;
                        }
                        else
                        {
                            this.Context.VariableExpressionList.Add(this.Identifier.ToUpperInvariant(), this.Expression);
                        }

                        if (this.Context.CurrentDataRow != null)
                        {
                            vresult = this.Expression.Execute();
                            if (vresult == null)
                            {
                                this.Context.CurrentDataRow[var.Name] = DBNull.Value;
                            }
                            else
                            {
                                this.Context.CurrentDataRow[var.Name] = vresult;
                            }
                        }
                        else
                        {
                            
                            dataTable = this.Context.DataSet.Tables["output"];
                            if (dataTable.Rows.Count == 0)
                            {
                                DataRow R = dataTable.NewRow();
                                dataTable.Rows.Add(R);
                            }

                            this.Context.GetOutput(DefineMapDataFunction);

                            /*
                            vresult = null;
                            for (int i = 0; i < dataTable.Rows.Count; i++)
                            {
                                this.Context.CurrentDataRow = dataTable.Rows[i];
                                vresult = this.Expression.Execute();
                                if (vresult == null)
                                {
                                    this.Context.CurrentDataRow[var.Name] = DBNull.Value;
                                }
                                else
                                {
                                    this.Context.CurrentDataRow[var.Name] = vresult;
                                }
                            }
                            this.Context.CurrentDataRow = null;*/
                        }
                    }
                }
                Context.DefineVarList.Clear();

                Dictionary<string, string> args = new Dictionary<string, string>();
                args.Add("COMMANDNAME", CommandNames.DEFINE);
                this.Context.replacedysisCheckCodeInterface.Display(args);

                return results;
            }
            catch (Exception ex)
            {
                Epi.Diagnostics.Debugger.Break();
                Epi.Diagnostics.Debugger.LogException(ex);
                throw ex;
            }
        }

19 Source : Rule_Display.cs
with Apache License 2.0
from Epi-Info

private DataRow GetDataTable(DataColumn dataColumn, string tableText, string pattern, Dictionary<string, string> formatStrings, DataRow[] rows, DataTable table)
        {

            pattern = string.Empty;

            IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName);
            if (var != null)
            {
                if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined)
                {
                    formatStrings.TryGetValue(var.Name, out pattern);
                }
                else
                {
                    tableText = "Defined";
                }
            }
            else
            {
                //tableText = "Defined";
                var = new DataSourceVariable(dataColumn.ColumnName, DataType.Unknown);
            }

            DataRow row = table.NewRow();


            if (
                this.Context.CurrentRead != null &&
                this.Context.CurrentRead.IsEpi7ProjectRead &&
                this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier) &&
                this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields.Exists(var.Name)
                )
            {
                Epi.Fields.Field field = this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields[var.Name];
                if (field is FieldWithSeparatePrompt)
                {
                    row[ColumnNames.PROMPT] = ((FieldWithSeparatePrompt)field).PromptText;
                }
                else
                {
                    row[ColumnNames.PROMPT] = var.PromptText;
                }
                //Fiexes for Issue: 943
                if (field.FieldType.ToString() == MetaFieldType.Checkbox.ToString())
                {
                    row[ColumnNames.FIELDTYPE] = "Checkbox";
                }
                else
                {
                    row[ColumnNames.FIELDTYPE] = field.FieldType.ToString();
                }



            }
            else
            {
                row[ColumnNames.PROMPT] = var.PromptText;
                if (var.VarType == VariableType.Permanent)
                {
                    row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
                }
                else
                {

                    if (this.Context.DataSet.Tables.Contains("output"))
                    {                       
                        row[ColumnNames.FIELDTYPE] = GetVariableType(this.Context.DataSet.Tables["output"].Columns[var.Name].DataType.ToString());
                    }
                    else
                    {
                        row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
                    }
                }

            }

            row[ColumnNames.VARIABLE] = var.Name;

            row[ColumnNames.FORMATVALUE] = pattern;
            row[ColumnNames.SPECIALINFO] = var.VarType.ToString();
            row[ColumnNames.TABLE] = tableText;


            //  table.Rows.Add(row);

            return row;
        }

19 Source : Rule_Relate.cs
with Apache License 2.0
from Epi-Info

public DataTable JoinPagesTables(DataTable recStatusTable, DataTable pageTable)
        {
            DataTable result = new DataTable("Output");

            using (DataSet set = new DataSet())
            {
                set.Tables.AddRange(new DataTable[] { recStatusTable.Copy(), pageTable.Copy() });
                DataColumn parentColumn = set.Tables[0].Columns["GlobalRecordId"];
                DataColumn childColumn = set.Tables[1].Columns["GlobalRecordId"];
                DataRelation dataRelation = new DataRelation(string.Empty, parentColumn, childColumn, false);
                set.Relations.Add(dataRelation);

                for (int i = 0; i < recStatusTable.Columns.Count; i++)
                {
                    result.Columns.Add(recStatusTable.Columns[i].ColumnName, recStatusTable.Columns[i].DataType);
                }

                for (int i = 0; i < pageTable.Columns.Count; i++)
                {
                    bool isDataField = (
                            pageTable.Columns[i].ColumnName.Equals("RecStatus", StringComparison.CurrentCultureIgnoreCase) ||
                            pageTable.Columns[i].ColumnName.Equals("FKEY", StringComparison.CurrentCultureIgnoreCase) ||
                            pageTable.Columns[i].ColumnName.Equals("GlobalRecordId", StringComparison.CurrentCultureIgnoreCase
                            )) == false;
                    
                    if ( isDataField )
                    {
                        if (result.Columns.Contains(pageTable.Columns[i].ColumnName) == false)
                        {
                            result.Columns.Add(pageTable.Columns[i].ColumnName, pageTable.Columns[i].DataType);
                        }
                        else
                        {
                            int count = 0;
                            foreach (DataColumn column in result.Columns)
                            {
                                if (column.ColumnName.StartsWith(pageTable.Columns[i].ColumnName))
                                {
                                    count++;
                                }
                            }
                            
                            result.Columns.Add(pageTable.Columns[i].ColumnName + count.ToString(), recStatusTable.Columns[i].DataType);
                        }
                    }
                }

                foreach (DataRow parentRow in set.Tables[0].Rows)
                {
                    DataRow resultRow = result.NewRow();
                    DataRow[] childRow = parentRow.GetChildRows(dataRelation);

                    if (childRow != null && childRow.Length > 0)
                    {
                        foreach (DataColumn dataColumn in pageTable.Columns)
                        {
                            resultRow[dataColumn.ColumnName] = childRow[0][dataColumn.ColumnName];
                        }

                        foreach (DataColumn dataColumn in recStatusTable.Columns)
                        {
                            resultRow[dataColumn.ColumnName] = parentRow[dataColumn.ColumnName];
                        }

                        result.Rows.Add(resultRow);
                    }
                }
                
                result.AcceptChanges();
            }

            return result;
        }

19 Source : EntityDataReader.cs
with Apache License 2.0
from Epi-Info

public override DataTable GetSchemaTable()
    {
      DataSet s = new DataSet();
      s.Locale = System.Globalization.CultureInfo.CurrentCulture;
      s.ReadXmlSchema(new System.IO.StringReader(shemaTableSchema));
      DataTable t = s.Tables[0];
      for (int i = 0; i < this.FieldCount; i++)
      {
        DataRow row = t.NewRow();
        row["ColumnName"] = this.GetName(i);
        row["ColumnOrdinal"] = i;

        Type type = this.GetFieldType(i);
        if (type.IsGenericType
          && type.GetGenericTypeDefinition() == typeof(System.Nullable<int>).GetGenericTypeDefinition())
        {
          type = type.GetGenericArguments()[0];
        }
        row["DataType"] = this.GetFieldType(i);
        row["DataTypeName"] = this.GetDataTypeName(i);
        row["ColumnSize"] = -1;
        t.Rows.Add(row);
      }
      return t;

    }

19 Source : TabOrder.Designer.cs
with Apache License 2.0
from Epi-Info

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "15.0.0.0")]
            public TabOrderRow NewTabOrderRow() {
                return ((TabOrderRow)(this.NewRow()));
            }

19 Source : MemoryRegion.cs
with Apache License 2.0
from Epi-Info

private DataRow AddRow(DataTable table, IVariable var)
        {
            DataRow row = table.NewRow();
            row[ColumnNames.NAME] = var.Name;
            row[ColumnNames.DATA_TYPE] = var.DataType;
            row[ColumnNames.VARIABLE_SCOPE] = var.VarType;
            row[ColumnNames.VARIABLE_VALUE] = var.Expression;
            row[ColumnNames.ADDITIONAL_INFO] = string.Empty;
            row[ColumnNames.PROMPT] = string.Empty;

            // Data source variables have an extra piece of information: Table name
            if (var is IDataSourceVariable)
            {
                IDataSourceVariable dataSourceVar = var as IDataSourceVariable;
                row[ColumnNames.DATA_TABLE_NAME] = dataSourceVar.TableName;

            }

            // Data field variables know the field type.
            if (var is IDataField)
            {
                IDataField dataField = var as IDataField;
                row[ColumnNames.FIELD_TYPE_ID] = dataField.FieldType;
            }

            table.Rows.Add(row);
            return row;
        }

19 Source : Rule_Write.cs
with Apache License 2.0
from Epi-Info

private void PopulateTable(Dictionary<string, List<TableColumn>> pTableColumns)
        {

            //DataTable sourceTable = OutputDriver.GetTableData(this.TableName);
            //DataTable sourceTable = OutputDriver.GetTableData(this.TableName);
            foreach (KeyValuePair<string, List<TableColumn>> kvp in pTableColumns)
            {
                StringBuilder ColumnSQL = new StringBuilder();
                DataTable WritableTable = CurrentDataTable.Clone();
                List<TableColumn> TableColumns = kvp.Value;

                for (int i = WritableTable.Columns.Count - 1; i > -1; i--)
                {
                    DataColumn col = WritableTable.Columns[i];
                    bool isFound = false;
                    foreach (TableColumn TC in TableColumns)
                    {
                        if (TC.Name.Equals(col.ColumnName, StringComparison.OrdinalIgnoreCase))
                        {
                            isFound = true;
                            break;
                        }
                    }

                    if (!isFound)
                    {
                        WritableTable.Columns.Remove(col);
                    }
                }

                foreach (DataRow row in CurrentDataTable.Select("", this.Context.SortExpression.ToString()))
                {
                    DataRow newRow = WritableTable.NewRow();
                    foreach (TableColumn column in TableColumns)
                    {
                        newRow[column.Name] = row[column.Name];
                    }
                    WritableTable.Rows.Add(newRow);
                }


                System.Data.Common.DbDataReader DataReader = WritableTable.CreateDataReader();
                DBReadExecute.InsertBulkRows(FilePath, "Select * From [" + kvp.Key + "]", DataReader, SetGadgetStatusHandler);

                this.OutTarget += "<br/>" + FilePath + "\\" + kvp.Key;
            }


            if (CurrentDataTable.Rows.Count > 0)
            {
                this.statusMessage = "Export completed successfully, ";
            }
            else
            {
                this.statusMessage = "Export was not completed successfully, ";
            }
            this.statusMessage += CurrentDataTable.Rows.Count.ToString() + " records written.";

        }

19 Source : Template.cs
with Apache License 2.0
from Epi-Info

public DataTable GetProjectTable(string subFolder)
        {
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("TemplateName", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("TemplateDescription", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("TemplatePath", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("TemplateCreateDate", System.Type.GetType("System.String")));
 
            table.Columns.Add(new DataColumn("Name", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("Location", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("Description", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("EpiVersion", System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("CreateDate", System.Type.GetType("System.String")));
            DataRow row;

            string projectFolderPath = Path.Combine(templatesPath, subFolder);
            
            if (Directory.Exists(projectFolderPath) != true)
            {
                return table;
            }

            String[] projectTemplates = GetFiles(projectFolderPath, "*.xml;*.eit");

            foreach(string path in projectTemplates)
            {
                row = table.NewRow();

                try
                {
                    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(path))
                    {
                        while (reader.ReadToFollowing("Template"))
                        {
                            if (reader.MoveToFirstAttribute())
                            {
                                AddAttributeToProjectTableRow(row, reader);

                                while (reader.MoveToNextAttribute())
                                {
                                    AddAttributeToProjectTableRow(row, reader);
                                }

                                while (reader.ReadToFollowing("Project"))
                                {
                                    if (reader.MoveToFirstAttribute())
                                    {

                                        if (table.Columns.Contains(reader.Name))
                                        {
                                            row[reader.Name] = reader.Value;
                                        }

                                        while (reader.MoveToNextAttribute())
                                        {
                                            if (table.Columns.Contains(reader.Name))
                                            {
                                                row[reader.Name] = reader.Value;
                                            }
                                        }
                                    }
                                }

                                row["TemplatePath"] = path;
                                table.Rows.Add(row);
                            }
                        }
                    }
                }
                catch{}
            }

            return table;
        }

See More Examples