Below are the quick read about my code implemented
Declared interface in ILogic.cs file.
DataSet updateStatus();
Return interface in CLogic.cs file.
public DataSet updateStatus()
{
return this.Repository.updateStatus();
}
Interface method implementation in Repository.cs file, What is the correct way to implement this method.
public DataSet updateStatus()
{
try
{
dataSet = new DataSet();
using (SqlCommand cmd = new SqlCommand(StoredProcedures.JobStausUpdate, conETLITG))
{
conITG.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(jobid);
adapt.Fill(dataSet);
conITG.Close();
}
return dataSet;
}
catch (Exception es)
{
throw es;
}
}
Calling method as below in Program.cs file so how can I pass #Execution_Job_ID in updateStatus
intjobId=86746;
commonLogic.updateStatus(jobId);
SQL Store Procedure
CREATE PROCEDURE JobStausUpdate
( #Execution_Job_ID INT
)
AS
BEGIN
SELECT TOP 3
ji.jobname,
jel.*
INTO #tempjobstatus
FROM joblog jel
INNER JOIN jobinfo ji
ON jel.jobid=ji.jobid
WHERE jel.jobid IN (67,89,44)
AND jel.joblogid <= #Execution_Job_ID
ORDER BY 2 DESC
DECLARE #ARefresh VARCHAR(30),
#BRefresh VARCHAR(30),
#statusId INT,
#statusReturn INT
SET #ARefresh =
(
SELECT jobstatus
FROM #tempjobstatus
WHERE jobname ='aRefresh')
IF (#ARefresh = 'Failed')
BEGIN
SET #BRefresh =
(
SELECT jobstatus
FROM #tempjobstatus
WHERE jobname ='bRefresh')
IF (#BRefresh = 'In Progress')
BEGIN
SET #statusId =
(
SELECT joblogid
FROM #tempjobstatus
WHERE jobname ='bRefresh')
UPDATE joblog
SET jobstatus = 'Failed'
WHERE joblogid = #statusId
SET #statusReturn=1
END
ELSE SET #statusReturn =0
END
ELSE IF (#ARefresh = 'Completed')
BEGIN
SET #BRefresh =
(
SELECT jobstatus
FROM #tempjobstatus
WHERE jobname ='bRefresh')
IF (#BRefresh = 'In Progress')
BEGIN
SET #statusId =
(
SELECT joblogid
FROM #tempjobstatus
WHERE jobname ='bRefresh')
UPDATE joblog
SET jobstatus = 'Completed'
WHERE joblogid = #statusId
SET #statusReturn=1
END
ELSE SET #statusReturn =0
END
ELSE
BEGIN
SET #statusReturn=0
END
SELECT #statusReturn
SELECT * FROM #tempjobstatus
END
Maybe I'm misunderstanding the question but you just need to update your Interface to include the int you want to pass then change your cmc.Parameters.Add.
DataSet updateStatus(int jobid);
cmd.Parameters.Add(new SqlParameter("#JobID",jobid));
Related
I am trying to get the value of output parameter of a stored procedure in c# function. when i execute the SP i am getting correct result in sql server but i can't get in c#. Can you please tell me how can i get the output value in c#. Below is the function i am trying to get the output value in C# DAC.
public DataSet GetOrderItemPictureByOrderId(int orderID, int PageIndex)
{
DataSet dtOrder = new DataSet();
/// Connect to database.
Database db = DatabaseFactory.CreateDatabase(CONNECTION_NAME);
using (DbCommand cmd = db.GetStoredProcCommand("uspGetOrderItemPicturePageWise"))
{
/// Set parameter values.
db.AddInParameter(cmd, "#OrderID", DbType.Int32, orderID);
db.AddInParameter(cmd, "#PageIndex", DbType.Int32, PageIndex);
db.AddInParameter(cmd, "#PageSize", DbType.Int32, 6);
db.AddOutParameter(cmd, "#RecordCount", DbType.Int32, 4);
try
{
dtOrder = db.ExecuteDataSet(cmd);
string outputValue = cmd.Parameters["#RecordCount"].Value.ToString(); // here i want to get the output value and want to return the value to main code
}
catch (Exception ex)
{
LogErrors.WriteError(ex);
}
}
return dtOrder;
}
}
Here i am calling the function :-
DataSet _ds = _orderPicDAC.GetOrderItemPictureByOrderId(OrderID, PageIndex);
My Store Procedure :--
CREATE PROCEDURE [dbo].[uspGetOrderItemPicturePageWise]
#OrderID int,
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PictureId] ASC
)AS RowNumber,
Orderid,
GenericFieldID,
ItemImage
INTO #Results
FROM [OrderPictures]
WHERE OrderID = #OrderID
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Thanks for your help in advance.
If you want to get value of output parameter outside the method without changing the return type of the method, you may use out parameters in C#.
Change your method definition like below:
public DataSet GetOrderItemPictureByOrderId(int orderID, int PageIndex, out string outputValue)
{
//code here
outputValue = db.GetParameterValue(cmd, "#RecordCount");
//code here
}
and then call this method
string outvalue;
DataSet _ds = _orderPicDAC.GetOrderItemPictureByOrderId(OrderID, PageIndex,out outvalue;);
You will have the value in outvalue variable.
You can try with below
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#OrderID", DbType.Int32, orderID);
con.Open();
cmd.ExecuteNonQuery();
}
}
This is the BL class for insert of data:
public string CategoryIsert(clsCategoryPL objCategory, out int returnId)
{
returnId = 0;
try
{
var db = new KSoftEntities();
var category = new tblCategory
{
Name = objCategory.Name,
ParentCategoryID = objCategory.ParentCategoryID,
description = objCategory.description,
image = objCategory.image,
Status = objCategory.Status
};
//db.AddTotblCategories(category);
db.tblCategories.Add(category);
db.SaveChanges();
returnId = category.CategoryID;
}
catch (Exception ex) { }
if (returnId > 0)
return "User Inserted Successfully";
else
return "Error on insertion";
}
aspx code for adding value:
private int AddCategory()
{
clsCategoryBL objcategory = new clsCategoryBL();
clsCategoryPL objCategoryPL = new clsCategoryPL();
int retnid = 0;
objCategoryPL.description = txtCategoryDescription.Text;
objCategoryPL.Name = txtCategoryName.Text;
objCategoryPL.ParentCategoryID = Convert.ToInt32(ddlParentCategory.SelectedValue);
objCategoryPL.Status = true;
objcategory.CategoryIsert(objCategoryPL, out retnid);
if (retnid > 0)
{
if (Convert.ToInt32(ddlParentCategory.SelectedValue) == 0)
{
objCategoryPL.ParentCategoryID = retnid;
}
objCategoryPL.CategoryID = retnid;
string strMessage = objcategory.CategoryUpdate(objCategoryPL);
}
return retnid;
}
I have created a stored procedure in the database:
CREATE PROCEDURE [dbo].[Sp_Checknm_Cat]
#ID int,
#NAME nvarchar(400),
#Count INT = 0
AS
BEGIN
DECLARE #output int
IF(#ID > 0)
BEGIN
SET #Count = (select count(*) from tblCategory
where Name = #NAME and CategoryID <> #ID)
END
ELSE
BEGIN
SET #Count = (select count(*) from tblCategory where Name = #NAME)
END
IF(#Count > 0)
BEGIN
SET #output = 0
END
ELSE
BEGIN
SET #output = 1
END
RETURN #output
END
I want to check if the name is already exist during insert/update, then it will show me a error message in lable
So where is the change needed?
This is for bl :
ClsDB objdb = new ClsDB();
public Int32 InsertnmCheck(int id, string nm)
{
DataTable dtdonor = new DataTable();
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("#ID", SqlDbType.Int);
param[0].Direction = ParameterDirection.Input;
param[0].Value = id;
param[1] = new SqlParameter("#NAME", SqlDbType.NVarChar);
param[1].Direction = ParameterDirection.Input;
param[1].Value = nm;
int a = objdb.insert_delete_update("[Sp_Checknm_Cat]", param);
return a;
}
here is my backend code:
else if (btnSubmit.CommandName == "Add")
{
clsCategoryBL obj = new clsCategoryBL();
Int32 dt = obj.InsertnmCheck(0, txtCategoryName.Text);
// DataTable dt = obj.InsertnmCheck(0, txtCategoryName.Text);
{
}
int retid = AddCategory();
if (retid > 0)
{
}
problem is that the query(sp) returns 0 but in bl class it will returns -1
so is there any solution??
Throw an exception.
CREATE PROCEDURE [dbo].[usp_Checknm_Cat] /* do not prefix with 'sp' */
#ID int,
#NAME nvarchar(400),
#Count INT=0
AS
BEGIN
DECLARE #output int
if(#ID>0)
begin
set #Count= #Count + (select count(*) from tblCategory where Name=#NAME and CategoryID<>#ID)
end
else
begin
set #Count= #Count + (select count(*) from tblCategory where Name=#NAME)
end
if(#Count>0)
BEGIN;
THROW 51000, 'Duplicates Exist', 1;
END;
END
and c#
public void /* VOID, not a return code or return string */ CategoryIsert(clsCategoryPL objCategory)
{
try
{
var db = new KSoftEntities();
var category = new tblCategory
{
Name = objCategory.Name,
ParentCategoryID = objCategory.ParentCategoryID,
description = objCategory.description,
image = objCategory.image,
Status = objCategory.Status
};
//db.AddTotblCategories(category);
db.tblCategories.Add(category);
db.SaveChanges();
returnId = category.CategoryID;
}
catch (SqlException sqlex) {
/* you can examine the sql exception here, if you want to look for the 51000 */
throw;
}
catch (Exception ex) {
throw;
}
}
I created a procedure that returns the ID of the Question based on the input text
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
#Tekst nvarchar(100)
)
AS
DECLARE #QuestionID int
SELECT QuestionID
FROM dbo.Questions
WHERE Tekst = #Tekst
RETURN #QuestionID
and I have a problem in getting the value of the QuestionID:
public static int getQuestionID(Question p)
{
using (Entities dm = new Entities())
{
return dm.GetQuestionIDbyTekst(p.Tekst);
}
}
Make the #QuestionID as Output parameter. Also you need to assign the result to #QuestionID
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
#Tekst nvarchar(100),
#QuestionID INT OUTPUT
)
AS
BEGIN
DECLARE #QuestionID int
SELECT #QuestionID = QuestionID FROM dbo.Questions WHERE Tekst = #Tekst
END
please try this:
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
#Tekst nvarchar(100)
)
AS
-- DECLARE #QuestionID int
SELECT QuestionID
FROM dbo.Questions
WHERE Tekst = #Tekst
-- RETURN #QuestionID
You can use your variant of the stored procedure.
And if you use ADO.NET and want to get return value, try this:
SqlConnection con = new SqlConnection(#"Data Source=localhost\***;Initial Catalog=***;Integrated Security=True;Persist Security Info=False;");
con.Open();
SqlCommand cmd = new SqlCommand("GetQuestionIDbyTekst", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#Tekst", System.Data.SqlDbType.NVarChar).Value = "eee";
SqlParameter returnPar = new SqlParameter();
returnPar.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(retturnPar);
cmd.ExecuteScalar();
var result = returnPar.Value;
If you use Entity Framework, you may use this variant:
public static int GetQuestionIDbyTekst(string question)
{
using (var context = new EfDbContext())
{
var test = new SqlParameter("#Tekst", question);
var resultParam = new SqlParameter("#result", SqlDbType.Int);
resultParam.Direction = ParameterDirection.Output;
context.Database.ExecuteSqlCommand("exec #result = [dbo].[testProc] #Tekst", resultParam, test);
return (int)resultParam.Value;
}
}
I write this function in SQL:
ALTER FUNCTION Fn_CheckBill
(
#image AS image,
#number AS nvarchar(50),
#date AS nchar(10)
)
RETURNS bit
AS
BEGIN
DECLARE #flag bit;
IF EXISTS ( SELECT *
FROM tblBill
WHERE ((cast([Image] as varbinary(max)) = cast(#image as varbinary(max))) AND (Number = #number) AND ([Date] = #date)) )
BEGIN
SET #flag = 0
END
ELSE
BEGIN
SET #flag = 1
END
RETURN #flag
END
And write this code in my C# source code:
int flag;
try
{
objCommand = new SqlCommand("SELECT Fn_CheckBill(#image,#date,#number) AS int");
objCommand.CommandType = CommandType.Text;
objCommand.Parameters.AddWithValue("image", image);
objCommand.Parameters.AddWithValue("number", number);
objCommand.Parameters.AddWithValue("date", _Date);
using (objConnection = new SqlConnection(connenctString))
{
objConnection.Open();
objCommand.Connection = objConnection;
flag = int.Parse(objCommand.ExecuteScalar().ToString());
}
if (flag == 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
But It throw this exception when executed:
'Fn_CheckBill' is not a recognized function name.
Please help me to solve this problem :(
You need to supply the schema in any SQL function call
objCommand = new SqlCommand("SELECT dbo.Fn_CheckBill(#image,#date,#number) AS int");
I would consider rewriting this as an inline table valued function. Something like this:
create FUNCTION Fn_CheckBill
(
#image AS varbinary(max),
#number AS nvarchar(50),
#date AS nchar(10)
)
RETURNS table
AS
RETURN
SELECT CAST(count(*) as bit) as RowFound
FROM tblBill
WHERE [Image] = #image
AND Number = #number
AND [Date] = #date
Below is an example of using the stored procedure(GetTimesWithCustomerNames) then via ArrayList collecting data retrieved by the query:
/*
GetTimesWithCustomerNames 3571, 6, 2012, 1
GetTimesWithCustomerNames '3571', '6', '2012', '0'
*/
ALTER PROCEDURE [dbo].[GetTimesWithCustomerNames]
#userid int=0, #month int=0, #year int=0,#reasonid int=0
AS
BEGIN
SET NOCOUNT ON;
if #userid!=0 begin
create table #tmp (tId int, UserId int,
TimeIn1 smalldatetime, [TimeOut1] smalldatetime,
TimeIn2 smalldatetime, [TimeOut2] smalldatetime, tId2 int,
TimeIn3 smalldatetime, [TimeOut3] smalldatetime, tId3 int,
ActiveDate smalldatetime, ReasonID int, Name nvarchar(100), ReasonType nvarchar(100),
TotalMins int)
insert into #tmp (tId, UserId, TimeIn1, TimeOut1, ActiveDate, ReasonID, Name, ReasonType)
SELECT
t1.tId, t1.UserId, t1.TimeIn, t1.[TimeOut], t1.ActiveDate, t1.ReasonID, tblCustomers.Name,
(select reasontype from tblTimeReas where ReasonID=t1.ReasonID) as ReasonType
FROM tblTime t1
inner join tblCustomers on t1.UserId=tblCustomers.custID
where (t1.userid=#userid)
and (DATEPART(MONTH,t1.timein)=#month or #month=0)
and (DATEPART(YEAR,t1.timein)=#year or #year=0)
and (t1.reasonid = #reasonid or #reasonid=0)
and
(select COUNT(1) from tblTime t2 where userid=#userid and datediff(day,t2.TimeIn,t1.TimeIn)=0 and t2.tId<t1.tId)=0
update #tmp
set tId2 = (select top 1 tId from tblTime t2 where userid=#userid and DATEDIFF(day,t2.timein,#tmp.timein1)=0
and t2.tId>#tmp.tId order by tId asc)
update #tmp
set tId3 = (select top 1 tId from tblTime t3 where userid=#userid and DATEDIFF(day,t3.timein,#tmp.timein2)=0
and t3.tId>#tmp.tId2 order by tId asc)
update #tmp
set TimeIn2 = (select TimeIn from tblTime where tId=tId2),
TimeOut2 = (select [TimeOut] from tblTime where tId=tId2),
TimeIn3 = (select TimeIn from tblTime where tId=tId3),
TimeOut3 = (select [TimeOut] from tblTime where tId=tId3)
update #tmp set TotalMins = (
isnull(DATEDIFF(minute,timein1,timeout1),0)+
isnull(DATEDIFF(minute,timein2,timeout2),0)+
isnull(DATEDIFF(minute,timein3,timeout3),0)
)
select * from #tmp order by TimeIn1
drop table #tmp
end
END
I would like to know, for given userid I can have all data returned into an ArrayList - what is the way to retrive a set of values per userid ? Will it be possible to have a data returned per user(few) in an arrayList and not for one only like this procedure ?
In this query data is TimeIn TimeOut ActiveDate etc...
ReEditing
I think my question is should the task be for the code behind in a foreach loop or would it be possible to modify the procedure to accept more than one userid?
The code I am using to store data in code behind is:
public static ArrayList loadData(string sql)
{
DBManager dbManager = new DBManager(DataProvider.SqlServer, "Data Source=(local);Initial Catalog=databaseName;Integrated Security=True");
ArrayList data = new ArrayList();
try
{
dbManager.Open();
dbManager.ExecuteReader(System.Data.CommandType.Text, sql);
while (dbManager.DataReader.Read())
{
Hashtable x = new Hashtable();
for (int i = 0; i < dbManager.DataReader.FieldCount; i++)
{
x.Add(dbManager.DataReader.GetName(i), dbManager.DataReader.GetValue(i));
}
x.Add("COUNTER", data.Count+1);
data.Add(x);
}
}
catch { data = null; }
finally
{
dbManager.Dispose();
}
return data;
}
public static List<Dictionary<string, object>> loadData(string sql)
{
itson = (sql.StartsWith("GetTimesWith"));
DBManager dbManager = new DBManager(DataProvider.SqlServer, "Data Source=(local);Initial Catalog=hental;Integrated Security=True");
//ArrayList data = new ArrayList();
List<Dictionary<string, object>> data = new List<Dictionary<string,object>>();
try
{
dbManager.Open();
dbManager.ExecuteReader(System.Data.CommandType.Text, sql);
while (dbManager.DataReader.Read())
{
//Hashtable x = new Hashtable();
Dictionary<string, object> x = new Dictionary<string, object>();
for (int i = 0; i < dbManager.DataReader.FieldCount; i++)
{
x.Add(dbManager.DataReader.GetName(i), dbManager.DataReader.GetValue(i));
}
x.Add("COUNTER", data.Count+1);
data.Add(x);
ncx = data.Count;
}
}
catch { data = null; }
finally
{
dbManager.Dispose();
}
return data;
}