예제 #1
0
        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            ApplicationConfigurationViewModel appConfig = null;
            EmailConfiguration emailConfig = new EmailConfiguration();

            appConfig             = appConfigRepo.GetAppConfigByNameNonAsync("SMTP_URL", "Y");
            emailConfig.Host      = appConfig.AppConfigValue;
            appConfig             = appConfigRepo.GetAppConfigByNameNonAsync("SMTP_UN", "Y");
            emailConfig.UserName  = appConfig.AppConfigValue;
            appConfig             = appConfigRepo.GetAppConfigByNameNonAsync("SMTP_PWD", "Y");
            emailConfig.Password  = CustomUtils.DecodeFromBase64(appConfig.AppConfigValue);
            appConfig             = appConfigRepo.GetAppConfigByNameNonAsync("SMTP_PORT", "Y");
            emailConfig.Port      = Int32.Parse(appConfig.AppConfigValue);
            appConfig             = appConfigRepo.GetAppConfigByNameNonAsync("SMTP_ENABLE_SSL", "Y");
            emailConfig.EnableSSL = bool.Parse(appConfig.AppConfigValue);

            var client = new SmtpClient(emailConfig.Host, emailConfig.Port)
            {
                Credentials = new NetworkCredential(emailConfig.UserName, emailConfig.Password),
                EnableSsl   = emailConfig.EnableSSL
            };

            return(client.SendMailAsync(
                       new MailMessage(emailConfig.UserName, email, subject, htmlMessage)
            {
                IsBodyHtml = true
            }
                       ));
        }
예제 #2
0
        public async Task <IActionResult> GetReport()
        {
            var type   = TempData["type"];
            var report = new StiReport();

            if (type.Equals("CMR"))
            {
                ApplicationConfigurationViewModel appConfig = null;
                appConfig = await appConfigRepo.GetAppConfigByName("MRXPassword", "Y");

                if (appConfig != null && appConfig.AppConfigValue != null)
                {
                    var path = Path.Combine(_hostingEnvironment.WebRootPath, "reports/EquipmentConditionMonitoring.mrx");
                    report.LoadEncryptedReport(path, appConfig.AppConfigValue);
                }
                else
                {
                    throw new CustomException("Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.", "Error", true, "Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.");
                }
            }
            else if (type.Equals("SR"))
            {
                ApplicationConfigurationViewModel appConfig = null;
                appConfig = await appConfigRepo.GetAppConfigByName("MRXPassword", "Y");

                if (appConfig != null && appConfig.AppConfigValue != null)
                {
                    var path = Path.Combine(_hostingEnvironment.WebRootPath, "reports/SummaryReport.mrx");
                    report.LoadEncryptedReport(path, appConfig.AppConfigValue);
                }
                else
                {
                    throw new CustomException("Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.", "Error", true, "Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.");
                }
            }

            string newConnectionString = Configuration.GetConnectionString("SKF.Master");

            report.Dictionary.Databases.Clear();
            report.Dictionary.Databases.Add(new Stimulsoft.Report.Dictionary.StiSqlDatabase("C2Maintenance", newConnectionString));

            if (type.Equals("CMR"))
            {
                report.Dictionary.Variables["@JobEquipmentId"].ValueObject = TempData["jeId"];
            }
            else if (type.Equals("SR"))
            {
                report.Dictionary.Variables["@JobId"].ValueObject        = TempData["jId"];
                report.Dictionary.Variables["@ClientSiteId"].ValueObject = TempData["cId"];
            }
            report.Dictionary.Variables["@LanguageId"].ValueObject = TempData["lId"];

            return(StiNetCoreViewer.GetReportResult(this, report));
        }
예제 #3
0
        public async Task <String> GetAppConfigValue(string AppConfigName, string Status)
        {
            appConfig = await appConfigRepo.GetAppConfigByName(AppConfigName, Status);

            if (appConfig != null)
            {
                return(appConfig.AppConfigValue);
            }
            else
            {
                throw new CustomException("Application Config is missing, Please Contact Support !!!", "Error", true, "Application Configuration is missing for name (" + AppConfigName + ")");
            }
        }
예제 #4
0
        public IActionResult GetApplicationSettingsById(long id)
        {
            ApplicationConfigurationViewModel applicationConfigurationViewModel = _client_ConfigurationRepository.GetApplicationConfigurationId(id);

            if (applicationConfigurationViewModel == null)
            {
                return(Ok(new Application_ResponseWrapper()
                {
                    ResponseCode = "1001", ResponseMessage = "Result not found", Status = "failed"
                }));
            }
            return(Ok(new Application_ResponseWrapper()
            {
                ResponseCode = "0", ResponseMessage = "success", Status = "success", ResponseResult = applicationConfigurationViewModel
            }));
        }
        public async Task <IActionResult> Create([FromBody] ApplicationConfigurationViewModel ccv)
        {
            try
            {
                CurrentUser cUser = new CurrentUser(HttpContext, _configuration);
                ccv.UserId = cUser.UserId;
                var result = await applicationConfigurationRepo.SaveOrUpdate(ccv);

                await auditLogService.LogActivity(cUser.UserId, cUser.HostIP, cUser.SessionId, "ApplicationConfiguration", "Application Configuration Created");

                return(Ok(result));
            }
            catch (CustomException cex)
            {
                var returnObj = new EmaintenanceMessage(cex.Message, cex.Type, cex.IsException, cex.Exception?.ToString());
                return(StatusCode(StatusCodes.Status500InternalServerError, returnObj));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new EmaintenanceMessage(ex.Message)));
            }
        }
        public async Task <IEnumerable <dynamic> > SaveOrUpdate([FromBody] ApplicationConfigurationViewModel ccv)
        {
            string sql = "dbo.EAppSaveAppConfiguration";

            using (var conn = util.MasterCon())
            {
                try
                {
                    return(await(conn.QueryAsync <dynamic>(sql, new
                    {
                        ccv.AppConfigId,
                        ccv.AppConfigName,
                        ccv.AppConfigCode,
                        ccv.AppConfigValue,
                        ccv.Descriptions,
                        ccv.Active,
                        ccv.UserId,
                    }, commandType: CommandType.StoredProcedure)));
                }
                catch (SqlException sqlException)
                {
                    if (sqlException.Number == 2601 || sqlException.Number == 2627)
                    {
                        throw new CustomException("Duplicate", "AppConfiguration Code already Exists.", "Error", true, sqlException);
                    }
                    else
                    {
                        throw new CustomException("Due to some Technical Reason, Unable to Save or Update", "Error", true, sqlException);
                    }
                }
                catch (Exception ex)
                {
                    throw new CustomException("Unable to Save Or Update, Please Contact Support!!!", "Error", true, ex);
                }
            }
        }
예제 #7
0
        public async Task <List <FileUploadViewModel> > UploadFiles(HttpRequest Request, HttpContext HttpContext)
        {
            try
            {
                var          files                          = Request.Form.Files;
                var          customHeaders                  = Request.Headers;
                StringValues aId                            = "";
                StringValues Type                           = "";
                StringValues PlotType                       = ""; // Local variable to handle.
                string       FilePath                       = "";
                string       ImageUrl                       = "";
                Boolean      isExternalPath                 = true;
                string       SubPath                        = "";
                string       TypeFormat                     = "";
                string       Delimiter                      = "";
                var          dir                            = "";
                List <FileUploadViewModel>        fuvms     = new List <FileUploadViewModel>();
                ApplicationConfigurationViewModel appConfig = null;
                if (customHeaders.ContainsKey("aId") && customHeaders.ContainsKey("Type"))
                {
                    customHeaders.TryGetValue("aId", out aId);
                    customHeaders.TryGetValue("Type", out Type);
                    appConfig = await appConfigRepo.GetAppConfigByName("BaseFilePath", "Y");

                    FilePath  = appConfig.AppConfigValue;
                    appConfig = await appConfigRepo.GetAppConfigByName("ImageUrl", "Y");

                    ImageUrl  = appConfig.AppConfigValue;
                    appConfig = await appConfigRepo.GetAppConfigByName("IsExternalPath", "Y");

                    if (appConfig.AppConfigValue != null)
                    {
                        isExternalPath = bool.Parse(appConfig.AppConfigValue); // This will used to store the files inside the application.
                        if (!isExternalPath)
                        {
                            dir = Directory.GetCurrentDirectory() + $@"\wwwroot\" + FilePath;
                            //FilePath = _dir + FilePath;
                        }
                        else
                        {
                            dir = FilePath;
                        }
                    }
                    if (Type == "Equipment")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("EquipmentPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("EquipmentSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "Drive")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("DrivePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue; //TypeFormat = "DR";
                        appConfig  = await appConfigRepo.GetAppConfigByName("DriveSubPath", "Y");

                        SubPath = appConfig.AppConfigValue; //SubPath = "Attachments//Equipment//";
                    }
                    if (Type == "Intermediate")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("IntermediatePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("IntermediateSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "Driven")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("DrivenPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("DrivenSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "UnitAnalysis")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("UnitAnalysisPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("UnitAnalysisSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "ClientDoc")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("ClientDocPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("ClientDocSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        SubPath = SubPath + aId + "\\";
                    }
                    if (Type == "OtherReports")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("OtherReportsPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("OtherReportsSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        SubPath = SubPath + aId + "\\";
                    }
                    if (Type == "TechUpgrade")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("TechUpgradePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("TechUpgradeSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        SubPath = SubPath + aId + "\\";
                    }
                    if (Type == "FailureReport")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("FailureReportPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("FailureReportSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "AvoidedPlannedMaintenence")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("AvoidedPlannedMaintenancePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("AvoidedPlannedMaintenenceSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                    if (Type == "ClientSite")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("ClientSitePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("ClientSiteSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        SubPath = SubPath + aId + "\\";
                    }
                    if (Type == "Leverage")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("LeveragePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("LeverageSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        SubPath = SubPath + aId + "\\";
                    }
                    if (Type == "ImagePlot")
                    {
                        if (customHeaders.ContainsKey("plotType"))
                        {
                            customHeaders.TryGetValue("plotType", out PlotType);
                            appConfig = PlotType == "PL" ? await appConfigRepo.GetAppConfigByName("PlantImagePlotFormat", "Y") :
                                        PlotType == "EQ" ? await appConfigRepo.GetAppConfigByName("EquipmentImagePlotFormat", "Y") :
                                        PlotType == "AS" ? await appConfigRepo.GetAppConfigByName("AssetImagePlotFormat", "Y") :
                                        await appConfigRepo.GetAppConfigByName("ImagePlotFormat", "Y");
                        }
                        TypeFormat = appConfig.AppConfigValue;
                        appConfig  = await appConfigRepo.GetAppConfigByName("ImagePlotSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                    }
                }

                var dateFormat = "yyyyMMddHHmmssFFF"; // Returns 20190118183526247
                appConfig = await appConfigRepo.GetAppConfigByName("FileNameDateFormat", "Y");

                if (appConfig.AppConfigValue != null)
                {
                    dateFormat = appConfig.AppConfigValue;
                }
                string LogicalFilePattern = TypeFormat + Delimiter + aId + Delimiter;

                CurrentUser cUser = new CurrentUser(HttpContext, _configuration);

                foreach (IFormFile file in files)
                {
                    string _LogicalFilePattern = null;
                    _LogicalFilePattern = LogicalFilePattern + DateTime.Now.ToString(dateFormat);

                    // The below method call is used to write the Files in a specified Location and return the Save Parameters.
                    fuvms.Add(CopyFilesToLocation(file, _LogicalFilePattern, dir + SubPath, ImageUrl + SubPath));

                    // The below code will save the return parameters in DataBase based on Type (Equipment | Drive | Intermediate | Driven).
                    //await equipmentRepo.SaveOrUpdateAttachments(Type, Int32.Parse(aId), 0, fuvm.OriginalFileName, fuvm.LogicalFileName, fuvm.PhysicalFilePath, "Y", cUser.UserId);
                }
                return(fuvms);
            }

            catch (Exception ex)
            {
                throw new CustomException(ex.Message, "Error", true, ex?.ToString());
            }
        }
예제 #8
0
        public async Task <IEnumerable <dynamic> > SaveOrUpdate(UsersViewModel u, UserManager <IdentityUser> identityManager)
        {
            ApplicationConfigurationViewModel appConfig = null;
            Boolean IsUserActivationEnable = true;
            var     appUser = await identityManager.FindByEmailAsync(u.UserName.ToUpper());

            //u.EmailId = u.UserName;
            if (appUser == null)
            {
                var user = new ApplicationUser {
                    UserName = u.UserName, Email = u.UserName
                };
                u.EmailId = u.UserName;

                if (u.Password == null)
                {
                    //appConfig = await appConfigRepo.GetAppConfigByName("DEFAULT_APP_PWD", "Y");
                    //u.Password = CustomUtils.DecodeFromBase64(appConfig.AppConfigValue);

                    u.Password = CustomUtils.RandomString(10);
                }
                // Create Identity User.
                var result = await identityManager.CreateAsync(user, u.Password);

                // Query to get the Identity UserId.
                appUser = await identityManager.FindByEmailAsync(u.UserName.ToUpper());

                u.Id = appUser.Id;

                appConfig = await appConfigRepo.GetAppConfigByName("O_USER_ACTIVATION_ENABLED", "Y");

                IsUserActivationEnable = Boolean.Parse(appConfig.AppConfigValue);

                if (IsUserActivationEnable)
                {
                    appConfig = await appConfigRepo.GetAppConfigByName("O_USER_CONTROLLER_ACTION", "Y");

                    u.ApplicationBaseURL += appConfig.AppConfigValue;
                    string ActivationUrl = u.ApplicationBaseURL.Replace("$@USER_ID@$", u.Id);

                    /** Notify eMail to User Activation */
                    try
                    {
                        await Task.Factory.StartNew(async() =>
                        {
                            await notificationServiceHelper.PrepareUserEmailNotification(u.FirstName + " " + u.LastName, u.UserName, ActivationUrl);
                        });
                    }
                    catch (Exception ex)
                    {
                        // Notification exception.
                    }
                }
                else
                {
                    u.Active = "Y";
                }

                if (!result.Succeeded)
                {
                    var msg = "Unable to create User. Please contact Support.";
                    if (result.Errors.Count() > 0)
                    {
                        foreach (var er in result.Errors)
                        {
                            msg += "  " + er.Code + ":" + er.Description;
                        }
                    }
                    throw new Exception(msg);
                }
            }

            string sql = "dbo.EAppSaveUsers";

            using (var conn = util.MasterCon())
            {
                try
                {
                    string Password = u.Password != null?CustomUtils.EncodeToBase64(u.Password) : null;

                    return(await(conn.QueryAsync <dynamic>(sql, new
                    {
                        u.UserId,
                        u.UserName,
                        u.FirstName,
                        u.MiddleName,
                        u.LastName,
                        u.EmailId,
                        u.UserTypeId,
                        u.UserStatusId,
                        u.Mobile,
                        u.Phone,
                        u.CreatedUserId,
                        u.Id,
                        Password,
                        u.ReturnKey
                    }, commandType: CommandType.StoredProcedure)));
                }
                catch (SqlException sqlException)
                {
                    if (sqlException.Number == 515 || sqlException.Number == 2601 || sqlException.Number == 2627)
                    {
                        throw new CustomException("Duplicate", "Username already Exists.", "Error", true, sqlException);
                    }
                    else
                    {
                        throw new CustomException("Due to some Technical Reason, Unable to Save or Update", "Error", true, sqlException);
                    }
                }
                catch (Exception ex)
                {
                    throw new CustomException("Unable to Save Or Update, Please Contact Support!!!", "Error", true, ex);
                }
            }
        }
        public async Task <IActionResult> GetReport()
        {
            CurrentUser cUser  = new CurrentUser(HttpContext, _configuration);
            var         report = new StiReport();
            ApplicationConfigurationViewModel appConfig = null;

            appConfig = await appConfigRepo.GetAppConfigByName("MRXPassword", "Y");

            // This is to load Admin Dashboard
            if (customAuthService.CheckPermission(cUser.UserId, "PRG53", "P1"))
            {
                if (appConfig != null && appConfig.AppConfigValue != null)
                {
                    var path = Path.Combine(_hostingEnvironment.WebRootPath, "reports/EmaintAnalystDashboard.mrx");
                    report.LoadEncryptedReport(path, appConfig.AppConfigValue);
                }
                else
                {
                    throw new CustomException("Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.", "Error", true, "Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.");
                }
            }
            // This is to load Client Dashboard
            else if (customAuthService.CheckPermission(cUser.UserId, "PRG54", "P1"))
            {
                if (appConfig != null && appConfig.AppConfigValue != null)
                {
                    var path = Path.Combine(_hostingEnvironment.WebRootPath, "reports/EmaintClientDashboard.mrx");
                    report.LoadEncryptedReport(path, appConfig.AppConfigValue);
                }
                else
                {
                    throw new CustomException("Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.", "Error", true, "Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.");
                }
            }
            // This is to load Warning MRX states, "Insufficient Privilege Please contact your Administrator"
            else
            {
                if (appConfig != null && appConfig.AppConfigValue != null)
                {
                    var path = Path.Combine(_hostingEnvironment.WebRootPath, "reports/UnauthorizedDashboard.mrt");
                    report.Load(path);
                    return(StiNetCoreViewer.GetReportResult(this, report));
                }
                else
                {
                    throw new CustomException("Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.", "Error", true, "Unable to Load Data, Please Contact Support!!!, Please provide a valid password to read the Report Template.");
                }
            }

            string newConnectionString = _configuration.GetConnectionString("SKF.Master");

            report.Dictionary.Databases.Clear();
            report.Dictionary.Databases.Add(new Stimulsoft.Report.Dictionary.StiSqlDatabase("C2Maintenance", newConnectionString));
            Stimulsoft.Report.Dashboard.StiCacheCleaner.Clean(report.Key);
            report.Key = StiKeyHelper.GenerateKey();
            //report.Dictionary.Variables["@ClientSiteId"].ValueObject = TempData["csId"];
            report.Dictionary.Variables["@UserId"].ValueObject     = cUser.UserId;
            report.Dictionary.Variables["@LanguageId"].ValueObject = TempData["lId"];

            return(StiNetCoreViewer.GetReportResult(this, report));
        }
        public async Task <IActionResult> UploadFilesAjax()
        {
            try
            {
                var          files          = Request.Form.Files;
                var          customHeaders  = Request.Headers;
                StringValues aId            = "";
                StringValues Type           = "";
                string       FilePath       = "";
                Boolean      isExternalPath = true;
                string       SubPath        = "";
                string       TypeFormat     = "";
                string       Delimiter      = "";
                var          dir            = "";
                ApplicationConfigurationViewModel appConfig = null;
                if (customHeaders.ContainsKey("aId") && customHeaders.ContainsKey("Type"))
                {
                    customHeaders.TryGetValue("aId", out aId);
                    customHeaders.TryGetValue("Type", out Type);
                    appConfig = await appConfigRepo.GetAppConfigByName("BaseFilePath", "Y");

                    FilePath  = appConfig.AppConfigValue;
                    appConfig = await appConfigRepo.GetAppConfigByName("IsExternalPath", "Y");

                    if (appConfig.AppConfigValue != null)
                    {
                        isExternalPath = bool.Parse(appConfig.AppConfigValue); // This will used to store the files inside the application.
                        if (isExternalPath)
                        {
                            dir = Directory.GetCurrentDirectory() + $@"\wwwroot\" + FilePath;
                            //FilePath = _dir + FilePath;
                        }
                    }
                    if (Type == "Equipment")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("EquipmentPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        //TypeFormat = "EQ";
                        appConfig = await appConfigRepo.GetAppConfigByName("EquipmentSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        //SubPath = "Attachments//Equipment//";
                    }
                    if (Type == "Drive")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("DrivePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        //TypeFormat = "DR";
                        appConfig = await appConfigRepo.GetAppConfigByName("DriveSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        //SubPath = "Attachments//Equipment//";
                    }
                    if (Type == "Intermediate")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("IntermediatePrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        //TypeFormat = "IN";
                        appConfig = await appConfigRepo.GetAppConfigByName("IntermediateSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        //SubPath = "Attachments//Equipment//";
                    }
                    if (Type == "Driven")
                    {
                        appConfig = await appConfigRepo.GetAppConfigByName("DrivenPrefixFormat", "Y");

                        TypeFormat = appConfig.AppConfigValue;
                        //TypeFormat = "DN";
                        appConfig = await appConfigRepo.GetAppConfigByName("DrivenSubPath", "Y");

                        SubPath = appConfig.AppConfigValue;
                        //SubPath = "Attachments//Equipment//";
                    }
                }

                var dateFormat = "yyyyMMddHHmmssFFF"; // Returns 20190118183526247
                appConfig = await appConfigRepo.GetAppConfigByName("FileNameDateFormat", "Y");

                if (appConfig.AppConfigValue != null)
                {
                    dateFormat = appConfig.AppConfigValue;
                }
                string LogicalFilePattern = TypeFormat + Delimiter + aId + Delimiter;

                CurrentUser cUser = new CurrentUser(HttpContext, _configuration);


                foreach (IFormFile file in files)
                {
                    LogicalFilePattern = LogicalFilePattern + DateTime.Now.ToString(dateFormat);

                    // The below method call is used to write the Files in a specified Location and return the Save Parameters.
                    FileUploadViewModel fuvm = fileUploadService.CopyFilesToLocation(file, LogicalFilePattern, dir + SubPath, FilePath + SubPath);

                    // The below code will save the return parameters in DataBase based on Type (Equipment | Drive | Intermediate | Driven).
                    //await equipmentRepo.SaveOrUpdateAttachments(Type, Int32.Parse(aId), 0, fuvm.OriginalFileName, fuvm.LogicalFileName, fuvm.PhysicalFilePath, "Y", cUser.UserId);
                }
                return(Json("Success"));
            }

            catch (CustomException cex)
            {
                var responseObj = new EmaintenanceMessage(cex.Message, cex.Type, cex.IsException, cex.Exception?.ToString());
                return(StatusCode(StatusCodes.Status500InternalServerError, responseObj));
            }
            catch (Exception ex)
            {
                return(Ok(new EmaintenanceMessage(ex.Message)));
            }
        }
예제 #11
0
        public async Task <dynamic> SendInvite(EmailViewModel emailViewModel)
        {
            ApplicationConfigurationViewModel appConfig = null;
            string SmtpUrl       = null;
            string SmtpUN        = null;
            string SmtpPwd       = null;
            string SenderEmailId = null;
            int    Port          = 0;
            bool   EnableSsl     = false;

            try
            {
                appConfig = await appConfigRepo.GetAppConfigByName("O_SMTP_URL", "Y");

                SmtpUrl   = appConfig.AppConfigValue;
                appConfig = await appConfigRepo.GetAppConfigByName("O_SMTP_UN", "Y");

                SmtpUN    = appConfig.AppConfigValue;
                appConfig = await appConfigRepo.GetAppConfigByName("O_SMTP_PWD", "Y");

                SmtpPwd   = CustomUtils.DecodeFromBase64(appConfig.AppConfigValue);
                appConfig = await appConfigRepo.GetAppConfigByName("O_SMTP_PORT", "Y");

                Port      = Int32.Parse(appConfig.AppConfigValue);
                appConfig = await appConfigRepo.GetAppConfigByName("O_SENDER_EMAIL", "Y");

                SenderEmailId = appConfig.AppConfigValue;
                appConfig     = await appConfigRepo.GetAppConfigByName("O_SMTP_ENABLE_SSL", "Y");

                EnableSsl = bool.Parse(appConfig.AppConfigValue);

                // Create SMTP Client.
                SmtpClient        sc = new SmtpClient(SmtpUrl);
                NetworkCredential nc = new NetworkCredential(SmtpUN, SmtpPwd);
                sc.Port        = Port;
                sc.EnableSsl   = EnableSsl;
                sc.Credentials = nc;

                // Setup e-mail message
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

                if (emailViewModel.FromEmail != null && emailViewModel.FromEmail.EmailId != null)
                {
                    msg.From = new MailAddress(emailViewModel.FromEmail.EmailId);
                }
                else
                {
                    EmailAttributesViewModel emailAttr = new EmailAttributesViewModel();
                    emailAttr.EmailId        = SenderEmailId;
                    emailAttr.Name           = SenderEmailId;
                    emailViewModel.FromEmail = emailAttr;
                    msg.From = new MailAddress(SenderEmailId);
                }

                AddToEmails(msg, emailViewModel.ToEmailList);
                ApplicationConfigurationViewModel sub = await appConfigRepo.GetAppConfigByName("O_APP_ENV", "Y");

                if (sub != null && sub.AppConfigValue != null && sub.AppConfigValue != "")
                {
                    emailViewModel.Subject = sub.AppConfigValue + " " + emailViewModel.Subject;
                    msg.Subject            = emailViewModel.Subject;
                }
                else
                {
                    msg.Subject = emailViewModel.Subject;
                }

                msg.Body       = emailViewModel.Body;
                msg.IsBodyHtml = true;

                if (emailViewModel.Attachments != null && emailViewModel.Attachments.Count > 0)
                {
                    // Need to write code for Attachments.
                }

                // The below method is used to send an Calendar Invite.
                if (emailViewModel.IsCalendarInvite)
                {
                    StringBuilder str = new StringBuilder();
                    str.AppendLine("BEGIN:VCALENDAR");
                    str.AppendLine("PRODID:-//" + emailViewModel.FromEmail.EmailId);
                    str.AppendLine("VERSION:2.0");
                    str.AppendLine("X-WR-TIMEZONE:Asia/Kolkata");
                    str.AppendLine("CALSCALE:GREGORIAN");
                    str.AppendLine("METHOD:REQUEST");
                    str.AppendLine("BEGIN:VEVENT");
                    str.AppendLine(string.Format("SUMMARY:{0}", emailViewModel.Subject));
                    str.AppendLine(string.Format("DESCRIPTION:{0}", emailViewModel.Body));
                    //str.AppendLine("BEGIN:VTIMEZONE");
                    str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", emailViewModel.StartDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z")));
                    str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", new DateTime().ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z")));
                    str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", emailViewModel.EndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z")));
                    str.AppendLine("LOCATION:" + emailViewModel.Location);
                    //str.AppendLine("END:VTIMEZONE");
                    str.AppendLine("CLASS:PUBLIC");
                    str.AppendLine("IMPORTANT:0");
                    str.AppendLine("STATUS: CONFIRMED");
                    str.AppendLine("COMMENT:");
                    str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
                    str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", emailViewModel.Body));
                    str.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{0}", emailViewModel.FromEmail.EmailId));

                    foreach (MailAddress emto in msg.To)
                    {
                        str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION:mailto:{1}", emto.DisplayName, emto.Address));
                    }
                    //str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", emto.DisplayName, emto.Address));
                    //str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));
                    str.AppendLine("BEGIN:VALARM");
                    str.AppendLine("TRIGGER:-PT15M");
                    //str.AppendLine("ACTION:DISPLAY");
                    str.AppendLine("ACTION:EMAIL");
                    str.AppendLine("DESCRIPTION:Reminder");
                    str.AppendLine("END:VALARM");
                    str.AppendLine("END:VEVENT");
                    str.AppendLine("END:VCALENDAR");
                    System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
                    ct.Parameters.Add("method", "REQUEST");
                    AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct);
                    msg.AlternateViews.Add(avCal);
                }

                try
                {
                    sc.Send(msg);
                    return("Success");
                }
                catch (Exception ex)
                {
                    return("Fail Reason +++++++++ " + ex);
                }
            }
            catch (Exception e)
            {
                return("" + e);
            }
            return(string.Empty);
        }