コード例 #1
0
 public SkypeManager(ILogHandler logger, IMessageRouter<IMessage> messageRouter, List<ISkypeBehaviour> skypeBehaviours)
 {
     Logger = logger;
     MessageRouter = messageRouter;
     AttachedBehaviours = skypeBehaviours;
     Priority = Priority.Normal;
 }
コード例 #2
0
        public AdminController(IAdminModuleManager adminModuleManager, ILogHandler logHandler, IWebSiteModuleManager webSiteModuleManager)
        {
            AdminModuleManager = adminModuleManager;
            LogHandler = logHandler;

            //this.ViewBag.TemplatedPageList = webSiteModuleManager.GetTemplatedPages();
        }
コード例 #3
0
        public CommandLoggerAdapter([NotNull] string name, [NotNull] ILogHandler logHandler)
            : base(name)
        {
            Check.NotNull(logHandler, nameof(logHandler));

            _logHandler = logHandler;
        }
コード例 #4
0
ファイル: AlgorithmRunner.cs プロジェクト: AlexCatarino/Lean
        public static void RunLocalBacktest(string algorithm, Dictionary<string, string> expectedStatistics, Language language)
        {
            var statistics = new Dictionary<string, string>();

            Composer.Instance.Reset();

            try
            {
                // set the configuration up
                Config.Set("algorithm-type-name", algorithm);
                Config.Set("live-mode", "false");
                Config.Set("environment", "");
                Config.Set("messaging-handler", "QuantConnect.Messaging.Messaging");
                Config.Set("job-queue-handler", "QuantConnect.Queues.JobQueue");
                Config.Set("api-handler", "QuantConnect.Api.Api");
                Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.BacktestingResultHandler");
                Config.Set("algorithm-language", language.ToString());
                Config.Set("algorithm-location", "QuantConnect.Algorithm." + language + ".dll");

                var debugEnabled = Log.DebuggingEnabled;

                var logHandlers = new ILogHandler[] {new ConsoleLogHandler(), new FileLogHandler("regression.log", false)};
                using (Log.LogHandler = new CompositeLogHandler(logHandlers))
                using (var algorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance))
                using (var systemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance))
                {
                    Log.DebuggingEnabled = true;

                    Log.LogHandler.Trace("");
                    Log.LogHandler.Trace("{0}: Running " + algorithm + "...", DateTime.UtcNow);
                    Log.LogHandler.Trace("");

                    // run the algorithm in its own thread

                    var engine = new Lean.Engine.Engine(systemHandlers, algorithmHandlers, false);
                    Task.Factory.StartNew(() =>
                    {
                        string algorithmPath;
                        var job = systemHandlers.JobQueue.NextJob(out algorithmPath);
                        engine.Run(job, algorithmPath);
                    }).Wait();

                    var backtestingResultHandler = (BacktestingResultHandler)algorithmHandlers.Results;
                    statistics = backtestingResultHandler.FinalStatistics;
                    
                    Log.DebuggingEnabled = debugEnabled;
                }
            }
            catch (Exception ex)
            {
                Log.LogHandler.Error("{0} {1}", ex.Message, ex.StackTrace);
            }

            foreach (var stat in expectedStatistics)
            {
                Assert.AreEqual(true, statistics.ContainsKey(stat.Key), "Missing key: " + stat.Key);
                Assert.AreEqual(stat.Value, statistics[stat.Key], "Failed on " + stat.Key);
            }
        }
コード例 #5
0
 public TemplatesModule(IConsoleRepository consoleRepository, ILogHandler logHandler,
                           ICurrentHttpContext currentHttpContext, IWebSiteModuleManager webSiteModuleManager)
 {
     this.LogHandler = logHandler;
     this.ConsoleRepository = consoleRepository;
     this.CurrentHttpContext = currentHttpContext;
     this.WebSiteModuleManager = webSiteModuleManager;
 }
コード例 #6
0
 public BlyncLightManager(ILogHandler logger, IMessageRouter<IMessage> messageRouter, List<IBlyncLightBehaviour> blyncLightBehaviours)
 {
     Logger = logger;
     MessageRouter = messageRouter;
     AttachedBehaviours = blyncLightBehaviours;
     Priority = Priority.High;
     DeviceStatus = DeviceStatus.Disconnected;
 }
コード例 #7
0
ファイル: CompositeLogHandler.cs プロジェクト: reddream/Lean
        /// <summary>
        /// Initializes a new instance of the <see cref="CompositeLogHandler"/> class from the specified handlers
        /// </summary>
        /// <param name="handlers">The implementations to compose</param>
        public CompositeLogHandler(ILogHandler[] handlers)
        {
            if (handlers == null || handlers.Length == 0)
            {
                throw new ArgumentNullException("handlers");
            }

            _handlers = handlers;
        }
        public void Init()
        {
            _container = new UnityContainer();
            _container.AddNewExtension<EnterpriseLibraryCoreExtension>();
            _logHandler = _container.Resolve<LogHandler>();

            // Note: this path is also set in "Rolling Flat File Trace Listener" section
            _logFileLocation = ConfigurationManager.AppSettings["logFileLocation"].ToString();
        }
コード例 #9
0
 public PolicyBusinessModule(IPolicyData policyData, 
     SubscribeService.IPolicyService subscribeService,
     PolicyDataService.IPolicyService policyDataService,
     IWebSiteModuleManager webSiteModuleManager, ILogHandler logHandler)
 {
     _policyData = policyData;
     _subscribeService = subscribeService;
     _policyDataService = policyDataService;
     _webSiteModuleManager = webSiteModuleManager;
     _logHandler = logHandler;
 }
コード例 #10
0
 public CrawlService(LogType logLevel)
 {
     _logLevel = logLevel;
     _log = new ConsoleLogHandler(_logLevel);
     SlowPageDetector = new SlowPageDetectorSettings();
     LargePageDetector = new LargePageDetectorSettings();
     ErrorDetector = new ErrorDetectorSettings();
     AllReferencesCollector = new AllReferencesCollectorSettings();
     SchemeCollector = new SchemeCollectorSettings();
     ExternalLinksCollector = new ExternalLinksCollectorSettings();
 }
コード例 #11
0
        public Crawler(ICrawl crawl, ILogHandler log, IExaminerFactory examinerFactory, IEnumerable<IInspector> inspectors)
        {
            if (crawl == null) throw new ArgumentNullException(nameof(crawl));
            if (log == null) throw new ArgumentNullException(nameof(log));
            if (examinerFactory == null) throw new ArgumentNullException(nameof(examinerFactory));
            if (inspectors == null) throw new ArgumentNullException(nameof(inspectors));

            _crawl = crawl;
            _log = log;
            _examinerFactory = examinerFactory;
            _inspectors = inspectors.ToList();
        }
コード例 #12
0
        /// <summary>
        /// Usual Initialize summary
        /// </summary>
        public override void Initialize()
        {
            //Initialize dates
            SetStartDate(new DateTime(2016, 1, 11));
            SetEndDate(new DateTime(2016, 1, 14));
            SetCash(50000);

            AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);

            // Uncomment this instantition
            mylog = Composer.Instance.GetExportedValueByTypeName<ILogHandler>("CustomFileLogHandler");

        }
コード例 #13
0
        public DNP3SimulatorPlugin(ILog log)
        {
            this.logHandler = new ForwardingLogHandler(log);

            this.manager = DNP3ManagerFactory.CreateManager(this.logHandler);

            imgList.Images.Add(Properties.Resources.satellite_dish);
            imgList.Images.Add(Properties.Resources.network_monitor);
            imgList.Images.Add(Properties.Resources.send_container);

            /*
                Load outstation plugins here
            */
        }
コード例 #14
0
 /// <summary>
 /// Aggiunge un gestore dei messaggi di log e restituisce true se l'oggetto specificato è stato aggiunto,
 /// altrimenti false se è già presente oppure è null e quindi non è stato aggiunto.
 /// </summary>
 /// <param name="handler">il gestore da aggiungere</param>
 /// <returns>true se l'oggetto specificato è stato aggiunto, altrimenti false se è null o già presente</returns>
 public bool Add(ILogHandler handler)
 {
     lock (m_SyncLock)
     {
         if (handler != null && !m_LogHandlers.Contains(handler))
         {
             m_LogHandlers.Add(handler);
             return true;
         }
         else
         {
             return false;
         }
     }
 }
        public static void Init(TestContext context)
        {
            GetMockSubscribeService();
            GetMockCurrentHttpContext();
            CreateBasicSubmission();
            CreateComplexSubmission();
            
            _container = new UnityContainer();
            _container.AddNewExtension<EnterpriseLibraryCoreExtension>();
            _logHandler = _container.Resolve<LogHandler>();
            _consoleRepository = _container.Resolve<ConsoleRepository>();

            var mockCurrentHttpContext = new Mock<CurrentHttpContext>();
            var user = @"talbotdev\MurrayE";
            user = user.Replace(@"\\", @"\");
            mockCurrentHttpContext.Setup(h => h.CurrentUser).Returns(new GenericPrincipal(new GenericIdentity(user), null));
            mockCurrentHttpContext.Setup(h => h.Context).Returns(MvcMockHelpers.FakeHttpContextWithSession());
        }
コード例 #16
0
ファイル: AlgorithmRunner.cs プロジェクト: aihua/quant-lean
        public static void RunLocalBacktest(string algorithm, Dictionary <string, string> expectedStatistics, AlphaRuntimeStatistics expectedAlphaStatistics, Language language)
        {
            var statistics       = new Dictionary <string, string>();
            var alphaStatistics  = new AlphaRuntimeStatistics();
            var algorithmManager = new AlgorithmManager(false);

            Composer.Instance.Reset();
            var ordersLogFile = string.Empty;
            var logFile       = $"./regression/{algorithm}.{language.ToLower()}.log";

            Directory.CreateDirectory(Path.GetDirectoryName(logFile));
            File.Delete(logFile);

            try
            {
                // set the configuration up
                Config.Set("algorithm-type-name", algorithm);
                Config.Set("live-mode", "false");
                Config.Set("environment", "");
                Config.Set("messaging-handler", "QuantConnect.Messaging.Messaging");
                Config.Set("job-queue-handler", "QuantConnect.Queues.JobQueue");
                Config.Set("setup-handler", "RegressionSetupHandlerWrapper");
                Config.Set("history-provider", "RegressionHistoryProviderWrapper");
                Config.Set("api-handler", "QuantConnect.Api.Api");
                Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.RegressionResultHandler");
                Config.Set("algorithm-language", language.ToString());
                Config.Set("algorithm-location",
                           language == Language.Python
                        ? "../../../Algorithm.Python/" + algorithm + ".py"
                        : "QuantConnect.Algorithm." + language + ".dll");


                var debugEnabled = Log.DebuggingEnabled;


                var logHandlers = new ILogHandler[] { new ConsoleLogHandler(), new FileLogHandler(logFile, false) };
                using (Log.LogHandler = new CompositeLogHandler(logHandlers))
                    using (var algorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance))
                        using (var systemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance))
                        {
                            Log.DebuggingEnabled = true;

                            Log.LogHandler.Trace("");
                            Log.LogHandler.Trace("{0}: Running " + algorithm + "...", DateTime.UtcNow);
                            Log.LogHandler.Trace("");

                            // run the algorithm in its own thread

                            var engine = new Lean.Engine.Engine(systemHandlers, algorithmHandlers, false);
                            Task.Factory.StartNew(() =>
                            {
                                try
                                {
                                    string algorithmPath;
                                    var job = systemHandlers.JobQueue.NextJob(out algorithmPath);
                                    ((BacktestNodePacket)job).BacktestId = algorithm;
                                    engine.Run(job, algorithmManager, algorithmPath);
                                    ordersLogFile = ((RegressionResultHandler)algorithmHandlers.Results).OrdersLogFilePath;
                                }
                                catch (Exception e)
                                {
                                    Log.LogHandler.Trace($"Error in AlgorithmRunner task: {e}");
                                }
                            }).Wait();

                            var backtestingResultHandler = (BacktestingResultHandler)algorithmHandlers.Results;
                            statistics = backtestingResultHandler.FinalStatistics;

                            var defaultAlphaHandler = (DefaultAlphaHandler)algorithmHandlers.Alphas;
                            alphaStatistics = defaultAlphaHandler.RuntimeStatistics;

                            Log.DebuggingEnabled = debugEnabled;
                        }
            }
            catch (Exception ex)
            {
                Log.LogHandler.Error("{0} {1}", ex.Message, ex.StackTrace);
            }
            if (algorithmManager.State != AlgorithmStatus.Completed)
            {
                Assert.Fail($"Algorithm state should be completed and is: {algorithmManager.State}");
            }

            foreach (var stat in expectedStatistics)
            {
                Assert.AreEqual(true, statistics.ContainsKey(stat.Key), "Missing key: " + stat.Key);
                Assert.AreEqual(stat.Value, statistics[stat.Key], "Failed on " + stat.Key);
            }

            if (expectedAlphaStatistics != null)
            {
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.MeanPopulationScore.Direction);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.MeanPopulationScore.Magnitude);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.RollingAveragedPopulationScore.Direction);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.RollingAveragedPopulationScore.Magnitude);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.LongShortRatio);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsClosed);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsGenerated);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalAccumulatedEstimatedAlphaValue);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsAnalysisCompleted);
            }

            // we successfully passed the regression test, copy the log file so we don't have to continually
            // re-run master in order to compare against a passing run
            var passedFile = logFile.Replace("./regression/", "./passed/");

            Directory.CreateDirectory(Path.GetDirectoryName(passedFile));
            File.Delete(passedFile);
            File.Copy(logFile, passedFile);

            var passedOrderLogFile = ordersLogFile.Replace("./regression/", "./passed/");

            Directory.CreateDirectory(Path.GetDirectoryName(passedFile));
            File.Delete(passedOrderLogFile);
            if (File.Exists(ordersLogFile))
            {
                File.Copy(ordersLogFile, passedOrderLogFile);
            }
        }
コード例 #17
0
        /// <summary>
        /// To send notify email for change contract fee
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="BatchDate"></param>
        /// <returns></returns>
        public SECOM_AJIS.Common.Util.doBatchProcessResult SendNotifyEmailForChangeFee(string UserId, DateTime BatchDate)
        {
            SECOM_AJIS.Common.Util.doBatchProcessResult doResult = new SECOM_AJIS.Common.Util.doBatchProcessResult();
            try
            {
                ILogHandler handLog = ServiceContainer.GetService <ILogHandler>() as ILogHandler;

                //1. Get list of unsent email
                List <tbt_ContractEmail> dtTbt_ContractEmail = this.GetUnsentNotifyEmail();

                //2. For each unsent email in dtTbt_ContractEmail
                int failedItem    = 0;
                int completdeItem = 0;
                foreach (tbt_ContractEmail email in dtTbt_ContractEmail)
                {
                    //2.1 Prepare destination email
                    //2.1.1 Get employee data of destination email
                    IEmployeeMasterHandler handMaster = ServiceContainer.GetService <IEmployeeMasterHandler>() as IEmployeeMasterHandler;
                    List <tbm_Employee>    dtEmployee = handMaster.GetTbm_Employee(email.ToEmpNo);

                    //2.1.2 If dtEmployee is empty
                    if (dtEmployee.Count <= 0)
                    {
                        handLog.WriteWindowLog(EventType.C_EVENT_TYPE_ERROR, (MessageUtil.GetMessage(MessageUtil.MODULE_CONTRACT, MessageUtil.MessageList.MSG3077, email.ToEmpNo)).Message, EventID.C_EVENT_ID_NOTIFY_EMAIL_ERROR);
                        failedItem += 1;
                        continue;
                    }

                    //2.1.3 Get default email if endDate is not empty
                    String strEmailTo = (dtEmployee[0].EndDate != null) ?
                                        this.getEmailsOfDefaultDepartment() :
                                        dtEmployee[0].EmailAddress;

                    //2.2 Prepare email object for sending
                    doEmailProcess emailProc = new doEmailProcess();
                    emailProc.MailTo   = strEmailTo;
                    emailProc.MailFrom = email.EmailFrom;
                    emailProc.Subject  = email.EmailSubject;
                    emailProc.Message  = email.EmailContent;

                    //2.3 Send email
                    //2.3.1 Retry for 3 times while strStatus is still fails
                    int retry = 0;
                    do
                    {
                        try
                        {
                            ICommonHandler commonHand = ServiceContainer.GetService <ICommonHandler>() as ICommonHandler;
                            commonHand.SendMail(emailProc);
                            break;
                        }
                        catch (Exception)
                        {
                            retry += 1;
                        }
                    } while (retry < 3);

                    ICommonContractHandler comContractHand = ServiceContainer.GetService <ICommonContractHandler>() as ICommonContractHandler;
                    if (retry == 3)
                    {
                        failedItem += 1;
                        email.FailSendingCounter = (email.FailSendingCounter == null) ? 1 : email.FailSendingCounter + 1;
                        email.UpdateBy           = UserId;
                        //Update to database
                        comContractHand.UpdateTbt_ContractEmail(email);

                        //Check the number of fail for reporting error
                        if (email.FailSendingCounter >= 6 && email.FailSendingCounter % 3 == 0)
                        {
                            handLog.WriteWindowLog(EventType.C_EVENT_TYPE_ERROR, (MessageUtil.GetMessage(MessageUtil.MODULE_CONTRACT, MessageUtil.MessageList.MSG3078, strEmailTo)).Message, EventID.C_EVENT_ID_NOTIFY_EMAIL_ERROR);
                        }
                    }
                    else
                    {
                        completdeItem += 1;

                        //Delete sent email
                        comContractHand.DeleteTbt_ContractEmail(email.ContractEmailID, UserId);
                    }
                }

                //3. Prepare process result for returning
                doResult.Result   = FlagType.C_FLAG_ON;
                doResult.Total    = dtTbt_ContractEmail.Count;
                doResult.Complete = completdeItem;
                doResult.Failed   = failedItem;
            }
            catch (Exception)
            {
                throw;
            }
            return(doResult);
        }
コード例 #18
0
 public InsuredBusinessModule(IInsuredData insuredData, ILogHandler logHandler, IConsoleRepository consoleRepository)
 {
     _logHandler = logHandler;
     _insuredData = insuredData;
     _consoleRepository = consoleRepository;
 }
コード例 #19
0
ファイル: Log.cs プロジェクト: qwad1000/NEFClassLib
 public static void RegisterHandler(ILogHandler handler)
 {
     if (!mHandlers.Contains(handler))
         mHandlers.Add(handler);
 }
コード例 #20
0
ファイル: Log.cs プロジェクト: qwad1000/NEFClassLib
 public static void UnregisterHandler(ILogHandler handler)
 {
     mHandlers.Remove(handler);
 }
コード例 #21
0
        public InterestModuleManager(IConsoleRepository rep, ILogHandler logHandler)
		{
			_repository = rep;
			_logHandler = logHandler;		    
		}
コード例 #22
0
 public CustomLogger(ILogHandler logHandler) : base(logHandler)
 {
 }
コード例 #23
0
ファイル: Log.cs プロジェクト: DLastStarFighter/Project37w
 public static void Unregister(ILogHandler handler)
 {
     GetInstance()._logHandlers.Remove(handler);
 }
コード例 #24
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

              mEventLog = new EventLog(
              mLogName
            , string.IsNullOrEmpty(mMachineName.Trim()) ? DEFAULT_MACHINE_NAME : mMachineName
            , mSourceName);

              mEventLog.EntryWritten       += EventLogEntryWritten;
              mEventLog.EnableRaisingEvents = true;
        }
コード例 #25
0
        public static CreateQuoteResponse CreateSubscribeRecord(Quote q, Submission s, ILogHandler logHandler, IPolicyService subsribeService)
        {
            var insuredList = new InsuredCollection();

            if (q.AdditionalInsuredList != null)
            {
                insuredList.AddRange(q.AdditionalInsuredList
                                     .Select(insured => new Insured
                {
                    AddlInsdId = insured.InsuredId,
                    AddlInsdNm = insured.InsuredId == 0 ? insured.InsuredName : null,
                    AddlInsdTy = insured.InsuredType
                }));
            }

            var policyContract = new PolicyContract
            {
                AccYr                 = q.AccountYear.ToString(),
                BenchPrm              = q.BenchmarkPremium,
                BindSt                = q.TechnicalPricingBindStatus,
                BkrNo                 = "???",             // TODO - not referenced in CreateQuote sp
                BkrPsu                = q.BrokerPseudonym, // No validation carried out in service validation sp
                BkrSeqId              = q.BrokerSequenceId,
                Brokerage             = q.Brokerage,
                COB                   = q.COBId,
                DeclineReason         = q.DeclinatureReason,
                DOM                   = q.Domicile,
                EntSt                 = q.EntryStatus,
                ExpyDt                = (q.ExpiryDate.HasValue) ? q.ExpiryDate.Value.ToString("yyyyMMdd") : null,
                ExsAmt                = q.ExcessAmount,
                FacyPolId             = (String.IsNullOrEmpty(q.RenPolId) ? q.FacilityRef : String.Empty),
                LdrNo                 = q.LeaderNo,
                Ldr                   = q.Leader,
                IncpDt                = (q.InceptionDate.HasValue) ? q.InceptionDate.Value.ToString("yyyyMMdd") : null,
                InsdId                = q.InsuredId,
                InsdNm                = q.InsuredName,
                AddlInsuredCollection = insuredList,
                LmtAmt                = q.LimitAmount,
                LmtCcy                = q.LimitCCY,
                MOA                   = q.MOA,
                OrigOff               = q.OriginatingOfficeId,
                PolTy                 = q.PolicyType,
                PricingCcy            = q.Currency,
                RenPolId              = q.RenPolId,
                Status                = q.SubmissionStatus,
                TechPrm               = q.TechnicalPremium,
                UnitPsu               = "AGY",
                Uwr                   = q.UnderwriterCode,
                ExsCcy                = q.ExcessCCY,
                Method                = q.TechnicalPricingMethod,
                NonLonBkr             = q.NonLondonBrokerCode,
                PctgAmt               = q.TechnicalPricingPremiumPctgAmt,

                TechPmTy = "TechPm",     // TODO - not referenced in CreateQuote sp
                PolDsc   = q.Description,

                //  These are the fields required for edit only
                TimeStamp = q.SubscribeTimestamp,
                PolId     = q.SubscribeReference,

                // PolAnlyCd
                // TODO: Update this win value from form.
                WordReqd  = (string.IsNullOrEmpty(q.WordingRequired)) ? "" : q.WordingRequired,
                AggsReqd  = (string.IsNullOrEmpty(q.AggsRequired)) ? "" : q.AggsRequired,
                FSA_Class = (string.IsNullOrEmpty(q.FSAClass)) ? "" : q.FSAClass,

                CtcNm = q.BrokerContact,
                //CtcTelNo = q.BrokerContactPhone,
                //CtcEmail = q.BrokerContactEmail
            };

            if (q.QuoteExpiryDate != null)
            {
                policyContract.SettDueDt = SetSettlementDueDate(q.QuoteExpiryDate.Value, s.ExpiryDateOffset, q.InceptionDate);
            }
            if (!string.IsNullOrEmpty(q.BrokerContactPhone))
            {
                policyContract.CtcTelNo = q.BrokerContactPhone;
            }
            if (!string.IsNullOrEmpty(q.BrokerContactEmail))
            {
                policyContract.CtcEmail = q.BrokerContactEmail;
            }

            if (q.RenewalRate.HasValue)
            {
                policyContract.RenewalRate = q.RenewalRate;
            }
            if (q.RenewalConditions.HasValue)
            {
                policyContract.RenewalConditions = q.RenewalConditions;
            }
            if (q.RenewalDeductibles.HasValue)
            {
                policyContract.RenewalDeductibles = q.RenewalDeductibles;
            }
            if (q.RenewalExposure.HasValue)
            {
                policyContract.RenewalExposurePctg = q.RenewalExposure;
            }
            if (q.RenewalBase.HasValue)
            {
                policyContract.RenewalBase = q.RenewalBase;
            }
            if (q.RenewalFull.HasValue)
            {
                policyContract.RenewalFull = q.RenewalFull;
            }

            var createQuoteResponse = subsribeService.CreateQuote(new CreateQuoteRequest
            {
                objPolicyContract = policyContract
            });

            if (createQuoteResponse.CreateQuoteResult.ErrorInfo == null)
            {
                q.SubscribeReference = createQuoteResponse.objInfoCollection.PolId;

                var doc = new XmlDocument();

                doc.LoadXml(createQuoteResponse.CreateQuoteResult.OutputXml);

                var subscribeTimestamp = default(long);

                q.SubscribeTimestamp = long.TryParse(doc.GetElementsByTagName("TimeStamp")[0].InnerText,
                                                     out subscribeTimestamp)
                                                   ? subscribeTimestamp
                                                   : 0;

                SyncQuoteCreateAndUpdate(s, q, subsribeService);
            }
            else
            {
                logHandler.WriteLog(createQuoteResponse.CreateQuoteResult.ErrorInfo.ErrorXML, LogSeverity.Error,
                                    LogCategory.BusinessComponent);

                throw new ApplicationException(
                          string.IsNullOrEmpty(createQuoteResponse.CreateQuoteResult.ErrorInfo.Description)
                                    ? ParseDetailedError(createQuoteResponse.CreateQuoteResult.ErrorInfo.DetailedDescription)
                                    : createQuoteResponse.CreateQuoteResult.ErrorInfo.Description);
            }

            return(createQuoteResponse);
        }
コード例 #26
0
 public void AddLogHandler(ILogHandler item)
 {
     mLogHandler.Handlers.Add(item);
 }
コード例 #27
0
	// Use this for initialization
	void Start () {
		
		if(SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 11") || SystemInfo.operatingSystem.Contains("Mac"))
		{
			DeviceSupportsSharedTextures = true;
		}
		
		if (m_UISystem == null)
		{
			m_SystemListener = (SystemListenerFactoryFunc != null)? SystemListenerFactoryFunc(this.OnSystemReady) : new SystemListener(this.OnSystemReady);
			m_LogHandler = new UnityLogHandler();
			if (FileHandlerFactoryFunc != null)
			{
				m_FileHandler = FileHandlerFactoryFunc();
			}
			if (m_FileHandler == null)
			{
				Debug.LogWarning("Unable to create file handler using factory function! Falling back to default handler.");
				m_FileHandler = new UnityFileHandler();
			}
			
			#if UNITY_EDITOR || COHERENT_UNITY_STANDALONE
			SystemSettings settings = new SystemSettings() { 
				HostDirectory = Path.Combine(Application.dataPath, this.HostDirectory),
				EnableProxy = this.EnableProxy,
				AllowCookies = this.AllowCookies,
				CookiesResource = "file:///" + Application.persistentDataPath + '/' + this.CookiesResource,
				CachePath = Path.Combine(Application.temporaryCachePath, this.CachePath),
				HTML5LocalStoragePath = Path.Combine(Application.temporaryCachePath, this.HTML5LocalStoragePath),
				ForceDisablePluginFullscreen = this.ForceDisablePluginFullscreen,
				DisableWebSecurity = this.DisableWebSecutiry,
				DebuggerPort = this.DebuggerPort,
			};
			#elif UNITY_IPHONE
			SystemSettings settings = new SystemSettings() {
				
			};
			#endif
			if (string.IsNullOrEmpty(Coherent.UI.License.COHERENT_KEY))
			{
				throw new System.ApplicationException("You must supply a license key to start Coherent UI! Follow the instructions in the manual for editing the License.cs file.");
			}
			m_UISystem = CoherentUI_Native.InitializeUISystem(Coherent.UI.License.COHERENT_KEY, settings, m_SystemListener, Severity.Warning, m_LogHandler, m_FileHandler);
			if (m_UISystem == null)
			{
				throw new System.ApplicationException("UI System initialization failed!");
			}
			Debug.Log ("Coherent UI system initialized..");
		}
		
		DontDestroyOnLoad(this.gameObject);
	}
コード例 #28
0
 public RiskCodeController(IRiskCodeModuleManager riskCodeServiceModuleManager, ILogHandler logHandler)
 {
     _riskCodeServiceModuleManager = riskCodeServiceModuleManager;
     _logHandler = logHandler;
 }
コード例 #29
0
 public OrderController(IMapper mapper, IRepositoryWrapper repository, ILogHandler logger)
 {
     _mapper     = mapper;
     _repository = repository;
     _logger     = logger;
 }
コード例 #30
0
        public static UpdatePolicyResponse UpdateSubscribeRecord(Quote q, Submission s, ILogHandler logHandler, IPolicyService subsribeService)
        {
            var insuredList = new InsuredCollection();
            if (s.AdditionalInsuredList != null)
            {
                insuredList.AddRange(s.AdditionalInsuredList
                                      .Select(insured => new Insured
                                      {
                                          AddlInsdId = insured.InsuredId,
                                          AddlInsdNm = insured.InsuredId == 0 ? insured.InsuredName : null,
                                          AddlInsdTy = insured.InsuredType
                                      }));
            }

            var policyContract = new PolicyContract
            {
                AccYr = q.AccountYear.ToString(),
                BenchPrm = q.BenchmarkPremium,
                BindSt = q.TechnicalPricingBindStatus,
                BkrNo = "???", // TODO - not referenced in CreateQuote sp
                BkrPsu = s.BrokerPseudonym, // No validation carried out in service validation sp
                BkrSeqId = s.BrokerSequenceId,
                Brokerage = s.Brokerage,
                COB = q.COBId,
                DeclineReason = q.DeclinatureReason,
                DOM = s.Domicile,
                EntSt = q.EntryStatus,
                ExpyDt = (q.ExpiryDate.HasValue) ? q.ExpiryDate.Value.ToString("yyyyMMdd") : null,
                ExsAmt = q.ExcessAmount,
                FacyPolId = q.FacilityRef,
                LdrNo = s.LeaderNo,
                Ldr = s.Leader,
                IncpDt = (q.InceptionDate.HasValue) ? q.InceptionDate.Value.ToString("yyyyMMdd") : null,
                InsdId = s.InsuredId,
                InsdNm = s.InsuredName,
                AddlInsuredCollection = insuredList,
                LmtAmt = q.LimitAmount,
                LmtCcy = q.LimitCCY,
                MOA = q.MOA,
                OrigOff = q.OriginatingOfficeId,
                PolTy = q.PolicyType,
                PricingCcy = q.Currency,
                RenPolId = q.RenPolId,
                Status = q.SubmissionStatus,
                TechPrm = q.TechnicalPremium,
                UnitPsu = "AGY",
                Uwr = s.UnderwriterCode,
                ExsCcy = q.ExcessCCY,
                Method = q.TechnicalPricingMethod,
                NonLonBkr = s.NonLondonBrokerCode,
                PctgAmt = q.TechnicalPricingPremiumPctgAmt,
                SettDueDt = q.QuoteExpiryDate.ToString("yyyyMMdd"),
                TechPmTy = "TechPm", // TODO - not referenced in CreateQuote sp
                PolDsc = q.Description,

                //  These are the fields required for edit only
                TimeStamp = q.SubscribeTimestamp,
                PolId = q.SubscribeReference,

                CtcNm = (string.IsNullOrEmpty(s.BrokerContact)) ? s.NewBrokerContactName : s.BrokerContact,
                CtcTelNo = s.NewBrokerContactPhoneNumber,
                CtcEmail = s.NewBrokerContactEmail
            };

            if (q.RenewalRate.HasValue) policyContract.RenewalRate = q.RenewalRate;
            if (q.RenewalConditions.HasValue) policyContract.RenewalConditions = q.RenewalConditions;
            if (q.RenewalDeductibles.HasValue) policyContract.RenewalDeductibles = q.RenewalDeductibles;
            if (q.RenewalExposure.HasValue) policyContract.RenewalExposurePctg = q.RenewalExposure;
            if (q.RenewalBase.HasValue) policyContract.RenewalBase = q.RenewalBase;
            if (q.RenewalFull.HasValue) policyContract.RenewalFull = q.RenewalFull;

            var updateResp = subsribeService.UpdatePolicy(new UpdatePolicyRequest
            {
                objPolicyContract = policyContract
            });
          
            if (updateResp.UpdatePolicyResult.ErrorInfo == null)
            {
                
                    var doc = new XmlDocument();

                    doc.LoadXml(updateResp.UpdatePolicyResult.OutputXml);

                    q.SubscribeTimestamp = long.Parse(doc.GetElementsByTagName("TimeStamp")[0].InnerText);

                    q.FacilityRef = string.IsNullOrEmpty(doc.GetElementsByTagName("NewFacyPolId")[0].InnerText)
                                        ? q.FacilityRef
                                        : doc.GetElementsByTagName("NewFacyPolId")[0].InnerText;
               
               
            }
            else
            {
                logHandler.WriteLog(updateResp.UpdatePolicyResult.ErrorInfo.ErrorXML, LogSeverity.Error,
                                     LogCategory.BusinessComponent);

                throw new ApplicationException(
                    string.IsNullOrEmpty(updateResp.UpdatePolicyResult.ErrorInfo.Description)
                        ? ParseDetailedError(updateResp.UpdatePolicyResult.ErrorInfo.DetailedDescription)
                        : updateResp.UpdatePolicyResult.ErrorInfo.Description);
            }

            return updateResp;
        }
コード例 #31
0
        public PolicyController(IPolicyBusinessModule bm, IWebSiteModuleManager webSiteModuleManager, ILogHandler logHandler)
        {
			this._policyBusinessModule = bm;
            _webSiteModuleManager = webSiteModuleManager;
            _logHandler = logHandler;
        }
コード例 #32
0
 public WorldCheckController(IWorldCheckBusinessModule bm, ILogHandler logHandler)
 {
     _bm = bm;
     _logHandler = logHandler;
 }
コード例 #33
0
 public UserController(IWebSiteModuleManager websiteModuleManager, ILogHandler logHandler)
 {
     this._websiteModuleManager = websiteModuleManager;
     this._logHandler = logHandler;
 }
コード例 #34
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

              try
              {
            mUdpClient        = new UdpClient();
            mUdpClient.Client = new Socket(
            AddressFamily.InterNetwork
              , SocketType.Dgram
              , ProtocolType.Udp);

            IPEndPoint localEP = new IPEndPoint(
            mListenInterface.Address
              , mListenInterface.Port);

            mUdpClient.Client.Bind(localEP);

            if (mMulticastIpAddress != null)
            {
              try
              {
            mUdpClient.JoinMulticastGroup(
                mMulticastIpAddress
              , mListenInterface.Address);
              }
              catch (Exception ex)
              {
            Logger.Warn(ex.Message);
              }
            }

            UdpState state = new UdpState(
            mUdpClient
              , mListenInterface);

            mUdpClient.BeginReceive(
            ReceiveUdpMessage
              , state);
              }
              catch (Exception ex)
              {
            Logger.Warn(ex.Message);
              }
        }
コード例 #35
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

            Regex         filePattern    = new Regex(mFilenamePattern);
            DirectoryInfo dirInfo        = new DirectoryInfo(mDirectoryToObserve);
            List <string> collectedFiles = new List <string>();

            foreach (FileInfo fInfo in dirInfo.GetFiles())
            {
                if (filePattern.IsMatch(fInfo.FullName))
                {
                    collectedFiles.Add(fInfo.FullName);
                }
            }

            // Ensure the list of files is natural sorted.
            collectedFiles.Sort(new NaturalStringComparer());

            mLogNumber = 1;

            if (mStartFromBeginning)
            {
                for (int i = collectedFiles.Count - 1; i > 0; i--)
                {
                    using (mFileReader = new StreamReader(new FileStream(collectedFiles[i], FileMode.Open, FileAccess.Read, FileShare.ReadWrite), mEncoding))
                    {
                        // Reset file offset count.
                        mLastFileOffset = 0;

                        // Read the current file.
                        ReadNewLogMessagesFromFile();
                    }
                }
            }

            if (collectedFiles.Count > 0)
            {
                // The very first file (without decimal suffix) is the current log file.
                mCurrentLogFile = collectedFiles[0];

                mFileReader = new StreamReader(new FileStream(
                                                   mCurrentLogFile
                                                   , FileMode.Open
                                                   , FileAccess.Read
                                                   , FileShare.ReadWrite)
                                               , mEncoding);

                if (!mStartFromBeginning)
                {
                    // Ommit the already logged data.
                    mLastFileOffset = mFileReader.BaseStream.Length;
                }

                ReadNewLogMessagesFromFile();
            }

            mFileWatcher = new FileSystemWatcher(mDirectoryToObserve);

            mFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.FileName;
            mFileWatcher.Changed     += OnLogFileChanged;
            mFileWatcher.Created     += OnLogFileChanged;
            mFileWatcher.Error       += OnFileWatcherError;

            mFileWatcher.EnableRaisingEvents = IsActive;
        }
コード例 #36
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

              mFileReader = new StreamReader(new FileStream(
              mFileToObserve
            , FileMode.Open
            , FileAccess.Read
            , FileShare.ReadWrite));

              mLogNumber      = 0;
              mLastFileOffset = mStartFromBeginning
            ? 0
            : mFileReader.BaseStream.Length;

              string pathOfFile = Path.GetDirectoryName(mFileToObserve);
              string nameOfFile = Path.GetFileName(mFileToObserve);

              if (!string.IsNullOrEmpty(pathOfFile) && !string.IsNullOrEmpty(nameOfFile))
              {
            mFileWatcher = new FileSystemWatcher(
            pathOfFile
              , nameOfFile);

            mFileWatcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.Size;
            mFileWatcher.Changed            += OnLogFileChanged;
            mFileWatcher.Error              += OnFileWatcherError;
            mFileWatcher.EnableRaisingEvents = IsActive;

            ReadNewLogMessagesFromFile();
              }
        }
コード例 #37
0
ファイル: AlgorithmRunner.cs プロジェクト: yzhao20/Lean
        public static AlgorithmRunnerResults RunLocalBacktest(
            string algorithm,
            Dictionary <string, string> expectedStatistics,
            AlphaRuntimeStatistics expectedAlphaStatistics,
            Language language,
            AlgorithmStatus expectedFinalStatus,
            DateTime?startDate  = null,
            DateTime?endDate    = null,
            string setupHandler = "RegressionSetupHandlerWrapper",
            decimal?initialCash = null)
        {
            AlgorithmManager algorithmManager = null;
            var statistics      = new Dictionary <string, string>();
            var alphaStatistics = new AlphaRuntimeStatistics(new TestAccountCurrencyProvider());
            BacktestingResultHandler results = null;

            Composer.Instance.Reset();
            SymbolCache.Clear();

            var ordersLogFile = string.Empty;
            var logFile       = $"./regression/{algorithm}.{language.ToLower()}.log";

            Directory.CreateDirectory(Path.GetDirectoryName(logFile));
            File.Delete(logFile);

            try
            {
                // set the configuration up
                Config.Set("algorithm-type-name", algorithm);
                Config.Set("live-mode", "false");
                Config.Set("environment", "");
                Config.Set("messaging-handler", "QuantConnect.Messaging.Messaging");
                Config.Set("job-queue-handler", "QuantConnect.Queues.JobQueue");
                Config.Set("setup-handler", setupHandler);
                Config.Set("history-provider", "RegressionHistoryProviderWrapper");
                Config.Set("api-handler", "QuantConnect.Api.Api");
                Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.RegressionResultHandler");
                Config.Set("algorithm-language", language.ToString());
                Config.Set("algorithm-location",
                           language == Language.Python
                        ? "../../../Algorithm.Python/" + algorithm + ".py"
                        : "QuantConnect.Algorithm." + language + ".dll");

                // Store initial log variables
                var initialLogHandler   = Log.LogHandler;
                var initialDebugEnabled = Log.DebuggingEnabled;

                // Use our current test LogHandler and a FileLogHandler
                var newLogHandlers = new ILogHandler[] { MaintainLogHandlerAttribute.GetLogHandler(), new FileLogHandler(logFile, false) };

                using (Log.LogHandler = new CompositeLogHandler(newLogHandlers))
                    using (var algorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance))
                        using (var systemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance))
                            using (var workerThread = new TestWorkerThread())
                            {
                                Log.DebuggingEnabled = true;

                                Log.Trace("");
                                Log.Trace("{0}: Running " + algorithm + "...", DateTime.UtcNow);
                                Log.Trace("");

                                // run the algorithm in its own thread
                                var engine = new Lean.Engine.Engine(systemHandlers, algorithmHandlers, false);
                                Task.Factory.StartNew(() =>
                                {
                                    try
                                    {
                                        string algorithmPath;
                                        var job          = (BacktestNodePacket)systemHandlers.JobQueue.NextJob(out algorithmPath);
                                        job.BacktestId   = algorithm;
                                        job.PeriodStart  = startDate;
                                        job.PeriodFinish = endDate;
                                        if (initialCash.HasValue)
                                        {
                                            job.CashAmount = new CashAmount(initialCash.Value, Currencies.USD);
                                        }
                                        algorithmManager = new AlgorithmManager(false, job);

                                        systemHandlers.LeanManager.Initialize(systemHandlers, algorithmHandlers, job, algorithmManager);

                                        engine.Run(job, algorithmManager, algorithmPath, workerThread);
                                        ordersLogFile = ((RegressionResultHandler)algorithmHandlers.Results).LogFilePath;
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Trace($"Error in AlgorithmRunner task: {e}");
                                    }
                                }).Wait();

                                var backtestingResultHandler = (BacktestingResultHandler)algorithmHandlers.Results;
                                results    = backtestingResultHandler;
                                statistics = backtestingResultHandler.FinalStatistics;

                                var defaultAlphaHandler = (DefaultAlphaHandler)algorithmHandlers.Alphas;
                                alphaStatistics = defaultAlphaHandler.RuntimeStatistics;
                            }

                // Reset settings to initial values
                Log.LogHandler       = initialLogHandler;
                Log.DebuggingEnabled = initialDebugEnabled;
            }
            catch (Exception ex)
            {
                if (expectedFinalStatus != AlgorithmStatus.RuntimeError)
                {
                    Log.Error("{0} {1}", ex.Message, ex.StackTrace);
                }
            }

            if (algorithmManager?.State != expectedFinalStatus)
            {
                Assert.Fail($"Algorithm state should be {expectedFinalStatus} and is: {algorithmManager?.State}");
            }

            foreach (var stat in expectedStatistics)
            {
                Assert.AreEqual(true, statistics.ContainsKey(stat.Key), "Missing key: " + stat.Key);
                Assert.AreEqual(stat.Value, statistics[stat.Key], "Failed on " + stat.Key);
            }

            if (expectedAlphaStatistics != null)
            {
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.MeanPopulationScore.Direction);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.MeanPopulationScore.Magnitude);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.RollingAveragedPopulationScore.Direction);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.RollingAveragedPopulationScore.Magnitude);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.LongShortRatio);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsClosed);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsGenerated);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalAccumulatedEstimatedAlphaValue);
                AssertAlphaStatistics(expectedAlphaStatistics, alphaStatistics, s => s.TotalInsightsAnalysisCompleted);
            }

            // we successfully passed the regression test, copy the log file so we don't have to continually
            // re-run master in order to compare against a passing run
            var passedFile = logFile.Replace("./regression/", "./passed/");

            Directory.CreateDirectory(Path.GetDirectoryName(passedFile));
            File.Delete(passedFile);
            File.Copy(logFile, passedFile);

            var passedOrderLogFile = ordersLogFile.Replace("./regression/", "./passed/");

            Directory.CreateDirectory(Path.GetDirectoryName(passedFile));
            File.Delete(passedOrderLogFile);
            if (File.Exists(ordersLogFile))
            {
                File.Copy(ordersLogFile, passedOrderLogFile);
            }

            return(new AlgorithmRunnerResults(algorithm, language, algorithmManager, results));
        }
コード例 #38
0
        /// <summary>
        /// Intizializes the <see cref="ILogProvider"/>.
        /// </summary>
        /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param>
        public override void Initialize(ILogHandler logHandler)
        {
            base.Initialize(logHandler);

              try
              {
            mSocket = new Socket(
            AddressFamily.InterNetwork
              , SocketType.Stream
              , ProtocolType.Tcp);

            mSocket.ExclusiveAddressUse = true;
            mSocket.ReceiveBufferSize   = RECEIVE_BUFFER_SIZE;

            mSocket.Bind(new IPEndPoint(
            IPAddress.Any
              , mPort));

            mSocket.Listen(100);

            SocketAsyncEventArgs socketEvent = new SocketAsyncEventArgs();
            socketEvent.Completed += SocketEventCompleted;

            mSocket.AcceptAsync(socketEvent);
              }
              catch (Exception ex)
              {
            Logger.Warn(ex.Message);
              }
        }
コード例 #39
0
 /// <summary>
 /// 增加日志处理器
 /// </summary>
 /// <param name="handler">处理器</param>
 public void AddLogHandler(ILogHandler handler)
 {
     Guard.Requires <ArgumentNullException>(handler != null);
     handlers.Add(handler);
 }