How do I check a not-null query string against a sql database in c# for ASP.NET? - asp.net

I have a web page that is pulling information about a specific database entry based on the reference number of that database entry. This reference number is not the SQL ID number, but a number that we assign at entry time.
This reference number is passed to the page in the form of a query string, and as long as the reference number actually exists in the database, everything is fine. However, if the reference number does not exist, my details page comes up blank: no exception or anything.
I'm not sure how relevant sharing my code is in this case, but I'll play it safe:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
DescRepeater.DataSource = KidSpecific.ToList();
DescRepeater.DataBind();
}
}
I can put in a redirect in case some joker tries to bring up my details page without going through the main directory (which would bring up a null query string), but if used correctly, my query string will never be null or empty. What I'm trying to prepare for is if someone bookmarks my details page with a query string that was valid at the time of bookmarking, but then gets taken down.
How can I check to make sure there is a reference number in the database that matches the query string before the var "KidSpecific" fires? If there is no such reference number, I need to be able to use a Response.Redirect to put up an error page instead of the blank screen that shows now.
Thanks in advance for any help.

Why do you need to do your check before the query fires? You'll have to check the database for the entry either way. Try redirecting if your query comes up empty:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
var KidSpecificList = KidSpecific.ToList();
//Redirect if there are no results!
if (KidSpecificList.Count() < 1)
Response.Redirect("RedirectPage.aspx");
DescRepeater.DataSource = KidSpecificList;
DescRepeater.DataBind();
}
}

You can check quety string with string.IsNullOrEmpty like this:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
if ( string.IsNullOrEmpty ( KidNum ) ) {
Response.Redirect ( "WhatEverURI" );
} else {
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
DescRepeater.DataSource = KidSpecific.ToList();
DescRepeater.DataBind();
}
}
}

Related

How to parse specific data from query string in a url in C#?

I want to parse the data from a URL query string and store it. Given below is my sample URL. From this I want to parse the data and store somewhere
http://www.example.com/default.aspx?VN=919999999999&Rawmessage=urlTest&Time=2013-04-08 12:32:04&Send=919000000002&MID=101878052
I want to store VN and Rawmessage into these strings,
string x = Request.QueryString["VN"]
string y = Request.QueryString["Rawmessage"]
Please help me find a solution.
Place this code in the Page_Load() function in Default.aspx.cs file.
protected void Page_Load(object sender, EventArgs e)
{
string x = Request.QueryString["VN"];
string y = Request.QueryString["Rawmessage"];
}
With reference to the discussion we had, I think you want to parse the query string key-value pair and use the values somewhere else.
Also, ASP.Net doesn't have to do anything with parsing, It's a pure C# problem.
I'm giving the sample solution to the problem in the context of a Console App, you're free to reuse the codes as per your taste.
var inputUrl =
#"http://www.example.com/default.aspx?VN=919999999999&Rawmessage=urlTest&Time=2013-04-08 12:32:04&Send=919000000002&MID=101878052";
int index = inputUrl.IndexOf("?");
var queryString = inputUrl
.Substring(index + 1)
.Split('&');
foreach (var strKeyValuePair in queryString)
{
var keyValPair = strKeyValuePair.Split('=');
Console.WriteLine("Key: {0}, Value:
{1}",keyValPair[0],keyValPair[1]);
}
Console.WriteLine("\n============================================\n\n");
string VN = queryString.FirstOrDefault(x => x.StartsWith("VN"));
string RawMessage = queryString.FirstOrDefault(x =>
x.StartsWith("Rawmessage"));
Console.WriteLine("VN: {0}",VN.Split('=')[1]);
Console.WriteLine("RawMessage: {0}", RawMessage.Split('=')[1]);
Console.ReadLine(); // just to halt the console

Selected value in asp.net dropdown in a repeater not returned

I've currently go a very strange problem. I'm using an asp.net wizard to upload some files. The files are uploaded using plupload. After the files have uploaded I have a list of the upload files stored in a session variable. I use the session variable to create a table showing the upload files. The user now has option to set a file category using a dropdown in the table. When the user clicks 'finish' button the code reads the list of files and the category from the table. The odd thing is this code works fine on my development machine and on several servers but on a particular clients server the drop down value always returns as null. Here is the relevent code:
protected void Page_Init(object sender, EventArgs e)
{
bindRepeater();
}
private void bindRepeater()
{
ArrayList sessionFiles = (ArrayList)Session["PLUploadFiles"];
IList<document> files = new List<document>();
foreach (string fileName in sessionFiles)
{
document doc = new document();
doc.FileName = fileName;
doc.Description = fileName.Split('.').First();
files.Add(doc);
}
TableRepeater.DataSource = files;
TableRepeater.DataBind();
}
protected void SaveButton_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in TableRepeater.Items)
{
Label descriptionLabel = (Label) item.FindControl("DescriptionLabel");
String description = descriptionLabel.Text;
Label fileNameLabel = (Label)item.FindControl("FileNameLabel");
String fileName = fileNameLabel.Text;
DropDownList categoryDropDown = (DropDownList) item.FindControl("CategoryDropDownList");
string category = categoryDropDown.SelectedValue;
if(SaveClicked != null)
{
SaveEventArgs s = new SaveEventArgs();
s.FileName = fileName;
s.Category = category;
s.Description = description;
SaveClicked(this, s);
}
}
Response.Redirect(RedirectURL);
}
Note that the entire wizard lives on a usercontrol. Has anybody got any idea why this code works fine on most machines but fails on one particular server?
Looks like I've fixed it. For some reason I was seeing a double postback. This was calling my code to reset the session variables in Page_Load at the wrong time. The work around is to reset the session variables in the page that links to the upload page so they are reset before the page is loaded. I've no idea why I'm seeing the double postback.

Can't submit changes to database or page controls

I've got a pretty simple page, consisting of two DropDownLists populated from the database, and a button. The purpose of the page is pretty simply to allow users to delete an entry from the database. When the button is clicked then a simple LINQ query is executed to delete the intended target, and remove the entry from the dropdownlists, but it doesn't work unless the response is redirected within that function, even if SubmitChanges() was called. Why would this happen?
Edit: Code
protected void Page_Init(object sender, EventArgs e)
{
var result = Database.DB.Data.GetTable<Database.tbl_module_>().Where(module => module.deptCode == ((User)Session["user"]).deptCode);
foreach (var row in result)
{
this.listModuleCode.Items.Add(new System.Web.UI.WebControls.ListItem(row.code));
this.listModuleTitle.Items.Add(new System.Web.UI.WebControls.ListItem(row.title));
}
}
protected void Delete_Click(object sender, EventArgs e)
{
var DB = Database.DB.Data;
var table = DB.GetTable<Database.tbl_module_>();
var result = table.Where(module => module.deptCode == ((User)Session["user"]).deptCode && module.code == listModuleCode.SelectedItem.Text);
listModuleCode.Items.Remove(listModuleCode.SelectedItem);
listModuleTitle.Items.Remove(listModuleTitle.SelectedItem);
table.DeleteAllOnSubmit(result);
DB.SubmitChanges();
Response.Redirect("deletemodule.aspx"); // redirect to this page
}
We need to see your code to help more probably. However:
You need to make sure it knows to delete on submit:
var q = db.Customers.Where(c => c.CustomerID == 2).Single();
db.Customers.DeleteOnSubmit(q);
db.SubmitChanges();
Don't forget you can pass straight SQL to the object:
db.ExecuteCommand("DELETE FROM Customers WHERE ID = 2");
Which you might think is easier.

delete record onClick, asp.net

I have a form where users can subscribe and unsubcribe to my email list. so far, i have the subscribe button working fine "add member" function. Now i need help with my "delete member " function (unsubscribe button). it will allows the user to delete their record from the database. When I run the code and click the "unsubscribe" button, i can't get the logic correct so that it will delete the user's record if it exisit. thanks for your help!
here's the code i'm using for the subscribe and unsubscribe buttons -----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class joinmailinglist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addMember(object sender, EventArgs e)
{
// here you are defining the classes for the database and the linq
mailinglistClassDataContext Class = new mailinglistClassDataContext();
mailinglistMember member = new mailinglistMember();
// Now we are going to add the data to the member
// Here we are going to let the system define a GUID for the unique user ID
member.memberID = new Guid();
// here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.
member.fname = txtFirstName.Text;
member.lname = txtLastName.Text;
member.email = txtEmail.Text;
// Here we are going to create the URL so we can later remove the user if they decide to opt out.
member.removeurl = "http://removeuser.aspx?code=" + member.memberID.ToString();
// Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.
var duplicatecheck = from emails in Class.mailinglistMembers
where emails.email.Contains(txtEmail.Text)
select emails;
// Here we are going to check that the count of duplicate is equal to zero. If so then we are going to insert the member information into the class and then submit the changes to the database.
if (duplicatecheck.Count() == 0)
{
Class.mailinglistMembers.InsertOnSubmit(member);
Class.SubmitChanges();
}
else
{
lblDuplicate.Text = "Hey you have already entered your information.";
}
}
protected void deleteMember(object sender, EventArgs e)
{
// here you are defining the classes for the database and the linq
mailingListClassDataContext Class = new mailingListClassDataContext();
mailinglistMember member = new mailinglistMember();
// here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.
member.email = txtEmail.Text;
// Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.
var deleterec = from emails in Class.mailinglistMembers
where emails.email.Contains(txtEmail.Text)
select emails;
// Here we check if the record exisits
if (deleterec.Count() == 0)
{
Class.mailinglistMembers.DeleteOnSubmit(member);
Class.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
}
else
{
lblDelete.Text = "No record exsists!";
}
}
}
Try the below code.
string mailAddress = txtEmail.Text.Trim().ToLower();
using (var db = new mailingListClassDataContext())
{
var records = from e in db.mailinglistMembers
where e.mail == mailAddress
select e;
if (records != null)
{
db.mailinglistMembers.DeleteAllOnSubmit(records);
db.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
Response.End();
}
else
{
lblDelete.Text = "No records exists!";
}
}
You may have meant to do this:
var deleterec = Class.mailinglistMembers
.FirstOrDefault(emails => emails.email.Contains(txtEmail.Text));
if (deleterec != null)
{
Class.mailinglistMembers.DeleteOnSubmit(deleterec);
Class.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
}
Looks like someone tried to add on to the code I origianlly posted in my article on code project. Not sure if you've read the article but it might help solve your problem and understand how it was intended to work. A link would return you to a removal page that would and capture the GUID. I used the GUID as the identifyer to remove the user. Original Article

Problem in dynamically load data to Drop-Down list box in InfoPath 2007?

I have a Drop-Down list in my InfoPath form and I am loading some other fields based on the selection of the drop-down list. so that I have written code as follows for the "changed" event of the drop down list.
public void ProjectName_Changed(object sender, XmlEventArgs e)
{
string projectId = e.NewValue;
dataQueryConnection = (AdoQueryConnection)this.DataConnections["ProjectInformation"];
dataQueryConnection.Command = dataQueryConnection.Command + string.Format(" WHERE ProjectId = '{0}'", projectId);
dataQueryConnection.Execute();
}
For the first time when I change an item in the drop down list its working fine but for the subsequent changes of items(2nd time, etc..) its give the following error,
The query cannot be run for the
following DataObject:
ProjectInformation InfoPath cannot run
the specified query.
[0x80040E14][Microsoft OLE DB Provider
for SQL Server] Incorrect syntax near
the keyword 'WHERE'.
And this is the reason, for the second time,
dataQueryConnection.Command = select
"EmployeeID","Accountname","ProjectName","ProjectId","ProjectRole","BillableUtilization","ClientName","BillingCode","BUHead"
from "TRF"."hrt_vw_ProjectInformation"
as "hrt_vw_ProjectInformation" WHERE
ProjectId = '3072507' WHERE ProjectId
= '3076478'
subsequent event firing biding the WHERE clause every time with the previous executed query.
How I can over come from this issue?
Store the initial command string in a global variable in your code (in the loading event). Then in your Changed function append to the global variable instead of to the previous value of the command.
string OrigString
public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
OrigString = dataQueryConnection.Command;
}
public void ProjectName_Changed(object sender, XmlEventArgs e)
{
string projectId = e.NewValue;
dataQueryConnection = (AdoQueryConnection)this.DataConnections["ProjectInformation"];
dataQueryConnection.Command = OrigString + string.Format(" WHERE ProjectId = '{0}'", projectId);
dataQueryConnection.Execute();
}

Resources