Solved

Validation in Linq to Sql

Posted on 2011-03-18
6
457 Views
Last Modified: 2012-05-11
Hi

Im using C#, ASp.net and Linq to Sql in my project

i have a partial method to validate my field, it works well but when I thow the exeption it shows me the ugly ASP error page, I would like to show this message in a ValidatorSummary , is this possible?
public partial class Oficios
{

    partial void OnNumPropuestaChanging(string value)
    {

        using (ModuloProgramacionDataContext db = new ModuloProgramacionDataContext())
        {

            var query = from p in db.Oficios
                        where p.NumPropuesta == value
                        select p;
            if (query.Count() > 0) throw new Exception("The field already exist in the database");
        
        
        }


    }

Open in new window

0
Comment
Question by:Veljean
6 Comments
 
LVL 10

Expert Comment

by:John Claes
ID: 35167165
You should Catch all your exceptions at the code behind your page and do something with them.
Every exception that is not catched will generate the "ugly" aspx page.

so add the message to the Validator summery in the Catch and show it then

poor beggar
0
 
LVL 1

Author Comment

by:Veljean
ID: 35167219
do you have an example ?
0
 
LVL 11

Expert Comment

by:Kusala Wijayasena
ID: 35167417
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 11

Accepted Solution

by:
SAMIR BHOGAYTA earned 250 total points
ID: 35167711
Hello,

LINQ to SQL Classes might not look like business objects but you can make them perform business rules validation. Let's say that you have a class called "Person". Person has FirstName, LastName, DOB (Date of Birth) etc. Now, you don't want two persons to have the same firstname or the lastname ( I know kinda weird requirement). You can use the OnFirstNameChanging method to implement the condition for same first name. Here is the code:

   partial void OnFirstNameChanging(string value)
        {
            // check if the firstname already exists in the database!
            SchoolDataContext school = new SchoolDataContext();

            var query = from p in school.Persons
                                  where p.FirstName == value
                                  select p;

            if (query.Count() > 0) throw new Exception("FirstName already exists in the database");
        }

Now, if the same first name already exists in the database then an exception is thrown. You can do the same thing for last name property.

 partial void OnLastNameChanging(string value)
        {
            SchoolDataContext school = new SchoolDataContext();

            var query = from p in school.Persons
                        where p.LastName == value
                        select p;

            if (query.Count() > 0) throw new Exception("LastName already exists in the database");
        }        

You can also use the OnValidate method of the Person object. In the following code I am checking that if the address has already been added.

  partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            SchoolDataContext school = new SchoolDataContext();

            if (action == System.Data.Linq.ChangeAction.Insert)
            {
                foreach (var address in this.Addresses)
                {
                    var query = from a in school.Addresses
                                where a.Street == address.Street
                                && a.PersonID == this.PersonID
                                select a;

                    if (query.Count() > 0) throw new Exception("Address already exists");
                }
            }
        }

If your requirment was that two persons cannot have the same FirstName and LastName then you should have used the OnValidate event.
0
 
LVL 1

Author Comment

by:Veljean
ID: 35167734
samirbhogayta

thanks for your tips, but my problem is I dont know what to do with the new Exception and avoid the ugly ASP error page, how you handle this errors?
0
 
LVL 10

Assisted Solution

by:John Claes
John Claes earned 250 total points
ID: 35178949
Veljean:

Look for information about the Try Catch blocks


Example

try
{
int a = 0;
int b = 10;
int c = b / a;  // this wil generate a Divide by Zero exception
divideTextbox1.Text = c;
}
catch (Exception exception)
{       // here we'll catch all exceptions and try to do something with them.
        // For this example I'm just going to show the ErrorMessage in an Label

       errorLabel.Text = exception.Message;
}



This will not show the ugly page but will remain on the normal page and show the error message

regards

poor beggar
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now