Asp.net Handling duplicate key exception - c#

I am trying to handle duplicate key exception in detailsview, and my code under iteminserted is:
if (e.Exception.Message.Contains("duplicate key")
{
Response.Write("Student already registered!");
e.ExceptionHandled = true;
}
The code is running correctly when there is duplicate key, but in normal situation (no duplicate key) it gives following error:
‫System.NullReferenceException: Object reference not set to an instance of an object

Check if it is null before running the If statement.
if (e.Exception.Message != null){
if (e.Exception.Message.Contains("duplicate key")
{
Response.Write("Student already registered!");
e.ExceptionHandled = true;
}
}

Related

Google Firebase Auth in Unity: How to read error codes

When using the Google Firebase Authentication plugin in Unity, how do you read error codes of faulted requests?
For example, within this code:
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if(task.IsFaulted){
Debug.Log("ERROR ENCOUNTERED: " + task.Exception);
return;
}
if(task.IsCompleted){
// Success!
}
});
You can see that if an error occurs I can log the exception out, which prints the following:
ERROR ENCOUNTERED: System.AggregateException: Exception of type 'System.AggregateException' was thrown.
Firebase.FirebaseException: There is no user record corresponding to this identifier. The user may have been deleted.
That's very human-readable, but not very elegant to put into a switch statement. Is there any way for me to cast the task.Exception to be a FirebaseException so I can grab the error code? And is there a list of these error codes somewhere? I can find the documentation for the FirebaseException, but the error codes aren't there. Thanks for the help!
Edit:
So while I am still hoping for an answer, I've come to think that Google expects developers to use blanket error statements based on the context of the request. For example, when failing to sign in with an email and password (as in the above code), we should use the common statement of "Email or password is incorrect." The problem with that is that I can't let the user know the difference between them providing the incorrect details versus them entering an email which doesn't have an account associated with it at all.
Hopefully you've solved this by now but I've just come across the exact same problem and I'll share my solution:
According to MSDN, System.AggregateException is a representation of one or more errors that may occur during the task execution.
Therefore, you'll need to loop through the InnerException(s) presented by the AggregateException, and look for the suspected FirebaseException:
Retrieving the FirebaseException:
AggregateException ex = task.Exception as AggregateException;
if (ex != null) {
Firebase.FirebaseException fbEx = null;
foreach (Exception e in ex.InnerExceptions) {
fbEx = e as Firebase.FirebaseException;
if (fbEx != null)
break;
}
if (fbEx != null) {
Debug.LogError("Encountered a FirebaseException:" + fbEx.Message);
}
}
Getting the Error Code:
Wish I could help here but I haven't found anything - these aren't documented within the official API, AFIK. The only reference states: "If the error code is 0, the error is with the Task itself, and not the API. See the exception message for more detail."
I encountered the same dilemma trying to find out which error code I get from Firebase and display appropriate message for the user.
The correct way to read the Firebase Exception is with this function I created:
bool CheckError(AggregateException exception, int firebaseExceptionCode)
{
Firebase.FirebaseException fbEx = null;
foreach (Exception e in exception.Flatten().InnerExceptions)
{
fbEx = e as Firebase.FirebaseException;
if (fbEx != null)
break;
}
if (fbEx != null)
{
if (fbEx.ErrorCode == firebaseExceptionCode)
{
return true;
}
else
{
return false;
}
}
return false;
}
And you can use it like this:
auth.SignInWithEmailAndPasswordAsync("test#gmail.com", "password").ContinueWith(task => {
if (task.IsCanceled)
{
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted)
{
if(CheckError(task.Exception, (int)Firebase.Auth.AuthError.EmailAlreadyInUse))
{
// do whatever you want in this case
Debug.LogError("Email already in use");
}
Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception);
}
}
Here is some more code samples from firebase:
https://github.com/firebase/quickstart-unity/blob/master/auth/testapp/Assets/Firebase/Sample/Auth/UIHandler.cs
I got the answer from this thread:
https://github.com/firebase/quickstart-unity/issues/96
I hope this will help someone. All the best!

DescribeTable Error Type, Amazon DynamoDB

I am referencing this answer to another, very similar question (the only difference being the use of PHP).
I have seen an example of getting detailed error information from an exception throw by AWS DynamoDB's DescribeTable method in PHP (see above linked answer); however, I have had trouble finding similar information in C#.
Here is what I have mimicked so far:
var describeTableResponse = _client.DescribeTable(tableName);
var responseStatusCode = describeTableResponse.HttpStatusCode;
if (responseStatusCode == HttpStatusCode.OK)
{
return true;
}
else if(responseStatusCode == HttpStatusCode.BadRequest)
{
var error = // get detailed information; looking for ResourceNotFoundException
}
throw new AmazonDynamoDBException("Error performing the DescribeTable operation");
Above, client is a correctly configured DB client of type AmazonDynamoDBClient.
Any thoughts on how to do the equivalent of:
$error_type = $response->body->__type;
$error_code = explode('#', $error_type)[1];
if($error_code == 'ResourceNotFoundException')
{
echo "Table ".$table_name." exists.";
}
I actually ended up going a completely different route due to the specification surrounding the .Net DescribeTable() function -- it throws the ResourceNotFoundException.
try
{
_client.DescribeTable(tableName);
}
catch (AmazonServiceException amazonServiceException)
{
if (amazonServiceException.GetType() != typeof(ResourceNotFoundException))
{
throw;
}
return false;
}
return true;

tableadapter failed constraints

I'm using a tableadapter in a large project and I keep getting the "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." error whenever I call any of my queries on it. I do not have null values and I do have unique primary key values in the result set. Nevertheless, I have tried setting EnforceConstraints to False everywhere in the generated source. I also removed any primary keys using "delete key" option in the context menu for the column. I set AllowDBNull true for all the columns in the tableadapter. The exception still occurs. I have three queries defined under the tableadapter all of which return the same exact same columns (the SQL differs only in the filter expressions used). Researching this issue online, I found the suggestion to set a try/catch in the generated source code to examine the error to determine the exact cause. When I do this, no error is generated at all. The generated source is as follows:
public virtual CyberevToo.ReactionImagesDataTable AllMedia(string MindfileID, string FilePath) {
this.Adapter.SelectCommand = this.CommandCollection[1];
if ((MindfileID == null)) {
throw new global::System.ArgumentNullException("MindfileID");
}
else {
this.Adapter.SelectCommand.Parameters[0].Value = ((string)(MindfileID));
}
if ((FilePath == null)) {
throw new global::System.ArgumentNullException("FilePath");
}
else {
this.Adapter.SelectCommand.Parameters[1].Value = ((string)(FilePath));
}
CyberevToo.ReactionImagesDataTable dataTable = new CyberevToo.ReactionImagesDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
The exception is thrown on the "this.Adapter.Fill(dataTable);" line. After modification, the source code is as follows:
public virtual CyberevToo.ReactionImagesDataTable AllMedia(string MindfileID, string FilePath) {
this.Adapter.SelectCommand = this.CommandCollection[1];
if ((MindfileID == null)) {
throw new global::System.ArgumentNullException("MindfileID");
}
else {
this.Adapter.SelectCommand.Parameters[0].Value = ((string)(MindfileID));
}
if ((FilePath == null)) {
throw new global::System.ArgumentNullException("FilePath");
}
else {
this.Adapter.SelectCommand.Parameters[1].Value = ((string)(FilePath));
}
CyberevToo.ReactionImagesDataTable dataTable = new CyberevToo.ReactionImagesDataTable();
try
{
this.Adapter.Fill(dataTable);
}
catch (System.Exception ex) {
System.Console.WriteLine(ex.Message);
}
return dataTable;
}
with a breakpoint set on the line "System.Console.WriteLine(ex.Message);" which never gets reached. With the try/catch in place, the DataTable is returned fine and full of data. Without it, no data is returned at all. When I build and run the program with the try/catch, no exception occurs. When it executes without a try/catch, it fails with the above exception.
Any ideas WHY? I don't want to have to re-code the generated code for all 20 something tableadapters I have in the XSD every time I make a change to one of the definitions!

Check object null or not [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I wanted to check if User exists or not in the database, and i take a User object and check if it is null or not.But the problem is in my code if user doen't exist in our database it returns following exception,
Object reference not set to an instance of an object.
I know this error happen when there is no such a user in our database.So.. i wanted to know if this user object( i want to return null or not) null or not.
My Part of Code
if(newsManager.GetUserUsingEmail(User.Email).Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
How to solve it ?
The null reference exception is probably due to you trying to access the Email property on the user returned from the GetUserUsingEmail method. You should test if the returned value is null first and only then try accessing properties on it.
var user = newsManager.GetUserUsingEmail(User.Email);
if (user != null)
{
// user exists
}
else
{
// user does not exist
}
if newsManager.GetUserUsingEmail(User.Email) returns null, then you will agree that attempting to invoke .Email should give you the Object reference not set to an instance of an object. error, right?
As suggested in the comments, if your condition is truly just checking to see if the user exists or not, then simply do this:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
If, as your code suggests, your intent is really to enter the if block only if you have a valid Email value for a valid user, then you can do that like this instead:
var user = newsManager.GetUserUsingEmail(User.Email);
if(user != null && !string.IsNullOrEmpty(user.Email))
{
//User Exists and has a valid email
}
else
{
//User Doesn't exists or doesn't have a valid email.
}
You cannot get property from null. Check object != null instead:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
In C# 6.0 you can use Safe Navigation Operator (?.):
if(newsManager.GetUserUsingEmail(User.Email)?.Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}

Entity Framework Error: An object with a null EntityKey value cannot be attached to an object context

In my application I have the following code...
public Boolean SaveUserInformation(UserInfoDTO UserInformation)
{
return dataManager.SaveUserInfo(new UserInfo()
{
UserInfoID = UserInformation.UserInfoID.HasValue ? UserInformation.UserInfoID.Value : 0,
UserID = UserInformation.UserID,
ProxyUsername = UserInformation.ProxyUsername,
Email = UserInformation.Email,
Status = UserInformation.Status
});
}
This code calls a method on a dataManager object that utilizes Entity Framework...
public Boolean SaveUserInfo(UserInfo userInfo)
{
try
{
//Validate data prior to database update
if (userInfo.UserID == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with UserID property set to NULL."); }
if (userInfo.ProxyUsername == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with ProxyUsername property set to NULL."); }
if (userInfo.Email == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with Email property set to NULL."); }
if (userInfo.UserInfoID == 0)
{
//Perform Insert
using (PriorityOneEntities entities = new PriorityOneEntities())
{
entities.UserInfoes.AddObject(userInfo);
entities.SaveChanges();
}
}
else
{
//Perform Update
using (PriorityOneEntities entities = new PriorityOneEntities())
{
entities.Attach(userInfo);
entities.SaveChanges();
}
}
return true;
}
catch (Exception ex)
{
//TODO: Log Error
return false;
}
}
The insert on this code works just fine. But when I try to perform an update I'm getting an error saying: "An object with a null EntityKey value cannot be attached to an object context."
It occurs on this line of code: entities.Attach(userInfo);
What I'm trying to accomplish is to avoid making a round trip to the database just to select the record that I will later make changes to and update, thus making two round trips to the database.
Any ideas what is going wrong, or how I could better accomplish this?
Thanks.
Seems like you're using EF 4.1+
You have to tell EF that you want your entity to be updated (Modified state):
//Perform Update
using (PriorityOneEntities entities = new PriorityOneEntities())
{
entities.Entry(userInfo).State = EntityState.Modified;
entities.SaveChanges();
}
P.S. You don't have to explicitly call Attach. It's done under the hood.
Update:
based on your comments, you're using EF 4.0. Here's what you have to do to attach your object as modified in EF 4.0:
ctx.AddObject("userInfoes", userInfo);
ctx.ObjectStateManager.ChangeObjectState(userInfo, EntityState.Modified);
ctx.SaveChanges();
You cannot use Attach method. From http://msdn.microsoft.com/en-us/library/bb896271.aspx:
If more than one entity of a particular type has the same key value, the Entity Framework will throw an exception. To avoid getting the exception, use the AddObject method to attach the detached objects and then change the state appropriately.
From MSDN
The object that is passed to the Attach method must have a valid
EntityKey value. If the object does not have a valid EntityKey value,
use the AttachTo method to specify the name of the entity set.
Hope this will help you.

Categories

Resources