Пример #1
0
        // event handlers

        public async void HandleResuming(object sender, object e)
        {
            LogThis();
            await _lifecycleStrategy.ResumingAsync();

            _messengerService.Send(new Messages.ResumingMessage());
        }
Пример #2
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                var requireEmailConfirmation =
                    Convert.ToBoolean(ConfigurationManager.AppSettings["requireEmailConfirmation"] ?? "false");
                var token = webSecurity.CreateUserAndAccount(model.UserName, model.Password,
                                                             requireConfirmationToken: requireEmailConfirmation);

                if (requireEmailConfirmation)
                {
                    // Send email to user with confirmation token
                    if (Request.Url != null)
                    {
                        string hostUrl         = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                        string confirmationUrl = hostUrl +
                                                 VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" +
                                                                               HttpUtility.UrlEncode(token));

                        const string fromAddress = "Your Email Address";
                        var          toAddress   = model.Email;
                        const string subject     =
                            "Thanks for registering but first you need to confirm your registration...";
                        var body =
                            string.Format(
                                "Your confirmation code is: {0}. Visit <a href=\"{1}\">{1}</a> to activate your account.",
                                token, confirmationUrl);

                        // NOTE: This is just for sample purposes
                        // It's generally a best practice to not send emails (or do anything on that could take a long time and potentially fail)
                        // on the same thread as the main site
                        // You should probably hand this off to a background MessageSender service by queueing the email, etc.
                        messengerService.Send(fromAddress, toAddress, subject, body, true);
                    }

                    // Thank the user for registering and let them know an email is on its way
                    return(RedirectToAction("Thanks", "Account"));
                }
                // Navigate back to the homepage and exit
                webSecurity.Login(model.UserName, model.Password);
                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = webSecurity.MinPasswordLength;
            return(View(model));
        }
Пример #3
0
 static NetworkService()
 {
     _helper = new NetworkAvailableHelper();
     _helper.AvailabilityChanged += (e) =>
     {
         _messengerService?.Send(new Messages.NetworkAvailabilityChangedMessage(e));
     };
 }
Пример #4
0
        private void InitBackServiceEvents()
        {
            _backService2.BackRequested += (s, e) =>
            {
                _backRequested?.Invoke(s, e);
                if (BackRequestedMode == EventModes.Allow)
                {
                    _messenger.Send(new Messages.BackRequestedMessage());
                }
            };

            _backService2.ForwardRequested += (s, e) =>
            {
                _forwardRequested?.Invoke(s, e);
                if (BackForwardRequestedMode == EventModes.Allow)
                {
                    _messenger.Send(new Messages.ForwardRequestedMessage());
                }
            };
        }
Пример #5
0
        /// <inheritdoc/>
        public void Log(
            string header,
            string message,
            MessageLevelEnum level,
            LoggingTargetEnum outputTarget = LoggingTargetEnum.LogFile | LoggingTargetEnum.TraceTool | LoggingTargetEnum.OutputPanel,
            bool shouldLogHeader           = true,
            bool isHeaderResourceKey       = false)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(header), DevConstants.ValueCannotBeNullOrWhitespace);
            Debug.Assert(!string.IsNullOrWhiteSpace(message), DevConstants.ValueCannotBeNullOrWhitespace);

            var logToOutputPanel = (outputTarget & LoggingTargetEnum.OutputPanel) == LoggingTargetEnum.OutputPanel;

            var messageToLog = message;

            if (shouldLogHeader || logToOutputPanel)
            {
                var headerToLog = isHeaderResourceKey ? _localisationService.GetLocalisedString(header) : header;

                if (shouldLogHeader)
                {
                    messageToLog = $"{headerToLog}: {message}";
                }

                if (logToOutputPanel)
                {
                    var watchLookup = new WatchLookup(headerToLog, message, _dateTimeService.Now, level);

                    var outputMessage = _messageFactory.CreateOutputMessage(this, watchLookup, messageLevel: level);
                    _messengerService.Send(outputMessage);
                }
            }

            if ((outputTarget & LoggingTargetEnum.LogFile) == LoggingTargetEnum.LogFile)
            {
                _logActionDictionary[level](messageToLog);
            }

            if (_traceService.IsEnabled && (outputTarget & LoggingTargetEnum.TraceTool) == LoggingTargetEnum.TraceTool)
            {
                _traceService.Send(messageToLog, level);
            }
        }
Пример #6
0
        public async Task SuspendAsync(ISuspendingEventArgs e)
        {
            Navigation.Settings.LastSuspended = DateTime.Now;

            if (Settings.EnableLifecycleStrategy)
            {
                PreviouslySuspended = true;

                _messengerService.Send(new Messages.SuspendingMessage {
                    EventArgs = e
                });

                // TODO: what to do with multiple views?

                foreach (var nav in NavigationService.Instances.Select(x => x as INavigationService2))
                {
                    await nav.SaveAsync(true);
                }
            }
        }
        /// <inheritdoc />
        public void ChangeLanguage(
            LanguageEnum language)
        {
            CurrentLanguage = language;
            LocalizeDictionary.Instance.Culture = CultureInfo
                                                  .CreateSpecificCulture(_languageDictionary[CurrentLanguage]);
            ReloadLocalisedLanguageDictionary();
            ReloadLanguages();

            var messageText = GetLocalisedString(LocalisationServiceResourceUserInterfaceNames.Msg_LanguageChanged);

            var formattedMessage = string
                                   .Format(
                CultureInfo.CurrentUICulture,
                messageText,
                _languageDictionary[CurrentLanguage]);

            var message = _messageFactory.CreateLanguageChangedMessage(this, CurrentLanguage, formattedMessage);

            _messengerService.Send(message);
        }
        public async Task <bool> MapFileAsync(string sourceFileReference, string sourceFileContainer, string targetFileContainer, CancellationToken cancellationToken)
        {
            const int taskCount   = 7;
            var       currentTask = 0;

            _logger.LogInfo($"Mapping {sourceFileReference} into {targetFileContainer}");

            var timer = new Stopwatch();

            timer.Start();

            try
            {
                _messengerService.Send(new TaskProgressMessage("Starting", currentTask++, taskCount));

                // Generate new filename
                var targetFileReference = GenerateOutputName(sourceFileReference);
                _logger.LogInfo($"Updated filename from {sourceFileReference} is {targetFileReference}");

                // Need to do extract from zip (if relevant) here
                Loose.Previous.Message sourceMessage = null;

                using (var sourceStream = await _fileService.OpenReadStreamAsync(sourceFileReference, sourceFileContainer, new System.Threading.CancellationToken()))
                {
                    _logger.LogVerbose($"Read in {timer.ElapsedMilliseconds}ms");
                    timer.Restart();

                    // Validation against XSD
                    if (!ValidateSchema(sourceStream))
                    {
                        return(false);
                    }

                    _logger.LogVerbose($"Schema validated in {timer.ElapsedMilliseconds}ms");
                    _messengerService.Send(new TaskProgressMessage("Schema validated", currentTask++, taskCount));
                    timer.Restart();

                    sourceMessage = _xmlSerializationService.Deserialize <Loose.Previous.Message>(sourceStream);
                    _logger.LogVerbose($"Deserialize in {timer.ElapsedMilliseconds}ms");
                    _messengerService.Send(new TaskProgressMessage("File loaded", currentTask++, taskCount));
                    timer.Restart();
                }

                // Map from previous year to current year structure via automapper
                var targetMessage = _mapper.Map(sourceMessage);
                _logger.LogVerbose($"Mapped in {timer.ElapsedMilliseconds}ms");
                _messengerService.Send(new TaskProgressMessage("Mapped to current year structure", currentTask++, taskCount));
                timer.Restart();

                // Uplift any relevant values in the current year structure
                var upliftedMessage = _yearUplifter.Process(targetMessage);
                _logger.LogVerbose($"Uplifted in {timer.ElapsedMilliseconds}ms");
                _messengerService.Send(new TaskProgressMessage("Values uplifted for current year", currentTask++, taskCount));
                timer.Restart();

                // Anonymise any PII information in the current year structure
                var anonymisedMessage = _anonymiser.Process(upliftedMessage);
                _logger.LogVerbose($"Anonymised in {timer.ElapsedMilliseconds}ms");
                _messengerService.Send(new TaskProgressMessage("Anonymised for current year", currentTask++, taskCount));
                timer.Restart();

                // Write out the current year structure
                using (var targetStream = await _fileService.OpenWriteStreamAsync(targetFileReference, targetFileContainer, new System.Threading.CancellationToken()))
                {
                    _logger.LogVerbose($"Get Out Stream in {timer.ElapsedMilliseconds}ms");
                    timer.Restart();

                    _xmlSerializationService.Serialize <Loose.Message>(anonymisedMessage, targetStream);
                    _logger.LogVerbose($"Serialize in {timer.ElapsedMilliseconds}ms");
                    timer.Restart();

                    await targetStream.FlushAsync();

                    _logger.LogVerbose($"Flush in {timer.ElapsedMilliseconds}ms");
                    timer.Restart();
                }

                // Write out the anonymisation lookup details (LRN and ULN)
                if (_anonymiseLog?.Log.Any() == true)
                {
                    using (var targetStream = await _fileService.OpenWriteStreamAsync(
                               targetFileReference + ".CSV",
                               targetFileContainer,
                               new System.Threading.CancellationToken()))
                    {
                        var newLineBytes = Encoding.ASCII.GetBytes(Environment.NewLine);
                        foreach (var logEntry in _anonymiseLog.Log)
                        {
                            var reportLine      = $"{logEntry.FieldName} {logEntry.OldValue} {logEntry.NewValue}";
                            var reportLineBytes = Encoding.ASCII.GetBytes(reportLine);
                            targetStream.Write(reportLineBytes, 0, reportLineBytes.Length);
                            targetStream.Write(newLineBytes, 0, newLineBytes.Length);
                        }

                        await targetStream.FlushAsync();

                        _anonymiseLog.Clear();
                    }
                }

                _messengerService.Send(_validationErrorHandler.ErrorRaised ?
                                       new TaskProgressMessage("File saved - Completed with XML Validation warnings - Please check logs", currentTask++, taskCount) :
                                       new TaskProgressMessage("File saved - Completed", currentTask++, taskCount));
            }
            catch (Exception ex)
            {
                _logger.LogFatal($"Failed mapping {sourceFileReference} into {targetFileContainer}", ex);
                return(false);
            }

            return(true);
        }
Пример #9
0
 private void Logout()
 {
     _messengerService.Send(new NotificationMessage("Logout"));
 }
Пример #10
0
        public async Task <bool> ProcessAsync(IEnumerable <string> filePaths, string outputDirectory, CancellationToken cancellationToken)
        {
            List <AmalgamationRoot> amalgamationRoots = new List <AmalgamationRoot>();

            try
            {
                if (!string.IsNullOrEmpty(outputDirectory) && !Directory.Exists(outputDirectory))
                {
                    Directory.CreateDirectory(outputDirectory);
                }

                var outputDirectoryForInstance = $"{outputDirectory}/FileMerge-{_dateTimeProvider.GetNowUtc().ToString("yyyyMMdd-HHmmss")}";
                Directory.CreateDirectory(outputDirectoryForInstance);

                bool validSchema = true;

                foreach (var file in filePaths)
                {
                    validSchema = _xsdValidationService.ValidateSchema(file);

                    if (!validSchema)
                    {
                        break;
                    }
                }

                if (!validSchema)
                {
                    await _amalgamationOutputService.ProcessAsync(_validationErrorHandler.ValidationErrors, outputDirectoryForInstance, cancellationToken);

                    return(false);
                }

                foreach (var file in filePaths)
                {
                    var amalgamationRoot = await _messageProvider.ProvideAsync(file, cancellationToken);

                    _parentRelationshipMapper.MapChildren(amalgamationRoot as IAmalgamationRoot);
                    amalgamationRoot.Message = _crossValidationService.CrossValidateLearners(amalgamationRoot.Message);
                    amalgamationRoots.Add(amalgamationRoot);
                }

                if (_validationErrorHandler.ValidationErrors.Any())
                {
                    await _amalgamationOutputService.ProcessAsync(_validationErrorHandler.ValidationErrors, outputDirectoryForInstance, cancellationToken);

                    return(false);
                }

                var amalgamationResult = await _amalgamationService.AmalgamateAsync(amalgamationRoots, cancellationToken);

                amalgamationResult = _invalidRecordRemovalService.RemoveInvalidLearners(amalgamationResult);
                await _amalgamationOutputService.ProcessAsync(amalgamationResult, outputDirectoryForInstance, cancellationToken);

                var learnersInAllFiles        = amalgamationRoots.SelectMany(x => x.Message.Learner).GroupBy(y => y.LearnRefNumber).Count();
                var learnersInAmalgamatedFile = amalgamationResult.Message.Learner.Count();
                _messengerService.Send(new AmalgamationSummary()
                {
                    FileLearnerCount          = amalgamationRoots.Select(x => new KeyValuePair <string, int>(x.Filename, x.Message.Learner.Count())),
                    LearnersInAllFiles        = learnersInAllFiles,
                    AmalgamationErrors        = amalgamationResult.ValidationErrors.Count(x => x.Severity == Severity.Error),
                    AmalgamationWarnings      = amalgamationResult.ValidationErrors.Count(x => x.Severity == Severity.Warning),
                    LearnersInAmalgamatedFile = learnersInAmalgamatedFile,
                    RejectedLearners          = learnersInAllFiles - learnersInAmalgamatedFile
                });

                return(true);
            }
            catch (Exception ex)
            {
                _loggger.LogError("Critical error occurred", ex);

                return(false);
            }
        }
Пример #11
0
        public async Task <bool> PopulateAsyncByType(IInputReferenceDataContext inputReferenceDataContext, CancellationToken cancellationToken)
        {
            const int taskCount   = 9;
            var       currentTask = 0;

            _messengerService.Send(new TaskProgressMessage("Dacpac starting", currentTask++, taskCount));
            _logger.LogInfo("Starting create from dacpac");
            CreateDatabaseFromDacPack(inputReferenceDataContext.ConnectionString, cancellationToken);
            _logger.LogInfo("Finished create from dacpac");
            _messengerService.Send(new TaskProgressMessage("Dacpac applied", currentTask++, taskCount));

            _logger.LogInfo("Starting Truncate existing data");
            _referenceInputTruncator.TruncateReferenceData(inputReferenceDataContext);
            _logger.LogInfo("Finished Truncate existing data");
            _messengerService.Send(new TaskProgressMessage("Existing data truncated.", currentTask++, taskCount));

            var insertTimeout = inputReferenceDataContext.InsertCommandTimeout;

            using (var sqlConnection = new SqlConnection(inputReferenceDataContext.ConnectionString))
            {
                sqlConnection.Open();
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    try
                    {
                        // Metadata
                        await PopulateMetaData(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);

                        _messengerService.Send(new TaskProgressMessage("Meta data applied", currentTask++, taskCount));

                        // Lars data structures
                        await PopulateTopLevelNode <LARSStandard, LARS_LARSStandard>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <LARSLearningDelivery, LARS_LARSLearningDelivery>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <LARSFrameworkDesktop, LARS_LARSFrameworkDesktop>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <LARSFrameworkAimDesktop, LARS_LARSFrameworkAim>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);

                        _messengerService.Send(new TaskProgressMessage("Lars data applied", currentTask++, taskCount));

                        // Postcode structures
                        await PopulateTopLevelNode <Postcode, Postcodes_Postcode>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <McaGlaSofLookup, PostcodesDevolution_McaGlaSofLookup>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <DevolvedPostcode, PostcodesDevolution_Postcode>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);

                        _messengerService.Send(new TaskProgressMessage("Postcode data applied", currentTask++, taskCount));

                        // Organisations
                        await PopulateTopLevelNode <Organisation, Organisations_Organisation>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);
                        await PopulateTopLevelNode <EPAOrganisation, EPAOrganisations_EPAOrganisation>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);

                        _messengerService.Send(new TaskProgressMessage("Organisations data applied", currentTask++, taskCount));

                        // Employers
                        await PopulateTopLevelNode <Employer, Employers_Employer>(inputReferenceDataContext, sqlConnection, sqlTransaction, insertTimeout, cancellationToken);

                        _messengerService.Send(new TaskProgressMessage("Employers data applied", currentTask++, taskCount));

                        sqlTransaction.Commit();
                        _messengerService.Send(new TaskProgressMessage("Data committed", currentTask++, taskCount));
                    }
                    catch (Exception e)
                    {
                        sqlTransaction.Rollback();

                        Console.WriteLine(e);
                        throw;
                    }
                }
            }

            return(false);
        }
Пример #12
0
        public async Task <ICompletionContext> ProcessAsync(IDesktopContext desktopContext, CancellationToken cancellationToken)
        {
            var completionContext = new CompletionContext()
            {
                OutputDirectory           = desktopContext.OutputDirectory,
                ProcessingCompletionState = ProcessingCompletionStates.Success,
            };

            var stepsList = _ilrPipelineProvider.Provide();

            var step = 0;

            while (step < stepsList.Count)
            {
                var desktopTaskDefinition = stepsList[step];

                _messengerService.Send(new TaskProgressMessage(desktopTaskDefinition.Key.GetDisplayText(), step, stepsList.Count));

                try
                {
                    desktopContext = await _desktopTaskExecutionService
                                     .ExecuteAsync(desktopTaskDefinition.Key, desktopContext, cancellationToken)
                                     .ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    step++;
                }
                catch (TaskCanceledException taskCanceledException)
                {
                    completionContext.ProcessingCompletionState = ProcessingCompletionStates.Cancelled;

                    _logger.LogError($"Task Cancelled - Step {step}", taskCanceledException);

                    return(completionContext);
                }
                catch (Exception exception)
                {
                    if (desktopTaskDefinition.FailureKey != null)
                    {
                        if (desktopTaskDefinition.FailureContextMutatorKey != null)
                        {
                            desktopContext = _contextMutatorExecutor.Execute(desktopTaskDefinition.FailureContextMutatorKey.Value, desktopContext);
                        }

                        step = _ilrPipelineProvider.IndexFor(desktopTaskDefinition.FailureKey.Value, stepsList);

                        completionContext.ProcessingCompletionState = ProcessingCompletionStates.HandledFail;

                        _logger.LogError($"Task Execution Handled Failure - Step {step}", exception);
                    }
                    else
                    {
                        completionContext.ProcessingCompletionState = ProcessingCompletionStates.UnhandledFail;

                        _logger.LogError($"Task Execution Unhandled Failure - Step {step}", exception);

                        return(completionContext);
                    }
                }
            }

            _messengerService.Send(new TaskProgressMessage("Processing Complete", stepsList.Count, stepsList.Count));

            return(completionContext);
        }
Пример #13
0
        public bool SendEmailToApproverFromRequester(string hostUrl,Request request, ESKAPEDEContext Db,IMessengerService MessengerService)
        {
            var isSuccess = false;
            try
            {
                var RequestID = request.RequestID ;
                var fromFirstName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.FirstName).SingleOrDefault();
                var fromLastName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.LastName).SingleOrDefault();
                if (fromLastName == null) fromLastName = "";
                var fromfullName = string.Format("{0}.{1}", fromFirstName.ToUpper(), fromLastName.ToUpper());
                var fromAddress = ConfigurationManager.AppSettings["Sender"];
                var fromPositionName = Db.Positions.Where(a => a.PositionID == request.PositionID).Select(a => a.PositionName).SingleOrDefault();
                var fromDivisionName = Db.Positions.Where(a => a.PositionID  == request.PositionID).Select(a => a.Unit.Division.DivisionName).SingleOrDefault();
                var fromCountryName = Db.Positions.Where(a => a.PositionID  == request.PositionID).Select(a => a.Country.CountryName).SingleOrDefault();
                var fromDesti = Db.Countries.Where(a => a.CountryID == request.FromCountryID).Select(a => a.CountryName).SingleOrDefault();
                var toDesti = Db.Countries.Where(a => a.CountryID == request.ToCountryID).Select(a => a.CountryName).SingleOrDefault();
                var fromDate = request.StartDate.Date.ToShortDateString();
                var toDate = request.EndDate.Date.ToShortDateString();
                var skpdEventName = request.EventName;
                var skpdEndDate = request.EndDate.Date.ToShortDateString();
                var toAddress = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.Email).SingleOrDefault();
                var toName = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.Username).SingleOrDefault();
                var skpdRequestID = request.RequestID.ToString();
                var QueryParam = string.Format("UserName={0}&RequestID={1}", toName, skpdRequestID);
                var QueryParamEncrypt = QueryStringEncrypt(QueryParam);
                var approveUrl = hostUrl + VirtualPathUtility.ToAbsolute(string.Format("~/FromEmail/Approve{0}", QueryParamEncrypt));
                var rejectUrl = hostUrl + VirtualPathUtility.ToAbsolute(string.Format("~/FromEmail/Reject{0}", QueryParamEncrypt));
                var subject = string.Format("Pengajuan Permohonan Perjalanan Dinas Dari Bapak/Ibu {0}", fromfullName);
                IEnumerable<RequestInTransport> ListTrans = Db.RequestInTransports.Include("Transport").Where(a => a.RequestID == request.RequestID);
                var anggaran = Db.RequestInPrograms.Where(a => a.RequestID == request.RequestID).Select(a => a.Program.ProgramName).FirstOrDefault();

                //IEnumerable<Transport> transport = db.Transports;
                var StrListTrans = "<ul>";
                foreach (var item in ListTrans)
                {
                    StrListTrans += string.Format("<li>{0}</li>", item.Transport.TransportName);
                }
                StrListTrans = string.Format("{0}</ul>", StrListTrans);

                var body = string.Format("Kepada Yth,<br />" +
                                        "Bapak/Ibu. {0} <br /><br/>" +
                                        "Permohonan Persetujuan Perjalanan Dinas : " +
                                        "<br/><br/>No. Perjadin: {1} " +
                                        "<br/>Nama: {2} " +
                                        "<br/>Posisi: {3} " +
                                        "<br/>Divisi : {4} " +
                                        "<br/>Kantor : {5} " +
                                        "<br/>Kegiatan : {6} " +
                                        "<br/>Perjalanan : {7} - {8} " +
                                        "<br/>Tanggal: {9} - {10}" +
                                        "<br/>Transportasi : {11} " +
                                        "<br/>Beban Anggaran : {12} " +
                                        "<br/><br /> Apakah Permohonan perjalanan dinas ini di SETUJUI atau TIDAK DISETUJUI ? " +
                                        "<br/><br/><p><strong><a href=\"{13}\">DISETUJUI</a></strong></p> " +
                                        "<br/><br/><p><strong><a href=\"{14}\">TIDAK DISETUJUI</a></strong></p>",
                                        toName.ToUpper(), skpdRequestID, fromfullName, fromPositionName, fromDivisionName,
                                        fromCountryName, skpdEventName, fromDesti, toDesti, fromDate, toDate,
                                        StrListTrans, anggaran, approveUrl, rejectUrl);

                if (MessengerService.Send(fromAddress, toAddress, subject, body, true))
                {
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                //Log exception
                ex.ToString();
            }

            return isSuccess;
        }
Пример #14
0
        public bool SendEmailResultToRequesterCcApprover(Request request, ESKAPEDEContext Db, IMessengerService MessengerService)
        {
            var isSuccess = false;
            try
            {
                //SEND EMAIL TO REQUESTER Cc APPROVER
                var RequestID = request.RequestID.ToString();
                var fromFirstName = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.FirstName).SingleOrDefault();
                var fromLastName = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.LastName).SingleOrDefault();
                if (fromLastName == null) fromLastName = "";
                var fromfullName = string.Format("{0}.{1}", fromFirstName.ToUpper(), fromLastName.ToUpper());
                var toFirstName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.FirstName).SingleOrDefault();
                var toLastName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.LastName).SingleOrDefault();
                var tofullName = string.Format("{0}.{1}", toFirstName.ToUpper(), toLastName.ToUpper());
                var fromAddress = ConfigurationManager.AppSettings["Sender"];
                var toAddress = Db.Users.Where(a => a.ID == request.UserID).Select(a => a.Email).SingleOrDefault();
                var ccAddress = ccEmail(request.RequestID);
                var subject = string.Format("Hasil Pengajuan Perjalanan Dinas Dari {0}", tofullName);
                var appSkpdUrl = ConfigurationManager.AppSettings["hostUrl"];
                var body = string.Format("<p>Kepada Yth,<br /> Bapak/Ibu {0}<br /><br />" +
                                        "<p>No. Perjadin : {1}</p> <br />" +
                                        "<p>Pengajuan perjalanan dinas anda telah DISETUJUI oleh Bapak/Ibu {2}</p><br />" +
                                        "<p>Untuk informasi lengkap <a href=\"{3}\">login</a></p>",
                                        tofullName.ToUpper(), RequestID, fromfullName, appSkpdUrl);

                if (MessengerService.Send(fromAddress, toAddress, subject, body, true, ccAddress))
                {
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return isSuccess;
        }
Пример #15
0
        //public bool ExclusiveApprover(int ApprovalPositionID)
        //{
        //    var ApprovalPositionName = "";
        //    bool PositionName = false;
        //    string[] Exclusive;
        //    Exclusive = new string[2];
        //    Exclusive[0] = "KADIV";
        //    Exclusive[1] = "KA. KPM";
        //    List<string> _Exclusive = new List<string>(Exclusive);
        //    using (var db = new ESKAPEDEContext())
        //    {
        //        ApprovalPositionName = db.Positions.Where(a => a.PositionID == ApprovalPositionID).Select(a => a.PositionName).First();
        //    }
        //    if (_Exclusive.Any(s => ApprovalPositionName.Contains(s)))
        //    {
        //        PositionName = true;
        //    }
        //    return PositionName;
        //}
        public bool SendEmailRejectToRequesterCcApprover(Request request, ESKAPEDEContext Db, IMessengerService MessengerService)
        {
            var isSuccess = false;
            try
            {
                var RequestID = request.RequestID;
                var fromUsername = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.Username).SingleOrDefault();
                var fromFirstName = Db.Users.Where(a => a.Username == fromUsername).Select(a => a.FirstName).SingleOrDefault();
                var fromLastName = Db.Users.Where(a => a.Username == fromUsername).Select(a => a.LastName).SingleOrDefault();
                if (fromLastName == null) fromLastName = "";
                var fromfullName = string.Format("{0}.{1}", fromFirstName.ToUpper(), fromLastName.ToUpper());
                var fromAddress = ConfigurationManager.AppSettings["Sender"];
                var toAddress = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.Email).SingleOrDefault();
                var toFirstName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.FirstName).SingleOrDefault();
                var toLastName = Db.Users.Where(a => a.Username == request.CreatedBy).Select(a => a.LastName).SingleOrDefault();
                var tofullName = string.Format("{0}.{1}", toFirstName.ToUpper(), toLastName.ToUpper());
                //var ccAddress = Db.Users.Where(a => a.PositionID == request.ApprovalPositionID).Select(a => a.Email).Single();
                var ccAddress = ccEmail(request.RequestID);
                var subject = string.Format("Hasil Permohonan Pengajuan Perjalan Dinas Dari {0}", fromfullName);
                var appSkpdUrl = ConfigurationManager.AppSettings["hostUrl"];
                var fromReason = request.RejectedReason;
                var body = string.Format("<p>Kepada Yth,<br />" +
                                        "Bapak/Ibu {0}<br /><br />" +
                                        "No. Perjadin : {1} <br />" +
                                        "TIDAK DISETUJUI Oleh Bapak/Ibu {2}</p><br />" +
                                        "Dengan Alasan : {3}" +
                                        "<p>Untuk informasi lengkap <a href='{4}'>login</a></p>",
                                        tofullName.ToUpper(), RequestID, fromfullName, request.RejectedReason, appSkpdUrl);
                if (MessengerService.Send(fromAddress, toAddress, subject, body, true, ccAddress))
                {
                    isSuccess = true;
                }

            }
            catch (Exception ex)
            {
                //Log exception
                ex.ToString();
            }

            return isSuccess;
        }
Пример #16
0
 public void SetLoadingData(bool isLoadingData)
 {
     _messengerService.Send(new LoadingDataMessage(isLoadingData));
 }