public static void GetFileTypeFullNameInAppDomain()
        {
            try
            {
                var filePath = (string)AppDomain.CurrentDomain.GetData(configFilePath);

                var assembliesProjects = (string[])AppDomain.CurrentDomain.GetData(configAssembliesProjects);
                var assemblies         = (string[])AppDomain.CurrentDomain.GetData(configAssemblies);

                AppDomain.CurrentDomain.SetData(configResult, string.Empty);

                HashSet <string> list = new HashSet <string>(assembliesProjects, StringComparer.InvariantCultureIgnoreCase);

                var resolver = new AssemblyResolver(assembliesProjects.Select(e => Path.GetDirectoryName(e)).ToArray());

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver.Domain_ReflectionOnlyAssemblyResolve;
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver.Domain_ReflectionOnlyAssemblyResolve;
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver.Domain_ReflectionOnlyAssemblyResolve;
                AppDomain.CurrentDomain.AssemblyResolve -= resolver.Domain_AssemblyResolve;
                AppDomain.CurrentDomain.AssemblyResolve -= resolver.Domain_AssemblyResolve;
                AppDomain.CurrentDomain.AssemblyResolve += resolver.Domain_AssemblyResolve;

                var hash = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);

                foreach (var item in assemblies)
                {
                    Assembly assembly = Assembly.ReflectionOnlyLoadFrom(item);

                    if (hash.Add(Path.GetFileName(item)))
                    {
                        list.Add(item);
                    }
                }

                foreach (var item in assemblies)
                {
                    Assembly assembly = Assembly.ReflectionOnlyLoadFrom(item);

                    var files = assembly.GetReferencedAssemblies();

                    foreach (var reference in files)
                    {
                        if (reference.Name != "mscorlib")
                        {
                            var temp = Assembly.ReflectionOnlyLoad(reference.FullName);

                            if (!string.IsNullOrEmpty(temp.CodeBase))
                            {
                                var uri = new Uri(temp.CodeBase);

                                if (hash.Add(Path.GetFileName(uri.LocalPath)))
                                {
                                    list.Add(uri.LocalPath);
                                }
                            }
                        }
                    }
                }

                foreach (var item in assembliesProjects)
                {
                    Assembly assembly = Assembly.ReflectionOnlyLoadFrom(item);

                    if (hash.Add(Path.GetFileName(item)))
                    {
                        list.Add(item);
                    }
                }

                foreach (var item in assembliesProjects)
                {
                    Assembly assembly = Assembly.ReflectionOnlyLoadFrom(item);

                    var files = assembly.GetReferencedAssemblies();

                    foreach (var reference in files)
                    {
                        if (reference.Name != "mscorlib")
                        {
                            var temp = Assembly.ReflectionOnlyLoad(reference.FullName);

                            if (!string.IsNullOrEmpty(temp.CodeBase))
                            {
                                var uri = new Uri(temp.CodeBase);

                                if (hash.Add(Path.GetFileName(uri.LocalPath)))
                                {
                                    list.Add(uri.LocalPath);
                                }
                            }
                        }
                    }
                }

                string code = File.ReadAllText(filePath);

                CompilerParameters parameters = new CompilerParameters()
                {
                    GenerateInMemory   = true,
                    GenerateExecutable = false,
                };

                parameters.ReferencedAssemblies.AddRange(list.ToArray());

                using (CSharpCodeProvider provider = new CSharpCodeProvider())
                {
                    var compilerResults = provider.CompileAssemblyFromSource(parameters, code);

                    if (compilerResults.Errors.Count == 0)
                    {
                        var types = compilerResults.CompiledAssembly.DefinedTypes;

                        AppDomain.CurrentDomain.SetData(configResult, types.FirstOrDefault()?.FullName);
                    }

                    AppDomain.CurrentDomain.AssemblyResolve -= resolver.Domain_AssemblyResolve;
                    AppDomain.CurrentDomain.AssemblyResolve -= resolver.Domain_AssemblyResolve;
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver.Domain_ReflectionOnlyAssemblyResolve;
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver.Domain_ReflectionOnlyAssemblyResolve;
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);
            }
        }
示例#2
0
        private async Task FillDescriptionUsedEntities(StringBuilder strFile, HashSet <Guid> workflowsWithEntities, Dictionary <EntityReference, HashSet <Guid> > list)
        {
            string message = string.Empty;

            if (list.Count == 0)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "No used entities in workflows."))
                ;
                return;
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendFormat(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "Used Entities {0}", list.Count)).AppendLine()
            ;

            var orderedList = list.Keys.OrderBy(i => i.LogicalName).ThenBy(i => i.Name).ThenBy(i => i.Id);

            {
                FormatTextTableHandler table = new FormatTextTableHandler();
                table.SetHeader("LogicalName", "Name", "Id", "Url");

                foreach (var item in orderedList)
                {
                    var values = new List <string>()
                    {
                        item.LogicalName, item.Name, item.Id.ToString()
                    };

                    var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                    if (!string.IsNullOrEmpty(url))
                    {
                        values.Add(url);
                    }

                    table.AddLine(values);
                }

                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(tabspacer + s));
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendLine()
            .AppendLine(new string('-', 150))
            .AppendLine()
            .AppendLine()
            .AppendLine()
            ;

            strFile.AppendFormat("Used Entities Full Information {0}", list.Count).AppendLine();

            foreach (var item in orderedList)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine();

                FormatTextTableHandler table = new FormatTextTableHandler();
                table.SetHeader("LogicalName", "Name", "Id");
                table.AddLine(item.LogicalName, item.Name, item.Id.ToString());
                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(s));

                var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                if (!string.IsNullOrEmpty(url))
                {
                    strFile.AppendLine("Url:");
                    strFile.AppendLine(url);
                }

                strFile.AppendLine();

                try
                {
                    var entityMetadata = _descriptor.MetadataSource.GetEntityMetadata(item.LogicalName);

                    if (entityMetadata != null)
                    {
                        var repositoryGeneric = new GenericRepository(_service, entityMetadata);

                        var entity = await repositoryGeneric.GetEntityByIdAsync(item.Id, new ColumnSet(true));

                        if (entity != null)
                        {
                            var desc = await EntityDescriptionHandler.GetEntityDescriptionAsync(entity, null, _service.ConnectionData);

                            strFile
                            .AppendLine(desc)
                            .AppendLine()
                            .AppendLine()
                            ;
                        }
                        else
                        {
                            strFile
                            .AppendFormat("{0} With Id = {1} Does Not Exists", item.LogicalName, item.Id).AppendLine()
                            .AppendLine()
                            .AppendLine()
                            ;
                        }
                    }
                    else
                    {
                        strFile
                        .AppendFormat("Entity with name '{0}' Does Not Exists", item.LogicalName).AppendLine()
                        .AppendFormat("{0} With Id = {1} Does Not Exists", item.LogicalName, item.Id).AppendLine()
                        .AppendLine()
                        .AppendLine()
                        ;
                    }
                }
                catch (Exception ex)
                {
                    var description = DTEHelper.GetExceptionDescription(ex);

                    strFile
                    .AppendLine(description)
                    .AppendLine()
                    .AppendLine()
                    ;
                }

                message = await _descriptor.GetSolutionComponentsDescriptionAsync(list[item].Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile
                .AppendLine("This entity Used By Workflows:")
                .AppendLine(message)
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(new string('-', 150))
                ;
            }

            if (workflowsWithEntities.Any())
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine("These entities Used By Workflows:")
                ;

                message = await _descriptor.GetSolutionComponentsDescriptionAsync(workflowsWithEntities.Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile.AppendLine(message);
            }
        }
        private Assembly Domain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var message = new StringBuilder();

            message.AppendFormat("Resolve Assembly {0}", args.Name);

            if (args.RequestingAssembly != null)
            {
                message
                .AppendLine()
                .AppendFormat("Requesting Assembly {0}", args.RequestingAssembly.FullName)
                ;
            }

            Assembly result = null;

            var assemblyName = new AssemblyName(args.Name);

            foreach (var knownedAssemblyName in _knownCrmAssemblies)
            {
                if (string.Equals(assemblyName.Name, knownedAssemblyName, StringComparison.InvariantCultureIgnoreCase))
                {
                    var temp = Assembly.Load(knownedAssemblyName + ", Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL");

                    message
                    .AppendLine()
                    .AppendFormat("Resolving from Knowed Assembly {0}", temp.FullName)
                    .AppendLine()
                    .AppendFormat("Resolving from path {0}", temp.CodeBase)
                    ;

                    result = Assembly.ReflectionOnlyLoadFrom(temp.CodeBase);
                }
            }

            if (result == null)
            {
                string fileName = assemblyName.Name + ".dll";

                foreach (string probeSubdirectory in AssemblyProbeSubdirectories)
                {
                    string filePath = Path.Combine(Path.Combine(_assemblyDirectory, probeSubdirectory), fileName);

                    if (File.Exists(filePath))
                    {
                        message
                        .AppendLine()
                        .AppendFormat("Resolving from File {0}", filePath)
                        ;

                        Assembly assembly2 = Assembly.Load(AssemblyName.GetAssemblyName(filePath));

                        if (assembly2 != null)
                        {
                            message
                            .AppendLine()
                            .AppendFormat("Resolving from CodeBase : {0}", assembly2.CodeBase)
                            ;

                            result = Assembly.ReflectionOnlyLoadFrom(assembly2.CodeBase);
                        }
                    }
                }
            }

            if (result == null)
            {
                message
                .AppendLine()
                .Append("Resolving by Default")
                ;

                var temp = Assembly.Load(args.Name);

                if (temp != null)
                {
                    message
                    .AppendLine()
                    .AppendFormat("Resolving by Default from : {0}", temp.CodeBase)
                    ;

                    result = Assembly.ReflectionOnlyLoadFrom(temp.CodeBase);
                }
            }

            message.AppendLine().AppendLine();

            if (result == null)
            {
                message.Append("Assembly NOT RESOLVED.");

                DTEHelper.WriteToLog(message.ToString());
            }

            return(result);
        }
        private static async Task LoadOrganizationDataAsync(OrganizationServiceExtentedProxy service, OrganizationDetail organizationDetail, WhoAmIResponse whoAmIResponse = null)
        {
            try
            {
                Guid?idOrganization = null;

                if (organizationDetail != null)
                {
                    idOrganization = organizationDetail.OrganizationId;

                    service.ConnectionData.OrganizationInformationExpirationDate = DateTime.Now.AddHours(_hoursOrganizationInformation);

                    service.ConnectionData.FriendlyName        = organizationDetail.FriendlyName;
                    service.ConnectionData.OrganizationId      = organizationDetail.OrganizationId;
                    service.ConnectionData.OrganizationVersion = organizationDetail.OrganizationVersion;
                    service.ConnectionData.OrganizationState   = organizationDetail.State.ToString();
                    service.ConnectionData.UniqueOrgName       = organizationDetail.UniqueName;
                    service.ConnectionData.UrlName             = organizationDetail.UrlName;

                    if (organizationDetail.Endpoints.ContainsKey(EndpointType.OrganizationService))
                    {
                        var organizationUrlEndpoint = organizationDetail.Endpoints[EndpointType.OrganizationService];

                        if (string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl) &&
                            !string.IsNullOrEmpty(organizationUrlEndpoint)
                            )
                        {
                            service.ConnectionData.OrganizationUrl = organizationUrlEndpoint;
                        }
                    }

                    if (organizationDetail.Endpoints.ContainsKey(EndpointType.WebApplication))
                    {
                        var publicUrl = organizationDetail.Endpoints[EndpointType.WebApplication];

                        if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) &&
                            !string.IsNullOrEmpty(publicUrl)
                            )
                        {
                            service.ConnectionData.PublicUrl = publicUrl;
                        }
                    }
                }

                if (!idOrganization.HasValue)
                {
                    if (whoAmIResponse == null)
                    {
                        whoAmIResponse = await service.ExecuteAsync <WhoAmIResponse>(new WhoAmIRequest());
                    }

                    idOrganization = whoAmIResponse.OrganizationId;
                }

                service.ConnectionData.DefaultLanguage        = string.Empty;
                service.ConnectionData.BaseCurrency           = string.Empty;
                service.ConnectionData.DefaultLanguage        = string.Empty;
                service.ConnectionData.InstalledLanguagePacks = string.Empty;

                if (idOrganization.HasValue)
                {
                    var organization = await service
                                       .RetrieveAsync <Organization>(Organization.EntityLogicalName, idOrganization.Value, new ColumnSet(Organization.Schema.Attributes.languagecode, Organization.Schema.Attributes.basecurrencyid))
                    ;

                    if (organization.BaseCurrencyId != null)
                    {
                        service.ConnectionData.BaseCurrency = organization.BaseCurrencyId.Name;
                    }

                    var request  = new RetrieveInstalledLanguagePacksRequest();
                    var response = await service.ExecuteAsync <RetrieveInstalledLanguagePacksResponse>(request);

                    var rep = new EntityMetadataRepository(service);

                    var isEntityExists = rep.IsEntityExists(LanguageLocale.EntityLogicalName);

                    if (isEntityExists)
                    {
                        var repository = new LanguageLocaleRepository(service);

                        if (organization.LanguageCode.HasValue)
                        {
                            var lang = (await repository.GetListAsync(organization.LanguageCode.Value)).FirstOrDefault();

                            if (lang != null)
                            {
                                service.ConnectionData.DefaultLanguage = lang.ToString();
                            }
                            else
                            {
                                service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value);
                            }
                        }

                        if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any())
                        {
                            var list = await repository.GetListAsync(response.RetrieveInstalledLanguagePacks);

                            service.ConnectionData.InstalledLanguagePacks = string.Join(",", list.OrderBy(s => s.LocaleId.Value, LocaleComparer.Comparer).Select(l => l.ToString()));
                        }
                    }
                    else
                    {
                        if (organization.LanguageCode.HasValue)
                        {
                            service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value);
                        }

                        if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any())
                        {
                            service.ConnectionData.InstalledLanguagePacks = string.Join(",", response.RetrieveInstalledLanguagePacks.OrderBy(s => s, LocaleComparer.Comparer).Select(l => LanguageLocale.GetLocaleName(l)));
                        }
                    }
                }

                if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) &&
                    !string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl)
                    )
                {
                    var orgUrl = service.ConnectionData.OrganizationUrl.TrimEnd('/');

                    if (orgUrl.EndsWith("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var lastIndex = orgUrl.LastIndexOf("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase);

                        var publicUrl = orgUrl.Substring(0, lastIndex + 1).TrimEnd('/');

                        service.ConnectionData.PublicUrl = publicUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(service.ConnectionData, ex);
            }
        }
        private async Task <string> GetDescriptionGroupByRequiredComponents(List <Dependency> list)
        {
            StringBuilder builder = new StringBuilder();
            string        format  = "Dependent components:";

            var groupsComponent = list
                                  .GroupBy(d => d.RequiredComponentType)
                                  .OrderBy(gr => gr.Key?.Value);

            foreach (var grComp in groupsComponent)
            {
                var groupsObject = grComp
                                   .GroupBy(d => new { RequiredComponentType = d.RequiredComponentType.Value, RequiredComponentObjectId = d.RequiredComponentObjectId.Value });

                Dictionary <string, string> dict = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

                foreach (var grObj in groupsObject)
                {
                    try
                    {
                        var entityDesc = _descriptor.GetComponentDescription(grObj.Key.RequiredComponentType, grObj.Key.RequiredComponentObjectId);

                        var grList = grObj.Select(d => d.DependentToSolutionComponent()).ToList();

                        var collectionDesc = await _descriptor.GetSolutionComponentsDescriptionAsync(grList);

                        if (!string.IsNullOrEmpty(collectionDesc))
                        {
                            dict.Add(entityDesc, collectionDesc);
                        }
                    }
                    catch (Exception ex)
                    {
                        builder.AppendLine().AppendLine("Exception");
                        builder.AppendLine().AppendLine(DTEHelper.GetExceptionDescription(ex)).AppendLine();

                        DTEHelper.WriteExceptionToOutput(_descriptor.ConnectionData, ex);

#if DEBUG
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            System.Diagnostics.Debugger.Break();
                        }
#endif
                    }
                }

                foreach (var entityDesc in dict.Keys.OrderBy(s => s))
                {
                    if (builder.Length > 0)
                    {
                        builder
                        .AppendLine()
                        .AppendLine(new string('-', 100))
                        .AppendLine();
                    }

                    builder.AppendLine(entityDesc);
                    builder.AppendLine(format);
                    builder.AppendLine(dict[entityDesc]);
                }
            }

            return(builder.ToString());
        }