public void EqualityTest_SimpleType_DifferentVersion() { AssetIdentifier aid = AssetIdentifier.Parse("{T:System.Object, V:4.1.2.3}"); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(object)); Assert.False(aid.Equals(aid2)); }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { MonobehaviourAsset monobehaviour = new MonobehaviourAsset(); int fileId = reader.ReadInt32(); monobehaviour.GameObjectIdentifier = new AssetIdentifier(relativeFileIdToPath[fileId], reader.ReadInt64()); monobehaviour.Enabled = reader.ReadBoolean(); reader.Align(); monobehaviour.MonoscriptIdentifier = new AssetIdentifier(relativeFileIdToPath[reader.ReadInt32()], reader.ReadInt64()); monobehaviour.Name = reader.ReadCountStringInt32(); // Hack - If we have not yet loaded monoscripts then we are currently processing unit monobehaviours // that we do not care about. Monoscripts should be fully loaded before we actually parse anything // we do care about in resource.assets. If this becomes a problem later, we can do two passes and // load monobeahviours in the second pass. if (!MonoscriptAssetParser.MonoscriptsByAssetId.ContainsKey(monobehaviour.MonoscriptIdentifier)) { return; } MonoscriptAsset monoscript = MonoscriptAssetParser.MonoscriptsByAssetId[monobehaviour.MonoscriptIdentifier]; monobehaviour.MonoscriptName = monoscript.Name; if (monobehaviourParsersByMonoscriptName.TryGetValue(monoscript.Name, out MonobehaviourParser monoResourceParser)) { monoResourceParser.Parse(identifier, monobehaviour.GameObjectIdentifier, reader, resourceAssets, relativeFileIdToPath); } MonobehavioursByAssetId.Add(identifier, monobehaviour); }
public void EqualityTest_ClosedGenericType_NotEqual() { AssetIdentifier aid = AssetIdentifier.FromMemberInfo(typeof(List <string>)); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(HashSet <string>)); Assert.False(aid.Equals(aid2)); }
public void EqualityTest_ClosedGenericType_EqualTypeParam() { AssetIdentifier aid = AssetIdentifier.FromMemberInfo(typeof(List <int>)); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(List <int>)); Assert.True(aid.Equals(aid2)); }
public void EqualityTest_SimpleType_NotEqual() { AssetIdentifier aid = AssetIdentifier.FromMemberInfo(typeof(string)); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(int)); Assert.False(aid.Equals(aid2)); }
public void EqualityTest_OpenGenericType() { AssetIdentifier aid = AssetIdentifier.FromMemberInfo(typeof(List <>)); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(List <>)); Assert.True(aid.Equals(aid2)); }
public T Take <T>(string id, bool ins = true) where T : class { Performance.RecordProfiler(nameof(Take)); object retv; if (!_pool.TryGetValue(id, out var resi)) { Performance.RecordProfiler(nameof(AssetIdentifier)); resi = new AssetIdentifier(id, typeof(T)); resi.Load(); //load for the first time _pool.Add(id, resi); //add to pool Performance.End(nameof(AssetIdentifier), true, $"first load:{id}"); } if (!ins) { retv = resi.Mapped; } else if (!TryGetRecycle(resi, out retv)) //look for reusable fails, load pool prototype { retv = resi.Instantiate(); } if (retv == null) { return(null); } if (ins) { ActivateObject(retv, resi); } Performance.End(nameof(Take)); return(retv as T); }
public void ParseOpenGenericTypeAssetId_TwoParams() { AssetIdentifier aid = AssetIdentifier.Parse("{T:System.Collections.Generic.Dictionary`2, V:4.0.0.0}"); AssetIdentifier aid2 = AssetIdentifier.FromMemberInfo(typeof(Dictionary <string, string>)); Assert.Equal(aid.ToString(), aid2.ToString()); }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets) { MonobehaviourAsset monobehaviour = new MonobehaviourAsset(); monobehaviour.GameObjectIdentifier = new AssetIdentifier((uint)reader.ReadInt32(), (ulong)reader.ReadInt64()); monobehaviour.Enabled = reader.ReadInt32(); // unknown but assume this is what it is monobehaviour.MonoscriptIdentifier = new AssetIdentifier((uint)reader.ReadInt32(), (ulong)reader.ReadInt64()); monobehaviour.Name = reader.ReadCountStringInt32(); // Hack - If we have not yet loaded monoscripts then we are currently processing unit monobehaviours // that we do not care about. Monoscripts should be fully loaded before we actually parse anything // we do care about in resource.assets. If this becomes a problem later, we can do two passes and // load monobeahviours in the second pass. if (!MonoscriptAssetParser.MonoscriptsByAssetId.ContainsKey(monobehaviour.MonoscriptIdentifier)) { return; } MonoscriptAsset monoscript = MonoscriptAssetParser.MonoscriptsByAssetId[monobehaviour.MonoscriptIdentifier]; monobehaviour.MonoscriptName = monoscript.Name; MonobehaviourParser monoResourceParser; if (monobehaviourParsersByMonoscriptName.TryGetValue(monoscript.Name, out monoResourceParser)) { monoResourceParser.Parse(identifier, monobehaviour.GameObjectIdentifier, reader, resourceAssets); } MonobehavioursByAssetId.Add(identifier, monobehaviour); }
public override void Parse(AssetIdentifier identifier, AssetIdentifier gameObjectIdentifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { string classId = reader.ReadCountStringInt32(); ClassIdByGameObjectId.Add(gameObjectIdentifier, classId); GameObjectIdByClassId.Add(classId, gameObjectIdentifier); }
public bool AddReference(string assetId) { if (string.IsNullOrEmpty(assetId)) throw new ArgumentException("Argument cannot be null or empty.", "assetId"); AssetIdentifier aid = AssetIdentifier.Parse(assetId); Debug.Assert(aid.ToString().Equals(assetId, StringComparison.Ordinal), "AssetIdentifier '{0}' failed to roundtrip.", assetId); if (aid.AssetId[aid.AssetId.Length - 1] == ']') aid = new AssetIdentifier(aid.AssetId.Substring(0, aid.AssetId.LastIndexOf('[')), aid.Version); object resolve = this.AssetResolver.Resolve(aid); Debug.Assert(resolve != null); Debug.Assert(!string.IsNullOrWhiteSpace(aid.AssetId)); if (this._references.Add(aid)) { TraceSources.GeneratorSource.TraceEvent(TraceEventType.Verbose, 1, "Reference: {0}", aid); return true; } return false; }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { string assetName = reader.ReadCountStringInt32(); if (assetName == "RandomStart") { reader.Position += 9; int width = reader.ReadInt32(); int height = reader.ReadInt32(); int imageSize = reader.ReadInt32(); reader.Position += 52; byte[] data = reader.ReadBytes(imageSize); byte[] decodedData = AssetsTools.NET.Extra.DXTDecoders.ReadDXT1(data, width, height); using (MemoryStream stream = new MemoryStream(decodedData)) { Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); Rectangle dimension = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData picData = bmp.LockBits(dimension, ImageLockMode.ReadWrite, bmp.PixelFormat); picData.Stride = width * 4; IntPtr pixelStartAddress = picData.Scan0; Marshal.Copy(decodedData, 0, pixelStartAddress, decodedData.Length); bmp.UnlockBits(picData); resourceAssets.NitroxRandom = new RandomStartGenerator(bmp); } } }
public override void Parse(AssetIdentifier identifier, AssetIdentifier gameObjectIdentifier, AssetsFileReader reader, ResourceAssets resourceAssets) { string classId = reader.ReadCountStringInt32(); ClassIdByGameObjectId.Add(gameObjectIdentifier, classId); GameObjectIdByClassId.Add(classId, gameObjectIdentifier); }
public bool Filter(IFilterContext context, AssetIdentifier asset) { object obj = context.AssetResolver.Resolve(asset); if (!(obj is FieldInfo) || !((FieldInfo)obj).DeclaringType.IsEnum) return false; return !(((FieldInfo)obj).IsStatic && ((FieldInfo)obj).IsPublic); }
public void BuildAssetsUrlFromId_WithGivenAssetId_ReturnsExpectedUrl() { var assetId = Guid.NewGuid(); var expectedResult = $"https://manage.kenticocloud.com/projects/{PROJECT_ID}/assets/{assetId}"; var actualResult = _builder.BuildAssetsUrl(AssetIdentifier.ById(assetId)); Assert.Equal(expectedResult, actualResult); }
public override bool Equals(object obj) { AssetIdentifier identifier = obj as AssetIdentifier; return(identifier != null && FileId == identifier.FileId && IndexId == identifier.IndexId); }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { MonoscriptAsset monoscriptAsset = new MonoscriptAsset(); monoscriptAsset.Name = reader.ReadCountStringInt32(); MonoscriptsByAssetId.Add(identifier, monoscriptAsset); }
public object Resolve(AssetIdentifier assetIdentifier, AssetIdentifier hintAssembly) { object ret; if (!this._cache.TryGetValue(assetIdentifier, out ret)) this._cache.Add(assetIdentifier, ret = this.ResolveInternal(assetIdentifier, (Assembly)this.ResolveInternal(hintAssembly))); return ret; }
public bool Filter(IFilterContext context, AssetIdentifier asset) { Type t = context.AssetResolver.Resolve(asset) as Type; if (t != null) return Filter(context, t); return false; }
public bool Filter(IFilterContext context, AssetIdentifier asset) { MemberInfo mi = context.AssetResolver.Resolve(asset) as MemberInfo; if (mi != null) return Filter(context, mi); return false; }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets) { MonoscriptAsset monoscriptAsset = new MonoscriptAsset(); monoscriptAsset.Name = reader.ReadCountStringInt32(); MonoscriptsByAssetId.Add(identifier, monoscriptAsset); }
private Optional <NitroxEntitySlot> GetEntitySlot(string classId) { AssetIdentifier prefabId = PrefabIdentifierParser.GameObjectIdByClassId[classId]; GameObjectAsset gameObject = GameObjectAssetParser.GameObjectsByAssetId[prefabId]; EntitySlotParser.EntitySlotsByIdentifier.TryGetValue(gameObject.Identifier, out NitroxEntitySlot entitySlot); return(Optional.OfNullable(entitySlot)); }
public void RoundTripTypes(string assetId) { Debug.WriteLine(assetId); AssetIdentifier aid = AssetIdentifier.Parse(assetId); object obj = this._resolver.Resolve(aid); Assert.NotNull(obj); Assert.Equal(assetId, AssetIdentifier.FromMemberInfo((Type)obj).AssetId); }
public void RoundTripMember(string assetId) { Debug.WriteLine(assetId); AssetIdentifier aid = AssetIdentifier.Parse(assetId); MemberInfo obj = (MemberInfo)this._resolver.Resolve(aid); Assert.NotNull(obj); Assert.Equal(assetId, AssetIdentifier.FromMemberInfo(obj).AssetId); }
public void ParseSimpleUnknown() { AssetIdentifier aid = AssetIdentifier.Parse("Overload:System.Xml.XmlWriter.Create"); Assert.Equal(AssetType.Unknown, aid.Type); Assert.Equal("Overload", aid.TypeMarker); Assert.Equal("Overload:System.Xml.XmlWriter.Create", aid.AssetId); Assert.Null(aid.Version); Assert.False(aid.HasVersion); }
/// <summary> /// Deletes given asset. /// </summary> /// <param name="identifier">The identifier of the asset.</param> public async Task DeleteAssetAsync(AssetIdentifier identifier) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } var endpointUrl = _urlBuilder.BuildAssetsUrl(identifier); await _actionInvoker.InvokeMethodAsync(endpointUrl, HttpMethod.Delete); }
public void ParseSimpleAssetId_Method() { AssetIdentifier aid = AssetIdentifier.Parse("M:System.Object.ToString"); Assert.Equal(AssetType.Method, aid.Type); Assert.Equal("M", aid.TypeMarker); Assert.Equal("M:System.Object.ToString", aid.AssetId); Assert.Null(aid.Version); Assert.False(aid.HasVersion); }
public override void Parse(AssetIdentifier identifier, AssetIdentifier gameObjectIdentifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { PrefabPlaceholderAsset prefabPlaceholderAsset = new PrefabPlaceholderAsset(); prefabPlaceholderAsset.Identifier = identifier; prefabPlaceholderAsset.GameObjectIdentifier = gameObjectIdentifier; prefabPlaceholderAsset.ClassId = reader.ReadCountStringInt32(); PrefabPlaceholderIdToPlaceholderAsset.Add(identifier, prefabPlaceholderAsset); }
void ActivateObject(object resObject, AssetIdentifier resId) { Performance.RecordProfiler(nameof(ActivateObject)); _activePool.Add(resObject, resId); if (resObject is GameObject rObj) { rObj.transform.SetParent(ActiveObjectRoot, false); } Performance.End(nameof(ActivateObject)); }
public void ParseSimpleAssetId_WithVersion() { AssetIdentifier aid = AssetIdentifier.Parse("{T:System.Object, V:4.1.2.3}"); Assert.Equal(AssetType.Type, aid.Type); Assert.Equal("T", aid.TypeMarker); Assert.Equal("T:System.Object", aid.AssetId); Assert.Equal(new Version(4, 1, 2, 3), aid.Version); Assert.True(aid.HasVersion); }
public override void Parse(AssetIdentifier identifier, AssetsFileReader reader, ResourceAssets resourceAssets, Dictionary <int, string> relativeFileIdToPath) { string assetName = reader.ReadCountStringInt32(); if (textParsersByAssetName.TryGetValue(assetName, out AssetParser textResourceParser)) { textResourceParser.Parse(identifier, reader, resourceAssets, relativeFileIdToPath); } }
public void ParseSimpleAssetId_NestedTypeAssetIdWithGenericParent() { AssetIdentifier aid = AssetIdentifier.Parse("T:System.Collections.Generic.List`1.Enumerator"); Assert.Equal(AssetType.Type, aid.Type); Assert.Equal("T", aid.TypeMarker); Assert.Equal("T:System.Collections.Generic.List`1.Enumerator", aid.AssetId); Assert.Null(aid.Version); Assert.False(aid.HasVersion); }
public void ParseSimpleAssetId_Type() { AssetIdentifier aid = AssetIdentifier.Parse("T:System.Object"); Assert.Equal(AssetType.Type, aid.Type); Assert.Equal("T", aid.TypeMarker); Assert.Equal("T:System.Object", aid.AssetId); Assert.Null(aid.Version); Assert.False(aid.HasVersion); }
public void GetDeclaringType_WithHintAssembly(string assetId, Type declaringType) { AssetIdentifier aid = AssetIdentifier.Parse(assetId); int pos = 0; Type resolvedType = this._resolver.GetDeclaringType(aid.AssetId.Substring(aid.TypeMarker.Length + 1), ref pos, declaringType.Assembly); Assert.Equal(declaringType.AssemblyQualifiedName, resolvedType.AssemblyQualifiedName); }
public override int GetHashCode() { #if UNITY_EDITOR if (AssetIdentifier == "") { Debug.LogError("Saveable asset has not been initialized yet! To fix this click in the Menue \"SaveableAssets -> Validate all Assets\"."); } #endif return(AssetIdentifier.GetHashCode()); }
public string resolveAsset(string assetId, string version) { string ret = null; AssetIdentifier aid = null; // perform asset redirect if (!string.IsNullOrEmpty(version)) { aid = new AssetIdentifier(assetId, Version.Parse(version)); AssetIdentifier targetAid; if (this._context.TemplateData.AssetRedirects.TryGet(aid, out targetAid)) { assetId = targetAid.AssetId; version = targetAid.Version.ToString(); TraceSources.AssetResolverSource.TraceVerbose("Redirected assetd {0} => {1}", aid, targetAid); } } if (aid == null) aid = new AssetIdentifier(assetId, new Version()); // TODO this doesn't seem very threadsafe, use concurrent dictionary? if (!_resolveCache.TryGetValue(aid, out ret)) { for (int i = 0; i < this._context.AssetUriResolvers.Length; i++) { Uri target = this._context.AssetUriResolvers[i].ResolveAssetId(assetId, string.IsNullOrEmpty(version) ? null : new Version(version)); if (target != null) { if (!target.IsAbsoluteUri) target = this.MakeRelative(target); ret = target.ToString(); break; } } _resolveCache.Add(aid, ret); } if (ret == null) { ret = "urn:asset-not-found:" + assetId + "," + version; TraceSources.AssetResolverSource.TraceWarning("{0}, {1} => {2}", assetId, version, ret); } else TraceSources.AssetResolverSource.TraceVerbose("{0}, {1} => {2}", assetId, version, ret); return ret; }
private string ResolveAssetIdentifier(AssetIdentifier aid) { for (int i = 0; i < this._context.AssetUriResolvers.Length; i++) { Uri target = this._context.AssetUriResolvers[i].ResolveAssetId(aid.AssetId, aid.HasVersion ? aid.Version : null); if (target != null) { if (!target.IsAbsoluteUri) target = this.MakeRelative(target); return target.ToString(); } } return null; }
public string getVersionedId(string assetId) { AssetIdentifier aid = AssetIdentifier.Parse(assetId); AssetIdentifier hintAsmAid = null; if (this._hintAssembly != null) hintAsmAid = AssetIdentifier.FromAssembly(this._hintAssembly); if (aid.Type == AssetType.Assembly) { Assembly asm = (Assembly)this._context.AssetResolver.Resolve(aid, hintAsmAid); aid = AssetIdentifier.FromAssembly(asm); } else if (aid.Type == AssetType.Namespace) { string ns = aid.AssetId.Substring(aid.TypeMarker.Length + 1); var version = this.GetNamespaceVersion(this._hintAssembly, ns); if (version == null) throw new Exception("Version not found for asset: " + assetId); aid = AssetIdentifier.FromNamespace(ns, version); } else { object obj = this._context.AssetResolver.Resolve(aid, hintAsmAid); if (aid.Type == AssetType.Unknown) { MethodInfo[] arr = obj as MethodInfo[]; if (arr != null) { // TODO this isn't very nice but it should do the trick for now var dummyAid = AssetIdentifier.FromMemberInfo(arr[0]); aid = new AssetIdentifier(aid.AssetId, dummyAid.Version); } else throw new NotSupportedException("Unknow AssetIdentifier marker: " + aid.TypeMarker); } else aid = AssetIdentifier.FromMemberInfo((MemberInfo)obj); } this._context.AddReference(aid); return aid.ToString(); }
private EventInfo ResolveEvent(AssetIdentifier assetIdentifier, Assembly hintAssembly) { string asset = assetIdentifier.AssetId.Substring(assetIdentifier.TypeMarker.Length + 1); int startIndex = 0; Type type = this.GetDeclaringType(asset, ref startIndex, hintAssembly); EventInfo[] allEvents = type.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); return allEvents.Single(e => Naming.GetAssetId(e).Equals(assetIdentifier.AssetId)); }
public string resolveAsset(string assetId, string version) { string ret = null; AssetIdentifier aid = null; // perform asset redirect if (!string.IsNullOrEmpty(version)) { aid = new AssetIdentifier(assetId, Version.Parse(version)); AssetIdentifier targetAid; if (this._context.TemplateData.AssetRedirects.TryGet(aid, out targetAid)) { assetId = targetAid.AssetId; version = targetAid.Version.ToString(); TraceSources.AssetResolverSource.TraceVerbose("Redirected assetd {0} => {1}", aid, targetAid); } } if (aid == null) aid = new AssetIdentifier(assetId, new Version()); ret = _resolveCache.GetOrAdd(aid, id => ResolveAssetIdentifier(assetId, version)); if (ret == null) { ret = "urn:asset-not-found:" + assetId + "," + version; TraceSources.AssetResolverSource.TraceWarning("{0}, {1} => {2}", assetId, version, ret); } else TraceSources.AssetResolverSource.TraceVerbose("{0}, {1} => {2}", assetId, version, ret); return ret; }
public bool IsFiltered(AssetIdentifier assetId) { IFilterContext filterContext = new FilterContext(this.Cache, this.Container, this.AssetResolver, FilterState.Generating); for (int i = 0; i < this._filters.Length; i++) { if (this._filters[i].Filter(filterContext, assetId)) { TraceSources.GeneratorSource.TraceEvent(TraceEventType.Verbose, 0, "{0} - Filtered by {1}", assetId.AssetId, this._filters[i]); return true; } } return false; }
public AssetSection(AssetIdentifier aid, string name, Uri uri) { this.AssetIdentifier = aid; this.Name = name; this.Uri = uri; }
private XElement GenerateEventElement(IProcessingContext context, AssetIdentifier assetId) { EventInfo eventInfo = (EventInfo)context.AssetResolver.Resolve(assetId); XElement ret = new XElement("event", new XAttribute("name", eventInfo.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); GenerateTypeRef(context.Clone(ret), eventInfo.EventHandlerType); MethodInfo addMethod = eventInfo.GetAddMethod(true); MethodInfo removeMethod = eventInfo.GetRemoveMethod(true); if (addMethod != null) { var addElem = new XElement("add"); if (addMethod.IsPublic) addElem.Add(new XAttribute("isPublic", XmlConvert.ToString(addMethod.IsPublic))); if (addMethod.IsPrivate) addElem.Add(new XAttribute("isPrivate", XmlConvert.ToString(addMethod.IsPrivate))); if (addMethod.IsFamily) addElem.Add(new XAttribute("isProtected", XmlConvert.ToString(addMethod.IsFamily))); ret.Add(addElem); } if (removeMethod != null) { var removeElem = new XElement("remove"); if (removeMethod.IsPublic) removeElem.Add(new XAttribute("isPublic", XmlConvert.ToString(removeMethod.IsPublic))); if (removeMethod.IsPrivate) removeElem.Add(new XAttribute("isPrivate", XmlConvert.ToString(removeMethod.IsPrivate))); if (removeMethod.IsFamily) removeElem.Add(new XAttribute("isProtected", XmlConvert.ToString(removeMethod.IsFamily))); ret.Add(removeElem); } context.Element.Add(ret); this.GenerateImplementsElement(context.Clone(ret), eventInfo); foreach (IEnricher item in this.Enrichers) item.EnrichEvent(context.Clone(ret), eventInfo); return ret; }
private object ResolveField(AssetIdentifier assetIdentifier, Assembly hintAssembly) { string asset = assetIdentifier.AssetId.Substring(assetIdentifier.TypeMarker.Length + 1); int startIndex = 0; Type type = this.GetDeclaringType(asset, ref startIndex, hintAssembly); if (type.IsEnum) { MemberInfo[] members = type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (MemberInfo memberInfo in members) { AssetIdentifier ret = AssetIdentifier.FromMemberInfo(memberInfo); if (ret.AssetId == assetIdentifier.AssetId) return memberInfo; } return null; } else { FieldInfo[] allFields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); return allFields.Single(f => Naming.GetAssetId(f).Equals(assetIdentifier.AssetId)); } }
private MethodInfo[] ResolveOverloads(AssetIdentifier assetIdentifier, Assembly hintAssembly) { string asset = assetIdentifier.AssetId.Substring(assetIdentifier.TypeMarker.Length + 1); int startIndex = 0; Type type = this.GetDeclaringType(asset, ref startIndex, hintAssembly); string methodName = asset.Substring(startIndex + 1); var allMethods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); return allMethods .Where(m => m.Name.Equals(methodName, StringComparison.Ordinal)) .ToArray(); }
private bool IsFiltered(IFilterContext filterContext, AssetIdentifier typeAsset) { bool filtered = false; foreach (IAssetFilter filter in this.AssetFilters) { if (filter.Filter(filterContext, typeAsset)) { filtered = true; TraceSources.GeneratorSource.TraceEvent(TraceEventType.Verbose, 0, "{0} - Filtered by {1}", typeAsset.AssetId, filter); break; } } return filtered; }
private XElement GenerateAssemblyElement(IProcessingContext context, AssetIdentifier assetId) { Assembly asm = (Assembly)context.AssetResolver.Resolve(assetId); var ret = new XElement("assembly", new XAttribute("name", asm.GetName().Name), new XAttribute("filename", asm.ManifestModule.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase), asm.GetReferencedAssemblies().Select( an => new XElement("references", new XAttribute("assembly", AssetIdentifier. FromAssembly( Assembly . ReflectionOnlyLoad (an . FullName)))))); context.Element.Add(ret); foreach (IEnricher enricher in this._enrichers) enricher.EnrichAssembly(context.Clone(ret), asm); return ret; }
private XElement GenerateTypeElement(IProcessingContext context, AssetIdentifier assetId) { XElement ret; Type type = (Type)context.AssetResolver.Resolve(assetId); string elemName; if (type.IsClass) elemName = "class"; else if (type.IsEnum) elemName = "enum"; else if (type.IsValueType) elemName = "struct"; else if (type.IsInterface) elemName = "interface"; else throw new ArgumentException("Unknown asset type: " + assetId.Type.ToString(), "assetId"); ret = new XElement(elemName, new XAttribute("name", type.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); if (type.IsEnum) { AssetIdentifier aid = AssetIdentifier.FromType(type.GetEnumUnderlyingType()); ret.Add(new XAttribute("underlyingType", aid)); context.AddReference(aid); } if (!type.IsInterface && type.IsAbstract) ret.Add(new XAttribute("isAbstract", XmlConvert.ToString(type.IsAbstract))); if (!type.IsVisible || type.IsNested && type.IsNestedAssembly) ret.Add(new XAttribute("isInternal", XmlConvert.ToString(true))); if (type.IsPublic || type.IsNested && type.IsNestedPublic) ret.Add(new XAttribute("isPublic", XmlConvert.ToString(true))); if (type.IsNested && type.IsNestedPrivate) ret.Add(new XAttribute("isPrivate", XmlConvert.ToString(true))); if (type.IsNested && type.IsNestedFamily) ret.Add(new XAttribute("isProtected", XmlConvert.ToString(true))); if (type.IsNested && type.IsNestedFamANDAssem) ret.Add(new XAttribute("isProtectedAndInternal", XmlConvert.ToString(true))); if (type.IsNested && type.IsNestedFamORAssem) ret.Add(new XAttribute("isProtectedOrInternal", XmlConvert.ToString(true))); if (type.IsClass && type.IsSealed) ret.Add(new XAttribute("isSealed", XmlConvert.ToString(true))); if (type.BaseType != null) { AssetIdentifier baseAid = AssetIdentifier.FromType(type.BaseType); if (!context.IsFiltered(baseAid)) { var inheritsElem = new XElement("inherits"); ret.Add(inheritsElem); GenerateTypeRef(context.Clone(inheritsElem), type.BaseType); } } if (type.ContainsGenericParameters) { Type[] typeParams = type.GetGenericArguments(); foreach (Type tp in typeParams) { this.GenerateTypeParamElement(context.Clone(ret), type, tp); } } if (type.IsClass) { foreach (Type interfaceType in type.GetInterfaces()) { InterfaceMapping mapping = type.GetInterfaceMap(interfaceType); if (mapping.TargetType == type) { AssetIdentifier interfaceAssetId = AssetIdentifier.FromType(interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType); if (!context.IsFiltered(interfaceAssetId)) { var implElement = new XElement("implements"); ret.Add(implElement); GenerateTypeRef(context.Clone(implElement), interfaceType, "interface"); } } } } foreach (IEnricher enricher in this._enrichers) enricher.EnrichType(context.Clone(ret), type); context.Element.Add(ret); return ret; }
public IEnumerable<AssetIdentifier> GetAssetHierarchy(AssetIdentifier assetId) { if (assetId.Type == AssetType.Unknown) yield break; yield return assetId; switch (assetId.Type) { case AssetType.Namespace: string ns = (string)this.Resolve(assetId); Assembly[] matchingAssemblies = this._assemblyLoader.Where(a => a.GetName().Version == assetId.Version) .Where(a => a.GetTypes().Any( t1 => t1.Namespace != null && (StringComparer.Ordinal.Equals(t1.Namespace, ns) || t1.Namespace.StartsWith(ns + ".", StringComparison.Ordinal)))) .ToArray(); if (matchingAssemblies.Length == 0) throw new InvalidOperationException("Found no assembly containing namespace: " + ns); if (matchingAssemblies.Length > 1) { TraceSources.AssetResolverSource.TraceWarning( "Namespace {0} found in more than one assembly: {1}", ns, string.Join(", ", matchingAssemblies.Select(a => a.GetName().Name))); } yield return AssetIdentifier.FromAssembly(matchingAssemblies[0]); break; case AssetType.Type: Type t = (Type)this.Resolve(assetId); while (t.IsNested) { t = t.DeclaringType; yield return AssetIdentifier.FromMemberInfo(t); } yield return AssetIdentifier.FromNamespace(t.Namespace, t.Assembly.GetName().Version); yield return AssetIdentifier.FromAssembly(t.Assembly); break; case AssetType.Method: case AssetType.Field: case AssetType.Event: case AssetType.Property: object resolve = this.Resolve(assetId); MemberInfo mi = (MemberInfo)resolve; foreach ( AssetIdentifier aid in this.GetAssetHierarchy(AssetIdentifier.FromMemberInfo(mi.ReflectedType))) yield return aid; break; case AssetType.Assembly: yield break; default: throw new ArgumentOutOfRangeException(); } }
private XElement GenerateConstructorElement(IProcessingContext context, AssetIdentifier assetId) { ConstructorInfo constructorInfo = (ConstructorInfo)context.AssetResolver.Resolve(assetId); XElement ret = new XElement("constructor", new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); if (constructorInfo.IsStatic) ret.Add(new XAttribute("isStatic", XmlConvert.ToString(constructorInfo.IsStatic))); if (constructorInfo.IsPublic) ret.Add(new XAttribute("isPublic", XmlConvert.ToString(constructorInfo.IsPublic))); if (constructorInfo.IsPrivate) ret.Add(new XAttribute("isPrivate", XmlConvert.ToString(constructorInfo.IsPrivate))); if (constructorInfo.IsFamily) ret.Add(new XAttribute("isProtected", XmlConvert.ToString(constructorInfo.IsFamily))); context.Element.Add(ret); foreach (IEnricher item in this.Enrichers) item.EnrichConstructor(context.Clone(ret), constructorInfo); ParameterInfo[] methodParams = constructorInfo.GetParameters(); this.GenerateParameterElements(context.Clone(ret), methodParams); return ret; }
private void BuildHierarchy(IAssetResolver assetResolver, XElement parentNode, LinkedListNode<AssetIdentifier> hierarchy, AssetIdentifier asset, HashSet<AssetIdentifier> references, HashSet<AssetIdentifier> emittedAssets, int phase) { if (hierarchy == null) return; IAssemblyLoader assemblyLoader = new ReflectionOnlyAssemblyLoader(this._cache, this._assemblyPaths.Select(Path.GetDirectoryName)); AssetIdentifier aid = hierarchy.Value; IProcessingContext pctx = new ProcessingContext(this._cache, this._filters, assemblyLoader, assetResolver, parentNode, references, phase); XElement newElement; // add asset to list of generated assets emittedAssets.Add(aid); // dispatch depending on type switch (aid.Type) { case AssetType.Namespace: newElement = parentNode.XPathSelectElement(string.Format("namespace[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateNamespaceElement(pctx, aid); break; case AssetType.Type: newElement = parentNode.XPathSelectElement(string.Format("*[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateTypeElement(pctx, aid); break; case AssetType.Method: newElement = parentNode.XPathSelectElement(string.Format("*[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateMethodElement(pctx, aid); break; case AssetType.Field: newElement = parentNode.XPathSelectElement(string.Format("field[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateFieldElement(pctx, aid); break; case AssetType.Event: newElement = parentNode.XPathSelectElement(string.Format("event[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateEventElement(pctx, aid); break; case AssetType.Property: newElement = parentNode.XPathSelectElement(string.Format("property[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GeneratePropertyElement(pctx, aid); break; case AssetType.Assembly: newElement = parentNode.XPathSelectElement(string.Format("assembly[@assetId = '{0}']", aid)); if (newElement == null) newElement = this.GenerateAssemblyElement(pctx, aid); break; default: throw new ArgumentOutOfRangeException(); } this.BuildHierarchy(assetResolver, newElement, hierarchy.Next, asset, references, emittedAssets, phase); }
private object ResolveAssembly(AssetIdentifier assetId, Assembly hintAssembly) { IEnumerable<Assembly> referencedAssemblies = this._assemblyLoader.SelectMany( a => a.GetReferencedAssemblies().Select( n => Assembly.ReflectionOnlyLoad(n.FullName))); IEnumerable<Assembly> assemblies = this._assemblyLoader.Concat(referencedAssemblies); foreach (Assembly assembly in assemblies) { if (AssetIdentifier.FromAssembly(assembly).Equals(assetId)) return assembly; } return null; }
private XElement GenerateNamespaceElement(IProcessingContext context, AssetIdentifier assetId) { string ns = (string)context.AssetResolver.Resolve(assetId); var ret = new XElement("namespace", new XAttribute("name", ns), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); context.Element.Add(ret); foreach (IEnricher enricher in this._enrichers) enricher.EnrichNamespace(context.Clone(ret), ns); return ret; }
private MemberInfo ResolveMethod(AssetIdentifier assetId, Assembly hintAssembly) { string asset = assetId.AssetId.Substring(2); int startIndex = 0; Type type = this.GetDeclaringType(asset, ref startIndex, hintAssembly); const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; var allMethods = type.GetMethods(bindingFlags) .Concat<MethodBase>(type.GetConstructors(bindingFlags)); MethodBase[] methods = allMethods.Where( m => (m is ConstructorInfo && assetId.AssetId.Equals(Naming.GetAssetId((ConstructorInfo) m), StringComparison.Ordinal)) || (m is MethodInfo && assetId.AssetId.Equals(Naming.GetAssetId((MethodInfo) m), StringComparison.Ordinal))) .ToArray(); // if there is a "new" method on the type we'll find both it and the method it hides. if (methods.Length == 2 && methods[1].DeclaringType == type) return methods[1]; Debug.Assert(methods.Length == 1 || methods.Length == 2, string.Format("Found {0} methods, expected 1 or 2.", methods.Length)); return methods[0]; }
private XElement GenerateMethodElement(IProcessingContext context, AssetIdentifier assetId) { // Debug.Assert(context.Element.Name.LocalName != "type", "Cannot put Method into closed generic type"); MethodBase mBase = (MethodBase)context.AssetResolver.Resolve(assetId); if (mBase is ConstructorInfo) return this.GenerateConstructorElement(context, assetId); MethodInfo mInfo = (MethodInfo)mBase; string elemName; if (this.IsOperator(mInfo)) elemName = "operator"; else elemName = "method"; XElement ret = new XElement(elemName, new XAttribute("name", mInfo.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); context.Element.Add(ret); Type declaringType = mInfo.DeclaringType; if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition) declaringType = declaringType.GetGenericTypeDefinition(); MethodInfo realMethodInfo = declaringType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Single( mi => mi.MetadataToken == mInfo.MetadataToken && mi.Module == mInfo.Module); AssetIdentifier declaredAs = AssetIdentifier.FromMemberInfo(realMethodInfo); if (declaringType != mInfo.ReflectedType) { ret.Add(new XAttribute("declaredAs", declaredAs)); context.AddReference(declaredAs); } else if (realMethodInfo.GetBaseDefinition() != realMethodInfo) { MethodInfo baseMethod = realMethodInfo.GetBaseDefinition(); if (baseMethod.ReflectedType.IsGenericType) { Type realTypeBase = baseMethod.ReflectedType.GetGenericTypeDefinition(); MethodInfo[] allMethods = realTypeBase.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); baseMethod = allMethods.Single( m => m.Module == baseMethod.Module && m.MetadataToken == baseMethod.MetadataToken); } declaredAs = AssetIdentifier.FromMemberInfo(baseMethod); ret.Add(new XAttribute("overrides", declaredAs)); context.AddReference(declaredAs); } this.GenerateImplementsElement(context.Clone(ret), mInfo); this.GenerateAccessModifiers(ret, mInfo); if (mInfo.ContainsGenericParameters) { Type[] typeParams = mInfo.GetGenericArguments(); foreach (Type tp in typeParams) this.GenerateTypeParamElement(context.Clone(ret), mInfo, tp); } foreach (IEnricher item in this.Enrichers) item.EnrichMethod(context.Clone(ret), mInfo); ParameterInfo[] methodParams = mInfo.GetParameters(); this.GenerateParameterElements(context.Clone(ret), methodParams); if (mInfo.ReturnType != typeof(void)) { XElement retElem = new XElement("returns"); GenerateTypeRef(context.Clone(retElem), mInfo.ReturnType); foreach (IEnricher item in this.Enrichers) item.EnrichReturnValue(context.Clone(retElem), mInfo); ret.Add(retElem); } return ret; }
private PropertyInfo ResolveProperty(AssetIdentifier assetId, Assembly hintAssembly) { string asset = assetId.AssetId.Substring(2); int startIndex = 0; Type type = this.GetDeclaringType(asset, ref startIndex, hintAssembly); PropertyInfo[] allProps = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); PropertyInfo[] properties = allProps .Where(p => assetId.AssetId.Equals(Naming.GetAssetId(p), StringComparison.Ordinal)) .ToArray(); // if there is a "new" property on the type we'll find both it and the property it hides. if (properties.Length == 2 && properties[1].DeclaringType == type) return properties[1]; Debug.Assert(properties.Length == 1 || properties.Length == 2, string.Format("Found {0} properties, expected 1 or 2.", properties.Length)); return properties[0]; }
private XElement GenerateFieldElement(IProcessingContext context, AssetIdentifier assetId) { object resolve = context.AssetResolver.Resolve(assetId); FieldInfo fieldInfo = (FieldInfo)resolve; XElement ret = new XElement("field", new XAttribute("name", fieldInfo.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); if (fieldInfo.IsStatic) ret.Add(new XAttribute("isStatic", XmlConvert.ToString(fieldInfo.IsStatic))); if (fieldInfo.IsPublic) ret.Add(new XAttribute("isPublic", XmlConvert.ToString(fieldInfo.IsPublic))); if (fieldInfo.IsPrivate) ret.Add(new XAttribute("isPrivate", XmlConvert.ToString(fieldInfo.IsPrivate))); if (fieldInfo.IsFamily) ret.Add(new XAttribute("isProtected", XmlConvert.ToString(fieldInfo.IsFamily))); if (fieldInfo.IsFamilyOrAssembly) ret.Add(new XAttribute("isProtectedOrInternal", XmlConvert.ToString(fieldInfo.IsFamilyOrAssembly))); if (fieldInfo.IsFamilyAndAssembly) ret.Add(new XAttribute("isProtectedAndInternal", XmlConvert.ToString(fieldInfo.IsFamilyAndAssembly))); if (fieldInfo.IsSpecialName) ret.Add(new XAttribute("isSpecialName", XmlConvert.ToString(fieldInfo.IsSpecialName))); GenerateTypeRef(context.Clone(ret), fieldInfo.FieldType); context.Element.Add(ret); foreach (IEnricher item in this.Enrichers) item.EnrichField(context.Clone(ret), fieldInfo); return ret; }
private object ResolveType(AssetIdentifier assetId, Assembly hintAssembly) { string typeName = assetId.AssetId.Substring(assetId.TypeMarker.Length + 1); int startIndex = 0; return this.GetDeclaringType(typeName, ref startIndex, hintAssembly); }
private XElement GeneratePropertyElement(IProcessingContext context, AssetIdentifier assetId) { PropertyInfo propInfo = (PropertyInfo)context.AssetResolver.Resolve(assetId); XElement ret = new XElement("property", new XAttribute("name", propInfo.Name), new XAttribute("assetId", assetId), new XAttribute("phase", context.Phase)); GenerateTypeRef(context.Clone(ret), propInfo.PropertyType); ParameterInfo[] pInfos = propInfo.GetIndexParameters(); this.GenerateParameterElements(context.Clone(ret), pInfos); MethodInfo setMethod = propInfo.GetSetMethod(true); MethodInfo getMethod = propInfo.GetGetMethod(true); if ((setMethod ?? getMethod).IsAbstract) ret.Add(new XAttribute("isAbstract", XmlConvert.ToString(true))); if ((setMethod ?? getMethod).IsVirtual) ret.Add(new XAttribute("isVirtual", XmlConvert.ToString(true))); const int C_PUBLIC = 10; const int C_INTERNAL_OR_PROTECTED = 8; const int C_INTERNAL = 6; const int C_PROTECTED = 4; const int C_INTERNAL_AND_PROTECTED = 2; const int C_PRIVATE = 0; int leastRestrictiveAccessModifier; if (setMethod != null && setMethod.IsPublic || getMethod != null && getMethod.IsPublic) { ret.Add(new XAttribute("isPublic", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_PUBLIC; } else if (setMethod != null && setMethod.IsFamilyOrAssembly || getMethod != null && getMethod.IsFamilyOrAssembly) { ret.Add(new XAttribute("isInternalOrProtected", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_INTERNAL_OR_PROTECTED; } else if (setMethod != null && setMethod.IsAssembly || getMethod != null && getMethod.IsAssembly) { ret.Add(new XAttribute("isInternal", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_INTERNAL; } else if (setMethod != null && setMethod.IsFamily || getMethod != null && getMethod.IsFamily) { ret.Add(new XAttribute("isProtected", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_PROTECTED; } else if (setMethod != null && setMethod.IsFamilyAndAssembly || getMethod != null && getMethod.IsFamilyAndAssembly) { ret.Add(new XAttribute("isInternalAndProtected", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_INTERNAL_AND_PROTECTED; } else if (setMethod != null && setMethod.IsPrivate || getMethod != null && getMethod.IsPrivate) { ret.Add(new XAttribute("isPrivate", XmlConvert.ToString(true))); leastRestrictiveAccessModifier = C_PRIVATE; } else { throw new InvalidOperationException("What the hell happened here?"); } if (setMethod != null) { var setElem = new XElement("set"); if (leastRestrictiveAccessModifier > C_INTERNAL_OR_PROTECTED && setMethod.IsFamilyOrAssembly) setElem.Add(new XAttribute("isInternalOrProtected", XmlConvert.ToString(setMethod.IsFamilyOrAssembly))); if (leastRestrictiveAccessModifier > C_INTERNAL && setMethod.IsAssembly) setElem.Add(new XAttribute("isInternal", XmlConvert.ToString(setMethod.IsAssembly))); if (leastRestrictiveAccessModifier > C_PROTECTED && setMethod.IsFamily) setElem.Add(new XAttribute("isProtected", XmlConvert.ToString(setMethod.IsFamily))); if (leastRestrictiveAccessModifier > C_INTERNAL_AND_PROTECTED && setMethod.IsFamilyAndAssembly) setElem.Add(new XAttribute("isInternalAndProtected", XmlConvert.ToString(setMethod.IsFamilyAndAssembly))); if (leastRestrictiveAccessModifier > C_PRIVATE && setMethod.IsPrivate) setElem.Add(new XAttribute("isPrivate", XmlConvert.ToString(setMethod.IsPrivate))); ret.Add(setElem); } if (getMethod != null) { var getElem = new XElement("get"); if (leastRestrictiveAccessModifier > C_INTERNAL_OR_PROTECTED && getMethod.IsFamilyOrAssembly) getElem.Add(new XAttribute("isInternalOrProtected", XmlConvert.ToString(getMethod.IsFamilyOrAssembly))); if (leastRestrictiveAccessModifier > C_INTERNAL && getMethod.IsAssembly) getElem.Add(new XAttribute("isInternal", XmlConvert.ToString(getMethod.IsAssembly))); if (leastRestrictiveAccessModifier > C_PROTECTED && getMethod.IsFamily) getElem.Add(new XAttribute("isProtected", XmlConvert.ToString(getMethod.IsFamily))); if (leastRestrictiveAccessModifier > C_INTERNAL_AND_PROTECTED && getMethod.IsFamilyAndAssembly) getElem.Add(new XAttribute("isInternalAndProtected", XmlConvert.ToString(getMethod.IsFamilyAndAssembly))); if (leastRestrictiveAccessModifier > C_PRIVATE && getMethod.IsPrivate) getElem.Add(new XAttribute("isPrivate", XmlConvert.ToString(getMethod.IsPrivate))); ret.Add(getElem); } if (propInfo.IsSpecialName) ret.Add(new XAttribute("isSpecialName", XmlConvert.ToString(propInfo.IsSpecialName))); context.Element.Add(ret); this.GenerateImplementsElement(context.Clone(ret), propInfo); foreach (IEnricher item in this.Enrichers) item.EnrichProperty(context.Clone(ret), propInfo); return ret; }
private object ResolveInternal(AssetIdentifier assetIdentifier, Assembly hintAssembly = null) { switch (assetIdentifier.Type) { case AssetType.Unknown: if (StringComparer.Ordinal.Equals("Overload", assetIdentifier.TypeMarker)) { return this.ResolveOverloads(assetIdentifier, hintAssembly); } throw new ArgumentException(string.Format("Type '{0}' not supported.", assetIdentifier.TypeMarker), "assetIdentifier"); case AssetType.Namespace: return assetIdentifier.AssetId.Substring(assetIdentifier.TypeMarker.Length + 1); case AssetType.Type: return this.ResolveType(assetIdentifier, hintAssembly); case AssetType.Method: return this.ResolveMethod(assetIdentifier, hintAssembly); case AssetType.Field: return this.ResolveField(assetIdentifier, hintAssembly); case AssetType.Event: return this.ResolveEvent(assetIdentifier, hintAssembly); case AssetType.Property: return this.ResolveProperty(assetIdentifier, hintAssembly); case AssetType.Assembly: return this.ResolveAssembly(assetIdentifier, hintAssembly); default: throw new ArgumentOutOfRangeException(); } }