Related
I'm executing a SQL Server stored procedure which returns a single output parameter using AsyncPoco:
CREATE PROCEDURE [dbo].[GenerateId]
(#RETVAL VARCHAR(12) OUTPUT)
AS
DECLARE #pkgID VARCHAR(12)
BEGIN
SELECT #pkgID = 'ABC' + '000'
SELECT #RETVAL = #pkgID
END
GO
Here's how I'm calling it:
var spOutput = new SqlParameter("#RETVAL", System.Data.SqlDbType.VarChar)
{
Direction = System.Data.ParameterDirection.Output,
Size = 12,
};
var sql = $";EXEC [dbo].[GenerateId] #0 OUTPUT";
var response = await _dbAdapter.FetchAsync<dynamic>(sql, new object[] { spOutput });
return (string)spOutput.Value;
This is the error I get:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Object.GetType()
at AsyncPoco.Database.FormatCommand(String sql, Object[] args) in C:\Aldenteware\AsyncPoco\code\AsyncPoco\Database.cs:line 2279
I figured it out:
var spOutput = new SqlParameter("#RETVAL", System.Data.SqlDbType.VarChar)
{
Direction = System.Data.ParameterDirection.Output,
Size = 12,
};
var sql = $";EXEC [dbo].[GenerateId] ##RETVAL = #0 OUTPUT";
var sqlClass = new Sql();
var s = sqlClass.Append(sql, spOutput);
var response = await _dbAdapter.ExecuteAsync(s);
return (string)spOutput.Value;
Can anyone help me with problem with trigger on insert/update when inserting records to tables in a SQL Server database using EF and TransactionScope?
When I try the trigger in SQL Server Management Studio, it's working fine, also the app is working fine when there is no trigger or trigger is disabled.
I have 2 SQL Server tables, Orders and OrdersParts. I have a trigger on OrdersParts that I use to update another table based calculations of inserted records.
Is any workaround so I can make something in SQL Server trigger because I don't want to change the code?
Thank you...
Here is my code in VS, I get fail in repository.CreateOrder
public void CreateOrder(Guid userId, int? referenceId, Cart cart, OrderInfo orderInfo)
{
using (TransactionScope transaction = new TransactionScope())
{
var order = new Orders
{
UserId = userId,
ReferenceId = referenceId,
Status = (int)OrderStatus.Created,
PaymentType = (int)orderInfo.PaymentType,
ShippingType = orderInfo.ShippingType,
Comment = orderInfo.Comment,
DateTimeCreated = DateTime.Now
};
context.Orders.Add(order);
context.SaveChanges();
foreach (var line in cart.Lines)
{
context.OrdersParts.Add(new OrdersParts
{
PartId = line.Product.ProductId,
OrderId = order.OrderId,
Price = line.Product.Price,
Quantity = line.Quantity
});
}
context.SaveChanges();
transaction.Complete();
}
}
Here is My CreateOrder HTTP Post Method:
[HttpPost]
public ActionResult CreateOrder(Cart cart, OrderInfo orderInfo)
{
var result = new JsonResult<bool>() { Status = true };
var user = Membership.GetUser(User.Identity.Name);
var userId = (Guid)user.ProviderUserKey;
try
{
var userDetails = usersRepository.Members.FirstOrDefault(x => x.UserId == userId);
if (!userDetails.ClientId.HasValue)
{
result.Status = false;
result.Result = false;
result.Message = "Errror Client";
return Json(result);
}
int clientId = userDetails.ClientId.Value;
// Create order in WareHouse
string message = null;
int? referenceId;
if (!integrationService.CreateOrder(clientId, cart, orderInfo, out referenceId, out message))
{
result.Status = false;
result.Result = false;
result.Message = message;
return Json(result);
}
repository.CreateOrder(userId, referenceId, cart, orderInfo);
cart.Clear();
result.Result = true;
result.Message = "";
}
catch
{
result.Status = false;
result.Result = false;
result.Message = "Error on creating order! Please try again.";
}
return Json(result);
}
Trigger:
ALTER TRIGGER [dbo].[UpdateComment] ON [dbo].[OrdersParts]
WITH EXECUTE AS CALLER
AFTER INSERT, UPDATE
AS
BEGIN
DECLARE #OrderID INT;
DECLARE #QDefWareH INT;
DECLARE #OrderedQuantity INT;
DECLARE #ArticleID VARCHAR(20);
DECLARE my_Cursor CURSOR FAST_FORWARD
FOR
SELECT a.OrderId ,
a.Quantity ,
b.RefSifra
FROM INSERTED a
LEFT OUTER JOIN dbo.Accounting b ON b.PartId = a.PartId;
OPEN my_Cursor;
FETCH NEXT FROM my_Cursor INTO #OrderID, #OrderedQuantity, #ArticleID;
EXEC #QDefWareH = _SPArtInDefWarehouse #ArticleID;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #QDefWareH;
IF ( #OrderedQuantity > #QDefWareH )
BEGIN
UPDATE dbo.Orders
SET Comment = IIF(Comment IS NULL, #ArticleID, Comment
+ ' ;' + CHAR(13) + CHAR(10) + #ArticleID)
WHERE OrderId = #OrderID;
END;
FETCH NEXT FROM my_Cursor INTO #OrderID, #OrderedQuantity,
#ArticleID;
END;
CLOSE my_Cursor;
DEALLOCATE my_Cursor;
END;
I have an ASP.NET MVC application in C# where I am calling a stored procedure CreateFunctionNavigation. I am having issue calling that stored procedure along with parameters. I have model class as;
Model class
public class CreateFunctionNavigation_SP_Map
{
public CreateFunctionNavigation_SP_Map()
{
}
[StringLength(250)]
[Required(ErrorMessage = "Required Function Title")]
[Display(Name = "Function Title")]
public string FunctionName { get; set; }
[Required(ErrorMessage = "Required Function Hierarchy; i.e Where Function Exists In Hierarchy Tree \n Top-Level Start From 1 ")]
[Display(Name = "Function Hierarchy Level")]
public int FunctionHierarchy_Level { get; set; }
[StringLength(250)]
[Required(ErrorMessage = "Required Controller Title")]
[Display(Name = "Controller Title")]
public string ControllerName { get; set; }
[StringLength(250)]
[Required(ErrorMessage = "Required Action Title")]
[Display(Name = "Action Title")]
public string ActionName { get; set; }
[Required(ErrorMessage = "Required Function Parent - Child Relation ID \n Put 0 In Case Given Function doesn't Have Any Parent Function ")]
[Display(Name = "Function Parent's FunctionID")]
public int Function_ParentsFunctionID { get; set; }
}
Stored procedure:
ALTER PROCEDURE [dbo].[CreateFunctionNavigation]
#FunctionName nvarchar(250),
#Hierarchy_Level INT,
#Function_identity INT OUTPUT,
#ControllerName nvarchar(250),
#Controller_identity INT OUTPUT,
#ControllerInFunction_identity INT OUTPUT,
#ActionName nvarchar(250),
#Action_identity INT OUTPUT,
#ActionInFunction_identity INT OUTPUT,
#Function_ParentsFunctionID INT,
#Function_ParentsFunction_identity INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Navigation_Functions] ([FunctionName],[Hierarchy_Level])
VALUES(#FunctionName, #Hierarchy_Level)
SET #Function_identity = SCOPE_IDENTITY()
INSERT INTO [dbo].[Navigation_FunctionController] ([ControllerName])
VALUES(#ControllerName)
SET #Controller_identity = SCOPE_IDENTITY()
INSERT INTO [dbo].[Navigation_FunctionInController] ([Function_ID], [ControllerID])
VALUES (#Function_identity, #Controller_identity)
SET #ControllerInFunction_identity = SCOPE_IDENTITY()
INSERT INTO [dbo].[Navigation_FunctionAction] ([ActionName], [ControllerID])
VALUES (#ActionName, #Controller_identity)
SET #Action_identity = SCOPE_IDENTITY()
INSERT INTO [dbo].[Navigation_FunctionInAction] ([ActionID], [Function_ID])
VALUES (#Action_identity, #Function_identity)
SET #ActionInFunction_identity = SCOPE_IDENTITY()
INSERT INTO [dbo].[Navigation_FunctionHierarchy] ([Function_IDs], [Parent_Function_ID])
VALUES (#Function_identity, #Function_ParentsFunctionID)
SET #Function_ParentsFunction_identity = SCOPE_IDENTITY()
RETURN
END
now in C# class I am trying to run this stored procedure with passing parameters but in SQL Server Profiler I cannot see if this stored procedure is not called.
C# Code to run stored procedure
var _result = dbContext.Database.SqlQuery<CreateFunctionNavigation_SP_Map>("exec CreateFunctionNavigation #FunctionName #FunctionHierarchy_Level #ControllerName #ActionName #Function_ParentsFunctionID",
new SqlParameter("FunctionName",_entity.FunctionName),
new SqlParameter("FunctionHierarchy_Level",_entity.FunctionHierarchy_Level),
new SqlParameter("ControllerName", _entity.ControllerName),
new SqlParameter("ActionName", _entity.ActionName),
new SqlParameter("Function_ParentsFunctionID",_entity.Function_ParentsFunctionID)
);
But if I run this stored procedure by just calling it without parameter and of course simply stored procedure with select statement then it works and I can also see in SQL Profiler that stored procedure is called.
Working C# code
List<CreateFunctionNavigation_SP_Map> query;
query = dbContext.Database.SqlQuery<CreateFunctionNavigation_SP_Map>("exec CreateFunctionNavigation").ToList();
So I believe issue is C# class from where I am trying to call SP along with parameters. I badly stuck, tried different options but don't know what I am doing wrong. Many thanks in advance
have you tried adding commas inbetween your parameter names?
dbContext.Database.SqlQuery<CreateFunctionNavigation_SP_Map>("exec CreateFunctionNavigation #FunctionName, #FunctionHierarchy_Level, #ControllerName, #ActionName, #Function_ParentsFunctionID"
UPDATE: just checked out your stored proc code too, seen there are some issues with it.
Here is how I would change it
ALTER PROCEDURE [dbo].[CreateFunctionNavigation]
#FunctionName nvarchar(250),
#Hierarchy_Level INT,
#ControllerName nvarchar(250),
#ActionName nvarchar(250),
#Function_ParentsFunctionID INT,
#Function_identity INT OUTPUT,
#Controller_identity INT OUTPUT,
#ControllerInFunction_identity INT OUTPUT,
#Action_identity INT OUTPUT,
#ActionInFunction_identity INT OUTPUT,
#Function_ParentsFunction_identity INT OUTPUT
This puts all your outputs at the end of the function.
Right, on your c# code
var function_identity new SqlParameter() {ParameterName = "Function_identity", Direction = ParameterDirection.Output};
var controller_identity new SqlParameter() {ParameterName = "Controller_identity", Direction = ParameterDirection.Output};
var controllerInFunction_identity new SqlParameter() {ParameterName = "ControllerInFunction_identity", Direction = ParameterDirection.Output};
var action_identity new SqlParameter() {ParameterName = "Action_identity", Direction = ParameterDirection.Output};
var actionInFunction_identity new SqlParameter() {ParameterName = "ActionInFunction_identity", Direction = ParameterDirection.Output};
var function_ParentsFunction_identity new SqlParameter() {ParameterName = "Function_ParentsFunction_identity", Direction = ParameterDirection.Output};
var _result = dbContext.Database.SqlQuery<CreateFunctionNavigation_SP_Map>("exec CreateFunctionNavigation #FunctionName, #FunctionHierarchy_Level, #ControllerName, #ActionName, #Function_ParentsFunctionID, #Function_identity out, #Controller_identity out, #ControllerInFunction_identity out, #Action_identity out, #ActionInFunction_identity out, #Function_ParentsFunction_identity out",
new SqlParameter("FunctionName",_entity.FunctionName),
new SqlParameter("FunctionHierarchy_Level",_entity.FunctionHierarchy_Level),
new SqlParameter("ControllerName", _entity.ControllerName),
new SqlParameter("ActionName", _entity.ActionName),
new SqlParameter("Function_ParentsFunctionID",_entity.Function_ParentsFunctionID),
function_identity ,
controller_identity ,
controllerInFunction_identity ,
action_identity ,
actionInFunction_identity,
function_ParentsFunction_identity
);
That might get you somewhere close.
here is my answer; it is working
List<GetNewlyCreatedNavigationsFunction_SP_Map> _query;
var function_identity_out = new SqlParameter("Function_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
var controller_identity_out = new SqlParameter("Controller_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
var controllerInFunction_identity_out = new SqlParameter("ControllerInFunction_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
var action_identity_out = new SqlParameter("Action_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
var actionInFunction_identity_out = new SqlParameter("ActionInFunction_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
var function_ParentsFunction_identity_out = new SqlParameter("Function_ParentsFunction_identity", SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output };
_query = dbContext.Database.SqlQuery<GetNewlyCreatedNavigationsFunction_SP_Map>("exec CreateFunctionNavigation #FunctionName, #Hierarchy_Level, #ControllerName, #ActionName, #Function_ParentsFunctionID, #Function_identity out, #Controller_identity out, #ControllerInFunction_identity out, #Action_identity out, #ActionInFunction_identity out, #Function_ParentsFunction_identity out",
new SqlParameter("#FunctionName", _entity.FunctionName),
new SqlParameter("#Hierarchy_Level", _entity.FunctionHierarchy_Level),
new SqlParameter("#ControllerName", _entity.ControllerName),
new SqlParameter("#ActionName", _entity.ActionName),
new SqlParameter("#Function_ParentsFunctionID", _entity.Function_ParentsFunctionID),
function_identity_out,
controller_identity_out,
controllerInFunction_identity_out,
action_identity_out,
actionInFunction_identity_out,
function_ParentsFunction_identity_out
).ToList();
I have got 2 asp pages. Firstly i get logged in through log in page and 2nd page is home page where i got few buttons of some tasks. Along with that i got user details which consists of FULLNAME,ADDRESS,CELL NUMBER,BLOOD GROUP and EMAILID, this should be displayed dynamically in their particular labels from DATABASE once the user logs in using his username and password.
I have written Query for this within the GetLoginDetails Stored Procedure. I have to display Employee Name,his Last Login Date,Time etc. once his log in and enters home page in the same way i should get user details.
ALTER PROCEDURE [dbo].[GetLastLogin]
#LoggedInUser nvarchar(50),
#FullName nvarchar(50),
#Address nvarchar(50),
#MobileNumber bigint,
#EmailID nvarchar(50),
#BloodGroup nvarchar(50),
#EmpName nvarchar(50)
As
Declare #LastLogin int
Set #LastLogin = (Select MAX(AccessID)from dbo.ACCESS_INFO where Flag = 1)
Select Access_Date, Access_Time from dbo.ACCESS_INFO where LoggedInUser = #LoggedInUser and AccessID = #LastLogin
Update dbo.EmployeeData
Set Empname = #EmpName
where FullName = #FullName and Address = #Address and MobileNumber = #MobileNumber and EmailID = #EmailID and BloodGroup = #BloodGroup ;
im getting error saying tht ("Procedure or function 'GetLastLogin' expects parameter '#FullName', which was not supplied.") please help me out
back end code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
try
{
MTMSDTO objc = new MTMSDTO();
LblLogdInUser.Text = Session["EmpName"].ToString();
LblUser.Text = Session["Username"].ToString();
objc.LoggedInUser = LblUser.Text;
DataSet laslogin = obj.GetLastLogin(objc);
DataView LasLogin = new DataView();
LasLogin.Table = laslogin.Tables[0];
GrdLasLogin.DataSource = LasLogin;
GrdLasLogin.DataBind();
if (!IsPostBack)
{
int lastlog = GrdLasLogin.Rows.Count;
if (lastlog == 0)
{
LblLastLoginD.Text = "This is your First Login";
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
else
{
LblLastLoginD.Text = Convert.ToDateTime(GrdLasLogin.Rows[0].Cells[0].Text).ToString("dd/MMM/yyyy");
LblLastLoginT.Text = GrdLasLogin.Rows[0].Cells[1].Text;
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
LblFname.Visible = true;
LblAdd.Visible = true;
LblMnum.Visible = true;
LblMailID.Visible = true;
LblBGroup.Visible = true;
}
}
catch (Exception ex)
{
Response.Redirect("ERROR.aspx");
Session.Abandon();
}
}
else
{
Response.Redirect("~/Login.aspx");
}
Response.CacheControl = "no-cache";
}
The error message makes it clear that you need to supply values for the parameter FullName. So, if you aren't already doing that, then go do that. The only complication here is null values; a string can be null, but to specify that in ADO.NET you need to pass DBNull.Value; if you use null the parameter is not included. This means you end up with code like:
cmd.Parameters.AddWithValue("FullName", (object)fullName ?? DBNull.Value);
Ugly, but it works.
Alternatively, many helper utilities will do this for you. So with "dapper":
var lastAccess = conn.Query<AccessInfo>("GetLastLogin",
new { LoggedInUser = cn, FullName = fullName, /* snipped */ },
commandType: CommandType.StoredProcesdure).FirstOrDefault();
The problem is not in your SQL. It's in your calling function in asp. You are not sending the fullname parameter to SQL server correctly. Check out this question for an example on how to send parameters.
Call a stored procedure with parameter in c#
I have an SQL server with the following layout
Table ( id int
title varchar(40),
start Date(),
end Date(),
allDay bool,
username varchar(40)
);
I have gotten the following code from this blog to create a JSON object from the data I wish to use, however his data is stored differently. How do I create the same object, extracted from my database?
I am guessing I need to make the file a .cshtml file rather than a .js file and use this :
#{
var db = Database.Open("events");
var selectQueryString = "SELECT * FROM events";
}
#foreach(var row in db.Query(selectQueryString)){ }
But how do I adapt this code to produce the same JSON object?
Here is the relevant code from the blog, my attempt is below :
public JsonResult GetEvents(double start, double end)
{
var userName = Session["UserName"] as string;
if(string.IsNullOrEmpty(userName))
{
return null;
}
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var rep = Resolver.Resolve<IEventRepository>();
var events = rep.ListEventsForUser(userName,fromDate,toDate);
var eventList = from e in events
select new {
id = e.Id,
title = e.Title,
start = e.FromDate.ToString("s"),
end = e.ToDate.ToString("s"),
allDay = false
};
var rows = eventList.ToArray();
return Json(rows,JsonRequestBehavior.AllowGet);
}
Edit :
I am now working with the following .cshtml code for the GetEvents command, but it will not work. Does anybody have any ideas ?
#{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var fromDate = origin.AddSeconds((Request["start"]));
var toDate = origin.AddSeconds(Request["end"]);
var db = Database.Open("events");
var result = db.Query("SELECT * FROM events");
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
There are no controllers and actions in WebMatrix WebPages. You need to write a separate .cshtml page that will query the database and serve the JSON to the response:
#{
var db = Database.Open("events");
var result = db.Query("SELECT * FROM events");
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
and then in another page in which you want to display the calendar you could configure it:
$(document).ready(function() {
$('#calendar').fullCalendar({
theme: true,
header: {
left: '',
center: '',
right: ''
},
defaultView: 'agendaDay',
editable: false,
events: '/events.cshtml'
});
});
UPDATE: Here's an example of how you could use parametrized queries:
#{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var fromDate = origin.AddSeconds(int.Parse(Request["start"]));
var toDate = origin.AddSeconds(int.Parse(Request["end"]));
var db = Database.Open("events");
var sql = "SELECT * FROM events WHERE start >= #0 AND end <= #1";
var result = db.Query(sql, fromDate, toDate);
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
Now you could query the page like this: /events.cshtml?start=5&end=10
DECLARE #listCol VARCHAR(2000)
DECLARE #query VARCHAR(4000)
SELECT #listCol = STUFF(( SELECT distinct '], [' + [PSize]
FROM Pattern
FOR
XML PATH('')
), 1, 2, '') + ']'
SET #query = 'SELECT * FROM
(SELECT PColour as Colour_Size_Matrix, PSize, PCode
FROM Pattern
) src
PIVOT (Count(PCode) FOR PSize
IN (' + #listCol + ')) AS pvt'
EXECUTE ( #query )
I want the result of this query as JSON