protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter("[property_type]=1"); yield return new CommandFilter(string.Format("[cube_name]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption )); yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption , filters.Single(f => f.Target == Target.Hierarchies).Caption )); yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption , filters.Single(f => f.Target == Target.Hierarchies).Caption , filters.Single(f => f.Target == Target.Levels).Caption )); var filter = filters.SingleOrDefault(f => f.Target == Target.Properties); if (filter!=null) yield return new CommandFilter(string.Format("[property_caption]='{0}'" , filter.Caption )); }
public MessageBrokerConnection(IEnumerable<KeyValuePair<string, string>> rabbitEnvironment) { this.Server = rabbitEnvironment.Single(kvp => kvp.Key == "RabbitMQServer").Value; this.Port = Convert.ToInt32(rabbitEnvironment.Single(kvp => kvp.Key == "RabbitMQPort").Value, CultureInfo.InvariantCulture); this.VHost = rabbitEnvironment.Single(kvp => kvp.Key == "RabbitMQVHost").Value; this.Connection = this.CreateConnection(); this.Connection.ConnectionShutdown += Connection_ConnectionShutdown; }
public static GameStatus CreateFromEntity(Entity.Game entity, IEnumerable<Player> players) { return new Model.GameStatus( players.Single(x => x.ID == entity.CurrentPlayerID), players.Single(x => x.ID != entity.CurrentPlayerID), players.FirstOrDefault(x => x.ID == entity.WinnerID), entity.Active, Model.GameMove.Empty, Model.GameMoveResultType.Nothing, null, null); }
protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter(string.Format("[routine_schema]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); var filter = filters.SingleOrDefault(f => f.Target == Target.Routines); if (filter != null) yield return new CommandFilter(string.Format("[routine_name]='{0}'" , filters.Single(f => f.Target == Target.Routines).Caption )); }
public static ResourceSet GetResourceSet(IEnumerable<PlanetResource> resources) { var metal = resources.Single(r => r.ResourceId == (int)ResourceItem.Metal); var crystal = resources.Single(r => r.ResourceId == (int)ResourceItem.Crystal); var deiterium = resources.Single(r => r.ResourceId == (int)ResourceItem.Deiterium); return new ResourceSet { Metal = metal, Crystal = crystal, Deiterium = deiterium }; }
public static KpisViewModel FromQueryModel(IEnumerable<Kpi> data) { if (data == null || data.Count() == 0) return new KpisViewModel(); return new KpisViewModel() { Employees = data.Single(i => i.Id == "Employees").Value, GrossPay = data.Single(i => i.Id == "GrossPay").Value, Benefits = data.Single(i => i.Id == "Benefits").Value, NetPay = data.Single(i => i.Id == "NetPay").Value }; }
protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter("len(measuregroup_name)>0"); yield return new CommandFilter(string.Format("[cube_name]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); var mgFilter = filters.SingleOrDefault(f => f.Target == Target.MeasureGroups); if (mgFilter != null) yield return new CommandFilter(string.Format("[measuregroup_name]='{0}'" , filters.Single(f => f.Target == Target.MeasureGroups).Caption )); }
protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter(string.Format("[table_schema]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); yield return new CommandFilter(string.Format("[table_name]='{0}'" , filters.Single(f => f.Target == Target.Tables).Caption )); yield return new CommandFilter(string.Format("[column_name]='{0}'" , filters.Single(f => f.Target == Target.Columns).Caption )); }
public static Position GetCentralPosition(IEnumerable<Position> geoCoordinates) { if (geoCoordinates.Count() == 1) { return geoCoordinates.Single (); } double x = 0; double y = 0; double z = 0; foreach (var geoCoordinate in geoCoordinates) { var latitude = geoCoordinate.Latitude * Math.PI / 180; var longitude = geoCoordinate.Longitude * Math.PI / 180; x += Math.Cos (latitude) * Math.Cos (longitude); y += Math.Cos (latitude) * Math.Sin (longitude); z += Math.Sin (latitude); } var total = geoCoordinates.Count(); x = x / total; y = y / total; z = z / total; var centralLongitude = Math.Atan2 (y, x); var centralSquareRoot = Math.Sqrt (x * x + y * y); var centralLatitude = Math.Atan2 (z, centralSquareRoot); return new Position ( centralLatitude * 180 / Math.PI, centralLongitude * 180 / Math.PI ); }
/// <summary> /// Gets the effective domain name of an OrgUnit, based on it's own CustomUrl or it's ancestry. /// </summary> /// <param name="orgUnitId">The org unit id.</param> /// <param name="associations">The associations.</param> /// <returns></returns> public static string GetDomainName(int orgUnitId, IEnumerable<OrgUnitAssociationDto> associations) { var association = associations.SingleOrDefault(a => a.SecondaryId == orgUnitId); if (association != null) { var url = association.SecondaryCustomUrl; if (string.IsNullOrEmpty(url)) { while (association.HasAscendant) { var ascendant = associations.Single(a => a.SecondaryId == association.PrimaryId); if (!string.IsNullOrEmpty(ascendant.SecondaryCustomUrl)) { url = ascendant.SecondaryCustomUrl; break; } association = ascendant; } } if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) { return new Uri(url).Host; } } return string.Empty; }
IEnumerable<Price> IMarketPriceRepository.FetchPrices(IEnumerable<Item> items, SolarSystem system) { string urlData = ""; foreach (Item item in items) { urlData += "typeid=" + item.ApiId + "&"; } urlData += "usesystem=" + system.ApiId; XDocument doc = XDocument.Load(String.Format(String.Format(_priceURL, urlData))); IEnumerable<XElement> itemElements = doc.Element("evec_api").Element("marketstat").Elements("type"); IList<Price> prices = new List<Price>(); foreach (XElement itemElement in itemElements) { string itemApi = itemElement.Attribute("id").Value; Item currentItem = items.Single(i => i.ApiId.Equals(itemApi)); Price price = new Price { Item = currentItem, SolarSystem = system, Buy = Double.Parse(itemElement.Element("buy").Element("max").Value, CultureInfo.InvariantCulture), Sell = Double.Parse(itemElement.Element("sell").Element("min").Value, CultureInfo.InvariantCulture), Date = DateTime.Today }; prices.Add(price); } return prices.AsEnumerable(); }
public Expr Convolute(IContext context, IEnumerable<Expr> args) { var arg = args.Single(); return EvalConvolution(arg) ?? ConstantConvolution(arg) ?? SpecificConvolution(context, arg); }
public void UpdateSession(IEnumerable<EventSourceSettings> updatedEventSources) { Guard.ArgumentNotNull(updatedEventSources, "updatedEventSources"); var eventSourceComparer = new EventSourceSettingsEqualityComparer(nameOnly: true); // updated sources foreach (var currentSource in this.eventSources.Intersect(updatedEventSources, eventSourceComparer).ToArray()) { var updatedSource = updatedEventSources.Single(s => s.Name == currentSource.Name); if (updatedSource.Level != currentSource.Level || updatedSource.MatchAnyKeyword != currentSource.MatchAnyKeyword) { TraceEventUtil.EnableProvider(this.session, updatedSource.EventSourceId, updatedSource.Level, updatedSource.MatchAnyKeyword, sendManifest: false); currentSource.Level = updatedSource.Level; currentSource.MatchAnyKeyword = updatedSource.MatchAnyKeyword; } } // new sources foreach (var newSource in updatedEventSources.Except(this.eventSources, eventSourceComparer).ToArray()) { TraceEventUtil.EnableProvider(this.session, newSource.EventSourceId, newSource.Level, newSource.MatchAnyKeyword, sendManifest: true); this.eventSources.Add(newSource); } // removed sources foreach (var removedSource in this.eventSources.Except(updatedEventSources, eventSourceComparer).ToArray()) { this.session.DisableProvider(removedSource.EventSourceId); this.eventSources.Remove(removedSource); } }
public static void WriteSchedule(this ITestOutputHelper output, IEnumerable <Assignment> assignments, IEnumerable <Session> sessions) { var names = new Dictionary <int, string>(); foreach (var s in sessions) { names.Add(s.Id, s.Name); } var timeslots = assignments.Select(a => a.TimeslotId).Distinct().OrderBy(a => a); var rooms = assignments.Select(a => a.RoomId).Distinct().OrderBy(a => a); var result = new StringBuilder(); result.Append("R\\T\t|\t"); foreach (var timeslot in timeslots) { result.Append($"{timeslot.ToString().PadRight(15, ' ')}\t"); } result.AppendLine(); result.AppendLine("---------------------------------------------------------------------------"); foreach (var room in rooms) { result.Append($"{room}\t|\t"); foreach (var timeslot in timeslots) { if (assignments.Count(a => a.RoomId == room && a.TimeslotId == timeslot) > 1) { throw new ArgumentException($"Multiple assignments to room {room} and timeslot {timeslot}."); } else { string name; var session = assignments.Where(a => a.RoomId == room && a.TimeslotId == timeslot).SingleOrDefault(); if (session == null) { name = "(empty)".PadRight(15); } else if (names == null) { name = session.SessionId.ToString().PadRight(15); } else { var fullName = names.Single(n => n.Key == session.SessionId).Value; var currentSession = sessions?.Single(s => s.Id == session.SessionId); name = $"{fullName.Substring(0, Math.Min(fullName.Length, 10)).PadRight(10)} ({ (currentSession == null ? session.SessionId.Value : currentSession.TopicId)})"; } result.Append($"{name}\t"); } } result.AppendLine(); } output.WriteLine(result.ToString()); }
private void EnsureNonDuplicationOfParty(IEnumerable<DataCollectionParty> dataCollectionParties) { var newUrdmsParties = (from o in dataCollectionParties where o.Party.Id < 1 && !string.IsNullOrWhiteSpace(o.Party.UserId) select o.Party).ToList(); if (newUrdmsParties.Count != 0) { var parties = _session.QueryOver<Party>().List(); foreach (var newUrdmsParty in newUrdmsParties) { var key = newUrdmsParty.UserId; var existingParty = parties.Where(o => o.UserId == key).Take(1).FirstOrDefault(); if (existingParty != null) { existingParty.FirstName = newUrdmsParty.FirstName; existingParty.LastName = newUrdmsParty.LastName; existingParty.FullName = newUrdmsParty.FullName; existingParty.Email = newUrdmsParty.Email; var dataCollectionParty = dataCollectionParties.Single(o => o.Party.UserId == key); dataCollectionParty.Party = existingParty; } } } }
public ParameterSetResolver(Object target, IEnumerable<ParameterSet> parameterSets) { if (target == null) { throw Logger.Fatal.ArgumentNull(nameof(target)); } if (parameterSets == null) { throw Logger.Fatal.ArgumentNull(nameof(parameterSets)); } if (!parameterSets.Any()) { throw Logger.Fatal.ArgumentEmptySequence(nameof(parameterSets)); } DefaultParameterSet = parameterSets.Single( set => set.IsDefault ); ParameterSets = parameterSets.ToImmutableDictionary( set => set.Name, ParameterSet.NameComparer ); Target = target; }
public override object SetIndex(Func<object> proceed, dynamic self, IEnumerable<object> keys, object value) { if (keys.Count() == 1) { var name = keys.Single().ToString(); if (name.Equals("Id")) { // need to mutate the actual type var s = self as Shape; if (s != null) { s.Id = System.Convert.ToString(value); } return value; } if (name.Equals("Classes")) { var args = Arguments.From(new[] { value }, Enumerable.Empty<string>()); MergeClasses(args, self.Classes); return value; } if (name.Equals("Attributes")) { var args = Arguments.From(new[] { value }, Enumerable.Empty<string>()); MergeAttributes(args, self.Attributes); return value; } if (name.Equals("Items")) { var args = Arguments.From(new[] { value }, Enumerable.Empty<string>()); MergeItems(args, self); return value; } } return proceed(); }
private void UpdateMenuCommandShortcutKeyDisplayString(IEnumerable<MenuCommand> targetList, IEnumerable<MenuCommand> sourceList) { foreach (var sourceMc in sourceList.Where(mc => !mc.IsSeparator)) { var targetMc = targetList.Single(mc => !mc.IsSeparator && mc.Name == sourceMc.Name); targetMc.ShortcutKeyDisplayString = sourceMc.ShortcutKeyDisplayString; } }
private string ReadAcceptType(IEnumerable<string> header) { if (header == null || header.Count() == 0) return "*/*"; if (header.Count() == 1) return header.Single(); return header.Join(", "); }
public void DefaultUkIfUnselected(IEnumerable<CountryData> countries) { if (Address != null && !Address.CountryId.HasValue) { Address.CountryId = countries.Single(c => c.Name.Equals("United Kingdom", StringComparison.InvariantCultureIgnoreCase)).Id; } }
private Card TrashAndDiscard(TurnContext context, RevealZone revealZone, IEnumerable<ITreasureCard> revealedTreasures) { var trashedCard = revealedTreasures.Single(); trashedCard.MoveTo(context.Game.Trash); context.Game.Log.LogTrash(revealZone.Owner, trashedCard); revealZone.MoveAll(revealZone.Owner.Discards); return (Card) trashedCard; }
private static RuntimeTransition BuildRuntimeTransition(IEnumerable <RuntimeStateBase> runtimeStates, Transition transition) { return(new RuntimeTransition( transition.Name, runtimeStates?.Single(s => s.Name == transition.Target.Name), transition.Action, null)); }
public override bool CallEquals(IEnumerable<Expression> Arguments, Expression E) { if (base.CallEquals(Arguments, E)) return true; MatchContext m = LogE.Matches(E); return m != null && m[x].Equals(Arguments.Single()); }
private static RuntimeTransition BuildExternalRuntimeTransition(IEnumerable <RuntimeStateBase> runtimeStates, ExternalTransition transition) { return(new RuntimeTransition( transition.Name, runtimeStates?.Single(s => s.Name == transition.Target.Name), transition.Action, transition.Guard)); }
static IOperation VerifySingleMatch(IEnumerable<IOperation> operations) { if (operations == null) return null; if (operations.Count() > 1) throw new AmbiguousRequestException(operations); return operations.Single(); }
public IVirtualMachine Attach(IEnumerable<KeyValuePair<string, IConnectorArgument>> arguments) { var pid = (IConnectorIntegerArgument)arguments.Single(i => i.Key == "pid").Value; var sourcePaths = (IConnectorStringArgument)arguments.SingleOrDefault(i => i.Key == "sourcePaths").Value; VirtualMachine virtualMachine = VirtualMachine.BeginAttachToProcess(pid.Value, sourcePaths.StringValue.Split(';')); virtualMachine.AttachComplete += OnAttachComplete; return virtualMachine; }
private static void CompareCollections(IEnumerable<KeyValuePair<string, string>> first, IEnumerable<KeyValuePair<string, string>> second) { foreach (var pair in second) { string expected = first.Single(x => x.Key == pair.Key).Value; Assert.Equal(expected, pair.Value); } }
public Expression Bind(ProjectionExpression projection, ProjectionBindingContext context, MethodCallExpression node, IEnumerable<Expression> arguments) { return new ProjectionExpression( new SkipExpression( projection.Source, (int)((ConstantExpression)arguments.Single()).Value), projection.Projector, projection.Aggregator); }
public static Maybe<object> ChangeType(IEnumerable<string> values, Type conversionType, bool scalar, CultureInfo conversionCulture) { if (values == null) throw new ArgumentNullException("values"); if (conversionType == null) throw new ArgumentNullException("conversionType"); if (conversionCulture == null) throw new ArgumentNullException("conversionCulture"); return scalar ? ChangeType(values.Single(), conversionType, conversionCulture) : ChangeType(values, conversionType, conversionCulture); }
private static void CompareCollections(IEnumerable<KeyValuePair<string,string>> info, NameValueCollection error) { foreach (string key in error.Keys) { string expected = info.Single(x => x.Key == key).Value; string actual = error[key]; Assert.Equal(expected, actual); } }
private static JProperty GetProperty(string packageName, IEnumerable<string> versions) { if (versions.Count() == 1) { return GetProperty(new NuGetPackage(packageName, versions.Single())); } var content = JArray.FromObject(versions.ToArray()); return new JProperty(packageName, content); }
private static IEnumerable<MetaColumn> SortColumns(MetaTable table, IEnumerable<MetaColumn> columns) { string[] order; if (!SortOrders.TryGetValue(table.Name, out order)) { order = new string[0]; } return Enumerable.Concat( order.Select(s => columns.Single(c => String.Equals(c.Name, s))), columns.Where(c => !order.Contains(c.Name))); }
private string GetClaimValue(IEnumerable <Claim> claims, string claimType) { try { return(claims?.Single(claim => claim.Type == claimType).Value); } catch { return(null); } }
public static void AssertItemWithErrorStatus(IEnumerable<ItemType> itemsType, Type expectedType, string expectedMessageChunk) { Assert.IsNotNull(itemsType, "The return of GetItemsToCollect cannot be null."); Assert.AreEqual(1, itemsType.Count(), "Unexpected quantity of generated items."); var systemItem = itemsType.Single(); Assert.IsInstanceOfType(systemItem, expectedType, "Unxpected generated item type was found."); Assert.AreEqual(StatusEnumeration.error, systemItem.status, "An unexpected item status was found."); Assert.IsNotNull(systemItem.message, "The Entity Item Message Type cannot be null"); Assert.IsTrue(systemItem.message.First().Value.Contains(expectedMessageChunk), string.Format("The exception message cannot be found in entity item message. Found message: '{0}'", systemItem.message.First().Value)); }
// FIX ME: Shall we return an instance with no ctorArgs or explicitly fail when properties is null? private static VersionVariables FromDictionary(IEnumerable <KeyValuePair <string, string> >?properties) { var type = typeof(VersionVariables); var constructors = type.GetConstructors(); var ctor = constructors.Single(); var ctorArgs = ctor.GetParameters() .Select(p => properties?.Single(v => string.Equals(v.Key, p.Name, StringComparison.InvariantCultureIgnoreCase)).Value) .Cast <object>() .ToArray(); return((VersionVariables)Activator.CreateInstance(type, ctorArgs)); }
/// <summary> /// Synchronizes the sevDesk contacts and the Exchange contacts of a single user. /// </summary> /// <param name="syncStates">The sync states of the last synchronization.</param> /// <param name="exchangeUserId">The ID of the exchange user.</param> /// <param name="contactCategoryIds">The sevDesk categories of contacts that should be synchronized.</param> /// <param name="progress">The progress that emits status messages.</param> /// <returns>Returns the new sync states.</returns> private async Task <IEnumerable <ContactSyncState> > SynchronizeContactsAsync(IEnumerable <ContactSyncState> syncStates, string exchangeUserId, IEnumerable <string> contactCategoryIds, IProgress <string> progress) { // Initialiezs new the sync states List <ContactSyncState> newSyncStates = new List <ContactSyncState>(); // Gets the sevDesk contacts and Exchange contacts List <SevDesk.Contacts.Person> sevDeskContacts = (await this.GetSevDeskContactsAsync(contactCategoryIds)).ToList(); List <Exchange.Contacts.Contact> exchangeContacts = (await this.GetExchangeContactsAsync(exchangeUserId)).ToList(); // Creates contacts that do not exist in Exchange yet foreach (SevDesk.Contacts.Person sevDeskContact in sevDeskContacts.Where(sevDeskContact => !syncStates.Any(state => state.SevDeskContactId == sevDeskContact.Id) || syncStates.Any(state => state.SevDeskContactId == sevDeskContact.Id && !exchangeContacts.Any(exchangeContact => state.ExchangeContactId == exchangeContact.Id))).ToList()) { // Creates the contact in Exchange progress.Report($"Adding new contact to Exchange (sevDESK user with ID \"{sevDeskContact.Id}\")."); Exchange.Contacts.Contact newContact = await this.ExchangeService.CreateContactAsync(exchangeUserId, new Exchange.Contacts.ContactOptions { LastName = sevDeskContact.LastName, FirstName = sevDeskContact.FirstName }); // Synchronizes the data from sevDesk to Exchange newSyncStates.Add(await this.SynchronizeContactFromSevDeskToExchangeAsync(sevDeskContact, exchangeUserId, newContact.Id)); // Removes the contact from the list sevDeskContacts.Remove(sevDeskContact); } // Removes the contacts that no longer exist in sevDesk foreach (Exchange.Contacts.Contact exchangeContact in exchangeContacts.Where(exchangeContact => syncStates.Any(state => state.ExchangeContactId == exchangeContact.Id && !sevDeskContacts.Any(sevDeskContact => state.SevDeskContactId == sevDeskContact.Id))).ToList()) { // Removes the contact from Exchange progress.Report($"Removing contact from Exchange (Exchange user with ID \"{exchangeContact.Id}\")."); await this.ExchangeService.RemoveContactAsync(exchangeUserId, exchangeContact.Id); // Removes the contact from the lsit exchangeContacts.Remove(exchangeContact); } // Cycles over all contacts and checks for updates foreach (SevDesk.Contacts.Person sevDeskContact in sevDeskContacts) { // Gets the sync state and the exchange contact ContactSyncState contactSyncState = syncStates.Single(state => state.SevDeskContactId == sevDeskContact.Id); Exchange.Contacts.Contact exchangeContact = exchangeContacts.Single(contact => contact.Id == contactSyncState.ExchangeContactId); // Checks if both contacts have not changed if (contactSyncState.SevDeskContactUpdateDateTime == sevDeskContact.UpdateDateTime && contactSyncState.ExchangeContactLastModifiedDateTime == exchangeContact.LastModifiedDateTime) { progress.Report($"No changes for contact (sevDesk user with ID \"{sevDeskContact.Id}\", Exchange user with ID \"{exchangeContact.Id}\")."); newSyncStates.Add(contactSyncState); continue; } // Checks if the sevDesk contact changed, but the Exchange contact did not if (contactSyncState.SevDeskContactUpdateDateTime != sevDeskContact.UpdateDateTime && contactSyncState.ExchangeContactLastModifiedDateTime == exchangeContact.LastModifiedDateTime) { progress.Report($"Synchronizing from sevDesk to Exchange (sevDesk user with ID \"{sevDeskContact.Id}\", Exchange user with ID \"{exchangeContact.Id}\")."); newSyncStates.Add(await this.SynchronizeContactFromSevDeskToExchangeAsync(sevDeskContact, exchangeUserId, exchangeContact.Id)); continue; } // Checks if the Exchange contact changed, but the sevDesk contact did not if (contactSyncState.SevDeskContactUpdateDateTime == sevDeskContact.UpdateDateTime && contactSyncState.ExchangeContactLastModifiedDateTime != exchangeContact.LastModifiedDateTime) { progress.Report($"Synchronizing from Exchange to sevDesk (sevDesk user with ID \"{sevDeskContact.Id}\", Exchange user with ID \"{exchangeContact.Id}\")."); newSyncStates.Add(await this.SynchronizeContactFromExchangeToSevDeskAsync(exchangeUserId, exchangeContact, sevDeskContact)); continue; } // As both contacts changed, checks which one is newer if (sevDeskContact.UpdateDateTime > exchangeContact.LastModifiedDateTime) { progress.Report($"Synchronizing from sevDesk to Exchange (sevDesk user with ID \"{sevDeskContact.Id}\", Exchange user with ID \"{exchangeContact.Id}\")."); newSyncStates.Add(await this.SynchronizeContactFromSevDeskToExchangeAsync(sevDeskContact, exchangeUserId, exchangeContact.Id)); } else { progress.Report($"Synchronizing from Exchange to sevDesk (sevDesk user with ID \"{sevDeskContact.Id}\", Exchange user with ID \"{exchangeContact.Id}\")."); newSyncStates.Add(await this.SynchronizeContactFromExchangeToSevDeskAsync(exchangeUserId, exchangeContact, sevDeskContact)); } } // Returns the new sync states return(newSyncStates); }
public AbstractQuotaMonitor(IQuotaRepository quotaRepository, IEnumerable <IQuotaConfig> configs, string type) { _quotaRepository = quotaRepository; _config = configs.Single(x => x.Type == type); Type = type; }
public TObj GetScalar() { return(_foundObjects.Single()); }
public void FilesOfClassTest() { Assert.AreEqual(1, assembliesWithoutPreprocessing.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.TestClass").Files.Count(), "Wrong number of files"); Assert.AreEqual(2, assembliesWithoutPreprocessing.Single(a => a.Name == "Test").Classes.Single(c => c.Name == "Test.PartialClass").Files.Count(), "Wrong number of files"); }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { TypeDef runtimeType = context.Registry.GetService <IRuntimeService>().GetRuntimeType("Confuser.Runtime.ModuleFlood"); IMarkerService service = context.Registry.GetService <IMarkerService>(); INameService service2 = context.Registry.GetService <INameService>(); foreach (ModuleDef moduleDef in parameters.Targets.OfType <ModuleDef>()) { var r = new Random(DateTime.Now.Millisecond); IEnumerable <IDnlibDef> enumerable = Core.Helpers.InjectHelper.Inject(runtimeType, moduleDef.GlobalType, moduleDef); MethodDef methodDef = moduleDef.GlobalType.FindStaticConstructor(); for (int i = 0; i < r.Next(100, 200); i++) { methodDef.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, (MethodDef)enumerable.Single((IDnlibDef method) => method.Name == "Initialize"))); } foreach (IDnlibDef def in enumerable) { service2.MarkHelper(def, service, (Protection)base.Parent); } } }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var rt = context.Registry.GetService <IRuntimeService>(); var marker = context.Registry.GetService <IMarkerService>(); var name = context.Registry.GetService <INameService>(); foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>()) { AntiMode mode = parameters.GetParameter(context, module, "mode", AntiMode.Ultimate); TypeDef rtType; TypeDef attr = null; const string attrName = "System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute"; switch (mode) { case AntiMode.Ultimate: rtType = rt.GetRuntimeType("Confuser.Runtime.AntiDebugUltimate"); break; case AntiMode.Safe: rtType = rt.GetRuntimeType("Confuser.Runtime.AntiDebugSafe"); break; case AntiMode.Win32: rtType = rt.GetRuntimeType("Confuser.Runtime.AntiDebugWin32"); break; case AntiMode.Antinet: rtType = rt.GetRuntimeType("Confuser.Runtime.AntiDebugAntinet"); attr = rt.GetRuntimeType(attrName); module.Types.Add(attr = InjectHelper.Inject(attr, module)); foreach (IDnlibDef member in attr.FindDefinitions()) { marker.Mark(member, (Protection)Parent); name.Analyze(member); } name.SetCanRename(attr, false); break; default: throw new UnreachableException(); } IEnumerable <IDnlibDef> members = InjectHelper.Inject(rtType, module.GlobalType, module); MethodDef cctor = module.GlobalType.FindStaticConstructor(); var init = (MethodDef)members.Single(method => method.Name == "Initialize"); cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init)); foreach (IDnlibDef member in members) { marker.Mark(member, (Protection)Parent); name.Analyze(member); bool ren = true; if (member is MethodDef) { var method = (MethodDef)member; if (method.Access == MethodAttributes.Public) { method.Access = MethodAttributes.Assembly; } if (!method.IsConstructor) { method.IsSpecialName = false; } else { ren = false; } CustomAttribute ca = method.CustomAttributes.Find(attrName); if (ca != null) { ca.Constructor = attr.FindMethod(".ctor"); } } else if (member is FieldDef) { var field = (FieldDef)member; if (field.Access == FieldAttributes.Public) { field.Access = FieldAttributes.Assembly; } if (field.IsLiteral) { field.DeclaringType.Fields.Remove(field); continue; } } if (ren) { member.Name = name.ObfuscateName(member.Name, RenameMode.Unicode); name.SetCanRename(member, false); } } } }
public Person Read(Guid identifier) { return(_people.Single(p => p.Identifier == identifier)); }
public override void WriteToXml(XmlWriter writer) { var xmlType = new XmlType { Name = Parser.Class.Name, Id = Parser.Fields.Find(entry => entry.Name == "protocolId").Value, Heritage = Parser.Class.Heritage, }; var xmlFields = new List <XmlField>(); MethodInfo deserializeAsMethod = Parser.Methods.Find(entry => entry.Name.Contains("deserializeAs")); string type = null; int limit = 0; for (int i = 0; i < deserializeAsMethod.Statements.Count; i++) { if (deserializeAsMethod.Statements[i] is AssignationStatement && ((AssignationStatement)deserializeAsMethod.Statements[i]).Value.Contains("Read")) { var statement = ((AssignationStatement)deserializeAsMethod.Statements[i]); type = Regex.Match(statement.Value, @"Read([\w\d_]+)\(").Groups[1].Value.ToLower(); var name = statement.Name; if (type == "bytes") { type = "byte[]"; } Match match = Regex.Match(name, @"^([\w\d]+)\[.+\]$"); if (match.Success) { IEnumerable <string> limitLinq = from entry in Parser.Constructors[0].Statements where entry is AssignationStatement && ((AssignationStatement)entry).Name == match.Groups[1].Value let entryMatch = Regex.Match(((AssignationStatement)entry).Value, @"new List<[\d\w\._]+>\(([\d]+)\)") where entryMatch.Success select entryMatch.Groups[1].Value; if (limitLinq.Count() == 1) { limit = int.Parse(limitLinq.Single()); } type += "[]"; name = name.Split('[')[0]; } FieldInfo field = Parser.Fields.Find(entry => entry.Name == name); if (field != null) { string condition = null; if (i + 1 < deserializeAsMethod.Statements.Count && deserializeAsMethod.Statements[i + 1] is ControlStatement && ((ControlStatement)deserializeAsMethod.Statements[i + 1]).ControlType == ControlType.If) { condition = ((ControlStatement)deserializeAsMethod.Statements[i + 1]).Condition; } xmlFields.Add(new XmlField { Name = field.Name, Type = type, Limit = limit > 0 ? limit.ToString() : null, Condition = condition, }); limit = 0; type = null; } } if (deserializeAsMethod.Statements[i] is InvokeExpression && ((InvokeExpression)deserializeAsMethod.Statements[i]).Name == "deserialize") { var statement = ((InvokeExpression)deserializeAsMethod.Statements[i]); FieldInfo field = Parser.Fields.Find(entry => entry.Name == statement.Target); if (field != null && xmlFields.Count(entry => entry.Name == field.Name) <= 0) { type = "Types." + field.Type; string condition = null; if (i + 1 < deserializeAsMethod.Statements.Count && deserializeAsMethod.Statements[i + 1] is ControlStatement && ((ControlStatement)deserializeAsMethod.Statements[i + 1]).ControlType == ControlType.If) { condition = ((ControlStatement)deserializeAsMethod.Statements[i + 1]).Condition; } xmlFields.Add(new XmlField { Name = field.Name, Type = type, Limit = limit > 0 ? limit.ToString() : null, Condition = condition, }); limit = 0; type = null; } else if (i > 0 && deserializeAsMethod.Statements[i - 1] is AssignationStatement) { var substatement = ((AssignationStatement)deserializeAsMethod.Statements[i - 1]); var name = substatement.Name; Match match = Regex.Match(substatement.Value, @"new ([\d\w]+)"); if (match.Success) { type = "Types." + match.Groups[1].Value; Match arrayMatch = Regex.Match(name, @"^([\w\d]+)\[.+\]$"); if (arrayMatch.Success) { IEnumerable <string> limitLinq = from entry in Parser.Constructors[0].Statements where entry is AssignationStatement && ((AssignationStatement)entry).Name == arrayMatch.Groups[1].Value let entryMatch = Regex.Match(((AssignationStatement)entry).Value, @"new List<[\d\w\._]+>\(([\d]+)\)") where entryMatch.Success select entryMatch.Groups[1].Value; if (limitLinq.Count() == 1) { limit = int.Parse(limitLinq.Single()); } type += "[]"; name = name.Split('[')[0]; } } field = Parser.Fields.Find(entry => entry.Name == name); if (field != null && xmlFields.Count(entry => entry.Name == field.Name) <= 0) { string condition = null; if (i + 1 < deserializeAsMethod.Statements.Count && deserializeAsMethod.Statements[i + 1] is ControlStatement && ((ControlStatement)deserializeAsMethod.Statements[i + 1]).ControlType == ControlType.If) { condition = ((ControlStatement)deserializeAsMethod.Statements[i + 1]).Condition; } xmlFields.Add(new XmlField { Name = field.Name, Type = type, Limit = limit > 0 ? limit.ToString() : null, Condition = condition, }); limit = 0; type = null; } } } if (deserializeAsMethod.Statements[i] is AssignationStatement && ((AssignationStatement)deserializeAsMethod.Statements[i]).Value.Contains("getFlag")) { var statement = ((AssignationStatement)deserializeAsMethod.Statements[i]); FieldInfo field = Parser.Fields.Find(entry => entry.Name == statement.Name); var match = Regex.Match(statement.Value, @"getFlag\([\w\d]+,(\d+)\)"); if (match.Success) { type = "flag(" + match.Groups[1].Value + ")"; if (field != null) { xmlFields.Add(new XmlField { Name = field.Name, Type = type, }); type = null; } } } if (deserializeAsMethod.Statements[i] is AssignationStatement && ((AssignationStatement)deserializeAsMethod.Statements[i]).Value.Contains("getInstance")) { var statement = ((AssignationStatement)deserializeAsMethod.Statements[i]); FieldInfo field = Parser.Fields.Find(entry => entry.Name == statement.Name); type = "instance of Types." + Regex.Match(statement.Value, @"getInstance\(([\w\d_\.]+),").Groups[1].Value; if (field != null) { xmlFields.Add(new XmlField { Name = field.Name, Type = type, }); type = null; } } if (deserializeAsMethod.Statements[i] is InvokeExpression && ((InvokeExpression)deserializeAsMethod.Statements[i]).Name == "Add" && type != null) { var statement = ((InvokeExpression)deserializeAsMethod.Statements[i]); FieldInfo field = Parser.Fields.Find(entry => entry.Name == statement.Target); string condition = null; if (i + 1 < deserializeAsMethod.Statements.Count && deserializeAsMethod.Statements[i + 1] is ControlStatement && ((ControlStatement)deserializeAsMethod.Statements[i + 1]).ControlType == ControlType.If) { condition = ((ControlStatement)deserializeAsMethod.Statements[i + 1]).Condition; } xmlFields.Add(new XmlField { Name = field.Name, Type = type + "[]", Limit = limit > 0 ? limit.ToString() : null, Condition = condition, }); limit = 0; type = null; } } xmlType.Fields = xmlFields.ToArray(); var serializer = new XmlSerializer(typeof(XmlType)); serializer.Serialize(writer, xmlType); }
protected void CreateTreeView() { NewsOverviewTree.Nodes.Clear(); var newsEnglish = from n in newsValues where n.CultureCode == BRITISH_CULTURE orderby n.NewsKey.NewsDate descending select n; var numOfCultures = cultures.Count(); // top level nodes in tree view var nodeTop = new TreeNode("Top news"); var nodeNonTop = new TreeNode("Other news"); var nodeHidden = new TreeNode("Hidden news"); nodeTop.SelectAction = TreeNodeSelectAction.Expand; nodeNonTop.SelectAction = TreeNodeSelectAction.Expand; nodeHidden.SelectAction = TreeNodeSelectAction.Expand; // Node header string header; foreach (var n in newsEnglish) { TreeNode node = new TreeNode(n.HeaderText, n.NewsKeyID.ToString()); node.ToolTip = String.Format("{0:D}", n.NewsKey.NewsDate); node.SelectAction = TreeNodeSelectAction.Expand; // distrubute news items between 'hidden', 'top' and 'other' if (!n.NewsKey.Visible) { nodeHidden.ChildNodes.Add(node); } else if (n.NewsKey.TopNewsIndicator) { nodeTop.ChildNodes.Add(node); } else { nodeNonTop.ChildNodes.Add(node); } // add a child node for each available translation foreach (var localizedNewsItem in newsValues.Where(x => x.NewsKeyID == n.NewsKeyID)) { string language = cultures.Single(x => x.Code == localizedNewsItem.CultureCode).EnglishName; var languageNode = new TreeNode(language, localizedNewsItem.CultureCode); node.ChildNodes.Add(languageNode); } // add a link to add a new translation if (node.ChildNodes.Count < numOfCultures) { var addLanugageNode = new TreeNode("Add new language", NEW_LANGUAGE); node.ChildNodes.Add(addLanugageNode); } } // add all top level nodes, if not empty if (nodeTop.ChildNodes.Count > 0) { NewsOverviewTree.Nodes.Add(nodeTop); } if (nodeNonTop.ChildNodes.Count > 0) { NewsOverviewTree.Nodes.Add(nodeNonTop); } if (nodeHidden.ChildNodes.Count > 0) { NewsOverviewTree.Nodes.Add(nodeHidden); } NewsOverviewTree.CollapseAll(); }
private void LoadNewsItem() { if (HiddenCultureCode.Value == NEW_LANGUAGE) { ClearNewsForm(); // Language always English for new news items DataBindLanguageList(); LanguageList.Visible = true; lbLanguageList.Visible = true; var key = newsKeys.Single(x => x.NewsKeyID == int.Parse(HiddenSubmitID.Value)); NewsCalender.SelectedDate = key.NewsDate; NewsCalender.VisibleDate = key.NewsDate; cbTopNews.Checked = key.TopNewsIndicator; cbHideNews.Checked = false; lbEnglishTitle.Visible = true; tbEnglishTitle.Visible = true; tbEnglishTitle.Text = GetEnglishNewsTitle(key.NewsKeyID); lbWorkingLanguage.Text = String.Format("You are about to add a new translation for the chosen news story. Choose a language from the drop down list."); } else { var newsItems = from val in newsValues join key in newsKeys on val.NewsKeyID equals key.NewsKeyID where val.CultureCode == HiddenCultureCode.Value && key.NewsKeyID == int.Parse(HiddenSubmitID.Value) select new { NewsId = key.NewsKeyID, NewsDate = key.NewsDate, TopNews = key.TopNewsIndicator, TitleText = val.HeaderText, ContentText = val.BodyText, CultureCode = val.CultureCode, Visible = key.Visible }; var item = newsItems.First(); // set text boxes TextEditorNews.Value = item.ContentText; tbNewsTitleEditor.Text = item.TitleText; if (item.CultureCode.Equals(BRITISH_CULTURE)) { tbEnglishTitle.Visible = false; lbEnglishTitle.Visible = false; } else { lbEnglishTitle.Visible = true; tbEnglishTitle.Visible = true; tbEnglishTitle.Text = GetEnglishNewsTitle(item.NewsId); } // set top news cbTopNews.Checked = item.TopNews; // set 'hide news story' cbHideNews.Checked = !item.Visible; // set calendar NewsCalender.SelectedDate = item.NewsDate; NewsCalender.VisibleDate = item.NewsDate; lbWorkingLanguage.Text = String.Format("Current working language is {0}", GetEnglishLanguageName(item.CultureCode)); LanguageList.Visible = false; lbLanguageList.Visible = false; } NewsEditorFuncDisplay.Visible = true; }
/// <inheritdoc/> public virtual TestProcessStartInfo GetTestHostProcessStartInfo( IEnumerable <string> sources, IDictionary <string, string> environmentVariables, TestRunnerConnectionInfo connectionInfo) { var startInfo = new TestProcessStartInfo(); // .NET core host manager is not a shared host. It will expect a single test source to be provided. var args = string.Empty; var sourcePath = sources.Single(); var sourceFile = Path.GetFileNameWithoutExtension(sourcePath); var sourceDirectory = Path.GetDirectoryName(sourcePath); // Probe for runtimeconfig and deps file for the test source var runtimeConfigPath = Path.Combine(sourceDirectory, string.Concat(sourceFile, ".runtimeconfig.json")); if (this.fileHelper.Exists(runtimeConfigPath)) { string argsToAdd = " --runtimeconfig " + runtimeConfigPath.AddDoubleQuote(); args += argsToAdd; EqtTrace.Verbose("DotnetTestHostmanager: Adding {0} in args", argsToAdd); } else { EqtTrace.Verbose("DotnetTestHostmanager: File {0}, doesnot exist", runtimeConfigPath); } // Use the deps.json for test source var depsFilePath = Path.Combine(sourceDirectory, string.Concat(sourceFile, ".deps.json")); if (this.fileHelper.Exists(depsFilePath)) { string argsToAdd = " --depsfile " + depsFilePath.AddDoubleQuote(); args += argsToAdd; EqtTrace.Verbose("DotnetTestHostmanager: Adding {0} in args", argsToAdd); } else { EqtTrace.Verbose("DotnetTestHostmanager: File {0}, doesnot exist", depsFilePath); } var runtimeConfigDevPath = Path.Combine(sourceDirectory, string.Concat(sourceFile, ".runtimeconfig.dev.json")); string testHostPath = string.Empty; // If testhost.exe is available use it bool testHostExeFound = false; if (this.platformEnvironment.OperatingSystem.Equals(PlatformOperatingSystem.Windows)) { var exeName = this.architecture == Architecture.X86 ? "testhost.x86.exe" : "testhost.exe"; var fullExePath = Path.Combine(sourceDirectory, exeName); // check for testhost.exe in sourceDirectory. If not found, check in nuget folder. if (this.fileHelper.Exists(fullExePath)) { EqtTrace.Verbose("DotnetTestHostManager: Testhost.exe/testhost.x86.exe found at path: " + fullExePath); startInfo.FileName = fullExePath; testHostExeFound = true; } else { // Check if testhost.dll is found in nuget folder. testHostPath = this.GetTestHostPath(runtimeConfigDevPath, depsFilePath, sourceDirectory); if (testHostPath.IndexOf("microsoft.testplatform.testhost", StringComparison.OrdinalIgnoreCase) >= 0) { // testhost.dll is present in path {testHostNugetRoot}\lib\netcoreapp2.1\testhost.dll // testhost.(x86).exe is present in location {testHostNugetRoot}\build\netcoreapp2.1\{x86/x64}\{testhost.x86.exe/testhost.exe} var folderName = this.architecture == Architecture.X86 ? "x86" : "x64"; var testHostNugetRoot = new DirectoryInfo(testHostPath).Parent.Parent.Parent; var testHostExeNugetPath = Path.Combine(testHostNugetRoot.FullName, "build", "netcoreapp2.1", folderName, exeName); if (this.fileHelper.Exists(testHostExeNugetPath)) { EqtTrace.Verbose("DotnetTestHostManager: Testhost.exe/testhost.x86.exe found at path: " + testHostExeNugetPath); startInfo.FileName = testHostExeNugetPath; testHostExeFound = true; } } } } if (!testHostExeFound) { var currentProcessPath = this.processHelper.GetCurrentProcessFileName(); if (string.IsNullOrEmpty(testHostPath)) { testHostPath = this.GetTestHostPath(runtimeConfigDevPath, depsFilePath, sourceDirectory); } // This host manager can create process start info for dotnet core targets only. // If already running with the dotnet executable, use it; otherwise pick up the dotnet available on path. // Wrap the paths with quotes in case dotnet executable is installed on a path with whitespace. if (currentProcessPath.EndsWith("dotnet", StringComparison.OrdinalIgnoreCase) || currentProcessPath.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase)) { startInfo.FileName = currentProcessPath; } else { startInfo.FileName = this.dotnetHostHelper.GetDotnetPath(); } EqtTrace.Verbose("DotnetTestHostmanager: Full path of testhost.dll is {0}", testHostPath); args = "exec" + args; args += " " + testHostPath.AddDoubleQuote(); } EqtTrace.Verbose("DotnetTestHostmanager: Full path of host exe is {0}", startInfo.FileName); args += " " + connectionInfo.ToCommandLineOptions(); // Create a additional probing path args with Nuget.Client // args += "--additionalprobingpath xxx" // TODO this may be required in ASP.net, requires validation // Sample command line for the spawned test host // "D:\dd\gh\Microsoft\vstest\tools\dotnet\dotnet.exe" exec // --runtimeconfig G:\tmp\netcore-test\bin\Debug\netcoreapp1.0\netcore-test.runtimeconfig.json // --depsfile G:\tmp\netcore-test\bin\Debug\netcoreapp1.0\netcore-test.deps.json // --additionalprobingpath C:\Users\username\.nuget\packages\ // G:\nuget-package-path\microsoft.testplatform.testhost\version\**\testhost.dll // G:\tmp\netcore-test\bin\Debug\netcoreapp1.0\netcore-test.dll startInfo.Arguments = args; startInfo.EnvironmentVariables = environmentVariables ?? new Dictionary <string, string>(); startInfo.WorkingDirectory = sourceDirectory; return(startInfo); }
private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable <IPackage> dependents) { if (dependents.Count <IPackage>() == 1) { object[] objArray1 = new object[] { package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single <IPackage>().Id }; return(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependent, objArray1))); } object[] args = new object[] { package.GetFullName(), resolvedPackage.GetFullName(), string.Join(", ", (IEnumerable <string>)(from d in dependents select d.Id)) }; return(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependents, args))); }
public void Write <TValue>(DataAddress address, IEnumerable <TValue> values) { if (address.Equals(DataAddress.Empty)) { throw new ApplicationException("地址为空"); } if (values == null || !values.Any()) { throw new ApplicationException($"参数异常,values为null或空"); } var valueType = typeof(TValue); try { var modbusAddress = ModbusAddress.Parse(address); switch (address.Type) { case DataAddressType.Boolean: { var datas = values.Select(e => (bool)Convert.ChangeType(e, valueType)).ToArray(); if (modbusAddress.IOType == IOType.DO) { master.WriteMultipleCoils(modbusAddress.SlaveNumber, modbusAddress.StartAddress, datas); } } break; case DataAddressType.Short: { var datas = new List <ushort>(); values.ToList().ForEach(e => { var value = (short)Convert.ChangeType(e, valueType); var bytes = BitConverter.GetBytes(value); datas.Add(BitConverter.ToUInt16(bytes.Reverse().ToArray(), 0)); }); Write(address, datas); } break; case DataAddressType.Ushort: { var datas = values.Select(e => (ushort)Convert.ChangeType(e, valueType)).ToArray(); if (modbusAddress.IOType == IOType.AO) { master.WriteMultipleRegisters(modbusAddress.SlaveNumber, modbusAddress.StartAddress, datas); } } break; case DataAddressType.Int: { var datas = new List <ushort>(); values.ToList().ForEach(e => { var value = (int)Convert.ChangeType(e, valueType); var bytes = BitConverter.GetBytes(value); datas.Add(BitConverter.ToUInt16(new byte[] { bytes[1], bytes[0] }, 0)); datas.Add(BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0)); }); Write(address, datas); } break; case DataAddressType.Float: { var datas = new List <ushort>(); values.ToList().ForEach(e => { var value = (float)Convert.ChangeType(e, valueType); var bytes = BitConverter.GetBytes(value); datas.Add(BitConverter.ToUInt16(new byte[] { bytes[1], bytes[0] }, 0)); datas.Add(BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0)); }); Write(address, datas); } break; case DataAddressType.String: { var datas = new List <ushort>(); var value = (string)Convert.ChangeType(values.Single(), valueType); var bytes = new List <byte>(Encoding.ASCII.GetBytes(value)); var count = ((int)Math.Ceiling((address.Offset + 1) / 2d)) * 2 - bytes.Count; while (count-- > 0) { bytes.Add(0x00); } for (int i = 0; i < modbusAddress.Length; i++) { datas.Add(BitConverter.ToUInt16(bytes.Skip(i * 2).Take(2).Reverse().ToArray(), 0)); } Write(address, datas); } break; default: throw new NotImplementedException(); } } catch (Exception e) { Reconnect(); throw new ApplicationException($"写入失败,地址:{address }", e); } }
/// <summary> /// Gets the <see cref="ReferenceLink"/> with the rel value of of type TLink pluralized using the Single System.Linq method. /// </summary> /// <param name="links">The <see cref="ReferenceLink"/>s to query.</param> /// <returns>The <see cref="ReferenceLink"/>.</returns> /// <exception cref="InvalidOperationException">If zero or more than one results are found.</exception> /// <seealso cref="Relationships">For details of how the rel values relate to the type TLink.</seealso> public static ReferenceLink ListRelSingle <TLink>(this IEnumerable <ReferenceLink> links) { return(links.Single(l => l.Rel == typeof(TLink).ListRel())); }
private bool PersonIdCheck(IEnumerable <string> ids, string checksum) { return(ids.Single() == checksum); }
/// <summary> /// Gets the <see cref="ReferenceLink"/> with the rel value of "self" using the Single System.Linq method. /// </summary> /// <param name="links">The <see cref="ReferenceLink"/>s to query.</param> /// <returns>The <see cref="ReferenceLink"/>.</returns> /// <exception cref="InvalidOperationException">If zero or more than one results are found.</exception> public static ReferenceLink SelfLinkSingle(this IEnumerable <ReferenceLink> links) { return(links.Single(l => l.Rel == Relationships.Self)); }
private bool TodoCheck(IEnumerable <TodoItem> entities, string checksum) { return(entities.Single().Description == checksum); }
public static T?SingleOrNullable <T>(this IEnumerable <T> enumerable) where T : struct { return(enumerable.IsNullOrEmpty() ? new T?() : enumerable.Single()); }
private static FileAnalysis GetFileAnalysis(IEnumerable <Assembly> assemblies, string className, string fileName) => assemblies .Single(a => a.Name == "test.exe").Classes .Single(c => c.Name == className).Files .Single(f => f.Path == fileName) .AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null));
private static async Task Seed_Database(ISchoolRepository repository) { if ((await repository.CountAsync <StudentModel, Student>()) > 0) { return;//database has been seeded } InstructorModel[] instructors = new InstructorModel[] { new InstructorModel { FirstName = "Roger", LastName = "Zheng", HireDate = DateTime.Parse("2004-02-12"), EntityState = LogicBuilder.Domain.EntityStateType.Added }, new InstructorModel { FirstName = "Kim", LastName = "Abercrombie", HireDate = DateTime.Parse("1995-03-11"), EntityState = LogicBuilder.Domain.EntityStateType.Added }, new InstructorModel { FirstName = "Fadi", LastName = "Fakhouri", HireDate = DateTime.Parse("2002-07-06"), OfficeAssignment = new OfficeAssignmentModel { Location = "Smith 17" }, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new InstructorModel { FirstName = "Roger", LastName = "Harui", HireDate = DateTime.Parse("1998-07-01"), OfficeAssignment = new OfficeAssignmentModel { Location = "Gowan 27" }, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new InstructorModel { FirstName = "Candace", LastName = "Kapoor", HireDate = DateTime.Parse("2001-01-15"), OfficeAssignment = new OfficeAssignmentModel { Location = "Thompson 304" }, EntityState = LogicBuilder.Domain.EntityStateType.Added } }; await repository.SaveGraphsAsync <InstructorModel, Instructor>(instructors); DepartmentModel[] departments = new DepartmentModel[] { new DepartmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, Name = "English", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single(i => i.FirstName == "Kim" && i.LastName == "Abercrombie").ID, Courses = new HashSet <CourseModel> { new CourseModel { CourseID = 2021, Title = "Composition", Credits = 3 }, new CourseModel { CourseID = 2042, Title = "Literature", Credits = 4 } } }, new DepartmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, Name = "Mathematics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single(i => i.FirstName == "Fadi" && i.LastName == "Fakhouri").ID, Courses = new HashSet <CourseModel> { new CourseModel { CourseID = 1045, Title = "Calculus", Credits = 4 }, new CourseModel { CourseID = 3141, Title = "Trigonometry", Credits = 4 } } }, new DepartmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, Name = "Engineering", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single(i => i.FirstName == "Roger" && i.LastName == "Harui").ID, Courses = new HashSet <CourseModel> { new CourseModel { CourseID = 1050, Title = "Chemistry", Credits = 3 } } }, new DepartmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, Name = "Economics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single(i => i.FirstName == "Candace" && i.LastName == "Kapoor").ID, Courses = new HashSet <CourseModel> { new CourseModel { CourseID = 4022, Title = "Microeconomics", Credits = 3 }, new CourseModel { CourseID = 4041, Title = "Macroeconomics", Credits = 3 } } } }; await repository.SaveGraphsAsync <DepartmentModel, Department>(departments); IEnumerable <CourseModel> courses = departments.SelectMany(d => d.Courses); CourseAssignmentModel[] courseInstructors = new CourseAssignmentModel[] { new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, InstructorID = instructors.Single(i => i.LastName == "Harui").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID, InstructorID = instructors.Single(i => i.LastName == "Zheng").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Macroeconomics").CourseID, InstructorID = instructors.Single(i => i.LastName == "Zheng").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Calculus").CourseID, InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Trigonometry").CourseID, InstructorID = instructors.Single(i => i.LastName == "Harui").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Composition").CourseID, InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID }, new CourseAssignmentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, CourseID = courses.Single(c => c.Title == "Literature").CourseID, InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID }, }; await repository.SaveGraphsAsync <CourseAssignmentModel, CourseAssignment>(courseInstructors); StudentModel[] students = new StudentModel[] { new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2010-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, Grade = Contoso.Domain.Entities.Grade.A }, new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID, Grade = Contoso.Domain.Entities.Grade.C }, new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Macroeconomics").CourseID, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2012-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Calculus").CourseID, Grade = Contoso.Domain.Entities.Grade.B }, new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Trigonometry").CourseID, Grade = Contoso.Domain.Entities.Grade.B }, new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Composition").CourseID, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2013-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Chemistry").CourseID }, new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID, Grade = Contoso.Domain.Entities.Grade.B }, } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2012-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2012-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Composition").CourseID, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2011-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = courses.Single(c => c.Title == "Literature").CourseID, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2013-09-01") }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Tom", LastName = "Spratt", EnrollmentDate = DateTime.Parse("2010-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = 1045, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Billie", LastName = "Spratt", EnrollmentDate = DateTime.Parse("2010-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = 1050, Grade = Contoso.Domain.Entities.Grade.B } } }, new StudentModel { EntityState = LogicBuilder.Domain.EntityStateType.Added, FirstName = "Jackson", LastName = "Spratt", EnrollmentDate = DateTime.Parse("2017-09-01"), Enrollments = new HashSet <EnrollmentModel> { new EnrollmentModel { CourseID = 2021, Grade = Contoso.Domain.Entities.Grade.B } } } }; await repository.SaveGraphsAsync <StudentModel, Student>(students); LookUpsModel[] lookups = new LookUpsModel[] { new LookUpsModel { ListName = "Grades", Text = "A", Value = "A", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Grades", Text = "B", Value = "B", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Grades", Text = "C", Value = "C", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Grades", Text = "D", Value = "D", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Grades", Text = "E", Value = "E", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Grades", Text = "F", Value = "F", EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Credits", Text = "One", NumericValue = 1, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Credits", Text = "Two", NumericValue = 2, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Credits", Text = "Three", NumericValue = 3, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Credits", Text = "Four", NumericValue = 4, EntityState = LogicBuilder.Domain.EntityStateType.Added }, new LookUpsModel { ListName = "Credits", Text = "Five", NumericValue = 5, EntityState = LogicBuilder.Domain.EntityStateType.Added } }; await repository.SaveGraphsAsync <LookUpsModel, LookUps>(lookups); }
private static CodeFile GetFile(IEnumerable <Assembly> assemblies, string className, string fileName) => assemblies .Single(a => a.Name == "test.exe").Classes .Single(c => c.Name == className).Files .Single(f => f.Path == fileName);
public bool Apply(IEnumerable <ITypedDeclaration> others, ITypedDeclaration source, MemberPatternContext context, MemberPatternInfo info) { if (source.Dimensions != null) { string typeName = this.nameLookup.Lookup(source.Type, true); info.Interop = new TypedDefinition { Name = source.Name, Type = typeName }; if (source.Dimensions.Length == 2) { info.Public.Add(new TypedDefinition { Name = source.Name, Type = "ArrayProxy<string>" + (context.IsMethod ? "?" : ""), DefaultValue = source.IsOptional ? Null : null, Comment = this.commentGenerator.Lookup(context.VkName, source.VkName) }); info.MarshalTo.Add((getTarget, getValue) => { return(new AssignAction { ValueExpression = StaticCall("Interop.HeapUtil", "MarshalTo", getValue(source.Name)), TargetExpression = getTarget(source.Name), MemberType = this.nameLookup.Lookup(source.Type, false), Type = AssignActionType.Assign }); }); } else if (source.Dimensions.Length == 1) { switch (source.Dimensions[0].Type) { case LenType.NullTerminated: info.Public.Add(new TypedDefinition { Name = source.Name, Comment = this.commentGenerator.Lookup(context.VkName, source.VkName), Type = "string" }); info.InteropFullType = typeName; info.MarshalTo.Add((getTarget, getValue) => new AssignAction { ValueExpression = StaticCall("Interop.HeapUtil", "MarshalTo", getValue(source.Name)), TargetExpression = getTarget(source.Name), MemberType = this.nameLookup.Lookup(source.Type, false), Type = AssignActionType.Assign }); info.MarshalFrom.Add((getTarget, getValue) => new AssignAction { ValueExpression = StaticCall("Interop.HeapUtil", "MarshalStringFrom", getValue(source.Name)), TargetExpression = getTarget(source.Name), MemberType = this.nameLookup.Lookup(source.Type, false), Type = AssignActionType.Assign }); break; case LenType.Expression: var elementType = source.Type.Deref(); bool isDoubleMarshalled = false; string semiMarshalledName = "semiMarshalled" + source.Name.FirstToUpper(); string semiMarshalType = this.nameLookup.Lookup(elementType, true); if (elementType.PointerType.IsPointer()) { info.MarshalTo.Add((getTarget, getValue) => new DeclarationAction { MemberType = semiMarshalType, MemberName = semiMarshalledName }); isDoubleMarshalled = true; elementType = elementType.Deref(); } if (elementType.VkName == "void") { elementType.VkName = "uint8_t"; } var marshalling = this.marshallingRules.ApplyFirst(elementType); info.Interop.Type = marshalling.InteropType + "*"; info.InteropFullType = marshalling.InteropType; if (source.Type.PointerType.IsPointer()) { info.InteropFullType += new string('*', source.Type.PointerType.GetPointerCount()); } string arrayType = $"{marshalling.MemberType}[]"; if (context.IsMethod) { info.Public.Add(new TypedDefinition { Name = source.Name, Type = $"ArrayProxy<{marshalling.MemberType}>?", Comment = new[] { "" }.ToList(), DefaultValue = source.IsOptional ? Null : null }); info.ReturnType = arrayType; info.MarshalTo.Add((getTarget, getValue) => { var proxyValue = Member(getValue(source.Name), "Value"); var isNullOptional = new OptionalAction { CheckExpression = Call(getValue(source.Name), "IsNull") }; var isSingleOptional = new OptionalAction { CheckExpression = IsEqual(Member(proxyValue, "Contents"), EnumField("ProxyContents", "Single")) }; var loopAssign = new AssignAction { TargetExpression = isDoubleMarshalled ? Variable(semiMarshalledName) : getTarget(source.Name), MemberType = marshalling.InteropType, IsLoop = true, IndexName = "index", Type = marshalling.MarshalToActionType, LengthExpression = StaticCall("Interop.HeapUtil", "GetLength", proxyValue), ValueExpression = marshalling.BuildMarshalToValueExpression(Index(proxyValue, Variable("index")), context.GetHandle) }; isSingleOptional.Actions.Add(new AssignAction { Type = AssignActionType.Alloc, TargetExpression = isDoubleMarshalled ? Variable(semiMarshalledName) : getTarget(source.Name), MemberType = marshalling.InteropType }); isSingleOptional.Actions.Add(new AssignAction { Type = marshalling.MarshalToActionType, MemberType = marshalling.InteropType, ValueExpression = marshalling.BuildMarshalToValueExpression(Call(proxyValue, "GetSingleValue"), context.GetHandle), TargetExpression = Deref(Cast(marshalling.InteropType + "*", isDoubleMarshalled ? Variable(semiMarshalledName) : getTarget(source.Name))) }); isSingleOptional.ElseActions.Add(loopAssign); if (isDoubleMarshalled) { isSingleOptional.ElseActions.Add(new AssignAction { TargetExpression = getTarget(source.Name), MemberType = semiMarshalType, IsLoop = true, IndexName = "index", Type = AssignActionType.Assign, LengthExpression = StaticCall("Interop.HeapUtil", "GetLength", proxyValue), ValueExpression = AddressOf(Index(Variable(semiMarshalledName), Variable("index"))), FieldPointerName = "marshalledFieldPointer" }); } isNullOptional.Actions.Add(new AssignAction { TargetExpression = getTarget(source.Name), ValueExpression = Null }); isNullOptional.ElseActions.Add(isSingleOptional); return(isNullOptional); }); } else { info.Public.Add(new TypedDefinition { Name = source.Name, Comment = this.commentGenerator.Lookup(context.VkName, source.VkName), Type = arrayType }); info.MarshalTo.Add((getTarget, getValue) => new AssignAction { TargetExpression = isDoubleMarshalled ? Variable(semiMarshalledName) : getTarget(source.Name), MemberType = marshalling.InteropType, IsLoop = true, IndexName = "index", Type = marshalling.MarshalToActionType, NullCheckExpression = IsNotEqual(getValue(source.Name), Null), LengthExpression = Member(getValue(source.Name), "Length"), ValueExpression = marshalling.BuildMarshalToValueExpression(Index(getValue(source.Name), Variable("index")), context.GetHandle) }); if (isDoubleMarshalled) { info.MarshalTo.Add((getTarget, getValue) => new AssignAction { TargetExpression = getTarget(source.Name), MemberType = semiMarshalType, IsLoop = true, IndexName = "index", Type = AssignActionType.Assign, NullCheckExpression = IsNotEqual(getValue(source.Name), Null), LengthExpression = Member(getValue(source.Name), "Length"), ValueExpression = AddressOf(Index(Variable(semiMarshalledName), Variable("index"))) }); } } Func <Func <string, Action <ExpressionBuilder> >, Action <ExpressionBuilder> > lenValue = null; if (source.Dimensions[0].Value is LenExpressionToken lenToken) { lenValue = getValue => getValue(others.Single(x => x.VkName == lenToken.Value).Name); } else { lenValue = getValue => this.expressionBuilder.Build(source.Dimensions[0].Value, x => others.Single(y => y.VkName == x)); } info.MarshalFrom.Add((getTarget, getValue) => new AssignAction { TargetExpression = getTarget(source.Name), MemberType = marshalling.MemberType, IsLoop = true, IsArray = true, IndexName = "index", Type = marshalling.MarshalFromActionType, NullCheckExpression = IsNotEqual(getValue(source.Name), Null), LengthExpression = lenValue(getValue), ValueExpression = marshalling.BuildMarshalFromValueExpression(Index(getValue(source.Name), Variable("index")), context.GetHandle) }); break; } } return(true); } else { return(false); } }
public Ninja GetNinja(string id) { return(_ninjas.Single(n => n.Id == id)); }
internal static Body get(CelestialBody b) { return(ALL.Single(body => body.isSame(b))); }
private static FileAnalysis GetFileAnalysis(IEnumerable <Assembly> assemblies, string className, string fileName) => assemblies .Single(a => a.Name == "Test").Classes .Single(c => c.Name == className).Files .Single(f => f.Path == fileName) .AnalyzeFile();