aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.Shared/SQL/RemoteSqlDataSet.cs
blob: 72b8d2eb2f1520ca4960a82d578141b6102bf375 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.PPC.Shared.SQL
{
    /// <summary>
    /// Represents remote database query result composed of rows and columns.
    /// </summary>
    /// <example>
    /// <para>
    /// <i>
    /// The following example demonstrates how to set the connected machine's demo state and query for the connected machine's jobs.
    /// </i>
    /// </para>
    /// <code lang="C#" source="../Tango.FSE.Procedures/Examples/Sql/Program.cs" title="Remote SQL" region="Example" />
    /// </example>
    public class RemoteSqlDataSet
    {
        /// <summary>
        /// Gets or sets the dataset columns.
        /// </summary>
        public RemoteSqlColumnCollection Columns { get; set; }

        private ObservableCollection<RemoteSqlRow> _rows;
        /// <summary>
        /// Gets or sets the dataset rows.
        /// </summary>
        public ObservableCollection<RemoteSqlRow> Rows
        {
            get { return _rows; }
            set { _rows = value; OnRowsChanged(); }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RemoteSqlDataSet"/> class.
        /// </summary>
        public RemoteSqlDataSet()
        {
            Columns = new RemoteSqlColumnCollection();
            Rows = new ObservableCollection<RemoteSqlRow>();
        }

        private void OnRowsChanged()
        {
            if (Rows != null)
            {
                Rows.CollectionChanged -= Rows_CollectionChanged;
                Rows.CollectionChanged += Rows_CollectionChanged;

                InitRows();
            }
        }

        private void Rows_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            InitRows();
        }

        private void InitRows()
        {
            if (Rows != null)
            {
                foreach (var row in Rows.ToList())
                {
                    row.Init(
                        (key) =>
                        {
                            return row.Values[Columns.GetIndexOf(key)];
                        },
                        (index) =>
                        {
                            return row.Values[index];
                        });
                }
            }
        }

        /// <summary>
        /// Creates a new <see cref="RemoteSqlDataSet"/> using the specified <see cref="SqlDataReader"/>.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns></returns>
        public static Task<RemoteSqlDataSet> Load(SqlDataReader reader)
        {
            return Task.Factory.StartNew<RemoteSqlDataSet>(() =>
            {
                bool columnsRead = false;
                RemoteSqlDataSet dataSet = new RemoteSqlDataSet();

                try
                {
                    while (reader.Read())
                    {
                        RemoteSqlRow row = new RemoteSqlRow();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            if (!columnsRead)
                            {
                                dataSet.Columns.Add(new RemoteSqlColumn()
                                {
                                    Name = reader.GetName(i)
                                });
                            }

                            row.Values.Add(reader.GetValue(i));
                        }

                        columnsRead = true;
                        dataSet.Rows.Add(row);
                    }
                }
                finally
                {
                    reader.Close();
                }

                return dataSet;
            });
        }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return String.Join(", ", Columns.Select(x => x.Name)) + "\n" + String.Join(Environment.NewLine, Rows.Select(x => x.ToString()));
        }

        /// <summary>
        /// Formats this dataset as a string with columns and rows.
        /// </summary>
        /// <returns></returns>
        public String ToTableString()
        {
            Dictionary<int, int> columnsMaxLength = new Dictionary<int, int>();

            for (int i = 0; i < Columns.Count; i++)
            {
                columnsMaxLength.Add(i, Columns[i].Name.Length);
            }

            foreach (var row in Rows)
            {
                for (int i = 0; i < row.Values.Count; i++)
                {
                    int valueLength = row.Values[i].ToStringSafe().Length;

                    if (valueLength > columnsMaxLength[i])
                    {
                        columnsMaxLength[i] = valueLength;
                    }
                }
            }

            String str = String.Empty;

            for (int i = 0; i < Columns.Count; i++)
            {
                str += $"{Columns[i].Name.PadRight(columnsMaxLength[i])}{(i < Columns.Count - 1 ? " | " : "")}";
            }

            int width = str.Length;
            str += Environment.NewLine + String.Empty.PadRight(width, '-');

            foreach (var row in Rows)
            {
                str += Environment.NewLine;

                for (int i = 0; i < row.Values.Count; i++)
                {
                    str += $"{row.Values[i].ToStringSafe().PadRight(columnsMaxLength[i])}{(i < Columns.Count - 1 ? " | " : "")}";
                }
            }

            return str;
        }
    }
}