I have a T-SQL stored procedure in a SQL Server 2008 database that I am calling from some C# code. The stored procedure is as follows:
ALTER PROCEDURE [dbo].[spDeleteActivityFromUserProfile](
@profile_id int,
@user_id nvarchar(50),
@activity_name nvarchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
-- statements for procedure here
DECLARE @profiles_xml xml
SET @profiles_xml = (SELECT profiles from tbl_applied_profiles WHERE profiles.value('(Profile/ID)[1]','int')= @profile_id)
SET @dprofiles_xml.modify('
delete /Profile/User[ID = sql:variable("@user_id")]/Activities/Activity[Name=sql:variable("@activity_name")]
')
UPDATE tbl_applied_profiles
SET profiles = @profiles_xml
WHERE profiles.value('(Profile/ID)[1]','int')= @profile_id
END
An example of the XML entries from the table, such as would be contained in @profiles_xml would be :
<Profile>
<ID>20</ID>
<User>
<ID>BC4A18CA-AFB5-4268-BDA9-C990DAFE7783</ID>
<Name>somename</Name>
<Activities>
<Activity>
<Name>activity1</Name>
</Activity>
</Activities>
</User>
</Profile>
This stored procedure functions as expected when I execute it in the the SQL Server Management Studio, and deletes a specified element from the targeted xml. However When I try and call it from my C# code, I get the following error:
System.Data.SqlClient.SqlException: XML parsing: line 1, character 143,
illegal name character\r\n
I am calling it from my C# code as follows:
public Boolean DeleteServiceFromServerProfile(int profileID, String userID, String activityName)
{
try
{
SqlCommand com = odbchelper.SQLConnection.CreateCommand();
com.CommandText = "spDeleteActivityFromUserProfile";
/*add command parameters*/
SqlParameter paramProfileID = new SqlParameter("@profile_id", profileID);
com.Parameters.Add(paramProfileID);
SqlParameter paramUserID = new SqlParameter("@user_id", userID);
com.Parameters.Add(paramuserID);
SqlParameter paramActivityName = new SqlParameter("@activity_name", activityName);
com.Parameters.Add(paramActivityName);
// execute query
com.ExecuteNonQuery();
return true;
}
catch(Exception ex)
{
sLastError = ex.ToString();
}
return false;
}
I am not sure how the \r\n (which is a system new line character) is getting injected into the command. Is there a way I can check for that and strip it out from either the command in the C# or from the parameters within the stored procedure itself?
The issue was caused because I had not set the command type of the SqlCommand. I added this line and it fixed the problem:
com.CommandType = CommandType.StoredProcedure;