public ProviderMethodBindingGenerator( ModuleDefinition moduleDefinition, References references, TypeReference moduleType, MethodDefinition providerMethod, bool isLibrary) : base(moduleDefinition, references) { this.providerMethod = providerMethod; this.moduleType = moduleType; this.isLibrary = isLibrary; var name = ProviderMethod.GetNamedAttributeName(); key = CompilerKeys.ForType(ProviderMethod.ReturnType, name); var attr = providerMethod.CustomAttributes.First(Attributes.IsProvidesAttribute); if (attr.HasConstructorArguments) { var providesTypeArg = attr.ConstructorArguments.Single(); ProvidesType = (ProvidesType) providesTypeArg.Value; } else { ProvidesType = ProvidesType.Default; } }
public ProviderBindingGenerator(ModuleDefinition moduleDefinition, References references, string key, string providerKey, TypeReference providedType) : base(moduleDefinition, references) { this.key = Conditions.CheckNotNull(key, "key"); this.providerKey = Conditions.CheckNotNull(providerKey, "providerKey"); this.providedType = Conditions.CheckNotNull(providedType, "providedType"); }
/// <summary> /// This is the Cartesian version of Pythagoras' theorem. In three-dimensional space, /// the distance between points (x1,y1,z1) and (x2,y2,z2) is /// http://upload.wikimedia.org/math/3/a/e/3ae1d79e0bfcc8f38223c7df4a7320c5.png /// which can be obtained by two consecutive applications of Pythagoras' theorem. /// http://en.wikipedia.org/wiki/Cartesian_coordinate_system#Distance_between_two_points /// the square root of ( /// ((point2.x - point1.x)squared) + /// ((point2.y - point1.y)squared) + /// ((point2.z - point1.z)squared) /// ) /// </summary> public static float distanceBetweenPythagCartesian(References.Vector3 point1, References.Vector3 point2) { return Mogre.Math.Sqrt( (Mogre.Math.Sqr(point2.x - point1.x) + Mogre.Math.Sqr(point2.y - point1.y) + Mogre.Math.Sqr(point2.z - point1.z) )); }
public ContentPipelineManager(References references, string xnaFrameworkVersion) { if (references == null) throw new ArgumentNullException("references"); _referencedAssemblies = new string[0]; OnReferencesChanged(references); _pipelineScanner = GetPipelineScanner(xnaFrameworkVersion); }
public InjectBindingGenerator(ModuleDefinition moduleDefinition, References references, TypeReference injectedType, bool isEntryPoint) : base(moduleDefinition, references) { this.injectedType = injectedType.IsDefinition ? (TypeDefinition) injectedType : ModuleDefinition.Import(injectedType).Resolve(); this.isEntryPoint = isEntryPoint; CtorParams = new List<InjectMemberInfo>(); InjectableProperties = new List<PropertyInfo>(); IsVisibleToPlugin = true; }
public ProviderMethodBindingGenerator( ModuleDefinition moduleDefinition, References references, TypeDefinition moduleType, MethodDefinition providerMethod, bool isLibrary) : base(moduleDefinition, references) { this.providerMethod = Conditions.CheckNotNull(providerMethod, "providerMethod"); this.moduleType = Conditions.CheckNotNull(moduleType, "moduleType"); this.isLibrary = isLibrary; var name = ProviderMethod.GetNamedAttributeName(); key = CompilerKeys.ForType(ProviderMethod.ReturnType, name); }
public InjectBindingGenerator(ModuleDefinition moduleDefinition, References references, TypeReference injectedType, bool isModuleInjectable) : base(moduleDefinition, references) { this.injectedType = injectedType.IsDefinition ? (TypeDefinition)injectedType : injectedType.Resolve(); importedInjectedType = Import(injectedType); genericInstanceType = injectedType as GenericInstanceType; this.isModuleInjectable = isModuleInjectable; CtorParams = new List<InjectMemberInfo>(); InjectableProperties = new List<PropertyInfo>(); IsVisibleToLoader = true; }
internal void RemoveReferenceCore(string name, References references) { try { var referenceName = System.IO.Path.GetFileNameWithoutExtension(name); Reference reference = references.Item(referenceName); if (reference == null) { // No exact match found for referenceName. Trying case-insensitive search Logger.Log(MessageLevel.Warning, VsResources.Warning_NoExactMatchForReference, referenceName); foreach (Reference r in references) { if (String.Equals(referenceName, r.Name, StringComparison.OrdinalIgnoreCase)) { if (reference == null) { reference = r; } else { var message = String.Format(CultureInfo.CurrentCulture, VsResources.FailedToRemoveReference, referenceName); Logger.Log(MessageLevel.Error, message); throw new InvalidOperationException(message); } } } } // At this point, the necessary case-sensitive and case-insensitive search are performed if (reference != null) { reference.Remove(); Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName); } else { Logger.Log(MessageLevel.Warning, VsResources.Warning_FailedToFindMatchForRemoveReference, referenceName); } } catch (Exception e) { Logger.Log(MessageLevel.Warning, e.Message); } }
public LoaderGenerator( ModuleDefinition moduleDefinition, References references, IEnumerable<KeyedCtor> injectBindingCtors, IEnumerable<KeyedCtor> lazyBindingCtors, IEnumerable<KeyedCtor> providerBindingCtors, IEnumerable<Tuple<TypeReference, MethodReference>> runtimeModuleCtors) : base(moduleDefinition, references) { var bindingFns = GetFnMethods(References.FuncOfT, References.Binding); var lazyFns = GetFnMethods( References.FuncOfT4, References.String, References.Object, References.String, References.Binding); var providerFns = GetFnMethods( References.FuncOfT5, References.String, References.Object, References.Boolean, References.String, References.Binding); var moduleFns = GetFnMethods(References.FuncOfT, References.RuntimeModule); bindingFnType = bindingFns.Item1; bindingFnCtor = bindingFns.Item2; bindingFnInvoke = bindingFns.Item3; lazyFnType = lazyFns.Item1; lazyFnCtor = lazyFns.Item2; lazyFnInvoke = lazyFns.Item3; providerFnType = providerFns.Item1; providerFnCtor = providerFns.Item2; providerFnInvoke = providerFns.Item3; moduleFnType = moduleFns.Item1; moduleFnCtor = moduleFns.Item2; moduleFnInvoke = moduleFns.Item3; this.injectBindingCtors = Conditions.CheckNotNull(injectBindingCtors, "injectBindingCtors"); this.lazyBindingCtors = Conditions.CheckNotNull(lazyBindingCtors, "lazyBindingCtors"); this.providerBindingCtors = Conditions.CheckNotNull(providerBindingCtors, "providerBindingCtors"); this.runtimeModuleCtors = Conditions.CheckNotNull(runtimeModuleCtors, "runtimeModuleCtors"); }
public LazyBindingGenerator(ModuleDefinition moduleDefinition, References references, string key, string lazyKey, TypeReference lazyElementType) : base(moduleDefinition, references) { this.key = Conditions.CheckNotNull(key, "key"); this.lazyKey = Conditions.CheckNotNull(lazyKey, "lazyKey"); this.lazyElementType = Conditions.CheckNotNull(lazyElementType, "lazyElementType"); funcCtor = ImportGeneric( References.FuncOfT, m => m.IsConstructor && m.Parameters.Count == 2, lazyElementType); lazyCtor = ImportGeneric( References.LazyOfT, m => m.Parameters.Count == 1 && m.Parameters[0].ParameterType.Name.StartsWith("Func", StringComparison.Ordinal), lazyElementType); }
private void AddReference(References References, string name, string dir) { if (!File.Exists(dir + name)) { using (WebClient client = new WebClient()) { xh: try { client.DownloadFile("http://wnxd.me/dll/" + name, dir + name); } catch { goto xh; } } } References.Add(dir + name); }
void AddAssemblyReference(string fileName) { var projectItem = new ProjectReference(ReferenceType.Assembly, fileName); References.Add(projectItem); }
public override bool Execute() { var timer = Stopwatch.StartNew(); bool chagesMade = false; try { Log.LogMessage(MessageImportance.High, "-- Starting Brutal Developer .NET Assembly Strong-Name Signer Task --"); if (References == null || References.Length == 0) { return(true); } if (OutputPath == null || string.IsNullOrEmpty(OutputPath.ItemSpec)) { Log.LogError("Task parameter 'OutputPath' not provided."); return(false); } SignedAssembliesToReference = new ITaskItem[References.Length]; string signedAssemblyFolder = Path.GetFullPath(Path.Combine(OutputPath.ItemSpec, "StrongNameSigner")); if (!Directory.Exists(signedAssemblyFolder)) { Directory.CreateDirectory(signedAssemblyFolder); } string snkFilePath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "StrongNameSigner.snk"); if (!File.Exists(snkFilePath)) { File.WriteAllBytes(snkFilePath, SigningHelper.GenerateStrongNameKeyPair()); } Log.LogMessage(MessageImportance.Normal, "Signed Assembly Directory: {0}", signedAssemblyFolder); Log.LogMessage(MessageImportance.Normal, "SNK File Path: {0}", snkFilePath); var updatedReferencePaths = new Dictionary <string, string>(); var processedAssemblyPaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var signedAssemblyPaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var probingPaths = References.Select(r => Path.GetDirectoryName(r.ItemSpec)).Distinct().ToArray(); for (int i = 0; i < References.Length; i++) { var ret = new TaskItem(References[i]); if (References[i].ItemSpec.IndexOf("\\Reference Assemblies\\Microsoft\\", StringComparison.OrdinalIgnoreCase) > -1 || References[i].ItemSpec.IndexOf("\\Microsoft.NET\\Framework\\", StringComparison.OrdinalIgnoreCase) > -1 || References[i].ItemSpec.IndexOf("\\netstandard.library\\", StringComparison.OrdinalIgnoreCase) > -1 || References[i].ItemSpec.IndexOf("\\dotnet\\sdk\\", StringComparison.OrdinalIgnoreCase) > -1 || References[i].ItemSpec.IndexOf("\\dotnet\\packs\\", StringComparison.OrdinalIgnoreCase) > -1 || References[i].ItemSpec.IndexOf("\\dotnet\\shared\\Microsoft.", StringComparison.OrdinalIgnoreCase) > -1) { // Don't attempt to sign and process framework assemblies, they should be signed already, just add them to be copied. ret.ItemSpec = References[i].ItemSpec; SignedAssembliesToReference[i] = ret; if (SignedAssembliesToReference[i].ItemSpec != References[i].ItemSpec) { updatedReferencePaths[References[i].ItemSpec] = SignedAssembliesToReference[i].ItemSpec; } } else { var signedAssembly = SigningHelper.GetAssemblyInfo(References[i].ItemSpec); // Check if it is currently signed. if (!signedAssembly.IsSigned) { signedAssembly = SignSingleAssembly(References[i].ItemSpec, snkFilePath, signedAssemblyFolder, probingPaths); chagesMade = true; } if (signedAssembly.IsSigned) { signedAssemblyPaths.Add(signedAssembly.FilePath); processedAssemblyPaths.Add(signedAssembly.FilePath); ret.ItemSpec = signedAssembly.FilePath; } else { processedAssemblyPaths.Add(References[i].ItemSpec); } SignedAssembliesToReference[i] = ret; if (SignedAssembliesToReference[i].ItemSpec != References[i].ItemSpec) { updatedReferencePaths[References[i].ItemSpec] = SignedAssembliesToReference[i].ItemSpec; } } } if (chagesMade) { var referencesToFix = new HashSet <string>(processedAssemblyPaths, StringComparer.OrdinalIgnoreCase); foreach (var filePath in processedAssemblyPaths) { // Go through all the references excluding the file we are working on. foreach (var referencePath in referencesToFix.Where(r => !r.Equals(filePath))) { FixSingleAssemblyReference(filePath, referencePath, snkFilePath, probingPaths); } } // Remove all InternalsVisibleTo attributes without public keys from the processed assemblies. Signed assemblies cannot have unsigned friend assemblies. foreach (var filePath in signedAssemblyPaths) { RemoveInvalidFriendAssemblyReferences(filePath, snkFilePath, probingPaths); } } if (CopyLocalPaths != null) { NewCopyLocalFiles = new ITaskItem[CopyLocalPaths.Length]; for (int i = 0; i < CopyLocalPaths.Length; i++) { string updatedPath; if (updatedReferencePaths.TryGetValue(CopyLocalPaths[i].ItemSpec, out updatedPath)) { NewCopyLocalFiles[i] = new TaskItem(CopyLocalPaths[i]); NewCopyLocalFiles[i].ItemSpec = updatedPath; } else { NewCopyLocalFiles[i] = CopyLocalPaths[i]; } } } Log.LogMessage(MessageImportance.High, "-- Finished Brutal Developer .NET Assembly Strong-Name Signer Task -- {0}", timer.Elapsed); return(true); } catch (Exception ex) { Log.LogErrorFromException(ex, true, true, null); } return(false); }
public override void AddReference(IProject project) { References.InsertSorted(project); }
public void AddReference(IAssemblyReference reference) { References.Add(reference); }
public void AddReference(string reference) { References.Add(new FakeAssembly(reference)); }
private bool ParseArguments(string[] args) { for (int i = 0; i < args.Length; i++) { if (i + 1 >= args.Length) { Console.WriteLine("Missing value for argument."); return(false); } string @switch = args[i]; string value = args[++i]; switch (@switch) { case "-an": if (BuildAssemblyName != null) { Console.WriteLine("Assembly name specified multiple times."); return(false); } BuildAssemblyName = value; break; case "-ap": if (BuildAssemblyPath != null) { Console.WriteLine("Assembly path specified multiple times."); return(false); } BuildAssemblyPath = value; break; case "-r": References.Add(value); break; case "-k": if (KeyFile != null) { Console.WriteLine("Key file specified multiple times."); return(false); } KeyFile = value; break; default: Console.WriteLine("Unrecognized switch {0}.", @switch); return(false); } } if (BuildAssemblyName == null || BuildAssemblyPath == null) { Console.WriteLine("Assembly name and path required."); return(false); } return(true); }
public void AddReference(string reference) { References.Add(Parameters.LoadAssembly(reference, true)); }
private void ParseManagedSemantics() { var stringTable = m_context.PathTable.StringTable; var magicNugetMarker = PathAtom.Create(stringTable, "_._"); var dllExtension = PathAtom.Create(stringTable, ".dll"); foreach (var relativePath in PackageOnDisk.Contents.OrderBy(path => path.ToString(stringTable))) { // This is a dll. Check if it is in a lib folder or ref folder. // This code handles two layouts // Case 1: /runtimes/{targetRuntime}/[lib|ref]/{targetFramework}/{fileName} // Case 2: /[lib|ref]/{targetFramework}/{fileName} // In case 1, /runtimes/{targetRuntime} is removed and then rest of string is processed as in // case 2. // Case 2 treats files under 'lib' folder as runtime dependencies (and optionally compile-time // references if missing a corresponding set of compile-time references for the target framework // under the 'ref' folder). Files under 'ref' folder are treated strictly as compile-time only references. var atoms = new ReadOnlySpan <PathAtom>(relativePath.GetAtoms()); if (atoms.Length == 5) { var isRuntime = NugetFrameworkMonikers.RuntimesFolderName.CaseInsensitiveEquals(stringTable, atoms[0]) && NugetFrameworkMonikers.SupportedTargetRuntimeAtoms.Contains(atoms[1].StringId); if (isRuntime) { atoms = atoms.Slice(2); } } if (atoms.Length == 3) { var libOrRef = atoms[0]; var targetFrameworkFolder = atoms[1]; var fileName = atoms[2]; var isLib = NugetFrameworkMonikers.LibFolderName.CaseInsensitiveEquals(stringTable, libOrRef); var isRef = NugetFrameworkMonikers.RefFolderName.CaseInsensitiveEquals(stringTable, libOrRef); if (isLib || isRef) { if (!TryGetKnownTargetFramework(targetFrameworkFolder, out NugetTargetFramework targetFramework)) { // We skip unknown frameworks, packages are not necessarily well constructed. We log this // as a verbose message (i.e., this is not an error). Logger.Log.NugetUnknownFramework(m_context.LoggingContext, PackageOnDisk.Package.Id, targetFrameworkFolder.ToString(stringTable), relativePath.ToString(stringTable)); continue; } var isManagedEntry = false; var ext = fileName.GetExtension(stringTable); if (dllExtension.CaseInsensitiveEquals(stringTable, ext)) { isManagedEntry = true; if (isRef) { References.Add(targetFramework, relativePath); } if (isLib) { Libraries.Add(targetFramework, relativePath); } } else if (fileName == magicNugetMarker) { isManagedEntry = true; } if (isManagedEntry) { IsManagedPackage = true; if (!TargetFrameworks.Contains(targetFramework.Moniker)) { TargetFrameworks.Add(targetFramework.Moniker); } // The magic marker is there so the framework is declared as supported, but no actual files are listed // So we don't want to add a magic marker as a real artifact that can be referenced. if (fileName != magicNugetMarker) { AssemblyToTargetFramework.Add(fileName, targetFramework); } } } } } if (TargetFrameworks.Count == 0) { var history = ForceFullFrameworkQualifiersOnly ? NugetFrameworkMonikers.FullFrameworkVersionHistory : NugetFrameworkMonikers.WellknownMonikers.ToList(); foreach (var moniker in history) { TargetFrameworks.Add(moniker); } } // For the refs without lib, copy them to refs. foreach (var kv in Libraries) { if (!References.ContainsKey(kv.Key)) { References.Add(kv.Key, kv.Value.ToArray()); } } }
protected AttachmentProxy(References type) { RefType = type; }
/// <summary> /// Get reference attribute associated to specified object type /// </summary> /// <param name="refType">Type of reference</param> /// <returns>Reference attribute found, else null</returns> public Reference GetReference(Type refType) { return(References.FirstOrDefault(_ => _.ReferenceEntityType == refType)); }
protected Generator(ModuleDefinition moduleDefinition, References references) { this.moduleDefinition = Conditions.CheckNotNull(moduleDefinition, "moduleDefinition"); this.references = Conditions.CheckNotNull(references, "references"); }
public ReferenceCollectionNodeFactory(References references) { _references = references; }
private static void AddReferences(Project instantProject, References references) { foreach (Reference reference in references) { if (reference.SourceProject == null) { if (Path.GetFileName (reference.Path) == "mscorlib.dll") continue; // mscorlib is added automatically instantProject.References.Add (reference.Path); } else { instantProject.References.Add (GetOutputPath (reference.SourceProject)); AddReferences (instantProject, ((VSProject)reference.SourceProject.Object).References); } } }
public CecilMigrationResult Migrate(string source, string destination) { if (string.IsNullOrWhiteSpace(source)) { throw new ArgumentException($"Invalid source assembly path specified: '{source}'.", nameof(source)); } if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentException($"Invalid destination assembly path specified: '{destination}'.", nameof(destination)); } if (!File.Exists(source)) { throw new FileNotFoundException($"Source assembly does not exist: '{source}'.", source); } var pdbPath = Path.ChangeExtension(destination, "pdb"); var mdbPath = destination + ".mdb"; // copy the files to the dest to start off if (CopyFile(source, destination)) { LogVerboseMessage($"Copying source assembly '{source}' to '{destination}'."); CopyFile(Path.ChangeExtension(source, "pdb"), pdbPath); CopyFile(source + ".mdb", mdbPath); } var hasSymbols = File.Exists(pdbPath) || File.Exists(mdbPath); // start the migration var result = CecilMigrationResult.Skipped; var requiresSave = false; using (var resolver = new AssemblyResolver()) { if (References?.Count > 0) { var refs = References .Where(r => Path.GetFileName(r) != Path.GetFileName(destination)) .ToList(); foreach (var reference in refs) { resolver.AddAssembly(reference); } } var readerParams = new ReaderParameters { ReadSymbols = hasSymbols, ReadWrite = true, AssemblyResolver = resolver, }; LogVerboseMessage($"Processing assembly '{source}'..."); using (var assembly = AssemblyDefinition.ReadAssembly(destination, readerParams)) { if (!hasSymbols) { LogVerboseMessage($" No debug symbols found for the assembly."); } result = MigrateAssembly(assembly); requiresSave = result.HasFlag(CecilMigrationResult.ContainedSupport) || result.HasFlag(CecilMigrationResult.ContainedJni) || result.HasFlag(CecilMigrationResult.ContainedJavaArtifacts); if (requiresSave) { assembly.Write(new WriterParameters { WriteSymbols = hasSymbols, SymbolWriterProvider = hasSymbols ? new PortablePdbWriterProvider() : null, }); LogMessage($"Migrated assembly to '{destination}'."); } else { LogVerboseMessage($"Skipped assembly '{source}' due to lack of support types."); } } } if (requiresSave) { // remove .dll.mdb as that is not supported if (File.Exists(mdbPath)) { File.Delete(mdbPath); } } return(result); }
private void VisitQueryReference(QueryReferenceExpression expression) { References.Add(expression.QueryReference); }
public void Release() { References.Clear(); }
// Use this for initialization void Start() { _constants = GameObject.Find("ConstantsHolder").GetComponent <Constants> (); _references = GameObject.Find("ReferenceHolder").GetComponent <References> (); _register = GameObject.Find("UnitRegisterHolder").GetComponent <UnitRegister> (); }
internal void OnReferencesChanged(References references) { _needsRefresh = true; if (references == null) { _referencedAssemblies = new string[0]; } else { _referencedAssemblies = new string[references.Count]; int num = 0; try { foreach (Reference reference in references) { _referencedAssemblies[num++] = reference.Path; } } catch { _referencedAssemblies = new string[0]; throw; } } }
public void AddReference(IAssemblyReference reference) { References.Add(reference); ProjectContent.AddAssemblyReferences(new[] { reference }); }
public Conversion WithReference(Reference reference) { References.Add(reference); return(this); }
public async Task SetDiscoverSomethingTwitterAsync(TwitAuthenticateResponse twitAuthResponse, string screenName, long idMax, string idLogin) { var item = await DocumentDBRepository <Login> .GetItemAsync(idLogin); // Busca uma lista de tweets do usuário, neste caso os 100 primeiros. Após isso, é feito por thread, pegando os 100 tweets mais antigos que estes, e assim sucessivamente var timelineFormat = ""; var timelineUrl = ""; if (idMax > 0) { timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&max_id={1}&include_rts=0&exclude_replies=1&count=100"; timelineUrl = string.Format(timelineFormat, screenName, idMax); } else { timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=0&exclude_replies=1&count=100"; timelineUrl = string.Format(timelineFormat, screenName); } HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl); var timelineHeaderFormat = "{0} {1}"; timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.TokenType, twitAuthResponse.AccessToken)); timeLineRequest.Method = "Get"; WebResponse timeLineResponse = timeLineRequest.GetResponse(); var timeLineJson = string.Empty; using (timeLineResponse) { using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) { timeLineJson = reader.ReadToEnd(); } } dynamic tweets = new JavaScriptSerializer().DeserializeObject(timeLineJson); int count = 0; List <string> textTweets = new List <string>(); List <string> idTweets = new List <string>(); foreach (dynamic tweet in tweets) { //Joga todos os textos dos tweets dentro de uma lista, e os ids em outra textTweets.Add(tweet["text"]); long id = tweet["id"]; idTweets.Add(id.ToString()); count++; } //Busca token de acesso para API de Translate string authToken = await GetAccessTokenTranslateAsync(); //Chama API de Tradução, traduzindo o tweet de pt para en string[] translates = TranslateArray(authToken, "pt", "en", textTweets.ToArray()); string[] ids = idTweets.ToArray(); //Monta objeto para fazer a chamada da API de análise do texto do tweet KeyPhrases KeyPhrases = new KeyPhrases(); for (int i = 0; i < translates.Length; i++) { Document document = new Document(); document.Id = ids[i]; document.Language = "en"; document.Text = translates[i]; KeyPhrases.Documents.Add(document); } //Chama API de Análise de Texto, para buscar as palavras chave da frase tweetada dynamic keyPhrasesObj = GetKeyPhrases(KeyPhrases); List <string> keyPhrases = new List <string>(); foreach (var doc in keyPhrasesObj["documents"]) { //Coloca num stringão todas as palavras chaves separadas por ", " keyPhrases.Add(string.Join(", ", doc["keyPhrases"])); } //Busca token de acesso para API de Translate authToken = await GetAccessTokenTranslateAsync(); //Chama API de Tradução, agora traduzindo as palavras chave em en para pt para mostrar corretamente pro usuário string[] translateskeyPhrases = TranslateArray(authToken, "en", "pt", keyPhrases.ToArray()); for (int i = 0; i < translateskeyPhrases.Length; i++) { References reference = new References(); reference.IdTweet = ids[i]; //tweet.TextTweet = foreach (string keyPhraseTranslate in translateskeyPhrases[i].Split(new[] { ", " }, StringSplitOptions.None)) { //Verifica se já tem no objeto uma palavra chave com o mesmo texto if (item.KeyPhrases.Count(k => k.Text == keyPhraseTranslate) > 0) { //Se já existe, somente inclui uma nova referência item.KeyPhrases.FirstOrDefault(k => k.Text == keyPhraseTranslate).References.Add(reference); } else { //Caso não exista, cria uma nova KeyPhrase keyPhrase = new KeyPhrase(); keyPhrase.Text = keyPhraseTranslate; keyPhrase.References.Add(reference); item.KeyPhrases.Add(keyPhrase); } } } await DocumentDBRepository <Login> .UpdateItemAsync(idLogin, item); //ID do último tweet retornado, para consultar os mais antigos a partir desse, na próxima vez var lastTweet = tweets[count - 1]; long id_max = lastTweet["id"]; //Inicia thread para ir enchendo a base do usuário com mais tweets /*new Thread(async () => * { * await SetDiscoverSomethingTwitterAsync(twitAuthResponse, screenName, id_max - 1, idLogin); * }).Start();*/ }
private void Load() { var projectPath = LocalPath; var projectDir = Path.GetDirectoryName(projectPath); var splitOptions = StringSplitOptions.RemoveEmptyEntries; var setupInformation = AppDomain.CurrentDomain.SetupInformation; // Always null, why? probing path is set in vvvv.exe.config // var searchPath = AppDomain.CurrentDomain.RelativeSearchPath; ReferencePaths = new List <string>() { Path.GetFullPath(Path.Combine(setupInformation.ApplicationBase, "lib", "core")), Path.GetFullPath(Path.Combine(setupInformation.ApplicationBase, "lib", "nodes", "plugins")) }; try { var msBuildProject = MsProject; var referencePathProperty = msBuildProject.GetPropertyValue("ReferencePath"); if (!string.IsNullOrEmpty(referencePathProperty)) { foreach (var refPath in referencePathProperty.Split(FSplitChars, splitOptions)) { var trimmedRefPath = refPath.Trim(); trimmedRefPath = refPath.TrimEnd(Path.DirectorySeparatorChar); var absoluteRefPath = Path.IsPathRooted(trimmedRefPath) ? trimmedRefPath : Path.Combine(projectDir, trimmedRefPath); try { absoluteRefPath = Path.GetFullPath(absoluteRefPath); if (!ReferencePaths.Contains(absoluteRefPath) && Directory.Exists(absoluteRefPath)) { ReferencePaths.Add(absoluteRefPath); } } catch (NotSupportedException) { // Ignore } } } // Iterate through the various itemgroups // and subsequently through the items foreach (var projectItem in msBuildProject.Items) { switch (projectItem.ItemType) { case "Reference": IReference reference = null; var include = projectItem.EvaluatedInclude; if (include == "System.ComponentModel.Composition") { include = "System.ComponentModel.Composition.Codeplex"; } if (projectItem.HasMetadata("HintPath")) { var hintPath = projectItem.GetMetadataValue("HintPath"); var assemblyLocation = hintPath; if (!Path.IsPathRooted(assemblyLocation)) { assemblyLocation = projectDir.ConcatPath(hintPath); } if (!File.Exists(assemblyLocation)) { //search in reference paths assemblyLocation = TryAddReferencePath(assemblyLocation, include); } if (File.Exists(assemblyLocation)) { assemblyLocation = Path.GetFullPath(assemblyLocation); } reference = new AssemblyReference(assemblyLocation); } else { var assemblyLocation = TryAddReferencePath("", include); if (File.Exists(assemblyLocation)) { reference = new AssemblyReference(assemblyLocation, true); } } // Reference couldn't be found, try GAC if (reference == null) { try { var assemblyLocation = AssemblyCache.QueryAssemblyInfo(include); reference = new AssemblyReference(assemblyLocation, true); } catch (Exception) { reference = new AssemblyReference(string.Format("{0}.dll", include), true); } } if (reference != null) { References.Add(reference); } break; case "ProjectReference": // TODO: Load project references. break; case "Compile": case "None": IDocument document = null; var canBeCompiled = projectItem.ItemType == "Compile"; var documentPath = projectDir.ConcatPath(projectItem.EvaluatedInclude); if (!File.Exists(documentPath)) { document = new MissingDocument(documentPath, documentPath, canBeCompiled); } else { FDocumentConverter.Convert(documentPath, out document); } if (document != null) { Documents.Add(document); } break; default: break; } } } catch (Exception e) { Shell.Instance.Logger.Log(e); } }
internal ObjectReference <Account> CreateReference(Account account) { return(References.Create(account)); }
public override void RemoveReference(IProject project) { References.Remove(project); }
public static void AddProjectReferencesPathsIntoHost(References references, MetadataReaderHost host) { Contract.Requires(host != null); if (references == null) return; for (int i = 1; i <= references.Count; i++) { var tempRef = references.Item(i); if (tempRef == null) continue; var refPath = tempRef.Path; if (!String.IsNullOrEmpty(refPath)) { var refDir = Path.GetDirectoryName(refPath); if (refDir != null) { host.AddLibPath(refDir); var referenceAssemblyPath = Path.Combine(refDir, "CodeContracts"); if (System.IO.Directory.Exists(referenceAssemblyPath)) host.AddLibPath(referenceAssemblyPath); } } } }
public async Task KickAsync(IUser user = null, [Remainder] string reason = null) { Errors errors = new Errors(); if (user == null) { await errors.sendErrorTempAsync(Context.Channel, "Please mention the user you would like to kick.", Colours.errorCol); } if (reason == null) { await errors.sendErrorTempAsync(Context.Channel, "Please provide a reason for the kick!", Colours.errorCol); } if (user != null && reason != null) { await Context.Message.DeleteAsync(); await Context.Channel.SendMessageAsync("", false, new EmbedBuilder() { Color = Colours.adminCol, ImageUrl = "https://media1.giphy.com/media/3o7TKwVQMoQh2At9qU/giphy.gif", Title = "User kicked from the server!" }); BanChecks.SetIsCommandBan(); var userName = user as SocketGuildUser; await userName.KickAsync(); //await Context.Guild.AddBanAsync(user, 0, reason); //await Context.Guild.RemoveBanAsync(user); IUser kickHammerOwner = Context.Message.Author; int kickDay = DateTime.Now.Day; int kickMonth = DateTime.Now.Month; int kickYear = DateTime.Now.Year; TimeSpan kickTime = DateTime.Now.TimeOfDay; var embed = new EmbedBuilder() { Color = Colours.errorCol }; embed.WithAuthor("User was kicked from Discord"); embed.WithThumbnailUrl(References.GetGta5policeLogo()); embed.AddField(new EmbedFieldBuilder() { Name = "Discord User", Value = user.Username.ToString(), IsInline = true }); embed.AddField(new EmbedFieldBuilder() { Name = "Discord Id", Value = user.Id, IsInline = true }); embed.AddField(new EmbedFieldBuilder() { Name = "Reason", Value = reason, IsInline = false }); embed.AddField(new EmbedFieldBuilder() { Name = "Kicked By", Value = kickHammerOwner, IsInline = true }); embed.AddField(new EmbedFieldBuilder() { Name = "Time", Value = kickMonth + "/" + kickDay + "/" + kickYear + " - " + kickTime, IsInline = true }); var chan = await Context.Guild.GetTextChannelAsync(BotConfig.Load().LogsId); await chan.SendMessageAsync("", false, embed); await Program.Logger(new LogMessage(LogSeverity.Info, "GTA5Police Admin Commands", "Kick command was used by " + Context.User + " on the user " + user + ".")); Statistics.AddOutgoingMessages(); } }
/// <summary> /// initializes this script. /// </summary> void Begin() { refs = gameObject.GetComponent <References>(); if (GameObject.Find("Panel_Game").gameObject != null) { gamePanel = GameObject.Find("Panel_Game").gameObject; } else { Debug.Log("Panel_Game is disabled in the heirarchy, Please re-Enable!"); } if(GameObject.Find("Panel_PlayAgain").gameObject != null) { playAgainPanel = GameObject.Find("Panel_PlayAgain").gameObject; } else { Debug.Log("Panel_PlayAgain is disabled in the heirarchy, Please re-Enable!"); } playAgainPanel.SetActive(false); gamePanel.SetActive(false); }
/// <summary> /// 외부 참조를 추가합니다. /// </summary> /// <param name="path">외부 참조 파일의 경로입니다.</param> public void LoadReference(string path) { if (!IsNameContains(References, path)) { // 참조 추가 References.Add(path); LoadedReferences.Add(path); // 참조의 종속성 검사 foreach (AssemblyName assembly in Assembly.LoadFrom(path).GetReferencedAssemblies()) { // 참조 종속성 검사 string referencesName = null; string dllPath = string.Format(@"{0}\{1}.dll", Path.GetDirectoryName(path), assembly.Name); if (File.Exists(dllPath)) { // 동일 경로에 존재 referencesName = dllPath; } else { // 동일 경로에 없음 // 외부 종속성 중복 검사 if ((from callingAssembly in Assembly.GetCallingAssembly().GetReferencedAssemblies() select callingAssembly.Name).Contains(assembly.Name)) { continue; } // 글로벌 캐시에 존재 여부 검사 string[] dllGAC = Directory.GetFiles ( Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\assembly", assembly.Name + ".dll", SearchOption.AllDirectories ); dllGAC = dllGAC.Where(dll => dll.IndexOf(GetPublicKeyToken(assembly)) != -1).ToArray(); if (dllGAC.Length > 0) { // 글로벌 캐시에 존재 // 시스템에 맞는 파일 검색 if (dllGAC.Length == 1) { referencesName = dllGAC.First(); } else { referencesName = dllGAC.Where(dll => dll.IndexOf(Environment.Is64BitOperatingSystem ? "GAC_64" : "GAC_32") != -1).First(); } } else { referencesName = assembly.Name + ".dll"; } } // 참조의 종속성을 추가 if (!IsNameContains(References, referencesName)) { References.Add(referencesName); } } } }
private void broadcastPlayerLocationAllExcept(string Endpoint, References.Vector3 loc) { Event outevent = new Event(); outevent._Keyword = KeyWord.TONGITS_PLAYERLOCATION_UPDATE; outevent._IntendedRecipients = EventTransfer.SERVERTOCLIENT; outevent._Memories = new Memories(); outevent._Memories.Add(new Memory("", KeyWord.CARTESIAN_X, (loc.x.ToString()))); outevent._Memories.Add(new Memory("", KeyWord.CARTESIAN_Y, (loc.y.ToString()))); outevent._Memories.Add(new Memory("", KeyWord.CARTESIAN_Z, (loc.z.ToString()))); sendMessageAllUsersExcept(outevent, Endpoint); }
private void Awake() { Instance = this; }
public bool ReferenceExists(string name) { return(References.ContainsKey(name) || FrameworkReferences.Contains(name)); }
private void Init() { VitaNexCore.TryCatch( () => { Status = CompileStatus.Initializing; if (!InputDirectory.Exists) { Status = CompileStatus.Aborted; StatusMessage = "Input directory '" + InputDirectory + "' does not exist."; return; } var infos = new List <FileInfo>(); foreach (var file in FileMasks.SelectMany( t => InputDirectory.GetFiles(t, SearchOption.AllDirectories).Where(file => !infos.Contains(file)))) { infos.Add(file); } var files = infos.ToArray(); infos.Clear(); if (files.Length == 0) { Status = CompileStatus.Aborted; StatusMessage = "No files to compile."; return; } var refs = new List <string>(); var fileNames = new List <string>(); foreach (var fName in files.Select(t => t.FullName) .Where(fName => !String.IsNullOrEmpty(fName)) .Where(fName => !fileNames.Contains(fName))) { fileNames.Add(fName); } foreach (var t in DefaultReferences.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t))) { refs.Add(t); } foreach (var t in References.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t))) { refs.Add(t); } var configs = GetConfigFiles(); if (configs != null) { foreach (var t in configs.Select(GetConfigAssemblies) .SelectMany( asm => asm.Where(t => !String.IsNullOrEmpty(t)) .Where(t => File.Exists(IOUtility.GetSafeFilePath(IOUtility.GetBaseDirectory() + "/" + t, true))) .Where(t => !refs.Contains(t)))) { refs.Add(t); } } Status = CompileStatus.Compiling; Parameters = new CompilerParameters( refs.ToArray(), IOUtility.GetUnusedFilePath(OutputDirectory.FullName, OutputFileName), Debug) { GenerateExecutable = false, WarningLevel = 4, CompilerOptions = String.Empty }; foreach (var arg in Arguments) { Parameters.CompilerOptions += arg + " "; } Results = Provider.CompileAssemblyFromFile(Parameters, fileNames.ToArray()); if (Results.Errors.Count > 0) { int errorCount = 0, warningCount = 0; foreach (CompilerError e in Results.Errors) { if (e.IsWarning) { ++warningCount; } else { ++errorCount; } } Errors = new string[Results.Errors.Count]; for (var e = 0; e < Results.Errors.Count; e++) { Errors[e] = String.Format( "[{0}][{1}][{2}]: Line {3}, Column {4}\n{5}", Results.Errors[e].IsWarning ? "Warning" : "Error", Results.Errors[e].FileName, Results.Errors[e].ErrorNumber, Results.Errors[e].Line, Results.Errors[e].Column, Results.Errors[e].ErrorText); } StatusMessage = String.Format( "Finished compiling with {0} error{1} and {2} warning{3}", errorCount, errorCount > 1 ? "s" : "", warningCount, warningCount > 1 ? "s" : ""); Status = CompileStatus.Completed; } else { StatusMessage = "Finished compiling with no errors or warnings."; Status = CompileStatus.Completed; } }, ex => { Status = CompileStatus.Aborted; StatusMessage = ex.Message; }); if (CompiledCallback != null) { CompiledCallback(Results); } }
public string[] GetAllReferences() { return(References.Concat(ScriptAssemblyReferences.Select(a => a.FullPath)).ToArray()); }
private void ReadDirStream() { byte[] dir = CompoundDocument.DecompressPart(Document.Storage.SubStorage["VBA"].DataStreams["dir"]); MemoryStream ms = new MemoryStream(dir); BinaryReader br = new BinaryReader(ms); ExcelVbaReference currentRef = null; string referenceName = ""; ExcelVBAModule currentModule = null; bool terminate = false; while (br.BaseStream.Position < br.BaseStream.Length && terminate == false) { ushort id = br.ReadUInt16(); uint size = br.ReadUInt32(); switch (id) { case 0x01: SystemKind = (eSyskind)br.ReadUInt32(); break; case 0x02: Lcid = (int)br.ReadUInt32(); break; case 0x03: CodePage = (int)br.ReadUInt16(); break; case 0x04: Name = GetString(br, size); break; case 0x05: Description = GetUnicodeString(br, size); break; case 0x06: HelpFile1 = GetString(br, size); break; case 0x3D: HelpFile2 = GetString(br, size); break; case 0x07: HelpContextID = (int)br.ReadUInt32(); break; case 0x08: LibFlags = (int)br.ReadUInt32(); break; case 0x09: MajorVersion = (int)br.ReadUInt32(); MinorVersion = (int)br.ReadUInt16(); break; case 0x0C: Constants = GetUnicodeString(br, size); break; case 0x0D: uint sizeLibID = br.ReadUInt32(); var regRef = new ExcelVbaReference(); regRef.Name = referenceName; regRef.ReferenceRecordID = id; regRef.Libid = GetString(br, sizeLibID); uint reserved1 = br.ReadUInt32(); ushort reserved2 = br.ReadUInt16(); References.Add(regRef); break; case 0x0E: var projRef = new ExcelVbaReferenceProject(); projRef.ReferenceRecordID = id; projRef.Name = referenceName; sizeLibID = br.ReadUInt32(); projRef.Libid = GetString(br, sizeLibID); sizeLibID = br.ReadUInt32(); projRef.LibIdRelative = GetString(br, sizeLibID); projRef.MajorVersion = br.ReadUInt32(); projRef.MinorVersion = br.ReadUInt16(); References.Add(projRef); break; case 0x0F: ushort modualCount = br.ReadUInt16(); break; case 0x13: ushort cookie = br.ReadUInt16(); break; case 0x14: LcidInvoke = (int)br.ReadUInt32(); break; case 0x16: referenceName = GetUnicodeString(br, size); break; case 0x19: currentModule = new ExcelVBAModule(); currentModule.Name = GetUnicodeString(br, size); Modules.Add(currentModule); break; case 0x1A: currentModule.streamName = GetUnicodeString(br, size); break; case 0x1C: currentModule.Description = GetUnicodeString(br, size); break; case 0x1E: currentModule.HelpContext = (int)br.ReadUInt32(); break; case 0x21: case 0x22: break; case 0x2B: //Modul Terminator break; case 0x2C: currentModule.Cookie = br.ReadUInt16(); break; case 0x31: currentModule.ModuleOffset = br.ReadUInt32(); break; case 0x10: terminate = true; break; case 0x30: var extRef = (ExcelVbaReferenceControl)currentRef; var sizeExt = br.ReadUInt32(); extRef.LibIdExternal = GetString(br, sizeExt); uint reserved4 = br.ReadUInt32(); ushort reserved5 = br.ReadUInt16(); extRef.OriginalTypeLib = new Guid(br.ReadBytes(16)); extRef.Cookie = br.ReadUInt32(); break; case 0x33: currentRef = new ExcelVbaReferenceControl(); currentRef.ReferenceRecordID = id; currentRef.Name = referenceName; currentRef.Libid = GetString(br, size); References.Add(currentRef); break; case 0x2F: var contrRef = (ExcelVbaReferenceControl)currentRef; contrRef.ReferenceRecordID = id; var sizeTwiddled = br.ReadUInt32(); contrRef.LibIdTwiddled = GetString(br, sizeTwiddled); var r1 = br.ReadUInt32(); var r2 = br.ReadUInt16(); break; case 0x25: currentModule.ReadOnly = true; break; case 0x28: currentModule.Private = true; break; default: break; } } }
public void InjectCode(string assemblyPath, string outputAssemblyPath) { var debug = DebugSymbols || !string.IsNullOrEmpty(DebugType) && DebugType.ToLowerInvariant() != "none"; var assemblyReferenceResolver = new AssemblyReferenceResolver(); if (!string.IsNullOrEmpty(References)) { var paths = References.Replace("//", "/").Split(';').Distinct(); foreach (var p in paths) { var searchpath = Path.GetDirectoryName(p); //Logger.LogMessage($"Adding searchpath {searchpath}"); assemblyReferenceResolver.AddSearchDirectory(searchpath); } } var ad = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters { ReadWrite = true, ReadSymbols = true, AssemblyResolver = assemblyReferenceResolver }); var md = ad.MainModule; var test1 = md.AssemblyReferences; var types = md.Types.Where(x => x.BaseType != null).ToList(); var typesWithCorrectOrder = new List <TypeDefinition>(); foreach (var type in types) { if (type.BaseType is TypeDefinition baseTypeDeginition) { var baseTypes = GetBaseTypesWithCorrectOrder(baseTypeDeginition); foreach (var baseType in baseTypes) { if (!typesWithCorrectOrder.Contains(baseType)) { typesWithCorrectOrder.Add(baseType); } } typesWithCorrectOrder.Add(type); } else { if (!typesWithCorrectOrder.Contains(type)) { typesWithCorrectOrder.Add(type); } } } var iInstanceClassType = md.ImportReference(typeof(IInstanceClass)); foreach (var type in typesWithCorrectOrder) { if (type.Name.EndsWith("Delegate", StringComparison.InvariantCulture)) { continue; } Logger.LogMessage("Weaving Type: " + type.Name); var ctorParametersDefinition = type.CreateField(md, ctorParametersName, md.ImportReference(typeof(ArrayList))); ctorParameters = ctorParametersDefinition.GetReference(); var methods = type.Methods.ToList(); MethodDefinition getInstanceMethod = null; MethodDefinition instanceMethodGetters = null; if (type.IsDelegate(md) || type.IsEnum || type.IsValueType) { continue; } var hasImplementedIInstanceClass = type.HasImplementedIInstanceClass(iInstanceClassType, out getInstanceMethod, out instanceMethodGetters); ImplementIInstanceClass(md, type, ref getInstanceMethod, ref instanceMethodGetters, hasImplementedIInstanceClass); foreach (var method in methods) { if (method.CustomAttributes .Any(x => x.AttributeType.Name == "CompilerGeneratedAttribute") || method.CustomAttributes .Any(x => x.AttributeType.Name == "GeneratedCodeAttribute")) { continue; } if (method == instanceMethodGetters || method == getInstanceMethod) { continue; } //Ignore method with ref parameter if (method.Parameters.Any(x => x.ParameterType is ByReferenceType)) { continue; } WrapMethod(md, type, method, getInstanceMethod.GetReference(type, md)); if (method.IsVirtual) { var baseMethod = GetBaseMethod(type, method, md); if (baseMethod != null) { var hotReloadingBaseMethod = CreateBaseCallMethod(md, baseMethod); type.Methods.Add(hotReloadingBaseMethod); } } } if (!type.IsAbstract && !type.IsSealed && AllowOverride) { AddOverrideMethod(type, md, getInstanceMethod.GetReference(type, md), methods); } } if (assemblyPath == outputAssemblyPath) { ad.Write(new WriterParameters { WriteSymbols = debug }); } else { ad.Write(outputAssemblyPath, new WriterParameters { WriteSymbols = debug }); } ad.Dispose(); }
protected void Construct(string name, bool isExe) { FileName = name + (isExe ? ".exe" : ".dll"); Framework.Add(c => ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.FrameworkNone); References.Add(c => ShouldTargetTinyCorlib(c, this), Il2Cpp.TinyCorlib); Framework.Add(c => !ShouldTargetTinyCorlib(c, this), Bee.DotNet.Framework.Framework471); References.Add(c => !ShouldTargetTinyCorlib(c, this), new SystemReference("System")); ProjectFile.Path = DeterminePathForProjectFile(); ProjectFile.ReferenceModeCallback = arg => { // Most projects are AsmDefCSharpProgram. For everything else we'll look up their // packagestatus by the fact that we know it's in the same package as Unity.Entities.CPlusPlus // XXX This is not true any more! //var asmdefDotsProgram = (arg as AsmDefCSharpProgram)?.AsmDefDescription ?? AsmDefConfigFile.AsmDefDescriptionFor("Unity.Entities.CPlusPlus"); return(ProjectFile.ReferenceMode.ByCSProj); }; LanguageVersion = "7.3"; Defines.Add( "UNITY_DOTSPLAYER", "NET_DOTS", // TODO -- figure out what's gated with this, and if it should have a UNITY_DOTSPLAYER || ... "UNITY_2018_3_OR_NEWER", // And these might not make sense for DOTS Runtime anyway beacuse they are UnityEngine/UnityEditor APIs. // They break the build if we add them. //"UNITY_2019_1_OR_NEWER", //"UNITY_2019_2_OR_NEWER", //"UNITY_2019_3_OR_NEWER", // TODO -- removing this breaks Burst, it should be using DOTSPLAYER! "UNITY_ZEROPLAYER" ); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WebGLPlatform, "UNITY_WEBGL"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is WindowsPlatform, "UNITY_WINDOWS"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is MacOSXPlatform, "UNITY_MACOSX"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is LinuxPlatform, "UNITY_LINUX"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is IosPlatform, "UNITY_IOS"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Platform is AndroidPlatform, "UNITY_ANDROID"); Defines.Add(c => !((DotsRuntimeCSharpProgramConfiguration)c).MultiThreadedJobs, "UNITY_SINGLETHREADED_JOBS"); CopyReferencesNextToTarget = false; WarningsAsErrors = false; //hack, fix this in unity.mathematics foreach (var sourcePath in AllSourcePaths) { if (sourcePath.FileName == "Unity.Mathematics") { Sources.Add(sourcePath.Files("*.cs", true) .Where(f => f.FileName != "math_unity_conversion.cs" && f.FileName != "PropertyAttributes.cs")); } else { Sources.Add(new CustomProvideFiles(sourcePath)); } } foreach (var sourcePath in AllSourcePaths) { var cppFolder = sourcePath.Combine("cpp~"); var prejsFolder = sourcePath.Combine("prejs~"); var jsFolder = sourcePath.Combine("js~"); var postjsFolder = sourcePath.Combine("postjs~"); var beeFolder = sourcePath.Combine("bee~"); var includeFolder = cppFolder.Combine("include"); NPath[] cppFiles = Array.Empty <NPath>(); if (cppFolder.DirectoryExists()) { cppFiles = cppFolder.Files("*.c*", true); ProjectFile.AdditionalFiles.AddRange(cppFolder.Files(true)); GetOrMakeNativeProgram().Sources.Add(cppFiles); } if (prejsFolder.DirectoryExists()) { var jsFiles = prejsFolder.Files("*.js", true); ProjectFile.AdditionalFiles.AddRange(prejsFolder.Files(true)); GetOrMakeNativeProgram() .Libraries.Add(c => c.Platform is WebGLPlatform, jsFiles.Select(jsFile => new PreJsLibrary(jsFile))); } //todo: get rid of having both a regular js and a prejs folder if (jsFolder.DirectoryExists()) { var jsFiles = jsFolder.Files("*.js", true); ProjectFile.AdditionalFiles.AddRange(jsFolder.Files(true)); GetOrMakeNativeProgram() .Libraries.Add(c => c.Platform is WebGLPlatform, jsFiles.Select(jsFile => new JavascriptLibrary(jsFile))); } if (postjsFolder.DirectoryExists()) { var jsFiles = postjsFolder.Files("*.js", true); ProjectFile.AdditionalFiles.AddRange(postjsFolder.Files(true)); GetOrMakeNativeProgram() .Libraries.Add(c => c.Platform is WebGLPlatform, jsFiles.Select(jsFile => new PostJsLibrary(jsFile))); } if (beeFolder.DirectoryExists()) { ProjectFile.AdditionalFiles.AddRange(beeFolder.Files("*.cs")); } if (includeFolder.DirectoryExists()) { GetOrMakeNativeProgram().PublicIncludeDirectories.Add(includeFolder); } } SupportFiles.Add(AllSourcePaths.SelectMany(p => p.Files() .Where(f => f.HasExtension("jpg", "png", "wav", "mp3", "jpeg", "mp4", "webm", "ogg", "ttf", "json")))); Defines.Add(c => c.CodeGen == CSharpCodeGen.Debug || (c as DotsRuntimeCSharpProgramConfiguration)?.DotsConfiguration < DotsConfiguration.Release, "DEBUG"); Defines.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).EnableUnityCollectionsChecks, "ENABLE_UNITY_COLLECTIONS_CHECKS"); Defines.Add( c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.TinyIl2cpp, "UNITY_DOTSPLAYER_IL2CPP"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.ScriptingBackend == ScriptingBackend.Dotnet, "UNITY_DOTSPLAYER_DOTNET"); Defines.Add(c => (c as DotsRuntimeCSharpProgramConfiguration)?.Defines ?? new List <string>()); ProjectFile.RedirectMSBuildBuildTargetToBee = true; ProjectFile.AddCustomLinkRoot(MainSourcePath, "."); ProjectFile.RootNameSpace = ""; DotsRuntimeCSharpProgramCustomizer.RunAllCustomizersOn(this); }
private void AddDependency(ItemReference itemRef, XmlNode context, XmlNode reference, ItemReference masterRef) { _dependencies.Add(itemRef); if (context != null) { References refs; if (!_allDependencies.TryGetValue(itemRef, out refs)) { refs = new References(); _allDependencies.Add(itemRef, refs); } refs.AddReferences(reference, context, masterRef); } }
IEnumerable <string> GetFilteredReferences(IEnumerable <string> onlyBinaries, Configuration config) { if (config.IncludeAssemblies.Any()) { var skippedAssemblies = new List <string>(config.IncludeAssemblies); foreach (var file in onlyBinaries) { var assemblyName = Path.GetFileNameWithoutExtension(file); if (config.IncludeAssemblies.Any(x => x == assemblyName) && config.Unmanaged32Assemblies.All(x => x != assemblyName) && config.Unmanaged64Assemblies.All(x => x != assemblyName)) { skippedAssemblies.Remove(assemblyName); yield return(file); } } if (skippedAssemblies.Count > 0) { if (References == null) { throw new WeavingException("To embed references with CopyLocal='false', References is required - you may need to update to the latest version of Fody."); } var splittedReferences = References.Split(';'); foreach (var skippedAssembly in skippedAssemblies) { var fileName = (from splittedReference in splittedReferences where string.Equals(Path.GetFileNameWithoutExtension(splittedReference), skippedAssembly, StringComparison.InvariantCultureIgnoreCase) select splittedReference).FirstOrDefault(); if (string.IsNullOrEmpty(fileName)) { LogError($"Assembly '{skippedAssembly}' cannot be found (not even as CopyLocal='false'), please update the configuration"); } yield return(fileName); } } yield break; } if (config.ExcludeAssemblies.Any()) { foreach (var file in onlyBinaries.Except(config.Unmanaged32Assemblies).Except(config.Unmanaged64Assemblies)) { var assemblyName = Path.GetFileNameWithoutExtension(file); if (config.ExcludeAssemblies.Any(x => x == assemblyName) || config.Unmanaged32Assemblies.Any(x => x == assemblyName) || config.Unmanaged64Assemblies.Any(x => x == assemblyName)) { continue; } yield return(file); } yield break; } if (config.OptOut) { foreach (var file in onlyBinaries) { var assemblyName = Path.GetFileNameWithoutExtension(file); if (config.Unmanaged32Assemblies.All(x => x != assemblyName) && config.Unmanaged64Assemblies.All(x => x != assemblyName)) { yield return(file); } } } }
public override bool Execute() { var project = new ConfuserProject(); if (!string.IsNullOrWhiteSpace(SourceProject?.ItemSpec)) { var xmlDoc = new XmlDocument(); xmlDoc.Load(SourceProject.ItemSpec); project.Load(xmlDoc); // Probe Paths are not required, because all dependent assemblies are added as external modules. project.ProbePaths.Clear(); } project.BaseDirectory = Path.GetDirectoryName(AssemblyPath.ItemSpec); var mainModule = GetOrCreateProjectModule(project, AssemblyPath.ItemSpec); if (!string.IsNullOrWhiteSpace(KeyFilePath?.ItemSpec)) { mainModule.SNKeyPath = KeyFilePath.ItemSpec; } if (!string.IsNullOrWhiteSpace(PubKeyFilePath?.ItemSpec)) { mainModule.SNPubKeyPath = PubKeyFilePath.ItemSpec; } if (!string.IsNullOrWhiteSpace(SigKeyFilePath?.ItemSpec)) { mainModule.SNSigKeyPath = SigKeyFilePath.ItemSpec; } if (!string.IsNullOrWhiteSpace(PubSigKeyFilePath?.ItemSpec)) { mainModule.SNPubSigKeyPath = PubSigKeyFilePath.ItemSpec; } if (!string.IsNullOrWhiteSpace(DelaySig?.ItemSpec)) { bool.TryParse(DelaySig.ItemSpec, out bool delaySig); mainModule.SNDelaySig = delaySig; } if (SatelliteAssemblyPaths != null) { foreach (var satelliteAssembly in SatelliteAssemblyPaths) { if (string.IsNullOrWhiteSpace(satelliteAssembly?.ItemSpec)) { continue; } var satelliteModule = GetOrCreateProjectModule(project, satelliteAssembly.ItemSpec); satelliteModule.SNKeyPath = mainModule.SNKeyPath; satelliteModule.SNPubKeyPath = mainModule.SNPubKeyPath; satelliteModule.SNSigKeyPath = mainModule.SNSigKeyPath; satelliteModule.SNPubSigKeyPath = mainModule.SNPubSigKeyPath; satelliteModule.SNDelaySig = mainModule.SNDelaySig; } } foreach (var probePath in References.Select(r => Path.GetDirectoryName(r.ItemSpec)).Distinct()) { project.ProbePaths.Add(probePath); } project.Save().Save(ResultProject.ItemSpec); return(true); }
/// <summary> /// Called by References once it is done gathering all neccessary information /// Starts the game /// </summary> void Begin() { //Gets a link to the references script refs = gameObject.GetComponent<References>(); //Starts the game StartGame(); }
private void RenderArchives(Compilation c, IHTMLElement parent, Action<string> UpdateLocation) { var AllTypes = default(IHTMLDiv); var AllTypesNamespaceLookup = new Dictionary<string, IHTMLDiv>(); var GetAllTypesNamespaceContainer = default(Func<string, IHTMLDiv>); GetAllTypesNamespaceContainer = (Namespace) => { var ParentNamespace = Namespace.TakeUntilLastIfAny("."); var ParentContainer = AllTypes; if (ParentNamespace != Namespace) { ParentContainer = GetAllTypesNamespaceContainer(ParentNamespace); } if (!AllTypesNamespaceLookup.ContainsKey(Namespace)) { AllTypesNamespaceLookup[Namespace] = AddNamespace(ParentContainer, null, Namespace.SkipUntilLastIfAny("."), UpdateLocation); } return AllTypesNamespaceLookup[Namespace]; }; { var tr = new TreeNode(() => new VistaTreeNodePage()); tr.Text = "Class Viewer"; tr.Element.ClosedImage = new ClassViewer(); tr.Container.AttachTo(parent); var div = new IHTMLDiv().AttachTo(parent); div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana; var i = new References().AttachTo(div); i.style.verticalAlign = "middle"; i.style.marginRight = "0.5em"; new IHTMLSpan { innerText = "All Types" }.AttachTo(div); var children = new IHTMLDiv().AttachTo(parent); children.style.paddingLeft = "1em"; AllTypes = children; } var LoadActionList = new List<Action<Action>>(); var Archives = c.GetArchives(); foreach (var Archive in Archives) { Console.WriteLine(new { Archive.Name }); } // lets not freeze our browser:P foreach (var item in Archives.ToArray()) { var div = new IHTMLDiv().AttachTo(parent); div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana; var i = new References().AttachTo(div); i.style.verticalAlign = "middle"; i.style.marginRight = "0.5em"; new IHTMLSpan { innerText = item.Name }.AttachTo(div); var children = new IHTMLDiv().AttachTo(parent); children.style.paddingLeft = "1em"; Console.WriteLine("before RenderAssemblies"); RenderAssemblies(item, children, GetAllTypesNamespaceContainer, UpdateLocation, LoadActionList.Add); Console.WriteLine("after RenderAssemblies"); } Console.WriteLine("before LoadActionList"); LoadActionList.ForEach( (Current, Next) => { Console.WriteLine("before LoadActionList Next"); Current(Next); Console.WriteLine("after LoadActionList Next"); } ); }