Send e-mail after update statement in ASPX - asp.net

I'm building for my project work at school a website.
The main idea is that users can report damage or report a non functioning computer.
Then the IT department can give in if they've taken any steps try fixing it and there is also a checkbox if the problem is dealth with. If the checkbox in the formview is checked and updated, there should be sent an automatic e-mail to the original user with a message that the problem is solved. I've done everything and everything works, except for the e-mail part.
Can anybody give me some advice in how I should do this? There is an unique datasource who handeles the update statement.
Yours sincerely;
A.
Here is my code:
<asp:AccessDataSource ID="accAfgehandeld" runat="server"
DataFile="~/App_data/dbMeldingen.mdb"
DeleteCommand="DELETE FROM [tblMeldingen] WHERE [MeldingID] = ?"
InsertCommand="INSERT INTO [tblMeldingen] ([MeldingID], [Afgehandeld], [Categorie]) VALUES (?, ?, ?)"
SelectCommand="SELECT [MeldingID], [Afgehandeld], [Categorie] FROM [tblMeldingen] WHERE ([MeldingID] = ?)"
UpdateCommand="UPDATE [tblMeldingen] SET [Afgehandeld] = true, [Categorie] = ? WHERE [MeldingID] = ?"
OnUpdated="OnDSUpdatedHandler">
<DeleteParameters>
<asp:Parameter Name="MeldingID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="MeldingID" Type="Int32" />
<asp:Parameter Name="Afgehandeld" Type="Boolean" />
<asp:Parameter Name="Categorie" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="MeldingID" QueryStringField="id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Categorie" Type="Int32" />
<asp:Parameter Name="MeldingID" Type="Int32" />
</UpdateParameters>
</asp:AccessDataSource>
and my script in the same page:
<%# Control Language="VB" AutoEventWireup="false" CodeFile="meldingendetails.ascx.vb" Inherits="meldingendetails" %>
<script runat="server">
private void OnDSUpdatedHandler(Object sender, e.Updated) {
if (e.AffectedRows > 0)
{
MailMessage mailMessage = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
}
}
</script>
Visual studio gives an error over and over again with my script, even from the void part...

Set OnUpdated-handler
<asp:SqlDataSource
...
UpdateCommand="..."
OnUpdated="OnDSUpdatedHandler">
</asp:SqlDataSource>
and use it to send email
<script runat="server">
private void OnDSUpdatedHandler(Object source, SqlDataSourceStatusEventArgs e) {
if (e.AffectedRows > 0) {
MailMessage mailMessage = new MailMessage();
...
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
}
}
</script>

Related

SqlDataSource UpdateParameters - Input string was not in a correct format

I have inherited some ASP.NET code that I need to update which has resulted in my needing to change the ASP SqlDataSource's UpdateCommandType from a string (hard coded SQL Update statement) to a stored procedure containing the Update statement.
The string executes fine and uses parameters that are bound to controls in a details view (I know this is not best practice and it pains me having to work with data connections from the client side...! But I dont have time to re-write all the data connections for this and many pages just yet).
Anyway, I have just changed the UpdateCommand to a stored procedure that does the same thing and I just get the error
Input String was not in a correct format.
when I try to update on the page.
I can supply code if requested, but it is big & horrible so I am tentatively asking if anyone has any initial ideas? I will put a few small bits below though. I have been looking at the UpdateParameterCollection as I wonder if the parameter collection is getting cached anywhere - but cannot see anything.
I have controls bound to the DataSource items like so:
<EditItemTemplate>
<asp:CheckBox ID="chkNonReview" runat="server" Checked='<%# Bind("NonReview") %>' />
</EditItemTemplate>
And the SqlDataSource has been changed from this...
<asp:SqlDataSource ID="dsEventDV" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnString %>"
DeleteCommand="DELETE FROM [I_TRAINEE_EVENTS] WHERE [EVENTID] = #EVENTID"
InsertCommand="INSERT_TRAINEE_EVENTS_ED3"
InsertCommandType="StoredProcedure"
OnInserted="DSEvent_Inserted"
SelectCommand="Get_Candidate_Events_I3"
SelectCommandType="StoredProcedure"
UpdateCommand="UPDATE I_TRAINEE_EVENTS (etc...)"
.....
to this:
<asp:SqlDataSource ID="dsEventDV" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnString %>"
DeleteCommand="DELETE FROM [I_TRAINEE_EVENTS] WHERE [EVENTID] = #EVENTID"
InsertCommand="INSERT_TRAINEE_EVENTS_ED3"
InsertCommandType="StoredProcedure"
OnInserted="DSEvent_Inserted"
SelectCommand="Get_Candidate_Events_I3"
SelectCommandType="StoredProcedure"
UpdateCommand="UPDATE_TRAINEE_EVENTS"
UpdateCommandType="StoredProcedure">
.....
With the new UpdateCommand values.
The update parameters:
<UpdateParameters>
<asp:Parameter Name="EVENTID" Type="Int32"/>
<asp:Parameter Name="EVENTTYPEID" Type="Int32"/>
<asp:Parameter Name="EVENTDATE" Type="DateTime"/>
<asp:Parameter Name="STAFFID" Type="Int32"/>
<asp:Parameter Name="REVIEWNO" Type="Int32"/>
<asp:Parameter Name="COMMENTS" Type="String"/>
<asp:Parameter Name="DESTINYVERIFIED" Type="Int32"/>
<asp:Parameter Name="DESTINYVERIFIEDBY" Type="Int32"/>
<asp:Parameter Name="DESTINYVERIFIEDDATE" Type="DateTime"/>
<asp:Parameter Name="REASONFORSUSPENSIONID" Type="Int32"/>
<asp:Parameter Name="RETURNTOWORKDATE" Type="DateTime"/>
<asp:Parameter Name="ContactDetailsUpdated" Type="Int32"/>
<asp:Parameter Name="RETENTION_STATUS_ID" Type="Int32"/>
<asp:Parameter Name="RETENTION_REASON_ID" Type="Int32"/>
<asp:Parameter Name="NonReview" Type="Int32"/>
<asp:Parameter Name="FalsifiedEventReason" Type="Int32"/>
<asp:Parameter Name="SusReqReasonID" Type="Int32"/>
<asp:Parameter Name="SusReqReturnDate" Type="DateTime"/>
</UpdateParameters>
The stored procedure declaration is as follows:
CREATE PROCEDURE [dbo].[UPDATE_TRAINEE_EVENTS]
#EVENTID int,
#EVENTTYPEID int,
#EVENTDATE datetime,
#STAFFID int,
#REVIEWNO int,
#COMMENTS varchar(2100),
#DESTINYVERIFIED int,
#DESTINYVERIFIEDBY int,
#DESTINYVERIFIEDDATE datetime,
#REASONFORSUSPENSIONID int,
#RETURNTOWORKDATE datetime,
#ContactDetailsUpdated int,
#RETENTION_STATUS_ID int,
#RETENTION_REASON_ID int,
#NonReview int,
#FalsifiedEventReason int,
#SusReqReasonID int,
#SusReqReturnDate datetime
AS
......
I have also run SQL Server Profiler against the session to see what was being passed to the database, however the error comes in before anything hits the database which appears to suggest the problem is within the ASP.NET side of things.
Your <asp:Parameter Name="EVENTID" /> should have a datatype.
I think it should be like this..
<asp:Parameter Name="EVENTID" Type="Int32" />

Passing object to objectdatasource insert parameter

This is my object data source code.
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
InsertMethod="InsertCustomerItem" SelectMethod="GetCustomerItems"
TypeName="HPPWebsite.HPPClasses.TestClassHelper">
<InsertParameters>
<asp:Parameter Name="CustCode" Type="String" />
<asp:Parameter Name="ItemIn" Type="Object" />
</InsertParameters>
<SelectParameters>
<asp:SessionParameter Name="CustCode" SessionField="CustomerCode"
Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
This is my code behind:
<protected void Button1_Click(object sender, EventArgs e)
{
TestClass item = new TestClass();
item.CustCode = Session["CustomerCode"].ToString();
item.ItemCode =" ";
item.BasePrice =0.0;
item.AddMarkUp =true;
ObjectDataSource1.InsertParameters["CustCode"].DefaultValue = item.CustCode;
ObjectDataSource1.InsertParameters.Add("itemin",TypeCode.Object,"item");
ObjectDataSource1.Insert();
}
It gives me an error that type string cannot be converted to my testclass object. How can this be resolved please? I can do it if i just pass the object fieldds as seperate parameters but im trying to pass the whole object and do the trimmings and calculations in the stored proc

Deleting from SQL detailsView

Hey I am just learning to how to use asp.net and I am trying to use the grid view to display information and details view edit/delete the information from the database. Right now I can edit and update the information in the database but I also want it to delete and something is not working for me. I set up an exception and when I select the item and press delete it pops up my exception that another user has deleted the item when it hasn't. Im not really sure what i have done wrong, to me it looks like it should work.
Here is the code for the delete command and parameters from the details view
DeleteCommand="DELETE FROM [Customers]
WHERE [CustomerID] = #original_CustomerID
AND [Name] = #original_Name
AND [Address] = #original_Address
AND [City] = #original_City
AND [State] = #original_State
AND [ZipCode] = #original_ZipCode
AND ([Phone] = #original_Phone
OR [Phone] IS NULL AND #original_Phone IS NULL)
AND ([Email] = #original_Email
OR [Email] IS NULL AND #original_Email IS NULL)"
<DeleteParameters>
<asp:Parameter Name="original_CustomerID" Type="Int32" />
<asp:Parameter Name="original_Name" Type="String" />
<asp:Parameter Name="original_Address" Type="String" />
<asp:Parameter Name="original_City" Type="String" />
<asp:Parameter Name="original_State" Type="String" />
<asp:Parameter Name="original_ZipCode" Type="String" />
<asp:Parameter Name="original_Phone" Type="String" />
<asp:Parameter Name="original_Email" Type="String" />
</DeleteParameters>
and here is the delete functions in the cs file
protected void DetailsView1_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
{
if (e.Exception != null)
{
lblError.Text = "A database error has occurred.<br /><br />" +
"Message: " + e.Exception.Message;
e.ExceptionHandled = true;
}
else if (e.AffectedRows == 0)
lblError.Text = "Another user may have deleted that customer."
+ "<br />Please try again.";
else
GridView1.DataBind();
}
protected void DetailsView1_ItemDeleting(
object sender, DetailsViewDeleteEventArgs e)
{
e.Values["Name"]
= e.Values["Name"].ToString().Substring(1);
}
Why do you have such a huge query for a delete statement?Have a look how it's done in the MSDN DetailsView example
The CustomerID in your SQL table should be unique so your delete statement should be as simple as:
DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = #original_CustomerID"
And only one delete parameter:
<DeleteParameters>
<asp:Parameter Name="original_CustomerID" Type="Int32" />
</DeleteParameters>
One more thing which is quite important is you need to set DataKeyNames="CustomerID" on the DetailsView so that DetailsView1_ItemDeleted knows which row to delete. Hope this helps!

SWL Error Function has too many arguments specified

I am using ASP.NET 3.5 and SQL Server 2008.
I have a SQLDataSource & Gridview. I am trying to update 2 tables at the same time using a stored procedure in SQL.
SQLDatasource is passing 7 parameters.
5 parameters that the stored procedaure needs, Return value & StudentID.
Not sure if the error is in my SQLDatasorce or my stored procedure.
Here's my ASPX Code:
<asp:SqlDataSource ID="sqldsUserLoginNLevels" runat="server"
ConnectionString="<%$ ConnectionStrings:QuizStarConnectionString %>"
SelectCommand="SELECT UserLogins.StudentID, UserLogins.StudentName, UserLogins.UserID,
UserLogins.Password, UserLevels.GrammarStart, UserLevels.GrammarCurrent,
UserLevels.MathStart, UserLevels.MathCurrent
FROM UserLogins
INNER JOIN UserLevels ON UserLogins.StudentID = UserLevels.StudentID"
DeleteCommand="DELETE FROM [UserLogins] WHERE [StudentID] = #original_StudentID"
InsertCommand="INSERT INTO [UserLogins] ([StudentName], [UserID], [Password])
VALUES (#StudentName, #UserID, #Password)"
UpdateCommand="UpdateUserLoginsAndUserLevels"
UpdateCommandType="StoredProcedure" >
<DeleteParameters>
<asp:Parameter Name="original_StudentID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="StudentName" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="GrammarStart" Type="String" />
<asp:Parameter Name="MathStart" Type="String" />
<asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="StudentName" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
<asp:Parameter Name="Password" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
My Stored Procedure is:
ALTER PROCEDURE [dbo].[UpdateUserLoginsAndUserLevels] (
#StudentName VARCHAR(50),
#UserID NCHAR(10),
#Password NCHAR(10),
#GrammarStart NCHAR(10),
#MathStart NCHAR(10))
AS
DECLARE #StudentID INT;
BEGIN Transaction
BEGIN TRY
SELECT * From UserLogins
Where StudentID = #StudentID
UPDATE UserLogins
SET
StudentName= #StudentName,
UserID = #UserID,
Password = #Password
Where StudentID = #StudentID
UPDATE UserLevels
SET
GrammarStart= #GrammarStart,
MathStart = #MathStart
FROM UserLevels
INNER JOIN UserLogins ON UserLogins.StudentID = UserLevels.StudentID
WHERE (UserLevels.StudentID = #StudentID)
END TRY
BEGIN CATCH
DECLARE #ErrorMessage NVARCHAR(4000), #ErrorSeverity INT
-- Assign variables to error-handling functions that
-- capture information for RAISERROR.
SELECT #ErrorMessage = ERROR_MESSAGE(), #ErrorSeverity = ERROR_SEVERITY()
-- Rollback the failed transaction
ROLLBACK;
-- Raise an error: with the original error information.
RAISERROR(#ErrorMessage, #ErrorSeverity, 1);
END CATCH
COMMIT Transaction;
Have't figured how to post code yet. Sorry.
Make sure you are not double adding parameters. Since you are adding them in the aspx page you do not need to add them in your code behind.
For example if your code behind has this in it:
sqldsUserLoginNLevelsUserID.UpdateParameters.Add(new Parameter("UserID ", TypeCode.Int32));
It could explain your error.
If you need to set the value from code behind do it like this:
sqldsUserLoginNLevelsUserID.UpdateParameters["UserID "].DefaultValue = "1";

setting the default value for insert parameters in sql datasource asp.net

i have a datasource, which has an insertparameters, one of which whose type is set to Boolean, but while adding it from code behind insertparameters.defaultvalue always return string.
code behind code:
if (e.CommandName == "InsertNew")
{
TextBox Title = GridView1.FooterRow.FindControl("txtAddTitle") as TextBox;
TextBox Quote = GridView1.FooterRow.FindControl("txtAddQuote") as TextBox;
TextBox QuoteLink = GridView1.FooterRow.FindControl("txtAddQuoteLink") as TextBox;
CheckBox Published = GridView1.FooterRow.FindControl("chkAddBox") as CheckBox;
TextBox PublishedDate = GridView1.FooterRow.FindControl("txtAddPublishedDate") as TextBox;
SqlDataSource1.InsertParameters["Title"].DefaultValue = Title.Text;
SqlDataSource1.InsertParameters["Quote"].DefaultValue = Quote.Text;
SqlDataSource1.InsertParameters["QuoteLink"].DefaultValue = QuoteLink.Text;
SqlDataSource1.InsertParameters["Published"].DefaultValue = Convert.ToString(Published.Checked);
SqlDataSource1.InsertParameters["PublishedDate"].DefaultValue = PublishedDate.Text;
SqlDataSource1.Insert();
}
and aspx code for sql datasource is:
<InsertParameters>
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Quote" Type="String" />
<asp:Parameter Name="QuoteLink" Type="String" />
<asp:Parameter Name="Published" Type="Boolean" />
<asp:Parameter Name="PublishedDate" Type="DateTime" />
</InsertParameters>
Please reply how should i set the datatype as boolean from code behind.
1: Not sure why you are setting DefaultValue instead of the value
Or
2: Can you try this:
SqlDataSource1.InsertParameters["Published"].DefaultValue = Published.Checked==true?"true":"false";

Resources