Need help in stored procedure view data - stored-procedures

Somebody please help me by modying this code.when i retrieve the Login value through stored procedure call, i am getting this error message "Procedure or function 'GetUserLogin' expects parameter '#UserName', which was not supplied."
Here is my code:
public int GetLogin(string UserName, string Password)
{
SqlConnection con = new SqlConnection(str);
SqlDataAdapter da = new SqlDataAdapter("GetUserLogin", con);
SqlCommand com = new SqlCommand("GetUserLogin",con);
com.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
if ((ds.Tables[0].Rows[0].ItemArray[1].ToString() == UserName) && (ds.Tables[0].Rows[0].ItemArray[2].ToString() == Password))
{
return 1;
}
else
{
return 0;
}
}
else
{
return -1;
}
StoredProcedure:
CREATE PROCEDURE GetUserLogin #UserName varchar(50)
AS
select UserName,
Password
From Login where UserName=#UserName
RETURN
Thanks,
Masum

You need to add a UserName parameter to your command. Do something like this after you create your command, but before you execute it:
com.Parameters.Add("#UserName", SqlDbType.VarChar, 50);
com.Parameters["#UserName"].Value = UserName;

Add this before you fill the dataset
cmd.Parameters.AddWithValue("UserName",UserName);

Related

am working on updating a single attribute in the User Model which is the balance attribute,

how I can update a single value for an already existing row in the db by only having a parameters that I want to add it to this attribute
here is my code for a trivial way but didnt work
public bool BuyBook(int BookId, int UserId, int BookPrice){
using (var ctx = new OnlineBooksEntities())
{
User updatedCustomer = (from c in ctx.Users
where c.UserId == UserId
select c).FirstOrDefault();
updatedCustomer.Balance = BookPrice;
ctx.SaveChanges();
}
this.DeleteBook(BookId);
return true;
}
Add an sql query to the method solves the update aim
public bool BuyBook(int BookId, int UserId, int BookPrice)
{
try
{
using (var ctx = new OnlineBooksEntities())
{
User user = ctx.Users.Where(x => x.UserId == UserId).FirstOrDefault();
BookPrice = (int)user.Balance + BookPrice;
int noOfRowUpdated =
ctx.Database.ExecuteSqlCommand("Update Users set Balance = "+BookPrice+ " where UserId ="+UserId);
}
Updating basically means changing an existing row's value. Since you mentioned EF, you can do this by retrieving the object, changing its value, and saving it back. Thus you can do something like this:
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookPrice == bookPrice);
if (result != null)
{
result.SomeValue = "Your new value here";
db.SaveChanges();
}
}

Parameter missing at ExecuteNonQuery with stored procedure in ASP.NET MVC

Below is my code and I get an error at ExecuteNonQuery:
#Name parameter missing.
I have tried many time and even no error during building of program. The stored procedure contains an insert statement with 4 parameters, 3 of varchar type and one integer type as the primary key.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace CompanyMaster
{
public class Master
{
public IEnumerable<Company> Companies
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Company> companies = new List<Company>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetAllCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Company company = new Company();
company.CompanyCode = Convert.ToInt32(rdr["CompanyCode"]);
company.CompanyName = rdr["CompanyName"].ToString();
company.CompanyAddress = rdr["CompanyAddress"].ToString();
company.CompanyMail = rdr["CompanyMail"].ToString();
companies.Add(company);
}
}
return companies;
}
}
public void Addcompany(Company company)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spAddCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
SqlParameter paramCode = new SqlParameter();
paramCode.ParameterName = "#Code";
paramCode.Value = company.CompanyCode;
cmd.Parameters.Add(paramCode);
SqlParameter PName = new SqlParameter("#Name", SqlDbType.VarChar, 50);
//PName.ParameterName = "#Name";
PName.Value = company.CompanyName;
cmd.Parameters.Add(PName);
SqlParameter paramAddress = new SqlParameter();
paramAddress.ParameterName = "#Address";
paramAddress.Value = company.CompanyAddress;
cmd.Parameters.Add(paramAddress);
SqlParameter paramMail = new SqlParameter();
paramMail.ParameterName = "#Mail";
paramMail.Value = company.CompanyMail;
cmd.Parameters.Add(paramMail);
con.Open();
cmd.ExecuteNonQuery();-- error is occurring here
}
}
}
}
Here is my stored procedure:
CREATE PROCEDURE spAddCompany
#Code INT,
#Name NVARCHAR(50),
#Address NVARCHAR(60),
#Mail NVARCHAR(50)
AS
BEGIN
INSERT INTO CompanyMaster (CompanyCode, CompanyName, CompanyAddress, CompanyMail)
VALUES (#Code, #Name, #Address, #Mail)
END
#Name parameter is missing when the code reaches ExecuteNonQuery.
I think your problem has to do with null vs DBNull.Value.
Check if company.CompanyName is null (in c#). If it is, you should pass DBNull.Value instead.
For more information on the difference between the two, read What is the difference between null and System.DBNull.Value?
From Configuring Parameters and Parameter Data Types:
Note
When you send a null parameter value to the server, you must specify DBNull, not null (Nothing in Visual Basic). The null value in the system is an empty object that has no value. DBNull is used to represent null values. For more information about database nulls, see Handling Null Values.
Also, You can add parameters to the command and set their values in a single line of code, like this:
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = company.CompanyName;
This will make your code much shorter and more readable.
Here are the changes I've made to your code that I think should solve your problem:
public void Addcompany(Company company)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
// SqlCommand also implements the IDisposable interface
using(var cmd = new SqlCommand("spAddCompany", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Code", SqlDbType.Int).Value = company.CompanyCode;
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = company.CompanyName as object ?? (object)DBNull.Value;
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = company.CompanyAddress as object ?? (object)DBNull.Value;
cmd.Parameters.Add("#Mail", SqlDbType.VarChar, 50).Value = company.CompanyMail as object ?? (object)DBNull.Value;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Note the use of the null coalescing operator (??) and the casting to object.

ASP.NET Stored Procedure Call insert VarBinary into sql

I have a string that is data bytes base64EncodedString from iOS which is an extremely long string
let imageStr = imageData.base64EncodedString()
I am calling a .NET Method from my ios that will call a stored procedure to insert these bytes into the database.
Here is my .NET Method, I have the data type set to VarBinary
public string PostLandGradingImages(List<Images> landingCells)
{
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("PostLandGradingImages", connection))
{
command.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < landingCells.Count; i++)
{
command.Parameters.Clear();
SqlParameter parameter1 = new SqlParameter("#Job_No", SqlDbType.VarChar);
parameter1.Value = landingCells[i].jobNo;
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
SqlParameter parameter2 = new SqlParameter("#Image", SqlDbType.VarBinary);
parameter2.Value = landingCells[i].imageBytes;
parameter2.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter2);
command.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
return e.Message.ToString();
}
return "All Good";
}
Here is my Image Class, notice my imageBytes is defined as a byte[]:
public class Images
{
public string jobNo { get; set; }
public byte[] imageBytes { get; set; }
}
The column I am inserting into is defined as varbinary(MAX)
and here is my stored procedure:
ALTER PROCEDURE [dbo].[PostLandGradingImages]
-- Add the parameters for the stored procedure here
#Job_No varchar(MAX) = NULL,
#Image varbinary(MAX) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO LandGradingImages (Job_No, ImageBytes) VALUES (#Job_No, #Image)
END
My problem is nothing is getting inserted, I am getting this error in my catch:
Object reference not set to an instance of an object.
My question is, what am I doing wrong? Should I not be sending base64EncodedString or am I not setting my class right? or my db column?
I tried this:
byte[] bytes = System.Convert.FromBase64String(landingCells[i].imageBytes);
SqlParameter parameter2 = new SqlParameter("#Image", SqlDbType.VarBinary, 800000);
parameter2.Value = bytes;
parameter2.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter2);
Still does not work :( and I changed imageBytes to string.
I modified your code a little to the method below. It creates a new CommandType.StoredProcedure for every Image. Also the results are returned per image, so you can see which ones failed. In your method, if you have 10 images, and the 9th failed, you would not know that.
public List<Images> PostLandGradingImages(List<Images> landingCells)
{
//create a connection to the database
using (SqlConnection connection = new SqlConnection(Common.connectionString))
{
//loop all the images
for (int i = 0; i < landingCells.Count; i++)
{
//create a fresh sql command for every Image
using (SqlCommand command = new SqlCommand("PostLandGradingImages", connection))
{
command.CommandType = CommandType.StoredProcedure;
//add the parameters
command.Parameters.Add("#Job_No", SqlDbType.VarChar).Value = landingCells[i].jobNo;
command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = landingCells[i].imageBytes;
try
{
//open the connection if closed
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
//execute the stored procedure
command.ExecuteNonQuery();
//set the save result to the image
landingCells[i].saveResult = true;
}
catch (Exception ex)
{
//handle error per Image
landingCells[i].errorMessage = ex.Message;
}
}
}
}
return landingCells;
}
In order to track the save result per image I've added two properties to the Image class, but this can be done in various other ways as well.
public class Images
{
public string jobNo { get; set; }
public byte[] imageBytes { get; set; }
public bool saveResult { get; set; }
public string errorMessage { get; set; }
}
A simple test was done with the following code. None of them gave a NullReference Error. Even with both properties being null, a database entry was still made.
//create a new list with Images
List<Images> landingCells = new List<Images>();
//add some dummy data
landingCells.Add(new Images() { jobNo = null, imageBytes = null });
landingCells.Add(new Images() { jobNo = "Job 1", imageBytes = null });
landingCells.Add(new Images() { jobNo = null, imageBytes = new byte[10000] });
landingCells.Add(new Images() { jobNo = "Job 2", imageBytes = new byte[10000] });
//send the images to be saved
landingCells = PostLandGradingImages(landingCells);
//loop all the images to check the result
for (int i = 0; i < landingCells.Count; i++)
{
if (landingCells[i].saveResult == false)
{
//display the result for each failed image
Label1.Text += landingCells[i].errorMessage + "<br>";
}
}
If there is still a NullReference error, that means that your List landingCells itself is null, or an Image object within that List is null (in which case it should never have been added to the List in the first place imho). You can change the snippet easily to check for that.
Consider batching the queries in a transaction. Also you should validate the values provided to the method to make sure that you can call the stored procedure correctly.
public int PostLandGradingImages(List<Images> landingCells) {
int count = 0;
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
//Transaction to batch the actions.
using (var transaction = connection.BeginTransaction()) {
foreach (var image in landingCells) {
if (valid(image)) {//validate input properties.
try {
using (SqlCommand command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "PostLandGradingImages";
command.Parameters
.Add("#Job_No", SqlDbType.VarChar, image.jobNo.Length)
.Value = image.jobNo;
command.Parameters
.Add("#Image", SqlDbType.VarBinary, image.imageBytes.Length)
.Value = image.imageBytes;
count += command.ExecuteNonQuery();
}
} catch {
//TODO: Log error
}
}
}
if (landingCells.Count == count) {
transaction.Commit();
}
}
}
return count;
}
private bool valid(Images image) {
return image != null && String.IsNullOrWhiteSpace(image.jobNo)
&& image.imageBytes != null && image.imageBytes.Length > 0;
}

Not Displaying Data

Can any one please help me for this.
public Dictionary<string,object> UserExistOrNot()
{
Dictionary<string, object> result = new Dictionary<string, object>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
string _userName = "user01";
string _password = "user";
string sqlQuery = "select * from [User] t0 inner join UserProfile t1 on t0.UserId=t1.UserId where t0.UserName='" + _userName + "' and t0.Password='" + _password+"'";
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "usertable");
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
result.Add("UserId", dr["UserId"]);
result.Add("UserName", dr["UserName"]);
result.Add("Password", dr["Password"]);
result.Add("Email", dr["Email"]);
result.Add("Mobile", dr["Mobile"]);
result.Add("Gender", dr["Gender"]);
result.Add("Street1", dr["Street1"]);
result.Add("Street2", dr["Street2"]);
result.Add("Street3", dr["Street3"]);
result.Add("Street4", dr["Street4"]);
result.Add("CityId", dr["CityId"]);
result.Add("StateId", dr["StateId"]);
result.Add("Country", dr["Country"]);
}
}
else
return result;
return result;
}
Output displaying like this:
System.Collections.Generic.Dictionary`2[System.String,System.Object]
I want to display the data instead of type
Browser understands pure text, xml or html, but not complex types, so you have to return one of those types, or create a view with model Dictionary and iterate throw keys and vslues to see it.

How to call aspnet_UsersInRoles_IsUserInRole Stored Procedure with Dapper ORM

I need to call aspnet_UsersInRoles_IsUserInRole from Aspnet Membership.Im making dapper call like this:
public int CheckIfUserIsInRole(IsUserInRole userInRole)
{
using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserName", userInRole.UserName);
param.Add("#ApplicationName", userInRole.ApplicationName);
param.Add("#RoleName", userInRole.RoleName);
return connection.Query("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
}
And in controller i add:
public int IsUserInRole(IsUserInRole isUserInRole)
{
var model = _userRepository.CheckIfUserIsInRole(new IsUserInRole()
{
UserName = "testuser",
RoleName = "user",
ApplicationName = "USERMANAGEMENT"
});
return model;
}
The user exist and have the correct role but every time returns 0.
Here is the Stored Procedure from AspNet Membership:
ALTER PROCEDURE [dbo].[aspnet_UsersInRoles_IsUserInRole]
#ApplicationName nvarchar(256),
#UserName nvarchar(256),
#RoleName nvarchar(256)
AS
BEGIN
DECLARE #ApplicationId uniqueidentifier
SELECT #ApplicationId = NULL
SELECT #ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(#ApplicationName) = LoweredApplicationName
IF (#ApplicationId IS NULL)
RETURN(2)
DECLARE #UserId uniqueidentifier
SELECT #UserId = NULL
DECLARE #RoleId uniqueidentifier
SELECT #RoleId = NULL
SELECT #UserId = UserId
FROM dbo.aspnet_Users
WHERE LoweredUserName = LOWER(#UserName) AND ApplicationId = #ApplicationId
IF (#UserId IS NULL)
RETURN(2)
SELECT #RoleId = RoleId
FROM dbo.aspnet_Roles
WHERE LoweredRoleName = LOWER(#RoleName) AND ApplicationId = #ApplicationId
IF (#RoleId IS NULL)
RETURN(3)
IF (EXISTS( SELECT * FROM dbo.aspnet_UsersInRoles WHERE UserId = #UserId AND RoleId = #RoleId))
RETURN(1)
ELSE
RETURN(0)
END
Where I'm mistaking?
Any advice how to fix it ?
I need this Stored Procedure to check if the user is in that role so i can use it for [AuthorizeRoles("RoleTest")]
That stored procedure doesn't return any records; it uses the return value instead. This needs to be handled as a parameter:
public int CheckIfUserIsInRole(IsUserInRole userInRole)
{
using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserName", userInRole.UserName);
param.Add("#ApplicationName", userInRole.ApplicationName);
param.Add("#RoleName", userInRole.RoleName);
param.Add("#ReturnValue", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
connection.Execute("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure);
return param.Get<int>("#ReturnValue");
}
}
https://github.com/StackExchange/dapper-dot-net#stored-procedures
(Also posted to your copy of this question on CodeProject.)

Resources