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.
Related
My code isn't returning any rows from a test database table when I pass a string version of a list, but it does return rows if I pass the list members in directly.
When I use a message box to show the string joinedSerialsList, it appears to be formatted properly.
// Create comma delimited list of serials:
int currentSerial = beginning;
List<string> serialsList = new List<string>();
for (int i = 0; i < count; i++)
{
serialsList.Add(currentSerial.ToString());
currentSerial++;
}
string joinedSerialsList = string.Format("({0})", string.Join(", ", serialsList));
OleDbConnection connection = BadgeDatabaseDB.GetConnection();
string checkStatement
= "SELECT SerialNumber, OrderNumber "
+ "FROM SerialNumbersMFG "
+ "WHERE SerialNumber IN (#List)";
OleDbCommand command = new OleDbCommand(checkStatement, connection);
command.Parameters.AddWithValue("#List", joinedSerialsList);
string duplicateSerials = "";
try
{
connection.Open();
OleDbDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
duplicateSerials += dataReader["OrderNumber"].ToString() + "\n";
}
}
catch (OleDbException ex)
{
throw ex;
}
finally
{
connection.Close();
}
return duplicateSerials;
I rewrited your sample, this work:
private IEnumerable<string> getData()
{
// Create comma delimited list of serials:
int currentSerial = 4452; // your constant
var serialsList = new List<int>();
var count = 100;
for (int i = 0; i < count; i++)
serialsList.Add(currentSerial++);
var connString = getConnectionString();
var results = new List<string>();
string sqlSelect = $"SELECT SerialNumber, OrderNumber FROM SerialNumbersMFG WHERE SerialNumber IN ({string.Join(",", serialsList)})";
using (var connection = new SqlConnection(connString)) // BadgeDatabaseDB.GetConnection();
{
using (var command = new SqlCommand(sqlSelect, connection))
{
connection.Open();
var dataReader = command.ExecuteReader();
while (dataReader.Read())
results.Add(dataReader["OrderNumber"].ToString());
}
}
return results;
}
Have the error 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException, however VisualStudio does not pause the program and throw the exception at me. Here is the code:private void BTN_NA_Click(object sender, EventArgs e)
{
if (TXT_NAUN.Text != "" && TXT_NAPW.Text != "" && TXT_NAPW2.Text != "")
{
if (TXT_NAPW.Text == TXT_NAPW2.Text)
{
string input = TXT_NAPW.Text;
int hash = 0;
int output = 0;
foreach (char chara in input)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
output = output + temp;
output = output * 2;
}
hash = output % 1000;
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT Accounts.PlayerID FROM Accounts ORDER BY Accounts.PlayerID DESC ";
///string comm = "SELECT Accounts.PlayerID from Accounts";
/// INNER JOIN Leaderboard ON Leaderboard.PlayerID = Accounts.PlayerID WHERE Accounts.PlayerUsername = #ip";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
string result = "";
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
dbConn.Close();
{
string comm = "INSERT INTO Accounts (PlayerUsername, PlayerPassword, PlayerID, PlayerInvID) VALUES (#NAUN, #HPW, #NAPI, #NAPI)";
OleDbCommand command = new OleDbCommand(comm, dbConn);
command.Parameters.AddWithValue("#NAUN", TXT_NAUN.Text);
command.Parameters.AddWithValue("#HPW", hash);
foreach (char chara in result)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
result = result + temp;
}
result = result + 1;
command.Parameters.AddWithValue("#NAPI", result);
command.Parameters.AddWithValue("#NAPI", result);
dbConn.Open();
int rowsAffected = cmd.ExecuteNonQuery(); ///error appears here
dbConn.Close();
}
}
}
}
Any suggestions on solution, have tried a lot and this is my last hope!
Thanks,
Blackclaw_
At the line you got the error, you are using cmd (the select command). I think you want to use command (the insert command).
I want to retrieve multiple rows from SQL Server in a web service. I get 2 rows as result when I search jo number 1 and my table name is TestOrderStatus.
While I get only one row in the search result.
Thanks for all
public class ReturnOrder
{
public string Message;
public int QtqSlit;
public int QtyPcs;
public string Design;
}
[WebMethod(MessageName = "OrderStatus", Description = "OrderStatus new Order")]
[System.Xml.Serialization.XmlInclude(typeof(ReturnOrder))]
public ReturnOrder OrderStatus(string JO) /// get list of notes
{
int QtqSlit = 0;
int QtyPcs = 0;
String Design = "";
string Message = "";
SqlDataReader reader;
using (SqlConnection connection = new SqlConnection(DBConnection.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT QtqSlit,QtyPcs,Design FROM TestOrderStatus where JO=#JO");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#JO", JO);
connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
QtqSlit = reader.GetInt32(0);
QtyPcs = reader.GetInt32(1);
Design = reader.GetString(2);
}
}
if (QtqSlit == 0)
{
Message = " user name or password is incorrect";
}
reader.Close();
connection.Close();
}
ReturnOrder rt = new ReturnOrder();
rt.Message = Message;
rt.QtqSlit = QtqSlit;
rt.QtyPcs = QtyPcs;
rt.Design = Design;
return rt;
}
You need a List for multiple rows if you want more than one result. So your code may be like this.
public class ReturnOrder
{
public string Message;
public int QtqSlit;
public int QtyPcs;
public string Design;
}
[WebMethod(MessageName = "OrderStatus", Description = "OrderStatus new Order")]
[System.Xml.Serialization.XmlInclude(typeof(List<ReturnOrder>))]
public List<ReturnOrder> OrderStatus(string JO) /// get list of notes
{
List<ReturnOrder> result=new List<ReturnOrder>();
int QtqSlit = 0;
int QtyPcs = 0;
String Design = "";
string Message = "";
//try
//{
SqlDataReader reader;
using (SqlConnection connection = new SqlConnection(DBConnection.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT QtqSlit,QtyPcs,Design FROM TestOrderStatus where JO=#JO");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#JO", JO);
connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
QtqSlit = reader.GetInt32(0);
QtyPcs = reader.GetInt32(1);
Design = reader.GetString(2);
ReturnOrder rt = new ReturnOrder();
rt.Message = Message;
rt.QtqSlit = QtqSlit;
rt.QtyPcs = QtyPcs;
rt.Design = Design;
result.add(rt);
}
if (QtqSlit == 0)
{
Message = " user name or password is in correct";
}
reader.Close();
connection.Close();
}
//}
//catch (Exception ex)
//{
// Message = " cannot access to the data";
//}
return result;
}
Thank you to much now web service is ok , But when he summoned the values in Xamrian Android doesn't know.
public class Mainlistview : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Mainlistview);
ListView ListView = FindViewById<ListView>(Resource.Id.listView1);
Selling.WebServiceDB ws = new Selling.WebServiceDB();
ws.OrderStatusListCompleted += Ws_OrderStatusListCompleted;
ws.OrderStatusListAsync(Convert.ToString(1));
}
private void Ws_OrderStatusListCompleted(object sender, Selling.OrderStatusListCompletedEventArgs e)
{
ListView ListView = FindViewById<ListView>(Resource.Id.listView1);
string msg = "";
if (e.Result.QtqSlit.ToString().Equals("0"))
{
msg = e.Result.Message;
}
else
{
// full class
List<TableItem> tableItems = new List<TableItem>();
tableItems.Add(new TableItem("" + e.Result.QtqSlit, "" + e.Result.QtyPcs, Resource.Drawable.Icon));
ListView.Adapter = new HomeScreenAdapter(this, tableItems);
}
}
I am using the Ta-Lib in C# and for the most part it works great. I am using it to calculate a number of moving averages and they calculate perfectly.
When Calling the ATR function it returns 0, always. I use the same parameters (the ones that overlap) as I do for the SMA, but still 0. Here is the code in question. Member variable Period is an integer. I have more data in the queues than the period I am asking it to calculate, and my data in the queues is clean, I've triple checked that. The return code is Success, but 0 return value.
int outbegldx = 0;
int outnbelement = 0;
Queue<double> inputHigh = new Queue<double>();
Queue<double> inputLow = new Queue<double>();
Queue<double> inputClose = new Queue<double>();
//This is in a loop
inputHigh.Enqueue(Convert.ToDouble(rdr.GetDecimal(5)));
inputLow.Enqueue(Convert.ToDouble(rdr.GetDecimal(6)));
inputClose.Enqueue(Convert.ToDouble(rdr.GetDecimal(7)));
double[] outreal = new double[inputHigh.Count];
retCode = TicTacTec.TA.Library.Core.Atr(0, inputHigh.Count - 1, inputHigh.ToArray(), inputLow.ToArray(), inputClose.ToArray(), this.Period, out outbegldx, out outnbelement, outreal);
if (retCode == Core.RetCode.Success)
{
this.Output = new AverageTrueRangeOutput(this.Period, outreal[0], outbegldx, outnbelement);
}
OK I figured it out, finally after many, many hours. In my loop I was checking to make sure the array had the same amount of elements as the Period, if so, I performed the calculation. In fact, the array needs Period + 1 elements to perform the calculation. Here is my entire function.
public override void Calculate()
{
int outbegldx = 0;
int outnbelement = 0;
int marketID = 0;
TicTacTec.TA.Library.Core.RetCode retCode;
//Queue<OHLC> input = new Queue<OHLC>();
Queue<double> inputHigh = new Queue<double>();
Queue<double> inputLow = new Queue<double>();
Queue<double> inputClose = new Queue<double>();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.DB_CONNECTION_STRING))
{
using (SqlCommand cmd = new SqlCommand("[Data].[proc_GetHistoricalData]", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StartIndex", SqlDbType.Int);
cmd.Parameters.Add("#EndIndex", SqlDbType.Int);
cmd.Parameters.Add("#Weekly", SqlDbType.Bit);
cmd.Parameters["#StartIndex"].Value = this.startIndex;
cmd.Parameters["#EndIndex"].Value = this.endIndex;
cmd.Parameters["#Weekly"].Value = (int)this.TimeFrame;
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(rdr.GetInt64(0));
if (marketID != rdr.GetInt32(2))
{
marketID = rdr.GetInt32(2);
inputHigh.Clear();
inputLow.Clear();
inputClose.Clear();
}
//input.Enqueue(new OHLC(rdr.GetDecimal(4), rdr.GetDecimal(5), rdr.GetDecimal(6), rdr.GetDecimal(7)));
inputHigh.Enqueue(Convert.ToDouble(rdr.GetDecimal(5)));
inputLow.Enqueue(Convert.ToDouble(rdr.GetDecimal(6)));
inputClose.Enqueue(Convert.ToDouble(rdr.GetDecimal(7)));
//We have enough data to calculate the ATR so do so
if (inputHigh.Count >= this.Period + 1)
{
double[] outreal = new double[inputHigh.Count - 1];
int lookBack = Core.AtrLookback(this.Period);
retCode = Core.Atr(0, inputHigh.Count - 1, inputHigh.ToArray(), inputLow.ToArray(), inputClose.ToArray(), lookBack, out outbegldx, out outnbelement, outreal);
//Calculated the ATR, now write it to the database
if (retCode == Core.RetCode.Success)
{
this.Output = new AverageTrueRangeOutput(this.Period, outreal[0], outbegldx, outnbelement);
//Now insert into db
using (SqlCommand cmdInsert = new SqlCommand("[Data].[proc_InsertHistoricalIndicator]", conn))
{
cmdInsert.CommandType = CommandType.StoredProcedure;
cmdInsert.Parameters.Add("#MarketID", SqlDbType.Int);
cmdInsert.Parameters.Add("#IndicatorID", SqlDbType.Int);
cmdInsert.Parameters.Add("#Date", SqlDbType.Date);
cmdInsert.Parameters.Add("#Value", SqlDbType.Xml);
cmdInsert.Parameters.Add("#Weekly", SqlDbType.Bit);
cmdInsert.Parameters["#MarketID"].Value = rdr.GetInt32(2);
cmdInsert.Parameters["#IndicatorID"].Value = this.Id;
cmdInsert.Parameters["#Weekly"].Value = (int)this.TimeFrame;
cmdInsert.Parameters["#Date"].Value = rdr.GetDateTime(3); //IBLib.Util.GetDate(
cmdInsert.Parameters["#Value"].Value = this.Output.toXML().OuterXml;
cmdInsert.ExecuteNonQuery();
}
}
inputHigh.Dequeue();
inputLow.Dequeue();
inputClose.Dequeue();
}
}
rdr.Close();
}
}
}
}
The line in question is this one - "if (inputHigh.Count >= this.Period + 1)" whereas previously I just had "if (inputHigh.Count >= this.Period)"
I'm having trouble coming up with the following search method:
public override List<Team> Search(Dictionary<string, string> prms, int pageSize, int page, out int results)
{
var tresults = new List<Team>();
string temp1 = "";
string temp2 = "";
using (SqlConnection conn = DB.GetSqlConnection())
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"Search";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
foreach (KeyValuePair<string, string> pair in prms)
{
temp1 = pair.Key;
temp2 = pair.Value;
}
if (temp1 == "TeamName")
{
SqlParameter p1 = new SqlParameter("TeamName", System.Data.SqlDbType.VarChar);
p1.Value = temp2;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("CityName", System.Data.SqlDbType.VarChar);
p2.Value = null;
cmd.Parameters.Add(p2);
}
else if (temp1 == "CityName")
{
SqlParameter p1 = new SqlParameter("TeamName", System.Data.SqlDbType.VarChar);
p1.Value = null;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("CityName", System.Data.SqlDbType.VarChar);
p2.Value = temp2;
cmd.Parameters.Add(p2);
}
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
}
//results = 1 + 1;
throw new NotImplementedException("Must be implemented by class. ");
}
What I'm trying to do is basically what this test is doing:
[TestMethod]
public void SearchForTeam()
{
var dic = new Dictionary<string, string>();
int total = 0;
dic.Add("TeamName", "Patriots");
var nd = new TeamRepository();
var teams = nd.Search(dic, 100, 1, out total);
Assert.IsTrue(teams.Find(p => p.TeamName == "Patriots") != null);
}
What I'm trying to do is have my method search by either Team Name (SQL column "TeamName", value "Patriots") or by City Name (SQL column "CityName" value "Chicago", etc. I think my issues mainly are that I'm not entirely sure if I'm understanding how the dictionary works.
Also, I'm not sure how the value I'm returning should work because I am both returning an int (from the out parameter) and type List. This is all pretty new to me, so its the basics that I don't quite understand I suppose.
How about this?
public override List<Team> Search(Dictionary<string, string> prms, int pageSize, int page)
{
var tresults = new List<Team>();
using (SqlConnection conn = DB.GetSqlConnection())
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"Search";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
foreach (KeyValuePair<string, string> pair in prms)
cmd.Parameters.Add(new SqlParameter(pair.Key, System.Data.SqlDbType.VarChar) { Value = pair.Value });
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
// I assume you'll use pageSize and page here?
}
}
return tresults; // I assume this is what you want to return.
}
If you don't want to use a specific column for your search, then there's no need to create a SqlParameter for that column and sets its Value to null -- just don't use that column!
Also, there's no need to have out int results. If you're returning the list of teams, then the invoker can just get the team count from the list (teams.Count). (If you are doing something else with results, then by all means ignore this paragraph.)
it's kind of hard to see what you are getting at here, I am unsure that you need a dictionary at all (would you pass in multiple records?)
personally I would do the below, the assumption is the stored procedure could handle the possibility of both parameters being populated if both are passed in completed.
public override List<Team> Search(string teamName,string cityName, int pageSize, int page)
{
var tresults = new List<Team>();
using (SqlConnection conn = DB.GetSqlConnection())
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"Search";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("TeamName", System.Data.SqlDbType.VarChar);
p1.Value = teamName;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("CityName", System.Data.SqlDbType.VarChar);
p2.Value = cityName;
cmd.Parameters.Add(p2);
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while(reader.Read())
{
tresults.Add(BuildTeamFromReader(reader));
}
}
}
return tresults;
}
private Team BuildTeamFromReader(SqlDataReader reader)
{
var team = new Team();
team.TeamName = reader["TeamName"];//or whatever your column name is for team name
//ToDo other mappings
return team;
}