Esempio n. 1
0
 public void TestMultipleArgumentBooleanExpressions()
 {
     // expression tests
     // - empty multi-AND = true
     {
         IExpression[] args = new IExpression[] { };
         Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false));
     }
     // - multi-AND true
     {
         IExpression[] args = new IExpression[] { Expr.Const(true), null, null, Expr.Const(true) };
         Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false));
     }
     // multi-AND false
     {
         IExpression[] args = new IExpression[] { Expr.Const(true), null, null, Expr.Const(false) };
         Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false));
     }
     // - empty multi-OR = false
     {
         IExpression[] args = new IExpression[] { };
         Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false));
     }
     // - multi-OR false
     {
         IExpression[] args = new IExpression[] { Expr.Const(false), null, null, Expr.Const(false) };
         Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false));
     }
     // multi-OR true
     {
         IExpression[] args = new IExpression[] { Expr.Const(false), null, null, Expr.Const(true) };
         Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false));
     }
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="scenarioRules"></param>
 /// <param name="scenarioName"></param>
 /// <param name="curveProperties"></param>
 /// <returns></returns>
 public static string RunScenarioRules(
     IEnumerable <CachedScenarioRule> scenarioRules,
     string scenarioName,
     NamedValueSet curveProperties)
 {
     if (scenarioName == null)
     {
         return(null);
     }
     if (curveProperties == null)
     {
         return(null);
     }
     return((from rule in scenarioRules
             where rule.ScenarioId.Equals(scenarioName, StringComparison.OrdinalIgnoreCase) && Expr.CastTo(rule.FilterExpr.Evaluate(curveProperties), false)
             select rule.StressId).FirstOrDefault());
 }
Esempio n. 3
0
        private void ProcessAllRules()
        {
            // note: no locks required - as we are inside main Dispatcher
            try
            {
                // publish latest rule status
                DateTimeOffset asAtTime = DateTimeOffset.Now;
                foreach (InternalRule rule in _ruleStore.Values)
                {
                    var props = new NamedValueSet();
                    try
                    {
                        if ((rule.LastMonitored + rule.MonitorPeriod) < asAtTime)
                        {
                            // update LastMonitored first to prevent infinite looping
                            // when there are repeated expression evaluation exceptions
                            rule.LastMonitored = asAtTime;
                            // build property set
                            string   smtpServer = rule.Properties.GetString(AlertRule.MailHost, null) ?? _defaultSmtpServer;
                            string   mailFrom   = rule.Properties.GetString(AlertRule.MailFrom, null) ?? _defaultMailFrom;
                            string[] recipients = rule.Properties.GetArray <string>(AlertRule.MailTo) ?? _defaultMailTo;
                            props.Set(AlertRule.MailHost, smtpServer);
                            props.Set(AlertRule.MailFrom, mailFrom);
                            props.Set(AlertRule.MailTo, recipients);
                            props.Set("host.AsAtTime", asAtTime);
                            props.Set("host.HostName", IntClient.Target.ClientInfo.HostName);
                            props.Set("rule.DebugEnabled", rule.Properties.GetValue <bool>("DebugEnabled", false));
                            props.Set("rule.RuleName", rule.RuleName);
                            props.Set("rule.Disabled", rule.Disabled);
                            props.Set("rule.DataSubsExpr", rule.DataSubsExpr.DisplayString());
                            props.Set("rule.Constraint", rule.Constraint.DisplayString());
                            props.Set("rule.Condition", rule.Condition.DisplayString());
                            props.Set("rule.MonitorPeriod", rule.MonitorPeriod);
                            props.Add(rule.Properties);
                            if (rule.CurrentReceivedItem != null)
                            {
                                props.Add(rule.CurrentReceivedItem.AppProps);
                                props.Set("item.IsNotNull", true);
                            }
                            else
                            {
                                // no item received
                                props.Set("item.IsNotNull", false);
                            }
                            AlertStatus newStatus;
                            string      statusMessage;
                            var         signal = new InternalSignal
                            {
                                RuleName    = rule.RuleName,
                                AlertServer = IntClient.Target.ClientInfo.HostName
                            };
                            if (rule.Disabled)
                            {
                                newStatus     = AlertStatus.Disabled;
                                statusMessage = "the rule is disabled";
                            }
                            else
                            {
                                // extend constraint
                                ICoreItem item       = rule.CurrentReceivedItem;
                                object    constraint = (item == null)
                                    ? rule.Constraint.Evaluate(props, null, DateTimeOffset.MinValue, DateTimeOffset.MinValue, asAtTime)
                                    : rule.Constraint.Evaluate(props, item.Name, item.Created, item.Expires, asAtTime);
                                if (Expr.CastTo(constraint, false))
                                {
                                    object condition = item == null
                                        ? rule.Condition.Evaluate(props, null, DateTimeOffset.MinValue, DateTimeOffset.MinValue, asAtTime)
                                        : rule.Condition.Evaluate(props, item.Name, item.Created, item.Expires, asAtTime);

                                    if (Expr.CastTo(condition, false))
                                    {
                                        newStatus     = AlertStatus.Alerted;
                                        statusMessage = rule.SignalFormat;
                                    }
                                    else
                                    {
                                        newStatus     = AlertStatus.AllClear;
                                        statusMessage = "the condition is no longer active";
                                    }
                                }
                                else
                                {
                                    newStatus     = AlertStatus.Inactive;
                                    statusMessage = "the constraint is no longer satisfied";
                                }
                            }
                            props.Set("rule.Status", newStatus.ToString());
                            signal.Status        = newStatus;
                            signal.LastMonitored = asAtTime;
                            signal.ReminderCount = 0;
                            if (rule.LastSignal != null)
                            {
                                signal.ReminderCount = rule.LastSignal.ReminderCount;
                            }
                            if (newStatus == AlertStatus.Alerted)
                            {
                                signal.SignalMessage = props.ReplaceTokens(statusMessage);
                            }
                            else
                            {
                                signal.SignalMessage =
                                    $"The previous alert message sent from this server ({signal.AlertServer}) " +
                                    $"for this rule ({signal.RuleName}) has been withdrawn because {statusMessage}.";
                            }
                            // set instance (repeat) count
                            if (newStatus != rule.LastStatus)
                            {
                                signal.ReminderCount = 0;
                            }
                            if ((newStatus != rule.LastStatus) || ((rule.LastPublished + rule.PublishPeriod) < asAtTime))
                            {
                                rule.LastPublished = asAtTime;
                                // publish signal
                                PublishAlertSignal(signal);
                                // email signal if status is or was alerted
                                if ((newStatus == AlertStatus.Alerted) || (rule.LastStatus == AlertStatus.Alerted))
                                {
                                    Logger.LogInfo(
                                        "Rule '{0}' {1}: {2}", signal.RuleName, signal.Status, signal.SignalMessage);
                                    SendAlertSignalEmail(signal, props);
                                }
                            }
                            // done
                            rule.LastStatus = newStatus;
                            rule.LastSignal = signal;
                        }
                    }
                    catch (Exception ex)
                    {
                        ReportUncaughtError("MainCallback", rule.RuleName, ex, props);
                    }
                } // foreach rule
            }
            catch (Exception ex)
            {
                ReportUncaughtError("MainCallback", null, ex, null);
            }
        }
Esempio n. 4
0
        private void ProcessRule(ICoreClient client, InternalRule rule, DateTimeOffset currentTime)
        {
            RuleStatusEnum ruleStatus;
            ILogger        logger = new FilterLogger(
                Logger, $"Rule {rule.RuleName}: ",
                rule.DebugEnabled ? LogSeverity.Debug : LogSeverity.Info);

            using (var settings = new SettingsTracker(client, "FileImporter." + rule.RuleName))
            {
                bool           lastCheckFailed    = false;
                string         lastCheckException = "(null)";
                DateTimeOffset lastCheckDateTime  = currentTime;
                //logger.LogDebug("Processing...");
                try
                {
                    ruleStatus = RuleStatusEnum.Disabled;
                    if (!rule.Disabled)
                    {
                        // evaluate rule constraint and condition
                        var properties = new NamedValueSet(settings.GetAllValues(true));
                        properties.Add(rule.Properties);
                        // last import date/time (default to 4 days ago)
                        var lastImportDateTime = settings.GetSetValue(RuleConst.LastImportDateTime, DateTimeOffset.Now.AddDays(-4));
                        properties.Set(RuleConst.LastImportDateTime, lastImportDateTime);
                        // calculate effective "as at" date
                        var thisImportDateTime = Expr.CastTo(rule.EffectiveDateExpr.Evaluate(properties, currentTime), currentTime);
                        properties.Set(RuleConst.EffectiveDateTime, thisImportDateTime);
                        // add useful date/time tokens
                        //foreach (string token in new string[] { "dd", "ddd", "MM", "MMM", "yyyy" })
                        //{
                        //    properties.Set(token, thisImportDateTime.ToString(token));
                        //}
                        // calculate import delay
                        var thisImportDelay = Expr.CastTo(rule.ImportDelayExpr.Evaluate(properties, currentTime), TimeSpan.Zero);
                        properties.Set(RuleConst.ImportDelay, thisImportDelay);
                        // evaluate rule check constraint and import condition
                        logger.LogDebug("Evaluation Params :");
                        properties.LogValues(text => logger.LogDebug("    " + text));
                        logger.LogDebug("Check Constraint  : {0}", rule.CheckConstraint);
                        ruleStatus = RuleStatusEnum.Inactive;
                        if (Expr.CastTo(rule.CheckConstraint.Evaluate(properties, currentTime), false))
                        {
                            logger.LogDebug("Import Condition  : {0}", rule.ImportCondition);
                            ruleStatus = RuleStatusEnum.NotReady;
                            if (Expr.CastTo(rule.ImportCondition.Evaluate(properties, currentTime), false))
                            {
                                ruleStatus = RuleStatusEnum.Failed;
                                // import condition is true
                                // process date/time tokens
                                string targetLocation = StringHelper.ReplaceDateTimeTokens(rule.TargetLocation, thisImportDateTime);
                                string sourceLocation = StringHelper.ReplaceDateTimeTokens(rule.SourceLocation, thisImportDateTime);
                                var    importedFiles  = new List <string>();
                                logger.LogInfo("Source Location  : {0}", sourceLocation);
                                logger.LogInfo("Target Location  : {0}", targetLocation);
                                logger.LogInfo("Filenames to copy: {0}", rule.CopyFilePatterns);
                                string thisImportException = "(null)";
                                try
                                {
                                    // import the file
                                    // - optionally clean up old files aged more than 7 days
                                    if (rule.RemoveOldTargetFiles)
                                    {
                                        try
                                        {
                                            string[] oldTargetFiles = Directory.GetFiles(targetLocation, "*.*", SearchOption.TopDirectoryOnly);
                                            foreach (string oldTargetFile in oldTargetFiles)
                                            {
                                                var targetFileInfo = new FileInfo(oldTargetFile);
                                                if ((currentTime - targetFileInfo.LastWriteTime) > TimeSpan.FromDays(2))
                                                {
                                                    File.Delete(oldTargetFile);
                                                }
                                            }
                                        }
                                        catch (IOException removeExcp)
                                        {
                                            logger.LogWarning("Error removing old files: {0}", removeExcp.GetType().Name);
                                            // ignored
                                        }
                                    }
                                    // - create target directory if required
                                    if (!Directory.Exists(targetLocation))
                                    {
                                        Directory.CreateDirectory(targetLocation);
                                    }
                                    // - copy file(s) from source to target
                                    foreach (string ruleFilePattern in rule.CopyFilePatterns.Split(';'))
                                    {
                                        string   filePattern = StringHelper.ReplaceDateTimeTokens(ruleFilePattern, thisImportDateTime);
                                        string[] sourceFiles = Directory.GetFiles(sourceLocation, filePattern, SearchOption.TopDirectoryOnly);
                                        logger.LogInfo("Copying file(s): {0} ({1} found)", filePattern, sourceFiles.Length);
                                        int copiedCount  = 0;
                                        int skippedCount = 0;
                                        foreach (string sourceFileFullname in sourceFiles)
                                        {
                                            string sourceFileBaseName = Path.GetFileName(sourceFileFullname);
                                            string targetFileFullname = $@"{targetLocation}\{sourceFileBaseName}";
                                            bool   copyRequired       = true;
                                            if (File.Exists(targetFileFullname) && rule.OnlyCopyUpdatedFiles)
                                            {
                                                var sourceFileInfo = new FileInfo(sourceFileFullname);
                                                var targetFileInfo = new FileInfo(targetFileFullname);
                                                copyRequired = (sourceFileInfo.LastWriteTime > targetFileInfo.LastWriteTime);
                                            }
                                            if (copyRequired)
                                            {
                                                logger.LogInfo("Copying file : {0}", sourceFileBaseName);
                                                logger.LogInfo("  From source: {0}", sourceLocation);
                                                logger.LogInfo("    To target: {0}", targetLocation);
                                                DateTime copyCommenced = DateTime.Now;
                                                File.Copy(sourceFileFullname, targetFileFullname, true);
                                                TimeSpan copyDuration = DateTime.Now - copyCommenced;
                                                importedFiles.Add(sourceFileBaseName);
                                                var targetFileInfo = new FileInfo(targetFileFullname);
                                                copiedCount++;
                                                logger.LogInfo("  Copied {0}MB in {1}s ({2}KB/sec)",
                                                               (targetFileInfo.Length / 1000000.0).ToString("N"),
                                                               copyDuration.TotalSeconds.ToString("N"),
                                                               (targetFileInfo.Length / (1000.0 * copyDuration.TotalSeconds)).ToString("N"));
                                                // publish rule import status
                                                var importFileResult = new ImportFileResult
                                                {
                                                    hostEnvName     = EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
                                                    hostComputer    = IntClient.Target.ClientInfo.HostName,
                                                    hostInstance    = null,
                                                    hostUserName    = client.ClientInfo.UserName,
                                                    RuleName        = rule.RuleName,
                                                    FileName        = sourceFileBaseName,
                                                    DebugEnabled    = rule.DebugEnabled,
                                                    DebugProperties = rule.DebugProperties.Serialise(),
                                                    FileContentType = rule.FileContentType,
                                                    ImportResult    = RuleStatusEnum.Completed.ToString(),
                                                    ImportException = null,
                                                    ImportDateTime  = currentTime.ToString("o"),
                                                    SourceSystem    = rule.SourceSystem,
                                                    SourceLocation  = sourceLocation,
                                                    TargetLocation  = targetLocation
                                                };
                                                IntClient.Target.SaveObject(importFileResult, true, TimeSpan.FromDays(30));
                                            }
                                            else
                                            {
                                                skippedCount++;
                                                logger.LogDebug("Skipping file : {0}", sourceFileBaseName);
                                            }
                                        } // foreach file
                                        logger.LogInfo("Copied {0} file(s), skipped {1} file(s).", copiedCount, skippedCount);
                                    }
                                    // - optionally decompress target
                                    // todo
                                    // done
                                    ruleStatus         = RuleStatusEnum.Completed;
                                    lastImportDateTime = Expr.CastTo(rule.DateUpdateExpr.Evaluate(properties, currentTime), currentTime);
                                }
                                catch (Exception e2)
                                {
                                    logger.Log(e2);
                                    thisImportException = e2.ToString();
                                    ruleStatus          = RuleStatusEnum.Failed;
                                }
                                finally
                                {
                                    settings.SetNewValue(RuleConst.LastImportResult, ruleStatus.ToString());
                                    settings.SetNewValue(RuleConst.LastImportException, thisImportException);
                                    settings.SetNewValue(RuleConst.LastImportDateTime, lastImportDateTime);
                                }
                                // publish rule import status
                                var importRuleResult = new ImportRuleResult
                                {
                                    hostEnvName     = EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
                                    hostComputer    = IntClient.Target.ClientInfo.HostName,
                                    hostInstance    = null,
                                    hostUserName    = client.ClientInfo.UserName,
                                    RuleName        = rule.RuleName,
                                    ImportResult    = ruleStatus.ToString(),
                                    ImportException = thisImportException,
                                    ImportDateTime  = currentTime.ToString("o"),
                                    SourceSystem    = rule.SourceSystem,
                                    SourceLocation  = sourceLocation,
                                    TargetLocation  = targetLocation,
                                    FileNames       = importedFiles.ToArray()
                                };
                                IntClient.Target.SaveObject(importRuleResult, true, TimeSpan.FromDays(30));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Log(e);
                    lastCheckFailed    = true;
                    lastCheckException = e.ToString();
                    ruleStatus         = RuleStatusEnum.Failed;
                }
                settings.SetNewValue(RuleConst.LastCheckFailed, lastCheckFailed);
                settings.SetNewValue(RuleConst.LastCheckException, lastCheckException);
                settings.SetNewValue(RuleConst.LastCheckDateTime, lastCheckDateTime);
            } // commit unsaved settings
            logger.LogDebug("Status={0}", ruleStatus);
        }
        public void ProcessRequest(RequestBase baseRequest, HandlerResponse response)
        {
            if (baseRequest == null)
            {
                throw new ArgumentNullException(nameof(baseRequest));
            }
            var request = baseRequest as StressedCurveGenRequest;

            if (request == null)
            {
                throw new InvalidCastException(
                          $"{typeof(RequestBase).Name} is not a {typeof(StressedCurveGenRequest).Name}");
            }
            // check for workflow cancellation
            if (Cancelled)
            {
                throw new OperationCanceledException(CancelReason);
            }
            DateTime lastStatusPublishedAt = DateTime.Now;

            CurveSelection[] curveSelectors = request.CurveSelector ?? new List <CurveSelection>().ToArray();

            #region Load stress rules

            //find the uniques namespaces
            var uniquesNameSpaces = new List <string>();
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                if (!uniquesNameSpaces.Contains(curveSelector.NameSpace))
                {
                    uniquesNameSpaces.Add(curveSelector.NameSpace);
                }
            }
            var cachedStressRules = new Dictionary <string, List <CachedStressRule> >();
            {
                IExpression       queryExpr         = Expr.IsEQU(EnvironmentProp.NameSpace, uniquesNameSpaces[0]);//TODO only does the first namespace....
                List <StressRule> storedStressRules = Context.Cache.LoadObjects <StressRule>(queryExpr);
                foreach (StressRule storedStressRule in storedStressRules)
                {
                    if ((storedStressRule.Disabled) || (storedStressRule.StressId == null))
                    {
                        continue;
                    }
                    string key = storedStressRule.StressId.ToLower();
                    List <CachedStressRule> rules;
                    if (!cachedStressRules.TryGetValue(key, out rules))
                    {
                        rules = new List <CachedStressRule>();
                        cachedStressRules[key] = rules;
                    }
                    rules.Add(new CachedStressRule(storedStressRule));
                    rules.Sort();
                }
            }
            #endregion

            response.ItemCount = curveSelectors.Length * cachedStressRules.Count;
            // iterate selected base curves
            foreach (CurveSelection curveSelector in curveSelectors)
            {
                // check for workflow cancellation
                if (Cancelled)
                {
                    throw new OperationCanceledException(CancelReason);
                }
                // publish 'intermediate' in-progress result (throttled)
                if ((DateTime.Now - lastStatusPublishedAt) > TimeSpan.FromSeconds(5))
                {
                    lastStatusPublishedAt = DateTime.Now;
                    response.Status       = RequestStatusEnum.InProgress;
                    Context.Cache.SaveObject(response);
                }
                string nameSpace       = curveSelector.NameSpace;
                string inputMarketName = curveSelector.MarketName;
                var    marketDate      = curveSelector.MarketDate;
                if (marketDate != null && marketDate != DateTime.MinValue)
                {
                    inputMarketName += "." + ((DateTime)marketDate).ToString(CurveProp.MarketDateFormat);
                }
                string inputCurveName = curveSelector.CurveName;
                string inputCurveType = curveSelector.CurveType;
                Context.Logger.LogDebug("Building stressed curve(s): {0}.{1}.{2}", inputMarketName, inputCurveType, inputCurveName);

                #region Load base curve

                var curveGenProps = new NamedValueSet();
                curveGenProps.Set(CurveProp.BaseDate, request.BaseDate);
                IPricingStructureIdentifier baseCurveId =
                    PricingStructureIdentifier.CreateMarketCurveIdentifier(curveGenProps, inputMarketName, null, inputCurveType, inputCurveName, null);
                var       baseCurveUniqueId = baseCurveId.Properties.GetValue <string>(CurveProp.UniqueIdentifier, true);
                ICoreItem baseCurveItem     = LoadAndCheckMarketItem(Context.Cache, nameSpace, baseCurveUniqueId);
                var       stressNameProp    = baseCurveItem.AppProps.GetValue <string>(CurveProp.StressName, null);
                if (stressNameProp != null)
                {
                    throw new ApplicationException("The Market with name '" + baseCurveUniqueId + "' is NOT a base curve! (Stress name is not null)");
                }
                var baseCurveFpml = (Market)baseCurveItem.Data;
                var baseCurveType = PropertyHelper.ExtractPricingStructureType(baseCurveItem.AppProps);

                #endregion

                #region Load the reference curves - if required

                string        fxCurveName = null, refCurveName = null, quoteCurveName = null;
                NamedValueSet fxProperties = null, refProperties = null, quoteProperties = null;
                Market        fxMarket = null, refMarket = null, quoteMarket = null;
                if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                    baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require a reference curve
                    refCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurveUniqueId, true);
                    // load the reference curve
                    var refCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, refCurveName);
                    refMarket     = (Market)refCurveItem.Data;
                    refProperties = refCurveItem.AppProps;
                }
                if (baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                {
                    // rate basis curves require an fx curve
                    fxCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceFxCurveUniqueId, true);
                    // load the reference curve
                    var fxCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, fxCurveName);
                    fxMarket     = (Market)fxCurveItem.Data;
                    fxProperties = fxCurveItem.AppProps;
                    // rate basis curves require a reference curve
                    quoteCurveName = baseCurveItem.AppProps.GetValue <string>(CurveProp.ReferenceCurrency2CurveId, true);
                    // load the reference curve
                    var quoteCurveItem = LoadAndCheckMarketItem(Context.Cache, nameSpace, quoteCurveName);
                    quoteMarket     = (Market)quoteCurveItem.Data;
                    quoteProperties = quoteCurveItem.AppProps;
                }
                #endregion

                // process stress rules
                foreach (var kvp in cachedStressRules)
                {
                    CachedStressRule stressRule = kvp.Value.FirstOrDefault(item => (item.FilterExpr == null) || (Expr.CastTo(item.FilterExpr.Evaluate(baseCurveItem.AppProps), false)));
                    // find stress rule that applies
                    if (stressRule == null)
                    {
                        // this stress does not apply to this base curve
                        Context.Logger.LogWarning("Stress '{0}' does not apply to base curve '{1}'!", kvp.Key, baseCurveUniqueId);
                        response.IncrementItemsPassed();
                        continue;
                    }
                    // apply the stress rule
                    //_Context.Logger.LogDebug("Applying stress '{0}' (rule {1}) to base curve '{2}'", stressRule.StressId, stressRule.RuleId, baseCurveUniqueId);
                    var stressDefProps = new NamedValueSet(baseCurveItem.AppProps, curveGenProps);
                    stressDefProps.Set("Identifier", null);//THis is done for backward compatability eith the old ratecurves.
                    stressDefProps.Set(CurveProp.BaseCurveType, baseCurveType);
                    IPricingStructureIdentifier stressCurveId = PricingStructureIdentifier.CreateMarketCurveIdentifier(
                        stressDefProps, inputMarketName, null, baseCurveType.ToString(), inputCurveName, stressRule.StressId);
                    NamedValueSet stressCurveProps = stressCurveId.Properties;
                    var           stressCurveName  = stressCurveProps.GetValue <string>(CurveProp.UniqueIdentifier, true);
                    // from here on a curve will be published (with error details included)
                    var stressCurve = new Market(); // empty
                    try
                    {
                        // clone the base curve and adjust the market quotes
                        var ps = BinarySerializerHelper.Clone(baseCurveFpml.Items[0]);
                        PricingStructureValuation psv = ApplyStress(stressRule, baseCurveFpml.Items1[0]);
                        // hack - supply base date
                        psv.baseDate = new IdentifiedDate {
                            Value = request.BaseDate
                        };
                        Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> refCurveFpmlTriplet = null;
                        if (baseCurveType == PricingStructureTypeEnum.RateBasisCurve ||
                            baseCurveType == PricingStructureTypeEnum.RateXccyCurve)
                        {
                            var psRef = BinarySerializerHelper.Clone(refMarket.Items[0]);
                            //var psvRef = BinarySerializerHelper.Clone<PricingStructureValuation>(refcurveFpml.Items1[0]);
                            var psvRef = ApplyStress(stressRule, refMarket.Items1[0]);
                            refCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    psRef, psvRef, refProperties);
                        }
                        IPricingStructure ips;
                        switch (baseCurveType)
                        {
                        case PricingStructureTypeEnum.RateBasisCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            var basisCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                    ps, psv, stressCurveProps);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, basisCurveFpmlTriplet);
                            break;

                        case PricingStructureTypeEnum.RateXccyCurve:
                            stressCurveProps.Set(CurveProp.ReferenceCurveUniqueId, refCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceFxCurveUniqueId, fxCurveName);
                            stressCurveProps.Set(CurveProp.ReferenceCurrency2CurveId, quoteCurveName);
                            var xccyCurveFpmlTriplet =
                                new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv,
                                                                                                         stressCurveProps);
                            //Format the ref curve data and call the pricing structure helper.
                            var psvFx = ApplyStress(stressRule, fxMarket.Items1[0]);
                            var fxCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      fxMarket.Items[0],
                                      psvFx, fxProperties);

                            var psvRef = ApplyStress(stressRule, quoteMarket.Items1[0]);
                            var quoteCurveFpmlTriplet
                                = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(
                                      quoteMarket.Items[0],
                                      psvRef, quoteProperties);
                            //create and set the pricingstructure
                            ips = CurveLoader.LoadInterestRateCurve(Context.Logger, Context.Cache, nameSpace, refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet,
                                                                    xccyCurveFpmlTriplet);
                            //Creator.Create(refCurveFpmlTriplet, fxCurveFpmlTriplet, quoteCurveFpmlTriplet, xccyCurveFpmlTriplet);
                            break;

                        default:
                            ips = CurveLoader.LoadCurve(Context.Logger, Context.Cache,
                                                        nameSpace, new Pair <PricingStructure, PricingStructureValuation>(ps, psv),
                                                        stressCurveProps);
                            //Creator.Create( new Pair<PricingStructure, PricingStructureValuation>(ps, psv), stressCurveProps);
                            break;
                        }
                        var identifier = ips.GetPricingStructureId().UniqueIdentifier;
                        // retrieve curve
                        stressCurve = PricingStructureHelper.CreateMarketFromFpML(
                            identifier,
                            ips.GetFpMLData());
                        // curve done
                        response.IncrementItemsPassed();
                    }
                    catch (Exception innerExcp)
                    {
                        response.IncrementItemsFailed();
                        Context.Logger.Log(innerExcp);
                        stressCurveProps.Set(WFPropName.ExcpName, WFHelper.GetExcpName(innerExcp));
                        stressCurveProps.Set(WFPropName.ExcpText, WFHelper.GetExcpText(innerExcp));
                    }
                    // save stressed curve with same lifetime as base curve
                    stressCurveProps.Set(EnvironmentProp.NameSpace, nameSpace);
                    Context.Cache.SaveObject(stressCurve, nameSpace + "." + stressCurveName, stressCurveProps, true, baseCurveItem.Expires);
                } // foreach stress rule
            }     // foreach base curve

            // success
            response.Status = RequestStatusEnum.Completed;
        }