简体   繁体   中英

How to update the logic to check the SQL query status and based on that return true/false in c#?

I'm new to C# and SQL. My code from the endpoint is as follows:

 public IActionResult EndSession([Required(ErrorMessage = "Session Id is required.")]string sessionId)
    {
        DateTime startTime = DateTime.Now;
        try
        {
            string logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Attempting to delete user session.");
            logger.LogInfo(logText);

           EndUserSession(sessionId);

            logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Successfully deleted user session.");
            logger.LogInfo(logText);

            return Ok(true);
        }
        catch (Exception ex)
        {
            string logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", ex.ToString());

            logger.LogError(logText, ex);

            return StatusCode(Constants.InternalServerErrorCode, "Failed! Unable to delete user session. Please check logs for more details.");
        }
    }

My code from the data access layer is as follows:

public void EndUserSession(string sessionId)
    {
        using (SqlConnection connection = new SqlConnection(DataSourceHelper.ConnectionString))
        {
            try
            {
                using (SqlCommand command = new SqlCommand("EndUserSession", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandTimeout = Constants.SQL_COMMAND_TIMEOUT;

                    command.Parameters.AddWithValue("@SessionId", sessionId);
                    command.Parameters.AddWithValue("@SessionEndTime", DateTime.Now);

                    connection.Open();
                    command.ExecuteNonQuery();                    

                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

Stored Procedure:

IF OBJECT_ID('[dbo].[EndUserSession]') IS NOT NULL
DROP PROCEDURE [dbo].[EndUserSession]
GO
CREATE PROCEDURE [dbo].[EndUserSession]
@SessionId nvarchar(36),
@SessionEndTime datetime
WITH ENCRYPTION
AS
BEGIN
UPDATE [dbo].[USER_SESSION] 
SET SESSION_END_DATETIME = @SessionEndTime
WHERE USER_SESSION_IID = @SessionId
END
GO

When the given sessionId doesn't exist in the database the application stops and immediately catches the error and throws a 500 internal server error code from the endpoint I call this function from.

What I want to do is update the logic so that you check the SQL query status and based on that return true/false from the EndUserSession function and based on that you log if there is a failure or if the session Id is not found in the User_Session table. What is the best way to achieve this?

ExecuteNonQuery() returns number of rows affected by an INSERT, UPDATE or DELETE statement. So I changed the functions to return bool and added this logic in my data access:

int a = command.ExecuteNonQuery();

                    if (a == 0)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }

In my endpoint I added an if statement that if the function returns true it would return a 200 and if it returns false it returns a 400 bad request logging that the sessionId couldn't be found therefore nothing was updated. It was as follows:

var testSession = EndUserSession(sessionId);

            if(testSession == true) 
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Successfully deleted user session.");
                logger.LogInfo(logText);

                return Ok(true);
            }
            else
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "SessionId not found, please try again.");
                logger.LogInfo(logText);

                return BadRequest(false);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM