public static HazardCurve CreateHazardCurve( [QuantSAExcelArgument(Description = "The reference entity for whom these hazard rates apply.")] ReferenceEntity referenceEntity, [QuantSAExcelArgument(Description = "The anchor date. Survival probabilities can only be calculated up to dates after this date.")] Date anchorDate, [QuantSAExcelArgument(Description = "The dates on which the hazard rates apply.")] Date[] dates, [QuantSAExcelArgument(Description = "The hazard rates.")] double[] hazardRates) { if (dates[0] < anchorDate) { throw new ArgumentException("dates must be on or after the anchor date."); } for (var i = 0; i < dates.Length - 1; i++) { if (dates[i] > dates[i + 1]) { throw new ArgumentException("dates must be increasing."); } } if (dates.Length != hazardRates.Length) { throw new ArgumentException("dates and rates must have the same length."); } return(new HazardCurve(referenceEntity, anchorDate, dates, hazardRates)); }
public static object _CreateCDS(string objectName, object[,] refEntity, object[,] ccy, object[,] paymentDates, object[,] notionals, object[,] rates, object[,] accrualFractions, object[,] boughtProtection) { try { ReferenceEntity _refEntity = XU.GetReferenceEntity0D(refEntity, "refEntity"); Currency _ccy = XU.GetCurrency0D(ccy, "ccy"); Date[] _paymentDates = XU.GetDate1D(paymentDates, "paymentDates"); Double[] _notionals = XU.GetDouble1D(notionals, "notionals"); Double[] _rates = XU.GetDouble1D(rates, "rates"); Double[] _accrualFractions = XU.GetDouble1D(accrualFractions, "accrualFractions"); Boolean _boughtProtection = XU.GetBoolean0D(boughtProtection, "boughtProtection"); CDS _result = XLCredit.CreateCDS(_refEntity, _ccy, _paymentDates, _notionals, _rates, _accrualFractions, _boughtProtection); return(XU.AddObject(objectName, _result)); } catch (Exception e) { return(XU.Error0D(e)); } }
public static HazardCurve CreateHazardCurve( [QuantSAExcelArgument(Description = "The reference entity for whom these hazard rates apply.")] ReferenceEntity referenceEntity, [QuantSAExcelArgument(Description = "The anchor date. Survival probabilites can only be calculated up to dates after this date.")] Date anchorDate, [QuantSAExcelArgument(Description = "The dates on which the hazard rates apply.")] Date[] dates, [QuantSAExcelArgument(Description = "The hazard rates.")] double[] hazardRates) { return(new HazardCurve(referenceEntity, anchorDate, dates, hazardRates)); }
public static CDS CreateCDS([QuantSAExcelArgument(Description = "The reference entity whose default is covered by this CDS.")] ReferenceEntity refEntity, [QuantSAExcelArgument(Description = "The currency of the cashflows of the premium and default legs.")] Currency ccy, [QuantSAExcelArgument(Description = "The payment dates on which the premium is paid.")] Date[] paymentDates, [QuantSAExcelArgument(Description = "The notionals that define the protection amount in the period until each payment date and the basis on which the premiums are calculated.")] double[] notionals, [QuantSAExcelArgument(Description = "The simple rates that apply until the default time. Used to calculate the premium flows.")] double[] rates, [QuantSAExcelArgument(Description = "The accrual fractions used to calculate the premiums paid on the paymentDates.")] double[] accrualFractions, [QuantSAExcelArgument(Description = "If set to TRUE then protection has been bought and the premium will be paid.")] bool boughtProtection) { return(new CDS(refEntity, ccy, paymentDates, notionals, rates, accrualFractions, boughtProtection)); }
/// <summary> /// Initializes a new instance of the <see cref="CDS"/> class. /// </summary> /// <param name="refEntity">The reference entity whose default is covered by this CDS.</param> /// <param name="ccy">The currency of the cashflows of the premium and default legs.</param> /// <param name="paymentDates">The payment dates on which the premium is paid.</param> /// <param name="notionals">The notionals that define the protection amount in the period until each payment date and the basis on which the premiums are calculated.</param> /// <param name="rates">The simple rates that apply until the default time. Used to calculate the premium flows.</param> /// <param name="accrualFractions">The accrual fractions used to calculate the premiums paid on the <paramref name="paymentDates"/>.</param> /// <param name="boughtProtection">If set to <c>true</c> then protection has been bought and the premium will be paid.</param> public CDS(ReferenceEntity refEntity, Currency ccy, Date[] paymentDates, double[] notionals, double[] rates, double[] accrualFractions, bool boughtProtection) { _defaultRecovery = new DefaultRecovery(refEntity); _defaultTime = new DefaultTime(refEntity); _ccy = ccy; _paymentDates = paymentDates; _notionals = notionals; _rates = rates; _accrualFractions = accrualFractions; _cfMultiplier = boughtProtection ? -1.0 : 1.0; }
public void TestQuantoCDS() { var spot = 1.00; var relJumpSizeInDefault = -0.2; var cdsSpread = 0.025; // Trades var anchorDate = new Date(2016, 11, 25); var refEntity = new ReferenceEntity("ABC"); Date[] paymentDates; double[] accrualFractions; DateGenerators.CreateDatesNoHolidays(Tenor.Months(3), anchorDate, 20, out paymentDates, out accrualFractions); var zarNotionals = Vector.Ones(paymentDates.Length).Multiply(1000000.0); var usdNotionals = zarNotionals.Divide(spot); var zarSpreads = Vector.Ones(paymentDates.Length).Multiply(cdsSpread); var usdSpreads = zarSpreads.Multiply(1 + relJumpSizeInDefault); // Adjusted for the FX jump size. var boughtProtection = true; var cdsZAR = new CDS(refEntity, Currency.ZAR, paymentDates, zarNotionals, zarSpreads, accrualFractions, boughtProtection); var cdsUSD = new CDS(refEntity, Currency.USD, paymentDates, zarNotionals, usdSpreads, accrualFractions, boughtProtection); // Model var curveDates = new[] { anchorDate, anchorDate.AddTenor(Tenor.Years(10)) }; var expectedRecovery = 0.4; var hazardRates = new[] { cdsSpread / (1 - expectedRecovery), cdsSpread / (1 - expectedRecovery) }; var usdRates = new[] { 0.01, 0.02 }; var zarRates = new[] { 0.07, 0.08 }; IDiscountingSource usdDiscountCurve = new DatesAndRates(Currency.USD, anchorDate, curveDates, usdRates); IDiscountingSource zarDiscountCurve = new DatesAndRates(Currency.ZAR, anchorDate, curveDates, zarRates); ISurvivalProbabilitySource abcHazardCurve = new HazardCurve(refEntity, anchorDate, curveDates, hazardRates); var otherCurrency = Currency.USD; var fxSource = new FXForecastCurve(otherCurrency, Currency.ZAR, spot, usdDiscountCurve, zarDiscountCurve); var fxVol = 0.15; NumeraireSimulator model = new DeterministicCreditWithFXJump(abcHazardCurve, otherCurrency, fxSource, zarDiscountCurve, fxVol, relJumpSizeInDefault, expectedRecovery); // Valuation var N = 5000; var coord = new Coordinator(model, new List <Simulator>(), N); var zarValue = coord.Value(new Product[] { cdsZAR }, anchorDate); var usdValue = coord.Value(new Product[] { cdsUSD }, anchorDate); Assert.AreEqual(0.0, zarValue, 800.0); // about 2bp Assert.AreEqual(0.0, usdValue, 800.0); // about 2bp }
/// <summary> /// Initializes a new instance of the <see cref="DeterministicCreditWithFXJump"/> class. /// </summary> /// <param name="survivalProbSource">A curve that provides survival probabilities. Usually a hazard curve.</param> /// <param name="otherCurrency">The other currency required in the simulation. The valuation currency will /// be inferred from the <paramref name="valueCurrencyDiscount"/>. This value needs to be explicitly set /// since <paramref name="fxSource"/> may provide multiple pairs.</param> /// <param name="fxSource">The source FX spot and forwards.</param> /// <param name="valueCurrencyDiscount">The value currency discount curve.</param> /// <param name="fxVol">The fx volatility.</param> /// <param name="relJumpSizeInDefault">The relative jump size in default. For example if the value currency is ZAR and the /// other currency is USD then the fx is modelled as ZAR per USD and in default the fx rate will change to: /// rate before default * (1 + relJumpSizeInDefault).</param> /// <param name="expectedRecoveryRate">The constant recovery rate that will be assumed to apply in default.</param> public DeterministicCreditWithFXJump(ISurvivalProbabilitySource survivalProbSource, Currency otherCurrency, IFXSource fxSource, IDiscountingSource valueCurrencyDiscount, double fxVol, double relJumpSizeInDefault, double expectedRecoveryRate) { this.survivalProbSource = survivalProbSource; valueCurrency = valueCurrencyDiscount.GetCurrency(); this.fxSource = fxSource; this.valueCurrencyDiscount = valueCurrencyDiscount; this.fxVol = fxVol; this.relJumpSizeInDefault = relJumpSizeInDefault; ReferenceEntity refEntity = survivalProbSource.GetReferenceEntity(); defaultTime = new DefaultTime(refEntity); defaultRecovery = new DefaultRecovery(refEntity); currencyPair = new CurrencyPair(otherCurrency, valueCurrency); anchorDate = valueCurrencyDiscount.GetAnchorDate(); spot = fxSource.GetRate(anchorDate); simRecoveryRate = expectedRecoveryRate; }
public static object _CreateHazardCurve(string objectName, object[,] referenceEntity, object[,] anchorDate, object[,] dates, object[,] hazardRates) { try { ReferenceEntity _referenceEntity = XU.GetReferenceEntity0D(referenceEntity, "referenceEntity"); Date _anchorDate = XU.GetDate0D(anchorDate, "anchorDate"); Date[] _dates = XU.GetDate1D(dates, "dates"); Double[] _hazardRates = XU.GetDouble1D(hazardRates, "hazardRates"); HazardCurve _result = XLCredit.CreateHazardCurve(_referenceEntity, _anchorDate, _dates, _hazardRates); return(XU.AddObject(objectName, _result)); } catch (Exception e) { return(XU.Error0D(e)); } }
public static async Task <ReferenceEntity> ToData(CdmReferencedEntityDeclarationDefinition instance, ResolveOptions resOpt, CopyOptions options) { var sourceIndex = instance.EntityPath.LastIndexOf("/"); if (sourceIndex == -1) { Logger.Error(instance.Ctx, Tag, nameof(ToData), instance.AtCorpusPath, CdmLogCode.ErrPersistModelJsonEntityRefConversionError, instance.EntityName); return(null); } var referenceEntity = new ReferenceEntity { Type = "ReferenceEntity", Name = instance.EntityName, Source = instance.EntityPath.Slice(sourceIndex + 1), Description = instance.Explanation, LastFileModifiedTime = instance.LastFileModifiedTime, LastFileStatusCheckTime = instance.LastFileStatusCheckTime }; Utils.ProcessTraitsAndAnnotationsToData(instance.Ctx, referenceEntity, instance.ExhibitsTraits); var t2pm = new TraitToPropertyMap(instance); var isHiddenTrait = t2pm.FetchTraitReference("is.hidden"); if (isHiddenTrait != null) { referenceEntity.IsHidden = true; } var propertiesTrait = t2pm.FetchTraitReference("is.propertyContent.multiTrait"); if (propertiesTrait != null) { referenceEntity.ModelId = propertiesTrait.Arguments.AllItems[0].Value as string; } return(referenceEntity); }
public ActionResult Edit(int id, int referenceId, ReferenceEntity reference, HttpPostedFileBase documentation, string documentationType, string link) { //reference.Title = ""; //title is no longer needed TODO: Update Service Layer to take out title field bool isUrl = false; string path = ""; RegexOptions options = RegexOptions.None; Regex regex = new Regex(@"[ ]{2,}", options); reference.ShortName = regex.Replace(reference.ShortName, @" "); if (reference.ReferenceId > 0) { ReferenceEntity oldReference = Service.ReferenceGet(reference.ReportId, reference.ReferenceId); // get the actual reference because there's no "path" or "isUrl" in the form isUrl = oldReference.isUrl; path = (oldReference.Path != null) ? oldReference.Path : ""; } if (documentationType == "link") //documentationType = 0 unless the user purposefully want to upload something { isUrl = true; path = new UriBuilder(link).Uri.AbsoluteUri; } if (documentationType == "document") path = Helpers.SaveFile(documentation, Server, "references/"+id.ToString()+"/"); bool shortNameIsValid = true; int updatedReferenceId = 0; if (reference.ReferenceId > 0) shortNameIsValid = Service.ReferenceUpdate(id, reference.ReferenceId, reference.ShortName, reference.Bibliography, reference.Authors, reference.Year, path, isUrl); //TODO GenEx else updatedReferenceId = Service.ReferenceAdd(id, reference.ShortName, reference.Bibliography, reference.Authors, reference.Year, path, isUrl); //TODO GenEx if (!shortNameIsValid || updatedReferenceId == -1) { TempData["error"] = "An existing reference already exists with the same shortname."; return RedirectToAction("Edit", new { id = id, referenceId = referenceId }); } return RedirectToAction("Index"); }
public static async Task <CdmReferencedEntityDeclarationDefinition> FromData(CdmCorpusContext ctx, ReferenceEntity obj, string location) { var referencedEntity = ctx.Corpus.MakeObject <CdmReferencedEntityDeclarationDefinition>(CdmObjectType.ReferencedEntityDeclarationDef, obj.Name); referencedEntity.EntityName = obj.Name; var corpusPath = ctx.Corpus.Storage.AdapterPathToCorpusPath(location); if (corpusPath == null) { Logger.Error((ResolveContext)ctx, Tag, nameof(FromData), null, CdmLogCode.ErrPersistModelJsonRefEntityInvalidLocation, location, referencedEntity.EntityName); return(null); } referencedEntity.EntityPath = $"{corpusPath}/{obj.Source}"; referencedEntity.Explanation = obj.Description; referencedEntity.LastFileModifiedTime = obj.LastFileModifiedTime; referencedEntity.LastFileStatusCheckTime = obj.LastFileStatusCheckTime; await Utils.ProcessAnnotationsFromData(ctx, obj, referencedEntity.ExhibitsTraits); if (obj.IsHidden == true) { var isHiddenTrait = ctx.Corpus.MakeRef <CdmTraitReference>(CdmObjectType.TraitRef, "is.hidden", true); isHiddenTrait.IsFromProperty = true; referencedEntity.ExhibitsTraits.Add(isHiddenTrait); } var trait = ctx.Corpus.MakeRef <CdmTraitReference>(CdmObjectType.TraitRef, "is.propertyContent.multiTrait", false); trait.IsFromProperty = true; var argument = ctx.Corpus.MakeObject <CdmArgumentDefinition>(CdmObjectType.ArgumentDef, "modelId"); argument.Value = obj.ModelId; trait.Arguments.Add(argument); referencedEntity.ExhibitsTraits.Add(trait); var extensionTraitDefList = new List <CdmTraitDefinition>(); var extensionTraits = new CdmTraitCollection(ctx, referencedEntity); ExtensionHelper.ProcessExtensionFromJson(ctx, obj, extensionTraits, extensionTraitDefList); if (extensionTraitDefList.Count > 0) { Logger.Warning(ctx, Tag, nameof(FromData), null, CdmLogCode.WarnPersistCustomExtNotSupported, referencedEntity.EntityName); } return(referencedEntity); }
public override void establish_context() { base.establish_context(); entity = new ReferenceEntity(); referenced = new[] { new OtherEntity(), new OtherEntity() }; }
public ReferenceEntity GetReferenceByShortName(int reportid, string shortName) { ReferenceEntity Reference = new ReferenceEntity(); DataTable dt = DB.GetDataTable(new SQLBuilder("Select * from Reference where ReportId = @0 AND ShortName = @1", reportid.ToString(), shortName.ToString())); if (dt.Rows.Count > 0) { Framework.EntityPopulate(Reference, dt.Rows[0]); Reference.ReferenceId = dt.Rows[0].Field<int>("Id"); Reference.isUrl = dt.Rows[0].Field<bool>("isUrl"); } return Reference; }
/// <summary> /// /// </summary> /// <param name="reportId"></param> /// <param name="filter"></param> /// <param name="recordsPerPage">eg: 10, 25</param> /// <param name="page">1 to x</param> /// <returns></returns> public IList<ReferenceEntity> ReferenceList(int reportId, string filter) { /*DataTable dt = DB.GetDataTable(new SQLBuilder(@"WITH result_set AS (SELECT ROW_NUMBER() OVER (ORDER BY ShortName) AS [row_number], Id as ReferenceId, ShortName, Bibliography from Reference where ReportId = @0 and (@1='%%' or (ReferenceKey like @1 or ShortName like @1 or Bibliography like @1))) SELECT * FROM result_set WHERE [row_number] BETWEEN @2 AND @3", reportId.ToString(), "%" + filter + "%",startRecord.ToString(), endRecord.ToString()));*/ DataTable dt = DB.GetDataTable(new SQLBuilder(@"Select Id as ReferenceId, ShortName, Bibliography, Path, IsURL, Year, Authors from Reference where ReportId = @0 and (@1='%%' or (Authors like @1) or (Bibliography like @1)) Order by ShortName", reportId.ToString(), "%" + filter.Trim() + "%")); List<ReferenceEntity> References = new List<ReferenceEntity>(); foreach (DataRow dr in dt.Rows) { ReferenceEntity Reference = new ReferenceEntity(); Framework.EntityPopulate(Reference, dr); // SQ1 nm: using old entity-less dev dB, must end-run Framework.EntityPopulate(). to restore: // - uncomment first commented line // - remove lines below to last commented line "//-----------------" //Reference.Bibliography = dr.Field<string>("Bibliography"); //Reference.ShortName = dr.Field<string>("ShortName"); //Reference.ReferenceId = dr.Field<int>("ReferenceId"); //------------------------- Reference.isUrl = dr.Field<bool>("isUrl"); References.Add(Reference); } return References; }
public static DataViewConfig Get(Guid DataViewTypeID) { if (DataViewConfigTypes == null) { DataViewConfigTypes = new Dictionary <Guid, DataViewConfig>(); } if (DataViewConfigTypes.Keys.Contains(DataViewTypeID)) { return(DataViewConfigTypes[DataViewTypeID]); } string p = System.Web.HttpContext.Current.Request.PhysicalApplicationPath; p = p + "Micajah.Common.config"; DataSet ds = new System.Data.DataSet(); ds.ReadXml(p); DataTable DataViewTable = ds.Tables["DataView"]; DataRow [] rr = DataViewTable.Select("DataViewTypeID='" + DataViewTypeID + "'"); if (rr == null || rr.Length < 1) { return(null); } string Name = (string)rr[0]["Name"]; Guid BaseEntityID = new Guid((string)rr[0]["BaseEntityID"]); int DataView_Id = (int)rr[0]["DataView_Id"]; DataTable ReferenceEntitiesTable = ds.Tables["ReferenceEntities"]; rr = ReferenceEntitiesTable.Select("DataView_Id=" + DataView_Id); if (rr == null || rr.Length < 1) { return(null); } int ReferenceEntities_Id = (int)rr[0]["ReferenceEntities_Id"]; DataTable ReferenceEntityTable = ds.Tables["ReferenceEntity"]; rr = ReferenceEntityTable.Select("ReferenceEntities_Id=" + ReferenceEntities_Id); if (rr == null || rr.Length < 1) { return(null); } List <ReferenceEntity> rel = new List <ReferenceEntity>(); foreach (DataRow r in rr) { ReferenceEntity re = new ReferenceEntity(); re.EntityID = new Guid((string)r["EntityID"]); re.OneToMany = ReferenceEntityTable.Columns.Contains("ReferenceType") && (r["ReferenceType"] is string) && (string)r["ReferenceType"] == "OneToMany"; re.ReferenceTable = ReferenceEntityTable.Columns.Contains("ReferenceTable") && (r["ReferenceTable"] is string)?(string)r["ReferenceTable"]:null; re.Alias = r["Alias"] as string; DataRow[] RR = ds.Tables["entity"].Select("id='" + re.EntityID + "'"); if (RR == null || RR.Length < 1) { return(null); } DataRow EntityRow = RR[0]; re.ReadableName = (string)EntityRow["name"]; re.SqlName = (string)EntityRow["tableName"]; //re.SqlNameFieldName = (string)EntityRow[]; int entity_Id = (int)EntityRow["entity_Id"]; RR = ds.Tables["fields"].Select("entity_Id=" + entity_Id); if (RR == null || RR.Length < 1) { return(null); } int fields_Id = (int)RR[0]["fields_Id"]; int ReferenceEntity_Id = (int)r["ReferenceEntity_Id"]; RR = ds.Tables["UseField"].Select("ReferenceEntity_Id=" + ReferenceEntity_Id); if (RR == null || RR.Length < 1) { return(null); } bool SelectControlExist = ds.Tables["UseField"].Columns.Contains("SelectControl"); re.UseFieldList = new List <ReferenceEntity.UseField>(); DataRow[] FieldsRows; FieldsRows = ds.Tables["field"].Select("fields_Id=" + fields_Id + " AND name='Name'"); if (FieldsRows != null && FieldsRows.Length > 0) { re.SqlNameFieldName = FieldsRows[0]["columnName"].ToString(); } foreach (DataRow R in RR) { ReferenceEntity.UseField uf = new ReferenceEntity.UseField(); uf.Entity = re; uf.ReadableName = (string)R["Name"]; FieldsRows = ds.Tables["field"].Select("fields_Id=" + fields_Id + " AND name='" + uf.ReadableName + "'"); if (FieldsRows == null || FieldsRows.Length < 1) { return(null); } uf.SqlName = (string)FieldsRows[0]["columnName"]; uf.FullColumnName = re.SqlName + "." + uf.SqlName; if (R.Table.Columns.Contains("NODecPlaces") && R["NODecPlaces"] is string) { uf.NODecPlaces = (string)R["NODecPlaces"]; } if (SelectControlExist) { uf.SelectControl = R["SelectControl"] as string; } re.UseFieldList.Add(uf); } rel.Add(re); } DataViewConfig ret = new DataViewConfig(Name, BaseEntityID, DataViewTypeID); ret.ReferenceEntityList = rel; DataViewConfigTypes[DataViewTypeID] = ret; return(ret); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultTime"/> class. /// </summary> /// <param name="refEntity">The reference entity for whom the default time will be monitored.</param> public DefaultRecovery(ReferenceEntity refEntity) { RefEntity = refEntity; }
public SurvivalProbabilitySource(ReferenceEntity referenceEntity, Date anchorDate) { this.referenceEntity = referenceEntity; this.anchorDate = anchorDate; }
private static List <QuestionEntity> GetQuestions(string path, int startOrder = 0) { string allText = File.ReadAllText(path); allText = allText.Replace(char.ConvertFromUtf32(8203), string.Empty); var quesions = allText.Split("###", StringSplitOptions.RemoveEmptyEntries).ToList();; List <QuestionEntity> qeList = new List <QuestionEntity>(); foreach (string question in quesions) { string[] questionsGroups = question.Split($"---", StringSplitOptions.RemoveEmptyEntries); List <string> questionContent = questionsGroups[0].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList(); if (questionContent.Count == 0) { continue; } List <string> questionAnswers = questionsGroups[1].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList(); if (questionAnswers.Any(s => s == "Off and On")) { } questionAnswers = questionAnswers.Where(s => !string.IsNullOrEmpty(s.Trim())).ToList(); List <string> questionExplanations = questionsGroups[2].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList(); questionExplanations = questionExplanations.Where(s => !string.IsNullOrEmpty(s.Trim())).ToList(); List <string> questionReferences = questionsGroups[3].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList(); questionReferences = questionReferences.Where(s => !string.IsNullOrEmpty(s.Trim())).ToList(); QuestionEntity qe = new QuestionEntity(); qe.Order = startOrder + 1 + quesions.IndexOf(question); if (questionContent.FirstOrDefault()?.Equals("C") == true) { qe.QuestionType = QuestionType.CheckBox; questionContent = questionContent.Skip(1).ToList(); } else if (questionContent.FirstOrDefault()?.Equals("D") == true) { qe.QuestionType = QuestionType.DropDown; questionContent = questionContent.Skip(1).ToList(); } foreach (string content in questionContent) { ContentEntity contentEntity = new ContentEntity() { Text = content, Order = questionContent.IndexOf(content), }; qe.Contents.Add(contentEntity); } foreach (string answer in questionAnswers) { AnswerEntity answerEntity = new AnswerEntity() { Text = answer, Order = questionAnswers.IndexOf(answer), }; if (answer.EndsWith("*")) { answerEntity.IsCorrect = true; answerEntity.Text = answer.TrimEnd('*').Trim(); } qe.Answers.Add(answerEntity); } foreach (string explanation in questionExplanations) { ExplanationEntity explanationEntity = new ExplanationEntity() { Text = explanation, Order = questionExplanations.IndexOf(explanation), }; qe.Explanations.Add(explanationEntity); } foreach (string reference in questionReferences) { if (reference.Length > 10) { ReferenceEntity referenceEntity = null; if (reference.Contains(";")) { List <string> parts = reference.Split(";").ToList(); referenceEntity = new ReferenceEntity() { Text = parts[0], Url = parts[1], Order = questionReferences.IndexOf(reference), }; } else { referenceEntity = new ReferenceEntity() { Text = reference, Url = reference, Order = questionReferences.IndexOf(reference), }; } qe.References.Add(referenceEntity); } } qeList.Add(qe); } return(qeList); }
public static async Task <CdmReferencedEntityDeclarationDefinition> FromData(CdmCorpusContext ctx, ReferenceEntity obj, string location, CdmCollection <CdmTraitDefinition> extensionTraitDefList) { var referencedEntity = ctx.Corpus.MakeObject <CdmReferencedEntityDeclarationDefinition>(CdmObjectType.ReferencedEntityDeclarationDef, obj.Name); var corpusPath = ctx.Corpus.Storage.AdapterPathToCorpusPath(location); referencedEntity.EntityName = obj.Name; referencedEntity.EntityPath = $"{corpusPath}/{obj.Source}"; referencedEntity.Explanation = obj.Description; referencedEntity.LastFileModifiedTime = obj.LastFileModifiedTime; referencedEntity.LastFileStatusCheckTime = obj.LastFileStatusCheckTime; await Utils.ProcessAnnotationsFromData(ctx, obj, referencedEntity.ExhibitsTraits); if (obj.IsHidden == true) { var isHiddenTrait = ctx.Corpus.MakeRef <CdmTraitReference>(CdmObjectType.TraitRef, "is.hidden", true); isHiddenTrait.IsFromProperty = true; referencedEntity.ExhibitsTraits.Add(isHiddenTrait); } var trait = ctx.Corpus.MakeRef <CdmTraitReference>(CdmObjectType.TraitRef, "is.propertyContent.multiTrait", true); trait.SimpleNamedReference = false; trait.IsFromProperty = true; var argument = ctx.Corpus.MakeObject <CdmArgumentDefinition>(CdmObjectType.ArgumentDef, "modelId"); argument.Value = obj.ModelId; trait.Arguments.Add(argument); referencedEntity.ExhibitsTraits.Add(trait); ExtensionHelper.ProcessExtensionFromJson(ctx, obj, referencedEntity.ExhibitsTraits, extensionTraitDefList); return(referencedEntity); }
public void Add(ReferenceEntity referenceItem) { db.References.Add(referenceItem); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultTime"/> class. /// </summary> /// <param name="refEntity">The reference entity for whom the default time will be monitored.</param> public DefaultTime(ReferenceEntity refEntity) { RefEntity = refEntity; }
/// <summary> /// Initializes a new instance of the <see cref="HazardCurve"/> class. /// </summary> /// <param name="referenceEntity">The reference entity for whom these hazard rates apply.</param> /// <param name="anchorDate">The anchor date. Survival probabilities can only be calculated up to dates after this date.</param> /// <param name="dates">The dates on which the hazard rates apply.</param> /// <param name="hazardRates">The hazard rates.</param> /// <exception cref="System.ArgumentException"> /// dates must be on or after the anchor date. /// dates must be increasing /// dates and rates must have the same length. /// </exception> public HazardCurve(ReferenceEntity referenceEntity, Date anchorDate, Date[] dates, double[] hazardRates) : base(referenceEntity, anchorDate) { _dates = dates; _hazardRates = hazardRates; }
public async static Task <Model> ToData(CdmManifestDefinition instance, ResolveOptions resOpt, CopyOptions options) { var result = new Model() { Name = instance.ManifestName, Description = instance.Explanation, ModifiedTime = instance.LastFileModifiedTime, LastChildFileModifiedTime = instance.LastChildFileModifiedTime, LastFileStatusCheckTime = instance.LastFileStatusCheckTime }; TraitToPropertyMap t2pm = new TraitToPropertyMap(instance); CdmTraitReference isHiddenTrait = t2pm.FetchTraitReference("is.hidden"); if (isHiddenTrait != null) { result.IsHidden = true; } CdmTraitReference applicationTrait = t2pm.FetchTraitReference("is.managedBy"); if (applicationTrait != null) { result.Application = applicationTrait.Arguments.AllItems[0].Value as string; } CdmTraitReference versionTrait = t2pm.FetchTraitReference("is.modelConversion.modelVersion"); if (versionTrait != null) { result.Version = versionTrait.Arguments.AllItems[0].Value; } else { // version property is required. If it doesn't exist set default. result.Version = "1.0"; } CdmTraitReference cultureTrait = t2pm.FetchTraitReference("is.partition.culture"); if (cultureTrait != null) { result.Culture = cultureTrait.Arguments.AllItems[0].Value as string; } Dictionary <string, string> referenceEntityLocations = new Dictionary <string, string>(); Dictionary <string, string> referenceModels = new Dictionary <string, string>(); CdmTraitReference referenceModelsTrait = t2pm.FetchTraitReference("is.modelConversion.referenceModelMap"); if (referenceModelsTrait != null) { JArray refModels = referenceModelsTrait.Arguments[0].Value as JArray; foreach (JObject referenceModel in refModels) { var referenceModelId = referenceModel["id"]; var referenceModelIdAsString = referenceModelId.ToString(); var referenceModelLocation = referenceModel["location"]; var referenceModelLocationAsString = referenceModelLocation.ToString(); referenceModels.Add(referenceModelIdAsString, referenceModelLocationAsString); referenceEntityLocations.Add(referenceModelLocationAsString, referenceModelIdAsString); } } await Utils.ProcessAnnotationsToData(instance.Ctx, result, instance.ExhibitsTraits); if (instance.Entities != null && instance.Entities.Count > 0) { List <Task> promises = new List <Task>(); var obtainedEntities = new ConcurrentBag <JToken>(); foreach (var entity in instance.Entities) { Task createdPromise = Task.Run(async() => { dynamic element = null; if (entity.ObjectType == CdmObjectType.LocalEntityDeclarationDef) { element = await LocalEntityDeclarationPersistence.ToData( entity as CdmLocalEntityDeclarationDefinition, instance, resOpt, options ); } else if (entity.ObjectType == CdmObjectType.ReferencedEntityDeclarationDef) { element = await ReferencedEntityDeclarationPersistence.ToData( entity as CdmReferencedEntityDeclarationDefinition, resOpt, options ); ReferenceEntity referenceEntity = element as ReferenceEntity; string location = instance.Ctx.Corpus.Storage.CorpusPathToAdapterPath( entity.EntityPath); if (referenceEntity.ModelId != null) { if (referenceModels[referenceEntity.ModelId] == null) { referenceModels[referenceEntity.ModelId] = location; } } else if (referenceEntityLocations[location] != null) { referenceEntity.ModelId = referenceEntityLocations[location]; } else { referenceEntity.ModelId = Guid.NewGuid().ToString(); referenceModels[referenceEntity.ModelId] = location; referenceEntityLocations[location] = referenceEntity.ModelId; } } if (element != null) { obtainedEntities.Add(JToken.FromObject(element)); } else { Logger.Error(nameof(ManifestPersistence), instance.Ctx, "There was an error while trying to convert entity declaration to model json format."); } }); promises.Add(createdPromise); // TODO: Currently function is synchronous. Remove next line to turn it asynchronous. // Currently some functions called are not thread safe. await createdPromise; } await Task.WhenAll(promises); result.Entities = obtainedEntities.ToList(); } if (referenceModels.Count > 0) { result.ReferenceModels = new List <ReferenceModel>(); foreach (var referenceModel in referenceModels) { result.ReferenceModels.Add(new ReferenceModel() { Id = referenceModel.Key, Location = referenceModel.Value }); } } if (instance.Relationships != null && instance.Relationships.Count > 0) { result.Relationships = new List <SingleKeyRelationship>(); foreach (var cdmRelationship in instance.Relationships) { var relationship = await RelationshipPersistence.ToData(cdmRelationship, resOpt, options); if (relationship != null) { result.Relationships.Add(relationship); } else { Logger.Error(nameof(ManifestPersistence), instance.Ctx, "There was an error while trying to convert cdm relationship to model.json relationship."); } } } if (instance.Imports != null && instance.Imports.Count > 0) { result.Imports = new List <Import>(); foreach (var element in instance.Imports) { result.Imports.Add(CdmFolder.ImportPersistence.ToData(element, resOpt, options)); } } return(result); }