public LogSearchResult Logs([FromBody] SearchParameters searchData)
        {
            LogSearchResult objLogSearchResult = new LogSearchResult();

            objLogSearchResult.LogList = new List <DTOLog>();

            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                objLogSearchResult.errorMessage = "Must be a Super Administrator to call this Method";
                return(objLogSearchResult);
            }

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(GetConnectionString());

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                int intTaskId = Convert.ToInt32(searchData.searchString);

                var QueryResult = (from Log in context.AdefHelpDeskLog
                                   where Log.TaskId == intTaskId
                                   select Log).OrderByDescending(l => l.LogId)
                                  .Skip(searchData.rowsPerPage * (searchData.pageNumber - 1))
                                  .Take(searchData.rowsPerPage).ToList();

                List <DTOLog> colDTOLog = new List <DTOLog>();

                foreach (var item in QueryResult)
                {
                    // Get user
                    DTOUser objDTOUSer = UtilitySecurity.UserFromUserId(item.UserId, GetConnectionString());

                    // Create Log
                    DTOLog objDTOLog = new DTOLog();

                    objDTOLog.LogID          = item.LogId;
                    objDTOLog.TaskID         = item.TaskId;
                    objDTOLog.LogDescription = item.LogDescription;
                    objDTOLog.UserName       = (objDTOUSer != null) ? objDTOUSer.userName : "******";
                    objDTOLog.DateCreated    = item.DateCreated.ToShortDateString() + ' ' + item.DateCreated.ToShortTimeString();

                    colDTOLog.Add(objDTOLog);
                }

                objLogSearchResult.LogList      = colDTOLog;
                objLogSearchResult.totalRows    = context.AdefHelpDeskLog.Where(x => x.TaskId == intTaskId).Count();
                objLogSearchResult.errorMessage = string.Empty;
            }

            return(objLogSearchResult);
        }
        public static DTOTask GetTask(DTOTask paramDTOTask, int intUserID, bool IsAdministrator, string DefaultConnection, string strCurrentUser, bool IsAuthenticated)
        {
            DTOTask objTask = new DTOTask();

            objTask.taskId = -1; // Task Not found
            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(DefaultConnection);

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                AdefHelpDeskTasks Result;

                // Perform Search
                if (paramDTOTask.ticketPassword != "")
                {
                    // Using ticketPassword
                    Result = (from task in context.AdefHelpDeskTasks
                              .Include(details => details.AdefHelpDeskTaskDetails)
                              .Include(categories => categories.AdefHelpDeskTaskCategories)
                              where task.TicketPassword == paramDTOTask.ticketPassword
                              where task.TaskId == paramDTOTask.taskId
                              select task).FirstOrDefault();

                    var myresult = Result.TaskId;
                }
                else
                {
                    // Using TaskId
                    Result = (from task in context.AdefHelpDeskTasks
                              .Include(details => details.AdefHelpDeskTaskDetails)
                              .Include(categories => categories.AdefHelpDeskTaskCategories)
                              where task.TaskId == paramDTOTask.taskId
                              select task).FirstOrDefault();

                    // Must be a Administrator or Requester to only use TaskId
                    if (!IsAdministrator)
                    {
                        if (!(Result.RequesterUserId == intUserID))
                        {
                            if (!UtilitySecurity.IsAdministrator(strCurrentUser, DefaultConnection))
                            {
                                return(objTask);
                            }
                        }
                    }
                }

                if (Result == null)
                {
                    return(objTask);
                }

                objTask.taskId              = Result.TaskId;
                objTask.status              = Result.Status;
                objTask.assignedRoleId      = Result.AssignedRoleId;
                objTask.createdDate         = Result.CreatedDate.ToShortDateString();
                objTask.description         = Result.Description;
                objTask.dueDate             = (Result.DueDate != null) ? Result.DueDate.Value.ToShortDateString() : "";
                objTask.estimatedCompletion = (Result.EstimatedCompletion != null) ? Result.EstimatedCompletion.Value.ToShortDateString() : "";
                objTask.estimatedHours      = Result.EstimatedHours;
                objTask.estimatedStart      = (Result.EstimatedStart != null) ? Result.EstimatedStart.Value.ToShortDateString() : "";
                objTask.portalId            = Result.PortalId;
                objTask.priority            = Result.Priority;
                objTask.requesterEmail      = Result.RequesterEmail;
                objTask.requesterName       = Result.RequesterName;
                objTask.requesterPhone      = Result.RequesterPhone;
                objTask.requesterUserId     = Result.RequesterUserId;
                objTask.ticketPassword      = Result.TicketPassword;

                // Set Requester Name
                if (Result.RequesterUserId > 0)
                {
                    var User = UtilitySecurity.UserFromUserId(Result.RequesterUserId, DefaultConnection);
                    objTask.requesterName = $"{User.firstName} {User.lastName}";
                }
                else
                {
                    objTask.requesterName = Result.RequesterName;
                }

                // Add Task Categories
                objTask.selectedTreeNodes = new List <int>();
                foreach (var itemTaskCategory in Result.AdefHelpDeskTaskCategories)
                {
                    objTask.selectedTreeNodes.Add(itemTaskCategory.CategoryId);
                }

                // Add Task Details
                objTask.colDTOTaskDetail = new List <DTOTaskDetail>();

                // Get all TaskDetails
                var TaskDetails = Result.AdefHelpDeskTaskDetails.OrderByDescending(x => x.DetailId);

                // Non-Admins can only see "Comment - Visible"
                if (!IsAdministrator)
                {
                    TaskDetails = TaskDetails.Where(x => x.DetailType == "Comment - Visible").OrderByDescending(x => x.DetailId);
                }
                else
                {
                    TaskDetails = TaskDetails.OrderByDescending(x => x.DetailId);
                }

                foreach (var itemTaskDetail in TaskDetails)
                {
                    DTOTaskDetail objDTOTaskDetail = new DTOTaskDetail();

                    objDTOTaskDetail.contentType = (itemTaskDetail.ContentType != null) ? itemTaskDetail.ContentType : Constants.TXT;
                    objDTOTaskDetail.description = itemTaskDetail.Description;
                    objDTOTaskDetail.detailId    = itemTaskDetail.DetailId;
                    objDTOTaskDetail.detailType  = itemTaskDetail.DetailType;
                    objDTOTaskDetail.insertDate  = itemTaskDetail.InsertDate.ToLongDateString() + " " + itemTaskDetail.InsertDate.ToLongTimeString();
                    objDTOTaskDetail.startTime   = (itemTaskDetail.StartTime != null) ? itemTaskDetail.StartTime.Value.ToShortDateString() + " " + itemTaskDetail.StartTime.Value.ToShortTimeString() : "";
                    objDTOTaskDetail.stopTime    = (itemTaskDetail.StopTime != null) ? itemTaskDetail.StopTime.Value.ToShortDateString() + " " + itemTaskDetail.StopTime.Value.ToShortTimeString() : "";
                    objDTOTaskDetail.userId      = itemTaskDetail.UserId;
                    objDTOTaskDetail.userName    = UtilitySecurity.UserFromUserId(itemTaskDetail.UserId, DefaultConnection).userName;

                    // Add Attachments
                    objDTOTaskDetail.colDTOAttachment = new List <DTOAttachment>();

                    var AttachmentResults = (from attachment in context.AdefHelpDeskAttachments
                                             where attachment.DetailId == objDTOTaskDetail.detailId
                                             select attachment);

                    foreach (var itemAttachmement in AttachmentResults)
                    {
                        DTOAttachment objDTOAttachment = new DTOAttachment();

                        objDTOAttachment.attachmentID = itemAttachmement.AttachmentId;
                        //objDTOAttachment.attachmentPath = itemAttachmement.AttachmentPath; -- Do not send for security reasons
                        //objDTOAttachment.fileName = itemAttachmement.FileName; -- Do not send for security reasons
                        objDTOAttachment.originalFileName = itemAttachmement.OriginalFileName;
                        objDTOAttachment.userId           = itemAttachmement.UserId.ToString();

                        objDTOTaskDetail.colDTOAttachment.Add(objDTOAttachment);

                        // If file type is .EML it is a Email
                        if (Path.GetExtension(itemAttachmement.OriginalFileName).ToUpper() == Constants.EML)
                        {
                            // Construct path
                            string FullFilePath = Path.Combine(itemAttachmement.AttachmentPath, itemAttachmement.FileName).Replace(@"\", @"/");
                            // Set Email Description and ContentType
                            SetEmailContents(itemAttachmement.FileName, itemAttachmement.AttachmentId, FullFilePath, DefaultConnection, ref objDTOTaskDetail);
                            objDTOTaskDetail.contentType = Constants.EML.Replace(".", "");
                        }
                    }

                    objTask.colDTOTaskDetail.Add(objDTOTaskDetail);
                }
            }

            #region **** Save to the Log
            if ((objTask.taskId != null) && (objTask.taskId != -1))
            {
                string strLogUserName = (IsAuthenticated) ? strCurrentUser : "******";
                Log.InsertLog(DefaultConnection, Convert.ToInt32(objTask.taskId), intUserID, $"{strLogUserName} viewed ticket.");
            }
            #endregion

            return(objTask);
        }
        // Private Methods

        #region public static TaskSearchResult SearchTasks(SearchTaskParameters searchData, int intUserId, int iSAdministrator, string DefaultConnection)
        public static TaskSearchResult SearchTasks(SearchTaskParameters searchData, int intUserId, int iSAdministrator, string DefaultConnection)
        {
            TaskSearchResult objTaskSearchResult = new TaskSearchResult();

            objTaskSearchResult.taskList = new List <DTOTask>();
            List <AdefHelpDeskRoles> AllRoles = new List <AdefHelpDeskRoles>();
            var resultTable = new DataTable();

            //If searchData.rowsPerPage = 0 set it to 1
            if (searchData.rowsPerPage == 0)
            {
                searchData.rowsPerPage = 1;
            }

            //If searchData.pageNumber = 0 set it to 1
            if (searchData.pageNumber == 0)
            {
                searchData.pageNumber = 1;
            }

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(DefaultConnection);

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                // Get all possible roles to reduce database calls later
                AllRoles = (from role in context.AdefHelpDeskRoles
                            select role).ToList();
            }

            using (var conn = new SqlConnection(DefaultConnection))
            {
                using (var cmd = new SqlCommand())
                {
                    cmd.CommandText = "[spSearchTasks]";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection  = conn;

                    cmd.Parameters.AddWithValue("@paramIsAdmin", iSAdministrator);
                    cmd.Parameters.AddWithValue("@paramUserId", intUserId);
                    cmd.Parameters.AddWithValue("@paramSearchText", searchData.searchText ?? "");
                    cmd.Parameters.AddWithValue("@paramStatus", searchData.status ?? "");
                    cmd.Parameters.AddWithValue("@paramPriority", searchData.priority ?? "");
                    cmd.Parameters.AddWithValue("@paramCreatedDate", searchData.createdDate ?? "");
                    cmd.Parameters.AddWithValue("@paramDueDate", searchData.dueDate ?? "");
                    cmd.Parameters.AddWithValue("@paramAssignedRoleId", searchData.assignedRoleId ?? "");
                    cmd.Parameters.AddWithValue("@paramSelectedTreeNodes", String.Join(",", searchData.selectedTreeNodes));
                    cmd.Parameters.AddWithValue("@paramSortOrder", searchData.sortOrder ?? "");
                    cmd.Parameters.AddWithValue("@paramSortField", searchData.sortField ?? "");
                    cmd.Parameters.AddWithValue("@paramRowsPerPage", searchData.rowsPerPage);
                    cmd.Parameters.AddWithValue("@paramPageNumber", searchData.pageNumber);

                    SqlParameter parTotalCount = new SqlParameter("@paramTotalCount", SqlDbType.Int);
                    parTotalCount.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(parTotalCount);

                    using (var adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(resultTable);
                    }

                    objTaskSearchResult.totalRows = Convert.ToInt32(parTotalCount.Value);
                }
            }

            List <DTOTask> colDTOTasks = new List <DTOTask>();

            foreach (System.Data.DataRow item in resultTable.Rows)
            {
                DTOTask objDTOTask = new DTOTask();

                objDTOTask.taskId              = Convert.ToInt32(item.ItemArray[0]);
                objDTOTask.portalId            = Convert.ToInt32(item.ItemArray[1]);
                objDTOTask.description         = Convert.ToString(item.ItemArray[2]);
                objDTOTask.status              = Convert.ToString(item.ItemArray[3]);
                objDTOTask.priority            = Convert.ToString(item.ItemArray[4]);
                objDTOTask.createdDate         = Convert.ToDateTime(item.ItemArray[5]).ToShortDateString();
                objDTOTask.estimatedStart      = (item.ItemArray[6].ToString() != "") ? Convert.ToDateTime(item.ItemArray[6]).ToShortDateString() : "";
                objDTOTask.estimatedCompletion = (item.ItemArray[7].ToString() != "") ? Convert.ToDateTime(item.ItemArray[7]).ToShortDateString() : "";
                objDTOTask.dueDate             = (item.ItemArray[8].ToString() != "") ? Convert.ToDateTime(item.ItemArray[8]).ToShortDateString() : "";
                objDTOTask.assignedRoleId      = Convert.ToInt32(item.ItemArray[9]);
                objDTOTask.ticketPassword      = Convert.ToString(item.ItemArray[10]);
                objDTOTask.requesterUserId     = Convert.ToInt32(item.ItemArray[11]);
                objDTOTask.requesterName       = Convert.ToString(item.ItemArray[12]);
                objDTOTask.requesterEmail      = Convert.ToString(item.ItemArray[13]);
                objDTOTask.requesterPhone      = Convert.ToString(item.ItemArray[14]);
                if (item.ItemArray[15].ToString() != "")
                {
                    objDTOTask.estimatedHours = Convert.ToInt32(item.ItemArray[15]);
                }

                // Set Requester Name
                if (objDTOTask.requesterUserId > 0)
                {
                    var User = UtilitySecurity.UserFromUserId(objDTOTask.requesterUserId.Value, DefaultConnection);
                    objDTOTask.requesterName = $"{User.firstName} {User.lastName}";
                }
                else
                {
                    objDTOTask.requesterName = objDTOTask.requesterName;
                }

                // Set AssignedRoleName
                var objUserRole = AllRoles.Where(x => x.Id == objDTOTask.assignedRoleId).FirstOrDefault();
                if (objUserRole != null)
                {
                    objDTOTask.assignedRoleName = objUserRole.RoleName;
                }
                else
                {
                    objDTOTask.assignedRoleName = "[Unassigned]";
                }

                colDTOTasks.Add(objDTOTask);
            }

            objTaskSearchResult.taskList     = colDTOTasks;
            objTaskSearchResult.errorMessage = string.Empty;

            return(objTaskSearchResult);
        }