105

pages enableEventValidation=true

by Mohit Bhardwaj 29. June 2009 11:47

There are many times when you are trying to use a datagrid or repeater in your page which you are binding at the Page_load event. You need to get some specific row from the button in that datagrid in your code behind, by using its CommandArgument property, but all you get is this error.

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Stack Trace:

[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
   System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

Now, if you clearly see, you might be calling the page_load event twice. Twice, how come?

I will explain, see you need to understand the lifecycle of the page. Everytime a request is made, a page undergoes a full processing at the server end. This results that for any event to happen, the Page_load event happens first obviously after Page_Init. So what happens there is when you are clicking the button, it undergoes the page_load event again, and you don't get the value of command argument of the button you clicked.

Solution: Put the (Datagrid/Gridview/Repeater/Datalist)'s binding mechanism inside if(IsPostBack==false), in the page_load event. What it will do is, it will check if the page is loaded for the first time or not. If it is loaded for the first time, then go ahead, and if not, you can create your own logic after that.

 

Tags:

Beginners

98

Sending Email using ASP.NET [PART 2]

by Mohit Bhardwaj 4. April 2009 12:19

Last time I have added a post on Sending email using Gmail. Now, I have been working on a project which needs to send emails to the different user's using Godaddy's smtp service. But problem was that I can not send emails to the godaddy server by using its default smtp address as smtpout.secureserver.net at port 80 from the webhosting server. After googling I found out that this smtp is an outside smtp service of godaddy which is used to send emails coming from outside of its server environment. But it will not work when the application is hosted inside of the server environment, which was the case I was having. So, I found out that the correct smtp server I should use from inside the webshosting server is relay-hosting.secureserver.net at port 25.

Now, I assumed that my problem has been resolved. But now here comes the actuall problem. Every time I needed to work on the project I had to change the smtp and port number to smtpout.secureserver.net instead of relay-hosting.secureserver.net because it is in inside relaying smtp hosts so it is not accessible from the outside world. And this has become many times a real problem as I usually forgets to update the settings again and upload it back on the server and then email doesn't work. CryCry

Then I came up with a trick to get the smtp and port number automatically by its own and here is how I did it.

I have created a file name Mail.xml. Save this file on your hosting service's Virtual directory which are you using on the internet.

<?xml version="1.0" encoding="utf-8" ?>

- <mail>
  <setting host="relay-hosting.secureserver.net" port="25" />
</mail>
And, we will create a second version of this xml file which will be saved in our local develoment PC i.e at the wwwroot/inetpub/project directory.

<?xml version="1.0" encoding="utf-8" ?>

- <mail>
  <setting host="smtpout.secureserver.net" port="80" />
</mail>
Then I have created a class file to introduce the functionality of getting the configuration and then send emails.

Imports Microsoft.VisualBasic

Imports System.Net

Imports System.Net.Mail

Imports System.Net.Configuration

Imports System.Xml

 

Public Class ModuleClass

Public function sendmail(ByVal body As String, ByVal too As String, ByVal subject As String) As String

Try

Dim arr As New ArrayListDim xtr As XmlTextReader = New XmlTextReader(System.Web.HttpContext.Current.Server.MapPath("Mail.xml"))

xtr.WhitespaceHandling = WhitespaceHandling.None

Dim xd As XmlDocument = New XmlDocument

xd.Load(xtr)

Dim xnodRoot As XmlNode = xd.DocumentElement

Dim xnodWorking As XmlNode

If xnodRoot.HasChildNodes Then

xnodWorking = xnodRoot.FirstChild

While Not IsNothing(xnodWorking) arr = ProcessChildren(xnodWorking, 0)

' ProcessChildren is a function that will return an arraylist with first parameter as server name and second as port number.

xnodWorking = xnodWorking.NextSibling

End While

End If

Dim mail As New MailMessage

mail.To.Add(New MailAddress(too))

' I am hardcoding here that email will be sent by xxxx@abc.com , if you want you can add one more parameter to the function.

mail.From =
New MailAddress("xxxx@abc.com")mail.Bcc.Add(New MailAddress("yyyy@123.com"))

mail.Body = body

mail.Subject = subject

Dim client As SmtpClient = New SmtpClient(arr(0).ToString(), CInt(arr(1).ToString()))

client.DeliveryMethod = SmtpDeliveryMethod.Network

client.Credentials =
New System.Net.NetworkCredential(mail.From.Address.ToString(), "^&%&^%&^%")

' this is the password of the account used in the from field of the email. Remember this must be a valid account and it should have the rights to send emails.

client.Send(mail)

Return "Success"

Catch ex As Exception

Return "Failed"

End Try

End Function

 

Private Function ProcessChildren(ByVal xnod As XmlNode, ByVal Depth As Integer) As ArrayList Dim arr As New ArrayList

Dim strNode As String

Dim intI, intJ As Integer

Dim atts As XmlAttributeCollection

'we're only going to process Text and Element nodes

If (xnod.NodeType = XmlNodeType.Element) Or (xnod.NodeType = XmlNodeType.Text) Then

strNode = ""

'attributes too

atts = xnod.Attributes

If Not atts Is Nothing Then

For intJ = 0 To atts.Count - 1

strNode = ""

For intI = 1 To Depth + 1

strNode &= "-"

Next

arr.Add(atts("host").Value.ToString()) arr.Add(atts("port").Value.ToString())

Next

End If

End If

Return arr

End Function

End Class

What happens now is that whenever you tries to send the email, it will load the configuration from the xml file in both the PC and server environment and then you can send email from both of them.

[Note: I have googled this code but I am not aware of the person who wrote this code of getting things from XML file. So I am hereby giving credit to that person who created this function. Thanks Man.]

Tags:

Beginners | No Category

37

Sending Email using ASP.NET

by Mohit Bhardwaj 24. March 2009 02:01

Last night I was thinking to write a small post about sending emails using .NET. Then I thought of using GMAIL smtp account to send email. So here is the code.

using System;
using System.Net;
using System.Net.Mail;

/// <summary>
/// Email Sending Class for GMAIL account.
/// </summary>

public class Emails
{
public Emails()
{
//
// TODO: Add constructor logic here
//
}

 

public string sendmail(string body)
{
try
{
MailMessage mail=
new MailMessage();
mail.To.Add(new MailAddress("xxxx@gmail.com"));
mail.From=
new MailAddress("yyyy@gmail.com");
mail.Body=body;
SmtpClient smtp=
new SmtpClient("smtp.gmail.com",587);
smtp.Credentials=new NetworkCredential("yyyy@gmail.com", "#&&$$%#%"); // This is where you have to specify account properties of the email account you are using to send email. yyyy@gmail.com is the userid and #&&$$%#% is the password.
smtp.EnableSsl=true;
smtp.Send(mail);
return "Success";
}
catch(Exception ex)
{
return "Failed";
}
}
 

Now from here you can call this class and send email. I have used the static emails here but you can make it change accordingly to use it as dynamically. You will need to add more paramaters like "body" in calling this function.

Thanks.

Tags:

Beginners

139

Series for Beginner's - Creating new project

by Mohit Bhardwaj 18. March 2009 02:16

Whenever someone have to work on something in Visual Studio, he have to create a project to easily manage the code and the relative information about it. Visual Studio provides many different types of solutions but you need to choose the best suitable project or solution type. For creating an ASP.NET Project, you need to so following:

  1. Open Visual Studio 2005 or 2008, whatever system installed on your PC.
  2. In the left hand side of the Start Page, you can see Recent Projects.
  3. Below that in the same area, you can find "Create Website" link.
  4. IF, by some chance you can not find "Create Website", then go to File->New->Website.
  5. There you can find the different solutions related to ASP.NET.
  6. Choose the best that fits your needs, I mean if you want to create web services first then choose web services solution.

HINT: Personally I feel, whatever solution you choose, In the location dropdown, always choose HTTP, instead of FTP or File System and specify the path as http://localhost/ProjectName for a simple reason that, if you somehow migrate to different environment like you move from XP to Vista, like I did, I didn't have to worry about changing the settings for the projects and solutions, because, FileSystem uses an ASP.NET Virtual Server to run your project, and that server's PORT Number is configured automatically when you install .Net Framework. So better to choose localhost, do all the programming and then if you have to move to differenr OS, you just need to take copy of your localhost folder, I mean, wwwroot folder under, C:\inetpub.

Moreover, the solutions that you create always saved in your My Document->Visual Studio 2005->Projects, so make sure that you copy that too, before moving to the new OS.

AND ALWAYS, BACK UP THESE 2 FOLDERS.

Tags:

Beginners

37

New Series

by Mohit Bhardwaj 13. March 2009 02:16

I would like to use this as a tool to spread the knowledge I have while working on ASP.NET. For starters, I will be posting a series for beginners.

It will help those young developers, who needs a professional approach towards development. I will call it as a "Series For Beginners". From now on, I will post related topics about the starting the website without any hush-mush for beginners, so that they can understand the concept easily.

Hope You all will like it.Smile

Tags:

Beginners

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft