public static GroupExpression Parse(ExpressionWalker ew, ExpressionToken left, ExpressionToken right) { ew.IsCurrentOrThrow(left); ew.NextOrThrow(); if (ew.Current.Token == right) { throw new UnexpectedTokenException($"Expected an expression, found end of group of type {right}"); } var expr = ParseExpression(ew, typeof(GroupExpression)); var grp = new GroupExpression() { _matchLeft = AttributeExtensions.GetAttribute <ExpressionTokenAttribute>(left).Emit.AsResult(), _matchRight = AttributeExtensions.GetAttribute <ExpressionTokenAttribute>(right).Emit.AsResult() }; if (ew.IsCurrent(ExpressionToken.Or)) { grp.InnerExpression = TernaryExpression.Parse(ew, expr); } else { grp.InnerExpression = expr; } ew.IsCurrentOrThrow(right); ew.Next(); return(grp); }
static System.Collections.Generic.List <BindItem> TryGetBind(System.Type entityType) { string key = entityType.AssemblyQualifiedName; var list = _list_key.GetOrAdd(key, (p) => { if (entityType.IsValueType || entityType == typeof(string) || entityType == typeof(object) || TypeExtensions.IsNullableType(entityType)) { return(null); } var cache = new System.Collections.Generic.List <BindItem>(); foreach (System.Reflection.PropertyInfo propertyInfo in entityType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.SetProperty)) { var binder = AttributeExtensions.GetCustomAttribute <DataBinderAttribute>(propertyInfo); if (binder == null) { continue; } BindItem bindItem = new BindItem() { propertyInfo = propertyInfo, binder = binder, bindAction = binder.Bind, }; cache.Add(bindItem); } return(cache); }); return(list); }
// Saves the element in the reader to the buffer (attributes preserved) // Type is populated from type attribute on reader // Reader must be positioned at an element public XmlSyndicationContent(XmlReader reader) { if (reader is null) { throw new ArgumentNullException(nameof(reader)); } SyndicationFeedFormatter.MoveToStartElement(reader); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string name = reader.LocalName; string ns = reader.NamespaceURI; string value = reader.Value; if (name == Atom10Constants.TypeTag && ns == string.Empty) { _type = value; } else if (!FeedUtils.IsXmlns(name, ns)) { AttributeExtensions.Add(new XmlQualifiedName(name, ns), value); } } reader.MoveToElement(); } _type = string.IsNullOrEmpty(_type) ? Atom10Constants.XmlMediaType : _type; _contentBuffer = new XmlBuffer(int.MaxValue); using (XmlDictionaryWriter writer = _contentBuffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteNode(reader, false); } _contentBuffer.CloseSection(); _contentBuffer.Close(); }
public static void GenerateOutputFields(FrontEndTranslator translator, ShaderType shaderType, ShaderInterfaceSet interfaceSet, ShaderBlock declarationBlock, ShaderBlock decorationsBlock) { if (interfaceSet.Fields.Count == 0) { return; } var outputsName = shaderType.mMeta.mName + "_Outputs"; EntryPointGenerationShared.GenerateInterfaceGlobalFields(translator, interfaceSet.Fields, outputsName, "Out", StorageClass.Output); foreach (var inputField in interfaceSet) { var fieldOp = interfaceSet.GetFieldInstance(translator, inputField, null); declarationBlock.mLocalVariables.Add(fieldOp); } Decorations.LocationCallback locationCallback = (ShaderField field, out int location, out int component) => { location = component = -1; var attribute = field.mMeta.mAttributes.FindFirstAttribute(typeof(Shader.StageOutput)); if (attribute == null) { return(false); } var parsedAttribute = AttributeExtensions.ParseStageOutput(attribute); location = parsedAttribute.Location; component = parsedAttribute.Component; return(false); }; Decorations.AddDecorationLocations(translator, shaderType, interfaceSet, locationCallback, decorationsBlock); }
/// <summary> /// Get attribute value. /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="enumValue"></param> /// <param name="attributeType"></param> /// <returns></returns> internal static string GetAttributeValue <TSource>(string enumValue, EnumAttributeTypes attributeType) where TSource : struct { TSource tValue; if (Enum.TryParse <TSource>(enumValue, true, out tValue)) { if (attributeType.Equals(EnumAttributeTypes.Description)) { return(AttributeExtensions.GetDescriptionAttribute <TSource>(tValue)); } else if (attributeType.Equals(EnumAttributeTypes.Category)) { return(AttributeExtensions.GetCategoryAttribute <TSource>(tValue)); } else if (attributeType.Equals(EnumAttributeTypes.DisplayIcon)) { return(AttributeExtensions.GetDisplayIconAttribute <TSource>(tValue)); } else if (attributeType.Equals(EnumAttributeTypes.ReportDefinition)) { return(AttributeExtensions.GetReportDefinitionAttribute <TSource>(tValue)); } return(AttributeExtensions.GetDescriptionAttribute <TSource>(tValue)); } else { return(null); } }
public byte[] Save(object instance) { Type type = instance.GetType(); TreePackage package = new TreePackage(); package.Attributes.Add("Type", type.AssemblyQualifiedName); foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if (!property.CanRead) { continue; } if (AttributeExtensions.IsDefined <NonPackageAttribute>(property) || AttributeExtensions.IsDefined <Formatting.IgnoreAttribute>(property)) { continue; } package.Add(property.Name, property.GetValue(instance, new object[0])); } foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) { if (AttributeExtensions.IsDefined <NonPackageAttribute>(field) || AttributeExtensions.IsDefined <Formatting.IgnoreAttribute>(field)) { continue; } package.Add(field.Name, field.GetValue(instance)); } return(package.Save()); }
/// <inheritdoc /> /// <summary> /// Create a container to run a plugin. /// Auto-detects sandbox mode plugins and tests them using Sandbox mode if the IsolationMode is Sandbox /// </summary> /// <param name="unsecureConfig">Unsecure configuration string</param> /// <param name="secureConfig">Secure configuration string</param> public PluginContainer(string unsecureConfig, string secureConfig) { var sandbox = AttributeExtensions.GetCrmPluginRegistrationAttributes(typeof(T)) .Any(a => a.IsolationMode == IsolationModeEnum.Sandbox); SetupContainer(sandbox, unsecureConfig, secureConfig); }
/// <summary> /// Register the screens in the application database /// </summary> /// <param name="assembly">Current Assembly</param> /// <returns>Void</returns> public static void RegisterScreens(Assembly assembly) { List <ScreenRoute> existingScreenRoute = userRepository.GetAvailableScreens(); List <ScreenRoute> controllerActions = assembly.GetTypes().Where(types => typeof(Controller).IsAssignableFrom(types)) .SelectMany(type => type.GetMethods()) .Where(method => method.IsPublic && !method.IsDefined(typeof(NonActionAttribute)) && method.IsDefined(typeof(LinkFilter)) && !method.DeclaringType.Name.Equals("Controller") && method.DeclaringType.Name.EndsWith("Controller")).Select( screenRoutes => new ScreenRoute { ActionName = screenRoutes.GetType().IsDefined(typeof(ActionNameAttribute)) ? AttributeExtensions.GetCustomAttribute <ActionNameAttribute>(screenRoutes).Name : screenRoutes.Name, ControllerName = screenRoutes.DeclaringType.Name, AreaName = GetAreaName(screenRoutes.DeclaringType.FullName, screenRoutes.DeclaringType.Name), LinkText = AttributeExtensions.GetCustomAttribute <LinkFilter>(screenRoutes).LinkText, Read = AttributeExtensions.GetCustomAttribute <LinkFilter>(screenRoutes).Read, Delete = AttributeExtensions.GetCustomAttribute <LinkFilter>(screenRoutes).Delete, Write = AttributeExtensions.GetCustomAttribute <LinkFilter>(screenRoutes).Write, GroupMenuTitle = AttributeExtensions.GetCustomAttribute <GroupMenuTitle>(screenRoutes.DeclaringType).Title, }).ToList(); List <ScreenRoute> missingScreens = controllerActions.Except(existingScreenRoute).ToList(); foreach (ScreenRoute screens in missingScreens) { userRepository.AddApplicationScreens(screens); } }
//------------------------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="EventFactory" /> class. /// </summary> public EventFactory() { // Create a dictionary for storing event reference keys and types. EventReference = new Dictionary <EventKey, Type>(); // Collect and loop through all of the event types. foreach (var eventObject in AttributeExtensions.GetTypesWith <DirectorEventAttribute>(true)) { // Check if the class is abstract base class, we don't want to add that. if (eventObject.GetTypeInfo().IsAbstract) { continue; } // Check the attribute itself from the event we are working on, which gives us the event type enumerable. var eventAttribute = eventObject.GetTypeInfo().GetAttributes <DirectorEventAttribute>(true).First(); // Initialize the execution history dictionary with every event type. foreach (var modeType in Enum.GetValues(typeof(EventCategory))) { // Create key for the event execution counter. var eventKey = new EventKey((EventCategory)modeType, eventObject.Name, eventAttribute.EventExecutionType); if (!EventReference.ContainsKey(eventKey)) { EventReference.Add(eventKey, eventObject); } } } }
public void AddNamespaces(bool purlContent) { AttributeExtensions.Add(new XmlQualifiedName("atom", XNamespace.Xmlns.NamespaceName), UrlAtom); if (purlContent) { AttributeExtensions.Add(new XmlQualifiedName("content", XNamespace.Xmlns.ToString()), UrlPurlContent); } }
/// <summary> /// /// </summary> protected internal virtual void LinkDataReaded() { var knowKeys = new List <XmlQualifiedName>(); foreach (var extAttribute in AttributeExtensions) { if ("count".Equals(extAttribute.Key.Name, StringComparison.Ordinal) && OpdsNamespaces.Threading.Value.Equals(extAttribute.Key.Namespace, StringComparison.Ordinal)) { int count; if (Int32.TryParse(extAttribute.Value, out count)) { Count = count; } } else if ("activeFacet".Equals(extAttribute.Key.Name, StringComparison.Ordinal) && OpdsNamespaces.Opds.Value.Equals(extAttribute.Key.Namespace, StringComparison.Ordinal)) { bool active; if (Boolean.TryParse(extAttribute.Value, out active)) { if (!active) { throw new XmlException("opds:activeFacet SOULD not has a value of 'false', just don't provide opds:activeFacet."); } ActiveFacet = true; } } else if ("facetGroup".Equals(extAttribute.Key.Name, StringComparison.Ordinal) && OpdsNamespaces.Opds.Value.Equals(extAttribute.Key.Namespace, StringComparison.Ordinal)) { if (String.IsNullOrEmpty(extAttribute.Value)) { throw new XmlException("opds:facetGroup SHOULD not be empty"); } FacetGroup = extAttribute.Value; } else { continue; } knowKeys.Add(extAttribute.Key); } // Remove parsed attributes. foreach (var key in knowKeys) { AttributeExtensions.Remove(key); } }
private static bool isxUnitTestClass(this Type type) { if (type.IsAbstract) { return(false); } if (type.IsStatic()) { return(false); } // All types could potentially host xUnit's facts, but we require there's at least one method marked xUnit.Fact in there return(type.GetMethods().Any(AttributeExtensions.HasAttributeDelegate("Xunit.FactAttribute", "Xunit.Sdk.XunitTest"))); }
internal void CopyAttributeExtensions(SyndicationContent source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (source._attributeExtensions != null) { foreach (XmlQualifiedName key in source._attributeExtensions.Keys) { AttributeExtensions.Add(key, source._attributeExtensions[key]); } } }
protected internal virtual bool TryParseElement(XmlReader reader, string version) { if (reader == null) { throw new ArgumentNullException("reader"); } reader.MoveToContent(); if (reader.LocalName != "service" || reader.NamespaceURI != version) { return(false); } for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (!TryParseAttribute(reader.LocalName, reader.NamespaceURI, reader.Value, version)) { AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } reader.MoveToElement(); if (reader.IsEmptyElement) { throw new XmlException("AtomPP service element requires at least one workspace element"); } reader.ReadStartElement(); for (reader.MoveToContent(); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent()) { if (reader.LocalName == "workspace" && reader.NamespaceURI == version) { var ws = CreateWorkspace(); if (ws.TryParseElement(reader, version)) { Workspaces.Add(ws); continue; } } ElementExtensions.Add(new SyndicationElementExtension(reader)); } reader.ReadEndElement(); return(true); }
public static WarehouseBuildItemRequest FromSprite(Sprite sprite, int column, int row) { var item = new WarehouseBuildItemRequest { column = column, row = row }; var behavior = AttributeExtensions.GetAssemblyTypes <SpriteAttribute>() .FirstOrDefault(x => x.attribute.Name == sprite.name || x.attribute.NamePattern.IsValid() && sprite.name.Contains(x.attribute.NamePattern)) .type; if (behavior != null) { item.itemType = behavior.ToString(); return(item); } else { // let's try to match on enum-types var enumSprites = AttributeExtensions.GetAssemblyEnumMembers <SpriteAttribute>(); var enumMatch = enumSprites.FirstOrDefault(x => x.matches.AsNotNull().Any(y => y.attributes.AsNotNull().Any(z => (z as SpriteAttribute)?.Name == sprite.name))); if (enumMatch.matches.HasItems()) { var enumType = enumMatch.enumType; var(enumName, attributes) = enumMatch.matches.First(x => x.attributes.Any(y => (y as SpriteAttribute)?.Name == sprite.name)); var spriteAttr = (SpriteAttribute)attributes.First(x => (x as SpriteAttribute).Name == sprite.name); switch (spriteAttr.Key) { case Marker.DefaultSpriteKey: item.markerType = (BoxType)Enum.Parse(enumType, enumName); break; case Box.DefaultSpriteKey: item.boxType = (BoxType)Enum.Parse(enumType, enumName); break; default: throw new NotImplementedException($"Can't resolve PlaceItem from '{spriteAttr.Key}' (sprite: {sprite?.name})."); } return(item); } } throw new ArgumentException($"Couldn't PlaceItem for sprite '{sprite?.name}'."); }
/// <summary> /// 注册 /// </summary> /// <param name="assembly">程序集实例。</param> public static void Register(System.Reflection.Assembly assembly) { if (assembly == null) { return; } var attributes = AttributeExtensions.GetCustomAttributes <ProviderAttribute>(assembly, true); foreach (var item in attributes) { if (string.IsNullOrEmpty(item.Name) || item.Type == null) { continue; } _list_cache.TryAdd(item.Name, FastWrapper.CreateInstance <IProvider>(item.Type, new object[0])); } }
/// <summary> /// 加载。 /// </summary> /// <param name="list">用于存储的列表。</param> /// <param name="attributeProvider">特性提供者。</param> public static void Load(ParameterInfoList list, System.Reflection.ICustomAttributeProvider attributeProvider) { if (list == null || attributeProvider == null) { return; } foreach (var attribute in AttributeExtensions.GetCustomAttributes <CloudArgsAttribute>(attributeProvider, true)) { if (attribute.Type == null) { continue; } list.AddRange(PropertyParameterInfo.As( FastWrapper.GetProperties(attribute.Type, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, true, true) ) ); } }
/// <summary> /// Initializes a new instance of the <see cref="T:WolfCurses.Window.Form.FormFactory" /> class. /// </summary> public FormFactory() { // Create dictionaries for reference tracking for what states belong to what game modes. LoadedForms = new Dictionary <Type, Type>(); // Collect all of the states with the custom attribute decorated on them. var foundStates = AttributeExtensions.GetTypesWith <ParentWindowAttribute>(false); foreach (var stateType in foundStates) { // GetModule the attribute itself from the state we are working on, which gives us the game Windows enum. var stateAttribute = stateType.GetTypeInfo().GetAttributes <ParentWindowAttribute>(false).First(); var stateParentMode = stateAttribute.ParentWindow; // Add the state reference list for lookup and instancing later during runtime. LoadedForms.Add(stateType, stateParentMode); } }
public static MessageLogModel FromEntity(MessageLog messageLog) { return(new MessageLogModel { DateLogged = messageLog.DateLogged, Message = messageLog.Message, MessageType = messageLog.MessageType, Context = messageLog.LogContext.ToString(), Details = messageLog.LogDetails, Errors = messageLog.LogErrors, Hint = messageLog.Hint, CorrelationId = messageLog.Message.GetCorrelationId(), DateOccurred = messageLog.Message.Attributes.GetDateTimeValue( AttributeExtensions.GetPluginScopedName("DateOccurred"), messageLog.DateLogged) }); }
private async Task <StunResult5389> BindingTestBaseAsync(IPEndPoint remote, bool notifyChanged, CancellationToken token) { BindingTestResult res; var test = new StunMessage5389 { StunMessageType = StunMessageType.BindingRequest }; var(response1, _, local1) = await TestAsync(test, remote, remote, token); var mappedAddress1 = AttributeExtensions.GetXorMappedAddressAttribute(response1); var otherAddress = AttributeExtensions.GetOtherAddressAttribute(response1); var local = local1 == null ? null : new IPEndPoint(local1, LocalEndPoint.Port); if (response1 == null) { res = BindingTestResult.Fail; } else if (mappedAddress1 == null) { res = BindingTestResult.UnsupportedServer; } else { res = BindingTestResult.Success; } if (notifyChanged) { _bindingSubj.OnNext(res); PubSubj.OnNext(mappedAddress1); } LocalSubj.OnNext(LocalEndPoint); return(new StunResult5389 { BindingTestResult = res, LocalEndPoint = local, PublicEndPoint = mappedAddress1, OtherEndPoint = otherAddress }); }
/// <summary> /// Initializes a new instance of the <see cref="T:OregonTrailDotNet.Module.Director.EventFactory" /> class. /// </summary> public EventFactory() { // Create dictionaries for storing event reference types, history of execution, and execution count. EventReference = new Dictionary <EventKey, Type>(); // Collect all of the event types with the attribute decorated on them. var randomEvents = AttributeExtensions.GetTypesWith <DirectorEventAttribute>(true); foreach (var eventObject in randomEvents) { // Check if the class is abstract base class, we don't want to add that. if (eventObject.GetTypeInfo().IsAbstract) { continue; } // Check the attribute itself from the event we are working on, which gives us the event type enum. var eventAttribute = eventObject.GetTypeInfo().GetAttributes <DirectorEventAttribute>(true).First(); var eventType = eventAttribute.EventCategory; // Initialize the execution history dictionary with every event type. foreach (var modeType in Enum.GetValues(typeof(EventCategory))) { // Only proceed if enum value matches attribute enum value for event type. if (!modeType.Equals(eventType)) { continue; } // Create key for the event execution counter. var eventKey = new EventKey((EventCategory)modeType, eventObject.Name, eventAttribute.EventExecutionType); // Reference type for creating instances. if (!EventReference.ContainsKey(eventKey)) { EventReference.Add(eventKey, eventObject); } } } }
protected internal virtual bool TryParseElement(XmlReader reader, string version) { if (reader == null) { throw new ArgumentNullException("reader"); } reader.MoveToContent(); if (reader.LocalName != "collection" || reader.NamespaceURI != version) { return(false); } for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (!TryParseAttribute(reader.LocalName, reader.NamespaceURI, reader.Value, version)) { AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } reader.MoveToElement(); if (!reader.IsEmptyElement) { reader.Read(); for (reader.MoveToContent(); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent()) { if (reader.LocalName == "title" && reader.NamespaceURI == Namespaces.Atom10) { Title = Atom10FeedFormatter.ReadTextSyndicationContent(reader); } else { ElementExtensions.Add(new SyndicationElementExtension(reader)); } } } reader.Read(); return(true); }
/// <summary> /// Applies the extensions in adapter to ExtensibleBase /// </summary> public void AddExtensions(IExtensionAdapter adapter) { if (adapter == null) { return; } IEnumerable <XmlAttribute> attributes = adapter.GetAttributeEntensions(); if (attributes != null) { AttributeExtensions.AddRange(attributes); } IEnumerable <XmlElement> elements = adapter.GetElementExtensions(); if (elements != null) { ElementExtensions.AddRange(elements); } }
static System.Collections.Generic.List <BindItem> TryGetBind(System.Type entityType) { string key = entityType.AssemblyQualifiedName; System.Collections.Generic.List <BindItem> list; if (!_list_key.TryGetValue(key, out list)) { ThreadHelper.Block(_list_key, () => { if (!_list_key.TryGetValue(key, out list)) { if (entityType.IsValueType || entityType == typeof(string) || entityType == typeof(object) || TypeExtensions.IsNullableType(entityType)) { _list_key.TryAdd(key, null); return; } list = new System.Collections.Generic.List <BindItem>(); foreach (System.Reflection.PropertyInfo propertyInfo in entityType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.SetProperty)) { var binder = AttributeExtensions.GetCustomAttribute <DataBinderAttribute>(propertyInfo); if (binder == null) { continue; } BindItem bindItem = new BindItem() { propertyInfo = propertyInfo, binder = binder, bindAction = binder.Bind, }; list.Add(bindItem); } _list_key.TryAdd(key, list.Count == 0 ? null : list); } }); } return(list); }
public static string Decrypt <T>(Expression <Func <T> > property) { var value = property.Compile()(); var cipherText = value.ToString(); try { var passPhrase = AttributeExtensions.GetCustomAttribute <T, EncryptAttribute>(property).Key; var cipherTextBytes = Convert.FromBase64String(cipherText); using (var password = new PasswordDeriveBytes(passPhrase, null)) { var keyBytes = password.GetBytes(keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)) { using (var memoryStream = new MemoryStream(cipherTextBytes)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var plainTextBytes = new byte[cipherTextBytes.Length]; var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); } } } } } } catch (Exception) { return(cipherText); } }
public static List <TokenMatch> Tokenize(string codeStr, params ExpressionToken[] exceptFor) { var code = new StringBuilder(codeStr); var allTokens = new List <(string Regex, ExpressionToken Token, List <ExpressionToken> Swallows, int Order)>( Enum.GetValues(typeof(ExpressionToken)).Cast <ExpressionToken>() .Where(t => AttributeExtensions.GetAttribute <ManuallySearchedAttribute>(t) == null) .Select(t => { List <ExpressionToken> DetermineSwallows(ExpressionToken tkn, List <ExpressionToken> @return) { @return = @return ?? new List <ExpressionToken>(); List <ExpressionToken> swlws = tkn.GetAttributes <SwallowsAttribute>().SelectMany(sw => sw.Targets).Distinct().ToList(); foreach (var set in swlws) { @return.Add(set); return(DetermineSwallows(set, @return)); } return(@return); } var attr = AttributeExtensions.GetAttribute <ExpressionTokenAttribute>(t); if (attr == null) { return(default);
/// <summary> /// Creates the where clause of the SPARQL query - the part that indicates what the properties of selected objects should be. /// </summary> /// <param name="sb">A <see cref="StringBuilder"/> into which the SPARQL should be inserted.</param> private void CreateWhereClause(StringBuilder sb) { // if using an identity projection then every available property of the type must be returned bool isIdentityProjection = OriginalType == typeof(T); // if there is no where clause then we want every instance back (and we won't be filtering) // the logic around this is a little tricky (or debatable) - // Given that you could have instances that are partially complete in the triple store (i.e. not all triples are present) // you need to be able to ensure that a query that does not explicitly include the missing properties does not // exclude any instances where those properties are missing. // I've reasoned that if you perform an identity projection, then you're saying "get me whatever you can", whereas if // you specifically request a certain property (via a projection) then you really must want a value for that, and thus // instances must be excluded where there is no value _known_ - Hence the '|| IsIdentityProjection'. bool getAnythingThatYouCan = !(Expressions.ContainsKey("Where")) || isIdentityProjection /* */; // using "$" distinguishes this varName from anything that could be introduced from the properties of the type // therefore the varName is 'safe' in the sense that there can never be a name clash. string varName = "$" + GetInstanceName(); sb.Append("WHERE {\n"); // if parameters have been defined somewhere. If using an identity projection then we will not be getting anything from projectionParameters // if we have no WHERE expression, then we also won't be getting anything from queryGraphParameters var parameters = new List <MemberInfo>(QueryGraphParameters.Union(ProjectionParameters)); if (parameters.Count == 0) { // is it an identity projection? If so, place all persistent properties into parameters if (isIdentityProjection) { foreach (PropertyInfo info in OwlClassSupertype.GetAllPersistentProperties(OriginalType)) { parameters.Add(info); } } } // if (parameters.Count > 0) // { sb.AppendFormat("{0} a {1}:{2} .\n", varName, OriginalType.GetOntology().Prefix, OriginalType.GetOwlResource().RelativeUriReference); // } // else // { // // I don't think there is any way to get into to this point unless the object is persistent, but has no // throw new ApplicationException( // "No persistent properties defined on the entity. Unable to generate a query."); // } // // temp var to get the object variables list IEnumerable <MemberInfo> args; // a temp string to get the tripleFormat that will be used to generate query triples. string tripleFormat = "OPTIONAL{{{0} {1}:{2} ?{3} .}}\n"; if (!getAnythingThatYouCan) { tripleFormat = "{0} {1}:{2} ?{3} .\n"; } if (isIdentityProjection) { args = OwlClassSupertype.GetAllPersistentProperties(OriginalType); } else { args = parameters; } foreach (MemberInfo arg in args) { // The ontology and prefix assigned to a class property need not match those assigned to the class itself. // e.g. The class could have a property which maps to foaf:name, or dc:title. OwlResourceAttribute ora = arg.GetOwlResource(); sb.AppendFormat(tripleFormat, varName, AttributeExtensions.GetOntologyPrefix(ora.OntologyName), //WAS: originalType.GetOntology().Prefix, ora.RelativeUriReference, arg.Name); } if (!string.IsNullOrEmpty(PropertyReferenceTriple)) { sb.AppendLine(PropertyReferenceTriple); } if (!string.IsNullOrEmpty(FilterClause)) { sb.AppendFormat("FILTER( {0} )\n", FilterClause); } sb.Append("}\n"); }
private async Task <StunResult5389> FilteringBehaviorTestBaseAsync(CancellationToken token) { // test I var result1 = await BindingTestBaseAsync(RemoteEndPoint, true, token); try { if (result1.BindingTestResult != BindingTestResult.Success) { return(result1); } if (result1.OtherEndPoint == null || Equals(result1.OtherEndPoint.Address, RemoteEndPoint.Address) || result1.OtherEndPoint.Port == RemoteEndPoint.Port) { result1.FilteringBehavior = FilteringBehavior.UnsupportedServer; return(result1); } // test II var test2 = new StunMessage5389 { StunMessageType = StunMessageType.BindingRequest, Attributes = new[] { AttributeExtensions.BuildChangeRequest(true, true) } }; var(response2, _, _) = await TestAsync(test2, RemoteEndPoint, result1.OtherEndPoint, token); if (response2 != null) { result1.FilteringBehavior = FilteringBehavior.EndpointIndependent; return(result1); } // test III var test3 = new StunMessage5389 { StunMessageType = StunMessageType.BindingRequest, Attributes = new[] { AttributeExtensions.BuildChangeRequest(false, true) } }; var(response3, remote3, _) = await TestAsync(test3, RemoteEndPoint, RemoteEndPoint, token); if (response3 == null) { result1.FilteringBehavior = FilteringBehavior.AddressAndPortDependent; return(result1); } if (Equals(remote3.Address, RemoteEndPoint.Address) && remote3.Port != RemoteEndPoint.Port) { result1.FilteringBehavior = FilteringBehavior.AddressAndPortDependent; } else { result1.FilteringBehavior = FilteringBehavior.UnsupportedServer; } return(result1); } finally { _filteringBehaviorSubj.OnNext(result1.FilteringBehavior); } }
static ReferenceIdentity() { _literalRegex = AttributeExtensions.GetAttribute <ExpressionTokenAttribute>(ExpressionToken.Literal).Regex; }
/// <summary> /// Main entry point for he business logic that the plug-in is to execute. /// </summary> /// <param name="serviceProvider">The service provider.</param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> public void Execute(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new InvalidPluginExecutionException(string.Format(ResponseMessages.NoServiceProvider, PluginName)); var localContext = new LocalPluginContext(serviceProvider); localContext.Trace(CultureInfo.InvariantCulture, TraceMessages.EnteringPlugin, PluginName); #region Load Config var configAttributeSettings = AttributeExtensions.GetCrmPluginConfigurationAttribute(GetType()); ConfigType = configAttributeSettings.ConfigType; if (configAttributeSettings.AutoLoad) try { LoadConfig(); } catch (Exception ex) { localContext.Trace(CultureInfo.InvariantCulture, TraceMessages.ErrorLoadingConfig, ex.Message); } #endregion var registrationAttributes = AttributeExtensions.GetCrmPluginRegistrationAttributes(GetType()).ToList(); var execContext = localContext.PluginExecutionContext; #region Validate Primary EntityName (if specified) if (!registrationAttributes.IsValidEntity(execContext.PrimaryEntityName)) throw new InvalidPluginExecutionException( string.Format(ResponseMessages.InvalidEntity, execContext.PrimaryEntityName, PluginName)); #endregion #region Validate Message Names if (!registrationAttributes.IsValidMessageName(execContext.MessageName)) throw new InvalidPluginExecutionException( string.Format(ResponseMessages.InvalidMessageName, execContext.MessageName, PluginName)); #endregion #region Validate Message Name and Entity Name combination if (!registrationAttributes.IsValidMessageAndEntityName(execContext.MessageName, execContext.PrimaryEntityName)) throw new InvalidPluginExecutionException( string.Format(ResponseMessages.InvalidMessageEntityCombination, execContext.MessageName, execContext.PrimaryEntityName, PluginName)); #endregion try { // Invoke the custom implementation Execute(localContext); // now exit if (configAttributeSettings.ForceErrorWhenComplete) throw new InvalidPluginExecutionException(string.Format(ResponseMessages.PluginAborted, PluginName)); } catch (FaultException<OrganizationServiceFault> e) { localContext.Trace(TraceMessages.OrganizationServiceFault, PluginName); localContext.Trace(e); throw; } catch (InvalidPluginExecutionException pex) { localContext.Trace(TraceMessages.OrganizationServiceFault, PluginName); localContext.Trace(pex); throw; } catch (Exception ex) { localContext.Trace(TraceMessages.OrganizationServiceFault, PluginName); localContext.Trace(ex); // Handle the exception. throw new InvalidPluginExecutionException( string.Format(ResponseMessages.OrganizationServiceFault, PluginName), ex); } finally { localContext.Trace(CultureInfo.InvariantCulture, TraceMessages.ExitingPlugin, PluginName); } }