Returning values from a stored procedure - c#

I have in the database:
ALTER PROCEDURE [dbo].[uspConsumeEnrollments]
(--#File NVARCHAR(300),
#XML XML,
#FamilySent INT = 0 OUTPUT)
AS
BEGIN
SELECT #FamilySent = 755;
Here I am trying to download data:
public int Create(FamilyModel model)
{
try
{
var XML = model.GetEnrolmentFromModel().Serialize();
var RV = -99;
var familySent = 0;
using (var imisContext = new ImisDB())
{
var returnParameter = new SqlParameter("#RV", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;
var xmlParameter = new SqlParameter("#XML", XML);
xmlParameter.DbType = DbType.Xml;
var familySentParameter = new SqlParameter("#FamilySent", SqlDbType.Int);
familySentParameter.Value = 0;
familySentParameter.Direction = ParameterDirection.Output;
var sql = "exec #RV = uspConsumeEnrollments #XML, #FamilySent";
SqlParameter[] myParams = { returnParameter, xmlParameter, familySentParameter };
var result = imisContext.Database.ExecuteSqlCommand(sql, myParams);
RV = (int)returnParameter.Value;
Debug.WriteLine("RV: " + RV);
try
{
familySent = (int)familySentParameter.Value;
}
catch { }
Debug.WriteLine("familySent: " + familySent);
}
return RV;
}
catch (SqlException e)
{
}
}
The reference to the procedure works because I get the RV
I have a problem with FamilySent: I do not get any value.
In the above example I have #FamilySent = 755;
This should be returned and displayed in
Debug.WriteLine("familySent:" + familySent);
but it does not work.

Please try this out :
Modified version of your stored procedure :
ALTER PROCEDURE [dbo].[uspConsumeEnrollments](
--#File NVARCHAR(300),
#XML XML,
#FamilySent INT = 0 OUTPUT
)
AS
BEGIN
SELECT #FamilySent = 755 as FamilySent;
C# code :
public int Create(FamilyModel model)
{
try
{
var XML = model.GetEnrolmentFromModel().Serialize();
var RV = -99;
var familySent = 0;
using (SqlConnection cnx = new SqlConnection(connexionString))
using (SqlCommand cmd = new SqlCommand("[dbo].[uspConsumeEnrollments]", cnx))
{
cmd.CommandType = CommandType.StoredProcedure;
var xmlParameter = new SqlParameter("#XML", XML);
xmlParameter.DbType = DbType.Xml;
cmd.Parameters.Add(xmlParameter);
var familySentParameter = new SqlParameter("#FamilySent", SqlDbType.Int);
familySentParameter.Value = 0;
familySentParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(familySentParameter);
cnx.Open();
List<string[]> res = new List<string[]>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
res.Add(new string[2]{reader.GetName(i),reader[i].ToString());
}
}
}
}
// then here get all of your data you need
if(res.Count > 0){
foreach(string[] s in res){
RV = s[1];
break;
}
}
}
cnx.Close();
return RV;
}
catch (SqlException e)
{
}
}

Related

Add string array to SQL query

I have a string array which consists of identifiers. I want to get some values from SQL using these identifiers . Is there a way of adding them with a string value to SqlCommand parameters?
I want to create a query like:
select CaseList from MasterReportData where Id = 1 OR Id = 2 OR Id = 3
This is my C# code:
public static List<string> GetCaseList(string[] masterIdList)
{
try
{
string query = " select CaseList from MasterReportData where #masterId";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
conn.Close();
}
catch (Exception e)
{
var err= 0;
}
return list;
}
There are many different ways you can go about doing this but I prefer to create a temp table of possible values. That way you can do something like
select CaseList from MasterReportData where Id IN(select Id from tempTable)
The best approach (with sql optimization) would be:
Create your Type:
CREATE TYPE dbo.IntTTV AS TABLE
( Id int )
Your Ids:
var ids = new List<int>
{
1,
2,
3,
}
Create a schema:
var tableSchema = new List<SqlMetaData>(1)
{
new SqlMetaData("Id", SqlDbType.Int) // I think it's Int
}.ToArray();
Create the table in C#
var table = ids
.Select(i =>
{
var row = new SqlDataRecord(tableSchema);
row.SetInt32(0, i);
return row;
})
.ToList();
Create the SQL Parameter
var parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "#Ids";
parameter.Value = table;
parameter.TypeName = "dbo.IntTTV";
var parameters = new SqlParameter[1]
{
parameter
};
Slightly change your query (this is just an example:)
string query = "select mrd.CaseList from MasterReportData mrd"
+ " inner join #ids i on mrd.Id = i.id";
public static List<string> GetCaseList(string[] masterIdList)
{
List<string> list = new List<string>();
try
{
string query = "select CaseList from MasterReportData where ";
using (SqlConnection conn = new SqlConnection(connString))
{
int i = 0;
SqlCommand cmd = new SqlCommand(query, conn);
for(i = 0; i < masterIdList.Length; i++)
{
var parm = "#ID" + i;
cmd.Parameters.Add(new SqlParameter(parm, masterIdList[i]));
query += (i > 0 ? " OR " : "") + " Id = " + parm;
}
cmd.CommandText = query;
//cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
}
}
catch (Exception e)
{
e.ToString();
}
return list;
}

asp.net A transport-level error has occurred when receiving results from the server

I am using ASP.Net C# with SQL Server 2012
My C# Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class autorefresh_create_emi : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["paconn"].ToString());
con.Open();
SqlCommand com1 = new SqlCommand("select max(f_casenum) from c_detail", con);
string check_max = com1.ExecuteScalar().ToString();
if (check_max == "0")
{
}
else
{
string st_id = "";
Int64 st = 0;
string max_id = "";
Int64 en = 0;
SqlCommand com2 = new SqlCommand("select top 1(f_casenum) from c_emi where f_casenum not in (select top 1 (f_casenum) from c_detail order by f_casenum) order by f_casenum", con);
com2.CommandTimeout = 0;
st_id = com2.ExecuteScalar().ToString();
st_id = st_id.Substring(2);
st = Convert.ToInt64(st_id);
max_id = check_max;
max_id = max_id.Substring(2);
en = Convert.ToInt64(max_id);
for (Int64 i = st; i <= en; i++)
{
string f_casenum = "PA" + i;
string c_status = "";
string f_tenure = "";
SqlCommand com3 = new SqlCommand("select * from c_detail where f_casenum=#f_casenum", con);
com3.CommandTimeout = 0;
com3.Parameters.AddWithValue("#f_casenum", f_casenum);
SqlDataReader reader3 = com3.ExecuteReader();
if (reader3.Read())
{
f_tenure = reader3["f_tenure"].ToString().Trim();
c_status = reader3["c_status"].ToString();
}
reader3.Close();
if (c_status == "Full Paid")
{
}
else
{
string row_check = "";
SqlCommand com4 = new SqlCommand("select count(f_invoice) from c_emi where f_casenum=#f_casenum", con);
com4.CommandTimeout = 0;
com4.Parameters.AddWithValue("#f_casenum", f_casenum);
row_check = com4.ExecuteScalar().ToString().Trim();
if (f_tenure.Equals(row_check))
{
}
else
{
string st_id_invoice = "";
Int64 st_invoice = 0;
string max_id_invoice = "";
Int64 en_invoice = 0;
SqlCommand com5 = new SqlCommand("select min(f_invoice) from c_emi where f_casenum=#f_casenum", con);
com5.CommandTimeout = 0;
com5.Parameters.AddWithValue("#f_casenum", f_casenum);
st_id_invoice = com5.ExecuteScalar().ToString();
st_id_invoice = st_id_invoice.Substring(3);
st_invoice = Convert.ToInt64(st_id_invoice);
SqlCommand com6 = new SqlCommand("select max(f_invoice) from c_emi where f_casenum=#f_casenum", con);
com6.CommandTimeout = 0;
com6.Parameters.AddWithValue("#f_casenum", f_casenum);
max_id_invoice = com6.ExecuteScalar().ToString();
max_id_invoice = max_id_invoice.Substring(3);
en_invoice = Convert.ToInt64(max_id_invoice);
for (Int64 j = st_invoice; j <= en_invoice; j++)
{
string invoice_date = "";
string f_emi_due = "";
string f_total_emi = "";
string f_emi = "";
string f_b_curr = "";
string f_invoice = "PAI" + j;
string f_casenum1 = "";
SqlCommand com7 = new SqlCommand("select * from c_emi where f_invoice=#f_invoice", con);
com7.CommandTimeout = 0;
com7.Parameters.AddWithValue("#f_invoice", f_invoice);
SqlDataReader reader7 = com7.ExecuteReader();
if (reader7.Read())
{
f_casenum1 = reader7["f_casenum"].ToString();
f_emi = reader7["f_emi"].ToString();
f_emi_due = reader7["f_emi_due"].ToString();
f_total_emi = reader7["f_total_emi"].ToString();
f_b_curr = reader7["f_b_curr"].ToString();
invoice_date = reader7["invoice_date"].ToString();
}
reader7.Close();
if (f_casenum == f_casenum1)
{
DateTime currr = DateTime.Now;
DateTime INDIAN_ZONE = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currr, "India Standard Time");
DateTime curr = INDIAN_ZONE;
string curr_invoicedate = curr.ToShortDateString();
DateTime check_invoicedate = Convert.ToDateTime(invoice_date);
check_invoicedate = check_invoicedate.AddDays(30);
check_invoicedate = Convert.ToDateTime(check_invoicedate);
string exit_date = check_invoicedate.ToShortDateString();
string f_emi_duedate = check_invoicedate.AddDays(10).ToShortDateString();
string invoice_date1 = check_invoicedate.ToShortDateString();
SqlCommand com8 = new SqlCommand("select f_casenum from c_emi where f_casenum=#f_casenum and CONVERT(date,invoice_date,101)=#invoice_date", con);
com8.CommandTimeout = 0;
com8.Parameters.AddWithValue("#f_casenum", f_casenum);
com8.Parameters.AddWithValue("#invoice_date", exit_date);
string check_exitdate = "";
SqlDataReader reader8 = com8.ExecuteReader();
if (reader8.Read())
{
check_exitdate = reader8["f_casenum"].ToString();
}
else
{
}
if (check_exitdate != "")
{
}
else
{
if (curr >= check_invoicedate)
{
string value = "0";
string owner = "";
string i_status = "Unlock";
SqlCommand com9 = new SqlCommand("select MAX(f_invoice) from c_emi", con);
com9.CommandTimeout = 0;
string maxid1 = com9.ExecuteScalar().ToString();
string id1 = maxid1;
Int64 code = 100000000001;
string c = "PAI";
if (id1.Substring(0, 1) != "P")
{
id1 = code.ToString();
id1 = c + id1.ToString();
}
else
{
id1 = id1.Substring(3);
Int64 a = Convert.ToInt64(id1);
a = a + 1;
id1 = c + a.ToString();
}
id1 = id1.ToString();
SqlCommand com11 = new SqlCommand("insert into c_emi values(#f_casenum,#f_b_amt,#f_emi,#f_emi_duedate,#f_invoice,#invoice_date,#f_overdue_amt,#f_emi_paid,#f_emi_due,#f_total_emi,#f_b_curr,#i_status,#owner,#convi_charges,#paidemi_date)", con);
com11.CommandTimeout = 0;
SqlParameter obj1 = new SqlParameter("#f_casenum", DbType.StringFixedLength);
obj1.Value = f_casenum;
com11.Parameters.Add(obj1);
SqlParameter obj2 = new SqlParameter("#f_overdue_amt", DbType.StringFixedLength);
obj2.Value = value;
com11.Parameters.Add(obj2);
SqlParameter obj3 = new SqlParameter("#f_emi_paid", DbType.StringFixedLength);
obj3.Value = value;
com11.Parameters.Add(obj3);
SqlParameter obj4 = new SqlParameter("#f_emi_due", DbType.StringFixedLength);
obj4.Value = value;
com11.Parameters.Add(obj4);
SqlParameter obj5 = new SqlParameter("#f_total_emi", DbType.StringFixedLength);
obj5.Value = f_emi;
com11.Parameters.Add(obj5);
SqlParameter obj6 = new SqlParameter("#f_emi", DbType.StringFixedLength);
obj6.Value = f_emi;
com11.Parameters.Add(obj6);
SqlParameter obj7 = new SqlParameter("#f_emi_duedate", DbType.StringFixedLength);
obj7.Value = f_emi_duedate;
com11.Parameters.Add(obj7);
SqlParameter obj8 = new SqlParameter("#f_invoice", DbType.StringFixedLength);
obj8.Value = id1;
com11.Parameters.Add(obj8);
SqlParameter obj9 = new SqlParameter("#invoice_date", DbType.StringFixedLength);
obj9.Value = invoice_date1;
com11.Parameters.Add(obj9);
SqlParameter obj10 = new SqlParameter("#f_b_amt", DbType.StringFixedLength);
obj10.Value = f_b_curr;
com11.Parameters.Add(obj10);
SqlParameter obj11 = new SqlParameter("#f_b_curr", DbType.StringFixedLength);
obj11.Value = f_b_curr;
com11.Parameters.Add(obj11);
SqlParameter obj12 = new SqlParameter("#i_status", DbType.StringFixedLength);
obj12.Value = i_status;
com11.Parameters.Add(obj12);
SqlParameter obj13 = new SqlParameter("#owner", DbType.StringFixedLength);
obj13.Value = owner;
com11.Parameters.Add(obj13);
SqlParameter obj14 = new SqlParameter("#convi_charges", DbType.StringFixedLength);
obj14.Value = value;
com11.Parameters.Add(obj14);
SqlParameter obj15 = new SqlParameter("#paidemi_date", DbType.StringFixedLength);
obj15.Value = owner;
com11.Parameters.Add(obj15);
com11.ExecuteNonQuery();
}
else
{
}
}
}
else
{
}
}
}
}
}
}
con.Close();
}
}
I have large database and my query is inserted many number of record on table when i run the web page
I recieve the following Error :
System.Data.SqlClient.SqlException: A transport-level error has
occurred when receiving results from the server. (provider: Session
Provider, error: 19 - Physical connection is not usable)
on the following Code
Line 111: com7.Parameters.AddWithValue("#f_invoice", f_invoice);
Line 112:
Line 113: SqlDataReader reader7 = com7.ExecuteReader();
Line 114: if (reader7.Read())
Line 115: {
My ErrorLog file says :
2015-01-13 11:27:23.96 Logon Error: 18456, Severity: 14, State:
8.
2015-01-13 11:27:23.96 Logon Login failed for user 'sa'.
Reason: Password did not match that for the login provided. [CLIENT:
108.171.243.19]
So what's the issue..??

Procedure or function has too many arguments specified

Below is my stored procedure for insert:
CREATE PROCEDURE [dbo].[Insertaddress_Master]
(
#add_Zip nvarchar(20),
#add_FullAddress nvarchar(250),
#add_user_Id int,
#add_CreatedDate datetime,
#add_UpdatedDate datetime,
#add_DeletedDate datetime,
#add_IsDeleted bit,
#add_IsPrimary bit,
#add_cntm_Id int,
#add_alt_No nvarchar(20)
)
As
BEGIN
SET NOCOUNT ON
Insert Into [address_Master]
(
[add_Zip],
[add_FullAddress],
[add_user_Id],
[add_CreatedDate],
[add_UpdatedDate],
[add_DeletedDate],
[add_IsDeleted],
[add_IsPrimary],
[add_cntm_Id],
[add_alt_No]
)
Values
(
#add_Zip,
#add_FullAddress,
#add_user_Id,
#add_CreatedDate,
#add_UpdatedDate,
#add_DeletedDate,
#add_IsDeleted,
#add_IsPrimary,
#add_cntm_Id,
#add_alt_No
)
END
Below is code behind function:
protected void AddNew(object sender, EventArgs e)
{
try
{
address_MasterBM obj = new address_MasterBM();
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text != "")
{
String add_Zipstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text;
obj.add_Zip = add_Zipstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text != "")
{
String add_FullAddressstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text;
obj.add_FullAddress = add_FullAddressstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text != "")
{
Int32 add_user_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text);
obj.add_user_Id = add_user_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text != "")
{
DateTime add_CreatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text);
obj.add_CreatedDate = add_CreatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text != "")
{
DateTime add_UpdatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text);
obj.add_UpdatedDate = add_UpdatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text != "")
{
DateTime add_DeletedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text);
obj.add_DeletedDate = add_DeletedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text != "")
{
Boolean add_IsDeletedstr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text);
obj.add_IsDeleted = add_IsDeletedstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text != "")
{
Boolean add_IsPrimarystr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text);
obj.add_IsPrimary = add_IsPrimarystr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text != "")
{
Int32 add_cntm_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text);
obj.add_cntm_Id = add_cntm_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text != "")
{
String add_alt_Nostr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text;
obj.add_alt_No = add_alt_Nostr;
}
obj.Insertaddress_Master();
BindData();
lblException.Text = "";
}
catch(Exception ex)
{
lblException.Text = ex.Message.ToString();
}
}
Below is business method code:
public void Insertaddress_Master() {
try
{
DataAccess obj = new DataAccess();
obj.Provider = EnumProviders.SQLClient;
obj.ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ToString();
ParamStruct[] param = new ParamStruct[10];
param[0].direction = ParameterDirection.Input;
param[0].ParamName = "#add_Zip";
param[0].DataType = DbType.String;
param[0].value = _add_Zip;
param[1].direction = ParameterDirection.Input;
param[1].ParamName = "#add_FullAddress";
param[1].DataType = DbType.String;
param[1].value = _add_FullAddress;
param[2].direction = ParameterDirection.Input;
param[2].ParamName = "#add_user_Id";
param[2].DataType = DbType.Int32;
param[2].value = _add_user_Id;
param[3].direction = ParameterDirection.Input;
param[3].ParamName = "#add_CreatedDate";
param[3].DataType = DbType.DateTime;
param[3].value = _add_CreatedDate;
param[4].direction = ParameterDirection.Input;
param[4].ParamName = "#add_UpdatedDate";
param[4].DataType = DbType.DateTime;
param[4].value = _add_UpdatedDate;
param[5].direction = ParameterDirection.Input;
param[5].ParamName = "#add_DeletedDate";
param[5].DataType = DbType.DateTime;
param[5].value = _add_DeletedDate;
param[6].direction = ParameterDirection.Input;
param[6].ParamName = "#add_IsDeleted";
param[6].DataType = DbType.Boolean;
param[6].value = _add_IsDeleted;
param[7].direction = ParameterDirection.Input;
param[7].ParamName = "#add_IsPrimary";
param[7].DataType = DbType.Boolean;
param[7].value = _add_IsPrimary;
param[8].direction = ParameterDirection.Input;
param[8].ParamName = "#add_cntm_Id";
param[8].DataType = DbType.Int32;
param[8].value = _add_cntm_Id;
param[9].direction = ParameterDirection.Input;
param[9].ParamName = "#add_alt_No";
param[9].DataType = DbType.String;
param[9].value = _add_alt_No;
obj.ExecScalar("Insertaddress_Master", CommandType.StoredProcedure, param);
_returnBoolean = true;
}
catch (DataException ex)
{
_returnBoolean = false;
throw ex;
}
}
when I try to insert data using this code it generates exception saying " Procedure or function Insertaddress_Master has too many arguments specified". Can anyone help solving this problem.
I've read all previous thread on this topic but couldn't find appropriate solution yet.
SqlCommand objCommand = new SqlCommand();
you can recreate this object then it will work.
I got this answer.
You have two fields:
Is Deleted
Is Primarry
You have to passed the boolean that may have true/false.
Try passing 1 for true and 0 for false.
This should do the trick

Oracle Parameters as Array throws "index was outside the bounds" of the array error

I have a problem executing an Oracle Stored Procedure with parameters in Visual Studio (C#). Parameters are array values which user select. When I try to execute, it throws "Index was outside the bounds of the array". I cannot solve the problem.
My code below:
public void ExecSPWBulkInsert(string spName, object[] myObjects)
{
OracleCommand command = new OracleCommand();
OracleParameter[] discoveredParameters = findSPParameters(spName);
command.Connection = oraConn;
command.ArrayBindCount = discoveredParameters.Length ;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
OracleParameter[] param = new OracleParameter[discoveredParameters.Length];
ArrayList[] parameters = new ArrayList[discoveredParameters.Length];
for (int i = 0; i < discoveredParameters.Length; i++)
{
parameters[i] = new ArrayList();
foreach (object obj in myObjects)
{
foreach (var prop in obj.GetType().GetProperties())
{
if (prop.Name == discoveredParameters[i].ParameterName)
{
parameters[i].Add(prop.GetValue(obj));
}
}
}
param[i] = new OracleParameter();
param[i].Direction = ParameterDirection.Input;
param[i].ArrayBindSize = new int[parameters[i].Count];
param[i].Size = 1000;
param[i].ParameterName = discoveredParameters[i].ParameterName;
param[i].OracleDbType = discoveredParameters[i].OracleDbType;
param[i].Value = parameters[i].ToArray();
command.Parameters.Add(param[i]);
}
try
{
oraConn.Open();
command.Transaction = oraConn.BeginTransaction();
command.ExecuteNonQuery();
command.Transaction.Commit();
oraConn.Close();
}
catch (Exception ex)
{
throw;
}
finally
{
oraConn.Close();
}
}

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