How to Assign variable? - angularjs

I don't know how to assign value return from stored procedure into web api? how to pass variables througn angulrjs
I called serivice
var promisePost = crudService.candidatePost(Candidates);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
}, function (err) {
alert("NOt Inserted")
});
my app.js is
MyApp.service('crudService', function ($http, RESOURCES) {
this.candidatePost = function (Candidate) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCandidate",
data: Candidate
});
return request;
}
});
my controller is
[HttpPost]
[Route("api/saveCandidate")]
public HttpResponseMessage AddDetail(Candidate ct)
{
SqlConnection con = new SqlConnection(Constant.ConnectionString);
SqlCommand cmd = new SqlCommand();
int rowInserted = 0;
try
{
cmd = new SqlCommand("sp_Insert_tblCandidate", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", ct.Name);
cmd.Parameters.AddWithValue("#Gender", ct.Gender);
cmd.Parameters.AddWithValue("#Dob", ct.Dob);
cmd.Parameters.AddWithValue("#Mob", ct.Mob);
cmd.Parameters.AddWithValue("#EntryDate", ct.EntryDate);
cmd.Parameters.AddWithValue("#Note", ct.Note);
cmd.Parameters.AddWithValue("#Emial", ct.Emial);
cmd.Parameters.AddWithValue("#Address", ct.Address);
rowInserted = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception obj)
{
if (rowInserted != 1)
{
var message = obj.Message;// string.Format("Insertion Of Data is not Succefully Executed");
HttpError err = new HttpError();
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
var alertmessage = string.Format("Insertion Of Data is Succefully Executed");
return Request.CreateResponse(HttpStatusCode.OK, alertmessage);
}
My stored Procedure is
IF EXISTS ( SELECT *
FROM sysobjects
WHERE id = object_id(N'[dbo].[sp_Insert_tblCandidate]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
DROP PROCEDURE [dbo].[sp_Insert_tblCandidate]
END
GO
Create procedure [dbo].[sp_Insert_tblCandidate]
(#Name varchar(50) ,
#Gender char(1),
#dob varchar(25),
#Mob varchar(15),
#EntryDate varchar(50),
#Note varchar(100),
#Emial varchar(50),
#Address varchar(50)
)As
Begin
INSERT INTO [dbo].[tblCandidate] VALUES (#Name,#Gender,#dob,#Mob,#EntryDate,#Note,#Emial,#Address);
SELECT SCOPE_IDENTITY() as CandidateId;
end
GO
My stored procedure purpose is insert data & return last inserted id. In this table id set to auto increment.Anyone can help me?

You are returning the new Id so you shouldn't be using
cmd.ExecuteNonQuery()
But something that can handle the return value. Try changing it to
rowInserted = (int) cmd.ExecuteScalar();
Also right now you are checking in the catch the rowInserted which doesn't makes much sense.

You cannot get a result from ExecuteNonQuery() as it only returns the number of rows affected for the query you just executed.
Since you are returning the SCOPE_IDENTITY(), you can either use ExecuteReader() or ExecuteScalar().
rowInserted = (int)cmd.ExecuteScalar();
or
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
rowInserted = Convert.ToInt32(rdr[0]);
}
}
But using SqlDataReader is kinda unnecessary in this scenario.
Plus, just an observation; be careful when choosing between SCOPE_IDENTITY(), ##IDENTITY and IDENT_CURRENT.

Related

How to retrieve SQL error message and display it with ASP.NET Core MVC?

I want to show my SQL Server error to the user. When a method returns a value there is no problem with this code.
But when there is no record I want to give an error message which gets retrieved from a reader.
Here is what I tried:
Controller:
public IActionResult Index()
{
//It works ok when there is a retrieved date
var expenses = context.GetAll(GetUserId());
//I think it`s like this. But it says there is a problem with view.
foreach (var item in expenses)
{
if (item.Error != null)
{
ViewBag.Error = item.Error;
return View();
}
}
return View(expenses);
}
I get this error:
System.ArgumentNullException: Value cannot be null.
Parameter name: source .
In my index view where I say:
#if (Model.Any())
{
html...
}
else
{
Viewbag.Error
}
C# method:
public IQueryable<Expenses> GetAll(string UserId)
{
List<Expenses> expenses = new List<Expenses>();
using (DALC.GetConnection())
{
DALC.Command("spGetUserExpenses");
DALC.cmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
using (SqlDataReader reader = DALC.cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Expenses entities = new Expenses
{
Id = Convert.ToInt32(reader["Id"]),
TotalAmount = Convert.ToDouble(reader["Amount"]),
Desription = reader["Notes"].ToString(),
Date = Convert.ToDateTime(reader["Date"]),
IsCash = Convert.ToBoolean(reader["IsCash"]),
IsCard = Convert.ToBoolean(reader["IsCard"])
};
expenses.Add(entities);
}
}
if (reader.NextResult())
{
reader.Read();
//setting second select statement which is an error by my side?
expenses.Add(new Expenses { Error = reader[0].ToString() });
}
}
}
return expenses.AsQueryable();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spGetUserExpenses]
#UserId nvarchar(450)
AS
BEGIN
SELECT
e.ID,
e.Amount,
e.Notes,
e.[Date],
e.IsCash,
e.IsCard
FROM
Expenses e
WHERE
UserId = #UserId
AND DATENAME(YEAR, CAST(e.[Date] AS varchar)) = DATENAME(YEAR, GETDATE())
AND DATENAME(MONTH, CAST(e.[Date] AS varchar)) = DATENAME(MONTH, GETDATE())
ORDER BY
e.ID DESC
IF (##ROWCOUNT = 0)
BEGIN
SELECT N'No Expense Found'
END
END
I prefer this way to select data from stored procedures, it works for me
connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand com = new SqlCommand("spGetUserExpenses", connection);
com.CommandType = CommandType.StoredProcedure;
//CARA 1
if (userid == null)
{
com.Parameters.AddWithValue("#UserId", DBNull.Value)
}
else
{
com.Parameters.AddWithValue("#UserId", UserId)
}
IDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Expenses entities = new Expenses()
{
Id = Convert.ToInt32(reader["Id"]),
TotalAmount = Convert.ToDouble(reader["Amount"]),
Desription = reader["Notes"].ToString(),
Date = Convert.ToDateTime(reader["Date"]),
IsCash = Convert.ToBoolean(reader["IsCash"]),
IsCard = Convert.ToBoolean(reader["IsCard"])
};
expenses.Add(entities);
}
reader.Close();
connection.Close();
return expenses;

Only first letter of particular data is getting saved in database in ASP.NET MVC

I'm pretty new to ASP.NET MVC so bear with me here.
I'm creating a Registration page using ASP.NET MVC 5 with SQL Server; whenever I fire my create action method, it only stores only the first letter of my data like if I enter "Stack" it will only store 'S'.
I'm posting my controller code here. Please help and thanks in advance.
Controller:
public ActionResult CreateUser()
{
return View(db.ClsUsers.Create());
}
[HttpPost]
public ActionResult CreateUser(FormCollection form, ClsUserReg userReg)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["CoupanCodeManagmentContext"].ConnectionString))
{
var cmd = new SqlCommand("SP_UserReg_Ins ", con);
cmd.CommandType = CommandType.StoredProcedure;
// cmd.Parameters.Add(new SqlParameter("#Id", SqlDbType.Int)).Value = userReg.Id;
cmd.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar)).Value = userReg.Name;
cmd.Parameters.Add(new SqlParameter("#Mobile", SqlDbType.NVarChar)).Value = userReg.Mobile;
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.NVarChar)).Value = userReg.Email;
cmd.Parameters.Add(new SqlParameter("#UserName", SqlDbType.NVarChar)).Value = userReg.UserName;
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.NVarChar)).Value = userReg.Password;
cmd.Parameters.Add(new SqlParameter("#ConfirmedPassword", SqlDbType.NVarChar)).Value = userReg.ConfirmedPassword;
try
{
if (con.State != ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
ModelState.Clear();
}
catch (Exception ex)
{
return View();
}
finally
{
if (con.State != ConnectionState.Closed)
con.Close();
}
return RedirectToAction("UsersList");
}
}
This is how it's getting saved
Check the couple of things
Mention the SqlParameter size manually by checking the columns size in SQL Server
You need to specify the size for NVARCHAR parameters in the stored procedure. If an nvarchar parameter does not have a size, it defaults to 1 character and will truncate the data that is passed to it. Refer more here
For example
ALTER PROCEDURE [dbo].[SP_UserReg_Ins]
(
#Name nvarchar(500) = null,
#Mobile nvarchar(500) = null,
#Email nvarchar(500) = null,
#UserName nvarchar(500) = null,
#Password nvarchar(500) = null,
#ConfirmPassword nvarchar(500) = null
)
AS
BEGIN
--INSERT Statement
END

SQL Server stored procedure waiting parameter

I have a SQL Server stored procedure:
exec GetBob #id=3
But when I call this stored procedure in a function, I get the error:
The procedure or function expects the #id parameter
But #id is the correct parameter (get value).
public List<Bob> GetBob(int id)
{
try
{
connection();
con.Open();
DynamicParameters param = new DynamicParameters();
param.Add("#id", id);
IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBob", param).ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}
Try this. You should be good. You need to provide command Type that it is Stored Procedure.
public List<Bob> GetBob(int id)
{
try
{
connection();
con.Open();
DynamicParameters param = new DynamicParameters();
param.Add("#id", id);
IList<Bob> EmpList = SqlMapper.Query<Bob>(
con, "GetBob",param,commandType: CommandType.StoredProcedure).ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}

How to mix executable and querieable SQL statements in Dapper

I Dapper I can execute some SQL that does not give a response using Execute:
var sql = #"INSERT INTO Items (id, userId, name, description, isPublic) VALUES (#id, #userId, #name, #description, #isPublic)";
using (var connection = new SqlConnection(ConnectionString))
{
connection.Execute(sql, new
{
id = value.Id,
userId = value.UserId,
name = value.Name,
description = value.Description,
isPublic = value.IsPublic
});
}
I can query using Query:
var sql = #"SELECT * FROM Items WHERE id = #id";
using (var connection = new SqlConnection(ConnectionString))
{
var item = connection.Query<Item>(sql, new { id = id }).Single();
return item;
}
Using [QueryMultiple]() I can simultaneously send several queries:
var sql = #"SELECT * FROM Collections WHERE id = #collectionId
SELECT * FROM Items WHERE id = #itemId";
using (var connection = new SqlConnection(ConnectionString))
{
var multi = connection.QueryMultiple(sql, new { collectionId = collectionId, itemId = itemId });
//...
How would I execute and query in one go? I.e. how would I call this combination:
var sql = #"INSERT INTO Items (id, userId, name, description, isPublic) VALUES (#id, #userId, #name, #description, #isPublic)
SELECT * FROM Items WHERE id = #itemId";"
It's pretty strait forward:
[TestFixture]
public class DapperTests
{
private SqlConnection _sqlConnection;
[SetUp]
public void Setup()
{
_sqlConnection = new SqlConnection(#"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=MyDb");
_sqlConnection.Open();
_sqlConnection.Execute(#"IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'temp'))
BEGIN
create table temp
(
Id int IDENTITY(1,1),
Value varchar(10)
)
END");
}
[TearDown]
public void Teardown()
{
_sqlConnection.Close();
}
[Test]
public void Test_Basic_Insert_Select()
{
var result = _sqlConnection.Query<int>("SELECT #value as Id into #temp; select Id from #temp where Id = #value", new { value = 1 }).Single();
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void Test_Basic_Insert_Select_QueryMultiple()
{
var result = _sqlConnection.QueryMultiple("insert into temp(Value) select #value; select 1 as foo; select 'bar' as bar", new { value = 1 });
var id = result.Read<int>().Single();
var bar = result.Read<string>().Single();
Assert.That(id, Is.EqualTo(1));
Assert.That(bar, Is.EqualTo("bar"));
}
[Test]
public void Test_Identity()
{
var result = _sqlConnection.Query<int>("insert into temp(Value) select #value ;select Id from temp where Id = (SELECT SCOPE_IDENTITY())", new { value = 1 });
Assert.That(result.Count(), Is.GreaterThan(0));
}
}

Executed Stored Procedure using Dapper

I am trying to execute a stored procedure using Dapper but I get two types of errors:
Error parsing column 9 (fTaxInvoiceNumber=INV0000000028PPN - String)
Object reference not set to an instance of an object
Here is the code to execute the stored procedure:
SqlConnection db = new SqlConnection(ConnectionFactory.ConnectionString("RebateSystem"));
db.Open();
try
{
var result = db.Query<PracticeRebateOrders>("GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
db.Close();
db.Dispose();
return result;
}
catch (Exception ex)
{
throw;
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[GetPracticeRebateOrderByInvoiceNumber]
#TaxInvoiceNumber NVARCHAR(20)
AS
BEGIN
SELECT TOP(1)
[fPracticeRebateOrdersID]
,[fPracticeID]
,[fPracticeUserID]
,[fCreatedDate]
,[fInvoiceInCredits]
,[fPurchaseDate]
,[fPracticeRebateOrderStatusID]
,[fRebatePaymentRunID]
,[fRebateBatchID]
,[fTaxInvoiceNumber]
FROM
[PracticeRebateSystem].[dbo].[PracticeRebateOrders]
WHERE
fTaxInvoiceNumber = #TaxInvoiceNumber
END
Not really an answer, but based on the code available in the question and in the comments I have this... which works fine and successfully...
public void SO24605346_ProcsAndStrings()
{
connection.Execute(#"create proc #GetPracticeRebateOrderByInvoiceNumber #TaxInvoiceNumber nvarchar(20) as
select #TaxInvoiceNumber as [fTaxInvoiceNumber]");
string InvoiceNumber = "INV0000000028PPN";
var result = connection.Query<PracticeRebateOrders>("#GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
result.TaxInvoiceNumber.IsEqualTo("INV0000000028PPN");
}
class PracticeRebateOrders
{
public string fTaxInvoiceNumber;
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TaxInvoiceNumber { get { return fTaxInvoiceNumber; } set { fTaxInvoiceNumber = value; } }
}
I'm happy to help, but I cannot reproduce an issue. Looks fine here.

Resources