Example #1
0
 protected KoreController()
 {
     WorkContext = EngineContext.Current.Resolve <IWebWorkContext>();
     T           = LocalizationUtilities.Resolve();
     Logger      = LoggingUtilities.Resolve();
     //Logger = NullLogger.Instance;
 }
Example #2
0
        /// <summary>
        /// Add TDS Login7 Option.
        /// </summary>
        /// <param name="optionName">Option Name</param>
        /// <param name="data">Option Data</param>
        public void AddOption(string optionName, string data)
        {
            if (optionName == null || data == null)
            {
                throw new ArgumentNullException();
            }

            if (this.Options.Where(opt => opt.Name == optionName).Any())
            {
                throw new Exception("Login7 option already set!");
            }

            if (optionName != "Password" && optionName != "ChangePassword")
            {
                LoggingUtilities.WriteLog($"  Adding Login7 option {optionName} [{data}].");
            }
            else
            {
                LoggingUtilities.WriteLog($"  Adding Login7 option {optionName}.");
            }

            var option = TDSLogin7OptionFactory.CreateOption(optionName, data);

            this.Options.Add(option);
        }
Example #3
0
 public AppDataFolder(IAppDataFolderRoot root, IVirtualPathMonitor virtualPathMonitor)
 {
     _root = root;
     _virtualPathMonitor = virtualPathMonitor;
     T      = NullLocalizer.Instance;
     Logger = LoggingUtilities.Resolve();
 }
Example #4
0
        /// <summary>
        /// Connect to the server.
        /// </summary>
        public void Connect()
        {
            LoggingUtilities.WriteLog($" Connect initiated.");
            do
            {
                this.reconnect       = false;
                this.Client          = new TcpClient(this.Server, this.Port);
                this.TdsCommunicator = new TDSCommunicator(this.Client.GetStream(), 4096, this.TrustServerCertificate);
                this.SendPreLogin();
                this.ReceivePreLoginResponse();
                this.SendLogin7();
                if (flag == TDSEncryptionOption.EncryptOff)
                {
                    this.TdsCommunicator = new TDSCommunicator(this.Client.GetStream(), 4096, this.TrustServerCertificate);
                }
                this.ReceiveLogin7Response();

                if (this.reconnect)
                {
                    this.Disconnect();
                    LoggingUtilities.WriteLog($" Routing to: {this.Server}:{this.Port}.");
                }
            }while (this.reconnect);

            LoggingUtilities.WriteLog($" Connect done.");
        }
Example #5
0
 /// <summary>
 /// Disconnect from the server.
 /// </summary>
 public void Disconnect()
 {
     LoggingUtilities.WriteLog($" Disconnect initiated.");
     this.Client.Close();
     this.Client = null;
     LoggingUtilities.WriteLog($" Disconnect done.");
 }
Example #6
0
        private bool TryUpdateMservEntry(ADUser user, FblRequestParameters fblRequestParameters)
        {
            bool result;

            try
            {
                if (user == null || fblRequestParameters == null)
                {
                    result = false;
                }
                else
                {
                    if (this.tenantRecipientSession is IAggregateSession)
                    {
                        ((IAggregateSession)this.tenantRecipientSession).MbxReadMode = MbxReadMode.NoMbxRead;
                    }
                    user[ADUserSchema.FblEnabled] = fblRequestParameters.OptIn;
                    this.tenantRecipientSession.Save(user);
                    FBLPerfCounters.NumberOfSuccessfulMSERVWriteRequests.Increment();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                FBLPerfCounters.NumberOfFailedMSERVWriteRequests.Increment();
                LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_TransientFblErrorUpdatingMServ, new object[]
                {
                    ex.InnerException ?? ex
                });
                result = false;
            }
            return(result);
        }
        /// <summary>
        /// Terminate TDS PreLogin Packet.
        /// </summary>
        public void Terminate()
        {
            this.Terminated = true;
            this.Options.Add(new TDSPreLoginOptionToken(TDSPreLoginOptionTokenType.Terminator));

            LoggingUtilities.WriteLog($"  Adding PreLogin message terminator.");
        }
Example #8
0
        private ADRawEntry GetADRawEntry(ulong puid, string emailAddress)
        {
            ADRawEntry result;

            try
            {
                List <ADPropertyDefinition> properties = new List <ADPropertyDefinition>(new ADPropertyDefinition[]
                {
                    ADMailboxRecipientSchema.ExchangeGuid,
                    ADUserSchema.NetID,
                    ADMailboxRecipientSchema.Database,
                    ADUserSchema.PrimaryMailboxSource,
                    ADUserSchema.SatchmoClusterIp,
                    ADUserSchema.SatchmoDGroup,
                    ADUserSchema.FblEnabled
                });
                ADRawEntry adrawEntry = this.tenantRecipientSession.FindByExchangeGuid(ConsumerIdentityHelper.GetExchangeGuidFromPuid(puid), properties) ?? this.tenantRecipientSession.FindByProxyAddress(ProxyAddress.Parse(emailAddress), properties);
                FBLPerfCounters.NumberOfSuccessfulMSERVReadRequests.Increment();
                result = adrawEntry;
            }
            catch (Exception ex)
            {
                FBLPerfCounters.NumberOfFailedMSERVReadRequests.Increment();
                LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_TransientFblErrorReadingMServ, new object[]
                {
                    ex.InnerException ?? ex
                });
                throw;
            }
            return(result);
        }
Example #9
0
 private void ProcessClassificationRequest(FblRequestParameters fblRequestParameters)
 {
     if (fblRequestParameters == null)
     {
         return;
     }
     Task.Factory.StartNew(delegate()
     {
         FBLPerfCounters.NumberOfFblClassificationRequestsReceived.Increment();
         ADRawEntry adrawEntry = this.GetADRawEntry(fblRequestParameters.Puid, fblRequestParameters.PrimaryEmail);
         if (!this.IsFblUser(adrawEntry))
         {
             FBLPerfCounters.NumberOfFblClassificationRequestsSuccessfullyProcessed.Increment();
             return;
         }
         if (this.TryPrepareAndSendXmrMessage(fblRequestParameters, "*****@*****.**"))
         {
             FBLPerfCounters.NumberOfFblClassificationRequestsSuccessfullyProcessed.Increment();
             return;
         }
         FBLPerfCounters.NumberOfFblClassificationRequestsFailed.Increment();
     }).ContinueWith(delegate(Task t)
     {
         if (t.Exception != null)
         {
             FBLPerfCounters.NumberOfFblClassificationRequestsFailed.Increment();
             Exception innerException = t.Exception.Flatten().InnerException;
             LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_FblUnableToProcessRequest, new object[]
             {
                 innerException
             });
         }
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
Example #10
0
        /// <summary>
        /// Receive PreLogin response from the server.
        /// </summary>
        public void ReceivePreLoginResponse()
        {
            LoggingUtilities.WriteLog($" ReceivePreLoginResponse initiated.");

            if (this.TdsCommunicator.ReceiveTDSMessage() is TDSPreLoginPacketData response)
            {
                if (response.Options.Exists(opt => opt.Type == TDSPreLoginOptionTokenType.Encryption) && response.Encryption == TDSEncryptionOption.EncryptReq)
                {
                    LoggingUtilities.WriteLog($" Server requires encryption, enabling encryption.");
                    this.TdsCommunicator.EnableEncryption(this.Server, this.EncryptionProtocol);
                    LoggingUtilities.WriteLog($" Encryption enabled.");
                }

                if (response.Options.Exists(opt => opt.Type == TDSPreLoginOptionTokenType.FedAuthRequired) && response.FedAuthRequired == true)
                {
                    throw new NotSupportedException("FedAuth is being requested but the client doesn't support FedAuth.");
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            LoggingUtilities.WriteLog($" ReceivePreLoginResponse done.");
        }
Example #11
0
        /// <summary>
        /// Receive Login7 response from the server.
        /// </summary>
        public void ReceiveLogin7Response()
        {
            LoggingUtilities.WriteLog($" ReceiveLogin7Response initiated.");

            if (this.TdsCommunicator.ReceiveTDSMessage() is TDSTokenStreamPacketData response)
            {
                foreach (var token in response.Tokens)
                {
                    if (token is TDSEnvChangeToken)
                    {
                        var envChangeToken = token as TDSEnvChangeToken;
                        if (envChangeToken.Type == Tokens.EnvChange.TDSEnvChangeType.Routing)
                        {
                            LoggingUtilities.WriteLog($" Client received EnvChange routing token, client is being routed.");
                            this.Server     = envChangeToken.Values["AlternateServer"];
                            this.ServerName = this.Server;
                            this.Port       = int.Parse(envChangeToken.Values["ProtocolProperty"]);
                            this.reconnect  = true;
                        }
                    }
                    else if (token is TDSErrorToken)
                    {
                        var errorToken = token as TDSErrorToken;
                        LoggingUtilities.WriteLog($" Client received Error token:");

                        LoggingUtilities.WriteLog($"     Number: {errorToken.Number}");
                        LoggingUtilities.WriteLog($"     State: {errorToken.State}");
                        LoggingUtilities.WriteLog($"     Class: {errorToken.Class}");
                        LoggingUtilities.WriteLog($"     MsgText: {errorToken.MsgText}");
                        LoggingUtilities.WriteLog($"     ServerName: {errorToken.ServerName}");
                        LoggingUtilities.WriteLog($"     ProcName: {errorToken.ProcName}");
                        LoggingUtilities.WriteLog($"     LineNumber: {errorToken.LineNumber}");

                        if (errorToken.Number == 18456)
                        {
                            throw new Exception("Login failure.");
                        }
                    }
                    else if (token is TDSInfoToken)
                    {
                        var infoToken = token as TDSInfoToken;
                        LoggingUtilities.WriteLog($" Client received Info token:");

                        LoggingUtilities.WriteLog($"     Number: {infoToken.Number}");
                        LoggingUtilities.WriteLog($"     State: {infoToken.State}");
                        LoggingUtilities.WriteLog($"     Class: {infoToken.Class}");
                        LoggingUtilities.WriteLog($"     MsgText: {infoToken.MsgText}");
                        LoggingUtilities.WriteLog($"     ServerName: {infoToken.ServerName}");
                        LoggingUtilities.WriteLog($"     ProcName: {infoToken.ProcName}");
                        LoggingUtilities.WriteLog($"     LineNumber: {infoToken.LineNumber}");
                    }
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            LoggingUtilities.WriteLog($" ReceiveLogin7Response done.");
        }
        public void Terminate()
        {
            Terminated = true;
            Options.Add(new TDSPreLoginOptionToken(TDSPreLoginOptionTokenType.Terminator));

            LoggingUtilities.WriteLogVerboseOnly($" Terminating PreLogin message.");
        }
Example #13
0
        /// <summary>
        ///		Creates a new thread dedicated to message receiving.
        /// </summary>
        protected void ReceiveMessages()
        {
            ReceiverThread = new Thread(new ThreadStart(delegate
            {
                while (true)
                {
                    try
                    {
                        // TODO: This throws an error when killing the network connection.
                        byte[] messageByteArray = Receiver.Receive(ref ReceivingEndPoint);
                        DistributeMessage(messageByteArray);
                    }
                    catch (System.Exception ex)
                    {
                        LoggingUtilities.LogFormat(
                            "Message: ({0})\nInner Exception: ({1})\nData: ({2})\nHelplink: ({3})\nHResult: ({4})\nSource: ({5})\nTargetSite: ({6})\nStack Trace: ({7})",
                            ex.Message,
                            ex.InnerException,
                            ex.Data,
                            ex.HelpLink,
                            ex.HResult,
                            ex.Source,
                            ex.TargetSite,
                            ex.StackTrace);
                    }
                }
            }));

            ReceiverThread.Start();
        }
Example #14
0
        private void Send(Packet packet, bool client)
        {
            lock (client ? _clientLock : _serverLock)
            {
                MemoryStream ms = new MemoryStream();
                using (PacketWriter w = new PacketWriter(ms))
                {
                    w.Write(0);
                    w.Write(packet.Id);
                    packet.Write(w);
                }

                byte[] data = ms.ToArray();
                PacketWriter.BlockCopyInt32(data, data.Length);
                if (client)
                {
                    ConsoleUtilities.VerboseWriteLine($"Sent {packet.Type} to the client");
                    _clientSendCipher.Cipher(data);
                    LoggingUtilities.LogPacketToFile(packet, client);
                    if (!_closed)
                    {
                        _clientStream.Write(data, 0, data.Length);
                    }
                }
                else
                {
                    ConsoleUtilities.VerboseWriteLine($"Sent {packet.Type} to the server");
                    _serverSendCipher.Cipher(data);
                    if (!_closed)
                    {
                        _serverStream.Write(data, 0, data.Length);
                    }
                }
            }
        }
Example #15
0
        public static TDSToken ReadTokenFromStream(MemoryStream stream)
        {
            var tokenType = (TDSTokenType)stream.ReadByte();

            LoggingUtilities.WriteLogVerboseOnly($" Recieved {tokenType.ToString()} token in Login7 response.");
            switch (tokenType)
            {
            case TDSTokenType.Error:
            {
                var token = new TDSErrorToken();
                token.Unpack(stream);
                return(token);
            }

            case TDSTokenType.EnvChange:
            {
                var token = new TDSEnvChangeToken();
                token.Unpack(stream);
                return(token);
            }

            default:
            {
                IgnoreToken(tokenType, stream);
                return(null);
            }
            }
        }
Example #16
0
        public GenericODataController(IRepository <TEntity> repository)
        {
            var cacheManager = EngineContext.Current.Resolve <ICacheManager>();

            this.Service = new GenericDataService <TEntity>(cacheManager, repository);
            this.Logger  = LoggingUtilities.Resolve();
        }
Example #17
0
        internal bool TryProcessFbl(string queryParams, out bool?isClassifyRequest, out bool?isOptIn)
        {
            isClassifyRequest = null;
            isOptIn           = null;
            FblRequestParameters fblRequestParameters = null;
            bool result;

            try
            {
                FBLPerfCounters.NumberOfFblRequestsReceived.Increment();
                if (!this.FblEnabled)
                {
                    result = true;
                }
                else if (string.IsNullOrEmpty(queryParams))
                {
                    FBLPerfCounters.NumberOfFblRequestsFailed.Increment();
                    result = false;
                }
                else
                {
                    fblRequestParameters = this.DecryptAndParseUrlParameters(queryParams);
                    if (fblRequestParameters == null)
                    {
                        result = false;
                    }
                    else
                    {
                        if (fblRequestParameters.IsClassifyRequest())
                        {
                            isClassifyRequest = new bool?(true);
                            this.ProcessClassificationRequest(fblRequestParameters);
                        }
                        else
                        {
                            isClassifyRequest = new bool?(false);
                            isOptIn           = new bool?(fblRequestParameters.OptIn);
                            if (!this.TryProcessSubscriptionRequest(fblRequestParameters))
                            {
                                FBLPerfCounters.NumberOfFblRequestsFailed.Increment();
                                return(false);
                            }
                        }
                        FBLPerfCounters.NumberOfFblRequestsSuccessfullyProcessed.Increment();
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                FBLPerfCounters.NumberOfFblRequestsFailed.Increment();
                LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_FblUnableToProcessRequest, new object[]
                {
                    ex.InnerException ?? ex
                });
                result = (fblRequestParameters != null && fblRequestParameters.IsClassifyRequest());
            }
            return(result);
        }
 private void StopBackUp()
 {
     backUpThread.Abort();
     loadIconThread.Abort();
     trayIcon.Icon = Resources.AppIcon;
     Reloadmenu();
     LoggingUtilities.Log("INTERRUPTED BACK-UP\n");
 }
Example #19
0
 private void writeBytes(byte[] buf, int offset, int size)
 {
     LOG.Debug("sending: " + LoggingUtilities.ByteArrayToString(buf, size));
     // converting from sync to async got rid of some of the apparent buffer corruption issues
     // when sending and receiving to the IOIO at the same time 2015/26/Apr
     //Stream_.Write(buf, offset, size);
     Stream_.WriteAsync(buf, offset, size);
 }
        public BackUpSettings Load(string settingsPath)
        {
            // loads selected settings.
            string json = File.ReadAllText(settingsPath);

            LoadedSettings = JsonUtility.FromJson <BackUpSettings>(json);
            LoggingUtilities.LogFormat("Loaded Settings: ({0})\n", json);
            return(LoadedSettings);
        }
        /// <summary>
        ///		Sends a message across the network.
        /// </summary>
        public void SendMessage(T message)
        {
            string msg = JsonUtility.ToJson(message);

            byte[] messageByteArray = Encoding.ASCII.GetBytes(msg);
            SendMessage(messageByteArray);

            LoggingUtilities.LogFormat("Sent message (\"{0}\") to ip ({1}) using port ({2})", msg, SendingEndPoint.Address, SendingEndPoint.Port);
        }
Example #22
0
        private bool TryProcessSubscriptionRequest(FblRequestParameters fblRequestParameters)
        {
            if (fblRequestParameters == null)
            {
                return(false);
            }
            ExPerformanceCounter exPerformanceCounter       = fblRequestParameters.OptIn ? FBLPerfCounters.NumberOfFblOptInRequestsReceived : FBLPerfCounters.NumberOfFblOptOutRequestsReceived;
            ExPerformanceCounter successSubscriptionCounter = fblRequestParameters.OptIn ? FBLPerfCounters.NumberOfFblOptInRequestsSuccessfullyProcessed : FBLPerfCounters.NumberOfFblOptOutRequestsSuccessfullyProcessed;
            ExPerformanceCounter failedSubscriptionCounter  = fblRequestParameters.OptIn ? FBLPerfCounters.NumberOfFblOptInRequestsFailed : FBLPerfCounters.NumberOfFblOptOutRequestsFailed;

            try
            {
                FBLPerfCounters.NumberOfFblSubscriptionRequestsReceived.Increment();
                exPerformanceCounter.Increment();
                ADUser aduser = this.GetADUser(fblRequestParameters.Puid, fblRequestParameters.PrimaryEmail);
                if (aduser == null || !this.TryUpdateMservEntry(aduser, fblRequestParameters))
                {
                    FBLPerfCounters.NumberOfFblSubscriptionRequestsFailed.Increment();
                    failedSubscriptionCounter.Increment();
                    return(false);
                }
                Task.Factory.StartNew(delegate()
                {
                    if (this.TryPrepareAndSendXmrMessage(fblRequestParameters, "*****@*****.**"))
                    {
                        FBLPerfCounters.NumberOfFblSubscriptionRequestsSuccessfullyProcessed.Increment();
                        successSubscriptionCounter.Increment();
                        return;
                    }
                    FBLPerfCounters.NumberOfFblSubscriptionRequestsFailed.Increment();
                    failedSubscriptionCounter.Increment();
                }).ContinueWith(delegate(Task t)
                {
                    if (t.Exception != null)
                    {
                        FBLPerfCounters.NumberOfFblSubscriptionRequestsFailed.Increment();
                        failedSubscriptionCounter.Increment();
                        Exception innerException = t.Exception.Flatten().InnerException;
                        LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_FblUnableToProcessRequest, new object[]
                        {
                            innerException
                        });
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);
            }
            catch (Exception ex)
            {
                FBLPerfCounters.NumberOfFblSubscriptionRequestsFailed.Increment();
                failedSubscriptionCounter.Increment();
                LoggingUtilities.LogEvent(ClientsEventLogConstants.Tuple_FblUnableToProcessRequest, new object[]
                {
                    ex.InnerException ?? ex
                });
                return(false);
            }
            return(true);
        }
Example #23
0
        //public IRepository<TEntity> Repository
        //{
        //    get { return repository; }
        //}

        #endregion Properties

        #region Constructor

        public GenericDataService(ICacheManager cacheManager, IRepository <TEntity> repository)
        {
            this.cacheManager = cacheManager;
            this.repository   = repository;
            this.Logger       = LoggingUtilities.Resolve();

            // Resolving eventBus this way for now instead of via constructor injection, because
            //  putting it into the constructor will mean changing a LOT of classes in multiple projects..
            //  That will take too much time. Might do it in future, if necessary.
            this.eventBus = EngineContext.Current.Resolve <IEventBus>();
        }
        /// <summary>
        /// Validate Server Certificate
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="certificate">X509 Certificate</param>
        /// <param name="chain">X509 Chain</param>
        /// <param name="sslPolicyErrors">SSL Policy Errors</param>
        /// <returns>Returns true if no errors occurred.</returns>
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            LoggingUtilities.WriteLog($"Certificate error: {sslPolicyErrors}");

            return(false);
        }
        public void SendPreLogin()
        {
            LoggingUtilities.WriteLog($" SendPreLogin initiated.");
            var tdsMessageBody = new TDSPreLoginPacketData(Version);

            tdsMessageBody.AddOption(TDSPreLoginOptionTokenType.Encryption, TDSEncryptionOption.EncryptOff);
            tdsMessageBody.Terminate();

            TdsCommunicator.SendTDSMessage(tdsMessageBody);
            LoggingUtilities.WriteLog($" SendPreLogin done.");
        }
        // FeatureExt - unsupported
        public void AddOption(string optionName, ushort length, object data)
        {
            if (optionName == null || data == null)
            {
                throw new ArgumentNullException();
            }

            OffsetLength.AddOptionPositionInfo(optionName, length);
            var prevLength = Data != null ? Data.Length : 0;

            byte[] optionData;
            if (optionName != "SSPI")
            {
                if (!(data is string))
                {
                    throw new ArgumentException();
                }

                optionData = Encoding.Unicode.GetBytes((string)data);

                if (optionName != "Password")
                {
                    LoggingUtilities.WriteLogVerboseOnly($" Adding Login7 option {optionName} [{(string)data}].");
                }
                else
                {
                    LoggingUtilities.WriteLogVerboseOnly($" Adding Login7 option {optionName}.");
                }
            }
            else
            {
                if (!(data is byte[]))
                {
                    throw new ArgumentException();
                }

                optionData = (byte[])data;
                LoggingUtilities.WriteLogVerboseOnly($" Adding Login7 option {optionName}.");
            }

            Array.Resize(ref Data, prevLength + optionData.Length);

            if (optionName == "Password")
            {
                for (int i = 0; i < optionData.Length; i++)
                {
                    var piece0 = (byte)(optionData[i] >> 4);
                    var piece1 = (byte)(optionData[i] & 0x0f);
                    optionData[i] = (byte)((piece0 | (piece1 << 4)) ^ 0xA5);
                }
            }

            Array.Copy(optionData, 0, Data, prevLength, optionData.Length);
        }
Example #27
0
        /// <summary>
        ///		Closes used port and message receiving thread.
        /// </summary>
        public virtual void Kill()
        {
            LoggingUtilities.LogFormat("Killing UDPMaster");

            SendingSocket.Close();

            Receiver.Close();
            ReceiverThread.Abort();

            IsInitialized = false;
        }
Example #28
0
 internal void SetConnection(string commandText, IDbConnection connection)
 {
     if (connection == null)
     {
         if (LoggingUtilities.FindSqlCommand(CommandCollection, commandText).Connection != null)
         {
             LoggingUtilities.FindSqlCommand(CommandCollection, commandText).Connection.Close();
         }
     }
     LoggingUtilities.FindSqlCommand(CommandCollection, commandText).Connection = connection;
 }
Example #29
0
        /// <summary>
        /// Sends PreLogin message to the server.
        /// </summary>
        public void SendPreLogin()
        {
            LoggingUtilities.WriteLog($" SendPreLogin initiated.");
            var tdsMessageBody = new TDSPreLoginPacketData(this.Version);

            tdsMessageBody.AddOption(TDSPreLoginOptionTokenType.Encryption, TDSEncryptionOption.EncryptOff);
            tdsMessageBody.AddOption(TDSPreLoginOptionTokenType.TraceID, new TDSClientTraceID(Guid.NewGuid().ToByteArray(), Guid.NewGuid().ToByteArray(), 0));
            tdsMessageBody.Terminate();

            this.TdsCommunicator.SendTDSMessage(tdsMessageBody);
            LoggingUtilities.WriteLog($" SendPreLogin done.");
        }
Example #30
0
        public void Execute()
        {
            int maxTries;
            int messagesPerBatch;

            // TODO: This will now be a problem because of tenants feature.. we need to do this task for each tenant
            var smtpSettings = EngineContext.Current.Resolve <SmtpSettings>();

            if (!string.IsNullOrEmpty(smtpSettings.Host))
            {
                maxTries         = smtpSettings.MaxTries;
                messagesPerBatch = smtpSettings.MessagesPerBatch;
            }
            else
            {
                maxTries         = 3;
                messagesPerBatch = 50;
            }

            var emailSender = EngineContext.Current.Resolve <IEmailSender>();
            var providers   = EngineContext.Current.ResolveAll <IQueuedMessageProvider>();

            //var componentContext = EngineContext.Current.Resolve<IComponentContext>();
            //var logger = componentContext.Resolve<ILogger>(new TypedParameter(typeof(Type), typeof(ProcessQueuedMailTask)));
            var logger      = LoggingUtilities.Resolve();
            var workContext = EngineContext.Current.Resolve <IWorkContext>();

            foreach (var provider in providers)
            {
                var queuedEmails = provider.GetQueuedEmails(workContext.CurrentTenant.Id, maxTries, messagesPerBatch);

                if (!queuedEmails.Any())
                {
                    continue;
                }

                foreach (var queuedEmail in queuedEmails)
                {
                    try
                    {
                        var mailMessage = queuedEmail.GetMailMessage();
                        emailSender.Send(mailMessage);
                        provider.OnSendSuccess(queuedEmail);
                    }
                    catch (Exception x)
                    {
                        logger.Error(string.Format("Error sending e-mail. {0}", x.Message), x);
                        provider.OnSendError(queuedEmail);
                    }
                }
            }
        }