///<summary>Inserts one Claim into the database. Returns the new priKey.</summary> internal static long Insert(Claim claim) { if(DataConnection.DBtype==DatabaseType.Oracle) { claim.ClaimNum=DbHelper.GetNextOracleKey("claim","ClaimNum"); int loopcount=0; while(loopcount<100){ try { return Insert(claim,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ claim.ClaimNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(claim,false); } }
public void ReplaceClaimsIfExist(IClaimsIdentity claimsIdentity, Claim claimToReplaceIfExists) { var existingClaim = claimsIdentity.Claims.FirstOrDefault(x=> x.ClaimType == claimToReplaceIfExists.ClaimType); if (existingClaim != null) claimsIdentity.Claims.Remove(existingClaim); claimsIdentity.Claims.Add(claimToReplaceIfExists); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var result = new Collection<Claim>(); while (reader.Read()) { if (reader.TokenType == JsonToken.EndArray) break; if (reader.TokenType != JsonToken.StartObject) continue; var jo = JObject.Load(reader); var claim = new Claim( (string)jo["ClaimType"], (string)jo["Value"], (string)jo["ValueType"], (string)jo["Issuer"], (string)jo["OriginalIssuer"] ); var jt = jo["Properties"]; var props = serializer.Deserialize<Dictionary<string, string>>(jt.CreateReader()); foreach (var entry in props) claim.Properties.Add(entry.Key, entry.Value); result.Add(claim); } // Reading EndObject; reader.Read(); return result; }
public Geo.Box addClaim(string userName, double lat, double lng) { Claim tile = new Claim(lat, lng); if (!_users.ContainsKey(userName)) { User user = new User(userName); _users.Add(userName, user); } if (!_claims.ContainsKey(tile.box)) { _claims.Add(tile.box, tile); } double changeInShares = _claims[tile.box].makeClaim(userName); _users[userName].addShares(changeInShares); foreach (string user in _claims[tile.box].getOwners().Keys) { if (user != userName) { _users[user].addShares(changeInShares * -1); } } return tile.box; }
public Claim[] getClaims() { Claim[] c = new Claim[_claims.Count]; _claims.Values.CopyTo(c,0); return c; }
public void Install() { SVEN = EmployeeFixture.SVEN; DICK = EmployeeFixture.DICK; var date1 = new DateTime(2007, 7, 15); SVEN_CLAIM_4 = CreateNewClaim(SVEN, DICK, "July 07 - 2 visits to Dublin", ProjectCodeFixture.CODE2, date1); AddPrivateCarJourney(SVEN_CLAIM_4, date1, "Own car to airport", "Henley on Thames", "Heathrow", true, 50); AddGeneralExpense(SVEN_CLAIM_4, date1, "Car Parking at Heathrow", Convert.ToDecimal(42.9)); AddAirfare(SVEN_CLAIM_4, date1, null, 165M, "Aer Lingus", "LHR", "DUB", true); AddTaxi(SVEN_CLAIM_4, date1, "Taxis to & from Hotel", 30M, "Dublin Airport", "Alexander Hotel", true); AddHotel(SVEN_CLAIM_4, date1, "Alexander Hotel", 0M, "http://ocallaghanhotels.visrez.com/dublinmain/Alexander.aspx", 1, 89M, Convert.ToDecimal(15.45), Convert.ToDecimal(3.5)); AddMeal(SVEN_CLAIM_4, date1, "Dinner", 28M); date1 = new DateTime(2007, 7, 23); AddPrivateCarJourney(SVEN_CLAIM_4, date1, "Own car to airport", "Henley on Thames", "Heathrow", true, 50); AddGeneralExpense(SVEN_CLAIM_4, date1, "Car Parking at Heathrow", Convert.ToDecimal(42.9)); AddAirfare(SVEN_CLAIM_4, date1, null, 129M, "Aer Lingus", "LHR", "DUB", true); AddTaxi(SVEN_CLAIM_4, date1, "Taxis to & from Hotel", 32M, "Dublin Airport", "Alexander Hotel", true); AddHotel(SVEN_CLAIM_4, date1, "Alexander Hotel", 0M, "http://ocallaghanhotels.visrez.com/dublinmain/Alexander.aspx", 1, 89M, Convert.ToDecimal(15.45), Convert.ToDecimal(4.8)); AddMeal(SVEN_CLAIM_4, date1, "Dinner", 31M); SVEN_CLAIM_4.Submit(DICK, false); SVEN_CLAIM_4.ApproveItems(false); }
public static void Execute(Claim claim) { var sw = Stopwatch.StartNew(); var transaction = claim.CreateAmendClaimWithoutValidationTransaction(); if (transaction == null) return; try { List<FlattenedTransaction> transactions; GlobalClaimWakeUp.MappedTransactionDetails.TryRemove(claim.ClaimReference, out transactions); if (ShouldExecute(claim)) { var claimHeader = transaction.ClaimHeader; claimHeader.CustomCode18 = claim.CustomCode18; transaction.Complete(false); } } catch { transaction.Cancel(); } finally { sw.Stop(); var workDone = GlobalClaimWakeUp.Statistics.GetOrAdd(typeof(SetCustomCode18Block).Name, TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); GlobalClaimWakeUp.Statistics[typeof(SetCustomCode18Block).Name] = (workDone + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); } }
private static void ValidateClaimUsingTransactionRules(AbstractClaimsBusinessTransaction amendTransaction, Claim claim) { // The System Rules Plugin is run for any component change - need to verify it will be run across components that haven't changed as well. var claimHeader = amendTransaction.ClaimHeader; try { amendTransaction.Validate(ValidationMode.Full); var errorOrFatalErrorMessages = amendTransaction.Results.SelectMany( r => r.Value.SelectMany( kvp => kvp.Value.Where( pr => (pr.Severity == ErrorSeverity.Error || pr.Severity == ErrorSeverity.Fatal) ) ) ) .ToArray(); if (errorOrFatalErrorMessages.Any()) { Logger.WarnFormat("Claim failed validation\r\n{0}\r\n", JObject.FromObject( new { claimHeader.ClaimReference, Messages = errorOrFatalErrorMessages.Select(m => new { m.Severity, m.MessageSource, m.Message }).ToArray() })); claim.CustomCode18 = "V02"; } } catch (Exception exc) { Logger.WarnFormat("Fatal validation error for Claim \r\n{0}\r\n", JObject.FromObject(new { amendTransaction.ClaimHeader.ClaimReference, exc.Message, exc.StackTrace })); claim.CustomCode18 = "V01"; } }
private static void AddDetails(ref PdfPTable table, ref Claim claim) { table.AddCell(CreateDetailTitleCell("Customer Complaint")); table.AddCell(CreateDetailCell(claim.CustomerComplaint.ToUpper())); table.AddCell(CreateSpacerCell()); table.AddCell(CreateDetailTitleCell("Cause of Failure")); table.AddCell(CreateDetailCell(claim.CauseOfFailure.ToUpper())); table.AddCell(CreateSpacerCell()); table.AddCell(CreateDetailTitleCell("Corrective Action")); table.AddCell(CreateDetailCell(claim.CorrectiveAction.ToUpper())); table.AddCell(CreateSpacerCell()); if(claim.MiscAmountExplanation.Trim().Length > 0 && !claim.MiscAmountExplanation.Trim().ToUpper().Equals("NONE")) { table.AddCell(CreateDetailTitleCell("Misc Amount Explanation")); table.AddCell(CreateDetailCell(claim.MiscAmountExplanation.ToUpper())); table.AddCell(CreateSpacerCell()); } if(claim.ReimbursementComment.Trim().Length > 0 && !claim.ReimbursementComment.Trim().ToUpper().Equals("NONE")) { table.AddCell(CreateDetailTitleCell("Reimbursement Comment")); table.AddCell(CreateDetailCell(claim.ReimbursementComment.ToUpper())); table.AddCell(CreateSpacerCell()); } }
private DefaultClaimSet CreateIssuer() { Claim issuerNameClaim = Claim.CreateNameClaim(IssuerName); Claim[] claims = new Claim[] { issuerNameClaim }; return new DefaultClaimSet(claims); }
public static Claim Execute(Claim claim) { var sw = Stopwatch.StartNew(); if (!ShouldExecute(claim)) return claim; ClearLocksBlock.UnlockClaim(claim); try { if (!Reopening(claim)) { var transaction = claim.CreateAmendClaimTransaction(); if (transaction == null) return claim; ValidateClaimUsingTransactionRules(transaction, claim); transaction.Cancel(); } if (string.IsNullOrEmpty(claim.CustomCode18)) claim.CustomCode18 = claim.ExcessAndDeductiblesToProcess ? "C01" : "C02"; return claim; } finally { sw.Stop(); var workDone = GlobalClaimWakeUp.Statistics.GetOrAdd(typeof(ValidateClaimBlock).Name, TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); GlobalClaimWakeUp.Statistics[typeof(ValidateClaimBlock).Name] = (workDone + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); } }
protected internal virtual CarRental AddCarRental(Claim claim, DateTime dateIncurred, string description, decimal amount, string rentalCompany, int noOfDays) { var item = (CarRental) (CreateExpenseItem(claim, ExpenseTypeFixture.CAR_RENTAL, dateIncurred, description, amount)); item.ModifyRentalCompany(rentalCompany); item.ModifyNumberOfDays(noOfDays); Container.Persist(ref item); return item; }
public static Claim Execute(Claim claim) { var sw = Stopwatch.StartNew(); try { if (!ShouldExecute(claim) ) return claim; var transaction = claim.CreateAmendClaimWithoutValidationTransaction(); ClaimHeader claimHeader = transaction.ClaimHeader; if (claimHeader == null && InvalidCodes.Contains(claimHeader.ClaimHeaderStatusCode)) { transaction.Cancel(); return claim; } // Transfer to Genius CreateClaimTransferRequests(claimHeader, claim); transaction.Cancel(); claim.ClaimTransfered = true; return claim; } finally { sw.Stop(); var workDone = GlobalClaimWakeUp.Statistics.GetOrAdd(typeof(CreateClaimTransferRequestsBlock).Name, TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); GlobalClaimWakeUp.Statistics[typeof(CreateClaimTransferRequestsBlock).Name] = (workDone + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); } }
protected internal virtual Airfare AddAirfare(Claim claim, DateTime dateIncurred, string description, decimal amount, string airline, string origin, string destination, bool returnJourney) { var item = (Airfare) (CreateExpenseItem(claim, ExpenseTypeFixture.AIRFARE, dateIncurred, description, amount)); item.ModifyAirlineAndFlight(airline); ModifyStandardJourneyFields(item, origin, destination, returnJourney); Container.Persist(ref item); return item; }
public void CRUD() { using (var executionContext = new CommonTestExecutionContext()) { var repository = new Common.DomRepository(executionContext); var unitTestClaims = repository.Common.Claim.Query().Where(c => c.ClaimResource.StartsWith("unittest_")).ToList(); Console.WriteLine("Delete old: " + TestUtility.DumpSorted(unitTestClaims, c => c.ClaimResource + "." + c.ClaimRight) + "."); repository.Common.Claim.Delete(unitTestClaims); IClaimRepository cr = repository.Common.Claim; var c1 = new Claim("unittest_c1", "c11"); var c2 = new Claim("unittest_c2", "c22"); var c3 = new Claim("unittest_c3", "c33"); cr.SaveClaims(new[] { c1, c2, c3 }, new ICommonClaim[] {}, new ICommonClaim[] {}); var loaded = cr.LoadClaims().Where(c => c.ClaimResource.StartsWith("unittest_")).ToList(); loaded.Sort((cl1, cl2) => cl1.ClaimResource.CompareTo(cl2.ClaimResource)); Assert.AreEqual("c11, c22, c33", TestUtility.Dump(loaded, c => c.ClaimRight)); loaded[0].ClaimRight = loaded[0].ClaimRight.ToUpper(); var c4 = new Claim("unittest_c4", "c44"); cr.SaveClaims(new[] { c4 }, new[] { loaded[0] }, new[] { loaded[1] }); loaded = cr.LoadClaims().Where(c => c.ClaimResource.StartsWith("unittest_")).ToList(); loaded.Sort((cl1, cl2) => cl1.ClaimResource.CompareTo(cl2.ClaimResource)); Assert.AreEqual("C11, c33, c44", TestUtility.Dump(loaded, c => c.ClaimRight)); } }
private static void CopyClaims(IClaimsIdentity source, IClaimsIdentity target) { foreach (var claim in source.Claims) { // We don't copy the issuer because it is not needed in this case. The STS always issues claims // using its own identity. var newClaim = new Claim(claim.ClaimType, claim.Value, claim.ValueType); // copy all claim properties foreach (var key in claim.Properties.Keys) { newClaim.Properties.Add(key, claim.Properties[key]); } // add claim to the destination identity target.Claims.Add(newClaim); } // Recursively copy claims from the source identity delegates if (source.Actor != null) { target.Actor = new ClaimsIdentity(); CopyClaims(source.Actor, target.Actor); } }
private AbstractExpenseItem CreateExpenseItem(Claim claim, ExpenseType type, DateTime dateIncurred, string description, decimal amount) { AbstractExpenseItem item = (claim.CreateNewExpenseItem(type)); item.ModifyDateIncurred(dateIncurred); item.ModifyDescription(description); item.ModifyAmount(Money(amount, claim)); return item; }
public static Claim Execute(Claim claim) { var sw = Stopwatch.StartNew(); if (!ShouldExecute(claim)) return claim; var transaction = claim.CreateAmendClaimWithoutValidationTransaction(); if (transaction == null) return claim; try { var claimHeader = transaction.ClaimHeader; if (claimHeader.ClaimHeaderInternalStatus >= (short)StaticValues.ClaimHeaderInternalStatus.Finalized) return claim; var productEvent = claim.ProductType == "MOT" ? _motorProductEvents.Value : _liabilityProductEvents.Value; var reviewEvent = CreateReviewEvent(claimHeader, claim.GeniusXClaimHandler, productEvent.ProductEventId); transaction.Complete(false); if (reviewEvent != null) { var processHandler = GlobalClaimWakeUp.Container.Resolve<ClaimsProcessHandler>(); processHandler.ProcessComponent(reviewEvent, ProcessInvocationPoint.Virtual, 0, new ProcessParameters { Alias = "AXAManualReviewStartClaimProcessHandler" }); Logger.InfoFormat("Review Task successfully created for Claim\r\n{0}\r\n", JObject.FromObject(new { claimHeader.ClaimReference, UserId = claim.GeniusXClaimHandler })); } return claim; } catch { transaction.Cancel(); return claim; } finally { sw.Stop(); var workDone = GlobalClaimWakeUp.Statistics.GetOrAdd(typeof(CreateReviewTaskBlock).Name, TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); GlobalClaimWakeUp.Statistics[typeof(CreateReviewTaskBlock).Name] = (workDone + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); } }
protected internal virtual PrivateCarJourney AddPrivateCarJourney(Claim claim, DateTime dateIncurred, string description, string origin, string destination, bool returnJourney, int totalMiles) { var item = (PrivateCarJourney) (CreateExpenseItem(claim, ExpenseTypeFixture.PRIVATE_CAR, dateIncurred, description, 0M)); ModifyStandardJourneyFields(item, origin, destination, returnJourney); item.ModifyTotalMiles(totalMiles); item.ModifyMileageRate(0.4); Container.Persist(ref item); return item; }
public void Install() { SVEN = EmployeeFixture.SVEN; DICK = EmployeeFixture.DICK; SVEN_CLAIM_5 = CreateNewClaim(SVEN, null, "14th Mar - Sales call, London", ProjectCodeFixture.CODE1, new DateTime(2007, 4, 3)); var mar14th = new DateTime(2007, 3, 14); AddTaxi(SVEN_CLAIM_5, mar14th, null, 18M, "Euston", "City", true); AddMeal(SVEN_CLAIM_5, mar14th, "Lunch with client", 50M); }
public void AdjustClaimReducesCorrectly() { ClaimCalculator calcualtor = new ClaimCalculator(); Claim claim = new Claim(1, DateTime.Now, 10.0); double expected = 5.0F; double actual = calcualtor.AdjustClaim(claim); Assert.AreEqual(expected, actual); }
public void CtorAndProperties() { // Act Claim claim = new Claim("claim-type", "claim-value"); // Assert Assert.Equal("claim-type", claim.ClaimType); Assert.Equal("claim-value", claim.Value); }
public void FromMemento() { var id = ClaimId.NewId(); var expected = new Claim(id); var actual = _unitUnderTest.FromMemento(expected.GetMemento()); Assert.AreEqual(expected, actual); }
public RuleException TestRule(int clientID, Claim claim) { string claimLimit = null; bool isRuleMet = false; int numberOfClaims = 0; int numberOfClaimsLimit = 0; // skip if no adjuster assigned to claim if ((claim.AdjusterID ?? 0) == 0) return null; // get number of claims assigned to adjuster numberOfClaims = ClaimsManager.getAdjusterClaimCount((int)claim.AdjusterID); // get business rules for client/rule type id using (BusinessRuleManager repository = new BusinessRuleManager()) { rules = repository.GetBusinessRules(clientID, Globals.RuleType.AdjusterClaimReview); } if (rules != null && rules.Count > 0) { // build value array values = new string[] { claim.AdjusterID.ToString() }; foreach (BusinessRule rule in rules) { XElement ruleXML = XElement.Parse(rule.RuleXML); XElement adjusterCondition = base.GetElement(ruleXML, "AdjusterID", claim.AdjusterID.ToString()); claimLimit = base.GetElementValue(ruleXML, "Claim"); if (adjusterCondition != null && !string.IsNullOrEmpty(claimLimit)) { if (int.TryParse(claimLimit, out numberOfClaimsLimit) && numberOfClaimsLimit > 0) { isRuleMet = (numberOfClaims <= numberOfClaimsLimit); } } if (isRuleMet) { // add exception to queue ruleException = new RuleException(); ruleException.BusinessRuleID = rule.BusinessRuleID; ruleException.ClientID = clientID; ruleException.ObjectID = claim.ClaimID; ruleException.ObjectTypeID = (int)Globals.ObjectType.Claim; break; } } } return this.ruleException; }
public void Install() { SVEN = EmployeeFixture.SVEN; DICK = EmployeeFixture.DICK; SVEN_CLAIM_1 = CreateNewClaim(SVEN, DICK, "28th Mar - Sales call, London", ProjectCodeFixture.CODE1, new DateTime(2007, 4, 3)); var mar28th = new DateTime(2007, 3, 28); AddTaxi(SVEN_CLAIM_1, mar28th, null, Convert.ToDecimal(8.5), "Euston", "Mayfair", false); AddMeal(SVEN_CLAIM_1, mar28th, "Lunch with client", Convert.ToDecimal(31.9)); AddTaxi(SVEN_CLAIM_1, mar28th, null, 11M, "Mayfair", "City", false); }
protected internal virtual Hotel AddHotel(Claim claim, DateTime dateIncurred, string description, decimal amount, string hotelURL, int numberOfNights, decimal accommodation, decimal food, decimal other) { var item = (Hotel) (CreateExpenseItem(claim, ExpenseTypeFixture.HOTEL, dateIncurred, description, amount)); item.ModifyHotelURL(hotelURL); item.ModifyNumberOfNights(numberOfNights); item.ModifyAccommodation(Money(accommodation, claim)); item.ModifyFood(Money(food, claim)); item.ModifyOther(Money(other, claim)); Container.Persist(ref item); return item; }
private static bool ShouldExecute(Claim claim) { var config = GlobalClaimWakeUp.Container.Resolve<ClaimProcessorConfiguration>(); if (config.ReopeningClaims) return config.TaskIsEnabled[typeof(CreateClaimTransferRequestsBlock)] && (!claim.ClaimIsDuplicate && claim.ClaimIsClosed && !claim.ClaimProcessingFailed && !claim.ClaimAlreadyProcessed); return config.TaskIsEnabled[typeof(CreateClaimTransferRequestsBlock)] && (!claim.ClaimIsDuplicate && !claim.ClaimIsClosed && !claim.ClaimProcessingFailed && !claim.ClaimAlreadyProcessed); }
public static void HasClaim(IEnumerable<Claim> claims, Claim expected) { Assert.AreEqual(1, (from c in claims where c.ClaimType == expected.ClaimType && c.Value == expected.Value && (String.IsNullOrEmpty(expected.OriginalIssuer) || c.OriginalIssuer == expected.OriginalIssuer) && (String.IsNullOrEmpty(expected.ValueType) || c.ValueType == expected.ValueType) && (String.IsNullOrEmpty(expected.Issuer) || c.Issuer == expected.Issuer) select c).Count()); }
protected virtual bool AuthorizeCore(Claim action, Collection<Claim> resource, IClaimsIdentity id) { switch (action.Value) { case Constants.Actions.Issue: return AuthorizeTokenIssuance(resource, id); case Constants.Actions.Administration: return AuthorizeAdministration(resource, id); } return false; }
/// <summary>Applies the splitting rule to the claim provided.</summary> /// <param name="c">The claim to split.</param> /// <remarks>If the procedure code is not in the claim, or the claim has all /// of the resulting codes of this rule already, then this function will not /// modify the claim in any way.</remarks> override public void Split(Claim c) { if (isAlreadySplit(c)) { return; } int tempFee; int tempPayments; Treatment tempTreatment; ArrayList newTreatments = new ArrayList(); int totalFee = 0; bool isSecondary = c.Identity.Type == ClaimType.Secondary; foreach (Treatment t in c.TreatmentInformation.Treatments) { if (t.ProcedureCode == this.ProcedureCode) { tempFee = NHDG.NHDGCommon.Utilities.UnFormatCurrency(t.Fee); if (isSecondary) tempPayments = NHDG.NHDGCommon.Utilities.UnFormatCurrency(t.PrimaryPaidAmount); else tempPayments = 0; foreach (SplitRuleDetail d in this.ruleDetails) { tempTreatment = new Treatment(); tempTreatment.Description = d.Description; tempTreatment.DiagnosisIndex = t.DiagnosisIndex; if (d.Priority == 0) { tempTreatment.Fee = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(tempFee); if (isSecondary) tempTreatment.PrimaryPaidAmount = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(tempPayments); } else if (tempFee >= d.Value) { tempFee -= d.Value; tempTreatment.Fee = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(d.Value); if (isSecondary) { if (tempPayments > NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.Fee)) { // There is more than enough money to cover this first payment tempTreatment.PrimaryPaidAmount = tempTreatment.Fee; } else { // All the available money goes toward this treatment tempTreatment.PrimaryPaidAmount = t.PrimaryPaidAmount; } tempPayments -= NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.PrimaryPaidAmount); } } else { tempTreatment.Fee = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(tempFee); if (tempFee > 0) { tempFee = 0; } if (isSecondary) { if (tempPayments > NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.Fee)) { // There is more than enough money to cover this first payment tempTreatment.PrimaryPaidAmount = tempTreatment.Fee; } else { // All the available money goes toward this treatment tempTreatment.PrimaryPaidAmount = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(tempPayments); } tempPayments -= NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.PrimaryPaidAmount); } } tempTreatment.ProcedureCode = d.ProcedureCode; tempTreatment.ProcedureDate = t.ProcedureDate; tempTreatment.Quantity = t.Quantity; tempTreatment.Surface = t.Surface; tempTreatment.Tooth = t.Tooth; if (isSecondary) { tempTreatment.SecondaryDate = t.SecondaryDate; tempTreatment.PatientResponsibleAmount = NHDG.NHDGCommon.Utilities.FormatCurrencyForXML(NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.Fee) - NHDG.NHDGCommon.Utilities.UnFormatCurrency(tempTreatment.PrimaryPaidAmount)); } newTreatments.Add(tempTreatment); totalFee += Utilities.UnFormatCurrency(tempTreatment.Fee); } } else { newTreatments.Add(t); totalFee += Utilities.UnFormatCurrency(t.Fee); } } c.TreatmentInformation.Treatments = newTreatments; c.TreatmentInformation.TotalFee = Utilities.FormatCurrencyForXML(totalFee); }
public ClaimDTO(Claim auth) { this.Id = auth.Id; this.Name = auth.Name; this.Permissions = auth.Permissions.Select(p => p.PermissionId).ToArray(); }
public User(Claim claim) { Name = claim.UserName; }
public ClaimRequirementFilter(Claim claim) { this.claim = claim; }
public RequisitoClaimFilter(Claim claim) { _claim = claim; }
public GetByClaim(Claim claim) { Claim = claim; }
private void ImportClaim(RoleData roleData) { if (Claims.ContainsKey(roleData.id)) { return; } var claim = new Claim { Project = Project, ProjectId = Project.ProjectId, Character = null, //see later Group = null, // see later Comments = new List <Comment>() { new Comment() { Author = Project.ProjectAcls.Single(acl => acl.IsOwner).User, CommentText = new CommentText() { Text = new MarkdownString($"<a href=\"http://site.allrpg.info/orders/orders/{roleData.id}/act=view&site={Project.Details.AllrpgId}\">Заявка в allrpg</a>") }, CreatedTime = UnixTime.ToDateTime(roleData.datesent), IsCommentByPlayer = false, IsVisibleToPlayer = false, LastEditTime = UnixTime.ToDateTime(roleData.datesent), ParentCommentId = null, Project = Project, } }, CreateDate = UnixTime.ToDateTime(roleData.datesent), Player = Users[roleData.sid], MasterDeclinedDate = roleData.todelete2 == 0 && roleData.status != 4 ? (DateTime?)null : UnixTime.ToDateTime(roleData.date), PlayerDeclinedDate = roleData.todelete == 0 ? (DateTime?)null : UnixTime.ToDateTime(roleData.date), PlayerAcceptedDate = UnixTime.ToDateTime(roleData.datesent), LastUpdateDateTime = UnixTime.ToDateTime(roleData.date) }; foreach (var virtualField in roleData.@virtual) { if (virtualField.Key == 7152) //Known steam2016 "responsible master" { int responsibleMasterIdx; if (int.TryParse(virtualField.Value, out responsibleMasterIdx)) { var responsibleSid = Steam2016ResponsibleMasters[responsibleMasterIdx]; claim.ResponsibleMasterUser = responsibleSid == null ? null : Users[(int)responsibleSid]; } } else if (ConvertToCommentVirtualFields.Contains(virtualField.Key) && !string.IsNullOrWhiteSpace(virtualField.Value)) { claim.Comments.Add(new Comment() { Author = Users[roleData.sid], CommentText = new CommentText() { Text = new MarkdownString(virtualField.Value) }, CreatedTime = claim.CreateDate, IsCommentByPlayer = true, IsVisibleToPlayer = true, LastEditTime = DateTime.UtcNow, ParentCommentId = null, Project = Project, }); } } bool canbeApproved = false; Character character; CharacterGroup characterGroup; if (Characters.TryGetValue(roleData.vacancy, out character)) { claim.Character = character; canbeApproved = true; } else if (LocationsFromVacancies.TryGetValue(roleData.vacancy, out characterGroup)) { claim.Group = characterGroup; } else if (Locations.TryGetValue(roleData.locat, out characterGroup)) { claim.Group = characterGroup; } else { claim.Group = Project.RootGroup; } claim.MasterAcceptedDate = canbeApproved && roleData.status == 3 ? UnixTime.ToDateTime(roleData.date) : (DateTime?)null; claim.ClaimStatus = ConvertAllrpgStatus(roleData, canbeApproved); Claims.Add(roleData.id, claim); }
/// <summary> /// 变更 /// </summary> /// <param name="currentPrincipalAccessor">当前安全主体访问器</param> /// <param name="claim">声明</param> public static IDisposable Change(this ICurrentPrincipalAccessor currentPrincipalAccessor, Claim claim) => currentPrincipalAccessor.Change(new[] { claim });
internal void ReplaceClaim(Claim existingClaim, Claim newClaim) { RemoveClaim(existingClaim); AddClaim(newClaim); }
internal void RemoveClaim(Claim claim) { Claims.RemoveAll(x => x.Type == claim.Type && x.Value == claim.Value); }
internal void AddClaim(Claim claim) { Claims.Add(claim); }
protected internal IdentityClaim(Guid id, [NotNull] Claim claim, Guid?tenantId) : this(id, claim.Type, claim.Value, tenantId) { }
/// <summary> ///初始化由其他索赔claimtype和claimvalue复制。 /// </summary> /// <param name="other">The claim to initialize from.</param> public virtual void InitializeFromClaim(Claim other) { ClaimType = other?.Type; ClaimValue = other?.Value; }
public Task AddClaimAsync(TUser user, Claim claim) { return(_userClaimRepository.InsertAsync(new UserClaim(user, claim))); }
/// <summary> /// Initializes the default settings related to users and roles. Also performs integrity checks against the exisiting default users and roles. /// </summary> public static async Task Initialize(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager, IConfiguration configuration, ILogger <RegisterModel> logger, DbCommonFunctionality dbCommonFunctionality) { context.Database.EnsureCreated(); var administration = configuration.GetSection("AdminDefault"); string userName = administration.GetSection("UserName").Value; string email = administration.GetSection("Email").Value; string phoneNumber = administration.GetSection("PhoneNumber").Value; string adminRole = configuration.GetSection("AdminRole").Value; string password = administration.GetSection("Password").Value; string firstName = administration.GetSection("FirstName").Value; string lastName = administration.GetSection("LastName").Value; string defaultRole = configuration.GetSection("DefaultRole").Value; // create the role associated to the default admin if it doesn't exist if (await roleManager.FindByNameAsync(adminRole) == null) { var result = await roleManager.CreateAsync(new ApplicationRole(adminRole)); if (result.Succeeded) { logger.LogInformation("Created admin role."); } else { LogErrors(result.Errors, logger); return; } } ApplicationRole createdAdminRole = await roleManager.FindByNameAsync(adminRole); Claim newAdminClaim = new Claim(configuration.GetSection("Claims").GetSection("AdminClaim").GetSection("Identifier").Value, "true"); Claim existingAdminClaim = (await roleManager.GetClaimsAsync(createdAdminRole)).FirstOrDefault(); // if existing admin claim is incorrect if (existingAdminClaim != null) { if (existingAdminClaim.Type != newAdminClaim.Type || existingAdminClaim.Value != newAdminClaim.Value) { // remove the incorrect admin claim var result = await roleManager.RemoveClaimAsync(createdAdminRole, existingAdminClaim); if (result.Succeeded) { existingAdminClaim = null; // make sure we add back the correct claim next logger.LogInformation("Removed incorrect admin claim."); } else { LogErrors(result.Errors, logger); return; } } } // create and assign the admin claim to the admin role if the admin claim doesn't exist if (existingAdminClaim == null) { var result = await roleManager.AddClaimAsync(createdAdminRole, newAdminClaim); if (result.Succeeded) { logger.LogInformation("Created admin claim."); } else { LogErrors(result.Errors, logger); return; } } // create the default role if it doesn't exist if (await roleManager.FindByNameAsync(defaultRole) == null) { var result = await roleManager.CreateAsync(new ApplicationRole(defaultRole)); if (result.Succeeded) { logger.LogInformation("Created user role."); } else { LogErrors(result.Errors, logger); return; } } var user = await userManager.FindByNameAsync(userName); // find admin by default admin username if (user == null) { // if couldn't find admin by default admin username then create it user = new ApplicationUser { UserName = userName, Email = email, PhoneNumber = phoneNumber, FirstName = firstName, LastName = lastName }; // add password associated to default admin var result = await userManager.CreateAsync(user, password); if (result.Succeeded) { logger.LogInformation("Created default admin account with password."); // find admin by default admin username again as a new id was created for this user so we need to get the user info again user = await userManager.FindByNameAsync(userName); } else { LogErrors(result.Errors, logger); return; } } // find current role associated to default admin var role = dbCommonFunctionality.GetRoleByUserId(user.Id); // if role is incorrect if (role != null && role.Name != adminRole) { // remove that incorrect role from the associated default admin IdentityResult result = await userManager.RemoveFromRoleAsync(user, role.Name); if (result.Succeeded) { logger.LogInformation("Invalid role removed from default admin account."); role = null; // role instance needs to be updated } else { LogErrors(result.Errors, logger); return; } } // if there's no role associated to default admin if (role == null) { // add the correct role to the default admin IdentityResult result = await userManager.AddToRoleAsync(user, adminRole); if (result.Succeeded) { logger.LogInformation("Admin role added to default admin account."); } else { LogErrors(result.Errors, logger); return; } } }
/// <summary> /// Returns a new IEnumerable that replaces claim based on newClaim.Type. /// </summary> /// <param name="claimsIdentity"></param> /// <param name="newClaim"></param> /// <returns></returns> public static IEnumerable <Claim> ReplaceClaim(this IEnumerable <Claim> claimsIdentity, Claim newClaim) { return(claimsIdentity.Select(claim => claim.Type == newClaim.Type ? newClaim : claim)); }
public IdentityUserClaim(Claim claim) { this.ClaimType = claim.Type; this.ClaimValue = claim.Value; }
public async Task <IEnumerable <ApplicationUser <TKey> > > GetUsersForClaimAsync(Claim claim) { string sqlQuery = "SELECT * FROM [dbo].[Users] AS [u] INNER JOIN [dbo].[UserClaims] AS [uc] " + "ON [u].[Id] = [uc].[UserId] WHERE ClaimType = @ClaimType, ClaimValue = @ClaimValue"; return(await _connection.QueryAsync <ApplicationUser <TKey> >(sqlQuery, new { ClaimType = claim.Type, ClaimValue = claim.Value })); }
public ClaimRequirementFilter(Claim claim) { _claim = claim; }
public async Task <IActionResult> IssueToken() { var pemFileName = Environment.GetEnvironmentVariable(Defines.PrivateKeyFileEnvironmentVariableName) ?? throw new ApplicationException( $"\"{Defines.PrivateKeyFileEnvironmentVariableName}\" environment variable is not set or empty"); logger.LogInformation($"Reading private key from file: {pemFileName}"); var pemDataBytes = await System.IO.File.ReadAllBytesAsync(pemFileName); var pemDataString = Encoding.UTF8.GetString(pemDataBytes); // Use "-----BEGIN PRIVATE KEY-----" and "-----END PRIVATE KEY-----" headers for PKCS8 var b64 = pemDataString.Replace("-----BEGIN RSA PRIVATE KEY-----", string.Empty) .Replace("-----END RSA PRIVATE KEY-----", string.Empty) .Replace("\n", string.Empty) .Trim(); var privateKey = Convert.FromBase64String(b64); var rsa = System.Security.Cryptography.RSA.Create(); // Use rsa.ImportPkcs8PrivateKey(privateKey, out var bytesRead) for PKCS8 keys rsa.ImportRSAPrivateKey(privateKey, out var bytesRead); logger.LogInformation($"RSA private key bytes read: {bytesRead}"); var securityKey = new RsaSecurityKey(rsa); logger.LogInformation($"RSA security key size: {securityKey.KeySize} bits"); // Use preferred sign algorithm var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256); var jwtHeader = new JwtHeader(signingCredentials); const string jti = "TokenIndex"; var jwtPayload = new JwtPayload { { JwtRegisteredClaimNames.Jti, jti }, { JwtRegisteredClaimNames.Sub, "TokenSubject" }, { JwtRegisteredClaimNames.Aud, "TokenAudience" }, { "CustomClaim", "SomeData" }, }; var i = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var e = i + Defines.TokenTtl; var iat = new Claim(JwtRegisteredClaimNames.Iat, i.ToString(), ClaimValueTypes.Integer64); var exp = new Claim(JwtRegisteredClaimNames.Exp, e.ToString(), ClaimValueTypes.Integer64); jwtPayload.AddClaim(iat); jwtPayload.AddClaim(exp); var token = new JwtSecurityToken(jwtHeader, jwtPayload); var tokenHandler = new JwtSecurityTokenHandler(); var accessToken = tokenHandler.WriteToken(token); return(Ok(new { accessToken })); }
/// <summary> /// Initializes a new instance of the <see cref="AuthorizationDetails"/> class. /// </summary> public AuthorizationDetails(IReadOnlyList <IEdFiAuthorizationStrategy> authorizationStrategies, Claim relevantClaim, string validationRuleSetName) { AuthorizationStrategies = authorizationStrategies; RelevantClaim = relevantClaim; ValidationRuleSetName = validationRuleSetName; }
public static bool CanPut(this Claim claim) { var dictionary = GetPermissions(claim.Value); return(dictionary["PUT"]); }
private bool hasPermission(HttpActionContext actionContext) { try { string controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerType.Name; string actionName = actionContext.ActionDescriptor.ActionName; string userId = string.Empty; string userName = string.Empty; if (actionContext.Request.Properties.ContainsKey("MS_OwinContext")) { var context = (OwinContext)actionContext.Request.Properties["MS_OwinContext"]; var claimsIdentity = context.Authentication.User.Identity as ClaimsIdentity; if (claimsIdentity.Claims.ToList().Count > 0) { Claim claimsUserId = claimsIdentity.Claims.Where(s => s.Type == ClaimTypes.PrimarySid).FirstOrDefault(); Claim claimsUserName = claimsIdentity.Claims.Where(s => s.Type == ClaimTypes.Name).FirstOrDefault(); userId = claimsUserId != null ? claimsUserId.Value : string.Empty; userName = claimsUserName != null ? claimsUserName.Value : string.Empty; } var usersService = WebApiInstaller.Resolve <IUsersService>(); var roleInPagesService = WebApiInstaller.Resolve <IRoleInPagesService>(); var controllerInActionService = WebApiInstaller.Resolve <IControllerActionsService>(); if (string.IsNullOrEmpty(userId)) { return(false); } UsersModel user = usersService.GetAsync(int.Parse(userId)).Result; if (user == null) { return(false); } if (user.Roles.Count < 1) { return(false); } var controllerInActions = controllerInActionService.GetControllerActionsByControllerAndActionAsync(controllerName, actionName).Result; if (controllerInActions == null) { return(false); } List <RoleInPagesModel> roleInPageList = new List <RoleInPagesModel>(); foreach (RolesModel role in user.Roles) { var result = roleInPagesService.GetByRoleIdAsync(role.Id).Result; if (result != null) { roleInPageList.AddRange(result); } } foreach (RoleInPagesModel model in roleInPageList.Distinct()) { switch (controllerInActions.OperationType) { case OperationType.Create: if (model.Create) { return(true); } break; case OperationType.Read: if (model.Read) { return(true); } break; case OperationType.Update: if (model.Update) { return(true); } break; case OperationType.Delete: if (model.Delete) { return(true); } break; case OperationType.Operation: if (model.Create && model.Read && model.Update && model.Delete) { return(true); } break; default: break; } } // var user = usersService.GetAsync(int.Parse(userId)).Result; //var roleList = user.Roles.Where( // u => u.Pages.Where( // p => p.ControllerActions.Where( // c => c.Controller == controllerName && c.Action == actionName).Count() > 0).Count() > 0).ToList(); //if (roleList.Count > 0) // return true; //else // return false; } return(false); } catch (Exception ex) { throw ex; } }
/// <summary> /// Validate the incoming Auth Header as a token sent from the Bot Framework Emulator. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="channelProvider">The channelService value that distinguishes public Azure from US Government Azure.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <param name="authConfig">The authentication configuration.</param> /// <returns> /// A valid ClaimsIdentity. /// </returns> /// <remarks> /// A token issued by the Bot Framework will FAIL this check. Only Emulator tokens will pass. /// </remarks> #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateEmulatorToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } var openIdMetadataUrl = (channelProvider != null && channelProvider.IsGovernment()) ? GovernmentAuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl : AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl; var tokenExtractor = new JwtTokenExtractor( httpClient, ToBotFromEmulatorTokenValidationParameters, openIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false); if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException("Invalid Identity"); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException("Token Not Authenticated"); } // Now check that the AppID in the claimset matches // what we're looking for. Note that in a multi-tenant bot, this value // comes from developer code that may be reaching out to a service, hence the // Async validation. Claim versionClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.VersionClaim); if (versionClaim == null) { throw new UnauthorizedAccessException("'ver' claim is required on Emulator Tokens."); } string tokenVersion = versionClaim.Value; string appID = string.Empty; // The Emulator, depending on Version, sends the AppId via either the // appid claim (Version 1) or the Authorized Party claim (Version 2). if (string.IsNullOrWhiteSpace(tokenVersion) || tokenVersion == "1.0") { // either no Version or a version of "1.0" means we should look for // the claim in the "appid" claim. Claim appIdClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AppIdClaim); if (appIdClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'appid' claim is required on Emulator Token version '1.0'."); } appID = appIdClaim.Value; } else if (tokenVersion == "2.0") { // Emulator, "2.0" puts the AppId in the "azp" claim. Claim appZClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AuthorizedParty); if (appZClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'azp' claim is required on Emulator Token version '2.0'."); } appID = appZClaim.Value; } else { // Unknown Version. Not Authorized. throw new UnauthorizedAccessException($"Unknown Emulator Token version '{tokenVersion}'."); } if (!await credentials.IsValidAppIdAsync(appID).ConfigureAwait(false)) { throw new UnauthorizedAccessException($"Invalid AppId passed on token: {appID}"); } return(identity); }
public static bool CanDelete(this Claim claim) { var dictionary = GetPermissions(claim.Value); return(dictionary["DELETE"]); }
public async Task AddClaimFromUser(int projectId, int? characterGroupId, int? characterId, string claimText, IReadOnlyDictionary<int, string?> fields) { var source = await ProjectRepository.GetClaimSource(projectId, characterGroupId, characterId); source.EnsureCanAddClaim(CurrentUserId); var responsibleMaster = source.GetResponsibleMasters().FirstOrDefault() //if we failed to calculate responsible master, assign owner as responsible master ?? source.Project.ProjectAcls.Where(w => w.IsOwner).FirstOrDefault()?.User //if we found no owner, assign random master ?? source.Project.ProjectAcls.First().User; var claim = new Claim() { CharacterGroupId = characterGroupId, CharacterId = characterId, ProjectId = projectId, PlayerUserId = CurrentUserId, PlayerAcceptedDate = Now, CreateDate = Now, ClaimStatus = Claim.Status.AddedByUser, ResponsibleMasterUserId = responsibleMaster.UserId, ResponsibleMasterUser = responsibleMaster, LastUpdateDateTime = Now, CommentDiscussion = new CommentDiscussion() { CommentDiscussionId = -1, ProjectId = projectId }, }; if (!string.IsNullOrWhiteSpace(claimText)) { claim.CommentDiscussion.Comments.Add(new Comment { CommentDiscussionId = -1, AuthorUserId = CurrentUserId, CommentText = new CommentText { Text = new MarkdownString(claimText) }, CreatedAt = Now, IsCommentByPlayer = true, IsVisibleToPlayer = true, ProjectId = projectId, LastEditTime = Now, ExtraAction = CommentExtraAction.NewClaim, }); } _ = UnitOfWork.GetDbSet<Claim>().Add(claim); var updatedFields = FieldSaveHelper.SaveCharacterFields(CurrentUserId, claim, fields, FieldDefaultValueGenerator); var claimEmail = await CreateClaimEmail<NewClaimEmail>(claim, claimText ?? "", s => s.ClaimStatusChange, CommentExtraAction.NewClaim); claimEmail.UpdatedFields = updatedFields; await UnitOfWork.SaveChangesAsync(); await EmailService.Email(claimEmail); if (claim.Project.Details.AutoAcceptClaims) { var userId = claim.ResponsibleMasterUserId ?? claim.Project.ProjectAcls.First().UserId; StartImpersonate(userId); //TODO[Localize] await ApproveByMaster(projectId, claim.ClaimId, "Ваша заявка была принята автоматически"); ResetImpersonation(); } }
protected override IdentityRoleClaim <string> CreateRoleClaim(ApplicationRole role, Claim claim) => new IdentityRoleClaim <string> { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value, };
public async Task<int> MoveToSecondRole(int projectId, int claimId, int characterId) { var oldClaim = (await ClaimsRepository.GetClaim(projectId, claimId)).RequestAccess(CurrentUserId); //TODO Specific right oldClaim.EnsureStatus(Claim.Status.CheckedIn); Debug.Assert(oldClaim.Character != null, "oldClaim.Character != null"); oldClaim.Character.InGame = false; MarkChanged(oldClaim.Character); var source = await CharactersRepository.GetCharacterAsync(projectId, characterId); MarkChanged(source); // TODO improve valitdation here //source.EnsureCanMoveClaim(oldClaim); var responsibleMaster = source.GetResponsibleMasters().FirstOrDefault(); var claim = new Claim() { CharacterGroupId = null, CharacterId = characterId, ProjectId = projectId, PlayerUserId = oldClaim.PlayerUserId, PlayerAcceptedDate = Now, CreateDate = Now, ClaimStatus = Claim.Status.Approved, CurrentFee = 0, ResponsibleMasterUserId = responsibleMaster?.UserId, ResponsibleMasterUser = responsibleMaster, LastUpdateDateTime = Now, MasterAcceptedDate = Now, CommentDiscussion = new CommentDiscussion() { CommentDiscussionId = -1, ProjectId = projectId }, }; claim.CommentDiscussion.Comments.Add(new Comment { CommentDiscussionId = -1, AuthorUserId = CurrentUserId, CommentText = new CommentText { Text = new MarkdownString(".") }, CreatedAt = Now, IsCommentByPlayer = false, IsVisibleToPlayer = true, ProjectId = projectId, LastEditTime = Now, ExtraAction = CommentExtraAction.SecondRole, }); oldClaim.ClaimStatus = Claim.Status.Approved; source.ApprovedClaim = claim; _ = AddCommentImpl(oldClaim, null, ".", true, CommentExtraAction.OutOfGame); _ = UnitOfWork.GetDbSet<Claim>().Add(claim); // ReSharper disable once UnusedVariable TODO decide if we should send email if FieldDefaultValueGenerator changes something var updatedFields = FieldSaveHelper.SaveCharacterFields(CurrentUserId, claim, new Dictionary<int, string?>(), FieldDefaultValueGenerator); await UnitOfWork.SaveChangesAsync(); var claimEmail = await CreateClaimEmail<SecondRoleEmail>(claim, "", s => s.ClaimStatusChange, CommentExtraAction.NewClaim); await EmailService.Email(claimEmail); return claim.ClaimId; }
private static Claim GetIssuedClaim(Claim issuedClaim) { return(null); }
public SerializableClaim(Claim claim) { this.Type = claim.Type; this.Value = claim.Value; }
protected override Microsoft.IdentityModel.Claims.IClaimsIdentity GetOutputClaimsIdentity(Microsoft.IdentityModel.Claims.IClaimsPrincipal principal, Microsoft.IdentityModel.Protocols.WSTrust.RequestSecurityToken request, Scope scope) { if (null == principal) { throw new InvalidRequestException("The caller's principal is null."); } // Get the incoming IClaimsIdentity from IPrincipal IClaimsIdentity callerIdentity = (IClaimsIdentity)principal.Identity; // Create the output IClaimsIdentity IClaimsIdentity outputIdentity = new ClaimsIdentity(); // Create a name claim from the incoming identity. Claim nameClaim = new Claim(ClaimTypes.Name, callerIdentity.Name); // Create an 'Age' claim with a value of 25. In a real scenario, this may likely be looked up from a database. Claim ageClaim = new Claim("http://WindowsIdentityFoundationSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer); // Add the name outputIdentity.Claims.Add(nameClaim); outputIdentity.Claims.Add(ageClaim); return outputIdentity; }