Exemplo n.º 1
0
        public async Task <IActionResult> Get(int id, [FromQuery] Int32 hid = 0)
        {
            if (hid <= 0)
            {
                return(BadRequest("HID is missing"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            EventHabitViewModel vm     = new EventHabitViewModel();
            SqlConnection       conn   = null;
            SqlCommand          cmd    = null;
            SqlDataReader       reader = null;
            String         queryString = "";
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    queryString = HIHDBUtility.Event_GetEventHabitQueryString(false, usrName, hid, null, null, id);

                    cmd    = new SqlCommand(queryString, conn);
                    reader = cmd.ExecuteReader();

                    // Detail
                    while (reader.Read())
                    {
                        EventHabitDetail detail = new EventHabitDetail();
                        HIHDBUtility.Event_HabitDB2VM(reader, vm, detail, false);
                        vm.Details.Add(detail);
                    }
                    reader.NextResult();

                    // Checkin
                    while (reader.Read())
                    {
                        EventHabitCheckInViewModel civm = new EventHabitCheckInViewModel();
                        civm.ID       = reader.GetInt32(0);
                        civm.TranDate = reader.GetDateTime(1);
                        if (!reader.IsDBNull(2))
                        {
                            civm.Score = reader.GetInt32(2);
                        }
                        if (!reader.IsDBNull(3))
                        {
                            civm.Comment = reader.GetString(3);
                        }
                        if (!reader.IsDBNull(4))
                        {
                            civm.CreatedBy = reader.GetString(4);
                        }
                        if (!reader.IsDBNull(5))
                        {
                            civm.CreatedAt = reader.GetDateTime(5);
                        }
                        if (!reader.IsDBNull(6))
                        {
                            civm.UpdatedBy = reader.GetString(6);
                        }
                        if (!reader.IsDBNull(7))
                        {
                            civm.UpdatedAt = reader.GetDateTime(7);
                        }
                        vm.CheckInLogs.Add(civm);
                    }
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(exp.Message);
#endif
                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(vm, setting));
        }
        public async Task <IActionResult> Post([FromBody] EventHabitCheckInViewModel vm)
        {
            if (vm == null)
            {
                return(BadRequest("No data is inputted"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest("Model status is invalid"));
            }
            if (vm.HabitID <= 0 || vm.HID <= 0)
            {
                return(BadRequest("Invalid data: home ID, habit ID"));
            }

            Boolean unitMode = Startup.UnitTestMode;

            SqlConnection  conn        = null;
            String         queryString = "";
            Int32          nNewID      = -1;
            String         strErrMsg   = "";
            String         usrName     = String.Empty;
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            if (unitMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usr = User.FindFirst(c => c.Type == "sub");
                if (usr != null)
                {
                    usrName = usr.Value;
                }
                if (String.IsNullOrEmpty(usrName))
                {
                    return(BadRequest("User is not recognized"));
                }
            }

            SqlCommand     cmd  = null;
            SqlTransaction tran = null;

            try
            {
                queryString = @"SELECT [ID]
                            FROM [dbo].[t_event_habit_checkin] WHERE [TranDate] = @trandate AND [HabitID] = @habitid";

                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw; // Re-throw
                    }

                    cmd = new SqlCommand(queryString, conn);
                    cmd.Parameters.AddWithValue("@trandate", vm.TranDate);
                    cmd.Parameters.AddWithValue("@habitid", vm.HabitID);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        Int32 nDuplicatedID = -1;
                        while (reader.Read())
                        {
                            nDuplicatedID = reader.GetInt32(0);
                            break;
                        }

                        errorCode = HttpStatusCode.BadRequest;
                        strErrMsg = "Event has been checked in at same date: " + nDuplicatedID.ToString();
                        throw new Exception(strErrMsg);
                    }
                    else
                    {
                        reader.Dispose();
                        reader = null;

                        cmd.Dispose();
                        cmd = null;

                        // Now go ahead for the creating
                        queryString = HIHDBUtility.Event_GetEventHabitCheckInInsertString();
                        tran        = conn.BeginTransaction();

                        cmd             = new SqlCommand(queryString, conn);
                        cmd.Transaction = tran;
                        HIHDBUtility.Event_BindEventHabitCheckInInsertParameters(cmd, vm, usrName);
                        SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                        idparam.Direction = ParameterDirection.Output;

                        Int32 nRst = await cmd.ExecuteNonQueryAsync();

                        nNewID = (Int32)idparam.Value;

                        tran.Commit();
                    }
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(exp.Message);
#endif

                if (tran != null)
                {
                    tran.Rollback();
                }

                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            vm.ID = nNewID;
            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(vm, setting));
        }