/// <summary> /// Restores CallContext if it was lost. /// </summary> /// <param name="context">HttpContext instance.</param> internal static void RestoreOperationContextIfLost(HttpContext context) { var requestTelemetry = context.GetRequestTelemetry(); var correlationContext = context.Items[CorrelationContextItemName] as IDictionary <string, string>; CorrelationHelper.SetOperationContext(requestTelemetry, correlationContext); }
public void Cleanup() { #if NET45 while (Activity.Current != null) { Activity.Current.Stop(); } #else CorrelationHelper.CleanOperationContext(); #endif }
public void TestCleanUp() { #if NET45 while (Activity.Current != null) { Activity.Current.Stop(); } #else CorrelationHelper.CleanOperationContext(); #endif ClientServerDependencyTracker.PretendProfilerIsAttached = false; }
/// <summary> /// Prepare for valuation. /// </summary> public override void PreValue(PriceFactorList factors) { var deal = (CFFloatingInterestListDeal)Deal; base.PreValue(factors); bool quanto = fForecastIsForeign && fCharacteristics.HasQuanto && Quanto_Correction == YesNo.Yes; bool convexity = !fCharacteristics.IsStandardLibor && Convexity_Correction == YesNo.Yes; // volatility surfaces for forecast rate if (fCharacteristics.HasCms) { fForecastYieldVol = InterestVolBase.GetYieldVol(factors, deal.Forecast_Rate_Swaption_Volatility, fForecastCurrency); } if (fCharacteristics.HasLibor && (fCharacteristics.HasOptionlet || convexity || quanto)) { fForecastRateVol = InterestVolBase.GetRateVol(factors, deal.Forecast_Rate_Cap_Volatility, fForecastCurrency); } // volatility surfaces for discount rate if (convexity) { // Discount rate volatility and correlation for convexity correction if (fCharacteristics.HasCms) { fDiscountYieldVol = InterestVolBase.GetYieldVol(factors, deal.Discount_Rate_Swaption_Volatility, fCurrency); } if (fCharacteristics.HasLibor) { fDiscountRateVol = InterestVolBase.GetRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency); } } if (fForecastIsForeign) { // Get factor for translation from forecast rate currency to settlement currency for cashflows with FX reset date if (fCharacteristics.HasFXReset) { fForecastFxRate = factors.GetInterface <IFxRate>(fForecastCurrency); } if (quanto) { fForecastFxVol = FXVolHelper.Get(factors, fForecastCurrency, fCurrency); fForecastFxCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(FxRate), fForecastCurrency, fCurrency); fForecastDiscountCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(InterestRate), fCurrency, null); } } }
public void NearestCorrelation() { var factory = new NArrayFactory(StorageLocation.Host); var correlation = factory.CreateNArray(new double[, ] { { 1.0, 0.84, -0.42 }, { 0.84, 1.0, 0.14 }, { -0.42, 0.14, 1.0 } }); var nearestCorrelation = CorrelationHelper.NearestCorrelationMatrix(correlation); Console.WriteLine(nearestCorrelation.ToString()); }
public async Task PublishEventAsync <T>( IntegrationEvent <T> integrationEvent, string routing, bool persistant) { integrationEvent.CorrelationId = integrationEvent.CorrelationId ?? CorrelationHelper.GetCorrelationId(); var message = JsonConvert.SerializeObject(integrationEvent); var body = Encoding.UTF8.GetBytes(message); var properties = new MessageProperties() { DeliveryMode = persistant ? PersistentDeliveryMode : NonPersistentDeliveryMode }; await PublishEventAsync(body, properties, routing); }
/// <summary> /// Register price factors used in valuation. /// </summary> public override void RegisterFactors(PriceFactorList factors, ErrorList errors) { base.RegisterFactors(factors, errors); var deal = (CFEquityFloatingInterestListDeal)Deal; deal.GetDealHelper().RegisterFactors(factors, errors); fEquityCurrency = deal.Equity_Currency; factors.RegisterInterface <IFxRate>(fEquityCurrency); fEquityPayoffCurrency = string.IsNullOrEmpty(deal.Equity_Payoff_Currency) ? fEquityCurrency : deal.Equity_Payoff_Currency; if (fEquityPayoffCurrency != fEquityCurrency) { factors.RegisterInterface <IFxRate>(fEquityPayoffCurrency); } // Get characteristics EquityCashflowListCharacteristics characteristics = deal.Cashflows.Analyze(factors.BaseDate); bool quanto = fForecastIsForeign && Quanto_Correction == YesNo.Yes; if (characteristics.fHasLibor) { if ((!characteristics.fIsStandardLibor && Convexity_Correction == YesNo.Yes) || quanto) { var forecastRateVol = InterestVolBase.RegisterInterestRateVol(factors, deal.Forecast_Rate_Cap_Volatility, fForecastCurrency); InterestVolBase.Validate(deal, forecastRateVol, ProbabilityDistribution.Lognormal, errors); } if (!characteristics.fIsStandardLibor && Convexity_Correction == YesNo.Yes) { var discountRateVol = InterestVolBase.RegisterInterestRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency); InterestVolBase.Validate(deal, discountRateVol, ProbabilityDistribution.Lognormal, errors); } } if (quanto) { FXVolHelper.Register(factors, fForecastCurrency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IFxRate), fForecastCurrency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IInterestRate), fCurrency, null); } deal.Cashflows.RegisterFactorsValidate(factors.BaseDate, deal.GetEquityPayoffType() == PayoffType.Compo, deal.IsCrossCurrency(), errors); }
public void RddTestHttpProcessingProfilerOnBeginAddsCorrelationContextHeader() { var request = WebRequest.Create(this.testUrl); Assert.IsNull(request.Headers[RequestResponseHeaders.CorrelationContextHeader]); #if NET45 var activity = new Activity("test").AddBaggage("Key1", "Value1").AddBaggage("Key2", "Value2").Start(); #else CorrelationHelper.SetOperationContext(new RequestTelemetry(), new Dictionary <string, string> { ["Key1"] = "Value1", ["Key2"] = "Value2" }); #endif this.httpProcessingProfiler.OnBeginForGetResponse(request); var actualCorrelationContextHeader = request.Headers[RequestResponseHeaders.CorrelationContextHeader]; Assert.IsNotNull(actualCorrelationContextHeader); Assert.IsTrue(actualCorrelationContextHeader == "Key2=Value2,Key1=Value1" || actualCorrelationContextHeader == "Key1=Value1,Key2=Value2"); }
#pragma warning disable 618 /// <summary> /// Parses incoming request headers; initializes Operation Context and stores it in CallContext. /// </summary> /// <param name="context">HttpContext instance.</param> /// <returns>RequestTelemetry with OperationContext parsed from the request.</returns> internal static RequestTelemetry ParseRequest(HttpContext context) { RequestTelemetry requestTelemetry = new RequestTelemetry(); var request = context.Request; IDictionary <string, string> correlationContext; string rootId, parentId; if (!TryParseStandardHeaders(request, out rootId, out parentId, out correlationContext)) { TryParseCustomHeaders(request, out rootId, out parentId); } requestTelemetry.Context.Operation.ParentId = parentId; if (rootId != null) { requestTelemetry.Id = ApplicationInsightsActivity.GenerateRequestId(rootId); } else if (parentId != null) { requestTelemetry.Id = ApplicationInsightsActivity.GenerateRequestId(parentId); } else { requestTelemetry.Id = ApplicationInsightsActivity.GenerateRequestId(); } requestTelemetry.Context.Operation.Id = ApplicationInsightsActivity.GetRootId(requestTelemetry.Id); if (correlationContext != null) { foreach (var item in correlationContext) { requestTelemetry.Context.Properties[item.Key] = item.Value; } } CorrelationHelper.SetOperationContext(requestTelemetry, correlationContext); // save correlation-context in case CallContext will be lost, the rest of the context is saved in requestTelemetry context.Items[CorrelationContextItemName] = correlationContext; return(requestTelemetry); }
public void BeginWebTrackingWithParentCallContextReturnsOperationItemWithTelemetryItem() { var requestTelemetry = new RequestTelemetry { Id = "|guid.1234_" }; var correlationContext = new Dictionary <string, string> { ["k"] = "v" }; CorrelationHelper.SetOperationContext(requestTelemetry, correlationContext); var telemetry = ClientServerDependencyTracker.BeginTracking(this.telemetryClient); Assert.AreEqual("|guid.1234_", telemetry.Context.Operation.ParentId); Assert.AreEqual("guid", telemetry.Context.Operation.Id); var properties = telemetry.Context.Properties; Assert.AreEqual(1, properties.Count); Assert.AreEqual("v", properties["k"]); CorrelationHelper.CleanOperationContext(); }
private List <string> CreateTestWeightsProvider(Context context, WeightsType weightsType, int returnsCount = 1000) { var correlationMatrix = context.Factory.CreateNArray(new double[, ] { { 1.0, 0.84, -0.42 }, { 0.84, 1.0, 0.14 }, { -0.42, 0.14, 1.0 } }); correlationMatrix = CorrelationHelper.NearestCorrelationMatrix(correlationMatrix); int weightsCount; NArray weightsMatrix; if (weightsType == WeightsType.Returns) { weightsCount = returnsCount; weightsMatrix = CalculateSyntheticReturns(correlationMatrix, weightsCount); } else { weightsCount = correlationMatrix.RowCount; weightsMatrix = NMath.CholeskyDecomposition(correlationMatrix); } var weights = context.Data.AddCalibrationParametersProvider (new WeightsProvider(weightsCount)); var identifiers = Enumerable.Range(1, weightsMatrix.ColumnCount) .Select(i => string.Format("TestFactor{0}", i)).ToList(); for (int i = 0; i < weightsMatrix.ColumnCount; ++i) { weights.AddValue(identifiers[i], weightsMatrix.Column(i)); } return(identifiers); }
/// <summary> /// Prepare for valuation. /// </summary> public override void PreValue(PriceFactorList factors) { base.PreValue(factors); var deal = (CFEquityFloatingInterestListDeal)Deal; deal.GetDealHelper().PreValueAsset(out fEquity, out fEquityVol, ref fEquityQuantoCompo, factors); // Get FX rate price factors fEquityCurrency = deal.Equity_Currency; fEquityPayoffCurrency = string.IsNullOrEmpty(deal.Equity_Payoff_Currency) ? fEquityCurrency : deal.Equity_Payoff_Currency; fEquityFXRate = factors.GetInterface <IFxRate>(fEquityCurrency); fEquityPayoffFXRate = fEquityPayoffCurrency != fEquityCurrency?factors.GetInterface <IFxRate>(fEquityPayoffCurrency) : fEquityFXRate; bool quanto = fForecastIsForeign && Quanto_Correction == YesNo.Yes; if (fCharacteristics.fHasLibor) { // volatility surfaces for forecast rate if ((!fCharacteristics.fIsStandardLibor && Convexity_Correction == YesNo.Yes) || quanto) { fForecastRateVol = InterestVolBase.GetRateVol(factors, deal.Forecast_Rate_Cap_Volatility, fForecastCurrency); } // volatility surfaces for discount rate if (!fCharacteristics.fIsStandardLibor && Convexity_Correction == YesNo.Yes) { fDiscountRateVol = InterestVolBase.GetRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency); } } if (quanto) { fForecastFXVol = FXVolHelper.Get(factors, fForecastCurrency, fCurrency); fForecastFXCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(FxRate), fForecastCurrency, fCurrency); fForecastDiscountCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(InterestRate), fCurrency, null); } }
/// <summary> /// Cleans up CallContext. /// </summary> internal static void CleanOperationContext() { // it just allows to have the same API for Activity/CallContext CorrelationHelper.CleanOperationContext(); }
/// <summary> /// Register price factors used in valuation. /// </summary> public override void RegisterFactors(PriceFactorList factors, ErrorList errors) { base.RegisterFactors(factors, errors); CFFloatingInterestListDeal deal = (CFFloatingInterestListDeal)Deal; // Deal validation specific to CFFloatingInterestListValuation foreach (var cashflow in deal.Cashflows) { if (!cashflow.Resets.Any()) { continue; } var lastResetDate = cashflow.Resets.Last().Reset_Date; if (cashflow.FX_Reset_Date > 0.0 && cashflow.FX_Reset_Date < lastResetDate) { errors.Add(ErrorLevel.Warning, string.Format("Quanto adjustments for cashflow paying on {0} are not supported when the FX reset date {1} is before interest rate reset date {2}", cashflow.Payment_Date, cashflow.FX_Reset_Date, lastResetDate)); } } // Get characteristics CashflowListCharacteristics characteristics = deal.Cashflows.Analyze(factors.BaseDate); bool quanto = fForecastIsForeign && characteristics.HasQuanto && Quanto_Correction == YesNo.Yes; bool convexity = !characteristics.IsStandardLibor && Convexity_Correction == YesNo.Yes; var requirements = new VolatilityRequirements( characteristics.HasCms, characteristics.HasLibor && (characteristics.HasOptionlet || convexity || quanto), characteristics.HasCms && convexity, characteristics.HasLibor && convexity); // Collect registered volatility price factors to check they have the same distribution type var volPriceFactors = new List <IInterestVol>(); // register forecast rate volatility surfaces if (requirements.NeedForecastYieldVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestYieldVol(factors, deal.Forecast_Rate_Swaption_Volatility, fForecastCurrency)); } if (requirements.NeedForecastRateVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestRateVol(factors, deal.Forecast_Rate_Cap_Volatility, fForecastCurrency)); } if (requirements.NeedDiscountYieldVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestYieldVol(factors, deal.Discount_Rate_Swaption_Volatility, fCurrency)); } if (requirements.NeedDiscountRateVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency)); } if (fForecastIsForeign) { // Register factor for translation from forecast rate currency to settlement currency for cashflows with FX reset date if (characteristics.HasFXReset) { factors.RegisterInterface <IFxRate>(fForecastCurrency); } if (quanto) { FXVolHelper.Register(factors, fForecastCurrency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IFxRate), fForecastCurrency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IInterestRate), fCurrency, null); } } if (volPriceFactors.Select(pf => pf.GetDistributionType()).Distinct().Count() > 1) { deal.AddToErrors(errors, "Volatility price factors must have the same distribution type."); } ValidateUnnecessaryVolatilities(deal, requirements, errors); }
/// <summary> /// Register price factors. /// </summary> public override void RegisterFactors(PriceFactorList factors, ErrorList errors) { base.RegisterFactors(factors, errors); CFGeneralInterestSpreadListDeal deal = (CFGeneralInterestSpreadListDeal)Deal; // Collect registered volatility price factors to check they have the same distribution type var volPriceFactors = new List <IInterestVol>(); // Get spread flow characteristics SpreadCashflowListCharacteristics spreadCashflowCharacteristics = deal.Cashflows.ValuationPriceFactorDependencies(factors.BaseDate, fCurrency, fForecastCurrency, fForecast2Currency); // register volatility surfaces for forecast rate1 if (spreadCashflowCharacteristics.NeedForecast1YieldVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestYieldVol(factors, deal.Forecast_Rate1_Swaption_Volatility, fForecastCurrency)); } if (spreadCashflowCharacteristics.NeedForecast1RateVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestRateVol(factors, deal.Forecast_Rate1_Cap_Volatility, fForecastCurrency)); } // register volatility surfaces for forecast rate2 if (spreadCashflowCharacteristics.NeedForecast2YieldVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestYieldVol(factors, deal.Forecast_Rate2_Swaption_Volatility, fForecast2Currency)); } if (spreadCashflowCharacteristics.NeedForecast2RateVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestRateVol(factors, deal.Forecast_Rate2_Cap_Volatility, fForecast2Currency)); } // vol surfaces for discount rate if (spreadCashflowCharacteristics.NeedDiscountYieldVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestYieldVol(factors, deal.Discount_Rate_Swaption_Volatility, fCurrency)); } if (spreadCashflowCharacteristics.NeedDiscountRateVol) { volPriceFactors.Add(InterestVolBase.RegisterInterestRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency)); } bool convexity = spreadCashflowCharacteristics.NeedDiscountYieldVol || spreadCashflowCharacteristics.NeedDiscountRateVol; if (fForecastCurrency != fCurrency) { if (Quanto_Correction == YesNo.Yes) { // fx vol, fx/ir correl and forecast/discount correl FXVolHelper.Register(factors, fForecastCurrency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IFxRate), fForecastCurrency, fCurrency); } if (convexity) { CorrelationHelper.Register(factors, typeof(IInterestRate), fCurrency, null, typeof(IInterestRate), fForecastCurrency, null); } } if (fForecast2Currency != fCurrency) { if (Quanto_Correction == YesNo.Yes) { // fx vol, fx/ir correl and forecast/discount correl FXVolHelper.Register(factors, fForecast2Currency, fCurrency); CorrelationHelper.Register(factors, typeof(IInterestRate), fForecast2Currency, null, typeof(IFxRate), fForecast2Currency, fCurrency); } if (convexity) { CorrelationHelper.Register(factors, typeof(IInterestRate), fCurrency, null, typeof(IInterestRate), fForecast2Currency, null); } } if (spreadCashflowCharacteristics.NeedForecast1Forecast2Correlation) { if (fForecastCurrency == fForecast2Currency) { // correl between forecast rates in same currency factors.Register <CMSRateCorrelations>(fForecastCurrency); } else { CorrelationHelper.Register(factors, typeof(IInterestRate), fForecastCurrency, null, typeof(IInterestRate), fForecast2Currency, null); } } if (volPriceFactors.Select(pf => pf.GetDistributionType()).Distinct().Count() > 1) { Deal.AddToErrors(errors, "Volatility price factors must have the same distribution type."); } ValidateUnnecessaryVolatilities(deal, spreadCashflowCharacteristics, errors); }
/// <summary> /// Prepare for valuation. /// </summary> public override void PreValue(PriceFactorList factors) { base.PreValue(factors); CFGeneralInterestSpreadListDeal deal = (CFGeneralInterestSpreadListDeal)Deal; // Get spread flow characteristics SpreadCashflowListCharacteristics spreadCashflowCharacteristics = fCashflows.ValuationPriceFactorDependencies(factors.BaseDate, fCurrency, fForecastCurrency, fForecast2Currency); // vols for first forecast rate if (spreadCashflowCharacteristics.NeedForecast1YieldVol) { fForecast1YieldVol = InterestVolBase.GetYieldVol(factors, deal.Forecast_Rate1_Swaption_Volatility, fForecastCurrency); } if (spreadCashflowCharacteristics.NeedForecast1RateVol) { fForecast1RateVol = InterestVolBase.GetRateVol(factors, deal.Forecast_Rate1_Cap_Volatility, fForecastCurrency); } // vols for second forecast rate if (spreadCashflowCharacteristics.NeedForecast2YieldVol) { fForecast2YieldVol = InterestVolBase.GetYieldVol(factors, deal.Forecast_Rate2_Swaption_Volatility, fForecast2Currency); } if (spreadCashflowCharacteristics.NeedForecast2RateVol) { fForecast2RateVol = InterestVolBase.GetRateVol(factors, deal.Forecast_Rate2_Cap_Volatility, fForecast2Currency); } // vols for discount rate if (spreadCashflowCharacteristics.NeedDiscountYieldVol) { fDiscountYieldVol = InterestVolBase.GetYieldVol(factors, deal.Discount_Rate_Swaption_Volatility, fCurrency); } if (spreadCashflowCharacteristics.NeedDiscountRateVol) { fDiscountRateVol = InterestVolBase.GetRateVol(factors, deal.Discount_Rate_Cap_Volatility, fCurrency); } bool convexity = spreadCashflowCharacteristics.NeedDiscountYieldVol || spreadCashflowCharacteristics.NeedDiscountRateVol; if (fForecastCurrency != fCurrency) { if (Quanto_Correction == YesNo.Yes) { // fx vol, fx/ir correl and forecast/discount correl fFx1Vol = FXVolHelper.Get(factors, fForecastCurrency, fCurrency); fForecast1Fx1Correl = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(FxRate), fForecastCurrency, fCurrency); } if (convexity) { fForecast1DiscountCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fCurrency, null, typeof(InterestRate), fForecastCurrency, null); } } if (fForecast2Currency != fCurrency) { if (Quanto_Correction == YesNo.Yes) { // fx vol, fx/ir correl and forecast/discount correl fFx2Vol = FXVolHelper.Get(factors, fForecast2Currency, fCurrency); fForecast2Fx2Correl = CorrelationHelper.Get(factors, typeof(InterestRate), fForecast2Currency, null, typeof(FxRate), fForecast2Currency, fCurrency); } if (convexity) { fForecast2DiscountCorrel = CorrelationHelper.Get(factors, typeof(InterestRate), fCurrency, null, typeof(InterestRate), fForecast2Currency, null); } } if (spreadCashflowCharacteristics.NeedForecast1Forecast2Correlation) { if (fForecastCurrency == fForecast2Currency) { // correl between forecast rates in same currency fForecast1Forecast2Correls = factors.Get <CMSRateCorrelations>(fForecastCurrency); } else { fForecast1Forecast2Correl = CorrelationHelper.Get(factors, typeof(InterestRate), fForecastCurrency, null, typeof(InterestRate), fForecast2Currency, null); } } }
/// <summary> /// Common helper for all Begin Callbacks. /// </summary> /// <param name="thisObj">This object.</param> /// <param name="injectCorrelationHeaders">Flag that enables Request-Id and Correlation-Context headers injection. /// Should be set to true only for profiler and old versions of DiagnosticSource Http hook events.</param> /// <returns>Null object as all context is maintained in this class via weak tables.</returns> internal object OnBegin(object thisObj, bool injectCorrelationHeaders = true) { try { if (thisObj == null) { DependencyCollectorEventSource.Log.NotExpectedCallback(0, "OnBeginHttp", "thisObj == null"); return(null); } WebRequest webRequest = thisObj as WebRequest; if (webRequest == null) { DependencyCollectorEventSource.Log.UnexpectedCallbackParameter("WebRequest"); } var url = this.GetUrl(webRequest); if (url == null) { DependencyCollectorEventSource.Log.NotExpectedCallback(thisObj.GetHashCode(), "OnBeginHttp", "resourceName is empty"); return(null); } string httpMethod = webRequest.Method; string resourceName = url.AbsolutePath; if (!string.IsNullOrEmpty(httpMethod)) { resourceName = httpMethod + " " + resourceName; } DependencyCollectorEventSource.Log.BeginCallbackCalled(thisObj.GetHashCode(), resourceName); if (this.applicationInsightsUrlFilter.IsApplicationInsightsUrl(url)) { // Not logging as we will be logging for all outbound AI calls return(null); } // If the object already exists, don't add again. This happens because either GetResponse or GetRequestStream could // be the starting point for the outbound call. DependencyTelemetry telemetry = null; var telemetryTuple = this.GetTupleForWebDependencies(webRequest); if (telemetryTuple != null) { if (telemetryTuple.Item1 != null) { telemetry = telemetryTuple.Item1; DependencyCollectorEventSource.Log.TrackingAnExistingTelemetryItemVerbose(); return(null); } } // Create and initialize a new telemetry object if needed if (telemetry == null) { bool isCustomCreated = false; telemetry = ClientServerDependencyTracker.BeginTracking(this.telemetryClient); this.AddTupleForWebDependencies(webRequest, telemetry, isCustomCreated); if (string.IsNullOrEmpty(telemetry.Context.InstrumentationKey)) { // Instrumentation key is probably empty, because the context has not yet had a chance to associate the requestTelemetry to the telemetry client yet. // and get they instrumentation key from all possible sources in the process. Let's do that now. this.telemetryClient.Initialize(telemetry); } } telemetry.Name = resourceName; telemetry.Target = DependencyTargetNameHelper.GetDependencyTargetName(url); telemetry.Type = RemoteDependencyConstants.HTTP; telemetry.Data = url.OriginalString; // Add the source instrumentation key header if collection is enabled, the request host is not in the excluded list and the same header doesn't already exist if (this.setCorrelationHeaders && !this.correlationDomainExclusionList.Contains(url.Host)) { try { if (!string.IsNullOrEmpty(telemetry.Context.InstrumentationKey) && webRequest.Headers.GetNameValueHeaderValue(RequestResponseHeaders.RequestContextHeader, RequestResponseHeaders.RequestContextCorrelationSourceKey) == null) { string appId; if (this.correlationIdLookupHelper.TryGetXComponentCorrelationId(telemetry.Context.InstrumentationKey, out appId)) { webRequest.Headers.SetNameValueHeaderValue(RequestResponseHeaders.RequestContextHeader, RequestResponseHeaders.RequestContextCorrelationSourceKey, appId); } } } catch (Exception ex) { AppMapCorrelationEventSource.Log.SetCrossComponentCorrelationHeaderFailed(ex.ToInvariantString()); } // Add the root ID var rootId = telemetry.Context.Operation.Id; if (!string.IsNullOrEmpty(rootId) && webRequest.Headers[RequestResponseHeaders.StandardRootIdHeader] == null) { webRequest.Headers.Add(RequestResponseHeaders.StandardRootIdHeader, rootId); } // Add the parent ID var parentId = telemetry.Id; if (!string.IsNullOrEmpty(parentId)) { if (webRequest.Headers[RequestResponseHeaders.StandardParentIdHeader] == null) { webRequest.Headers.Add(RequestResponseHeaders.StandardParentIdHeader, parentId); } } // ApplicationInsights only need to inject Request-Id and Correlation-Context headers // for profiler instrumentation, in case of Http Desktop DiagnosticSourceListener // they are injected in DiagnosticSource (with the System.Net.Http.Desktop.HttpRequestOut.Start event) if (injectCorrelationHeaders) { if (webRequest.Headers[RequestResponseHeaders.RequestIdHeader] == null) { webRequest.Headers.Add(RequestResponseHeaders.RequestIdHeader, telemetry.Id); } if (webRequest.Headers[RequestResponseHeaders.CorrelationContextHeader] == null) { #if NET45 var currentActivity = Activity.Current; if (currentActivity != null && currentActivity.Baggage.Any()) { webRequest.Headers.SetHeaderFromNameValueCollection(RequestResponseHeaders.CorrelationContextHeader, currentActivity.Baggage); } #else #pragma warning disable 618 var correlationContext = CorrelationHelper.GetCorrelationContext(); #pragma warning restore 618 if (correlationContext != null && correlationContext.Count > 0) { webRequest.Headers.SetHeaderFromNameValueCollection(RequestResponseHeaders.CorrelationContextHeader, correlationContext); } #endif } } } } catch (Exception exception) { DependencyCollectorEventSource.Log.CallbackError(thisObj == null ? 0 : thisObj.GetHashCode(), "OnBeginHttp", exception); } return(null); }
public static IntergrationEventParsingResult Parse(byte[] message) { var serializedMessage = Encoding.UTF8.GetString(message); List <string> errors = new List <string>(); JObject newObj; try { newObj = JObject.Parse(serializedMessage); } catch (JsonReaderException e) { return(new IntergrationEventParsingResult(null, new List <string> { $"Message is not valid JSON. {e.Message}" }, false)); } var eventIdJToken = newObj["EventId"]; Guid eventId; if (eventIdJToken == null) { errors.Add("EventId token is missed"); } else { if (!Guid.TryParse(eventIdJToken.Value <string>(), out eventId)) { errors.Add("EventId is not GUID"); } } var correlationIdJToken = newObj["CorrelationId"]; Guid correlationId = Guid.Empty; if (correlationIdJToken == null) { errors.Add("CorrelationId token is missed"); } else { if (!string.IsNullOrEmpty(correlationIdJToken.Value <string>())) { if (!Guid.TryParse(correlationIdJToken.Value <string>(), out correlationId)) { errors.Add("CorrelationId is not GUID"); } else { CorrelationHelper.SetCorrelationId(correlationId); } } } var eventCreationDateJToken = newObj["EventCreationDate"]; DateTime eventCreationDate = DateTime.MinValue; if (eventCreationDateJToken == null) { errors.Add("EventCreationDate token is missed"); } else { try { eventCreationDate = eventCreationDateJToken.Value <DateTime>(); } catch (InvalidCastException) { errors.Add("EventCreationDate is not DateTime"); } } var eventTypeJToken = newObj["EventType"]; string eventType = string.Empty; if (eventTypeJToken == null) { errors.Add("EventType token is missed"); } else { if (string.IsNullOrEmpty(eventTypeJToken.Value <string>())) { errors.Add("EventType can not be empty"); } else { eventType = eventTypeJToken.Value <string>(); } } var versionJToken = newObj["Version"]; string version = string.Empty; if (versionJToken == null) { errors.Add("Version token is missed"); } else { if (string.IsNullOrEmpty(versionJToken.Value <string>())) { errors.Add("Version can not be empty"); } else { version = versionJToken.Value <string>(); } } IntergrationEventParsingResult result; if (errors.Count == 0) { result = new IntergrationEventParsingResult(new IntegrationEvent { EventId = eventId, EventType = eventType, Version = version, EventCreationDate = eventCreationDate, CorrelationId = correlationId == Guid.Empty ? null : (Guid?)correlationId, }, new List <string>(), true); } else { result = new IntergrationEventParsingResult(null, errors, false); } return(result); }
/// <summary> /// Simulate state variables needed for the pricing step of the exposure calculation. State variables /// are not independent variables of the adjoint algorithmic differentation, and therefore can be simulated in advance. /// </summary> /// <param name="model"></param> /// <param name="allZeroRatesT0"></param> /// <param name="timePoints"></param> /// <param name="graph"></param> /// <param name="pricers"></param> public void SimulateModel(out LinearGaussianModel model, out IEnumerable <NArray> allZeroRatesT0, out TimePoint[] timePoints, out SimulationGraph graph, out List <IPricer> pricers) { var testDate = new DateTime(2015, 12, 1); graph = new SimulationGraph(StorageLocation.Host, testDate); var context = graph.Context; context.Settings.SimulationCount = 5000; var fixedLeg = Enumerable.Range(0, 40).Select(i => new FixedCashflowDeal() { Notional = -1e6, Rate = 0.002, Currency = Currency.EUR, StartDate = testDate.AddMonths(3 * i), EndDate = testDate.AddMonths(3 * (i + 1)) }); var floatingLeg = Enumerable.Range(0, 40).Select(i => new FloatingCashflowDeal() { Notional = 1e6, Currency = Currency.EUR, StartDate = testDate.AddMonths(3 * i), EndDate = testDate.AddMonths(3 * (i + 1)) }); var correlationMatrix = context.Factory.CreateNArray(new double[, ] { { 1.0, -0.92, 0.5 }, { -0.92, 1.0, -0.8 }, { 0.5, -0.8, 1.0 } }); var identifiers = new string[] { "IR_DiscountFactor_EUR_Factor0", "IR_DiscountFactor_EUR_Factor1", "IR_DiscountFactor_EUR_Factor2" }; CorrelationHelper.AddMultivariateModelWeightsProvider(context, identifiers, correlationMatrix); pricers = fixedLeg.Select(d => new FixedCashflowPricer(d) as IPricer) .Concat(floatingLeg.Select(d => new FloatingCashflowPricer(d) as IPricer)).ToList(); foreach (var pricer in pricers) { pricer.Register(graph); } var testVariates0 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor0"); var testVariates1 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor1"); var testVariates2 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor2"); var testFactor = graph.RegisterModel <MeanRevertingNormalPathModel>("IR_DiscountFactor_EUR_Factor0"); model = graph.RegisterModel <LinearGaussianModel>("EUR"); var numeraire = graph.RegisterModel <NumeraireModel>("EUR"); model.Factors[0].Sigma = 0.02; model.Factors[0].Lambda = 0.05; model.Factors[1].Sigma = 0.03; model.Factors[1].Lambda = 0.2; model.Factors[2].Sigma = 0.01; model.Factors[2].Lambda = 1.0; var years = new double[] { 0, 1 / 365.35, 7 / 365.25, 14 / 365.25, 1 / 12, 2 / 12, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60 }; var zeroRatesInPercent = new double[] { -0.3, -0.3, -0.29, -0.29, -0.3, -0.31, -0.31, -0.32, -0.32, -0.33, -0.34, -0.35, -0.35, -0.33, -0.28, -0.2, -0.11, -0.01, 0.1, 0.2, 0.37, 0.56, 0.71, 0.75, 0.76, 0.75, 0.75, 0.72, 0.7, 0.67, 0.64 }; model.ZeroRatesT0 = new Curve(years.Zip(zeroRatesInPercent, (y, r) => new DataPoint( testDate.AddDays(y * 365.25), NArray.CreateScalar(r / 100) )).ToArray()); var runner = graph.ToSimulationRunner(); runner.Prepare(); runner.Simulate(); timePoints = graph.Context.Settings.SimulationTimePoints; allZeroRatesT0 = model.ZeroRatesT0.Data.Select(d => d.Value); }