delete record onClick, asp.net - 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

Related

Nested subscription to messages on xamarin forms

I'm new with Xamarin forms and don't know how to deal with this case. I've tryed to implement it in several ways but with no success.
I have a page where when user makes an action (write a text on a text box and send it with enter key) my app must make some checkings. Depending on the result of the checks, it could be necessary to show a modal page with a list of item to select. Ones user makes the selection process must continue with other checks. And here is my problem, because in this next checkings I have to show another page. User must make a selection/enter some date, and then continue to complete the proccess, but this page is not appear.
I'm using the messagingCenter to subscribe to the modal pages. First modal page appears and makes the selection well. Second modal page is never shown and then proccess never complets.
Here is some of my code:
NavigationPage navigationPage = new NavigationPage(new ListItemsPage(products));
Navigation.PushModalAsync(navigationPage);
MessagingCenter.Subscribe<ListItemsPage, Guid?>(this, "Select product", (obj, item) =>
{
try
{
if (item != null)
{
product = products.SingleOrDefault(x => x.Guid == item);
if (product != null) ProcessLine(product);
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
MessagingCenter.Unsubscribe<ListItemsPage, Guid?>(this, "Select product");
}
});
On ListItemsPage I have this code whe item is selected:
private void MenuItem_Clicked(object sender, EventArgs e)
{
// some logic...
Navigation.PopModalAsync();
MessagingCenter.Send(this, "Select product", SelectedGuid);
}
SelectedGuid is a Guid type data and when debbugin is well selected.
Problems comes when goes to ProcessLine method.
private void ProcessLine(Product product) {
// make some logic...
NavigationPage navigationPage = new NavigationPage(new ControlUnitsPage(model));
Navigation.PushModalAsync(navigationPage);
MessagingCenter.Subscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", (obj, item) =>
{
try
{
if (item != null)
{
_date = item.Date;
_code = item.Code;
_units = item.Units;
Save(productLine, product, _units, _date,_code);
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
MessagingCenter.Unsubscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code");
}
});
}
ControlUnitsPage has the same structure as the last one page. First makes a PopModalAsync and then sends the message sending an instance of ControlUnits type.
private void Button_Clicked(object sender, EventArgs e)
{
//some logic...
Item = new ControlUnits() { Date = DateField.Date, Code = CodeField.Text, Units = int.Parse(SelectedUnits.Value.ToString()) };
Navigation.PopModalAsync();
MessagingCenter.Send(this, "Select units, date and lot code", Item);
}
I think problem is in the order of invoking method but dont know what is the properly order because I am not able to understand how pushmodal, popmodal methods work, whether or not I should use await with it if after that comes a subscription. I really don't know and I need help, please.
Thank you so much!
your Send and Subscribe calls both need to use matching parameters
if Subscribe looks like this
MessagingCenter.Subscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", (obj, item) => ... );
then Send needs to match
MessagingCenter.Send<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", Item);

How to prevent insertion in FormView?

I want to check my form before inserting to prevent insert duplicate ProductSerial in my data base.
so how can i check the txtProductSerial.text with my database and if it is duplicate I PREVENT INSERTION.
This are my codes
protected void fvwSoldForm_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["DateX"] = DateTime.Now;
e.Values["IsDeleted"] = false;
e.Values["Confirmed"] = false;
var solded = db.SoldedByResellers.ToList();
solded = solded.Where(p => p.ProductSerial == NumericSerial.Text).ToList();
if (solded.Count > 0)
Alert("Please Change the serial code, This code Used before");
//Here WHAT EVER I DO THE INSERTING GOES ON. I WANT TO STOP INSERTING HERE
}
To cancel the operation, set:
e.Cancel = true;
This will prevent the insert from happening. See the MSDN documentation for an example.

How do I check a not-null query string against a sql database in c# for 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();
}
}
}

Get Selected Text asp.net custom server control

I need to get the latest text set in the custom control by javascript. When i tried to get the selected text from server control, it is always returning the default text & not the modified text. How to retain the latest value set by the javascript in servercontrol? Below is the complete code for your reference..
ServerControl1.cs
[assembly: WebResource("ServerControl1.Scripts.JScript1.js", "text/javascript")]
namespace ServerControl1
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl
{
public List<string> ListItems
{
get
{
return ViewState["items"] as List<string>;
}
set
{
ViewState["items"] = value;
}
}
public string Text
{
get
{
return (FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor).InnerText;
}
set
{
((FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor)).InnerText = value;
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextContainer.ID = "middleDiv";
HtmlAnchor selectedTextAnchor = new HtmlAnchor();
selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextAnchor.ID = "anchorID";
selectedTextAnchor.HRef = "";
selectedTextContainer.Controls.Add(selectedTextAnchor);
HtmlGenericControl unList = new HtmlGenericControl("ul");
foreach (string item in ListItems)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlAnchor anchor = new HtmlAnchor();
anchor.HRef = "";
anchor.Attributes.Add("onclick", "updateData()");
anchor.InnerText = item;
li.Controls.Add(anchor);
unList.Controls.Add(li);
}
selectedTextContainer.Controls.Add(unList);
Controls.Add(selectedTextContainer);
ChildControlsCreated = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string resourceName = "ServerControl1.Scripts.JScript1.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(ServerControl1), resourceName);
}
}
}
JScript1.js
function updateData() {
var evt = window.event || arguments.callee.caller.arguments[0];
var target = evt.target || evt.srcElement;
var anchor = document.getElementById("anchorID");
anchor.innerText = target.innerText;
return false;
}
TestPage Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> items = GetDataSource();
ServerControl1.ListItems = items;
ServerControl1.Text = "Select ..";
}
}
protected void ClientButton_Click(object sender, EventArgs e)
{
string selectedText = ServerControl1.Text;
}
The server won't get your client changes unless you POST the changes to him. Your HtmlAnchors are being rendered in HTML as <a> controls, and these type of controls won't POST anything to the server.
You're going to need an <input> control to input the changes into the server (that's why they're called input controls after all). I suggest an <input type=hidden> to hold the value of the anchor.innerText and keeps its state.
Your Javascript function needs to be modified so it updates the anchor.innerText AND updates the hidden input value as well. This way when the page gets posted back to the server you can retrieve the updated and client-modified value from the hidden field.
First you need to define as private fields your selectedTextAnchor and the hiddenField you are going to insert. This is because you need to access them in your CreateChildControls method as well as in the getter and setter of yout Text property. Much in the way the partial designer classes define the controls you want to have available in code-behind.
ServerControl.cs
private HtmlAnchor selectedTextAnchor;
private HtmlInputHidden hiddenField;
In the CreateChildControls method you need to insert the hidden field.
You'll notice I removed the use of ClientIDMode.Static. Using that mode would make your client controls to have the same fixed IDs and Javascript might get confused when you have multiple copies of your ServerControl in a page, and thus losing the reusable purpose of a custom control.
Instead, you need to provide your Javascript function with the ClientID's of the controls it needs to modify. The key here is that you need to attach your controls to the Control's hierarchy BEFORE you try to get their ClientID's.
As soon as you do this.Controls.Add(dummyControl), you're making dummyControl to become a part of the Page and its dummyControl.ClientID will be suddenly changed to reflect the hierarchy of the page you're attaching it into.
I changed the order at which your controls are attached to the Control's collection so we can grab their ClientID's at the time we build the onclick attribute and pass the parameters so your Javascript function knows which anchor and hiddenField to affect.
ServerControl.cs
protected override void CreateChildControls()
{
base.CreateChildControls();
// Instantiate the hidden input field to include
hiddenField = new HtmlInputHidden();
hiddenField.ID = "ANCHORSTATE";
// Insert the hiddenfield into the Control's Collection hierarchy
// to ensure that hiddenField.ClientID contains all parent's NamingContainers
Controls.Add(hiddenField);
HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
// REMOVED: selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextContainer.ID = "middleDiv";
selectedTextAnchor = new HtmlAnchor();
// REMOVED: selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextAnchor.ID = "anchorID";
selectedTextAnchor.HRef = "";
selectedTextContainer.Controls.Add(selectedTextAnchor);
// Insert the selectedTextContainer (and its already attached selectedTextAnchor child)
// into the Control's Collection hierarchy
// to ensure that selectedTextAnchor.ClientID contains all parent's NamingContainers
Controls.Add(selectedTextContainer);
HtmlGenericControl unList = new HtmlGenericControl("ul");
foreach (string item in ListItems)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlAnchor anchor = new HtmlAnchor();
anchor.HRef = "";
// The updateData function is provided with parameters that will help
// to know who's triggering and to find the anchor and the hidden field.
// ClientID's are now all set and resolved at this point.
anchor.Attributes.Add("onclick", "updateData(this, '" + selectedTextAnchor.ClientID + "', '" + hiddenField.ClientID + "')");
anchor.InnerText = item;
li.Controls.Add(anchor);
unList.Controls.Add(li);
}
selectedTextContainer.Controls.Add(unList);
}
Note the use of the keyword this in the updateData function, it'll help us to grab the object that is triggering the action. Also note that both Id's are passed as strings (with single quotes)
The Javascript function would need to be modified so it updates the anchor and the hidden input field.
JScript1.js
function updateData(sender, anchorId, hidFieldId) {
// Update the anchor
var anchor = document.getElementById(anchorId);
anchor.innerText = sender.innerText;
// Update the hidden Input Field
var hidField = document.getElementById(hidFieldId);
hidField.value = sender.innerText;
return false;
}
The last thing to do is change the way you are setting and getting your Text property.
When you GET the property you need to check if it's a Postback, and if it is, then you want to check if among all the info that comes from the browser there is your HiddenInputField. You can grab all the info coming from the client right at the Request object, more specifically, in the Request.Form.
All enabled input controls on your page will be part of the Request.Form collection, and you can get their values by using Request.Form[anyInputControl.UniqueID]. Note that the key used for this object is the UniqueID, NOT ClientID.
Once you get your client-modified value from the hidden input, you assign its value to the selectedTextAnchor, otherwise it'll go back to the original "Select..." text.
When you SET the property, you just need to assign it to the selectedTextAnchor.
In both GET and SET you need to call EnsureChildControls(), which will actually call your CreateChildControls() to make sure that your selectedTextAnchor and hiddenField controls are instantiated before you try to get some of their properties. Pretty much the same way that it's done in Composite Controls.
ServerControl.cs
public string Text
{
get
{
EnsureChildControls();
if (this.Page.IsPostBack)
{
string HiddenFieldPostedValue = Context.Request.Form[hiddenField.UniqueID];
// Assign the value recovered from hidden field to the Anchor
selectedTextAnchor.InnerText = HiddenFieldPostedValue;
return HiddenFieldPostedValue;
}
else
{
return selectedTextAnchor.InnerText;
}
}
set
{
EnsureChildControls();
selectedTextAnchor.InnerText = value;
}
}
This way you can have a control that recognizes the changes made in client. Remember that server won't know any change in client unless you notice him.
Another approach would be to notice the server everytime you click a link through an ajax request, but this would require a whole new different code.
Good luck!

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.

Resources