Why query doesn't work if the value is blank - asp.net

I have a query that executes in my C# code:
protected void btnSearch_Click(object sender, EventArgs e) {
Conn = new SqlConnection(cString);
Conn.Open();
theGender = slcGender.SelectedItem.Text;
if (slcLocation.SelectedItem.Value == "") {
locVal = slcLocation.SelectedItem.Value;
}
if (slcLocation.SelectedItem.Value != "") {
locVal = slcLocation.SelectedItem.Text;
}
if (slcSpecialty.SelectedItem.Value == "") {
speVal = slcSpecialty.SelectedItem.Value;
}
if (slcSpecialty.SelectedItem.Value != "") {
speVal = slcSpecialty.SelectedItem.Text;
}
if (slcGender.SelectedItem.Value == "") {
genVal = slcGender.SelectedItem.Value;
}
if (slcGender.SelectedItem.Value != "") {
genVal = theGender.Substring(0, 1);
}
sqlCode =
"DECLARE #strLocation varchar(200)
SET #strLocation = '" + locVal + "'
DECLARE #strSpecialty varchar(200)
SET #strSpecialty = '" + speVal + "'
DECLARE #strGender varchar(200)
SET #strGender = '" + genVal + "'
SELECT
[content_title] AS [Physician Name]
, CAST([content_html] AS XML).value('(root/Physicians/picture/img/#src)[1]','varchar(255)') AS [Image]
, dbo.usp_ClearHTMLTags(CONVERT(nvarchar(600), CAST([content_html] AS XML).query('root/Physicians/gender'))) AS [Gender]
, CAST([content_html] AS XML).query('/root/Physicians/OfficeLocations/office1/a') AS [Office1]
, CAST([content_html] AS XML).query('/root/Physicians/OfficeLocations/office2/a') AS [Office2]
, CAST([content_html] AS XML).query('/root/Physicians/OfficeLocations/office3/a') AS [Office3]
, CAST([content_html] AS XML).query('/root/Physicians/OfficeLocations/office4/a') AS [Office4]
, dbo.usp_ClearHTMLTags(CONVERT(nvarchar(600), CAST([content_html] AS XML).query('/root/Physicians/phone1'))) AS [Phone #]
FROM
[database].[dbo].[content]
WHERE
[folder_id] = '188'
AND
(content_html LIKE '%<gender>'+ #strGender+'</gender>%')
AND
(content_html LIKE '%'+#strSpecialty+'%')
AND
(content_html LIKE '%'+#strLocation+'%')
ORDER BY
[content_title]";
/* EXECUTE AND DISPLAY THE DATA IN THE ASP PAGE */
using(SqlCommand command = new SqlCommand(sqlCode, Conn)) {
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader()) {
if (reader.HasRows) {
rptContent.DataSource = reader;
rptContent.DataBind();
}
else {
dlo.InnerHtml = "NO RESULT";
}
}
}
}
The declaration are for three separate dropdownlist in my ASP.net page. I am having an issue where If I execute the query with the above code, no result will show up, although there should be about 5 results.
The three dropdownboxes are as follow:
The All Locations, All Specialties, Any Gender has value of "" which should makes the following code search for ALL, if I understand correctly?
(content_html LIKE '%<gender>'+ #strGender+'</gender>%')
AND
(content_html LIKE '%'+#strSpecialty+'%')
AND
(content_html LIKE '%'+#strLocation+'%')
The only time it works if I fill in the gender and/or location along with the specialty, before the query gives me anything back.
How do I resolve it?

If gender is missing, it is probably missing, so there are no <gender> delimiters. Perhaps this will fix the problem:
(#strGender = '' or (content_html LIKE '%<gender>'+ #strGender+'</gender>%')) . . .

Related

Conversion failed when converting the varchar to data type int: SQL

I am creating a web app in asp.net mvc I have a query which looks like below
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
var p = new DynamicParameters();
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
p.Add("#SP_UserId", userId, dbType: DbType.Int32, direction: ParameterDirection.Input);
var obj = conn.Query<PendingKmsRequest>(sql: "SELECT [f].[id] AS [FileId],[fvr].[Id] AS [RequestId], [au].[Name]"
+ ", [fvr].[RequestByUserId], [fvr].[FromDate], [fvr].[ToDate],[f].[Title], [fvr].[Status], [fvr].[StatusRemarks]"
+ "FROM [dbo].[File] AS[f]"
+ "INNER JOIN [dbo].[FileViewRequest] AS [fvr] ON [f].[CurrentFileVersionId] = [fvr].[FileVersionId]"
+ "INNER JOIN [Access].[User] AS [au] ON [fvr].[RequestByUserId] = [au].[Id]"
+ "WHERE ([fvr].[Status] = 'P' OR ([fvr].[Status] = 'A' AND [fvr].[StatusByUserId] = #SP_UserId AND GETDATE() BETWEEN [fvr].[FromDate] AND [fvr].[ToDate]))"
+ "AND (SELECT 1 FROM [Access].[UserRoleMap] WHERE UserId=#SP_UserId AND RoleId IN(#SP_RoleId)) = 1", param: p, commandType: CommandType.Text);
if (obj != null && obj.Count() > 0)
return obj.ToList();
else
return new List<PendingKmsRequest>();
}
NOTE: Role id is always like (7,8,9) and it is int column in the database.
I get this conversion error on this line of code:
WHERE UserId = #SP_UserId AND RoleId IN (#SP_RoleId))
This is the error:
Conversion failed when converting the nvarchar value '7,9,10' to data type int.
How can I prevent this error?
The following line in your question code:
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
The value "7,8,9" is string and parameter type DbType.String is string as well.
But, you said this is int in your database. This is mismatch.
Further, your query:
WHERE UserId = #SP_UserId AND RoleId IN (#SP_RoleId))
The query is using IN clause.
Dapper can convert your value for IN clause if pass in an IEnumerable.
Change the line of code as below:
p.Add("#SP_RoleId", new[] {7,8,9}, dbType: DbType.Int32, direction: ParameterDirection.Input);
No need to use convert string in array or any string split() function
If you have comma saperated string then you can check it like below steps,
If you have #SP_RoleId = "7, 8, 9"
You can convert this string as below
#SP_RoleId = ",7,8,9," ( ',' + ltrim(rtrim( #SP_RoleId )) + ',' )
Now use Like to check ,UserId,
Updated code as below,
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
var p = new DynamicParameters();
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
p.Add("#SP_UserId", userId, dbType: DbType.Int32, direction: ParameterDirection.Input);
var obj = conn.Query<PendingKmsRequest>(sql: "SELECT [f].[id] AS [FileId],[fvr].[Id] AS [RequestId], [au].[Name]"
+ ", [fvr].[RequestByUserId], [fvr].[FromDate], [fvr].[ToDate],[f].[Title], [fvr].[Status], [fvr].[StatusRemarks]"
+ "FROM [dbo].[File] AS[f]"
+ "INNER JOIN [dbo].[FileViewRequest] AS [fvr] ON [f].[CurrentFileVersionId] = [fvr].[FileVersionId]"
+ "INNER JOIN [Access].[User] AS [au] ON [fvr].[RequestByUserId] = [au].[Id]"
+ "WHERE ([fvr].[Status] = 'P' OR ([fvr].[Status] = 'A' AND [fvr].[StatusByUserId] = #SP_UserId AND GETDATE() BETWEEN [fvr].[FromDate] AND [fvr].[ToDate]))"
+ "AND (SELECT 1 FROM [Access].[UserRoleMap] WHERE ',' + lTrim(rTrim(#SP_RoleId)) + ',' like '%,' + lTrim(rTrim(UserId) + ',%' " // Updated line
+ "AND RoleId IN(#SP_RoleId)) = 1", param: p, commandType: CommandType.Text);
if (obj != null && obj.Count() > 0)
return obj.ToList();
else
return new List<PendingKmsRequest>();
}

asp:calendar binds last value to date from database

I have to bind an <asp:calendar> with data fetched from a database using a linq query.
Here is the linq code
public List<AllCalander> SearchCalender(int month, int zip, string type, int cause)
{
var xyz = (from m in DB.Calenders
where(m.DateFrom.Value.Month==month || m.Zip==zip || m.ActivityType==type || m.CauseID==cause)
group m by new { m.DateFrom } into grp
select new
{
caustitle = grp.Select(x => x.Caus.CauseTitle),
datfrm = grp.Key.DateFrom,
total = grp.Count()
})
.ToList()
.Select(m => new AllCalander
{
DateFrom =Convert.ToDateTime(m.datfrm),
CauseTitle = string.Join(",", m.caustitle),
Total = m.total
});
My aspx.cs code is here
List<AllCalander> calnder = calbll.SearchCalender(mnth,ZipString,type,causeString);
foreach (var myItem in calnder)
{
string datetime = myItem.DateFrom.ToString();
Literal myEventNameLiteral = new Literal();
myEventNameLiteral.ID = i + myItem.CauseID.ToString();
// string currentcalanderDate = e.Day.Date.Day.ToString() ;
if (string.Equals(DateTime.Parse(datetime).ToString("MMM dd yyyy"), e.Day.Date.ToString("MMM dd yyyy")))
{
string a = myItem.CauseTitle;
if (a != cause)
cause = a;
coun++;
myEventNameLiteral.Mode = LiteralMode.PassThrough;
myEventNameLiteral.Text = "<br /><span style='font-family:verdana; font-size:10px;'>" + myItem.CauseTitle + "(" + myItem.Total + ")"+ " ";
e.Cell.Controls.Add(myEventNameLiteral);
}
i++;
}
but on output it only shows the last value from database instead of showing all the data.
Can somebody please tell me what's wrong?
Thanks in advance
group m by new { m.DateFrom, m.Caus.CauseTitle } into grp

Submitting Long Query String with Mid Function - Getting Error and String is Truncated

I have a page where the user can select a lot of check boxes, and then have each of the values they select get inserted into a database. I'm using a querystring to submit the values from the inital page to a post page.
The values are pipe-delimited, and the stored procedure runs for every one of them. I also have an integer I submit to the database as well.
A couple problems - first of all, on occasion I get a mid "invalid procedure call" error. And other times, it seems I am submitting way too many characters for the QueryString and so it gets truncated and not all the values get submitted.
Any help is appreciated. Thanks!
The main page that submits the values - Javascript:
function submit()
{
var n = 0;
var stringIDs = "";
//Number of records to submit stored in hidden text box.
for (n=1; n<=parseInt(document.getElementById("txtResultsIndex").value); n++)
{
try
{
var cb = document.getElementById("cbSelection"+n);
if (cb.checked)
{
stringIDs = stringIDs + "|" + document.getElementById("linkNumber"+n).innerText;
}
}
catch(exception)
{}
}
window.open("submit.asp?stringIDs=" + stringIDs + "|&cboResearchedBy=" + document.getElementById("cboResearchedBy").value);
}
The post page classic ASP (where the error seems to be originating):
Dim vSQLInsert, v1ID, RS, stringIDs, cboResearchedBy, CN
'GetDataConnection is included in header file.
Set CN = GetDataConnection
stringIDs = Request.QueryString("stringIDs")
cboResearchedBy = Request.QueryString("cboResearchedBy")
stringIDs = Mid(stringIDs,2,len(stringIDs))
Do While stringIDs <> ""
v1ID = Mid(stringIDs,1,InStr(stringIds,"|")-1)
'Insert data into main table.
vSQLInsert = "spInsert "
vSQLInsert = vSQLInsert & "#vResearchedBy = '" & cboResearchedBy & "',"
vSQLInsert = vSQLInsert & "#vSequenceNumber = '" & v1ID & "'"
Set RS = CN.Execute (vSQLInsert)
stringIDs = Replace(stringIDs, v1ID & "|","")
Loop
Remove Mid function. Place values in a text box to submit to the post page in an array, using a for each loop. Page still takes some time to submit, but no errors result.
vIndex = stripquotes(Request.Form("txtIndex"))
If Request.Form("cboResearchedBy") <> "" Then
vResearchedBy = stripquotes(Request.Form("cboResearchedBy"))
End If
If Request.Form("txtMySeq") <> "" Then
txtMySeq = Request.Form("txtMySeq")
End If
vSeqArray = Split(txtMySeq, "|")
For Each vSeq In vSeqArray
vSQLInsert = "Insert "
vSQLInsert = vSQLInsert & "#vResearchedBy = '" & vResearchedBy & "',"
vSQLInsert = vSQLInsert & "#vSequenceNumber = '" & vSeq & "'"
Response.Write(vSQLInsert)
Set RS = CN.Execute (vSQLInsert)
Next

When calling stored procedure, .hasRows keeps staying "false"

I have a stored procedure which I am calling which will return data from a table.
But when I try to populate an .aspx with the data it skips my method from doing it because my method is based on whether a reader detects rows.
Here is my method:
private void editExhibit(int expenseID)//new
{
saveExhibitBtn.Text = "Update Exhibit";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("p_CaseFiles_Exhibits_RetrieveExhibitDetails", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#ExhibitID", expenseID);
cmd.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
cmd.Parameters["#ExhibitID"].Value = expenseID;
bool hasAttachments = false;
string investigatorID = "";
//bool alreadyInvoiced = false;
bool isExpenseOwner = false;
string fileID = "-1";
try
{
conn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)//////////////////////craps out here bcause hasRows is false....
{
reader.Read();
fileID = reader["FileID"].ToString();
ddlCaseFiles.SelectedValue = fileID;
ddlCaseFiles.Enabled = false;
// retrieve exhibit details here
hasAttachments = (bool)reader["HasAttachments"];
investigatorID = reader["InvestigatorID"].ToString();
if (Session["InvestigatorID"].ToString() == investigatorID)
{
isExpenseOwner = true;
}
txtDateReceived.Value = reader["SeizeDate"].ToString();
ddlReceivedBy.SelectedValue = reader["SeizedByInvestigatorID"].ToString();
txtTimeReceived.Value = reader["SeizeTime"].ToString();
txtWhyHowReceived.Value = reader["SeizeAuthority"].ToString();
txtReceivedLocation.Value = reader["SeizeLocation"].ToString();
txtOurItemNum.Value = reader["NewExhibitOutItemNumber"].ToString();////////////
txtTheirItemNum.Value = reader["ClientItemNum"].ToString();
txtBagNum.Value = reader["BagNumber"].ToString();
txtBoxNum.Value = reader["BoxNumber"].ToString();
txtComment.Value = reader["ExhibitDecriptionPlainText"].ToString();
}
}
catch (SqlException ex)
{
ErrorLogger.Log(ex.Number, "NewExhibit.aspx - editExhibit - Retrieve Details", ex.Message);
}
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[p_CaseFiles_Exhibits_RetrieveExhibitDetails]
#FilterField nvarchar(max)=null
, #FilterQuery nvarchar(max)=null
, #SortName nvarchar(max)='SeizeDate, SeizeTime '
, #SortOrder nvarchar(max)='desc'
, #ExhibitID int
as
SET CONCAT_NULL_YIELDS_NULL OFF
declare #Command nvarchar(max)
Select #Command = 'select E.ExhibitID,convert(nvarchar,SeizeDate,111) as ''SeizeDate'',SeizeTime,ExhDesc,E.InvestigatorID as ''EnteredBy''
,E.SeizedByInvestigatoID as ''SeizedBy'',SBI.ActiveInvestigator, SBI.FName+'' '' + SBI.LName as ''SeizedByName'', E.FileID,[FileName]
,Investigators.FName,Investigators.LName,SzAuthority,Location,ItemID,SubItemID1,SubItemID2,SubItemID3,PageSerial,ClientItemNum,Privileged
,Private,E.HasAttachments,ItemEntryGradeID,BagNumber,BoxNumber,PL.PropertyId,P.PropertyTypeID,P.PropertyMakeID,P.PropertyModelID,SerialNumber,ColorID
,cast(ItemID as varchar)+''-''+cast(SubItemID1 as varchar)+''-''+cast(SubItemID2 as varchar)+''-''+cast(SubItemID3 as varchar) as ''ItemNumber'',StoredLocally
from CaseFileExhibits E
join Investigators on E.InvestigatorID = Investigators.InvestigatorID
join Investigators SBI on SBI.InvestigatorID=E.SeizedByInvestigatoID
join CaseFiles on E.FileID = CaseFiles.FileID
left join CaseFileExhibitPropertyLink PL on E.ExhibitID=PL.ExhibitID
left join Element09a_Properties P on P.PropertyID=PL.PropertyId
left join ElementPropertyTypes PT on PT.PropertyTypeID=P.PropertyTypeID
left join ElementPropertyMakes PM on PM.PropertyMakeID=P.PropertyMakeID
left join ElementPropertyModels PMD on PMD.PropertyModelID=P.PropertyModelID
where E.ExhibitID='+convert(nvarchar,#ExhibitID);
if(#FilterQuery is not null)
begin
select #Command+=' and '+#FilterField+ ' like '''+#FilterQuery+''' ';
end
select #Command+=' order by '+#SortName+' '+#SortOrder
So according to the stored procedure I only need to pass in the exhibitID, which I did.
Your Stored procedure looks incomplete. You probably need to add
exec sp_executesql #command;
At the end to get it to return your rows.
info about sp_executesql can be found at http://msdn.microsoft.com/en-us/library/ms188001.aspx

how to resolve object Null error?

I have a situation where i am assigning some value to a session. I have a situation in which that code is calling repeatedly. some times this code throws error of object null. I am not getting why this is happening while i am assign value to it.My code is
if (HttpContext.Current.Cache["Cache"] == null)
{
CreateChanhe();
DataTable dtcache= HttpContext.Current.Cache["HNS Connection"] as DataTable; //CreateConnectString(CCMMUtility.Encryptdata(txtPin.Text));
string sqlFilter = "Sp = '" + classses.DecryptString(HttpContext.Current.Request.Cookies["Cookies"].Values["sp"].ToString(), classses.SP) + "'";
DataRow[] dr = dtcache.Select(sqlFilter);
if (dr.Length > 0)
{
String[] Con = new String[2];
Con[0] = dr[0][0].ToString();
Con[1] = dr[0][1].ToString();
sp= Con[1];
HttpContext.Current.Session["Name"] = dr[0][2].ToString();
}
}
When i am try to do "Add watch" while debugging its says the "value" has some value but the HttpContext.Current.Session["Name"] is null. Can some let me know why this is happening.
Actually i am creating a cache then fills session from that cache. this is based on my requirement.
I suspect that dr[0][2] is null so when you call .ToString() on it you are getting a NRE.
Is that the HttpContext.Current is null? If so wrap a null check around it like this:
if (HttpContext.Current != null)
{
if (HttpContext.Current.Cache["Cache"] == null)
{
CreateChanhe();
DataTable dtcache= HttpContext.Current.Cache["HNS Connection"] as DataTable; //CreateConnectString(CCMMUtility.Encryptdata(txtPin.Text));
string sqlFilter = "Sp = '" + classses.DecryptString(HttpContext.Current.Request.Cookies["Cookies"].Values["sp"].ToString(), classses.SP) + "'";
DataRow[] dr = dtcache.Select(sqlFilter);
if (dr.Length > 0)
{
String[] Con = new String[2];
Con[0] = dr[0][0].ToString();
Con[1] = dr[0][1].ToString();
sp= Con[1];
HttpContext.Current.Session["Name"] = dr[0][2].ToString();
}
}
}

Resources