Recommended BatchSize for dealing with total x milion transaction - c#

Goal:
Handle a big batchsize based on total 3 million transaction (at least 3 milion) without any error or bug.
Problem:
How much can batchsize contain in order make a transaction based on total transaction of 3 million?
I don't want any bug or similiar during the process time of dealing with total of 3 milion transaction.
Info:
*The code is a sample and in reality the size is much bigger.
*The data is dummy.
*The total transaction can be larger size than 3 milion.
Thank you!
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApp9
{
public static class Program
{
private static int _loop = 20000; // 20 000 transaction
static void Main(string[] args)
{
List<Test> listOfTest = new List<Test>();
for (int i = 0; i < _loop; i++)
{
var price = NextDecimal(new Random());
var rank = new Random().Next(int.MinValue, int.MaxValue);
Test test = new Test(price, rank);
listOfTest.Add(test);
}
InsertData(listOfTest);
}
public static string GetConnectionString()
{
return
"Data Source=" +
"Initial Catalog=Test;" +
"Integrated Security=SSPI;";
}
private static void InsertData(List<Test> listOfTest)
{
const string queryConst = "INSERT INTO dbo.TestTbl (Price, Rank) " +
"VALUES ";
const int batchMaxSize = 5;
string query = queryConst;
var sep = "";
var batchSize = 0;
using (SqlConnection cn = new SqlConnection(GetConnectionString()))
using (SqlCommand cmd = new SqlCommand("", cn))
{
try
{
cn.Open();
for (int i = 0; i < listOfTest.Count; i++)
{
batchSize++;
query += $#"{sep}(#Price{i}, #Rank{i})";
cmd.Parameters.Add("#Price" + i.ToString(), SqlDbType.Decimal).Value = listOfTest[i].Price;
cmd.Parameters.Add("#Rank" + i.ToString(), SqlDbType.Int).Value = listOfTest[i].Rank;
sep = ",";
if ((batchSize == batchMaxSize) || ((i + 1) == listOfTest.Count))
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
batchSize = 0;
query = queryConst;
sep = "";
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
cn.Close();
}
}
}
public static decimal NextDecimal(this Random rng)
{
byte scale = (byte)rng.Next(29);
bool sign = rng.Next(2) == 1;
return new decimal(rng.NextInt32(),
rng.NextInt32(),
rng.NextInt32(),
sign,
scale);
}
public static int NextInt32(this Random rng)
{
int firstBits = rng.Next(0, 1 << 4) << 28;
int lastBits = rng.Next(0, 1 << 28);
return firstBits | lastBits;
}
}
public class Test
{
public Test(decimal price, int rank)
{
this.Price = price;
this.Rank = rank;
}
public decimal Price{ get; set; }
public int Rank { get; set; }
}
}
CREATE TABLE [dbo].[TestTbl]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Price] [decimal](38, 5) NULL,
[Rank] [int] NULL
)

Related

Export SQL Results To a Three Lines Text File

The Below Code Returns the following data into text file from the database.
Output
InvoiceNo InvoiceDate Amount Vat Total
001 1/1/2018 200 10 210
002 2/1/2018 300 15 315
What i am looking for is to get Amount,Vat and Total in separate line with the same invoice info so Desired out will be like below
Desired out
001 1/1/2018 200
001 1/1/2018 10
001 1/1/2018 210
002 2/1/2018 300
002 2/1/2018 15
002 2/1/2018 315
Code
private void button1_Click(object sender, EventArgs e)
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = #"C:\Log\";
try
{
string FileNamePart = "Invoice";
string DestinationFolder = #"C:\Destination\";
string TableName = "Invoice";
string FileDelimiter = ",";
string FileExtension = ".txt";
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "Data Source = .\\SQLEXPRESS; Initial Catalog =Backoffice; "
+ "Integrated Security=true;";
string query = "Select * From " + TableName;
SqlCommand cmd = new SqlCommand(query, SQLConnection);
SQLConnection.Open();
DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
SQLConnection.Close();
string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + datetime + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
MessageBox.Show("Done..");
}
catch (Exception exception)
{
}
}
How can I archives geting Amount,Vat and Total in separate line with Thanks.
Edit
I was thinking about this answer and I realized I assumed you would want to use this invoice data elsewhere. If you don't need to use the data elsewhere, you can just use this block of code. It doesn't store the data returned from the sql call in an object.
try {
var invoices = new List<Invoice>();
using (var SQLConnection = new SqlConnection(ConnectionString)) {
SQLConnection.Open();
using (var cmd = new SqlCommand(query, SQLConnection))
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
// Note: You should handle nulls if the sql columns are nullable
var number = (int)reader["InvoiceNo"];
var date = (DateTime)reader["InvoiceDate"];
var amount = (int)reader["Amount"];
var vat = (int)reader["Vat"];
var total = (int)reader["Total"];
var iNumAndDate = $"{number}{FileDelimiter}{date.ToString("M/dd/yyyy")}{FileDelimiter}";
sw.Write($"{iNumAndDate}{amount}");
sw.Write($"{iNumAndDate}{vat}");
sw.Write($"{iNumAndDate}{total}");
sw.Write(sw.NewLine);
}
}
}
}
catch (Exception exception) {
// TODO: Handle exceptions
}
Original:
First, I would make a class to store each Invoice, we'll call it Invoice
class Invoice
{
public int Number { get; set; }
public DateTime Date { get; set; }
public int Amount { get; set; }
public int Vat { get; set; }
public int Total { get; set; }
}
Then, just store your data from the dB in a List<Invoice> and then loop through this list to write to the file.
try {
var invoices = new List<Invoice>();
using (var SQLConnection = new SqlConnection(ConnectionString))
{
SQLConnection.Open();
using (var cmd = new SqlCommand(query, SQLConnection))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
invoices.Add(new Invoice {
// Note: You should handle nulls if the sql columns are nullable
Number = (int)reader["InvoiceNo"],
Date = (DateTime)reader["InvoiceDate"],
Amount = (int)reader["Amount"],
Vat = (int)reader["Vat"],
Total = (int)reader["Total"]
});
}
}
}
using (sw = new StreamWriter(FileFullPath, false))
{
foreach (var invoice in invoices)
{
var iNumAndDate = $"{invoice.Number}{FileDelimiter}{invoice.Date.ToString("M/dd/yyyy")}{FileDelimiter}";
sw.Write($"{iNumAndDate}{invoice.Amount}");
sw.Write($"{iNumAndDate}{invoice.Vat}");
sw.Write($"{iNumAndDate}{invoice.Total}");
sw.Write(sw.NewLine);
}
}
}
catch (Exception exception)
{
// TODO: Handle exceptions
}
You could do something like this :
foreach (DataRow dr in d_table.Rows)
{
StringBuilder builder = new StringBuilder();
for (int ir = 0; ir < 3; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
builder.Append(dr[ir].ToString());
}
builder.Append(FileDelimiter);
}
var lineStart = builder.ToString();
for (int ir = 3; ir < 6; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(lineStart);
sw.Write(dr[ir].ToString());
sw.Write(sw.NewLine);
}
}
}

Update columns of database from csv file. Csv file could contain variable number of columns

Need your help. I have to get csv file from user and update database columns according to that file.
For Example:
File has following fields:
Name | Description | Date
Another file has:
Name | Price
Please Guide me how i could do this in c# using sql 2008.
From checkboxes user can select columns which he wants to update.
else if (count == 4 && dataGridView1.ColumnCount - 1 == 4)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
int id = Convert.ToInt32(dataGridView1.Rows[i].Cells["Id"].Value);
ItemsC.UpdateDatacolumns(id, columnsList[1], dataGridView1.Rows[i].Cells[1].Value.ToString(), columnsList[2], dataGridView1.Rows[i].Cells[2].Value.ToString(), columnsList[3], dataGridView1.Rows[i].Cells[3].Value.ToString());
}
}
else if (count == 5 && dataGridView1.ColumnCount - 1 == 5)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
int id = Convert.ToInt32(dataGridView1.Rows[i].Cells["Id"].Value);
ItemsC.UpdateDatacolumns(id, columnsList[1], dataGridView1.Rows[i].Cells[1].Value.ToString(), columnsList[2], dataGridView1.Rows[i].Cells[2].Value.ToString(), columnsList[3], dataGridView1.Rows[i].Cells[3].Value.ToString(), columnsList[4], dataGridView1.Rows[i].Cells[4].Value.ToString());
}
}
In Backend Just Override Update Method:
public static bool UpdateDatacolumns(int id, string column, string value, string column2, string value2)
{
SqlConnection conn = database.getConnection();
string query = "update destinationItemTable set " + column + "= #value ," + column2+" =#value2 where Id=#id";
try
{
var p1 = new SqlParameter("#id", id);
var p2 = new SqlParameter("#value", value);
var p3 = new SqlParameter("#value2", value2);
var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text };
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cmd.Connection = conn;
conn.Open();
bool result = (cmd.ExecuteNonQuery() > 0);
cmd.Dispose();
return result;
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}

Must declare the scalar variable on #wachtwoord SQL

I got this error:
Must declare the scalar variable #wachtwoord
I tried to solve it using this post: same error but with no luck so far. I am a bit lost. I want the generate a code for #wachtwoord (password). Then I want to count all the rows in the database. I will use the count for my for statement, in my for statement will be an UPDATE statement to update every row in the database with their own generated password.
If you guys have any advise or a solution for this problem it would be great!
This is my code:
public partial class Form1 : Form
{
string cn = "Data Source=pc-wesley;Initial Catalog=ProjectVoteOrDie;Integrated Security=True";
string cm1 = "UPDATE Test SET wachtwoord = #wachtwoord WHERE id = #id";
string cm2 = "SELECT COUNT(*) FROM Test;";
public Form1()
{
InitializeComponent();
}
private void btnKlik_Click(object sender, EventArgs e)
{
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
//random code gen
var result = new string(
Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])
.ToArray());
SqlConnection scn = new SqlConnection(cn);
SqlCommand scm1 = new SqlCommand(cm1, scn);
SqlCommand scm2 = new SqlCommand(cm2, scn);
try
{
scn.Open();
int rows = Convert.ToInt32(scm2.ExecuteScalar());
scm2.Parameters.Clear();
for (int i = 1; i <= rows; i++)
{
scm1.Parameters.AddWithValue("#wachtwoord", result);
scm1.Parameters.AddWithValue("#id", i);
scm1.Parameters.Clear();
scm1.ExecuteNonQuery();
}
}
catch (Exception se) //got the error on
{
lblRandom.Text = Convert.ToString(se);
}
finally
{
scn.Close();
}
}

What is the optimum way of getting records from database in scenario that you have to pass lists that each of them has more than 2000 parameters?

Any comments on this code pieces to make it more professional will be gladly accepted. This is why I opened this topic. But the main concern is this; I need to pass item ids, store ids, and start date and end date to get sale records. One of the problem is because of SQL parameter limit (2100), I cannot send more than 2100 parameters to the statement. Now I am trying to receive records store by store (store number is more than 4000 and also item amount). But I could not figure out a good way to do it.
Any one who spent time to help appreciated.
This is data access:
public List<SalesList> ExecuteSales(List<string> items, int storeID, int W1,int W2,int vendorID,int retailerID)
{
SqlCommand command = new SqlCommand();
string statement = "SELECT I.ITEM_NBR,I.ITEM_DESC1,I.ITEM_DESC2,I.VENDOR_STK_NBR,SUM(SA.POS_QTY) AS POS_QTY,SUM(SA.POS_SALES) AS POS_SALES "
+ "FROM SALES_FTBL SA,ITEM_TBL I "
+ "WHERE SA.RETAILER_ID=I.RETAILER_ID "
+ "AND SA.RETAILER_ID = #RetailerID "
+ "AND SA.VENDOR_NBR = #VendorID "
+ "AND SA.STORE_NBR = #StoreID "
+ "AND SA.ITEM_NBR=I.ITEM_NBR "
+"AND SA.ITEM_NBR IN (";
command.Parameters.AddWithValue("#RetailerID", retailerID);
command.Parameters.AddWithValue("#VendorID",vendorID);
command.Parameters.AddWithValue("#StoreID", storeID);
for (int i = 0; i < items.Count; i++)
{
if (i > 0)
{
statement += ", ";
}
string paramStr = "#itemNo" + i;
statement += paramStr;
command.Parameters.Add(paramStr, System.Data.SqlDbType.Int);
command.Parameters[paramStr].Value = items[i];
}
statement += ") ";
//statement += "AND STORE_NBR IN (";
//for (int i = 0; i < stores.Count; i++)
//{
// if (i > 0)
// {
// statement += ", ";
// }
// string paramStr = "#storeNo" + i;
// statement += paramStr;
// command.Parameters.Add(paramStr, System.Data.SqlDbType.Int);
// command.Parameters[paramStr].Value = stores[i];
//}
//statement += ") ";
statement += "AND WEEK IN (";
for (int i = 0; i <1; i++)
{
if (i > 0)
{
statement += ", ";
}
string paramStr = "#W" + i;
statement += paramStr;
command.Parameters.Add(paramStr, System.Data.SqlDbType.Int);
command.Parameters[paramStr].Value = W1;
}
W1=W1+1;
for (int counter=W1; counter < W2;counter++ )
{
if (counter > 0)
{
statement += ", ";
}
string paramStr = "#W" + counter;
statement += paramStr;
command.Parameters.Add(paramStr, System.Data.SqlDbType.Int);
command.Parameters[paramStr].Value = W1++;
}
statement += ") ";
statement += "GROUP BY I.ITEM_NBR,I.VENDOR_STK_NBR,I.ITEM_DESC1,I.ITEM_DESC2 Order By I.ITEM_DESC2 ";
command.CommandText = statement;
command.Connection = connection;
List<SalesList> sales = new List<SalesList>();
SalesList sale;
string itemDescription;
string desc1;
string desc2;
int count = 0;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
sale = new SalesList();
sale.ItemNumber = Convert.ToInt32(reader["ITEM_NBR"].ToString().TrimEnd());
if (reader["ITEM_DESC1"] != null)
{
desc1 = reader["ITEM_DESC1"].ToString().TrimEnd();
}
else { desc1 = ""; }
if (reader["ITEM_DESC2"] != null)
{
desc2 = reader["ITEM_DESC2"].ToString().TrimEnd();
}
else { desc2 = ""; }
if (!desc1.Equals(desc2) || !desc2.Equals(desc1))
{ itemDescription = desc1 + " " + desc2; }
else { itemDescription = desc2; }
sale.ItemDescription2 = itemDescription;
sale.PosQuantity = Convert.ToInt32(reader["POS_QTY"].ToString().TrimEnd());
sale.VendorStockNumber = reader["VENDOR_STK_NBR"].ToString().TrimEnd();
if (reader["POS_SALES"].ToString() != "")
{
sale.PosSales = Convert.ToDouble(reader["POS_SALES"].ToString().TrimEnd());
}
else { sale.PosSales = 0; }
sales.Add(sale);
}
}
catch (SqlException se)
{
Debug.WriteLine("---------- DEBUG INFORMATION ----------");
Debug.WriteLine(se.Message);
Debug.WriteLine("=======================================");
throw se;
}
finally
{
connection.Close();
}
return sales;
}
And this is business layer :
private List<SalesList> ExecuteSales(List<string> items, List<string> stores, string date1, string date2, int vendorID, int retailerID) {
int W1 = CalculateWeek(date1);
int W2 = CalculateWeek(date2);
SalesListDL salesListDO = new SalesListDL();
List<SalesList> sales = new List<SalesList>();
List<SalesList> salesX = new List<SalesList>();
for (int counter = 0; counter < stores.Count; counter++)
{
int storeID = Convert.ToInt32(stores[counter]);
salesX = salesListDO.ExecuteSales(items, storeID, W1, W2, vendorID, retailerID);
if (salesX.Count > 0)
{
foreach (SalesList saleX in salesX.ToList())
{
int index = sales.FindIndex(item => item.ItemNumber == saleX.ItemNumber);
if (index > 0)
{
sales[index].PosQuantity = +saleX.PosQuantity;
sales[index].PosSales = +saleX.PosSales;
salesX.Remove(saleX);
}
else { sales.Add(saleX); }
}
}
}
return sales;
}
Table valued parameters is the way to go if this is indeed the way you need to approach this topic.
First, switch to a stored procedure since you're using SQL 2008 or
newer.
Second, read up on the using statement for disposing of your
sql items.
Psuedo data layer:
public List<SalesList> ExecuteSales(List<string> items, int storeID, int W1, int W2, int vendorID, int retailerID)
{
var sales = new List<SalesList>();
var table = new DataTable();
table.Columns.Add("ItemNumber");
foreach (var item in items)
{
table.Rows.Add(item);
}
using (var connection = new SqlConnection("ConnectionString"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "cp_ExecuteSales";
command.Parameters.AddWithValue("#RetailerID", retailerID);
command.Parameters.AddWithValue("#VendorID", vendorID);
command.Parameters.AddWithValue("#StoreID", storeID);
var tvp = new SqlParameter("#ItemIds", SqlDbType.Structured)
{
TypeName = "tvpItems",
Value = table
};
command.Parameters.Add(tvp);
using (var reader = command.ExecuteReader())
{
//DoWork
}
}
}
return sales;
}
Create the tvp:
CREATE TYPE [dbo].[tvpItems] AS TABLE(
[ItemNumber] [int] NULL
)
Create the stored proc:
CREATE PROCEDURE cp_ExecuteSales
#RetailerID VARCHAR(50),
#VendorID VARCHAR(50),
#StoreID VARCHAR(50),
#ItemIds tvpItems READONLY
AS
SELECT I.ITEM_NBR
,I.ITEM_DESC1
,I.ITEM_DESC2
,I.VENDOR_STK_NBR
,SUM(SA.POS_QTY) AS POS_QTY
,SUM(SA.POS_SALES) AS POS_SALES
FROM SALES_FTBL SA
INNER JOIN ITEM_TBL I ON SA.RETAILER_ID = I.RETAILER_ID
AND SA.ITEM_NBR = I.ITEM_NBR
INNER JOIN #ItemIds ID ON SA.ITEM_NBR = ID.ItemNumber
WHERE SA.RETAILER_ID=I.RETAILER_ID
AND SA.RETAILER_ID = #RetailerID
AND SA.VENDOR_NBR = #VendorID
AND SA.STORE_NBR = #StoreID
AND SA.ITEM_NBR=I.ITEM_NBR
If you need to add a second set of number parameters, then you can pass multiple parameters of different types to the database. In the past, we've created several generic types to support varying list of data types rather than having to manage a lot of table types.
CREATE TYPE [dbo].[IntList] AS TABLE(
[Value] [Int] NULL
)
Important things to remember:
The parameter type for a tvp must be SqlDbType.Structured
The TypeName for the parameter must match the Table Value Parameter
type name.
The Table Value Parameter parameter in the stored procedure must be
declared as READONLY

Webservice method that returns objects of struct

I have a webservice with two methods 1 that returns a struct with two arrays:
public struct GetWeatherItemDataStruct
{
//public DateTime[] TimeStamp;
public double[] Value;
public string[] TimeStamp;
}
[WebMethod]
public GetWeatherItemDataStruct GetWeatherItemData(string parameterName,string fromTime,string toTime)
{
GetWeatherItemDataStruct gwiDataStructObj = new GetWeatherItemDataStruct();
SqlConnection conn = null;
SqlDataReader rdr = null;
int prameterID = GetParameterID(parameterName);
int tblSize = GetTableSize(parameterName, fromTime, toTime, prameterID);
double[] result = new double[tblSize];
int i = 0;
string[] tStamp = new string[tblSize];
String source = "Data Source=MASTER-PC\\SQLEXPRESS;Initial Catalog=WeatherDatabase;Integrated Security=True";
try
{
using (conn = new SqlConnection(source))// create and open a connection object
{
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("GetWeatherItemData", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
//cmd.Parameters.Add(new SqlParameter("#WeatherParameterID", "1"));
cmd.Parameters.Add("#WeatherParameter", SqlDbType.VarChar).Value = parameterName;
cmd.Parameters.Add("#FromTimeStamp", SqlDbType.VarChar).Value = fromTime;
cmd.Parameters.Add("#ToTimeStamp", SqlDbType.VarChar).Value = toTime;
conn.Open();
// execute the command
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
result[i] = (double)rdr["MeasurementValue"];
tStamp[i] = rdr["Recieved"].ToString();
i++;
}
gwiDataStructObj.Value = result;
gwiDataStructObj.TimeStamp = tStamp;
int b = gwiDataStructObj.Value.Length;
}
}
catch (SqlException e)
{
//Log exception
//Display Error message
}
return gwiDataStructObj;
}
[WebMethod]
public int[] stringTest(string[] tString)
{
int numberOfStrings = tString.Length;
int[] returnS = new int[numberOfStrings];
for (int i = 0; i <= numberOfStrings; i++)
{
returnS[i] = 1;
}
return returnS;
}
On the Client program i can read from the struct tabels as following:
string dtFrom = "2012-10-04 19:05:57:190";
string dtTo = "2012-10-05 21:50:05:197";
double[] paramValue;
string[] timeStamp;
var client = new WebServiceSample.WebService1SoapClient();
paramValue = client.GetWeatherItemData(paramName, dtFrom, dtTo).Value.ToArray();
timeStamp = client.GetWeatherItemData(paramName, dtFrom, dtTo).TimeStamp.ToArray();
This seems to work fine. But i have annother method that returns an array of the same struct:
public struct GetWeatherItemDataStruct
{
//public DateTime[] TimeStamp;
public double[] Value;
public string[] TimeStamp;
}
[WebMethod]
public GetWeatherItemDataStruct[] GetSelectedWeatherItemsData(string[] parameterName, string fromTime, string toTime)
{
int numbeOfParameters = parameterName.Length;
GetWeatherItemDataStruct[] getSelectedItemsStructObj = new GetWeatherItemDataStruct[numbeOfParameters];
SqlConnection conn = null;
SqlDataReader rdr = null;
int prameterID = 0;
int tblSize = 0;
double[] result;
int i = 0;
int counter = 0;
for (counter = 0; counter < numbeOfParameters; numbeOfParameters++)
{
prameterID = GetParameterID(parameterName[counter]);
tblSize = GetTableSize(parameterName[counter], fromTime, toTime, prameterID);
result = new double[tblSize];
string[] tStamp = new string[tblSize];
String source = "Data Source=MASTER-PC\\SQLEXPRESS;Initial Catalog=WeatherDatabase;Integrated Security=True";
try
{
using (conn = new SqlConnection(source))// create and open a connection object
{
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("GetWeatherItemData", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
//cmd.Parameters.Add(new SqlParameter("#WeatherParameterID", "1"));
cmd.Parameters.Add("#WeatherParameter", SqlDbType.VarChar).Value = parameterName;
cmd.Parameters.Add("#FromTimeStamp", SqlDbType.VarChar).Value = fromTime;
cmd.Parameters.Add("#ToTimeStamp", SqlDbType.VarChar).Value = toTime;
conn.Open();
// execute the command
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
result[i] = (double)rdr["MeasurementValue"];
tStamp[i] = rdr["Recieved"].ToString();
i++;
}
getSelectedItemsStructObj[counter].Value = result;
getSelectedItemsStructObj[counter].TimeStamp = tStamp;
}
}
catch (SqlException e)
{
//Log exception
//Display Error message
}
}
return getSelectedItemsStructObj;
}
Here im stuck. How do i read the tables for each object?
Based on the comments above.
To get data from a struct inside an array, you retrieve it just like you were setting it.
myArrayOfStruct[0].myStructProperty
If it's an array IN the struct, it's just:
myArrayOfStruct[0].myArrayProperty[0]
If you wanted to loop through all structures in the array and all of the items in an array property, you'd next two loops:
for (int i = 0; i < myArrayOfStruct.length; i++){
for (int j = 0; j < myArrayProperty.length; j++){
myData = myArrayOfStruct[i].myArrayProperty[j];
// do something with the data
}
}
Basically, myArrayOfStruct[0].myProperty is the same as accessing it like this:
MyStruct myStruct = myArrayOfStruct[0];
myStruct.myProperty
Does this answer your question? You set it correctly above. You retrieve it in a similar fashion.

Categories

Resources