public async Task <IActionResult> Delete([FromRoute] int id)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(GetConnectionString());

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                var objApiSecurity = await context.AdefHelpDeskApiSecurity.SingleOrDefaultAsync(x => x.Id == id);

                if (objApiSecurity == null)
                {
                    return(NotFound());
                }

                context.AdefHelpDeskApiSecurity.Remove(objApiSecurity);
                await context.SaveChangesAsync();

                // Log to the System Log
                Log.InsertSystemLog(
                    GetConnectionString(),
                    Constants.WebAPIAccountDeleted,
                    this.User.Identity.Name,
                    $"({this.User.Identity.Name}) Deleted Username: {objApiSecurity.Username}");
            }

            return(NoContent());
        }
        public List <ApiSecurityDTO> Get()
        {
            // Collection to hold ApiSecuritys
            List <ApiSecurityDTO> colApiSecurityDTOs = new List <ApiSecurityDTO>();

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

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();

            optionsBuilder.UseSqlServer(GetConnectionString());

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                // This returns all ApiSecuritys in the database
                colApiSecurityDTOs = (from objApiSecurity in context.AdefHelpDeskApiSecurity
                                      select new ApiSecurityDTO
                {
                    id = objApiSecurity.Id,
                    username = objApiSecurity.Username,
                    contactName = objApiSecurity.ContactName,
                    contactCompany = objApiSecurity.ContactCompany,
                    contactWebsite = objApiSecurity.ContactWebsite,
                    contactEmail = objApiSecurity.ContactEmail,
                    contactPhone = objApiSecurity.ContactPhone,
                    password = objApiSecurity.Password,
                    isActive = objApiSecurity.IsActive,
                }).OrderBy(x => x.username).ToList();
            }

            return(colApiSecurityDTOs);
        }
Beispiel #3
0
        public IActionResult Delete([FromRoute] int id)
        {
            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.StatusMessage = "Failure";
            objDTOStatus.Success       = false;

            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }
            var result = DeleteUser(id, _userManager, GetConnectionString(), this.User.Identity.Name);

            if (result != "")
            {
                objDTOStatus.Success       = false;
                objDTOStatus.StatusMessage = result;
                return(Ok(objDTOStatus));
            }
            else
            {
                objDTOStatus.Success       = true;
                objDTOStatus.StatusMessage = "";
                return(Ok(objDTOStatus));
            }
        }
Beispiel #4
0
        public DTOSMTPSetting SMTPSettings()
        {
            // Create DTOSMTPSetting
            DTOSMTPSetting objDTOSMTPSetting = new DTOSMTPSetting();

            objDTOSMTPSetting.smtpValid  = true;
            objDTOSMTPSetting.smtpStatus = "";

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

            // Get Settings
            GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());

            // Set Settings
            objDTOSMTPSetting.smtpServer         = objGeneralSettings.SMTPServer;
            objDTOSMTPSetting.smtpAuthentication = objGeneralSettings.SMTPAuthendication;
            objDTOSMTPSetting.smtpFromEmail      = objGeneralSettings.SMTPFromEmail;
            objDTOSMTPSetting.smtpSecure         = (objGeneralSettings.SMTPSecure) ? "True" : "False";
            objDTOSMTPSetting.smtpUserName       = objGeneralSettings.SMTPUserName;
            objDTOSMTPSetting.smtpPassword       = Constants.NONPassword; // Never return the actual password to the client

            return(objDTOSMTPSetting);
        }
        public IActionResult Index([FromBody] RegisterDTO Register)
        {
            // RegisterStatus to return
            RegisterStatus objRegisterStatus = new RegisterStatus();

            objRegisterStatus.status       = "Registration Failure";
            objRegisterStatus.isSuccessful = false;

            // Only allow Registration for non-Super Admins if it is turned on in Settings
            GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());

            if (
                (!objGeneralSettings.AllowRegistration) &&
                (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString())))
            {
                objRegisterStatus.status       = "Registration is not allowed for non-Administrators.";
                objRegisterStatus.isSuccessful = false;
            }
            else
            {
                string strCurrentHostLocation = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
                objRegisterStatus = RegisterUser(Register, GetConnectionString(), _hostEnvironment, _userManager, _signInManager, strCurrentHostLocation, false, true);
            }

            return(Ok(objRegisterStatus));
        }
Beispiel #6
0
        public DTONode SystemFiles()
        {
            // Must be a Super User to proceed
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(new DTONode());
            }

            return(SystemFilesMethod(_hostEnvironment, _SystemFiles));
        }
        public IActionResult Delete([FromRoute] int id)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            return(Ok(DeleteRole(id, GetConnectionString())));
        }
        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);
        }
Beispiel #9
0
        public SystemLogSearchResult SystemLogs([FromBody] SearchParameters searchData)
        {
            SystemLogSearchResult objSystemLogSearchResult = new SystemLogSearchResult();

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

            return(SystemLogsMethod(searchData, this.User.Identity.Name, GetConnectionString()));
        }
Beispiel #10
0
        public DTOResponse ReturnContent([FromBody] DTONode paramDTONode)
        {
            DTOResponse objDTOResponse = new DTOResponse();

            // Must be a Super User to proceed
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                objDTOResponse.isSuccess = false;
                objDTOResponse.message   = "Must be a Super User to proceed";
                return(objDTOResponse);
            }

            return(GetFileContentMethod(paramDTONode, _SystemFiles));
        }
        public IActionResult Post([FromBody] RoleDTO RoleDTO)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(Ok(CreateRole(RoleDTO, GetConnectionString())));
        }
        public DTOApplicationSetting SetSettings([FromBody] DTOApplicationSetting FileUploadSetting)
        {
            DTOApplicationSetting objDTOApplicationSetting = new DTOApplicationSetting();

            objDTOApplicationSetting.valid  = true;
            objDTOApplicationSetting.status = "";

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

            // Get GeneralSettings
            GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());

            if (FileUploadSetting.uploadPermission == null)
            {
                FileUploadSetting.uploadPermission = "False";
            }

            // Update ****************************

            try
            {
                objGeneralSettings.UpdateApplicationName(GetConnectionString(), FileUploadSetting.applicationName);
                objGeneralSettings.UpdateFileUploadPath(GetConnectionString(), FileUploadSetting.fileUploadPath);
                objGeneralSettings.UpdateStorageFileType(GetConnectionString(), FileUploadSetting.storagefiletype);
                if (FileUploadSetting.storagefiletype == "AzureStorage")
                {
                    objGeneralSettings.UpdateAzureStorageConnection(GetConnectionString(), FileUploadSetting.azurestorageconnection);
                }
                objGeneralSettings.UpdateUploadPermission(GetConnectionString(), FileUploadSetting.uploadPermission);
                objGeneralSettings.UpdateAllowRegistration(GetConnectionString(), FileUploadSetting.allowRegistration);
                objGeneralSettings.UpdateVerifiedRegistration(GetConnectionString(), FileUploadSetting.verifiedRegistration);
            }
            catch (Exception ex)
            {
                objDTOApplicationSetting.valid  = false;
                objDTOApplicationSetting.status = ex.GetBaseException().Message;
                return(objDTOApplicationSetting);
            }

            return(objDTOApplicationSetting);
        }
Beispiel #13
0
        public IActionResult CreateUser([FromBody] DTOUser DTOUser)
        {
            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.StatusMessage = "Failure";
            objDTOStatus.Success       = false;

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

            string CurrentHostLocation = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";

            return(Ok(CreateUserMethod(DTOUser, _hostEnvironment, _userManager, _signInManager, GetConnectionString(), CurrentHostLocation, this.User.Identity.Name)));
        }
        public IActionResult Put([FromRoute] int id, [FromBody] CategoryNode categoryNode)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != categoryNode.Id)
            {
                return(BadRequest());
            }

            return(Ok(UpdateCategory(id, categoryNode, GetConnectionString())));
        }
        public DTOApplicationSetting GetSettings()
        {
            // Create DTOApplicationSetting
            DTOApplicationSetting objDTOApplicationSetting = new DTOApplicationSetting();

            objDTOApplicationSetting.valid  = true;
            objDTOApplicationSetting.status = "";

            try
            {
                // Get Settings
                GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());

                // Set Setting
                objDTOApplicationSetting.applicationName   = objGeneralSettings.ApplicationName;
                objDTOApplicationSetting.uploadPermission  = objGeneralSettings.UploadPermission;
                objDTOApplicationSetting.allowRegistration = objGeneralSettings.AllowRegistration;
                objDTOApplicationSetting.swaggerWebAddress = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/swagger";

                // Only return the following if a SuperUser is calling this method
                if (UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
                {
                    objDTOApplicationSetting.verifiedRegistration = objGeneralSettings.VerifiedRegistration;
                    objDTOApplicationSetting.applicationGUID      = objGeneralSettings.ApplicationGUID;

                    objDTOApplicationSetting.storagefiletype        = objGeneralSettings.StorageFileType;
                    objDTOApplicationSetting.azurestorageconnection = objGeneralSettings.AzureStorageConnection;

                    // For fileUploadPath we use special code to potentially get the default file path
                    objDTOApplicationSetting.fileUploadPath = GetFilesPath(_DefaultFilesPath, GetConnectionString());
                }
            }
            catch (Exception ex)
            {
                objDTOApplicationSetting.valid  = false;
                objDTOApplicationSetting.status = ex.GetBaseException().Message;
                return(objDTOApplicationSetting);
            }

            return(objDTOApplicationSetting);
        }
        public DTOStatus UpdateDatabase()
        {
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.Success = true;

            // Must be a Super User to proceed
            if (UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                // Run update scripts
                objDTOStatus = RunUpdateScripts(NewDatabaseVersion, _hostEnvironment, GetConnectionString());
            }
            else
            {
                objDTOStatus.Success       = false;
                objDTOStatus.StatusMessage = "Must be a Super User to proceed";
            }

            // Return the result
            return(objDTOStatus);
        }
Beispiel #17
0
        public IActionResult Index([FromForm] ICollection <IFormFile> files)
        {
            // Must be a Super User to proceed
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(Ok());
            }

            if (!Request.HasFormContentType)
            {
                return(BadRequest());
            }

            // Retrieve data from Form
            var form = Request.Form;

            // Retrieve SelectedFolder
            string SelectedFolder = form["selectedFolder"].First();

            // Process all Files
            foreach (var file in form.Files)
            {
                // Process file
                using (var readStream = file.OpenReadStream())
                {
                    var filename = file.FileName.Replace("\"", "").ToString();

                    filename = Path.Combine(_SystemFiles, SelectedFolder, filename).Replace(@"\", @"/");

                    //Save file to harddrive
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }
            }

            return(Ok());
        }
Beispiel #18
0
        public IActionResult Put([FromRoute] int id, [FromBody] DTOUser DTOUser)
        {
            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.StatusMessage = "Failure";
            objDTOStatus.Success       = false;

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

            if (id != DTOUser.userId)
            {
                return(BadRequest());
            }

            return(Ok(UpdateUser(id, DTOUser, _userManager, GetConnectionString(), this.User.Identity.Name)));
        }
Beispiel #19
0
        public DTOSMTPSetting SMTPSetting([FromBody] DTOSMTPSetting SMTPSetting)
        {
            DTOSMTPSetting objDTOSMTPSetting = new DTOSMTPSetting();

            objDTOSMTPSetting.smtpValid  = true;
            objDTOSMTPSetting.smtpStatus = "Settings Updated";

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

            // Get Update Type (Save/Test)
            string strUpdateType = SMTPSetting.updateType;

            // Get GeneralSettings
            GeneralSettings objGeneralSettings = new GeneralSettings(GetConnectionString());

            #region Validation ****************************
            if ((SMTPSetting.smtpServer == null) || (SMTPSetting.smtpServer.Trim().Length < 1))
            {
                objDTOSMTPSetting.smtpValid  = false;
                objDTOSMTPSetting.smtpStatus = "SMTP Server is not valid";
                return(objDTOSMTPSetting);
            }

            if ((SMTPSetting.smtpAuthentication == null) || (SMTPSetting.smtpAuthentication.Trim().Length < 1))
            {
                objDTOSMTPSetting.smtpValid  = false;
                objDTOSMTPSetting.smtpStatus = "SMTP Authentication is not valid";
                return(objDTOSMTPSetting);
            }

            if ((SMTPSetting.smtpFromEmail == null) || (SMTPSetting.smtpFromEmail.Trim().Length < 1))
            {
                objDTOSMTPSetting.smtpValid  = false;
                objDTOSMTPSetting.smtpStatus = "From Email is not valid";
                return(objDTOSMTPSetting);
            }

            EmailValidation objEmailValidation = new EmailValidation();
            if (!objEmailValidation.IsValidEmail(SMTPSetting.smtpFromEmail))
            {
                objDTOSMTPSetting.smtpValid  = false;
                objDTOSMTPSetting.smtpStatus = "From Email is not a valid email";
                return(objDTOSMTPSetting);
            }
            #endregion

            // Update ****************************

            try
            {
                objGeneralSettings.UpdateSMTPServer(GetConnectionString(), SMTPSetting.smtpServer);
                objGeneralSettings.UpdateSMTPAuthentication(GetConnectionString(), SMTPSetting.smtpAuthentication);
                objGeneralSettings.UpdateSMTPFromEmail(GetConnectionString(), SMTPSetting.smtpFromEmail);
                objGeneralSettings.UpdateSMTPSecure(GetConnectionString(), (SMTPSetting.smtpSecure == "True") ? true: false);
                objGeneralSettings.UpdateSMTPUserName(GetConnectionString(), SMTPSetting.smtpUserName);

                // Only set Password if it has been updated
                // The default non-password is
                if (SMTPSetting.smtpPassword.Replace(Constants.NONPassword, "") != "")
                {
                    objGeneralSettings.UpdateSMTPPassword(GetConnectionString(), SMTPSetting.smtpPassword);
                }
            }
            catch (Exception ex)
            {
                objDTOSMTPSetting.smtpValid  = false;
                objDTOSMTPSetting.smtpStatus = ex.GetBaseException().Message;
                return(objDTOSMTPSetting);
            }

            // Test Email  ****************************
            if (strUpdateType == "Test")
            {
                // Send Test Email
                objDTOSMTPSetting.smtpStatus = Email.SendMail(
                    false,
                    GetConnectionString(),
                    SMTPSetting.smtpFromEmail,
                    "ADefHelpDesk Administrator",
                    "", "",
                    SMTPSetting.smtpFromEmail,
                    "SMTP Test",
                    "ADefHelpDesk SMTP Test Email",
                    $"This is a ADefHelpDesk SMTP Test Email from: {this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}");

                if (objDTOSMTPSetting.smtpStatus != "")
                {
                    // There was some sort of error - return it
                    objDTOSMTPSetting.smtpValid = false;
                    return(objDTOSMTPSetting);
                }
                else
                {
                    objDTOSMTPSetting.smtpStatus = "Settings Updated - Test Email Sent";
                }
            }

            return(objDTOSMTPSetting);
        }
Beispiel #20
0
        public IActionResult Index()
        {
            // Must be a Super User to proceed
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(Ok());
            }

            string FileNameAndPath = _SystemFiles + $@"\UpgradePackage.zip";
            string WebConfigOrginalFileNameAndPath = _hostEnvironment.ContentRootPath + @"\Web.config";
            string WebConfigTempFileNameAndPath    = _hostEnvironment.ContentRootPath + @"\Web.config.txt";

            try
            {
                // Delete file if it exists
                if (System.IO.File.Exists(FileNameAndPath))
                {
                    System.IO.File.Delete(FileNameAndPath);
                }

                // Delete UpgradeProcess directory
                DirectoryInfo UpgradeDirectory = new DirectoryInfo(_UpgradeProcessDirectory);
                if (System.IO.Directory.Exists(_UpgradeProcessDirectory))
                {
                    UpgradeDirectory.Delete(true);
                }

                // Save file
                FormValueProvider formModel;
                using (var stream = System.IO.File.Create(FileNameAndPath))
                {
                    formModel = Request.StreamFile(stream).Result;
                }

                // Unzip files to ProcessDirectory
                ZipFile.ExtractToDirectory(FileNameAndPath, _UpgradeProcessDirectory);

                // *** Check upgrade
                // Get current version
                DTOVersion objVersion = GetDatabaseVersion();

                // Examine the manifest file
                objVersion = ReadManifest(objVersion);

                try
                {
                    if (objVersion.ManifestLowestVersion == "")
                    {
                        // Delete the files
                        if (System.IO.Directory.Exists(_UpgradeProcessDirectory))
                        {
                            UpgradeDirectory.Delete(true);
                        }
                        return(Ok("Error: Cound not find manifest"));
                    }
                }
                catch (Exception ex)
                {
                    // Delete the files
                    if (System.IO.Directory.Exists(_UpgradeProcessDirectory))
                    {
                        UpgradeDirectory.Delete(true);
                    }
                    return(Ok(ex.ToString()));
                }

                // Show error if needed and delete upgrade files
                if
                (
                    (ConvertToInteger(objVersion.VersionNumber) > ConvertToInteger(objVersion.ManifestHighestVersion)) ||
                    (ConvertToInteger(objVersion.VersionNumber) < ConvertToInteger(objVersion.ManifestLowestVersion))
                )
                {
                    // Delete the files
                    if (System.IO.Directory.Exists(_UpgradeProcessDirectory))
                    {
                        UpgradeDirectory.Delete(true);
                    }

                    // Return the error response
                    return(Ok(objVersion.ManifestFailure));
                }

                // Temporarily rename the web.config file
                // to release the locks on any assemblies
                System.IO.File.Copy(WebConfigOrginalFileNameAndPath, WebConfigTempFileNameAndPath);
                System.IO.File.Delete(WebConfigOrginalFileNameAndPath);

                // Give the site time to release locks on the assemblies
                Task.Delay(2000).Wait(); // Wait 2 seconds with blocking

                // Rename the temp web.config file back to web.config
                // so the site will be active again
                System.IO.File.Copy(WebConfigTempFileNameAndPath, WebConfigOrginalFileNameAndPath);
                System.IO.File.Delete(WebConfigTempFileNameAndPath);

                return(Ok(objVersion.ManifestSuccess));
            }
            catch (Exception ex1)
            {
                try
                {
                    // Rename the temp web.config file back to web.config
                    // so the site will be active again
                    System.IO.File.Copy(WebConfigTempFileNameAndPath, WebConfigOrginalFileNameAndPath);
                    System.IO.File.Delete(WebConfigTempFileNameAndPath);
                }
                catch (Exception ex2)
                {
                    return(Ok(ex2.Message));
                }

                return(Ok(ex1.Message));
            }
        }
        public async Task <IActionResult> Post([FromBody] ApiSecurityDTO ApiSecurityDTO)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.StatusMessage = "Failure";
            objDTOStatus.Success       = false;

            #region Validate
            if (
                (ApiSecurityDTO.username == null || ApiSecurityDTO.username == "") ||
                (ApiSecurityDTO.password == null || ApiSecurityDTO.password == "")
                )
            {
                objDTOStatus.StatusMessage = $"Error: A Username and Password are required.";
                objDTOStatus.Success       = false;
                return(Ok(objDTOStatus));
            }

            if (ApiSecurityDTO.password.Trim().Length < 5)
            {
                objDTOStatus.StatusMessage = $"Error: A password longer than 5 characters is required.";
                objDTOStatus.Success       = false;
                return(Ok(objDTOStatus));
            }
            #endregion

            try
            {
                var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
                optionsBuilder.UseSqlServer(GetConnectionString());

                using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                {
                    // Check for duplicate Username
                    var existingApiSecurity = await context.AdefHelpDeskApiSecurity.SingleOrDefaultAsync(x => x.Username == ApiSecurityDTO.username);

                    if (existingApiSecurity != null)
                    {
                        objDTOStatus.StatusMessage = $"Error: The username {ApiSecurityDTO.username} is already used";
                        objDTOStatus.Success       = false;
                        return(Ok(objDTOStatus));
                    }

                    var newApiSecurityDTO = new AdefHelpDeskApiSecurity();

                    newApiSecurityDTO.Username       = ApiSecurityDTO.username.Trim();
                    newApiSecurityDTO.Password       = ApiSecurityDTO.password.Trim();
                    newApiSecurityDTO.ContactName    = ApiSecurityDTO.contactName;
                    newApiSecurityDTO.ContactCompany = ApiSecurityDTO.contactCompany;
                    newApiSecurityDTO.ContactWebsite = ApiSecurityDTO.contactWebsite;
                    newApiSecurityDTO.ContactEmail   = ApiSecurityDTO.contactEmail;
                    newApiSecurityDTO.ContactPhone   = ApiSecurityDTO.contactPhone;
                    newApiSecurityDTO.IsActive       = ApiSecurityDTO.isActive;

                    context.AdefHelpDeskApiSecurity.Add(newApiSecurityDTO);
                    await context.SaveChangesAsync();

                    ApiSecurityDTO.id = newApiSecurityDTO.Id;

                    // Log to the System Log
                    Log.InsertSystemLog(
                        GetConnectionString(),
                        Constants.WebAPIAccountCreated,
                        this.User.Identity.Name,
                        $"({this.User.Identity.Name}) Created Username: {newApiSecurityDTO.Username}");
                }

                objDTOStatus.StatusMessage = "";
                objDTOStatus.Success       = true;
            }
            catch (Exception ex)
            {
                objDTOStatus.StatusMessage = ex.GetBaseException().Message;
                objDTOStatus.Success       = false;
                return(Ok(objDTOStatus));
            }

            return(Ok(objDTOStatus));
        }
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] ApiSecurityDTO ApiSecurityDTO)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != ApiSecurityDTO.id)
            {
                return(BadRequest());
            }

            // Status to return
            DTOStatus objDTOStatus = new DTOStatus();

            objDTOStatus.StatusMessage = "Failure";
            objDTOStatus.Success       = false;

            #region Validate
            if (ApiSecurityDTO.password == null || ApiSecurityDTO.password == "")
            {
                objDTOStatus.StatusMessage = $"Error: A Password is required.";
                objDTOStatus.Success       = false;
                return(Ok(objDTOStatus));
            }

            if (ApiSecurityDTO.password.Trim().Length < 5)
            {
                objDTOStatus.StatusMessage = $"Error: A password longer than 5 characters is required.";
                objDTOStatus.Success       = false;
                return(Ok(objDTOStatus));
            }
            #endregion

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
            optionsBuilder.UseSqlServer(GetConnectionString());

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                var existingApiSecurity = await context.AdefHelpDeskApiSecurity.SingleOrDefaultAsync(x => x.Id == id);

                if (existingApiSecurity == null)
                {
                    return(NotFound());
                }

                // Update the ApiSecurity
                existingApiSecurity.ContactName    = ApiSecurityDTO.contactName;
                existingApiSecurity.ContactCompany = ApiSecurityDTO.contactCompany;
                existingApiSecurity.ContactWebsite = ApiSecurityDTO.contactWebsite;
                existingApiSecurity.ContactEmail   = ApiSecurityDTO.contactEmail;
                existingApiSecurity.ContactPhone   = ApiSecurityDTO.contactPhone;
                existingApiSecurity.IsActive       = ApiSecurityDTO.isActive;

                if (ApiSecurityDTO.password != null)
                {
                    if (ApiSecurityDTO.password.Trim().Length > 1)
                    {
                        existingApiSecurity.Password = ApiSecurityDTO.password.Trim();
                    }
                }

                context.Entry(existingApiSecurity).State = EntityState.Modified;

                try
                {
                    await context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    objDTOStatus.StatusMessage = ex.GetBaseException().Message;
                    objDTOStatus.Success       = false;
                    return(Ok(objDTOStatus));
                }
                catch (Exception ex)
                {
                    objDTOStatus.StatusMessage = ex.GetBaseException().Message;
                    objDTOStatus.Success       = false;
                    return(Ok(objDTOStatus));
                }

                // Log to the System Log
                Log.InsertSystemLog(
                    GetConnectionString(),
                    Constants.WebAPIAccountUpdated,
                    this.User.Identity.Name,
                    $"({this.User.Identity.Name}) Updated Username: {ApiSecurityDTO.username}");
            }

            objDTOStatus.StatusMessage = "";
            objDTOStatus.Success       = true;

            return(Ok(objDTOStatus));
        }