コード例 #1
0
        public async Task <IActionResult> Post([FromBody] EventHabitViewModel vm, [FromQuery] Boolean geneMode = false)
        {
            if (vm == null)
            {
                return(BadRequest("No data is inputted"));
            }

            if (vm.Name != null)
            {
                vm.Name = vm.Name.Trim();
            }
            if (String.IsNullOrEmpty(vm.Name))
            {
                return(BadRequest("Name is a must!"));
            }

            // Check the details' generation
            EventGenerationInputViewModel datInput = new EventGenerationInputViewModel();

            datInput.StartTimePoint = vm.StartDate;
            datInput.EndTimePoint   = vm.EndDate;
            datInput.Name           = vm.Name;
            datInput.RptType        = vm.RptType;

            List <EventGenerationResultViewModel> listDetails = null;

            try
            {
                listDetails = EventUtility.GenerateHabitDetails(datInput);
            }
            catch (Exception exp)
            {
                return(BadRequest(exp.Message));
            }
            if (listDetails.Count <= 0)
            {
                return(BadRequest("Failed to generate the details"));
            }

            // For generation mode, just return the results
            if (geneMode)
            {
                return(Json(listDetails));
            }

            // For non-generation mode, go ahead for creating
            if (!ModelState.IsValid)
            {
                return(BadRequest("Model status is invalid"));
            }
            if (vm.Count <= 0)
            {
                return(BadRequest("Count is must"));
            }

            Boolean unitMode = Startup.UnitTestMode;

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

            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;
            HttpStatusCode errorCode = HttpStatusCode.OK;

            try
            {
                queryString = @"SELECT [ID]
                            FROM [dbo].[t_event_habit] WHERE [Name] = N'" + vm.Name + "'";

                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);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        Int32 nDuplicatedID = -1;
                        while (reader.Read())
                        {
                            nDuplicatedID = reader.GetInt32(0);
                            break;
                        }
                        strErrMsg = "Object with name already exists: " + nDuplicatedID.ToString();
                        errorCode = HttpStatusCode.BadRequest;
                        throw new Exception(strErrMsg);
                    }
                    else
                    {
                        reader.Dispose();
                        reader = null;

                        cmd.Dispose();
                        cmd = null;

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

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

                        Int32 nRst = await cmd.ExecuteNonQueryAsync();

                        nNewID = (Int32)idparam.Value;

                        // Then go to the details.
                        foreach (var detail in listDetails)
                        {
                            EventHabitDetail detailVM = new EventHabitDetail();
                            detailVM.HabitID   = nNewID;
                            detailVM.StartDate = detail.StartTimePoint;
                            detailVM.EndDate   = detail.EndTimePoint;

                            queryString = HIHDBUtility.Event_GetEventHabitDetailInsertString();

                            cmd.Dispose();
                            cmd = null;
                            cmd = new SqlCommand(queryString, conn, tran);
                            HIHDBUtility.Event_BindEventHabitDetailInsertParameter(cmd, detailVM);
                            await cmd.ExecuteNonQueryAsync();

                            vm.Details.Add(detailVM);
                        }

                        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.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));
        }