private void ProcessFactories(XmlNode node, IList factories) { foreach ( XmlNode child in node.ChildNodes ) { Type type; switch ( child.LocalName ) { case "add": type = Type.GetType(child.Attributes["type"].Value); if ( !factories.Contains(type) ) factories.Add(type); break; case "remove": type = Type.GetType(child.Attributes["type"].Value); if ( factories.Contains(type) ) factories.Remove(type); break; case "clear": factories.Clear(); break; default: // gives obsolete warning but needed for .NET 1.1 support throw new ConfigurationException(string.Format("Unknown element '{0}' in section '{0}'", child.LocalName, node.LocalName)); } } }
/// <summary> /// Get framework version for specified SubKey /// </summary> /// <param name="parentKey"></param> /// <param name="subVersionName"></param> /// <param name="versions"></param> private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, IList<NetFrameworkVersionInfo> versions) { if (parentKey != null) { string installed = Convert.ToString(parentKey.GetValue("Install")); if (installed == "1") { NetFrameworkVersionInfo versionInfo = new NetFrameworkVersionInfo(); versionInfo.VersionString = Convert.ToString(parentKey.GetValue("Version")); var test = versionInfo.BaseVersion; versionInfo.InstallPath = Convert.ToString(parentKey.GetValue("InstallPath")); versionInfo.ServicePackLevel = Convert.ToInt32(parentKey.GetValue("SP")); if (parentKey.Name.Contains("Client")) versionInfo.FrameworkProfile = "Client Profile"; else if (parentKey.Name.Contains("Full")) versionInfo.FrameworkProfile = "Full Profile"; if (!versions.Contains(versionInfo)) versions.Add(versionInfo); } } }
public static void CalculateTime(IList list, int k) { // Add var startAdding = DateTime.Now; string test = "Test string"; for (int i = 0; i < k; i++) { list.Add(test); } var finishAdding = DateTime.Now; Console.WriteLine("Addition time (" + k + " elements) : " + list.GetType() + " " + (finishAdding - startAdding)); // Search var startSearch = DateTime.Now; for (int i = 0; i < k; i++) { bool a = list.Contains(test); } var finishSearch = DateTime.Now; Console.WriteLine("Search time (" + k + " elements) : " + list.GetType() + " " + (finishSearch - startSearch)); // Remove k = 1000; var startRemoving = DateTime.Now; for (int i = 0; i < k; i++) { list.Remove(test); } var finishRemoving = DateTime.Now; Console.WriteLine("Removal time (" + k + " elements) : " + list.GetType() + " " + (finishRemoving - startRemoving) + "\n"); }
/// <summary> /// FPS command implementation. /// </summary> private void CommandExecute(IDebugCommandHost host, string command, IList<string> arguments) { foreach (string arg in arguments) { arg.ToLower(); } if (arguments.Contains("list")) { ShowList(); } if (arguments.Contains("open")) { int index = arguments.IndexOf("open"); string sceneToOpen = arguments[index + 1]; if (sceneManager.ContainsScene(sceneToOpen)) { // activate the selected scene sceneManager.ActivateScene(sceneToOpen); } } if (arguments.Contains("close")) { int index = arguments.IndexOf("close"); string sceneToClose = arguments[index + 1]; if (sceneManager.ContainsScene(sceneToClose)) { sceneManager.ExitScene(sceneToClose); } } // TODO: allow loading and disposing of scenes }
/// <summary> /// 验证用户授权: /// 验证规则: /// (1)没有被记录的url允许任何人访问; /// (2)url上的授权为null或者""时,拒绝任何用户访问; /// (3)url上的授权角色为问号 (?) ,表示该url可被任何用户访问; /// (4)url上的授权角色为问号 (*) ,表示该url可被任何通过授权验证的用户访问; /// (5)url上的授权为角色列表时,验证用户是不是同时属于该角色 /// </summary> /// <param name="userRoles"></param> /// <param name="menuRoles"></param> /// <returns></returns> public bool IsMatch(string[] userRoles, IList menuRoles) { bool result = false; // 菜单上没有任何授权 if (menuRoles == null || menuRoles.Count == 0) return false; // 菜单授权给匿名用户 if (menuRoles.Contains("?")) return true; // 菜单授权给登录的用户 if (menuRoles.Contains("*") && Context.User.Identity.IsAuthenticated) return true; // 用户没有任何角色,同时不满足上述条件 if (userRoles == null) return false; // 检查用户角色和菜单角色的匹配 foreach (string role in userRoles) { if (menuRoles.Contains(role)) { result = true; break; } } return result; }
private string Summarize(IList items) { string str = ""; if (null != items) { if (items.Contains("Cyan")) { str += "C"; } if (items.Contains("Majenta")) { str += "M"; } if (items.Contains("Yellow")) { str += "Y"; } if (items.Contains("Black")) { str += "K"; } } return str; }
private static IEnumerable<int> GenerateTermsForSeed(int seed, IList<int> terms) { if (!terms.Contains(seed)) { terms.Add(seed); } var current = seed; while (current != 1) { if (current < 0) { break; } // 256 128 64 32 16 8 4 2 1 if (current % 2 == 0) { current = current / 2; } else { current = (3 * current) + 1; } if (terms.Contains(current)) break; terms.Add(current); } return terms; }
/// <summary> /// ��֤�û���Ȩ�� /// ��֤���� /// ��1��û�б���¼��url�����κ��˷��ʣ� /// ��2��url�ϵ���ȨΪnull����""ʱ���ܾ��κ��û����ʣ� /// ��3��url�ϵ���Ȩ��ɫΪ�ʺ� (?) ����ʾ��url�ɱ��κ��û����ʣ� /// ��4��url�ϵ���Ȩ��ɫΪ�ʺ� (*) ����ʾ��url�ɱ��κ�ͨ����Ȩ��֤���û����ʣ� /// ��5��url�ϵ���ȨΪ��ɫ�б�ʱ����֤�û��Dz���ͬʱ���ڸý�ɫ /// </summary> /// <param name="userRoles"></param> /// <param name="menuRoles"></param> /// <returns></returns> public bool IsMatch(string[] userRoles, IList menuRoles) { bool result = false; // �˵���û���κ���Ȩ if (menuRoles == null || menuRoles.Count == 0) return false; // �˵���Ȩ�������û� if (menuRoles.Contains("?")) return true; // �˵���Ȩ����¼���û� if (menuRoles.Contains("*") && Context.User.Identity.IsAuthenticated) return true; // �û�û���κν�ɫ��ͬʱ�������������� if (userRoles == null) return false; // ����û���ɫ�Ͳ˵���ɫ��ƥ�� foreach (string role in userRoles) { if (menuRoles.Contains(role)) { result = true; break; } } return result; }
private void Visit(BinaryExpression binary) { if ((binary.NodeType == ExpressionType.Assign) && (binary.Left.NodeType == ExpressionType.Parameter) && (_joinedAssignmentVariables?.Contains(binary.Left) != true) && (_assignedAssignments?.Contains(binary) != true)) { var variable = (ParameterExpression)binary.Left; if (VariableHasNotYetBeenAccessed(variable)) { if (_constructs?.Any() == true) { (_constructsByAssignment ??= new Dictionary <BinaryExpression, object>()) .Add(binary, _constructs.Peek()); } (_joinedAssignments ??= new List <BinaryExpression>()).Add(binary); (_accessedVariables ??= new List <ParameterExpression>()).Add(variable); (_joinedAssignmentVariables ??= new List <ParameterExpression>()).Add(variable); } AddAssignmentIfAppropriate(binary.Right); } Visit(binary.Left); if (binary.Conversion != null) { Visit(binary.Conversion.Body); } Visit(binary.Right); }
protected void StartCamera() { if (_Camera == null) { _Camera = Camera.Open(); _CameraSupportedFlashModes = _CameraSupportedFlashModes ?? _Camera.GetParameters().SupportedFlashModes; if (_CameraSupportedFlashModes == null || !_CameraSupportedFlashModes.Contains(FlashlightOnMode) || !_CameraSupportedFlashModes.Contains(FlashlightOffMode)) { StopCamera(); } } }
public IEnumerable<BlobEvent> GetBlobEventsByBlob(DateTime fromdate, DateTime todate, IList<int> types, Guid blobId, int pageSize, int currentPage, out int totalPages) { fromdate = NormalizeFromDate(fromdate); todate = NormalizeToDate(todate); var count = this.context.BlobEvents.Where(ev => ev.Blob.BlobId == blobId && ev.EventDateTime >= fromdate && ev.EventDateTime < todate && types.Contains(ev.EventType)).Count(); totalPages = (int)Math.Ceiling((decimal)count / pageSize); return this.context.BlobEvents.Where(ev => ev.Blob.BlobId == blobId && ev.EventDateTime >= fromdate && ev.EventDateTime < todate && types.Contains(ev.EventType)).OrderByDescending(ev => ev.EventDateTime).Skip(pageSize * (currentPage - 1)).Take(pageSize).AsEnumerable(); }
public static bool IsComposedOfTwoWordsFromList(this string word, IList<string> words) { for (var i = 1; i < 6; i++) { if (words.Contains(word.Substring(0, i)) && words.Contains(word.Substring(i))) return true; } return false; }
public override IList<ReportColumn> GetCrosstabHeaders(IList<ReportColumn> columns) { if (columns.Count > 0) { if (columns.Contains(column => IsPrecursorType(column.Table))) return new[] { new ReportColumn(typeof(DbPrecursor), "IsotopeLabelType") }; // Not L10N if (columns.Contains(column => IsTransitionType(column.Table))) return new[] { new ReportColumn(typeof(DbTransition), "Precursor", "IsotopeLabelType") }; // Not L10N } return new ReportColumn[0]; }
public void TestContains() { list = new List<int>(); list.Add(1); Assert.AreEqual(true, list.Contains(1)); list.Add(1); Assert.AreEqual(true, list.Contains(1)); list.Remove(1); Assert.AreEqual(true, list.Contains(1)); list.RemoveAt(0); Assert.AreEqual(false, list.Contains(0)); }
public void Reload() { if (MainForm != null) { mSelectedTjItems = MainForm.SelectedTjItems; initTileItem(tileItemSjdy, mSelectedTjItems.Contains(TjItemEnum.数据打印)); initTileItem(tileItemNbjc, mSelectedTjItems.Contains(TjItemEnum.内部监测)); initTileItem(tileItemKqys, mSelectedTjItems.Contains(TjItemEnum.库区雨水)); initTileItem(tileItemGcjs, mSelectedTjItems.Contains(TjItemEnum.工程介绍)); initTileItem(tileItemZsjs, mSelectedTjItems.Contains(TjItemEnum.知识介绍)); } }
public HeaderViewModel(Profile userProfile, IList<string> userRoles) { if (userProfile == null) { return; } this.Email = userProfile.Email; this.Username = userProfile.UserName; //this.Firstname = userProfile.FirstName; //this.Lastname = userProfile.LastName; this.Role = (userRoles == null) ? "" : userRoles.Contains(RoleNames.ADMIN) ? RoleNames.ADMIN : userRoles.Contains(RoleNames.OWNER) ? RoleNames.OWNER : ""; }
public IList<Category> Get(IList<Guid> ids, bool fullGraph = false) { if (fullGraph) { return _context.Category .AsNoTracking() .Include(x => x.Topics.Select(l => l.LastPost.User)) .Include(x => x.ParentCategory) .Where(x => ids.Contains(x.Id)).ToList(); } return _context.Category .AsNoTracking().Where(x => ids.Contains(x.Id)).ToList(); }
public static bool IsRolesAccessibleToCurrentUser(IList roles) { // TODO: Your custom logic here if (roles.Contains("editor") && !isEditor()) //have to be both signed in and an editor for this to return true return false; if (roles.Contains("secure") && !isLoggedIn()) //have to be signed in return false; if (roles.Contains("intra") && !isIntra()) return false; if (roles.Contains("deliveries") && !seeDeliveries()) return false; return true; }
private static void keyboard_OnKeyReleased(IList<Keys> keys) { if (keys.Contains(Keys.F)) { game.ToggleFullScreen(); } if (keys.Contains(Keys.Escape)) { game.Exit(); } if (keys.Contains(Keys.R)) { HMCameraManager.ActiveCamera.Position = new Vector3(0, 0, 3); HMCameraManager.ActiveCamera.Revolve(new Vector3(1, 0, 0), -20 * 0.01f); HMCameraManager.ActiveCamera.RevolveGlobal(new Vector3(0, 1, 0), 70 * 0.01f); } }
public IList<ClientCard> Select(IList<ClientCard> cards, int min, int max) { IList<ClientCard> result = new List<ClientCard>(); switch (_type) { case SelectType.Card: if (cards.Contains(_card)) result.Add(_card); break; case SelectType.Cards: foreach (ClientCard card in _cards) if (cards.Contains(card)) result.Add(card); break; case SelectType.Id: foreach (ClientCard card in cards) if (card.Id == _id) result.Add(card); break; case SelectType.Ids: foreach (int id in _ids) foreach (ClientCard card in cards) if (card.Id == id) result.Add(card); break; case SelectType.Location: foreach (ClientCard card in cards) if (card.Location == _location) result.Add(card); break; } if (result.Count < min) { foreach (ClientCard card in cards) { if (!result.Contains(card)) result.Add(card); if (result.Count >= min) break; } } while (result.Count > max) result.RemoveAt(result.Count - 1); return result; }
private Node GetNodeTree(string name, string projectUrl, IEnumerable<Merge> merges, IList<string> svnBranches) { var childMerges = merges.Where(m => m.Parent == name); return new Node( name, svnBranches.Contains(name), childMerges.Select(m => new Branch( GetNodeTree(m.Child, projectUrl, merges, svnBranches), m.Enabled, svnBranches.Contains(name) && svnBranches.Contains(m.Child) ? _unmergedRevisionGetter.GetUnmergedRevisions(projectUrl, m.Child, name) : (long?) null))); }
private Model( DisconnectedBufferGraph disconnectedBufferGraph, IList<CompletionItem> totalItems, IList<CompletionItem> filteredItems, CompletionItem selectedItem, bool isHardSelection, bool isUnique, bool useSuggestionCompletionMode, CompletionItem builder, CompletionItem defaultBuilder, CompletionTriggerInfo triggerInfo, ITrackingPoint commitSpanEndPoint, bool dismissIfEmpty) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(totalItems.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(filteredItems.Count != 0, "Must have at least one filtered item."); Contract.ThrowIfFalse(filteredItems.Contains(selectedItem) || defaultBuilder == selectedItem, "Selected item must be in filtered items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TotalItems = totalItems; this.FilteredItems = filteredItems; this.SelectedItem = selectedItem; this.IsHardSelection = isHardSelection; this.IsUnique = isUnique; this.UseSuggestionCompletionMode = useSuggestionCompletionMode; this.Builder = builder; this.DefaultBuilder = defaultBuilder; this.TriggerInfo = triggerInfo; this.CommitTrackingSpanEndPoint = commitSpanEndPoint; this.DismissIfEmpty = dismissIfEmpty; }
private static void GenerateChains(IList<int> chain, int n) { var count = chain.Count; if (count >= n) return; var last = chain.Last(); var nextElems = _dict[last].Where(k => !chain.Contains(k)).ToList(); if (nextElems.Any() && count < n) { foreach (var next in nextElems) { var deeper = chain.ToList(); deeper.Add(next); GenerateChains(deeper, n); } } else if (IsPrime(last + 1) && count == n - 1) { _nrOfChains++; /*foreach (var elem in chain) { Console.Write(elem+" "); } Console.WriteLine(1);*/ } }
/// <summary> /// Insert a <see cref="IMigrationExpression"/> into the list /// </summary> /// <param name="list"></param> /// <param name="indexItem"></param> /// <param name="newItemToInsert"></param> /// <param name="after"></param> /// <returns></returns> public static IList <IMigrationExpression> Insert(this IList <IMigrationExpression> list, IMigrationExpression indexItem, IMigrationExpression newItemToInsert, bool after = false) { if (list?.Contains(newItemToInsert) ?? true) { return(list); } var index = list.IndexOf(indexItem); if (index < 0) { list.Add(newItemToInsert); } else { if (after) { index++; } list.Insert(index, newItemToInsert); } return(list); }
public bool ProccessGues(IList<int> digits, string gues, out int bulls, out int cows) { bulls = 0; cows = 0; if (gues.Length != NUMBER_OF_DIGITS) { return false; } int[] guestedDigits = new int[NUMBER_OF_DIGITS]; for (int index = 0; index < NUMBER_OF_DIGITS; index++) { if (!int.TryParse(gues[index].ToString(), out guestedDigits[index])) { return false; } if (guestedDigits[index] == digits[index]) { bulls++; } else if (digits.Contains(guestedDigits[index])) { cows++; } } return true; }
public Model( DisconnectedBufferGraph disconnectedBufferGraph, TextSpan textSpan, ISignatureHelpProvider provider, IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, int argumentIndex, int argumentCount, string argumentName, int? selectedParameter) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(items.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(items.Contains(selectedItem), "Selected item must be in list of items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TextSpan = textSpan; this.Items = items; this.Provider = provider; this.SelectedItem = selectedItem; this.ArgumentIndex = argumentIndex; this.ArgumentCount = argumentCount; this.ArgumentName = argumentName; this.SelectedParameter = selectedParameter; }
public IList<string> GetDayActivity(IList<string> zoo, string killer) { if (!zoo.Contains(killer)) { return new List<string>(); } var herring = new List<string>(GameResources.Herrings); var goodTraits = new List<string>(GameResources.GoodTraits); var badTraits = new List<string>(GameResources.BadTraits); herring.Shuffle(); goodTraits.Shuffle(); badTraits.Shuffle(); // good and bad traits int badIndex = 0; int goodIndex = 0; var clues = zoo.Select(x => { double chance = x == killer ? ChanceBadKillerTrait : ChanceBadFodderTrait; string trait = Extensions.RandomGenerator.Next(0, 999)/1000.0 < chance ? badTraits[badIndex++] : goodTraits[goodIndex++]; return String.Format(trait, x); }).ToList(); // herrings int herringIndex = 0; clues.AddRange(zoo.Select(x => String.Format(herring[herringIndex++], x))); clues.Shuffle(); return clues; }
public IDictionary<MapNode, double> GetDistance(MapNode source, IList<MapNode> dest) { distanceTo.Clear(); foreach (var n in map) { distanceTo[n] = double.MaxValue; } distanceTo[source] = 0.0; pq.Clear(); var ret = new Dictionary<MapNode, double>(); pq.Enqueue(source, 0.0d); while (pq.Count != 0) { var nodeToExam = pq.Dequeue(); Relax(nodeToExam); if (dest.Contains(nodeToExam)) { ret[nodeToExam] = distanceTo[nodeToExam]; if (ret.Count == dest.Count) return ret; } } return ret; }
protected override Assembly Load(AssemblyName assemblyName) { if ((dependencies?.Contains(assemblyName.Name) ?? false) == false) { return(Assembly.Load(new AssemblyName(assemblyName.Name))); } var deps = DependencyContext.Default; var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName.Name, StringComparison.OrdinalIgnoreCase)).ToList(); if (res.Count > 0) { return(Assembly.Load(new AssemblyName(res.First().Name))); } else { var apiApplicationFileInfo = new FileInfo($"{folderPath}{Path.DirectorySeparatorChar}{assemblyName.Name}.dll"); if (File.Exists(apiApplicationFileInfo.FullName)) { var asl = new AssemblyLoader(apiApplicationFileInfo.DirectoryName, dependencies); return(asl.LoadFromMemoryStream(apiApplicationFileInfo.FullName)); } } return(Assembly.Load(assemblyName)); }
public async Task<IList<DeploymentAudit>> GetAllAuditsAsync(IList<Guid> deploymentIds) { var list = await collection.AsQueryable() .Where(d => deploymentIds.Contains(d.DeploymentId)) .ToListAsync(); return list; }
private List<string> choices; //holds which information had been chose to be displayed #endregion Fields #region Constructors /// <summary> /// Constructor for infoSelect form which lets the user choose which information about the process will be displayed /// </summary> /// <param name="selected"></param> /// <param name="allPossibleData"></param> public InfoSelect(IList<string> selected, IList<string> allPossibleData) { InitializeComponent(); choices = new List<string>(); checkGroup = new List<CheckBox>(); checkGroup.AddRange(new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7, checkBox8, checkBox9, checkBox10, checkBox11, checkBox13, checkBox14}); int i = 0; //populate checkboxes with the avilable options foreach (CheckBox box in checkGroup) { if (i < allPossibleData.Count) { box.Text = allPossibleData[i]; box.Visible = true; i++; } else { break; } } //check the appropriate boxes foreach (CheckBox box in checkGroup) { if (selected.Contains(box.Text)) { box.Checked = true; } } }
private void TestAnnotations( string expectedText, IList<TextSpan> expectedSpans, SyntaxNode fixedRoot, string annotationKind, bool compareTokens, ParseOptions parseOptions = null) { expectedSpans = expectedSpans ?? new List<TextSpan>(); var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList(); Assert.Equal(expectedSpans.Count, annotatedTokens.Count); if (expectedSpans.Count > 0) { var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage(), parseOptions)); var actualTokens = TokenUtilities.GetTokens(fixedRoot); for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++) { var expectedToken = expectedTokens[i]; var actualToken = actualTokens[i]; var actualIsConflict = annotatedTokens.Contains(actualToken); var expectedIsConflict = expectedSpans.Contains(expectedToken.Span); Assert.Equal(expectedIsConflict, actualIsConflict); } } }
/// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <param name="value">The value for which to create a <see cref="System.String"/>.</param> /// <param name="useLineBreaks"> </param> /// <param name="processedObjects"> /// A collection of objects that /// </param> /// <param name="nestedPropertyLevel"> /// The level of nesting for the supplied value. This is used for indenting the format string for objects that have /// no <see cref="object.ToString()"/> override. /// </param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public string ToString(object value, bool useLineBreaks, IList<object> processedObjects = null, int nestedPropertyLevel = 0) { if (value.GetType() == typeof (object)) { return string.Format("System.Object (HashCode={0})", value.GetHashCode()); } string prefix = (useLineBreaks ? Environment.NewLine : ""); if (HasDefaultToStringImplementation(value)) { if (!processedObjects.Contains(value)) { processedObjects.Add(value); return prefix + GetTypeAndPublicPropertyValues(value, nestedPropertyLevel, processedObjects); } else { return string.Format("{{Cyclic reference to type {0} detected}}", value.GetType()); } } return prefix + value; }
/// <summary> /// Methods to map property with the same name from one class to another, destination class already existed, ignore type /// </summary> /// <typeparam name="T">source's type</typeparam> /// <typeparam name="TU">destination's type</typeparam> /// <param name="source">the source to convert from</param> /// <param name="destination">the destination to convert to</param> /// <returns></returns> public void SimpleAutoMap <T, TU>(T source, TU destination, IList <Type> ignoreTypes) where T : class where TU : class { PropertyInfo[] propertyInfos = typeof(T).GetProperties(); PropertyInfo[] destinationPropertyInfos = typeof(TU).GetProperties(); foreach (var propertyInfo in propertyInfos) { //Check if setter exist if (propertyInfo.GetSetMethod() == null) { continue; } if (ignoreTypes?.Contains(propertyInfo.PropertyType) == true) { continue; } try { if (!destinationPropertyInfos.Where(i => i.Name.Equals(propertyInfo.Name)).Any()) { continue; } typeof(TU).GetProperty(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase) .SetValue(destination, propertyInfo.GetValue(source)); } catch { /*Ignore errors.... */ } } }
public void Dispose() { if (_observers?.Contains(_observer) ?? false) { _observers.Remove(_observer); } if (_systemObservers?.Contains(_systemObserver) ?? false) { _systemObservers.Remove(_systemObserver); } }
public void AddProperties <TArea>(StructureInfo structureInfo, IFieldFramework oldFieldContainer, IFieldFramework fieldContainer, bool changeUrl = true, IList <string> excludeFields = null) where TArea : IArea { if (oldFieldContainer[SystemFieldDefinitionConstants.Images] is List <Guid> images) { var newImages = images.Select(structureInfo.Id).ToList(); fieldContainer[SystemFieldDefinitionConstants.Images] = newImages; } var fields = Get <TArea>((IFieldContainerAccessor)oldFieldContainer); foreach (var field in fields) { if (excludeFields?.Contains(field.Key) == true) { continue; } var fieldDefinition = _fieldDefinitionService.Get <TArea>(field.Key); if (fieldDefinition == null) { continue; } if (fieldDefinition.MultiCulture) { foreach (var cultureValue in field.Value) { var value = CorrectValue <TArea>(structureInfo, field.Key, cultureValue.Value, fieldDefinition, changeUrl); fieldContainer[fieldDefinition.Id, cultureValue.Key] = ConvertFromEditValue( new EditFieldTypeConverterArgs(fieldDefinition, new CultureInfo(cultureValue.Key)), value); } } else { if (field.Value.TryGetValue("*", out var value)) { var newValue = CorrectValue <TArea>(structureInfo, field.Key, value, fieldDefinition, changeUrl); fieldContainer[fieldDefinition.Id] = ConvertFromEditValue( new EditFieldTypeConverterArgs(fieldDefinition, CultureInfo.CurrentCulture), newValue); } else { fieldContainer.TryRemoveValue(fieldDefinition.Id, out _); } } } }
internal static void CopyFolderContents(string sourceFolder, string targetFolder, Func <string, string> nameConverter = null, IList <string> excludes = null) { var sourceDirectory = new DirectoryInfo(sourceFolder); foreach (var directory in sourceDirectory.EnumerateDirectories().Where( x => excludes?.Contains(x.Name) != true)) { CopyFiles(directory.FullName, Path.Combine(targetFolder, directory.Name), SearchOption.AllDirectories, nameConverter); } CopyFiles(sourceDirectory.FullName, targetFolder, SearchOption.TopDirectoryOnly, nameConverter); }
public static IList <T> Minus <T>(IList <T> list, IList <T> minus) { ValidationUtils.ArgumentNotNull(list, "list"); List <T> list2 = new List <T>(list.Count); foreach (T item in list) { if (!(minus?.Contains(item) ?? false)) { list2.Add(item); } } return(list2); }
public async Task <IOperationResult> ManageUserRoles(string userId, IList <string> roles) { try { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(OperationResult.Failed("User could not be loaded.")); } var userRoles = await _userManager.GetRolesAsync(user); if (userRoles != null) { //var rolesToKeep = roles?.Where(role => userRoles.Contains(role))?.ToList(); var rolesToRemove = userRoles.Where(userRole => roles?.Contains(userRole) == false).ToList(); if (rolesToRemove.Any()) { _logger.LogInformation( $"Removed roles '{string.Join(", ", rolesToRemove)}' from IdentityUser with Id '{user.Id}'"); await _userManager.RemoveFromRolesAsync(user, rolesToRemove); } var rolesToAdd = roles?.Where(role => userRoles.Contains(role) == false).ToList(); if (rolesToAdd != null && rolesToAdd.Any()) { _logger.LogInformation( $"Added roles '{string.Join(", ", rolesToAdd)}' to IdentityUser with Id '{user.Id}'"); await _userManager.AddToRolesAsync(user, rolesToAdd); } return(OperationResult.Success); } await _userManager.AddToRolesAsync(user, roles); return(OperationResult.Success); } catch (Exception ex) { _logger.LogError(ex); return(OperationResult.Failed(ex.Message)); } }
private async void OnRowDeleted(RowChangedEventArgs args) { await QueuedTask.Run(() => { Row row = args.Row; Feature feature = row as Feature; long objectId = feature?.GetObjectID() ?? -1; if (_selection?.Contains(objectId) ?? false) { _selection.Remove(objectId); } if (IsVisibleInGlobespotter && GlobeSpotterConfiguration.MeasurePermissions) { Measurement measurement = _measurementList.Get(objectId); measurement?.RemoveMeasurement(); } }); }
private AppendResult Append(PdfDocument input, int inputOffset = 0, IList <int> removals = null) { var remaining = MaxPageCount - PageCount; var inputPages = Enumerable .Range(1, input.PageCount) .Where(p => !(removals?.Contains(p) ?? false)) .Skip(inputOffset) .ToArray(); var inputPageCount = inputPages.Length; if (!Document.IsImported && ((inputPageCount > MaxPageCount && BreakForLargeDocuments) || inputPageCount / 2 > remaining)) { return(new AppendResult(false, 0, 0)); } var idx = 0; for (; idx < remaining && idx < inputPageCount; idx++) { Document.AddPage(input.Pages[inputPages[idx] - 1]); } var complete = idx >= inputPageCount; inputOffset = complete ? 0 : idx; Console.WriteLine( $"Merged pages ({string.Join(", ", inputPageCount)}) from {input.FullPath} into output document"); Console.WriteLine( $"Complete: {(complete ? "Yes" : "No")}\tNumber of pages written: {idx}\tResulting offset: {inputOffset}"); PageCount = Document.PageCount; return(new AppendResult(complete, inputOffset, idx)); }
/// <summary> /// This method must be invoked to load modules ready for handling instances of <see cref="IEvent"/>. This allows the module or /// modules being loaded to initialize internally. Passing a list of <see cref="ModuleName"/> as an argument to this method will /// only attempt to load the listed modules. This may be useful in an environment where you may wish to load modules individually /// or a subset of modules only when they are required. /// </summary> public virtual void LoadModules(IList <ModuleName> modules = null) { // We first need to initialize each module inside its container. The loading process of an array of modules is as follows: // 1) Ensure all module dependencies exist within the module ModuleAttributes.Dependencies array // 2) Initialize each module so we have a useable module type and can invoke its methods. // 3) Invoke OnLoading on each module based on ModuleAttributes.ModuleLoadPriority property. This allows the module to initialize // and configure any requirements within itself. which may require communication with other modules. // 4) Invoke OnLoaded on each module based on ModuleAttributes.ModuleLoadPriority property. // When we imported modules we ordered the containers by ModuleAttributes.LoadPriority which makes it nice and easy to just // itterate each container and invoke the requirements in order. foreach (var c in Containers) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { continue; } // Check dependencies... var missing = c.ModuleAttributes.Dependencies.Where(d => !HasModule(d)); if (missing.Count() > 0) { throw new Exception(string.Format("{0} module has missing module dependencies: {1}", c.ModuleAttributes.Name, string.Join(' ', missing))); } } foreach (var c in Containers) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { continue; } // Initialize the container. This creates an instance of the module using Activator.CreatInstance. if (!c.Initialized) { Host.Log(LoggingEvent.Severity.Debug, "Initializing module..." , c.ModuleAttributes); c.InitializeModule(); } } // Look for IModules with the IModuleAttribute.LoadFirst property set to true and trigger these to fully load before other modules. var loadFirst = Containers.Where(c => c.ModuleAttributes.LoadFirst == true); if (loadFirst != null && loadFirst.Count() > 0) { foreach (var c in loadFirst) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { Host.Log(LoggingEvent.Severity.Error, "Failed to load module..." , c.ModuleAttributes); continue; } // Invoke the OnLoading method on each module in the order in which they should be loaded. // We set the loaded property to true here so that any dependant module can raise events to // its dependencies while loading. if (!c.Module.Loaded) { Host.Log(LoggingEvent.Severity.Debug, "Loading module..." , c.ModuleAttributes); c.Module.OnLoading(); c.Module.Loaded = true; } } foreach (var c in loadFirst) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { continue; } // Finally we invoke OnLoaded on each module in the order in which they should be loaded. This is decided // in the ImportModules method and when the imported modules are added to this collection. if (c.Module.Loaded) { c.Module.OnLoaded(); Host.Log(LoggingEvent.Severity.Debug, "Loaded module..." , c.ModuleAttributes); } } } foreach (var c in Containers) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { continue; } // Invoke the OnLoading method on each module in the order in which they should be loaded. // We set the loaded property to true here so that any dependant module can raise events to // its dependencies while loading. if (!c.Module.Loaded) { Host.Log(LoggingEvent.Severity.Debug, "Loading module..." , c.ModuleAttributes); c.Module.OnLoading(); c.Module.Loaded = true; } } foreach (var c in Containers) { if (modules != null && !modules.Contains(c.ModuleAttributes.Name)) { continue; } // Finally we invoke OnLoaded on each module in the order in which they should be loaded. This is decided // in the ImportModules method and when the imported modules are added to this collection. if (c.Module.Loaded) { c.Module.OnLoaded(); Host.Log(LoggingEvent.Severity.Debug, "Loaded module..." , c.ModuleAttributes); } } }
/* * source: C:\Program Files\msysgit\doc\git\html\git-status.html */ public static List <GitItemStatus> GetAllChangedFilesFromString(string statusString, bool fromDiff /*old name and new name are switched.. %^&#^% */) { var diffFiles = new List <GitItemStatus>(); if (string.IsNullOrEmpty(statusString)) { return(diffFiles); } /*The status string can show warnings. This is a text block at the start or at the beginning * of the file status. Strip it. Example: * warning: LF will be replaced by CRLF in CustomDictionary.xml. * The file will have its original line endings in your working directory. * warning: LF will be replaced by CRLF in FxCop.targets. * The file will have its original line endings in your working directory.*/ var nl = new char[] { '\n', '\r' }; string trimmedStatus = statusString.Trim(nl); int lastNewLinePos = trimmedStatus.LastIndexOfAny(nl); if (lastNewLinePos > 0) { int ind = trimmedStatus.LastIndexOf('\0'); if (ind < lastNewLinePos) //Warning at end { lastNewLinePos = trimmedStatus.IndexOfAny(nl, ind >= 0 ? ind: 0); trimmedStatus = trimmedStatus.Substring(0, lastNewLinePos).Trim(nl); } else //Warning at beginning { trimmedStatus = trimmedStatus.Substring(lastNewLinePos).Trim(nl); } } // Doesn't work with removed submodules IList <string> Submodules = Settings.Module.GetSubmodulesNames(); //Split all files on '\0' (WE NEED ALL COMMANDS TO BE RUN WITH -z! THIS IS ALSO IMPORTANT FOR ENCODING ISSUES!) var files = trimmedStatus.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); for (int n = 0; n < files.Length; n++) { if (string.IsNullOrEmpty(files[n])) { continue; } int splitIndex = files[n].IndexOfAny(new char[] { '\0', '\t', ' ' }, 1); string status = string.Empty; string fileName = string.Empty; if (splitIndex < 0) { status = files[n]; fileName = files[n + 1]; n++; } else { status = files[n].Substring(0, splitIndex); fileName = files[n].Substring(splitIndex); } char x = status[0]; char y = status.Length > 1 ? status[1] : ' '; GitItemStatus gitItemStatus = null; if (x != '?' && x != '!') { n = GitItemStatusFromStatusCharacter(fromDiff, files, n, status, fileName, x, out gitItemStatus); if (gitItemStatus != null) { gitItemStatus.IsStaged = true; diffFiles.Add(gitItemStatus); } } if (!fromDiff) { n = GitItemStatusFromStatusCharacter(fromDiff, files, n, status, fileName, y, out gitItemStatus); if (gitItemStatus != null) { gitItemStatus.IsStaged = false; diffFiles.Add(gitItemStatus); } } if (gitItemStatus != null && Submodules.Contains(gitItemStatus.Name)) { gitItemStatus.IsSubmodule = true; } } return(diffFiles); }
protected internal override bool isValidSortByValue(string value) { return(VALID_SORT_BY_VALUES.Contains(value)); }
public bool settInnStasjonerIHovedstrekning(int hovstrId, IList <int> stasjonIder, int plassering) { return(hovstrId == 1 && stasjonIder.Contains(1) && plassering == 1); }
public bool IsEnabled(LogEventLevel level, string area) { return(level >= _level && (_areas?.Contains(area) ?? true)); }
/// <summary> /// Using an audio stream, get the translation of that audio file /// </summary> /// <param name="audioData"></param> /// <param name="fromLanguage"></param> /// <param name="toLanguages"></param> /// <returns></returns> public async Task <TranslationRecognitionResult> TranslateAudioStream(byte[] audioData, string fromLanguage, IList <string> toLanguages) { if (!_availableServices.Contains(AzureServiceType.Speech)) { return(null); } _speechSemaphore.Wait(); try { TranslationRecognitionResult result; StorageFolder localFolder = ApplicationData.Current.LocalFolder; //TODO Update to use PullAudioInputStream StorageFile storageFile = await localFolder.CreateFileAsync("AudioFromStream.wav", CreationCollisionOption.ReplaceExisting); using (var stream = await storageFile.OpenStreamForWriteAsync()) { await stream.WriteAsync(audioData, 0, audioData.Count()); stream.Close(); } var audioConfig = AudioConfig.FromWavFileInput(storageFile.Path); _speechTranslationConfig.SpeechRecognitionLanguage = fromLanguage; foreach (string language in toLanguages) { _speechTranslationConfig.AddTargetLanguage(language); } using (var translationRecognizer = new TranslationRecognizer(_speechTranslationConfig, audioConfig)) { result = await translationRecognizer.RecognizeOnceAsync(); } if (result.Reason == ResultReason.Canceled) { var cancellation = CancellationDetails.FromResult(result); _logger.LogWarning($"Call cancelled. {cancellation.Reason}"); if (cancellation.Reason == CancellationReason.Error) { _logger.Log($"Cancel error code = {cancellation.ErrorCode}"); _logger.Log($"Cancel details = {cancellation.ErrorDetails}"); if (cancellation.ErrorCode == CancellationErrorCode.NoError) { _logger.Log("You may be having an authorization issue, are your keys correct and up to date?"); } } } else if (result.Reason == ResultReason.TranslatedSpeech) { _logger.Log($"Azure Translation. '{result.Reason}': {result.Text}"); } return(result); } catch (Exception ex) { string message = "Failed processing image."; _logger.Log(message, ex); return(null); } finally { _speechSemaphore.Release(); } }
public bool Contains(int item) { return(instance.Contains(item)); }
/// <summary> /// Provide the spreadsheet filename (without .xlsx extension) as an argument and place the file in C:\TestCases /// </summary> /// <param name="fileName"></param> public void FormatWorksheet(string fileName) { int Import_Key = ImportHeaders.Key.GetIndex(); int Import_TCName = ImportHeaders.TCName.GetIndex(); int Import_PreConditions = ImportHeaders.Preconditions.GetIndex(); int Import_Objective = ImportHeaders.Objective.GetIndex(); int Import_Priority = ImportHeaders.Priority.GetIndex(); int Import_Labels = ImportHeaders.Labels.GetIndex(); int Import_Step = ImportHeaders.Step.GetIndex(); int Import_TestData = ImportHeaders.TestData.GetIndex(); int Import_Result = ImportHeaders.Result.GetIndex(); int Import_Folder = ImportHeaders.Folder.GetIndex(); int Dest_ID = DestHeaders.TestID.GetIndex(); int Dest_TCName = DestHeaders.TCName.GetIndex(); int Dest_Description = DestHeaders.Description.GetIndex(); int Dest_Tags = DestHeaders.Tags.GetIndex(); int Dest_Preconditions = DestHeaders.Preconditions.GetIndex(); int Dest_Step = DestHeaders.Step.GetIndex(); int Dest_Result = DestHeaders.Result.GetIndex(); string worksheetName = fileName; string filePath = $"{Utils.GetCodeBasePath(false)}\\TestCases\\{fileName}"; Console.WriteLine($"###FilePath: {filePath}"); using (var destPkg = new ExcelPackage()) { //Read from worksheet to export FileInfo existingFile = new FileInfo($"{filePath}.xlsx"); Console.WriteLine(existingFile.ToString()); using (var importPkg = new ExcelPackage(existingFile)) { ExcelWorksheet importWS = importPkg.Workbook.Worksheets["Sheet0"]; int colCount = importWS.Dimension.End.Column; int rowCount = importWS.Dimension.End.Row; for (int row = 2; row < rowCount; row++) { _key = importWS.Cells[row, Import_Key].Value?.ToString(); _tcName = importWS.Cells[row, Import_TCName].Value?.ToString(); _preConditions = importWS.Cells[row, Import_PreConditions].Value?.ToString(); _objective = importWS.Cells[row, Import_Objective].Value?.ToString(); _priority = importWS.Cells[row, Import_Priority].Value?.ToString(); _labels = importWS.Cells[row, Import_Labels].Value?.ToString(); _step = importWS.Cells[row, Import_Step].Value?.ToString(); _testData = importWS.Cells[row, Import_TestData].Value?.ToString(); _result = importWS.Cells[row, Import_Result].Value?.ToString(); _folder = importWS.Cells[row, Import_Folder].Value?.ToString(); if (!string.IsNullOrWhiteSpace(_key)) { var folders = Regex.Split(_folder, "/"); int fhCount = (folders.Length > 2) ? 3 : folders.Length; var folderHiearchy = _folder.Split(new[] { '/' }, fhCount); string rootFolder = folderHiearchy[1]; Console.WriteLine($"ROOT FOLDER: {rootFolder}"); var destWorksheets = destPkg.Workbook.Worksheets; destWsNamesList = new List <string>(); for (int i = 0; i < destWorksheets.Count; i++) { destWsNamesList.Add(destWorksheets[i].Name); } if (rootFolder.Length > 31) { rootFolder = rootFolder.Substring(0, 31); Console.WriteLine($"TRUNCATED ROOT FOLDER: {rootFolder}"); } bool rootWorksheetExists = (destWsNamesList.Contains(rootFolder)) ? true : false; string rootwsMsg; if (rootWorksheetExists) { rootwsMsg = "WORKSHEET EXISTS:"; destWS = destPkg.Workbook.Worksheets[rootFolder]; if (fhCount > 2) { using (var mergedCell = destWS.Cells[destRow, 1]) { mergedCell.Value = folderHiearchy[2]; destWS.Cells[destRow, 1, destRow, 7].Merge = true; destWS.Cells[destRow, 1, destRow, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; destRow++; } } } else { destRow = 1; rootwsMsg = "WORKSHEET NAME ADDED:"; destWS = destPkg.Workbook.Worksheets.Add(rootFolder); destWS.Cells[destRow, Dest_ID].Value = "Test ID"; destWS.Cells[destRow, Dest_TCName].Value = "Test name"; destWS.Cells[destRow, Dest_Description].Value = "Test description"; destWS.Cells[destRow, Dest_Tags].Value = "Test tags"; destWS.Cells[destRow, Dest_Preconditions].Value = "Pre-conditions"; destWS.Cells[destRow, Dest_Step].Value = "Steps"; destWS.Cells[destRow, Dest_Result].Value = "Result"; destRow++; if (fhCount > 2) { using (var mergedCell = destWS.Cells[destRow, 1]) { mergedCell.Value = folderHiearchy[2]; destWS.Cells[destRow, 1, destRow, 7].Merge = true; destWS.Cells[destRow, 1, destRow, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; destRow++; } } } Console.WriteLine($"{rootwsMsg} {rootFolder}"); destWS.Cells[destRow, Dest_ID].Value = _key; destWS.Cells[destRow, Dest_TCName].Value = _tcName; destWS.Cells[destRow, Dest_Description].Value = _objective; destWS.Cells[destRow, Dest_Preconditions].Value = _preConditions; destWS.Cells[destRow, Dest_Tags].Value = _priority; if (!string.IsNullOrWhiteSpace(_labels)) { if (_labels.Contains(",")) { string[] multiLabel = Regex.Split(_labels, ", "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < multiLabel.Length; i++) { sb.Append($"{multiLabel[i]}{Environment.NewLine}"); } destWS.Cells[destRow, Dest_Tags].Value = sb.ToString(); } else { destWS.Cells[destRow, Dest_Tags].Value = _labels; } } if (string.IsNullOrWhiteSpace(_step)) { if (!string.IsNullOrWhiteSpace(_testData)) { destWS.Cells[destRow, Dest_Step].Value = _testData; } } else { destWS.Cells[destRow, Dest_Step].Value = (!string.IsNullOrWhiteSpace(_testData)) ? $"{_step}, {Environment.NewLine}, {_testData}" : destWS.Cells[destRow, Dest_Step].Value = _step; } destWS.Cells[destRow, Dest_Result].Value = _result; } else { _step = importWS.Cells[row, Import_Step].Value?.ToString(); _testData = importWS.Cells[row, Import_TestData].Value?.ToString(); _result = importWS.Cells[row, Import_Result].Value?.ToString(); if (!string.IsNullOrWhiteSpace(_step)) { destWS.Cells[destRow, Dest_Step].Value = _step; } if (!string.IsNullOrWhiteSpace(_testData)) { destWS.Cells[destRow, Dest_Step].Value = _testData; } if (!string.IsNullOrWhiteSpace(_result)) { destWS.Cells[destRow, Dest_Result].Value = _result; } } destRow++; } } var xlFile = Utils.GetFileInfo($"{worksheetName}_Hiptest.xlsx"); Console.WriteLine($"File saved - {xlFile}"); destPkg.SaveAs(xlFile); } }
/// <summary> /// Determine whether a given snippet is valid /// </summary> /// <param name="availableLanguages"> Languages available for the snippet </param> /// <param name="language"> Language of the snippet </param> /// <param name="code"> Code for the snippet </param> /// <returns> True if the snippet is valid </returns> public bool Validate(IList <string> availableLanguages, string language, string code) => !string.IsNullOrEmpty(code) && (availableLanguages?.Contains(language) ?? false);
/// <summary> /// Audits assessment CUD operations. /// </summary> /// <param name="service">The audit service instance.</param> /// <param name="oldEntity">The old entity.</param> /// <param name="newEntity">The new entity.</param> /// <param name="action">The action name.</param> /// <param name="username">The current username.</param> /// <param name="propertiesToSkipAuditing">The properties to skip.</param> /// <remarks>All exceptions will be propagated to caller method.</remarks> internal static void Audit <T>(IAuditService service, T oldEntity, T newEntity, string action, string username, IList <string> propertiesToSkipAuditing = null) where T : IdentifiableEntity { JObject oldObject = null; var serializwer = JsonSerializer.Create(CommonHelper.SerializerSettings); JObject newObject = JObject.FromObject(newEntity, serializwer); IList <JProperty> oldProperties = null; IList <JProperty> newProperties = newObject.Properties().ToList(); if (oldEntity != null) { oldObject = JObject.FromObject(oldEntity, serializwer); oldProperties = oldObject.Properties().ToList(); } // keep time, so that all records have the same timestamp (also slightly improves performance) DateTime now = DateTime.Now; // iterate through all object properties IEnumerable <string> propertyNames = (oldProperties ?? newProperties).Select(p => p.Name); foreach (string propertyName in propertyNames) { if (propertiesToSkipAuditing != null && propertiesToSkipAuditing.Contains(propertyName)) { continue; } JToken oldPropertyValue = null; JToken newPropertyValue = newObject.Property(propertyName).Value; if (oldEntity != null) { oldPropertyValue = oldObject.Property(propertyName).Value; } // skip when both are null if (newPropertyValue.Type == JTokenType.Null && oldPropertyValue == null) { continue; } // when properties are the same - skip auditing if (JToken.DeepEquals(oldPropertyValue, newPropertyValue)) { continue; } var record = new AuditRecord { Action = action, Field = propertyName, ItemId = newEntity.Id, ItemType = typeof(T).FullName, Timestamp = now, PreviousValue = CommonHelper.GetJtokenValue(oldPropertyValue), NewValue = CommonHelper.GetJtokenValue(newPropertyValue), Username = username }; service.Create(record); } }
public bool ExistClass(Type type) { return(_existingClasses.Contains(type)); }
public async Task <IHttpActionResult> AddHasSkillRelationship([FromBody] AddHasSkillViewModel model) { if (model == null) { model = new AddHasSkillViewModel(); Validate(model); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Find skill category using id. var skillCategories = _unitOfWork.SkillCategories.Search(); skillCategories = skillCategories.Where(x => x.Id == model.SkillCategoryId); var skillCategory = await skillCategories.FirstOrDefaultAsync(); if (skillCategory == null) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.SkillCategoryNotFound))); } // Validate the skills list. IDictionary <int, int> mHasSkills = null; IList <int> skillIds = null; if (model.HasSkills != null) { mHasSkills = model.HasSkills.ToDictionary(key => key.SkillId, value => value.Point); skillIds = mHasSkills.Keys.ToList(); if (skillIds.Count > 0) { var skills = _unitOfWork.Skills.Search(); skills = skills.Where(skill => skillIds.Contains(skill.Id)); var iTotalValidSkills = await skills.CountAsync(); if (iTotalValidSkills != mHasSkills.Count) { ModelState.AddModelError($"{nameof(model)}.{nameof(model.HasSkills)}", HttpMessages.SkillInvalid); return(BadRequest(ModelState)); } } } // Begin a transaction. using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // Remove all skill category - skill relationships var hasSkills = _unitOfWork.SkillCategorySkillRelationships.Search(); hasSkills = hasSkills.Where(x => x.SkillCategoryId == skillCategory.Id); _unitOfWork.SkillCategorySkillRelationships.Remove(hasSkills); // Go through every skill ids and add 'em to the list. if (model.HasSkills != null) { foreach (var mHasSkill in model.HasSkills) { var hasSkill = new SkillCategorySkillRelationship(); hasSkill.SkillCategoryId = skillCategory.Id; hasSkill.SkillId = mHasSkill.SkillId; hasSkill.Point = mHasSkill.Point; hasSkill.CreatedTime = 0; _unitOfWork.SkillCategorySkillRelationships.Insert(hasSkill); } } // Save changes into database. await _unitOfWork.CommitAsync(); transactionScope.Complete(); } return(Ok()); }
internal static string SelectDefaultStartupFile(IList <string> fileList, string currentSelection) { return(string.IsNullOrEmpty(currentSelection) || !fileList.Contains(currentSelection) ? fileList.FirstOrDefault() : currentSelection); }
public bool Contains(DynamicEntity item) { return(_list.Contains(item)); }
public IList <TypeDescription> FindTypeDescriptions(IList <string> typeFullNames) { return(TypeDescriptions.Where(d => typeFullNames.Contains(d.FullName)).ToList()); }
public Task <List <Student> > GetStudentsByIdsAsync(IList <long> studentIds) { return(_applicationContext.Students .Where(student => studentIds.Contains(student.Id)) .ToListAsync()); }
public bool Contains(TypeReference value) { return(m_items.Contains(value)); }
public bool Contains(T item) { return(fList.Contains(item)); }
public bool Contains(T item) { return(items.Contains(item)); }