While writing codes in ADO.NET, the first thing you need to make sure what kind of operation are you performing .
If you are performing insert update or delete operation the database connection needs to be opened and closed.
If you are performing selection operation there is no need to open and close database connection.
So what we need to do is to check while performing crud operations is connection closed or not . If it is not closed we will close it first or if it is closed we will open it and then use it.
using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
{
if (sqlConnection.State == ConnectionState.Closed)
{
sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("uspRegisterUser", sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = empobj.FirstName;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = empobj.LastName;
cmd.Parameters.Add("@ProfileImage", SqlDbType.VarChar, 500).Value = ConfigurationManager.AppSettings["ProfileImageBaseAddress"].ToString();
cmd.Parameters.Add("@JobRoleID", SqlDbType.BigInt).Value = empobj.JobRoleID;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 200).Value = empobj.Email;
cmd.Parameters.Add("@CompanyID", SqlDbType.Int).Value = empobj.CompanyId;
cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = empobj.Password;
cmd.Parameters.Add("@PasswordSalt", SqlDbType.VarChar, 100).Value = Guid.NewGuid().ToString();
cmd.Parameters.Add("@AccessToken", SqlDbType.VarChar, 100).Value = accessToken;
cmd.Parameters.Add("@DeviceUUID", SqlDbType.VarChar, 50).Value = empobj.DeviceUUID;
cmd.Parameters.Add("@DeviceType", SqlDbType.VarChar, 50).Value = empobj.DeviceType;
cmd.Parameters.Add("@CreatedDate", SqlDbType.VarChar, 50).Value = System.DateTime.Now;
cmd.Parameters.Add("@IsDeleted", SqlDbType.VarChar, 50).Value = empobj.IsDeleted;
cmd.Parameters.Add("@DeletedDate", SqlDbType.Date).Value = System.DateTime.Now;
result = Convert.ToInt32(cmd.ExecuteNonQuery());
switch (result)
{
case 1:
empResponse.Status = true;
empResponse.Message = "User successfully registered.";
empobj.AccessToken = accessToken;
break;
case 2:
empResponse.Status = false;
empResponse.Message = "Email already exists.";
break;
default:
empResponse.Status = false;
empResponse.Message = "Registration failed.";
break;
}
}
}
catch (SqlException ex)
{
Logger.LogException(ex);
empResponse.Status = false;
empResponse.Message = ex.Message;
}
This code first check whether connection is open or not if it is not it will open the connection.
0 Comment(s)