internal string GetAssemblyPath(AssemblyName assemblyName)
        {
            if (IsFailedAssembly(assemblyName.FullName))
            {
                return string.Empty;
            }
            string filePath = string.Empty;

            if (string.IsNullOrEmpty(filePath))
            {
                IEnumerable<string> filePaths = GetAssemblyPaths(assemblyName);

                filePath = filePaths.FirstOrDefault() ?? string.Empty;

                if (string.IsNullOrEmpty(filePath))
                {
                    foreach (string currentFilePath in filePaths)
                    {
                        if (!string.IsNullOrEmpty(currentFilePath))
                        {
                            filePath = currentFilePath;
                            break;
                        }
                    }
                }

                if (CheckFoundedAssembly(assemblyName, filePath))
                {
                    return filePath;
                }
            }
            return filePath;
        }
 private bool AreDefaultDirEqual(AssemblyName assemblyName, AssemblyName assemblyNameFromStorage)
 {
     if (!assemblyName.HasDefaultDir && !assemblyNameFromStorage.HasDefaultDir)
     {
         return true;
     }
     if (assemblyName.HasDefaultDir && assemblyNameFromStorage.HasDefaultDir)
     {
         if (File.Exists(Path.Combine(assemblyName.DefaultDir, assemblyName.Name + ".dll"))
             && File.Exists(Path.Combine(assemblyNameFromStorage.DefaultDir, assemblyNameFromStorage.Name + ".dll")))
         {
             return assemblyName.DefaultDir == assemblyNameFromStorage.DefaultDir;
         }
         return true;
     }
     return true;
 }
        private IEnumerable<string> ResolveWinRTMetadata(AssemblyName assemblyName)
        {
            string filePath = string.Format(@"{0}\{1}.winmd", SystemInformation.WINRT_METADATA, assemblyName.Name);
            if (CheckFileExistence(assemblyName, filePath, true, false))
            {
                yield return filePath;
            }

            if (!Directory.Exists(SystemInformation.WINDOWS_WINMD_LOCATION))
            {
                yield break;
            }

            foreach (string foundFile in Directory.GetFiles(SystemInformation.WINDOWS_WINMD_LOCATION, assemblyName.Name + ".winmd", SearchOption.AllDirectories))
            {
                if (CheckFileExistence(assemblyName, foundFile, true, false))
                {
                    yield return foundFile;
                }
            }
        }
 public override string FindAssemblyPath(AssemblyName assemblyName, string fallbackDir, bool bubbleToUserIfFailed = true)
 {
     return base.FindAssemblyPath(assemblyName, fallbackDir, bubbleToUserIfFailed: false);
 }
        public string ResolveAssemblyPath(string strongName)
        {
            AssemblyNameReference nameRef = AssemblyNameReference.Parse(strongName);
            TargetArchitecture architecture = GetArchitectureFromStrongName(strongName);

            AssemblyName assemblyName = new AssemblyName(nameRef.Name,
                                               nameRef.FullName,
                                               nameRef.Version,
                                               nameRef.PublicKeyToken) { TargetArchitecture = architecture };
            IEnumerable<string> files = assemblyPathResolver.GetAssemblyPaths(assemblyName);

            foreach (string file in files)
            {
                if (GetAssemblyDefinition(file).main_module.GetModuleArchitecture().CanReference(architecture))
                {
                    return file;
                }
            }
            return string.Empty;
        }
        private bool TrySearchDirectory(AssemblyNameReference name, ReaderParameters parameters, TargetArchitecture architecture, IEnumerable<DirectoryAssemblyInfo> targetDirs, out AssemblyDefinition assemblyDefinition)
        {
            assemblyDefinition = null;

            string lowerName = name.Name.ToLowerInvariant();

            foreach (DirectoryAssemblyInfo directoryAssembly in targetDirs)
            {
                string assemblyPath = directoryAssembly.FullFileName;
                if (directoryAssembly.FileNameWithoutExtension == lowerName)
                {
                    AssemblyName assName = new AssemblyName(name.Name, name.FullName, name.Version, name.PublicKeyToken) { TargetArchitecture = architecture };
                    bool sameVersion = assemblyPathResolver.CheckFileExistence(assName, assemblyPath, false, false, checkForArchitectPlatfrom: true);
                    if (sameVersion)
                    {
                        assemblyDefinition = GetAssembly(directoryAssembly.FullFileName, parameters);

                        return true;
                    }
                }
            }
            return false;
        }
        /*Telerik Authorship*/
        private AssemblyDefinition GetFromResolvedAssemblies(AssemblyName assemblyName)
        {
            string extendedKey = assemblyName.FullName + ",Architecture=";
            foreach (string architectureString in GetReferencableArchitectures(assemblyName))
            {
                List<AssemblyDefinition> assemblyList;
                if (TryGetResolvedAssembly(extendedKey + architectureString, out assemblyList))
                {
                    return assemblyList[0];
                }
            }

            return null;
        }
        private IEnumerable<string> ResolveSilverlightPaths(AssemblyName assemblyName)
        {
            List<string> result = new List<string>();

            string runtime = ResolveSilverlightRuntimePath(assemblyName, SystemInformation.SILVERLIGHT_RUNTIME);

            string runtime64 = ResolveSilverlightRuntimePath(assemblyName, SystemInformation.SILVERLIGHT_RUNTIME_64);

            IEnumerable<string> @default = ResolveSilverlightPath(assemblyName, SystemInformation.SILVERLIGHT_DEFAULT);

            IEnumerable<string> sdk = ResolveSilverlightPath(assemblyName, SystemInformation.SILVERLIGHT_SDK);

            if (string.IsNullOrEmpty(runtime) == false)
            {
                result.Add(runtime);
            }
            result.AddRange(@default);

            result.AddRange(sdk);
            /*Telerik Authorship*/
            if (string.IsNullOrEmpty(runtime64) == false)
            {
                result.Add(runtime64);
            }
            return result;
        }
 private string ResolveSilverlightRuntimePath(AssemblyName assemblyName, string path)
 {
     string searchPattern = string.Format(path, assemblyName.Name);
     if (CheckFileExistence(assemblyName, searchPattern, true, true))
     {
         return searchPattern;
     }
     return string.Empty;
 }
        public IEnumerable<string> GetAssemblyPaths(AssemblyName sourceAssemblyName)
        {
            IEnumerable<string> results;

            if (TryGetAssemblyPathsFromCache(sourceAssemblyName, out results))
            {
                return results;
            }
            if (IsFailedAssembly(sourceAssemblyName.FullName))
            {
                return Enumerable.Empty<string>();
            }
            var platforms = new List<TargetPlatform>
            {
                TargetPlatform.CLR_4,
                TargetPlatform.CLR_2_3,
                TargetPlatform.Silverlight,
                TargetPlatform.WindowsPhone,
                TargetPlatform.WindowsCE,
                TargetPlatform.CLR_1,
                TargetPlatform.WinRT
            };
            var result = new List<string>();
            foreach (TargetPlatform platform in platforms)
            {
                IEnumerable<string> assemblyLocations = GetAssemblyLocationsByPlatform(sourceAssemblyName, platform);

                result.AddRange(assemblyLocations);
            }
            return result;
        }
        private IEnumerable<string> GetAssemblyLocationsByPlatform(AssemblyName assemblyName, TargetPlatform runtime)
        {
            var result = new List<string>();
            switch (runtime)
            {
                case TargetPlatform.CLR_1:
                    result.AddRange(ResolveClr1(assemblyName));
                    break;
                case TargetPlatform.CLR_2_3:
                case TargetPlatform.CLR_4:
                    result.AddRange(ResolveClr(assemblyName, runtime));
                    break;

                case TargetPlatform.WindowsCE:
                    result.AddRange(ResolveCompact(assemblyName));
                    break;

                case TargetPlatform.Silverlight:
                case TargetPlatform.WindowsPhone:
                    result.AddRange(ResolveSilverlightPaths(assemblyName));
                    result.AddRange(ResolveWP(assemblyName));
                    break;

                case TargetPlatform.WinRT:
                    result.AddRange(ResolveWinRTMetadata(assemblyName));
                    break;
            }
            AddPartCacheResult(result, runtime);

            return result;
        }
        internal bool TryGetAssemblyPathsFromCache(AssemblyName sourceAssemblyName, out IEnumerable<string> filePaths)
        {
            filePaths = Enumerable.Empty<string>();

            if (pathRepository.AssemblyPathName.ContainsKey(sourceAssemblyName.FullName))
            {
                List<string> targets = pathRepository.AssemblyPathName.Where(a => a.Key == sourceAssemblyName.FullName)
                                                        .Select(a => a.Value)
                                                        .ToList();

                if (sourceAssemblyName.HasDefaultDir && targets.Any(d => Path.GetDirectoryName(d) == sourceAssemblyName.DefaultDir))
                {
                    filePaths = targets.Where(d => Path.GetDirectoryName(d) == sourceAssemblyName.DefaultDir);

                    return true;
                }
                else
                {
                    string targetAssembly = pathRepository.AssemblyPathName
                                                             .Where(a => pathRepository.AssemblyPathArchitecture.ContainsKey(a.Value) && pathRepository.AssemblyPathArchitecture[a.Value].CanReference(sourceAssemblyName.TargetArchitecture))
                                                             .FirstOrDefault(a => a.Key == sourceAssemblyName.FullName).Value;
                    if (targetAssembly != null)
                    {
                        filePaths = new string[] { targetAssembly };

                        return true;
                    }
                }
            }
            return false;
        }
 private bool CheckFoundedAssembly(AssemblyName assemblyName, string filePath)
 {
     bool checkFileExistence = CheckFileExistence(assemblyName, filePath, false, false);
     return checkFileExistence;
 }
 public bool CheckFileExistence(AssemblyName assemblyName, string searchPattern, bool caching, bool checkForBaseDir, bool checkForArchitectPlatfrom = true)
 {
     AssemblyName assemblyNameFromStorage;
     if (TryGetAssemblyNameDefinition(searchPattern, caching, assemblyName.TargetArchitecture, out assemblyNameFromStorage, checkForArchitectPlatfrom))
     {
         var areEquals = AreVersionEquals(assemblyNameFromStorage.Version, assemblyName.Version)
                         && ArePublicKeyEquals(assemblyNameFromStorage.PublicKeyToken, assemblyName.PublicKeyToken)
                         && assemblyName.TargetArchitecture.CanReference(assemblyNameFromStorage.TargetArchitecture)
                         && (!checkForBaseDir || AreDefaultDirEqual(assemblyName, assemblyNameFromStorage));
         if (areEquals && caching)
         {
             pathRepository.AssemblyPathName.Add(assemblyName.FullName, searchPattern);
             if (!pathRepository.AssemblyPathArchitecture.ContainsKey(searchPattern))
             {
                 TargetArchitecture architecture = AssemblyDefinition.ReadAssembly(searchPattern, readerParameters).MainModule.GetModuleArchitecture();
                 pathRepository.AssemblyPathArchitecture.Add(new KeyValuePair<string, TargetArchitecture>(searchPattern, architecture));
             }
         }
         return areEquals;
     }
     return false;
 }
 private bool TryGetAssemblyNameDefinition(string assemblyFilePath,
                                                  bool caching,
                                                  TargetArchitecture architecture,
                                                  out AssemblyName assemblyName,
                                                  bool checkForArchitectPlatfrom = true)
 {
     assemblyName = null;
     if (pathRepository.AssemblyNameDefinition.ContainsKey(assemblyFilePath))
     {
         assemblyName = pathRepository.AssemblyNameDefinition[assemblyFilePath];
         if (!checkForArchitectPlatfrom)
         {
             return true;
         }
         else if (assemblyName.TargetArchitecture == architecture)
         {
             return true;
         }
     }
     if ((caching || assemblyName == null) && File.Exists(assemblyFilePath))
     {
         var moduleDef = ModuleDefinition.ReadModule(assemblyFilePath, readerParameters);
         if (moduleDef != null && moduleDef.Assembly != null)
         {
             AssemblyDefinition assemblyDef = moduleDef.Assembly;
             assemblyName = new AssemblyName(moduleDef.Name,
                                             assemblyDef.FullName,
                                             assemblyDef.Name.Version,
                                             assemblyDef.Name.PublicKeyToken,
                                             Path.GetDirectoryName(assemblyFilePath)) { TargetArchitecture = moduleDef.GetModuleArchitecture() };
             pathRepository.AssemblyNameDefinition[assemblyFilePath] = assemblyName;
             return true;
         }
     }
     return false;
 }
 private IEnumerable<string> ResolveSilverlightPath(AssemblyName assemblyName, string path)
 {
     foreach (var version in assemblyName.SupportedVersions(TargetPlatform.Silverlight))
     {
         string searchPattern = string.Format(path, SystemInformation.ProgramFilesX86, version, assemblyName.Name);
         if (CheckFileExistence(assemblyName, searchPattern, true, true))
         {
             yield return searchPattern;
         }
     }
 }
        internal void AddToAssemblyPathNameCache(AssemblyName assemblyName, string filePath)
        {
            pathRepository.AssemblyPathName.Add(assemblyName.FullName, filePath);

            if (!pathRepository.AssemblyPathArchitecture.ContainsKey(filePath))
            {
                pathRepository.AssemblyPathArchitecture.Add(new KeyValuePair<string, TargetArchitecture>(filePath, assemblyName.TargetArchitecture));
            }
        }
 private IEnumerable<string> ResolveCompact(AssemblyName assemblyName)
 {
     foreach (var ver in assemblyName.SupportedVersions(TargetPlatform.WindowsCE))
     {
         var searchPattern = string.Format(SystemInformation.COMPACT_FRAMEWORK, SystemInformation.ProgramFilesX86, ver, assemblyName.Name);
         if (CheckFileExistence(assemblyName, searchPattern, true, false))
         {
             yield return searchPattern;
         }
     }
 }
        protected ProjectItemGroup CreatePojectReferences(ModuleDefinition module, ProjectPropertyGroup basicProjectProperties)
        {
            ProjectItemGroup result = new ProjectItemGroup();

			ICollection<AssemblyNameReference> dependingOnAssemblies = GetAssembliesDependingOn(module);
            result.Reference = new ProjectItemGroupReference[dependingOnAssemblies.Count];

            string copiedReferencesSubfolder = basicProjectProperties.AssemblyName + "References";
            string referencesPath = TargetPath.Remove(TargetPath.LastIndexOf(Path.DirectorySeparatorChar)) + Path.DirectorySeparatorChar + copiedReferencesSubfolder;

            int assemblyReferenceIndex = 0;
            foreach (AssemblyNameReference reference in dependingOnAssemblies)
            {
                if (reference.Name == "mscorlib" ||
                    reference.Name == "Windows" && reference.Version.Equals(new Version(255, 255, 255, 255)) ||
                    reference.Name == "System.Runtime")
                {
                    continue;
                }

                AssemblyName assemblyName = new AssemblyName(reference.Name,
                                                                reference.FullName,
                                                                reference.Version,
                                                                reference.PublicKeyToken);

                string currentReferenceInitialLocation = this.currentAssemblyResolver.FindAssemblyPath(assemblyName, null);
                AssemblyDefinition referencedAssembly = this.currentAssemblyResolver.Resolve(reference, "", assembly.MainModule.GetModuleArchitecture());
#if NET35
				if (!currentReferenceInitialLocation.IsNullOrWhiteSpace())
#else
                if (!string.IsNullOrWhiteSpace(currentReferenceInitialLocation))
#endif
                {
                    result.Reference[assemblyReferenceIndex] = new ProjectItemGroupReference();
                    if (IsInReferenceAssemblies(referencedAssembly))
                    {
                        //TODO: Consider doing additional check, to see if the assembly is resolved because it was pointed by the used/already in the tree
                        //		In this case, it might be better to copy it.
                        result.Reference[assemblyReferenceIndex].Include = reference.Name;
                    }
                    else // Copy the referenced assembly
                    {
                        if (!Directory.Exists(referencesPath))
                        {
                            Directory.CreateDirectory(referencesPath);
                        }

                        string currentReferenceFileName = Path.GetFileName(currentReferenceInitialLocation);
                        string currentReferenceFinalLocation = Path.Combine(referencesPath, currentReferenceFileName);
                        File.Copy(currentReferenceInitialLocation, currentReferenceFinalLocation, true);

                        // set to normal for testing purposes- to allow the test project to delete the coppied file between test runs
                        File.SetAttributes(currentReferenceFinalLocation, FileAttributes.Normal);

                        string relativePath = Path.Combine(".", copiedReferencesSubfolder);
                        relativePath = Path.Combine(relativePath, currentReferenceFileName);

                        result.Reference[assemblyReferenceIndex].Include = Path.GetFileNameWithoutExtension(currentReferenceFinalLocation);
                        result.Reference[assemblyReferenceIndex].Item = relativePath;
                    }
                }

                assemblyReferenceIndex++;
            }

			ICollection<ModuleReference> dependingOnModules = GetModulesDependingOn(module);
			result.AddModules = new ProjectItemGroupAddModules[dependingOnModules.Count * 2];

			int moduleReferenceIndex = 0;
			foreach (ModuleReference moduleRef in dependingOnModules)
			{
				result.AddModules[moduleReferenceIndex] = new ProjectItemGroupAddModules();
				result.AddModules[moduleReferenceIndex].Include = @"bin\Debug\" + Utilities.GetNetmoduleName(moduleRef) + ".netmodule";
				result.AddModules[moduleReferenceIndex].Condition = " '$(Configuration)' == 'Debug' ";
				moduleReferenceIndex++;
				result.AddModules[moduleReferenceIndex] = new ProjectItemGroupAddModules();
				result.AddModules[moduleReferenceIndex].Include = @"bin\Release\" + Utilities.GetNetmoduleName(moduleRef) + ".netmodule";
				result.AddModules[moduleReferenceIndex].Condition = " '$(Configuration)' == 'Release' ";
				moduleReferenceIndex++; 
			}

            return result;
        }
 private IEnumerable<string> ResolveWP(AssemblyName assemblyName)
 {
     foreach (var version in assemblyName.SupportedVersions(TargetPlatform.WindowsPhone))
     {
         string windowsPhoneDir = string.Format(@"{0}\Reference Assemblies\Microsoft\Framework\Silverlight\{1}\Profile\",
                                                SystemInformation.ProgramFilesX86,
                                                version);
         if (Directory.Exists(windowsPhoneDir))
         {
             foreach (string dirVersions in Directory.GetDirectories(windowsPhoneDir, "WindowsPhone*."))
             {
                 string searchPattern = string.Format("{0}\\{1}.dll", dirVersions, assemblyName.Name);
                 if (CheckFileExistence(assemblyName, searchPattern, true, true))
                 {
                     yield return searchPattern;
                 }
             }
         }
     }
 }
 private string[] GetReferencableArchitectures(AssemblyName assemblyName)
 {
     if (assemblyName.TargetArchitecture != TargetArchitecture.AnyCPU)
     {
         return new string[] { "AnyCPU", assemblyName.TargetArchitecture.ToString() };
     }
     return architectureStrings;
 }
        private IEnumerable<string> ResolveClr(AssemblyName assemblyName, TargetPlatform clrRuntime)
        {
            var result = new List<string>();

            string versionMajor = string.Format("v{0}*", (clrRuntime == TargetPlatform.CLR_4 ? 4 : 2));

            var targetDirectories = new List<string>();
            if (Directory.Exists(SystemInformation.CLR_Default_32))
            {
                targetDirectories.AddRange(Directory.GetDirectories(SystemInformation.CLR_Default_32, versionMajor));
            }
            if (Directory.Exists(SystemInformation.CLR_Default_64))
            {
                targetDirectories.AddRange(Directory.GetDirectories(SystemInformation.CLR_Default_64, versionMajor));
            }
            foreach (var dir in targetDirectories)
            {
                foreach (string extension in SystemInformation.ResolvableExtensions)
                {
                    string filePath = dir + "\\" + assemblyName.Name + extension;
                    if (CheckFileExistence(assemblyName, filePath, true, false))
                    {
                        result.Add(filePath);
                    }
                }
            }
            var searchPattern = clrRuntime == TargetPlatform.CLR_4 ? SystemInformation.CLR_4 : SystemInformation.CLR;

            foreach (var targetRuntime in assemblyName.SupportedVersions(clrRuntime))
            {
                foreach (var extension in SystemInformation.ResolvableExtensions)
                {
                    string filePath = string.Format(searchPattern,
                                                    SystemInformation.WindowsPath,
                                                    targetRuntime,
                                                    assemblyName.Name,
                                                    assemblyName.ParentDirectory(clrRuntime),
                                                    assemblyName.Name,
                                                    extension);
                    if (CheckFileExistence(assemblyName, filePath, true, false))
                    {
                        result.Add(filePath);
                    }
                }
            }
            return result;
        }
 AssemblyDefinition TryGetTargetAssembly(AssemblyNameReference reference, ReaderParameters parameters, TargetArchitecture architecture)
 {
     if (reference == null)
     {
         return null;
     }
     var assemblyName = new AssemblyName(reference.Name,
                                        reference.FullName,
                                        reference.Version,
                                        reference.PublicKeyToken) { TargetArchitecture = architecture };
     IEnumerable<string> filePaths;
     if (assemblyPathResolver.TryGetAssemblyPathsFromCache(assemblyName, out filePaths))
     {
         return GetTargetAssembly(filePaths, parameters, architecture);
     }
     return null;
 }
        private IEnumerable<string> ResolveClr1(AssemblyName assemblyName)
        {
            string path = Path.Combine(SystemInformation.WindowsPath, "Microsoft.NET\\Framework");
            if (assemblyName.Version.Major != 1)
            {
                yield break;
            }

            foreach (string extension in SystemInformation.ResolvableExtensions)
            {
                string[] files = Directory.GetFiles(path, assemblyName.Name + extension, SearchOption.AllDirectories);
                foreach (string filePath in files)
                {
                    if (CheckFileExistence(assemblyName, filePath, true, false))
                    {
                        yield return filePath;
                    }
                }
            }
        }
        public virtual string FindAssemblyPath(AssemblyName assemblyName, string fallbackDir, bool bubbleToUserIfFailed = true)
        {
            if (assemblyPathResolver.IsFailedAssembly(assemblyName.FullName))
            {
                return null;
            }

            AssemblyDefinition resolvedAssembly = GetFromResolvedAssemblies(assemblyName);
            if (resolvedAssembly != null)
            {
                return resolvedAssembly.MainModule.FilePath;
            }

            var assemblyNameRef = new AssemblyNameReference(assemblyName.Name, assemblyName.Version) { PublicKeyToken = assemblyName.PublicKeyToken };

            IEnumerable<string> results;
            if (assemblyPathResolver.TryGetAssemblyPathsFromCache(assemblyName, out results))
            {
                return results.FirstOrDefault();
            }
            AssemblyDefinition assembluDefinition = SearchDirectory(assemblyNameRef, new ReaderParameters(this), assemblyName.TargetArchitecture, fallbackDir);

            if (assembluDefinition != null)
            {
                assemblyPathResolver.AddToAssemblyPathNameCache(assemblyName, assembluDefinition.MainModule.FilePath);

                return assembluDefinition.MainModule.FilePath;
            }
            string result = assemblyPathResolver.GetAssemblyPath(assemblyName);

#if !NET_4_0
            if (!result.IsNullOrWhiteSpace())
#else
            if (!string.IsNullOrWhiteSpace(result))
#endif
            {
                return result;
            }
            if (bubbleToUserIfFailed)
            {
                assembluDefinition = UserSpecifiedAssembly(assemblyNameRef, assemblyName.TargetArchitecture);
            }
            if (assembluDefinition != null)
            {
                string filePath = assembluDefinition.MainModule.FilePath;

                this.AddSearchDirectory(Path.GetDirectoryName(filePath));

                return filePath;
            }

            return result;
        }
 private IEnumerable<string> ResolveUWPReferences(AssemblyName assemblyName)
 {
     string fileName = string.Format("{0}.winmd", assemblyName.Name);
     string filePath = Path.Combine(SystemInformation.UWP_REFERENCES, assemblyName.Name, assemblyName.Version.ToString(), fileName);
     if (CheckFileExistence(assemblyName, filePath, true, false))
     {
         yield return filePath;
     }
 }