I want to pass and add data to the web service through a desktop program by stored procedure in SQL Server.
Stored procedure
ALTER PROCEDURE [dbo].[insert_user]
(#code nvarchar(50),
#codeuser nvarchar(50),
#pictureuser image,
#nameshop nvarchar(50),
#country nvarchar(50),
#addressuser nvarchar(50),
#telephone nvarchar(20),
#passworact nvarchar(20),
#dateregist date,
#active bit)
AS
INSERT INTO user_tb (code, codeuser, pictureuser, nameshop,
country, addressuser, telephone, passworact, dateregist, active)
VALUES (#code, #codeuser, #pictureuser, #nameshop,
#country, #addressuser, #telephone, #passworact, #dateregist, #active)
Web service add
[WebMethod]
public int Insertregester(string code, string codeuser, byte pictureuser, string nameshop, string country, string addressuser, string telephone, string passworact, DateTime dateregist, Boolean active)
{
int retRecord = 0;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("insert_user", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#code", SqlDbType.NVarChar).Value = code;
cmd.Parameters.Add("#codeuser", SqlDbType.NVarChar).Value = codeuser;
cmd.Parameters.Add("#pictureuser", SqlDbType.Image).Value = pictureuser;
cmd.Parameters.Add("#nameshop", SqlDbType.NVarChar).Value = nameshop;
cmd.Parameters.Add("#country", SqlDbType.NVarChar).Value = country;
cmd.Parameters.Add("#addressuser", SqlDbType.NVarChar).Value = addressuser;
cmd.Parameters.Add("#telephone", SqlDbType.NVarChar).Value = telephone;
cmd.Parameters.Add("#passworact", SqlDbType.NVarChar).Value = passworact;
cmd.Parameters.Add("#dateregist", SqlDbType.Date).Value = dateregist.ToShortDateString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = active;
if (con.State != ConnectionState.Open)
{
con.Open();
}
retRecord = cmd.ExecuteNonQuery();
}
}
return retRecord
}
Call service code in windows app
Servicea.WebServiceSoapClient _service = new WindowsForm_webservice.Servicea.WebServiceSoapClient();
This is the first time I have used the service.
My attempt:
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
_service.Insertregester(("22"), ("4578"), (photo_aray), (TEXT_NAME.Text), (TEXT_ADDRESS.Text), (TEXT_ADDRESS.Text), (TEXT_TEL.Text), (TEXT_PASSWO.Text),(DATE_PICK.Value.ToShortDateString),(true));
I get this error:
Related
I ran into a problem for which I couldn't find a solution in existing similarly asked questions. The problem is that I have the following stored procedure:
ALTER PROCEDURE SP_EditCustomer #ID int, #Name NVarchar(100), #Email Nvarchar(200), #Contact bigint,
#Address NVarchar(350), #About NVarChar(350), #Image image = null
AS
if(#Image is null)
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email
WHERE ClientID = #ID;
End
Else
Begin
UPDATE clientTable
SET ClientName = #Name, Contact= #Contact, Address = #Address, About = #About, Email = #Email,
Photo = #Image
WHERE ClientID = #ID;
End
I have set the #image parameter to be null as default but whenever I connect to SQL Server with the following code in C# winforms:
// Inserting image into DB
byte[] img = null;
if (imgLoc != null && imgLoc != "")
{
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
}
else
{
img = null;
}
//Connecting to Database
cmd = conString.CreateCommand();
cmd.CommandText = "Exec SP_EditCustomer #ID, #Name, #Email, #Contact, #Address, #About, #Image";
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(txtEditByID.Text);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value = txtFullName.Text.ToString();
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 200).Value = txtEmail.Text.ToString();
cmd.Parameters.Add("#Contact", SqlDbType.BigInt).Value = txtContact.Text;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 350).Value = txtAddress.Text.ToString();
cmd.Parameters.Add("#About", SqlDbType.NVarChar, 350).Value = txtAbout.Text.ToString();
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
conString.Open();
cmd.ExecuteNonQuery();
conString.Close();
I get this error:
The parameterized query '(#ID int,#Name nvarchar(100),#Email nvarchar(200),#Contact bigin' expects the parameter '#Image', which was not supplied.
Although if no new image is selected then the existing image shouldn't change (and for this purpose I have passed null but still I get the error above).
Thanks to #DaleK for suggesting the DBNull.Value.
I have solved it with his suggestion by adding the following lines:
if(img!=null)
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = img;
else
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = DBNull.Value;
I'm trying to add a new user to table using a SQL Server stored procedure, but it's not being added, and it does not shows any errors, either.
C# code:
public void ADD_USER(string firstname, string lastname, string username, string password, string birthdate, string shiftstart, string shiftend, string ssn, string address, int salary, byte[] id_image, byte[] avatar)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#USERNAME", SqlDbType.VarChar,100);
param[0].Value = username;
param[1] = new SqlParameter("#PASSWORD", SqlDbType.VarChar, 100);
param[1].Value = password;
param[2] = new SqlParameter("#FIRSTNAME", SqlDbType.VarChar, 100);
param[2].Value = firstname;
param[3] = new SqlParameter("#LASTNAME", SqlDbType.VarChar, 100);
param[3].Value = lastname ;
param[4] = new SqlParameter("#BIRTHDATE", SqlDbType.Date);
param[4].Value = birthdate;
param[5] = new SqlParameter("#ADDRESS", SqlDbType.VarChar, 100);
param[5].Value = address;
param[6] = new SqlParameter("#SSN", SqlDbType.Int);
param[6].Value = ssn;
param[7] = new SqlParameter("#SHIFTSTART", SqlDbType.Time);
param[7].Value = shiftstart;
param[8] = new SqlParameter("#SHIFTEND", SqlDbType.Time);
param[8].Value = shiftend;
param[9] = new SqlParameter("#SALARY", SqlDbType.Int);
param[9].Value = salary;
param[10] = new SqlParameter("#ID_IMAGE", SqlDbType.Image);
param[10].Value = id_image;
param[11] = new SqlParameter("#AVATAR", SqlDbType.Image);
param[11].Value = avatar;
try
{
DAL.executeCommand("ADD_USER", param);
}
catch (SqlException ex)
{
Console.Write(ex.Message);
}
DAL.close();
}
Stored procedure code:
CREATE PROC ADD_USER
#USERNAME VARCHAR(100),
#PASSWORD VARCHAR(100),
#FIRSTNAME VARCHAR(100),
#LASTNAME VARCHAR(100),
#BIRTHDATE VARCHAR(100),
#ADDRESS VARCHAR(100),
#SSN INT,
#ID_IMAGE IMAGE,
#AVATAR IMAGE,
#SHIFTSTART VARCHAR(100),
#SHIFTEND VARCHAR(100),
#SALARY INT
AS
INSERT INTO [CAFE].[dbo].[users] ([username], [password],
[firstname], [lastname], [SSN],
[id_image], [avatar],
[start_working], [shift_start], [shift_end],
[salary], [birth_date], [address])
VALUES (#USERNAME, #PASSWORD,
#FIRSTNAME, #LASTNAME, #SSN,
#ID_IMAGE, #AVATAR,
CONVERT(DATE, GETDATE()), #SHIFTSTART, #SHIFTEND,
#SALARY, #BIRTHDATE, #ADDRESS)
The stored procedure works fine on SQL Server itself, but doesn't add any records from C# code
I tried to trace this issue but I didn't get a result.
I'm using SQL Server 2008 R2 And Visual Studio 2015
I have 2 tables
tbl_orgs:
tbl_orgs
and tbl_location_records:
tbl_location_records
I am using a stored procedure to insert data into these tables.
Insert Organization
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp])
VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT
orgID, orgName, orgCity, orgArea, orgTel, orgEmail, orgType,
orgStatus, strOwner, db_tstamp
FROM
tbl_orgs
WHERE
(orgID = SCOPE_IDENTITY())
Insert Location Record
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsLoc]
(#userID int,
#orgID int,
#jobID int,
#strLat numeric(18, 0),
#strLong numeric(18, 0),
#strOwner varchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_location_records] ([userID], [orgID], [jobID], [strLat], [strLong], [strOwner], [db_tstamp])
VALUES (#userID, #orgID, #jobID, #strLat, #strLong, #strOwner, #db_tstamp);
SELECT
recordID, userID, orgID, jobID, strLat, strLong, strOwner, db_tstamp
FROM
tbl_location_records
WHERE
(recordID = SCOPE_IDENTITY())
I want to use single form to add inserted organization's location record once organization record successfully inserted.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["IBS_3"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
cmdloc.Parameters.Add("orgID", SqlDbType.Int).Value =
}
}
Trying to get some understanding from this link but I m clueless on this..
Inserting to one table, insert the ID to second table
Any help appreciated.
Thanks.
Add output parameter to the first stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(
#orgID int output,
#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2
)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp]) VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT #orgID = SCOPE_IDENTITY()
add output param to command..
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
var outParam = cmd.Parameters.Add("#orgID", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("#orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("#orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("#orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("#orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("#orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
var orgId = (int)outParam.Value;
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
}
I have a questionnaire which stores answers for each user who does the test. I need to store the output in the database (which is the user doing the test.) I'm not quite sure what i am doing wrong. Currently my inputID returns 0. (InputAnswers inputs the test answers for that user to database)
CREATE PROCEDURE [dbo].[InputAnswers]
#QuestionID int,
#InputID int OUTPUT,
#Answer nchar,
#Remark nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Answers (InputID, QuestionID, Answer, Remark) VALUES (#InputID, #QuestionID, #Answer, #Remark)
END
The code below loads the answers from the list view which holds the questions:
private void LoadAnswers(int inputID)
{
foreach (StepControl step in dckSteps.Children)
{
foreach (QuestionControl quest in step.listQuestions.Items)
{
int questionID = quest.questionID;
string answer = quest.answer;
string remark = quest.txtRemark.Text;
SqlConnection conDatabase = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
string query = "InputAnswers";
SqlCommand cmd = new SqlCommand(query, conDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = inputID;
cmd.Parameters.Add("#QuestionID", SqlDbType.Int).Value = questionID;
cmd.Parameters.Add("#Answer", SqlDbType.NChar).Value = answer;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = remark;
conDatabase.Open();
cmd.ExecuteNonQuery();
conDatabase.Close();
}
}
}
I then load these answers into the button click method:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
string name = txtName.Text;
string cno = txtCNO.Text;
var date = datePicker.SelectedDate;
int inputID = 0;
SqlConnection conDatabase = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
string query = "SaveInput";
SqlCommand cmd = new SqlCommand(query, conDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = ParameterDirection.Output;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#CNO", SqlDbType.NVarChar).Value = cno;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
conDatabase.Open();
cmd.ExecuteNonQuery();
conDatabase.Close();
LoadAnswers(inputID);
}
This all works correctly apart from sending the OUTPUT back to the database. Any ideas?
EDIT: The procedure SaveInput looks like this: (SaveInput stores the user info)
CREATE PROCEDURE [dbo].[SaveInput]
#InputID int OUTPUT,
#Name nvarchar(50),
#CNO nvarchar(50),
#Date DATETIME
AS
BEGIN
SET NOCOUNT ON;
IF(#InputID = 0)
BEGIN
INSERT INTO Input (Name, CNO, Date) VALUES (#Name, #CNO, #Date)
SET #InputID = ##IDENTITY
END
ELSE
BEGIN
UPDATE Input SET Name = #Name,
CNO = #CNO,
Date = #Date
WHERE InputID = #InputID
END
END
I have a feeling i don't need to use OUTPUT on both procedures.
This is at least part of the problem:
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = ParameterDirection.Output;
That's creating an input parameter - but giving it a value which is the enum value ParameterDirection.Output. You want:
cmd.Parameters.Add("#InputID", SqlDbType.Int).Direction = ParameterDirection.Output;
You then need to fetch the result from the parameter after executing the command:
cmd.ExecuteNonQuery();
// You might want to store the parameter reference in a local variable instead
// of fetching it again afterwards.
int inputId = (int) cmd.Parameters["#InputID"].Value;
If you want the parameter to be input/output though, you should be using ParameterDirection.InputOutput (and giving it a value before executing the command). For example:
int inputId = ...;
var inputIdParameter = cmd.Parameters.Add("#InputID", SqlDbType.Int);
inputIdParameter.Direction = ParameterDirection.InputOutput;
inputIdParameter.Value = inputId;
...
cmd.ExecuteNonQuery();
inputId = (int) inputIdParameter.Value;
I want to know what (if any) is wrong with the below stored procedure for updating address:
I have also given my database image to get a clear idea....
ALTER PROCEDURE [dbo].[usp_UpdateAddress]
(#OriginalEmail nvarchar(50), #FirstName varchar(50), #LastName varchar(50),
#Country_ID int, #AddressLine1 varchar(50), #AddressLine2 varchar(50),
#AddressLine3 varchar(50), #Telephone varchar(50), #Email nvarchar(50),
#City varchar(50), #State_ID int, #PostalCode varchar(50), #Mobile varchar(50))
AS
BEGIN
DECLARE #User_ID INT
SELECT #User_ID = ID FROM AUser Where Email = #OriginalEmail
UPDATE [AUserAddress]
SET [AUser_ID] = #User_ID, [FirstName] = #FirstName, [LastName] = #LastName,
[Country_ID] = #Country_ID, [AddressLine1] = #AddressLine1,
[AddressLine2] = #AddressLine2, [AddressLine3] = #AddressLine3,
[Telephone] = #Telephone, [Email] = #Email, [City] = #City,
[State_ID] = #State_ID, [PostalCode] = #PostalCode, [Mobile] = #Mobile
WHERE
Email = #OriginalEmail
END
Called from C#:
private void UpdateAddress()
{
try
{
string strSession = objGetSession.GetEmailFromSession();
con.Open();
SqlCommand sqlCmd = new SqlCommand("usp_UpdateAddress", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#OriginalEmail ", SqlDbType.NVarChar, 50).Value = strSession;
sqlCmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
sqlCmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
sqlCmd.Parameters.Add("#AddressLine1", SqlDbType.VarChar, 50).Value = txtAddressLine1.Text;
sqlCmd.Parameters.Add("#AddressLine2", SqlDbType.VarChar, 50).Value = txtAddressLine2.Text;
sqlCmd.Parameters.Add("#AddressLine3", SqlDbType.VarChar, 50).Value = txtAddressLine3.Text;
sqlCmd.Parameters.Add("#Telephone", SqlDbType.VarChar, 50).Value = txtTelephone.Text;
sqlCmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = txtEmailAddress.Text;
sqlCmd.Parameters.Add("#Country_ID", SqlDbType.Int).Value = ddlCountry.SelectedItem.Value;
sqlCmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = txtCity.Text;
sqlCmd.Parameters.Add("#State_ID", SqlDbType.Int).Value = ddlState.SelectedValue.ToString();
sqlCmd.Parameters.Add("#PostalCode", SqlDbType.VarChar, 50).Value = txtPostalCode.Text;
sqlCmd.Parameters.Add("#Mobile", SqlDbType.VarChar, 50).Value = txtMobile.Text;
sqlCmd.Connection = con;
sqlCmd.ExecuteNonQuery();
con.Close();
mpeTest.Show();
Response.Write("<script> alert('Address Updated!') </script>");
}
catch (Exception e)
{
Response.Write("An Error Occurred" + e);
}
}
Is the stored procedure not executing? Debugging shows that in Update Address() it does take the new value but when execution is completed, the database is not updated...
What if you UPDATE it directly by joining the tables?
UPDATE a
SET a.[auser_id] = b.ID,
a.[firstname] = #FirstName,
a.[lastname] = #LastName,
a.[country_id] = #Country_ID,
a.[addressline1] = #AddressLine1,
a.[addressline2] = #AddressLine2,
a.[addressline3] = #AddressLine3,
a.[telephone] = #Telephone,
a.[email] = #Email,
a.[city] = #City,
a.[state_id] = #State_ID,
a.[postalcode] = #PostalCode,
a.[mobile] = #Mobile
FROM [auseraddress] a
INNER JOIN AUser b
ON a.Email = b.Email
WHERE b.email = #OriginalEmail
Your stored procedure is wrong.
According to your image the AUserAddress tables does not contain a column called Email.