public void TestCollectionsExtensions() { { // Empty { List <string> values = new List <string>(); Assert.True(values.Empty()); Assert.False(values.NotEmpty()); values.Add("Boo"); Assert.True(values.NotEmpty()); Assert.False(values.Empty()); values.Clear(); Assert.False(values.NotNullOrEmpty()); } // Stack: Push Range { Stack <int> values = new Stack <int>(); values.PushRange(1, 2, 3); Assert.AreEqual(new int[] { 3, 2, 1 }, values.ToArray()); } // Queue : Enqueue Range { Queue <int> values = new Queue <int>(); values.EnqueueRange(1, 2, 3); Assert.AreEqual(new int[] { 1, 2, 3 }, values.ToArray()); } } }
public List <T> GetItemsByPattern(Func <List <T> > acquirer, params string[] keyPattern) { if (!_cacheEnabled) { return(acquirer()); } //precache //this.EnsurePreCached(); List <T> result = _cache.GetListItemsByPattern <T>(_cacheKey, keyPattern); if (result.NotEmpty()) { return(result); } result = acquirer(); if (result.NotEmpty()) { SetListItem(result); return(result); } else { foreach (var k in keyPattern) { SetNullValue(k.Replace("*", "")); } } return(result); }
public void CheckEmptyList() { var ints = new List <int>(); ints.NotEmpty().ShouldBeFalse(); ints.Add(12); ints.NotEmpty().ShouldBeTrue(); }
static void Main(string[] args) { Console.WriteLine("------------List-------------:"); List <string> list = null; Console.WriteLine($"List is empty? {list.IsEmpty()}"); Console.WriteLine($"List is not empty? {list.NotEmpty()}"); Console.WriteLine("------------Byte,String,Stream-------------:"); string str = "This is test string"; Console.WriteLine($"This string is null? {str.IsNullOrWhiteSpace()}"); Console.WriteLine($"This string is not null? {str.NotNullOrWhiteSpace()}"); var bytes = str.AsBytes(); Console.WriteLine($"Bytes length is {bytes.Length}"); Console.WriteLine($"Stream length is {bytes.AsStream().Length}"); Console.WriteLine("------------Json-------------:"); var obj = new { id = 1, name = "jack" }; var json = obj.ToJson(); Console.WriteLine($"Convert an object to josn string:{json}"); Console.WriteLine($"Convert a json string to object:{json.JsonToObject<dynamic>()}"); Console.WriteLine(UtilsExtension.GenerateRandomString(10)); Console.ReadKey(); }
public IActionResult AddMembers(Guid teamId, Guid[] userid) { if (userid.IsEmpty()) { return(JError(T["notspecified_record"])); } var query = new QueryExpression("TeamMembership", CurrentUser.UserSettings.LanguageId); query.ColumnSet.AddColumns("systemuserid"); query.Criteria.AddCondition("teamid", ConditionOperator.Equal, teamId); var members = _dataFinder.RetrieveAll(query); var addEntities = new List <Entity>(); foreach (var item in userid) { if (!members.Any(n => n.GetGuidValue("systemuserid") == item)) { Entity entity = new Entity("TeamMembership"); entity.SetAttributeValue("teamid", teamId); entity.SetAttributeValue("systemuserid", item); addEntities.Add(entity); } } if (addEntities.NotEmpty()) { _dataCreater.CreateMany(addEntities); } return(JOk(T["added_success"])); }
public bool Import(Guid solutionId, List <Domain.SystemForm> systemForms) { if (systemForms.NotEmpty()) { foreach (var item in systemForms) { var entity = _SystemFormFinder.FindById(item.SystemFormId); if (entity != null) { entity.Description = item.Description; entity.FormConfig = item.FormConfig; entity.IsDefault = item.IsDefault; entity.IsCustomButton = item.IsCustomButton; entity.CustomButtons = item.CustomButtons; entity.ModifiedBy = _currentUser.SystemUserId; entity.ModifiedOn = DateTime.Now; entity.Name = item.Name; entity.PublishedOn = DateTime.Now; entity.StateCode = item.StateCode; _SystemFormUpdater.Update(entity, true); } else { item.ComponentState = 0; item.SolutionId = solutionId; item.PublishedOn = DateTime.Now; item.IsCustomizable = true; item.CreatedBy = _currentUser.SystemUserId; _SystemFormCreater.Create(item); } } } return(true); }
public bool Share(Guid entityId, Guid recordId, List <PrincipalObjectAccess> principals, bool ignorePermissions = false) { try { var entityMetadata = _entityFinder.FindById(entityId); var query = new QueryExpression(entityMetadata.Name, _languageId); query.ColumnSet.AllColumns = true; query.Criteria.AddCondition(entityMetadata.Name + "id", ConditionOperator.Equal, recordId); var entity = _dataFinder.Retrieve(query); if (!ignorePermissions) { VerifyEntityPermission(entity, AccessRightValue.Share, entityMetadata); } var attributeMetadatas = _attributeFinder.FindByEntityId(entityMetadata.EntityId); _organizationDataProvider.BeginTransaction(); InternalOnShare(entity, OperationStage.PreOperation, entityMetadata, attributeMetadatas); _principalObjectAccessService.DeleteByObjectId(entityId, recordId); if (principals.NotEmpty()) { foreach (var item in principals) { item.PrincipalObjectAccessId = Guid.NewGuid(); } _principalObjectAccessService.CreateMany(principals); } _organizationDataProvider.CommitTransaction(); InternalOnShare(entity, OperationStage.PostOperation, entityMetadata, attributeMetadatas); return(true); } catch (Exception e) { _organizationDataProvider.RollBackTransaction(); return(OnException(e)); } }
public IActionResult AddUserRoles([FromBody] AddUserRolesModel model) { if (model.UserId.IsEmpty() || model.RoleId.IsEmpty()) { return(NotSpecifiedRecord()); } var userRoles = new List <SystemUserRoles>(); var existsUserRoles = _systemUserRolesService.Query(x => x.Where(f => f.SystemUserId.In(model.UserId) && f.RoleId.In(model.RoleId))); foreach (var uid in model.UserId) { foreach (var rid in model.RoleId) { if (existsUserRoles.Exists(x => x.RoleId == rid && x.SystemUserId == uid)) { continue; } var entity = new SystemUserRoles { SystemUserId = uid, RoleId = rid, SystemUserRoleId = Guid.NewGuid() }; userRoles.Add(entity); } } if (userRoles.NotEmpty()) { _systemUserRolesService.CreateMany(userRoles); } return(SaveSuccess()); }
public bool Import(Guid solutionId, List <RibbonButtonXmlInfo> ribbonButtons) { if (ribbonButtons.NotEmpty()) { foreach (var item in ribbonButtons) { var entity = _ribbonButtonFinder.FindById(item.RibbonButtonId); if (entity != null) { entity.CssClass = item.CssClass; entity.DisplayOrder = item.DisplayOrder; entity.Icon = item.Icon; entity.JsAction = item.JsAction; entity.JsLibrary = item.JsLibrary; entity.Label = item.Label; entity.ShowArea = item.ShowArea; entity.StateCode = item.StateCode; _ribbonButtonUpdater.Update(entity); } else { item.SolutionId = solutionId; item.ComponentState = 0; item.CreatedBy = _appContext.GetFeature <ICurrentUser>().SystemUserId; item.CreatedOn = DateTime.Now; _ribbonButtonCreater.Create(item); } } } return(true); }
public bool CreateMany(IList <ProcessStage> entities) { var result = true; using (UnitOfWork.Build(_processStageRepository.DbContext)) { result = _processStageRepository.CreateMany(entities); foreach (var entity in entities) { //依赖于实体 _dependencyBatchBuilder.Append(WorkFlowDefaults.ModuleName, entity.WorkFlowId, EntityDefaults.ModuleName, entity.EntityId); //依赖于字段 var st = new List <ProcessStep>().DeserializeFromJson(entity.Steps); if (st.NotEmpty()) { var attrNames = st.Select(x => x.AttributeName).ToArray(); var attributes = _attributeFinder.FindByName(entity.EntityId, attrNames); var attrIds = attributes.Select(x => x.AttributeId).ToArray(); _dependencyBatchBuilder.Append(WorkFlowDefaults.ModuleName, entity.WorkFlowId, AttributeDefaults.ModuleName, attrIds); } } _dependencyBatchBuilder.Save(); } return(result); }
public bool Import(Guid solutionId, List <Domain.QueryView> queryViews) { if (queryViews.NotEmpty()) { foreach (var item in queryViews) { var entity = _queryViewFinder.FindById(item.QueryViewId); if (entity != null) { entity.Description = item.Description; entity.FetchConfig = item.FetchConfig; entity.IsDefault = item.IsDefault; entity.StateCode = item.StateCode; entity.LayoutConfig = item.LayoutConfig; entity.IsCustomButton = item.IsCustomButton; entity.CustomButtons = item.CustomButtons; entity.TargetFormId = item.TargetFormId; entity.ModifiedBy = _appContext.GetFeature <ICurrentUser>().SystemUserId; entity.ModifiedOn = DateTime.Now; entity.Name = item.Name; _queryViewUpdater.Update(entity); } else { item.SolutionId = solutionId; item.ComponentState = 0; item.CreatedBy = _appContext.GetFeature <ICurrentUser>().SystemUserId; item.CreatedOn = DateTime.Now; _queryViewCreater.Create(item); } } } return(true); }
public bool Create(int dependentComponentType, Guid dependentObjectId, int requiredComponentType, params Guid[] requiredObjectId) { Guard.NotEmpty(requiredObjectId, nameof(requiredObjectId)); var existEntities = _dependencyRepository.Query(x => x.DependentComponentType == dependentComponentType && x.DependentObjectId == dependentObjectId && x.RequiredComponentType == requiredComponentType && x.RequiredObjectId.In(requiredObjectId))?.ToList(); List <Domain.Dependency> entities = new List <Domain.Dependency>(); foreach (var item in requiredObjectId) { if (item.Equals(Guid.Empty)) { continue; } if (existEntities != null && existEntities.Exists(x => x.DependentComponentType == dependentComponentType && x.DependentObjectId == dependentObjectId && x.RequiredComponentType == requiredComponentType && x.RequiredObjectId == item)) { continue; } var entity = new Domain.Dependency(); entity.DependencyId = Guid.NewGuid(); entity.DependentComponentType = dependentComponentType; entity.DependentObjectId = dependentObjectId; entity.RequiredComponentType = requiredComponentType; entity.RequiredObjectId = item; entities.Add(entity); } if (entities.NotEmpty()) { return(CreateMany(entities)); } return(false); }
private void RefreshView() { List <CreditCardMonthlyData> ul = DBController.DbMoney.Get(new CreditSearchParameters { }); if (ul.NotEmpty()) { var inactiveItems = ul.Where(x => !x.Active).ToList(); if (inactiveItems.NotEmpty()) { var avg = inactiveItems.Average(x => x.TotalSpent); txp1.Text = avg.ToInteger().FormattedString(); txp2.Text = inactiveItems.Average(x => x.DaylyValue.ToInteger()).ToInteger().FormattedString(); } var current = DBController.DbMoney.Get(new CreditSearchParameters { Month = DateTime.Now }).FirstOrDefault(); if (current != null) { txp3.Text = current.MonthlyPrediction.ToInteger().FormattedString(); } } RefreshGrid(gv); }
private void streamController() { while (!isDisposed && Auth_token == null) { Thread.Sleep(1000); } long lastTimestamp = 0; long nowTimestamp = 0; int frameCounter = 0; while (!isDisposed) { nowTimestamp = DateTime.Now.Ticks; int refreshRate = NanoleafPlugin.RefreshRate.Limit(10, 60); double milliSinceLast = ((double)(nowTimestamp - lastTimestamp)) / TimeSpan.TicksPerMillisecond; double frameDuration = (1000 / refreshRate); if (milliSinceLast < frameDuration) { if (milliSinceLast > frameDuration * 2) { log.Warn($"Streaming-Thread last send {milliSinceLast}ms"); } Thread.SpinWait(10); } else { lastTimestamp = DateTime.Now.Ticks; if (frameCounter >= refreshRate)//KeyFrame every 1s { lock (changedPanels) { changedPanels.Clear(); frameCounter = 0; if (panels.NotEmpty()) { Communication.SendUDPCommand(externalControlInfo, Communication.CreateStreamingData(panels)); } } } else if (externalControlInfo != null)//DeltaFrame { Panel[] _panels = new Panel[0]; lock (changedPanels) { if (!changedPanels.Empty()) { _panels = changedPanels.ToArray(); changedPanels.Clear(); } } if (_panels.Length > 0) { Communication.SendUDPCommand(externalControlInfo, Communication.CreateStreamingData(_panels)); } } frameCounter++; } } }
public String PackageValidationException() { var entities = ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified).Select(l => l); string exceptionString = "ValidationException" + Environment.NewLine; foreach (var entity in entities) { var validationContext = new ValidationContext(entity); var validationResults = new List <ValidationResult>(); Validator.TryValidateObject( entity.Entity, validationContext, validationResults: validationResults, validateAllProperties: true); if (validationResults.NotEmpty()) { exceptionString += entity.GetType().Name + Environment.NewLine; foreach (var result in validationResults) { exceptionString += result.ErrorMessage + Environment.NewLine; } } } return(exceptionString); }
private void ValidateConnections() { List <StratusTriggerBase> disconnected = new List <StratusTriggerBase>(); foreach (var t in triggers) { if (!IsConnected(t)) { disconnected.Add(t); } } foreach (var t in triggerables) { if (!IsConnected(t)) { disconnected.Add(t); } } if (disconnected.NotEmpty()) { string msg = $"Triggers marked as disconnected ({disconnected.Count}):"; foreach (var t in disconnected) { msg += $"\n- {t.GetType().Name} : <i>{t.description}</i>"; } AddMessage(msg, UnityEditor.MessageType.Warning, null); } }
/// <summary> /// 获取过滤条件 /// </summary> /// <param name="queryText"></param> /// <param name="p"></param> /// <param name="otherCondition"></param> /// <returns></returns> public static Sql GetConditions(string queryText, List <QueryParameter> p, Sql otherCondition = null) { //过滤条件 Sql filter = Sql.Builder; if (queryText.IsNotEmpty() && p.NotEmpty()) { var values = p.Select(n => n.Value).ToArray(); //AnsiString int i = 0; foreach (var item in values) { if (item is string) { values[i] = new AnsiString(item.ToString()); } i++; } filter.Append("WHERE"); filter.Append(queryText, values); } if (otherCondition != null && otherCondition.SQL.IsNotEmpty()) { if (filter.SQL.IsEmpty()) { filter.Append("WHERE"); } filter.Append(otherCondition); } return(filter); }
public override void Select() { if (buttons.NotEmpty()) { buttons.First().Select(); } }
public static void RemoveLast <T>(this List <T> list) { if (list.NotEmpty()) { list.RemoveAt(list.Count - 1); } }
static void Main(string[] args) { string s = "42,12"; List <int> list = new List <int>() { 4, 4, 5, 61, 1 }; List <int> list2 = new List <int>() { 1, 4, 5, 1, 8 }; HashSet <int> set = new HashSet <int>(list); HashSet <int> set2 = new HashSet <int>(list2); ConcurrentBag <int> bag = new ConcurrentBag <int>(list2); var e = set.Union(bag); Console.WriteLine(bag.Count(1)); Console.WriteLine("Hello Extension Methods!"); Console.WriteLine(list.IncludesAll(list2)); Console.WriteLine(list.NotEmpty()); var temp = list.SelectOcl(e => e > 4); Console.WriteLine(temp.Count); temp.Println(); }
public void Should_Be_Empty() { IEnumerable <int> values = new List <int>(); bool result = values.NotEmpty(); Assert.False(result); }
/// <summary> /// 获取最后一个对象 /// </summary> public static T _GetLast <T>(this List <T> list) { if (list.NotEmpty()) { return(list[list.Count - 1]); } return(default(T)); }
private static bool HasValidValues(List <string> values) { if (!values.NotEmpty <string>()) { return(false); } return(values.Any <string>(str => !string.IsNullOrEmpty(str))); }
public void ReSet() { this.TokenList.Clear(); this.Expressions.Clear(); if (ErrorList.NotEmpty()) { ErrorList.Clear(); } }
private void OnGUI() { if (cmds.NotEmpty()) { CommandHandler hdl = new IMUIHandler(transform as RectTransform); hdl.commands = cmds; hdl.Execute(); } }
/// <summary> /// 删除记录 /// </summary> /// <param name="ids">主键</param> /// <returns></returns> public bool DeleteMany(List <Guid> ids) { if (ids.NotEmpty()) { List <object> values = ids.Select(n => (object)n).ToList(); var result = _repository.DeleteMany(values); return(result); } return(false); }
public IActionResult SaveRolePermissions([FromBody] EditRolePermissionsModel model) { var resourceOwner = _resourceOwnerService.FindByName(model.ResourceName); if (resourceOwner == null) { return(NotFound()); } var Role = _roleService.FindById(model.RoleId); if (Role.Name.IsCaseInsensitiveEqual(RoleDefaults.ADMINISTRATOR)) { return(JError(T["notallow_edit"])); } if (ModelState.IsValid) { _roleObjectAccessService.DeleteByRole(model.RoleId, resourceOwner.ModuleName); if (model.ObjectId.NotEmpty()) { List <RoleObjectAccess> roleObjectAccess = new List <RoleObjectAccess>(); var objectTypeCode = Module.Core.ModuleCollection.GetIdentity(resourceOwner.ModuleName); int i = 0; foreach (var item in model.ObjectId) { var roa = new RoleObjectAccess { RoleObjectAccessId = Guid.NewGuid(), RoleId = model.RoleId, ObjectId = item, ObjectTypeCode = objectTypeCode }; if (model.Mask == null) { roa.AccessRightsMask = 1; } else if (model.Mask != null && model.Mask[i] > 0) { roa.AccessRightsMask = (int)model.Mask[i]; } if (roa.AccessRightsMask > 0 && !roleObjectAccess.Exists(x => x.ObjectId == item && x.ObjectTypeCode == objectTypeCode)) { roleObjectAccess.Add(roa); } i++; } if (roleObjectAccess.NotEmpty()) { _roleObjectAccessService.CreateMany(roleObjectAccess); } } return(SaveSuccess()); } return(SaveFailure(GetModelErrors())); }
public bool UpdateUserRoles(Guid systemUserId, List <SystemUserRoles> roles) { var userroles = Query(q => q.Where(f => f.SystemUserId == systemUserId)); DeleteById(userroles.Select(f => f.SystemUserRoleId).ToList()); if (roles.NotEmpty()) { return(CreateMany(roles)); } return(false); }
public static T[] GetComponentsInChildrenNotIncludeSelf <T>(this Component component, bool includeInactive) where T : Component { List <T> result = new List <T>(component.GetComponentsInChildren <T>(includeInactive)); if (result.NotEmpty() && result[0].transform == component.transform) { result.RemoveFirst(); } return(result.ToArray()); }
private void DrawContextMenu(StratusEditorUtility.ContextMenuType type, List <MenuOption> options) { if (options.NotEmpty()) { var menu = new GenericMenu(); foreach (var option in options) { menu.AddItem(option.content, false, option.menuFunction); } StratusEditorUtility.DrawContextMenu(menu, type); } }
public static PathFigure PathFigureFromPoints(IEnumerable<Point> points, bool isClosed) // REVIEW: General utility, should be elsewhere { List<Point> pathPoints = new List<Point>(points); Point ptFirst = new Point(); if (pathPoints.NotEmpty()) { ptFirst = pathPoints[0]; pathPoints.RemoveAt(0); } // PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = ptFirst; pathFigure.IsClosed = isClosed; // if (pathPoints.NotEmpty()) { PolyLineSegment polyLineSegment = new PolyLineSegment(); polyLineSegment.Points = new PointCollection(pathPoints); pathFigure.Segments.Add(polyLineSegment); } // return pathFigure; }
GraphComponent ComposeRendering(GraphComponent component, Strand strand, double y0 = 0) // We render a strand as a linear sequence of spring-separated particles. // We initially lay things out in a linear line, either to the right (for // normally oriented strands) or left (for reverse oriented strands). { if (null==component) component = new GraphComponent(this); // // Compose edges for domains along the strand backbone // List<GraphVertex> strandVertices = new List<GraphVertex>(); List<GraphEdge> strandEdges = new List<GraphEdge>(); // double count = strand.AllDomains().Count(); double length = strand.AllDomains().Sum(d => this.EdgeFromDomain(component, d).PreferredLength); double radius = length / 2.0 / Math.PI; // radius /= 3; // hack -> otherwise the forces pulling the circle together overshoot // int i = 0; foreach (Domain d in strand.AllDomains()) { GraphEdge edge = this.EdgeFromDomain(component, d); strandEdges.Add(edge); // // The first vertex in the strand needs to be explicitly positioned // double x,y; // if (strandVertices.IsEmpty()) { strandVertices.Add(edge.A); if (strand.IsCircular) x = strand.Orientation==Strand.Direction.FiveToThree ? -radius : radius; else x = 0; edge.A.SetLocation(x,y0); } // // Position the B vertex of the edge // if (strand.IsCircular) { double theta = i / count * 2 * Math.PI; x = radius * Math.Cos(theta); y = radius * Math.Sin(theta); if (strand.Orientation==Strand.Direction.FiveToThree) { x = -x; y = -y; } } else { y = y0; x = edge.PreferredLength; if (strand.Orientation == Strand.Direction.ThreeToFive) x = -x; x += strandVertices.Last().Location.X; } // edge.B.SetLocation(x, y); strandVertices.Add(edge.B); // i++; } // // Make a spline for the strand as a whole // if (strandVertices.NotEmpty()) { VisualStrand vStrand = new VisualStrand(strand, component, strandEdges, strandVertices); this.mpStrandVisualization[strand] = vStrand; // // Place ticks at the ends of each of the interior domains in the strand // for (i = strand.IsCircular ? 0 : 1; i < strandVertices.Count-1; i++) { new VisualDomainEndTick(component, vStrand, i, Constants.DomainEndLength); } // // Add domain labels and nucleotides // foreach (Domain d in strand.AllDomains()) { i = d.StrandIndex; // VisualStrandLabel label = new VisualStrandLabel(component, vStrand, i, i+1, d.FullDisplayName, Constants.StyleDomainLabel); label.LabelType = VisualStrandLabel.LABELTYPE.DOMAIN; vStrand.NoteDomainLabel(i, label); // if (d.Nucleotides.Length > 0 && true) { label = new VisualStrandLabel(component, vStrand, i, i+1, d.Nucleotides, Constants.StyleNucleotides); label.LabelType = VisualStrandLabel.LABELTYPE.NUCLEOTIDE; label.FontVerticallyCentered = true; label.AutoReverseText = true; } } } // if (strandVertices.NotEmpty()) { // Help a bit with initial placement: left align if we moved leftward // from zero due to strand direction. // if (!strand.IsCircular && strand.Orientation == Strand.Direction.ThreeToFive) { double dx = -strandVertices.Last().Location.X; foreach (GraphVertex v in strandVertices) { v.TranslateBy(dx, 0); } } } // // Put in stiffness along the strand // foreach (Domain d in strand.AllDomains()) { if (d.CircularNextTo5 != null) { GraphEdge curEdge = this.EdgeFromDomain(component, d); GraphEdge prevEdge = this.EdgeFromDomain(component, d.CircularNextTo5); // new StraighteningForce(component, prevEdge.A, curEdge.A, curEdge.B, Constants.StraighteningStrength); } } // return component; }