public static Expression UnionEnumerableExpressions(IEnumerable<Expression> expressions) { var count = expressions.Count(); if (count == 1) return expressions.FirstOrDefault(); else if(count >= 2) { var expressionGroups = expressions.GroupBy(x => x.Type); if( expressionGroups.Count() != 1 ) throw new Exception("All expressions must be of the same type"); var elementType = ReduceExpressionGeneration.GetTypeOfEnumerable( expressionGroups.First().Key ); var unionInfos = typeof(Enumerable).GetMethods().Where(x => x.Name == "Union"); var unionInfo = unionInfos.FirstOrDefault(); var mi = unionInfo.MakeGenericMethod(elementType); var first = expressions.FirstOrDefault(); var result = UnionEnumerableExpressions(expressions.Skip(1)); return Expression.Call ( method: mi, arg0: first, arg1: result ); } else { return null; } }
public TransactionDetailsViewItem(Model.Transaction transaction, IEnumerable<Model.TransactionItem> transactionItems, IEnumerable<Model.TransactionIgnoredItem> transactionIgnoredItems, IEnumerable<Model.License> domainlessLicenseQuery, IEnumerable<Model.License> customerapplessLicenseQuery) : base(transaction) { PurchaserEmail = transaction.PurchaserEmail; PurchaserName = (transactionItems.Any(l => l.License != null)) ? transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName; OwnerName = (transactionItems.Any(l => l.License != null)) ? transactionItems.FirstOrDefault().License.OwningCustomer.Name : "None"; SKUSummary = (from x in transactionItems select x.Sku).ToSummary(x => x.SkuCode, 99, ", "); IgnoredSummary = (from x in transactionIgnoredItems select x.Description).ToSummary(x => x, 99, ", "); StatusName = transaction.Status.GetDescription<Model.TransactionStatus>(); DomainlessLicenses = (from x in domainlessLicenseQuery select x.ObjectId).ToList(); CustomerapplessLicenses = (from x in customerapplessLicenseQuery select x.ObjectId).ToList(); }
private string GetName(IEnumerable<IRunElement> elements) { List<string> clues = new List<string>(); var host = elements.FirstOrDefault(e => e is BaseHostElement); if (host != null) { clues.Add(host.Name); } var trace = elements.FirstOrDefault(e => e is TraceElement); if (trace != null) { clues.Add(trace.Name); } var name = string.Join(" ", clues); if (string.IsNullOrEmpty(name)) { name = "Unknown"; } return name; }
private IFubuFile findMatch(IEnumerable<IFubuFile> files, string search) { var exactMatch = files.FirstOrDefault(x => x.RelativePath == search); if (exactMatch != null) return exactMatch; return files.FirstOrDefault(x => x.RelativePath.EndsWith(search)); }
public GameInfoViewModel MapGameInfo(GameDb game, IEnumerable<TeamDb> teams, Dictionary<string, string> users) { var result = new GameInfoViewModel(); var homeTeam = teams.FirstOrDefault(x => x.EntityId == game.HomeTeam.Id); if (homeTeam != null) { result.HomeTeamName = homeTeam.Name; result.HomeTeamMediaId = homeTeam.MediaId; result.HomeTeamScore = game.HomeTeam.Score; if (!string.IsNullOrEmpty(game.HomeTeam.BestMemberId)) result.HomeTeamBestPlayer = users[game.HomeTeam.BestMemberId]; result.HomeTeamScores = game .HomeTeam.Members .Where(x => x.Help != 0 || x.Score != 0) .Select(x => MapGameInfoMember(x, users)); } var guestTeam = teams.FirstOrDefault(x => x.EntityId == game.GuestTeam.Id); if (guestTeam != null) { result.GuestTeamName = guestTeam.Name; result.GuestTeamMediaId = guestTeam.MediaId; result.GuestTeamScore = game.GuestTeam.Score; if (!string.IsNullOrEmpty(game.GuestTeam.BestMemberId)) result.GuestTeamBestPlayer = users[game.GuestTeam.BestMemberId]; result.GuestTeamScores = game .GuestTeam.Members .Where(x => x.Help != 0 || x.Score != 0) .Select(x => MapGameInfoMember(x, users)); } return result; }
/// <summary> /// Constructor /// </summary> /// <param name="Profilers">The profilers.</param> public Manager(IEnumerable<IProfiler> Profilers) { Contract.Requires<ArgumentNullException>(Profilers != null, "Profilers"); Profiler = Profilers.FirstOrDefault(x => !x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase)); if (Profiler == null) Profiler = Profilers.FirstOrDefault(x => x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase)); }
private string GetValueSomewhereInThePage(HtmlNode document, string[] names, IEnumerable<HtmlNode> metaTags) { string result = null; var possibleNames = names.SelectMany(n => new[] { n, "og:" + n }); var metaField = metaTags.FirstOrDefault(m => m.HasAttribute("property") && possibleNames.Contains(m.GetAttributeValue("property"))); if (metaField == null) { metaField = metaTags.FirstOrDefault(m => m.HasAttribute("name") && possibleNames.Contains(m.GetAttributeValue("name"))); } if (metaField != null) { result = metaField.GetAttributeValue("content"); } if (String.IsNullOrWhiteSpace(result)) { foreach (var name in possibleNames) { var hiddenField = document.FindHiddenField(name); if (hiddenField != null) { result = hiddenField.GetAttributeValue("value"); break; } } } return result; }
public ActionResult CreateStaff(IEnumerable<StaffView> staffs) { //產生加密誤密碼字串 String sPwd = oDB.EncryptString(staffs.FirstOrDefault().DecryptionPassword); try { if (ModelState.IsValid) { var staff = new Staff { Account = staffs.FirstOrDefault().Account, Name = staffs.FirstOrDefault().Name, Password = sPwd, DecryptionPassword = staffs.FirstOrDefault().DecryptionPassword, Role = staffs.FirstOrDefault().Role }; if (TryUpdateModel(staff)) { db.Staff.Add(staff); db.SaveChanges(); } } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { }; return Json(null); }
private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, string nameToSearch, IMappingOptions mappingOptions) { MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch)); if (pi != null) return pi; MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch)); if (mi != null) return mi; pi = modelProperties.FirstOrDefault(prop => NameMatches(mappingOptions.SourceMemberNameTransformer(prop.Name), nameToSearch)); if (pi != null) return pi; mi = getMethods.FirstOrDefault(m => NameMatches(mappingOptions.SourceMemberNameTransformer(m.Name), nameToSearch)); if (mi != null) return mi; pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch))); if (pi != null) return pi; pi = getMethods.FirstOrDefault(m => NameMatches(m.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch))); if (pi != null) return pi; return null; }
private static void ReplaceColor( BaseBrush in_Brush, IEnumerable<ColorPair> in_Colors ) { if( (in_Brush == null) || (in_Colors == null) ) return; if( in_Colors.Count( ) == 0 ) return; if( in_Brush is NGraphics.Models.Brushes.GradientBrush ) { GradientBrush typedBrush = in_Brush as GradientBrush; foreach( GradientStop stop in typedBrush.Stops ) { ColorPair pair = in_Colors.FirstOrDefault(x => (stop.Color.Red == x.OldColor.R) && (stop.Color.Green == x.OldColor.G) && (stop.Color.Blue == x.OldColor.B) && (stop.Color.Alpha == x.OldColor.A)); if( pair != null ) stop.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A); } } else if( in_Brush is NGraphics.Models.Brushes.SolidBrush ) { SolidBrush typedBrush = in_Brush as SolidBrush; ColorPair pair = in_Colors.FirstOrDefault(x => (typedBrush.Color.Red == x.OldColor.R) && (typedBrush.Color.Green == x.OldColor.G) && (typedBrush.Color.Blue == x.OldColor.B) && (typedBrush.Color.Alpha == x.OldColor.A)); if( pair != null ) typedBrush.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A); } }
public IPagedList<OrderQueryModel> Query(IEnumerable<ExtendedQueryParameter> parameters, ICommerceDatabase db, int pageIndex, int pageSize) { if (pageIndex <= 1) pageIndex = 1; int num = 10; var numPara = parameters.FirstOrDefault(o => o.Name == "Num"); if (numPara != null && numPara.Value != null && !string.IsNullOrEmpty(numPara.Value.ToString())) num = Convert.ToInt32(numPara.Value); decimal totalPrice = 100.0m; var totalPara = parameters.FirstOrDefault(o => o.Name == "TotalPrice"); if (totalPara != null && totalPara.Value != null && !string.IsNullOrEmpty(totalPara.Value.ToString())) totalPrice = Convert.ToDecimal(totalPara.Value); var customerQuery = db.GetRepository<Customer>().Query(); IQueryable<OrderQueryModel> query = db.GetRepository<Order>().Query() .Join(customerQuery, order => order.CustomerId, customer => customer.Id, (order, customer) => new { Order = order, Customer = customer }) .Select(o => new OrderQueryModel() { Customer = o.Customer, Order = o.Order }) .Where(o => o.Order.Total > totalPrice) .OrderByDescending(o => o.Order.Total); var total = query.Count(); var data = query.Skip(0).Take(num).ToArray(); return new PagedList<OrderQueryModel>(data, pageIndex, pageSize, total); }
public static ClaimsPrincipal FromClaims(IEnumerable<Claim> claims, bool allowMissing = false) { var amr = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationMethod); var sub = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject); var idp = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.IdentityProvider); var authTime = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationTime); var id = new ClaimsIdentity(Constants.BuiltInIdentityProvider); if (sub != null) { id.AddClaim(sub); } else { if (allowMissing == false) { throw new InvalidOperationException("sub claim is missing"); } } if (amr != null) { id.AddClaim(amr); } else { if (allowMissing == false) { throw new InvalidOperationException("amr claim is missing"); } } if (idp != null) { id.AddClaim(idp); } else { if (allowMissing == false) { throw new InvalidOperationException("idp claim is missing"); } } if (authTime != null) { id.AddClaim(authTime); } else { if (allowMissing == false) { throw new InvalidOperationException("auth_time claim is missing"); } } return new ClaimsPrincipal(id); }
private static ConnectionStringSettings CreateConnectionString(IEnumerable<Claim> claims) { string dblogin = claims.FirstOrDefault(c => c.Type == "dblogin").Value; string dbpass = claims.FirstOrDefault(c => c.Type == "dbpass").Value; string dbname = claims.FirstOrDefault(c => c.Type == "dbname").Value; return Database.CreateConnectionString("System.Data.SqlClient", @"LUNALAPPY\SQLEXPRESS", Cryptography.Decrypt(dbname), Cryptography.Decrypt(dblogin), Cryptography.Decrypt(dbpass)); }
public override void ModifyMetadata(EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata, IEnumerable<Attribute> attributes) { base.ModifyMetadata(metadata, attributes); var groupKeyAttribute = attributes.FirstOrDefault(a => typeof (TagsGroupKeyAttribute) == a.GetType()) as TagsGroupKeyAttribute; var cultureSpecificAttribute = attributes.FirstOrDefault(a => typeof(CultureSpecificAttribute) == a.GetType()) as CultureSpecificAttribute; EditorConfiguration["GroupKey"] = Helpers.TagsHelper.GetGroupKeyFromAttributes(groupKeyAttribute, cultureSpecificAttribute); }
private static void WriteEntry(QueueEntry e, IEnumerable<Argument> arguments) { bool printProjectString = arguments.FirstOrDefault(a => a.Type == ArgumentType.PrintProjectString) != null ? true : false; bool showAll = arguments.FirstOrDefault(a => a.Type == ArgumentType.ShowAll) != null ? true : false; Console.Write(" Index {0}: {1}", e.Index, e.EntryStatusLiteral); if (e.SpeedFactor == 0) { Console.WriteLine(); } else { Console.WriteLine(" {0} X min speed", e.SpeedFactor); } Console.WriteLine(" server: {0}:{1}; project: {2}", e.ServerIP, e.ServerPort, e.ProjectID); string misc4aEndian = e.Misc4aBigEndian ? "be" : "le"; Console.WriteLine(" Folding: run {0}, clone {1}, generation {2}; benchmark {3}; misc: {4}, {5}, {6} ({7})", e.ProjectRun, e.ProjectClone, e.ProjectGen, e.Benchmark, e.Misc1a, e.Misc1b, e.Misc4a, misc4aEndian); if (printProjectString) { Console.WriteLine(" Project: {0} (Run {1}, Clone {2}, Gen {3})", e.ProjectID, e.ProjectRun, e.ProjectClone, e.ProjectGen); } Console.WriteLine(" issue: {0:ddd MMM dd HH:mm:ss yyyy}; begin: {1:ddd MMM dd HH:mm:ss yyyy}", e.ProjectIssuedLocal, e.BeginTimeLocal); Console.Write(" "); if (e.EntryStatus == 3 || e.EntryStatus == 7) { Console.Write("end: {0:ddd MMM dd HH:mm:ss yyyy}; ", e.EndTimeLocal); } TimeSpan preferred = e.DueTimeLocal.Subtract(e.BeginTimeLocal); Console.WriteLine("due: {0:ddd MMM dd HH:mm:ss yyyy} ({1} days)", e.DueTimeLocal, Math.Ceiling(preferred.TotalDays)); Console.WriteLine(" core URL: {0}", e.CoreDownloadUrl); Console.Write(" core number: 0x{0}", e.CoreNumber); Console.WriteLine("; core name: {0}", e.CoreName); Console.WriteLine(" CPU: {0},{1} {2}; OS: {3},{4} {5}", e.CpuType, e.CpuSpecies, e.CpuString, e.OsType, e.OsSpecies, e.OsString); Console.WriteLine(" smp cores: {0}; cores to use: {1}", e.NumberOfSmpCores, e.UseCores); Console.WriteLine(" tag: {0}", e.WorkUnitTag); if (e.Passkey.Length != 0 && showAll) { Console.WriteLine(" passkey: {0}", e.Passkey); } Console.WriteLine(" flops: {0} ({1:0.000000} megaflops)", e.Flops, e.MegaFlops); Console.WriteLine(" memory: {0} MB", e.Memory); Console.WriteLine(" client type: {0} {1}", e.RequiredClientType, e.RequiredClientTypeLiteral); string assignmentInfoEndian = e.AssignmentInfoBigEndian ? "be" : "le"; if (e.AssignmentInfoPresent) { Console.WriteLine(" assignment info ({0}): {1:ddd MMM dd HH:mm:ss yyyy}; {2}", assignmentInfoEndian, e.AssignmentTimeStampLocal, e.AssignmentInfoChecksum); } Console.Write(" CS: {0}; ", e.CollectionServerIP); if (e.NumberOfUploadFailures != 0) { Console.Write("upload failures: {0}; ", e.NumberOfUploadFailures); } Console.WriteLine("P limit: {0}", e.PacketSizeLimit); Console.WriteLine(" user: {0}; team: {1}; ID: {2}; mach ID: {3}", e.FoldingID, e.Team, e.ID, e.MachineID); Console.WriteLine(" work/wudata_{0:00}.dat file size: {1}; WU type: {2}", e.Index, e.WuDataFileSize, e.WorkUnitType); }
public DotvvmCompilationException(string message, Exception innerException, IEnumerable<TokenBase> tokens) : base(message, innerException) { if (tokens != null) { if (!(tokens is IList<TokenBase>)) tokens = tokens.ToArray(); this.Tokens = tokens; LineNumber = tokens.FirstOrDefault()?.LineNumber; ColumnNumber = tokens.FirstOrDefault()?.ColumnNumber; } }
private static string GetArgumentValue(IEnumerable<string> args, string prefix) { if (string.IsNullOrEmpty(prefix)) { return args.FirstOrDefault(x => !x.StartsWith("/")); } var arg = args.FirstOrDefault(x => x.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase)); return arg == null ? null : arg.Substring(prefix.Length).Replace("\"", ""); }
public static SettingValue GetDefaultSettingValue(IEnumerable<SettingValue> listWithItems) { var item = listWithItems.FirstOrDefault(x => x.Default); if (item == null) { item = listWithItems.FirstOrDefault(); } return item; }
public void CharacterOnEquippedItem(IEnumerable<InventoryItemBase> items, uint amount, bool cameFromCollection) { if (onEquippedItemEvents.Count > 0) { var item = items.FirstOrDefault(); RunEvents(onEquippedItemEvents, new plyEventArg("item", items.FirstOrDefault()), new plyEventArg("itemID", item != null ? (int)item.ID : -1), new plyEventArg("amount", (int)amount)); } }
public static Haeufigkeit GetDefaultHaeufigkeit(IEnumerable<Haeufigkeit> listWithItems) { var item = listWithItems.FirstOrDefault(x => x.Default); if (item == null) { item = listWithItems.FirstOrDefault(); } return item; }
/// <summary> /// Get hotel image by with and height /// </summary> /// <param name="images"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public string GetHotelImage(IEnumerable<Image> images, int width, int height) { var image = images.FirstOrDefault(i => i.Width >= width && i.Height >= width); if (image != null) { return GetImagePath(image); } else { return GetImagePath(images.FirstOrDefault()); } }
public TransactionIndexViewItem(Model.Transaction transaction, IEnumerable<Model.TransactionItem> transactionItems) : base(transaction) { PurchaserName = (transactionItems.FirstOrDefault().License != null) ? transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName; SKUSummary = transactionItems.ToSummary(x => (x.Sku != null) ? x.Sku.SkuCode : "None", 3, ", "); StatusName = transaction.Status.GetDescription<TransactionStatus>(); IsWaitingForClaim = transaction.IsWaitingForClaim; }
/// <summary> /// Find the best match constructor for given set of arguments /// </summary> /// <param name="constructors">List of constructors</param> /// <param name="constructorArguments">Set of constructor arguments</param> /// <returns></returns> public static ConstructorInfo GetBestMatch(IEnumerable<ConstructorInfo> constructors, object[] constructorArguments) { if (constructorArguments == null || constructorArguments.Length == 0) return constructors.FirstOrDefault(ci => ci.GetParameters().Length == 0); return constructors .FirstOrDefault(ci => ci.GetParameters().Count() == constructorArguments.Length && !ci.GetParameters() .Where((t, i) => t.ParameterType != constructorArguments[i].GetType()) .Any()); }
private static ValidationResult GetValidationResult(IEnumerable<ValidationResult> self, string propertyName, object type) { ValidationResult result; if (type == null) { result = self.FirstOrDefault(v => v.PropertyName == propertyName && v.Type == null); } else { result = self.FirstOrDefault(v => v.PropertyName == propertyName && v.Type != null && v.Type.Equals(type)); } return result; }
public override void ModifyMetadata(EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata, IEnumerable<Attribute> attributes) { base.ModifyMetadata(metadata, attributes); var groupKeyAttribute = attributes.FirstOrDefault(a => typeof (TagsGroupKeyAttribute) == a.GetType()) as TagsGroupKeyAttribute; var cultureSpecificAttribute = attributes.FirstOrDefault(a => typeof(CultureSpecificAttribute) == a.GetType()) as CultureSpecificAttribute; var getaAttribute = attributes.FirstOrDefault(a => typeof(GetaTagsAttribute) == a.GetType()) as GetaTagsAttribute; metadata.EditorConfiguration["GroupKey"] = Helpers.TagsHelper.GetGroupKeyFromAttributes(groupKeyAttribute, cultureSpecificAttribute); metadata.EditorConfiguration["allowSpaces"] = getaAttribute?.AllowSpaces ?? false; metadata.EditorConfiguration["allowDuplicates"] = getaAttribute?.AllowDuplicates ?? false; metadata.EditorConfiguration["readOnly"] = getaAttribute?.ReadOnly ?? false; metadata.EditorConfiguration["caseSensitive"] = getaAttribute?.CaseSensitive ?? true; }
//public Shutter(string name, int type, int iseId, string address, bool isVisible) : base(name, type, iseId, address, isVisible) //{ //} public override void SetState(IEnumerable<Datapoint> datapoints) { base.SetState(datapoints); var levelPoint = datapoints.FirstOrDefault(d => d.Type == DatapointType.LEVEL); if (levelPoint != null) Level = float.Parse(levelPoint.Value, CultureInfo.InvariantCulture.NumberFormat); var stopPoint = datapoints.FirstOrDefault(d => d.Type == DatapointType.STOP); if (stopPoint != null) { StopIseId = stopPoint.IseId; } }
protected override Card FindBestCardToPlay(IEnumerable<Card> cards) { if (this.RealThis.Phase == PhaseEnum.Action) { // Sort the cards by cost (potion = 2.5 * coin) // Also, use a cost of 7 for Prize cards (since they have no cost normally) cards = cards.Where(card => this.ShouldPlay(card)).OrderByDescending( card => (card.Category & Category.Prize) == Category.Prize ? 7 : (card.BaseCost.Coin.Value + 2.5 * card.BaseCost.Potion.Value)); // Always play King's Court if there is one (?) Card kc = cards.FirstOrDefault(card => card.CardType == Cards.Prosperity.TypeClass.KingsCourt); if (kc != null) return kc; // Always play Throne Room if there is one (?) Card tr = cards.FirstOrDefault(card => card.CardType == Cards.Base.TypeClass.ThroneRoom); if (tr != null) return tr; Card plusActions = cards.FirstOrDefault(card => card.Benefit.Actions > 0 && card.CardType != Cards.Intrigue.TypeClass.ShantyTown); if (plusActions != null) return plusActions; Card shantyTown = cards.FirstOrDefault(card => card.CardType == Cards.Intrigue.TypeClass.ShantyTown); if (shantyTown != null) return shantyTown; Turn previousTurn = null; if (this.RealThis._Game.TurnsTaken.Count > 1) previousTurn = this.RealThis._Game.TurnsTaken[this.RealThis._Game.TurnsTaken.Count - 2]; // Play Smugglers if the player to our right gained a card costing at least 5 (that we can gain as well) if (cards.Any(card => card.CardType == Cards.Seaside.TypeClass.Smugglers) && previousTurn != null && previousTurn.CardsGained.Any(card => _Game.ComputeCost(card).Potion == 0 && card.BaseCost.Coin >= 5 && this.RealThis._Game.Table.Supplies.ContainsKey(card) && this.RealThis._Game.Table.Supplies[card].CanGain())) return cards.First(card => card.CardType == Cards.Seaside.TypeClass.Smugglers); // Play an Ambassador card if there is one and we have at least 1 Curse in our hand Card ambassador = cards.FirstOrDefault(card => card.CardType == Cards.Seaside.TypeClass.Ambassador); if (ambassador != null) return ambassador; if (cards.Count() > 0) // Just play the most expensive one return cards.ElementAt(0); return null; } return base.FindBestCardToPlay(cards); }
public static void AddNodes(BinaryTreeNode<int> node, IEnumerable<int> nodes) { if (nodes.Any()) { var multiplied = node.Value * nodes.First(); var added = node.Value + nodes.First(); node.Left = new BinaryTreeNode<int>(added, nodes.FirstOrDefault()); node.Right = new BinaryTreeNode<int>(multiplied, nodes.FirstOrDefault()); nodes = nodes.Skip(1); AddNodes(node.Left, nodes); AddNodes(node.Right, nodes); } }
public static void Link( ButtonItem selectorButton, IEnumerable<Theme> themes, string selectedThemeName, IThemeSettingsContainer settingsContainer, Action<Theme, bool> themeSelected) { var themesExisted = themes.Any(); selectorButton.ForeColor = Color.Black; selectorButton.ImagePosition = eImagePosition.Left; selectorButton.Text = String.Empty; selectorButton.AutoExpandOnClick = false; if (themesExisted) { var currentTheme = themes.FirstOrDefault(t => t.Name.Equals(selectedThemeName) || String.IsNullOrEmpty(selectedThemeName)) ?? themes.FirstOrDefault(); if (currentTheme == null) return; selectorButton.Image = currentTheme.RibbonLogo; ((RibbonBar)selectorButton.ContainerControl).Text = String.Format("{0}", currentTheme.Name); if (selectorButton.Tag == null) { selectorButton.Tag = new ThemeButtonInfo(); selectorButton.Click += (button, e) => { ((ThemeButtonInfo)((ButtonItem)button).Tag).ClickHandler?.Invoke(); }; } ((ThemeButtonInfo)selectorButton.Tag).CurrentTheme = currentTheme; ((ThemeButtonInfo) selectorButton.Tag).ClickHandler = () => { using (var form = new FormThemeSelector()) { form.ApplyThemeForAllSlideTypes = settingsContainer.ApplyThemeForAllSlideTypes; form.LoadThemes(themes); form.Shown += (o, args) => { form.SetSelectedTheme(((ThemeButtonInfo)selectorButton.Tag).CurrentTheme.Name); }; if (form.ShowDialog() != DialogResult.OK) return; var selectedTheme = form.SelectedTheme; if (selectedTheme == null) return; selectorButton.Image = selectedTheme.RibbonLogo; ((RibbonBar)selectorButton.ContainerControl).Text = String.Format("{0}", selectedTheme.Name); ((ThemeButtonInfo)selectorButton.Tag).CurrentTheme = selectedTheme; themeSelected(selectedTheme, form.ApplyThemeForAllSlideTypes); } }; } else selectorButton.Image = Resources.OutputDisabled; }
public Push(String alert = null, IEnumerable<BaseAlert> deviceAlerts = null) { if(!string.IsNullOrEmpty(alert)) Notification.DefaultAlert = alert; if (deviceAlerts != null && deviceAlerts.Count() > 0) { Notification.AndroidAlert = deviceAlerts.FirstOrDefault(x => x is AndroidAlert) as AndroidAlert; Notification.IosAlert = deviceAlerts.FirstOrDefault(x => x is IosAlert) as IosAlert; Notification.WindowsAlert = deviceAlerts.FirstOrDefault(x => x is WindowsAlert) as WindowsAlert; Notification.WindowsPhoneAlert = deviceAlerts.FirstOrDefault(x => x is WindowsPhoneAlert) as WindowsPhoneAlert; Notification.BlackberryAlert = deviceAlerts.FirstOrDefault(x => x is BlackberryAlert) as BlackberryAlert; } }
/// <summary> /// Adds application-level rate limiting rules if they have not been added already. /// </summary> /// <param name="rules">The list of rules.</param> /// <param name="platformId">The platform ID of the response that contained the rate limit definitions. The request count will automatically be incremented for this platform.</param> /// <param name="currentCounts">The current request counts for each rule. If unspecified, 1 request for each rule will be assumed.</param> public virtual void TrySetRules(IEnumerable <RateLimitRule> rules, string platformId = null, IEnumerable <RateLimitRule> currentCounts = null) { var now = DateTime.UtcNow; foreach (var rule in rules) { appTrackers.AddOrUpdate(rule.Duration, (duration) => { var newTracker = new RateLimitTracker { Rule = rule }; if (platformId != null) { var currentCount = currentCounts?.FirstOrDefault(c => c.Duration == duration)?.Limit ?? 1; RequestCount requestCount = newTracker.RequestCounts.GetOrAdd(platformId, (pid) => new RequestCount()); // Wait a little longer than the reset time in case there's a bit of lag when talking to the server requestCount.ResetTime = now + TimeSpan.FromSeconds(duration + 0.75); requestCount.Count = currentCount; } return(newTracker); }, identityUpdateFactory); } }
public async Task <List <Models.Driver> > FilterMyDeparmentUsersAsync(string department, IEnumerable <Models.Driver> users) { List <Models.Driver> result = new List <Models.Driver>(); try { if (!string.IsNullOrEmpty(department)) { var coworkers = await GraphClient.Instance.Beta.Users.Request() .Select("userPrincipalName") // Escape url characters .Filter($"Department eq '{WebUtility.UrlEncode(department)}'") .GetAsync(); if (coworkers != null && coworkers.Any()) { foreach (var coworker in coworkers) { if (!string.IsNullOrEmpty(coworker.UserPrincipalName)) { var driver = users?.FirstOrDefault(u => coworker.UserPrincipalName.Equals(u.Name)); if (driver != null) { result.Add(driver); } } } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Error getting My Organization Users {e}"); } return(result); }
public virtual async Task <ResponseData> AddData([FromBody] Request model) { var stop = Stopwatch.StartNew(); try { if (model == null) { return(this.GetResponse(Responses.ComeNullModal)); // TODO change } var type = GetType(model.name); if (type == null) { return(this.GetResponse(Responses.ServiceNotFound)); //TODO change } var result = model.data.SerializeMe(type); var service = GetService(model.name); //_service[model.name]; var errlist = result.CheckJwt(User); if (errlist.Count > 0) { return(this.GetResponse(errlist)); } var command = _commands?.FirstOrDefault(m => m.Name == model.name); if (command != null) { await command.Add(result, User); } service.GetType().GetMethod("Add").Invoke(service, new object[] { result, 152, "PostData" }); stop.Stop(); return(this.GetResponse(result)); } catch (Exception ext) { return(this.ExceptionResult(ext, stop, model)); } }
/// <summary> /// 预览结果 编辑器连线数据,但是build模式也会执行 /// 这里注意不要对BuildingCtx直接进行修改,修改需要在Build中进行 /// </summary> /// <param name="target"></param> /// <param name="nodeData"></param> /// <param name="incoming"></param> /// <param name="connectionsToOutput"></param> /// <param name="outputFunc"></param> public override void Prepare(BuildTarget target, NodeData nodeData, IEnumerable <PerformGraph.AssetGroups> incoming, IEnumerable <ConnectionData> connectionsToOutput, PerformGraph.Output outputFunc) { if (incoming == null) { return; } this.BuildingCtx = BDFrameworkAssetsEnv.BuildingCtx; Debug.Log("prepare:" + this.GetType().Name + "-" + DateTime.Now.ToLongTimeString()); // var outMap = new Dictionary <string, List <AssetReference> >(); switch ((FolderAssetBundleRule)this.SetAssetBundleNameRule) { case FolderAssetBundleRule.用该目录路径设置AB名: { outMap = SetABNameUseThisFolderName(incoming); } break; case FolderAssetBundleRule.用子目录路径设置AB名: { outMap = DoSetABNameUseSubfolderName(incoming); } break; } var output = connectionsToOutput?.FirstOrDefault(); if (output != null) { outputFunc(output, outMap); } }
private static PackageInfo CreatePackageInfo(IPackageSearchMetadata packageSearchMetadata, FeedType feedType, IEnumerable <VersionInfo>?versionInfos) { var versionInfo = versionInfos?.FirstOrDefault(v => v.Version == packageSearchMetadata.Identity.Version); DateTimeOffset?published = null; int? downloadCount = null; if (packageSearchMetadata.Published.HasValue && packageSearchMetadata.Published.Value.Year > 1900) { // Note nuget.org reports 1900 for unlisted packages. Pretty sure it's was published later ;) published = packageSearchMetadata.Published; } downloadCount = (int)(versionInfo?.DownloadCount ?? packageSearchMetadata.DownloadCount.GetValueOrDefault()); if (downloadCount == 0) { // Note nuget.org reports no correct download counts in for unlisted. downloadCount = null; } return(new PackageInfo(packageSearchMetadata.Identity) { Authors = packageSearchMetadata.Authors, Published = published, DownloadCount = downloadCount, IsRemotePackage = (feedType == FeedType.HttpV3 || feedType == FeedType.HttpV2), IsPrefixReserved = packageSearchMetadata.PrefixReserved, Description = packageSearchMetadata.Description, Tags = packageSearchMetadata.Tags, Summary = packageSearchMetadata.Summary, LicenseUrl = packageSearchMetadata.LicenseUrl?.ToString() ?? string.Empty, ProjectUrl = packageSearchMetadata.ProjectUrl?.ToString() ?? string.Empty, ReportAbuseUrl = packageSearchMetadata.ReportAbuseUrl?.ToString() ?? string.Empty, IconUrl = packageSearchMetadata.IconUrl?.ToString() ?? string.Empty }); }
/// <summary> /// Creates a new instance of <see cref="DataEntityDataReader{TEntity}"/> object. /// </summary> /// <param name="tableName">The name of the target table.</param> /// <param name="entities">The list of the data entity object to be used for manipulation.</param> /// <param name="connection">The actual <see cref="IDbConnection"/> object used.</param> /// <param name="transaction">The transaction object that is currently in used.</param> public DataEntityDataReader(string tableName, IEnumerable <TEntity> entities, IDbConnection connection, IDbTransaction transaction) { if (entities == null) { throw new NullReferenceException("The entities could not be null."); } // Fields this.tableName = tableName ?? ClassMappedNameCache.Get <TEntity>(); isClosed = false; isDisposed = false; position = -1; recordsAffected = -1; // Type var entityType = typeof(TEntity); EntityType = entityType == StaticType.Object ? (entities?.FirstOrDefault()?.GetType() ?? entityType) : entityType; isDictionaryStringObject = EntityType.IsDictionaryStringObject(); // DbSetting DbSetting = connection?.GetDbSetting(); // Properties Connection = connection; Transaction = transaction; Enumerator = entities.GetEnumerator(); Entities = entities; Properties = GetClassProperties().AsList(); Fields = GetFields(Entities?.FirstOrDefault() as IDictionary <string, object>).AsList(); fieldCount = isDictionaryStringObject ? Fields.Count : Properties.Count; }
public async void underlyingContractCB1_SelectionChanged(object sender, SelectionChangedEventArgs e) { var uc = underlyingContractCB1.SelectedItem?.ToString(); var uexchange = underlyingEX1.SelectedItem?.ToString(); if (uc != null) { var handler = MessageHandlerContainer.DefaultInstance.Get <MarketDataHandler>(); QuoteVMCollection1.Clear(); var mktDataVM = await handler.SubMarketDataAsync(uc); if (mktDataVM != null) { QuoteVMCollection1.Add(mktDataVM); } var contract = _subbedContracts?.FirstOrDefault(); if (contract != null) { var strategy = _otcOptionHandler.StrategyVMCollection.FirstOrDefault(s => s.Exchange == contract.Exchange && s.Contract == contract.Contract); var pricingContract = strategy.PricingContractParams.FirstOrDefault(); if (pricingContract != null && pricingContract.Exchange == uexchange && pricingContract.Contract == uc) { return; } if (pricingContract == null) { pricingContract = new PricingContractParamVM(); strategy.PricingContractParams.Add(pricingContract); } pricingContract.Exchange = uexchange; pricingContract.Contract = uc; _otcOptionHandler.UpdateStrategyPricingContracts(strategy, StrategyVM.Model.PM); } } }
public IActionResult DeleteAppointment(int id) { try { Profile profile = null; var identity = HttpContext.User.Identity as ClaimsIdentity; IEnumerable <Claim> claims = identity?.Claims; var profileClaim = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name); if (profileClaim != null && int.TryParse(profileClaim.Value, out var profileId)) { profile = profileService.GetProfileById(profileId); } appointmentService.DeleteAppointment(id, profile?.Id ?? 0); } catch (Exception e) { Console.WriteLine(e); throw; } return(Ok()); }
public async Task <string> SectionStatusAsync(Guid applicationId, int sequenceId, int sectionId, IEnumerable <ApplicationSequence> applicationSequences, OrganisationVerificationStatus organisationVerificationStatus) { var sectionNotRequired = await SectionNotRequired(applicationId, sequenceId, sectionId); if (sectionNotRequired) { return(TaskListSectionStatus.NotRequired); } if (sequenceId == RoatpWorkflowSequenceIds.YourOrganisation && sectionId == RoatpWorkflowSectionIds.YourOrganisation.WhosInControl) { return(await WhosInControlSectionStatus(applicationId, applicationSequences, organisationVerificationStatus)); } var sequence = applicationSequences?.FirstOrDefault(x => x.SequenceId == sequenceId); var section = sequence?.Sections?.FirstOrDefault(x => x.SectionId == sectionId); if (section == null) { return(string.Empty); } if (!await PreviousSectionCompleted(applicationId, sequence.SequenceId, sectionId, applicationSequences, organisationVerificationStatus)) { return(string.Empty); } var questionsCompleted = SectionCompletedQuestionsCount(section); var sectionText = GetSectionText(questionsCompleted, section, sequence.Sequential); return(sectionText); }
/// <summary> /// Add json file settings based on current environment and the specified /// environment inheritance layers. /// If environments param is null, only appsettings.json will be added. /// </summary> /// <param name="configBuilder">config builder</param> /// <param name="environments">array of defined environments</param> /// <returns>config builder</returns> private static IConfigurationBuilder AddJsonFiles( this IConfigurationBuilder configBuilder, IEnumerable <HostEnvironment> environments) { var currentEnvName = HostEnvironment.Environment; // Try to look the current environment up from the given environment list var env = environments?.FirstOrDefault(e => string.Equals(e.Name, currentEnvName, StringComparison.OrdinalIgnoreCase)); if (env == null) { // If the current environment cannot be found from the environments list, we fall back to // the .net core behavior by creating a temp environment using current environment's name. env = new HostEnvironment(currentEnvName); } // Find the layering hierarchy (sigle direction list from children to parent), then reverse it (parent to children). var layers = new List <HostEnvironment>(); while (env != null) { layers.Add(env); env = env.Parent; } layers.Reverse(); // Add json files based on parent to child chains. Note appsettings.json is always included first. configBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false); foreach (var environment in layers) { configBuilder.AddJsonFile($"appsettings.{environment.Name}.json", optional: true, reloadOnChange: false); } return(configBuilder); }
private void CreateSummary([NotNull] ExcelReportEngine engine, double healthIndex, IEnumerable <QualityAnalyzerResult> outcomes) { var p = engine.AddPage("Summary"); engine.AddHeader(p, "Assessment", "Evaluation"); engine.AddRow(p, "Threat Model Health Index", QualityAnalyzersManager.GetHealthIndexDescription(healthIndex)); var analyzers = QualityAnalyzersManager.QualityAnalyzers?.ToArray(); if (analyzers?.Any() ?? false) { foreach (var analyzer in analyzers) { var outcome = outcomes?.FirstOrDefault(x => x.Id == analyzer.GetExtensionId()); if (outcome != null) { engine.AddRow(p, analyzer.Label, outcome.Assessment.GetEnumLabel()); } } } }
/// <summary> /// Initializes a new instance of the UserIdentity class with preset claims /// </summary> /// <param name="claims">The claims of user</param> public UserIdentity(IEnumerable <Claim> claims) { this.BuildClaims(claims); this.ID = this.FindFirst(ClaimTypes.NameIdentifier)?.Value; this.SessionID = this.FindFirst(ClaimTypes.Sid)?.Value; this.AuthenticationType = this.FindFirst(ClaimTypes.AuthenticationMethod)?.Value; var userData = claims?.FirstOrDefault(claim => claim.Type.Equals(ClaimTypes.UserData))?.Value; if (!string.IsNullOrWhiteSpace(userData)) { try { var info = userData.ToExpandoObject(); this.Roles = info.Get <List <string> >("Roles")?.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); this.Privileges = info.Get <List <Privilege> >("Privileges"); } catch { } } this.BuildClaimsOfRolesAndPrivileges(); this.SetUser(); }
/// <summary> /// 从当前节点及其子节点中搜索指定名称节点。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="element"></param> /// <param name="name">节点限定名称。</param> /// <returns>找到的第一个限定名称等于<paramref name="name"/>的节点,若没有找到,则为null。</returns> public static XmlElement GetElement(this XmlElement element, string name, Search.Method method = Search.Method.BFS) { Func <XmlElement, IEnumerable <XmlElement> > explorer = (node) => { return(from XmlNode child in node.ChildNodes where child is XmlElement select child as XmlElement); }; Func <XmlElement, bool> goal = (node) => node.Name == name; IEnumerable <XmlElement> resEnum = null; switch (method) { case Search.Method.BFS: resEnum = Search.BFS(element, explorer, goal); break; case Search.Method.DFS: resEnum = Search.DFS(element, explorer, goal); break; } return(resEnum?.FirstOrDefault()); }
public QuantityWithUnitGuiEnvironment(IEnumerable <IUnit> fixedUnits, IEnumerable <IUnit> additionalUnits) { if (null != fixedUnits) { _fixedUnits = fixedUnits.ToArray(); } else { _fixedUnits = _emptyUnitList; } _additionalUnits = new ObservableCollection <IUnit>(additionalUnits); CreateUnitListSortedByShortcutLengthDescending(); _additionalUnits.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(EhAdditionalUnits_CollectionChanged); if (null != fixedUnits?.FirstOrDefault()) { DefaultUnit = new PrefixedUnit(SIPrefix.None, fixedUnits.FirstOrDefault()); } else if (0 < _additionalUnits.Count) { DefaultUnit = new PrefixedUnit(SIPrefix.None, _additionalUnits[0]); } }
public User getUserInformation() { User user = new User(); var identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity; if (identity != null) { IEnumerable <Claim> claims = identity.Claims; user.username = claims?.FirstOrDefault(x => x.Type.Equals("user_name", StringComparison.OrdinalIgnoreCase))?.Value; user.email = claims?.FirstOrDefault(x => x.Type.Equals("user_email", StringComparison.OrdinalIgnoreCase))?.Value; user.provider = claims?.FirstOrDefault(x => x.Type.Equals("user_provider", StringComparison.OrdinalIgnoreCase))?.Value; user.confirmed = Convert.ToBoolean(claims?.FirstOrDefault(x => x.Type.Equals("user_confirmed", StringComparison.OrdinalIgnoreCase))?.Value); user.blocked = Convert.ToBoolean(claims?.FirstOrDefault(x => x.Type.Equals("user_blocked", StringComparison.OrdinalIgnoreCase))?.Value); user.role = new Role() { name = claims?.FirstOrDefault(x => x.Type.Equals("user_role", StringComparison.OrdinalIgnoreCase))?.Value }; } return(user); }
/// <summary> /// Creates a SQL Statement for merge-all operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be merged.</param> /// <param name="qualifiers">The list of the qualifier <see cref="Field"/> objects.</param> /// <param name="batchSize">The batch size of the operation.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <param name="hints">The table hints to be used.</param> /// <returns>A sql statement for merge operation.</returns> public override string CreateMergeAll(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields, IEnumerable <Field> qualifiers = null, int batchSize = Constant.DefaultBatchOperationSize, DbField primaryField = null, DbField identityField = null, string hints = null) { // Ensure with guards GuardTableName(tableName); GuardHints(hints); GuardPrimary(primaryField); GuardIdentity(identityField); // Verify the fields if (fields?.Any() != true) { throw new NullReferenceException($"The list of fields cannot be null or empty."); } // Check the qualifiers if (qualifiers?.Any() == true) { // Check if the qualifiers are present in the given fields var unmatchesQualifiers = qualifiers.Where(field => fields.FirstOrDefault(f => string.Equals(field.Name, f.Name, StringComparison.OrdinalIgnoreCase)) == null); // Throw an error we found any unmatches if (unmatchesQualifiers?.Any() == true) { throw new InvalidQualifiersException($"The qualifiers '{unmatchesQualifiers.Select(field => field.Name).Join(", ")}' are not " + $"present at the given fields '{fields.Select(field => field.Name).Join(", ")}'."); } } else { if (primaryField != null) { // Make sure that primary is present in the list of fields before qualifying to become a qualifier var isPresent = fields?.FirstOrDefault(f => string.Equals(f.Name, primaryField.Name, StringComparison.OrdinalIgnoreCase)) != null; // Throw if not present if (isPresent == false) { throw new InvalidQualifiersException($"There are no qualifier field objects found for '{tableName}'. Ensure that the " + $"primary field is present at the given fields '{fields.Select(field => field.Name).Join(", ")}'."); } // The primary is present, use it as a default if there are no qualifiers given qualifiers = primaryField.AsField().AsEnumerable(); } else { // Throw exception, qualifiers are not defined throw new NullReferenceException($"There are no qualifier field objects found for '{tableName}'."); } } // Get the insertable and updateable fields var insertableFields = fields .Where(field => !string.Equals(field.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); var updateableFields = fields .Where(field => !string.Equals(field.Name, primaryField?.Name, StringComparison.OrdinalIgnoreCase) && !string.Equals(field.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); // Variables needed var databaseType = (string)null; // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToDB2iSeriesStringNameResolver().Resolve(dbType.Value); } } else if (primaryField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(primaryField.Type); if (dbType != null) { databaseType = new DbTypeToDB2iSeriesStringNameResolver().Resolve(dbType.Value); } } // Initialize the builder var builder = queryBuilder ?? new QueryBuilder(); // Build the query builder.Clear(); // Iterate the indexes for (var index = 0; index < batchSize; index++) { // MERGE T USING S queryBuilder.Merge() .TableNameFrom(tableName, DbSetting) .As("T") .HintsFrom(hints) .Using() .OpenParen() .Select() .ParametersAsFieldsFrom(fields, index, DbSetting) .CloseParen() .As("S") // QUALIFIERS .On() .OpenParen() .WriteText(qualifiers? .Select( field => field.AsJoinQualifier("S", "T", DbSetting)) .Join(" AND ")) .CloseParen() // WHEN NOT MATCHED THEN INSERT VALUES .When() .Not() .Matched() .Then() .Insert() .OpenParen() .FieldsFrom(insertableFields, DbSetting) .CloseParen() .Values() .OpenParen() .AsAliasFieldsFrom(insertableFields, "S", DbSetting) .CloseParen() // WHEN MATCHED THEN UPDATE SET .When() .Matched() .Then() .Update() .Set() .FieldsAndAliasFieldsFrom(updateableFields, "T", "S", DbSetting); // Set the output var outputField = identityField ?? primaryField; if (outputField != null) { queryBuilder .WriteText(string.Concat("OUTPUT INSERTED.", outputField.Name.AsField(DbSetting))) .As("[Result]"); } // End the builder queryBuilder.End(); } // Return the query return(builder.GetString()); }
protected override void SetValue(string inputValue) { _providerName = _filteredProviders?.FirstOrDefault(p => p.Id == inputValue)?.DisplayName ?? inputValue; }
public static IList <IdentityPermission> GetAllActionByAssembly() { var result = new List <IdentityPermission>(); var types = Assembly.Load(new AssemblyName("HomeQI.ADream.Identity.Web")).GetTypes(); foreach (var type in types) { if (string.IsNullOrEmpty(type.Namespace)) { continue; } if (type.Namespace.Contains("HomeQI.ADream.Identity.Web.Controllers"))//如果是Controller { var members = type.GetMethods(); IEnumerable <AreaAttribute> areaName = type.GetTypeInfo(). BaseType?.GetTypeInfo(). GetCustomAttributes(typeof(AreaAttribute), true) as AreaAttribute[]; foreach (var member in members) { var name = member.ReturnType.Name; if ((member.ToString().Contains("IActionResult") || name == "IActionResult") && member.IsPublic) //如果是Action { if (!(member.Name == "Json" || type.Name.Contains("Base"))) { var pars = member.GetParameters().Select(o => new { o.ParameterType.FullName, o.Name }); IEnumerable <DescriptionAttribute> description = member.GetCustomAttributes(typeof(DescriptionAttribute), true) as DescriptionAttribute[]; var allowAnonymous = member.GetCustomAttributes(typeof(AllowAnonymousAttribute), true); var ap = new IdentityPermission { Action = member.Name }; if (pars != null) { if (pars.Count() > 0) { ap.Params = Serializer.ToJson(pars); } } ap.IsAllowAnonymous = allowAnonymous.Count() > 0; ap.Controller = type.Name.Replace("Controller", ""); // 去掉“Controller”后缀 if (description?.Count() > 0) { ap.Description = description?.FirstOrDefault().Description; } if (areaName?.Count() > 0) { ap.AreaName = areaName?.FirstOrDefault().RouteValue; } if (ap.Action.Contains("OnAction")) { continue; } result.Add(ap); } } } } } return(result); }
public async Task <bool> UpdateUser(int id, User user) { var admin = user.Admin ? 1 : 0; var recipient = user.Recipient ? 1 : 0; var verified = user.Verified ? 1 : 0; IEnumerable <GoogleAddress> addresses = null; try { var geocoder = new GoogleGeocoder(); addresses = await geocoder.GeocodeAsync($"{user.Organization_Address_Line1} {user.Organization_Address_Line2}, {user.Organization_City}, {user.Organization_State}, {user.Organization_PostalCode}"); } catch (Exception ex) { Console.WriteLine("Error geocoding: " + ex.StackTrace); } var query = $"UPDATE [User] SET " + $"[Person_Name] = @Person_Name, " + $"[Verified] = @Verified, " + $"[Admin] = @Admin, " + $"[Recipient] = @Recipient, " + $"[Status] = @Status, " + $"[Phone_Number] = @Phone_Number, " + $"[Organization_Name] = @Organization_Name, " + $"[Organization_Address_Line1] = @Organization_Address_Line1, " + $"[Organization_Address_Line2] = @Organization_Address_Line2, " + $"[Organization_City] = @Organization_City, " + $"[Organization_State] = @Organization_State, " + $"[Organization_PostalCode] = @Organization_PostalCode, " + $"[Organization_Country] = @Organization_Country, " + $"[Lat] = @Lat, " + $"[Long] = @Long " + $"WHERE [Id] = @Id"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Person_Name", user.Person_Name ?? ""); command.Parameters.AddWithValue("@Verified", verified); command.Parameters.AddWithValue("@Admin", admin); command.Parameters.AddWithValue("@Recipient", recipient); command.Parameters.AddWithValue("@Status", user.Status.ToString("F")); command.Parameters.AddWithValue("@Phone_Number", user.Phone_Number ?? ""); command.Parameters.AddWithValue("@Organization_Name", user.Organization_Name ?? ""); command.Parameters.AddWithValue("@Organization_Address_Line1", user.Organization_Address_Line1 ?? ""); command.Parameters.AddWithValue("@Organization_Address_Line2", user.Organization_Address_Line2 ?? ""); command.Parameters.AddWithValue("@Organization_City", user.Organization_City ?? ""); command.Parameters.AddWithValue("@Organization_State", user.Organization_State ?? ""); command.Parameters.AddWithValue("@Organization_PostalCode", user.Organization_PostalCode ?? ""); command.Parameters.AddWithValue("@Organization_Country", user.Organization_Country ?? ""); command.Parameters.AddWithValue("@Lat", addresses?.FirstOrDefault()?.Coordinates.Latitude ?? 0.0); command.Parameters.AddWithValue("@Long", addresses?.FirstOrDefault()?.Coordinates.Longitude ?? 0.0); command.Parameters.AddWithValue("@Id", id); var res = command.ExecuteNonQuery(); command.Parameters.Clear(); return(res == 1); } } }
public string GenerateImageUrl(IEnumerable<string> id) { return GenerateImageUrl(id?.FirstOrDefault()); }
private async Task <(bool valid, IEnumerable <JobDefinition> jobDefinitions, IActionResult failureResponse)> ValidateCreateJobsRequests(IEnumerable <JobCreateModel> jobs) { Guard.ArgumentNotNull(jobs, nameof(jobs)); if (!jobs.Any()) { string message = "Empty collection of job create models was provided"; _logger.Warning(message); return(false, ArraySegment <JobDefinition> .Empty, new BadRequestObjectResult(message)); } IEnumerable <JobDefinition> jobDefinitions = await _jobDefinitionsService.GetAllJobDefinitions(); if (jobDefinitions.IsNullOrEmpty()) { string message = "Failed to retrieve job definitions"; _logger.Error(message); return(false, ArraySegment <JobDefinition> .Empty, new InternalServerErrorResult(message)); } IList <ValidationResult> validationResults = new List <ValidationResult>(); //ensure all jobs in batch have the correct job definition foreach (JobCreateModel jobCreateModel in jobs) { Guard.IsNullOrWhiteSpace(jobCreateModel.JobDefinitionId, nameof(jobCreateModel.JobDefinitionId)); JobDefinition jobDefinition = jobDefinitions?.FirstOrDefault(m => m.Id == jobCreateModel.JobDefinitionId); if (jobDefinition == null) { string message = $"A job definition could not be found for id: {jobCreateModel.JobDefinitionId}"; _logger.Warning(message); return(false, ArraySegment <JobDefinition> .Empty, new PreconditionFailedResult(message)); } CreateJobValidationModel createJobValidationModel = new CreateJobValidationModel { JobCreateModel = jobCreateModel, JobDefinition = jobDefinition }; ValidationResult validationResult = _createJobValidator.Validate(createJobValidationModel); if (validationResult != null && !validationResult.IsValid) { validationResults.Add(validationResult); } } if (validationResults.Any()) { return(false, ArraySegment <JobDefinition> .Empty, new BadRequestObjectResult(validationResults)); } return(true, jobDefinitions, null); }
private async void OnGeoViewTapped(object sender, GeoViewInputEventArgs e) { try { _activityIndicator.StartAnimating(); _statusLabel.Text = "Identifying trace locations..."; // Identify the feature to be used. IEnumerable <IdentifyLayerResult> identifyResult = await _myMapView.IdentifyLayersAsync(e.Position, 10.0, false); ArcGISFeature feature = identifyResult?.FirstOrDefault()?.GeoElements?.FirstOrDefault() as ArcGISFeature; if (feature == null) { return; } // Create element from the identified feature. UtilityElement element = _utilityNetwork.CreateElement(feature); if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Junction) { // Select terminal for junction feature. IEnumerable <UtilityTerminal> terminals = element.AssetType.TerminalConfiguration?.Terminals; if (terminals?.Count() > 1) { element.Terminal = await WaitForTerminal(terminals); } _statusLabel.Text = $"Terminal: {element.Terminal?.Name ?? "default"}"; } else if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Edge) { // Compute how far tapped location is along the edge feature. if (feature.Geometry is Polyline line) { line = GeometryEngine.RemoveZ(line) as Polyline; element.FractionAlongEdge = GeometryEngine.FractionAlong(line, e.Location, -1); _statusLabel.Text = $"Fraction along edge: {element.FractionAlongEdge}"; } } // Check whether starting location or barrier is added to update the right collection and symbology. Symbol symbol = null; if (_startBarrierPicker.SelectedSegment == 0) { _startingLocations.Add(element); symbol = _startingPointSymbol; } else { _barriers.Add(element); symbol = _barrierPointSymbol; } // Add a graphic for the new utility element. Graphic traceLocationGraphic = new Graphic(feature.Geometry as MapPoint ?? e.Location, symbol); _myMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Add(traceLocationGraphic); } catch (Exception ex) { _statusLabel.Text = "Identifying locations failed..."; new UIAlertView("Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show(); } finally { if (_statusLabel.Text.Equals("Identifying trace locations...")) { _statusLabel.Text = "Could not identify location."; } _activityIndicator.StopAnimating(); } }
private List <NodeResult> ParseNode(XmlNode node, List <XmlDocument> docs, string parentName, Dictionary <string, int> valueIndex, IEnumerable <MatchVal> matchVals, IEnumerable <string> valsInclude, IEnumerable <string> valsExclude, IEnumerable <string> tagsOnce, IEnumerable <string> tagsExclude) { var result = new List <NodeResult>(); string name = parentName + node.Name + ","; bool added = false; string attribute = matchVals?.FirstOrDefault(v => v.Tags == name)?.Attribute; if (attribute != null) { string val = node.Attributes[attribute]?.Value; if (val != null && (valsInclude == null || valsInclude.Contains(val)) && (valsExclude == null || !valsExclude.Contains(val))) { int ind = NextIndex; if (valueIndex.ContainsKey(val)) { ind = valueIndex[val]; } else { valueIndex[val] = NextIndex; NextIndex = (NextIndex + 1) % docs.Count; } added = true; result.Add(new NodeResult(docs, ind, node, true)); } } if (!added) { if (tagsOnce != null && tagsOnce.Contains(name)) { int ind = NextIndex; NextIndex = (NextIndex + 1) % docs.Count; result.Add(new NodeResult(docs, ind, node, true)); } else if (tagsExclude != null && tagsExclude.Contains(name)) { // Do nothing if the node is on the exclude list. } else if (node.HasChildNodes && (matchVals?.Any(v => v.Tags.StartsWith(name)) == true || tagsOnce?.Any(v => v.StartsWith(name)) == true || tagsExclude?.Any(v => v.StartsWith(name)) == true)) { var totRes = new List <NodeResult>(); foreach (XmlNode child in node.ChildNodes) { List <NodeResult> res = ParseNode(child, docs, name, valueIndex, matchVals, valsInclude, valsExclude, tagsOnce, tagsExclude); totRes.AddRange(res); } var indices = totRes.Select(v => v.Index).Distinct(); foreach (int i in indices) { var nr = new NodeResult(docs, i, node, false); var nodes = totRes.Where(v => v.Index == i); foreach (var n in nodes) { nr.Node.AppendChild(n.Node); } result.Add(nr); } } else { for (int i = 0; i < docs.Count; i++) { result.Add(new NodeResult(docs, i, node, true)); } } } return(result); }
/// <summary> /// Insert multiple rows in the table. /// </summary> /// <typeparam name="TEntity">The type of the data entity objects.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entities">The list of data entity objects to be inserted.</param> /// <param name="batchSize">The batch size of the insertion.</param> /// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The number of inserted rows in the table.</returns> public static int InsertAll <TEntity>(this IDbConnection connection, string tableName, IEnumerable <TEntity> entities, int batchSize = Constant.DefaultBatchOperationSize, IEnumerable <Field> fields = null, string hints = null, int?commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return(InsertAllInternalBase <TEntity>(connection: connection, tableName: tableName, entities: entities, batchSize: batchSize, fields: GetQualifiedFields <TEntity>(fields, entities?.FirstOrDefault()), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder, skipIdentityCheck: true)); }
/// <summary> /// /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="connection"></param> /// <param name="tableName"></param> /// <param name="dbFields"></param> /// <param name="batchSize"></param> /// <param name="fields"></param> /// <param name="commandText"></param> /// <returns></returns> private static InsertAllExecutionContext <TEntity> CreateInternal <TEntity>(IDbConnection connection, string tableName, IEnumerable <DbField> dbFields, int batchSize, IEnumerable <Field> fields, string commandText) where TEntity : class { var typeOfEntity = typeof(TEntity); var dbSetting = connection.GetDbSetting(); var identity = (Field)null; var inputFields = (IEnumerable <DbField>)null; var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity); // Set the identity value if (typeOfEntity.IsClassType()) { identity = IdentityCache.Get <TEntity>()?.AsField() ?? FieldCache .Get <TEntity>()? .FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField?.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) ?? identityDbField?.AsField(); } // Filter the actual properties for input fields inputFields = dbFields? .Where(dbField => dbField.IsIdentity == false) .Where(dbField => fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null) .AsList(); // Variables for the context var multipleEntitiesFunc = (Action <DbCommand, IList <TEntity> >)null; var identitySettersFunc = (List <Action <TEntity, DbCommand> >)null; var singleEntityFunc = (Action <DbCommand, TEntity>)null; var identitySetterFunc = (Action <TEntity, object>)null; // Get if we have not skipped it if (typeOfEntity.IsClassType() && identity != null) { identitySetterFunc = FunctionCache.GetDataEntityPropertySetterCompiledFunction <TEntity>(identity); } // Identity which objects to set if (batchSize <= 1) { singleEntityFunc = FunctionCache.GetDataEntityDbParameterSetterCompiledFunction <TEntity>( string.Concat(typeof(TEntity).FullName, StringConstant.Period, tableName, ".InsertAll"), inputFields?.AsList(), null, dbSetting); } else { multipleEntitiesFunc = FunctionCache.GetDataEntityListDbParameterSetterCompiledFunction <TEntity>( string.Concat(typeof(TEntity).FullName, StringConstant.Period, tableName, ".InsertAll"), inputFields?.AsList(), null, batchSize, dbSetting); } // Return the value return(new InsertAllExecutionContext <TEntity> { CommandText = commandText, InputFields = inputFields, BatchSize = batchSize, SingleDataEntityParametersSetterFunc = singleEntityFunc, MultipleDataEntitiesParametersSetterFunc = multipleEntitiesFunc, IdentityPropertySetterFunc = identitySetterFunc, IdentityPropertySettersFunc = identitySettersFunc }); }
/// <summary> /// Gets the currently selected item. If more than one item is selected, it returns the first one. /// </summary> /// <remarks><see langword="null"/> if no items are selected.</remarks> public async Task <SolutionItem?> GetActiveItemAsync() { IEnumerable <SolutionItem>?items = await GetActiveItemsAsync(); return(items?.FirstOrDefault()); }
/// <summary> /// Gets A Profile Of A User /// </summary> /// <param name="userId">string user id of proile to get</param> /// <returns>System.Threading.Tasks.Task</returns> public async Task <Profile> GetUserProfiles(string defaultProfileId) { IEnumerable <Profile> profiles = await profileTable.Where(p => p.Id == defaultProfileId).ToEnumerableAsync(); return(profiles?.FirstOrDefault()); }
public async Task <CaregiverRelation> GetCaregiverRelation(string profileId, string relationId) { IEnumerable <CaregiverRelation> result = await GetCaregiversRelations(profileId); return(result?.FirstOrDefault(r => r.ProfileId == relationId)); }
public async Task <CaregiverRequest> GetCaregiverRequest(string profileId, string requestId) { IEnumerable <CaregiverRequest> result = await GetCaregiversRequests(profileId); return(result?.FirstOrDefault(r => r.ProfileId == requestId)); }
private static Point FindPreviousPoint(IEnumerable <AnimatedItem> previousItems, IFeature feature, string idField) { return(previousItems?.FirstOrDefault(f => f.Feature[idField].Equals(feature[idField]))?.CurrentPoint); }