Infragistics Filtered Row Scanning. Goal is to sum of all filtered rows based on column - infragistics

I have Infragistics UltraGrid which is filtered on different conditions. Now i want to sum of couple of columns from filtered row result. Check following code
UltraGridColumn column = this.ugResults.DisplayLayout.Bands[0].Columns["Air45HValue"];
double a = 0;
for (int i = 0; i < filtInCnt; i++)
{
if (ugResults.Rows[i].GetCellValue(column) != DBNull.Value)
{
a = a + Convert.ToDouble(ugResults.Rows[i].GetCellValue(column));
}
}
This does not give me a correct answer. I think, calculation is doing on original data source, not on filtered one. How can i do above function on filtered results?

Your code looks correct as I tested it in a small sample application. However, I do not see how you get filtInCnt as I would suggest you to use ugResults.Rows.GetFilteredInNonGroupByRows() instead. This method returns all the filtered rows. Then you should for each the collection and perform your calculations. Here is the code:
namespace WindowsFormsApplication1
{
using System;
using System.Data;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ultraGrid1.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.True;
this.ultraGrid1.DisplayLayout.Override.FilterUIType = FilterUIType.FilterRow;
this.ultraGrid1.DataSource = GetDataTable();
}
private DataTable GetDataTable(int rows = 100)
{
DataTable table = new DataTable("Table1");
table.Columns.Add("Integer column", typeof(int));
table.Columns.Add("DateTime column", typeof(DateTime));
table.Columns.Add("String column", typeof(string));
for (int i = 0; i < rows; i++)
{
DataRow row = table.NewRow();
row["Integer column"] = i;
row["String column"] = "text";
row["DateTime column"] = DateTime.Today.AddDays(i);
table.Rows.Add(row);
}
return table;
}
private void ultraButton1_Click(object sender, EventArgs e)
{
UltraGridColumn column = this.ultraGrid1.DisplayLayout.Bands[0].Columns["Integer column"];
double a = 0;
foreach(var row in this.ultraGrid1.Rows.GetFilteredInNonGroupByRows())
{
var cellValue = row.GetCellValue(column);
if(cellValue != DBNull.Value)
{
a = a + Convert.ToDouble(cellValue);
}
}
MessageBox.Show("Result: " + a);
}
}
}

Related

insert whole list of data into sql database table in xamarin.android

i'm trying to create an application where data in a list must be inserted into a database table at once. I made some research and found out that this is possible using user-defined table types where in c# a datatable is used and passed to a stored procedure that is executed. now my problem is that there are no data tables in Xamarin.Android. so I thought to use a list instead. my idea was to create a list in the application and pass it to the webservice method, and in my webservice method I receive the list and convert it to a datatable then pass it as a parameter to the stored procedure. I wrote the following codes:
in my webservice:
[WebMethod]
public bool insrt_dt(List<Class1> lst)
{
SqlParameter param;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
DataTable dt = list_to_dt(lst);
SqlCommand cmd = new SqlCommand("Insert_Customers", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
param = new SqlParameter("#tblcustomers", dt);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
cmd.CommandTimeout = 300;
int a=cmd.ExecuteNonQuery();
if (a > 0)
{
return true;
}
else return false;
}
}
Class1:
public class Class1
{
public int id { get; set; }
public string name { get; set; }
public string country { get; set; }
}
in my Xamarin.Android app
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += delegate
{
wr.WebService1 ws = new wr.WebService1();
wr.Class1 class1 = new wr.Class1();
List<wr.Class1> lst = new List<wr.Class1>(){
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
ws.insrt_dt(lst);
ws.insrt_dtCompleted += Ws_insrt_dtCompleted;
};
}
private void Ws_insrt_dtCompleted(object sender, wr.insrt_dtCompletedEventArgs e)
{
bool l = e.Result;
if (l == true)
Toast.MakeText(this, "khh", ToastLength.Long).Show();
else
Toast.MakeText(this, "ijo'pioo", ToastLength.Long).Show();
}
}
but I keep getting this error:
Argument 1: cannot convert from 'System.Collections.Generic.List<app_dt.wr.Class1>' to 'app_dt.wr.Class1[]
so I used these lines instead
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
wr.Class1[] class1s = lst.ToArray();
ws.insrt_dt(class1s);
now I don't get an error, but it doesn't work, I mean why does it say that the webservice method input must be an array and I've created it as a list. any suggestions for this?
As i know, Xamarin do not support System.Data.SqlClient. If you want to use the database for the Xamarin android project, you could use the SQLite.NET.
Install the package from the NuGet.
NuGet: sqlite-net-pcl https://www.nuget.org/packages/sqlite-net-pcl/
For the code sample about how to use the database in Xamarin, you could check the link below. https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
For Xamarin.Android, you could check the sample code in the link below. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm

Trying to fill in a List of class

I'm really sorry I'm such a beginner...
At the end I just have a list of 8 TimeCardDayStrip with the same name/position when it'd supposed to be the 8 different names/roles.
I don't understand what I'm doing wrong here:
thank you very much
'''
class TimeCardDayStrip {
String name, position;
DateTime day;
#override
String toString(){
return '{ $this.name, $this.position }';
}
}
void main() {
var tcds = TimeCardDayStrip();
var listOfTcds = [];
List<String> names, roles;
names = ["Michael", "Gunnell", "Byrne", "Aspromonte", "Davis", "Adam Jordan", "Mirko"];
roles = ["Director", "Vice", "President", "1ST", "KEY 2ND", "2ND", "BASECAMP PA", "PA", " PA", "Add'l PA"];
for (int i = 0; i < names.length; i++) {
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print(listOfTcds[i].name+' is '+listOfTcds[i].position);
}
//print the list of card to check
print('print the list of time card to check');
for (int x = 0; x < listOfTcds.length; x++){
print (listOfTcds.elementAt(x).name);
}
}
'''
If you just want to print out each name:
Put this within the loop (you should create new object each loop instead of updating the same one)
for (int i = 0; i < names.length; i++) {
var tcds = TimeCardDayStrip();
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print('${listOfTcds[i].name} is ${listOfTcds[i].position}');
}
Then later
listOfTcds[x].name
If you want to display stuff:
#override
Widget build(BuildContext ctx) {
return ListView.builder(
itemCount: listOfTcds.length,
itemBuilder: (context, index) {
return CustomTile(item: listOfTcds[index]);
},
);
}
I believe you need to declare the tcds as Tcds = new TimecardDayStrip() and not just tcds = TimeCardDayStrip() or you are just changing the same object and not creating a new instance.

How to make oledb query asychronous

I'm having problems with this query, it takes a long time to run and is timing out. I wanted to try to make it async but I can't find a good example that's close to what I'm trying to do.
Below is what I've tried, it starts but does nothing. This is inside a WinForm project.
namespace access_db_csharp
{
public partial class Form1 : Form
{
string SQL = "";
public Form1()
{
InitializeComponent();
textBox1.Text = "Select Project, Request, Release, TestName, AssignmentNumber, Formulation, Container, Closure FROM tblWtLossBottDropResults";
textBox2.Text = "Where Container LIKE '%2700-305%'";
dataGridView1.Focus();
}
OleDbConnection con=new OleDbConnection ();
OleDbCommand cmd=new OleDbCommand ();
string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=K:\R&D Dept\Development Lab\DLab Databases and Add Ins\DLab Results Database\DLab Results Individual Tables.accdb;Jet OLEDB:Database Password='roscoe'";
private async void button1_Click(object sender, EventArgs e)
{
Task<DataTable> task = new Task<DataTable>(RunQuery);
task.Start();
}
private DataTable RunQuery()
{
if (checkBox1.Checked == true)
{
SQL = textBox1.Text + " " + textBox2.Text;
}
else
{
SQL = textBox1.Text;
}
OleDbConnection con = new OleDbConnection(connectionstring);
OleDbCommand cmd = new OleDbCommand(SQL, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable tblWtLossBottDropResults = new DataTable();
da.Fill(tblWtLossBottDropResults);
dataGridView1.DataSource = tblWtLossBottDropResults;
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
return tblWtLossBottDropResults;
}
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = connectionstring;
con.Open();
}
}
}
Ideally I want to get the data from the query and load it into a datagridview table.
There are a few things you should change:
1. You should not mix UI and non-UI code.
2. You should keep your connection open for the shortest amount of time.
Because the OleDb provider doesn't have asynchronous APIs, your database code will be synchronous:
private DataTable RunQuery(string commandText)
{
using (var connection = new OleDbConnection(connectionstring))
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
using (var dataAdapter = new OleDbDataAdapter(command))
{
connection.Open();
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
}
Because it's a Windows Forms application you can use Task.Run to offload that work to the thread pool and free the UI thread:
private async void button1_Click(object sender, EventArgs e)
{
var commandText = checkBox1.Checked
? textBox1.Text + " " + textBox2.Text
: textBox1.Text;
var dataTable = await Task.Run(() => RunQuery(commandText));
/* This should be set on the designer or on the constructor
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
*/
dataGridView1.DataSource = dataTable;
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
}

Top n Record from infragistics xamdatagrid in wpf

I have a wpf application in which I am using xamdatagrid of infragistics 14.2 to show data.
Sometimes grid may contains more than 1000 record.In same application I have given print option to print grid data.for printing I am using Report object of Infragistics.but before printing I am generating preview of print data using xamprintpreview control.
When grid contains large data (for 1000 record) it takes 35 seconds to generate preview for 1000 records.
I am binding Datatable to xamdatagrid(so you can say every record is a type of DataRow).
To speedup the process of preview I have an idea to show only top n record of grid in preview.but I am not able to fetch top n record of grid and store them in a datatable because if I take 10 record from datatable that I have binded to grid and user has applied some filter on grid so my preview mismatch with actual grid.
So please help me to fetch tp 10 record from grid that is currently displayed and store them in
datatable.
Thanks in advance...
You have a complete working example here
The keys are:
xamDataGrid.RecordManager.GetFilteredInDataRecords() gives your the filtered records. If you have not any filter it gives you all records.
Then Take(10) will take ten as much.
And I implemented ToDataTable as an extension method to convert the records taken to a datatable.
<Window x:Class="Stackoverflow1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:igDP="http://infragistics.com/DataPresenter"
xmlns:local="clr-namespace:Stackoverflow1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<igDP:XamDataGrid x:Name="xamDataGrid" Loaded="XamDataGrid_Loaded">
<igDP:XamDataGrid.FieldLayoutSettings>
<igDP:FieldLayoutSettings FilterUIType="LabelIcons"/>
</igDP:XamDataGrid.FieldLayoutSettings>
<igDP:XamDataGrid.FieldSettings>
<igDP:FieldSettings AllowRecordFiltering="True" FilterLabelIconDropDownType="MultiSelectExcelStyle"/>
</igDP:XamDataGrid.FieldSettings>
<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>
<igDP:Field Name="Date"/>
<igDP:Field Name="Order"/>
</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>
</igDP:XamDataGrid>
<Button x:Name="btnPrintPreview" Content="Print Preview" Height="25" Width="100" Click="btnPrintPreview_Click"/>
</Grid>
</Window>
using Infragistics.Windows.DataPresenter;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows;
namespace Stackoverflow1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void XamDataGrid_Loaded(object sender, RoutedEventArgs e)
{
ObservableCollection<Item> list = new ObservableCollection<Item>();
for (int i = 0; i < 15; ++i)
{
list.Add(new Item { Date = DateTime.Now.AddDays(-i), Order = i});
}
xamDataGrid.DataSource = list;
}
private void btnPrintPreview_Click(object sender, RoutedEventArgs e)
{
IEnumerable<DataRecord> data = xamDataGrid.RecordManager.GetFilteredInDataRecords();
DataTable dt = data.Take(10).ToDataTable();
// DO YOUR PRINT PREVIEW
}
}
class Item
{
public DateTime Date { get; set; }
public int Order { get; set; }
}
static class Utils
{
public static DataTable ToDataTable(this IEnumerable<DataRecord> items)
{
if (items.Count() > 0)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Item));
DataTable table = new DataTable();
List<Item> list = new List<Item>();
foreach (var item in items)
{
list.Add((Item)item.DataItem);
}
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (Item item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
return null;
}
}
}
In the code behind in an event handler:
private void Button_ClickEventHandler(object sender, MouseButtonEventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Data1");
table.Columns.Add("Data2"); //etc... Add all columns necessary
var records = XamDataGridName.Records.Take(10);
foreach (var record in records)
{
var item = ((DataRecord)record).DataItem as DataType;
if (item != null)
{
table.Rows.Add(item.Data1, item.Data2);
}
}
}
Or using MVVM you can send the XamDataGrid.Records as a command parameter to a command in your view model and then loop through the data records, adding them to your data table.

CouchDB reduce bug when grouping?

I have a map reduce query that aggregates values extracted from several documents into a single aggregated document that maps to the object structure of by client application.
My key on the outputs is a 2 element array with a dataset identifier and a dataset country segment.
When I run the reduce on 'exact' grouping this works reliably.
The Problem: As soon as I aggregate the data by the dataset identifier only ie. I use group level 1, some of the values are incorrect, most of the incorrect ones are doubled, but some of them have other values. Is there any known issue, or is this a bug with my code?
After running my map query, I have a set of values that looks like:
{ [type]:
{ date:
{ [metric]: [value],
[more metric value combinations]
}
}
}
I have several documents and run a reduce that should join them so that I get the following structure:
{ type1:
{ date:
{ [metric]: [value],
[more metric value combinations]
},
anotherdate:
{ [metric]: [value],
[more metric value combinations]
},
},
type2:
{ date:
{ [metric]: [value],
[more metric value combinations]
}
},
}
To achieve this I use the following reduce query:
function (keys, values) {
//return values[0];
var returndoc = values[0];
for (var i = 1; i < values.length; i++) {
//Merge the current and previous object
returndoc = MergeDocs(returndoc, values[i]);
}
return returndoc;
}
function MergeDocs(doc1, doc2) {
var types = ['Live', 'Benchmark'];
for (var i = 0; i < types.length; i++) {
var t = types[i];
// if the source document does not Benchmark or Live column,
// create it and add values from the other document.
if (!doc1[t] && doc2[t]) {
doc1[t] = doc2[t];
}
// if the source document has a value and the other
// document exists, sum values.
else if (doc1[t] && doc2[t]) {
doc1[t] = MergeReports(doc1[t], doc2[t]);
}
}
return doc1;
}
function MergeReports(report1, report2) {
// iterate over the dates in the report in the report
for (var date in report2) {
// if there is no value for
if (!report1[date]) {
report1[date] = report2[date];
} else {
for (var metric in report2[date]) {
if (!report1[date][metric]) {
report1[date][metric] = report2[date][metric];
} else {
report1[date][metric] =
report1[date][metric] + report2[date][metric];
}
}
}
}
return report1;
}