Beispiel #1
0
        public static bool Execute(
            string[] seeds,
            string referenceAssembly,
            string[] compileFiles,
            string defineConstants,
            string outputSourcePath,
            TaskLoggingHelper logger,
            bool ignoreMissingTypes         = false,
            string[] ignoreMissingTypesList = null,
            string[] OmitTypes = null,
            ITaskItem[] seedTypePreferencesList = null)
        {
            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesList, logger);

            using (var contractHost = new HostEnvironment(nameTable, internFactory))
                using (var seedHost = new HostEnvironment(nameTable, internFactory))
                {
                    IAssembly            contractAssembly = contractHost.LoadAssembly(referenceAssembly);
                    IEnumerable <string> referenceTypes   = GetPublicVisibleTypes(contractAssembly);

                    if (OmitTypes != null)
                    {
                        referenceTypes = referenceTypes.Where(type => !OmitTypes.Contains(type));
                    }

                    IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();
                    var         seedTypes      = GenerateTypeTable(seedAssemblies);

                    var sourceGenerator = new SourceGenerator(referenceTypes, seedTypes, seedTypePreferences, outputSourcePath, ignoreMissingTypesList, logger);
                    return(sourceGenerator.GenerateSource(compileFiles, ParseDefineConstants(defineConstants), ignoreMissingTypes));
                }
        }
Beispiel #2
0
        /// <summary>
        /// Caching GenericTypeInstanceRefernece objects based on interned key, avoiding GenericTypeInstance.InitializeIfNecessary expense
        /// </summary>
        public IGenericTypeInstanceReference GetOrMakeGenericTypeInstanceReference(INamedTypeReference genericTypeReference, IEnumerable <ITypeReference> genericArguments)
        {
            InternFactory factory = m_factory as InternFactory;

            if (factory != null && !factory.InternKeysAreReliablyUnique)
            {
                return(new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true));
            }

            uint key = m_factory.GetGenericTypeInstanceReferenceInternedKey(genericTypeReference, genericArguments);

            IGenericTypeInstanceReference type = null;

            object value;

            if (m_objects.TryGetValue(key, out value))
            {
                type = value as IGenericTypeInstanceReference;

                if (type != null && !SequenceEquals(genericArguments, type.GenericArguments))
                {
                    // We can currently get problematic cache hits here for different objects representing the same type.
                    // e.g. SignatureGenericTypeParameter from ref signature can substitute for GenericTypeParameter
                    // from def signature. This breaks assumptions that were there prior to the sharing of generic
                    // type instances that was introduced by the caching intern factory. In that particular case, it breaks
                    // the subsequent specialization of the type parameter.
                    //
                    // We should investigate how to share more in these cases, but in the meantime, we conservatively
                    // only use an existing instantiation if the genericArguments are identical object references and
                    // otherwise force a cache miss here.
                    type = null;
                }
            }

            if (type == null)
            {
                type           = new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true);
                m_objects[key] = type;
            }

            return(type);
        }
Beispiel #3
0
        public static void Main(string[] args)
        {
            string         seeds                          = null;
            string         contracts                      = null;
            string         facadePath                     = null;
            Version        assemblyFileVersion            = null;
            bool           clearBuildAndRevision          = false;
            bool           ignoreMissingTypes             = false;
            bool           ignoreBuildAndRevisionMismatch = false;
            bool           buildDesignTimeFacades         = false;
            string         inclusionContracts             = null;
            ErrorTreatment seedLoadErrorTreatment         = ErrorTreatment.Default;
            ErrorTreatment contractLoadErrorTreatment     = ErrorTreatment.Default;

            string[] seedTypePreferencesUnsplit = null;
            bool     forceZeroVersionSeeds      = false;
            bool     producePdb = true;
            string   partialFacadeAssemblyPath = null;

            bool parsingSucceeded = CommandLineParser.ParseForConsoleApplication((parser) =>
            {
                parser.DefineQualifier("facadePath", ref facadePath, "Path to output the facades.");
                parser.DefineQualifier("seeds", ref seeds, "Path to the seed assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineQualifier("contracts", ref contracts, "Path to the contract assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("assemblyFileVersion", ref assemblyFileVersion, "Override the AssemblyFileVersion attribute from the contract with the given version for the generated facade.");
                parser.DefineOptionalQualifier("clearBuildAndRevision", ref clearBuildAndRevision, "Generate facade assembly version x.y.0.0 for contract version x.y.z.w");
                parser.DefineOptionalQualifier("ignoreBuildAndRevisionMismatch", ref ignoreBuildAndRevisionMismatch, "Ignore a mismatch in revision and build for partial facade.");
                parser.DefineOptionalQualifier("ignoreMissingTypes", ref ignoreMissingTypes, "Ignore types that cannot be found in the seed assemblies. This is not recommended but is sometimes helpful while hacking around or trying to produce partial facades.");
                parser.DefineOptionalQualifier("designTime", ref buildDesignTimeFacades, "Enable design-time facade generation (marks facades with reference assembly flag and attribute).");
                parser.DefineOptionalQualifier("include", ref inclusionContracts, "Add types from these contracts to the facades. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("seedError", ref seedLoadErrorTreatment, "Error handling for seed assembly load failure.");
                parser.DefineOptionalQualifier("contractError", ref seedLoadErrorTreatment, "Error handling for contract assembly load failure.");
                parser.DefineOptionalQualifier("preferSeedType", ref seedTypePreferencesUnsplit, "Set which seed assembly to choose for a given type when it is defined in more than one assembly. Format: FullTypeName=PreferredSeedAssemblyName");
                parser.DefineOptionalQualifier("forceZeroVersionSeeds", ref forceZeroVersionSeeds, "Forces all seed assembly versions to 0.0.0.0, regardless of their true version.");
                parser.DefineOptionalQualifier("partialFacadeAssemblyPath", ref partialFacadeAssemblyPath, "Specifies the path to a single partial facade assembly, into which appropriate type forwards will be added to satisfy the given contract. If this option is specified, only a single partial assembly and a single contract may be given.");
                parser.DefineOptionalQualifier("producePdb", ref producePdb, "Specifices if a PDB file should be produced for the resulting partial facade.");
            }, args);

            if (!parsingSucceeded)
            {
                return;
            }

            CommandLineTraceHandler.Enable();

            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    continue;
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
            }
        }
Beispiel #4
0
        public static bool Execute(
            string seeds,
            string contracts,
            string facadePath,
            Version assemblyFileVersion               = null,
            bool clearBuildAndRevision                = false,
            bool ignoreMissingTypes                   = false,
            bool ignoreBuildAndRevisionMismatch       = false,
            bool buildDesignTimeFacades               = false,
            string inclusionContracts                 = null,
            ErrorTreatment seedLoadErrorTreatment     = ErrorTreatment.Default,
            ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
            string[] seedTypePreferencesUnsplit       = null,
            bool forceZeroVersionSeeds                = false,
            bool producePdb = true,
            string partialFacadeAssemblyPath = null)
        {
            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            if (filledPartialFacade == null)
                            {
                                Trace.TraceError("Errors were encountered while generating the facade.");
                                return(false);
                            }

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    return(false);
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }

                return(true);
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
                return(false);
            }
        }
Beispiel #5
0
        private static void Main(string[] args)
        {
            EmployeeFactory        = ServiceLocator.Get <EmployeeFactory>();
            ProjectFactory         = ServiceLocator.Get <ProjectFactory>();
            InternFactory          = ServiceLocator.Get <InternFactory>();
            CompanyFactory         = ServiceLocator.Get <CompanyFactory>();
            ContractorFactory      = ServiceLocator.Get <ContractorFactory>();
            PersonFactory          = ServiceLocator.Get <PersonFactory>();
            PersonRepository       = ServiceLocator.Get <IPersonRepository>();
            PersonSkillsRepository = ServiceLocator.Get <IPersonSkillsRepository>();
            CompanyRepository      = ServiceLocator.Get <ICompanyRepository>();
            TaskFactory            = ServiceLocator.Get <TaskFactory>();

            try
            {
                Logger.Logger.AddToLog("----Begining of the program-----");

                PopulatingDb();

                //PersonRepository.UpdatePerson(15016, "White", "Dude", "1999-1-31");
                //PersonRepository.UpdatePerson(19022, lname: "White", fname: "Dude");
                //PersonRepository.UpdatePerson(15015, bdate: "2005-12-12");
                //PersonRepository.DeletePerson(15019);

                //ShowAllPersons();
                //ShowPersonSkillsByFirstname("Person 1");
                //ShowPersonByTaskname("Task 1");
                //ShowPersonLastnameById(3003);
                // ShowEmployeeDetails1();
                //ShowPersonRowsHavingMoreThanOneSkill();
                //ShowAllPersonsWithSkills();
                //ShowAllPersonsFirstAndLastNames_ProjectionList();
                //ShowPersonByLNameOrByFName;

                Console.ReadLine();

////Proxy
//                var appointment = new DirectorProxy(intern, director);
//                appointment.NewAppontment(DateTime.Today);
//                var appointment2 = new DirectorProxy(contractor, director);
//                appointment2.NewAppontment(DateTime.Today);
//                Console.ReadLine();

////observer
//                var hr = new HumanResources();
//                ProjectFactory.Subscribe(director);
//                ProjectFactory.Subscribe(hr);
//                ProjectFactory.CreateProject(1, "Rufus", "Making first project");
//                Console.ReadLine();

//                //TDD
//                var internlist = new List<Intern>();
//                internlist.Add(intern);
//                internlist.Add(intern2);
//                var hiredList = hr.Hire(internlist);
            }
            catch (InternValidationException exc1)
            {
                Console.WriteLine("{1} = {0}", exc1.Message, exc1.PersonName);
                Console.ReadLine();
                //throw;
            }
            catch (ArgumentOutOfRangeException exc2)
            {
                Console.WriteLine(" = {0}", exc2.Message);
                Console.ReadLine();
                //throw;
            }
            catch (NullReferenceException exc3)
            {
                Console.WriteLine(" = {0}", exc3.Message);
                Console.ReadLine();
                //throw;
            }
            finally
            {
                Logger.Logger.AddToLog("-------The End-------");
                Debug.WriteLine("Debug: Good luck!");
            }
        }