src/Misc/EFTools/EntityDesign/VisualStudio/SingleFileGenerator/EntityModelCodeGenerator.cs
/// <summary>
///     Calls the CodeGen API to generate the code file from the CSDL file
/// </summary>
/// <param name="inputFileName">The full path of the CSDL file; this is fed in from the ProjectItem</param>
/// <param name="inputFileContent">The contents of the CSDL file - this should always be used so that we can gen off of in memory documents</param>
/// <param name="defaultNamespace">The default namespace.</param>
/// <returns>null implies error, else the contents of the file</returns>
Calls the CodeGen API to generate the code file from the CSDL file
Calls the CodeGen API to generate the code file from the CSDL file
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsErrorList.BringToFront")]
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent, string defaultNamespace)
        {
            byte[] generatedBytes = null;
            var generatedCode = string.Empty;
            var projectItem = SiteServiceProvider.GetService(typeof(ProjectItem)) as ProjectItem;
            if (projectItem != null
                && IsAfterARename(projectItem))
            {
                var generatedCodeFile = GetCodeGenFilePathFromInputFile(inputFileName);
                if (File.Exists(generatedCodeFile))
                {
                    return GetBytesOfExistingCodeGenFile(generatedCodeFile);
                }
            }
            var languageOption = LanguageOption.GenerateCSharpCode;
            try
            {
                var defaultExtension = DefaultExtensionString.ToUpperInvariant();
                if (defaultExtension.Contains(".CS"))
                {
                    languageOption = LanguageOption.GenerateCSharpCode;
                }
                else if (defaultExtension.Contains(".VB"))
                {
                    languageOption = LanguageOption.GenerateVBCode;
                }
                else
                {
                    throw new NotSupportedException(Strings.UnknownLanguage);
                }
            }
            catch (Exception e)
            {
                string commentString;
                if (languageOption == LanguageOption.GenerateVBCode)
                {
                    commentString = "' " + e.Message;
                }
                else
                {
                    commentString = "// " + e.Message;
                }
                generatedBytes = Encoding.UTF8.GetBytes(commentString);
                return generatedBytes;
            }
            try
            {
                PackageManager.LoadEDMPackage(SiteServiceProvider);
            }
            catch (Exception)
            {
                VsUtils.ShowErrorDialog(Resources.LoadOurPackageError);
                string commentString;
                if (languageOption == LanguageOption.GenerateVBCode)
                {
                    commentString = "' " + Resources.LoadOurPackageError;
                }
                else
                {
                    commentString = "// " + Resources.LoadOurPackageError;
                }
                generatedBytes = Encoding.UTF8.GetBytes(commentString);
                return generatedBytes;
            }
            if (InputFileHasContent(inputFileContent))
            {
                var projectItemUri = Utils.FileName2Uri(inputFileName);
                ModelManager modelManager = PackageManager.Package.ModelManager;
                ModelManager tempModelManager = null;
                try
                {
                    var artifact = modelManager.GetArtifact(projectItemUri);
                    if (artifact == null)
                    {
                        tempModelManager = new EntityDesignModelManager(new EFArtifactFactory(), new VSArtifactSetFactory());
                        artifact = tempModelManager.GetNewOrExistingArtifact(
                            projectItemUri, new StandaloneXmlModelProvider(PackageManager.Package));
                        Debug.Assert(artifact != null, "We should have created the artifact from the temporary model manager");
                        foreach (var codeGenArtifact in artifact.ArtifactSet.Artifacts)
                        {
                            codeGenArtifact.IsCodeGenArtifact = true;
                        }
                    }
                    var codeGenStrategy = ModelHelper.GetDesignerPropertyValueFromArtifact(
                        OptionsDesignerInfo.ElementName, OptionsDesignerInfo.AttributeCodeGenerationStrategy, artifact);
                    if (String.IsNullOrEmpty(codeGenStrategy)
                        || codeGenStrategy.Equals(Resources.Default))
                    {
                        var cModel = artifact.ConceptualModel();
                        if (cModel != null)
                        {
                            IList<EdmSchemaError> generatorErrors;
                            using (var output = new StringWriter(CultureInfo.InvariantCulture))
                            {
                                defaultNamespace = GetCodeNamespace(defaultNamespace, artifact);
                                generatorErrors =
                                    new LegacyCodeGenerationDriver(languageOption, artifact.SchemaVersion)
                                        .GenerateCode(artifact, defaultNamespace, output);
                                generatedCode = output.ToString();
                            }
                            ProcessErrors(generatorErrors, projectItemUri, artifact);
                            if (generatorErrors.Count > 0
                                || string.IsNullOrEmpty(generatedCode))
                            {
                                generatedCode = GetCodeGenerationErrorComment(languageOption, inputFileName);
                            }
                            generatedBytes = Utils.StringToBytes(generatedCode, Encoding.UTF8);
                        }
                    }
                    else
                    {
                        generatedCode = GetCodeGenerationDisabledComment(languageOption, inputFileName);
                        generatedBytes = Utils.StringToBytes(generatedCode, Encoding.UTF8);
                    }
                }
                catch (Exception e)
                {
                    GeneratorErrorCallback(false, 0, e.Message, 0, 0);
                    ErrorList.BringToFront();
                }
                finally
                {
                    if (tempModelManager != null)
                    {
                        tempModelManager.Dispose();
                        tempModelManager = null;
                    }
                }
            }
            return generatedBytes;
        }
[ SuppressMessage ( " " , " " , MessageId = " " ) ] [ SuppressMessage ( " " , " " ) ] [ SuppressMessage ( " " , " " ) ] [ SuppressMessage ( " " , " " ) ] protected override byte [ ] GenerateCode ( string inputFileName , string inputFileContent , string defaultNamespace ) { byte [ ] generatedBytes = null ; var generatedCode = string . Empty ; var projectItem = SiteServiceProvider . GetService ( typeof ( ProjectItem ) ) as ProjectItem ; if ( projectItem != null && IsAfterARename ( projectItem ) ) { var generatedCodeFile = GetCodeGenFilePathFromInputFile ( inputFileName ) ; if ( File . Exists ( generatedCodeFile ) ) { return GetBytesOfExistingCodeGenFile ( generatedCodeFile ) ; } } var languageOption = LanguageOption . GenerateCSharpCode ; try { var defaultExtension = DefaultExtensionString . ToUpperInvariant ( ) ; if ( defaultExtension . Contains ( " " ) ) { languageOption = LanguageOption . GenerateCSharpCode ; } else if ( defaultExtension . Contains ( " " ) ) { languageOption = LanguageOption . GenerateVBCode ; } else { throw new NotSupportedException ( Strings . UnknownLanguage ) ; } } catch ( Exception e ) { string commentString ; if ( languageOption == LanguageOption . GenerateVBCode ) { commentString = " " + e . Message ; } else { commentString = " " + e . Message ; } generatedBytes = Encoding . UTF8 . GetBytes ( commentString ) ; return generatedBytes ; } try { PackageManager . LoadEDMPackage ( SiteServiceProvider ) ; } catch ( Exception ) { VsUtils . ShowErrorDialog ( Resources . LoadOurPackageError ) ; string commentString ; if ( languageOption == LanguageOption . GenerateVBCode ) { commentString = " " + Resources . LoadOurPackageError ; } else { commentString = " " + Resources . LoadOurPackageError ; } generatedBytes = Encoding . UTF8 . GetBytes ( commentString ) ; return generatedBytes ; } if ( InputFileHasContent ( inputFileContent ) ) { var projectItemUri = Utils . FileName2Uri ( inputFileName ) ; ModelManager modelManager = PackageManager . Package . ModelManager ; ModelManager tempModelManager = null ; try { var artifact = modelManager . GetArtifact ( projectItemUri ) ; if ( artifact == null ) { tempModelManager = new EntityDesignModelManager ( new EFArtifactFactory ( ) , new VSArtifactSetFactory ( ) ) ; artifact = tempModelManager . GetNewOrExistingArtifact ( projectItemUri , new StandaloneXmlModelProvider ( PackageManager . Package ) ) ; Debug . Assert ( artifact != null , " " ) ; foreach ( var codeGenArtifact in artifact . ArtifactSet . Artifacts ) { codeGenArtifact . IsCodeGenArtifact = true ; } } var codeGenStrategy = ModelHelper . GetDesignerPropertyValueFromArtifact ( OptionsDesignerInfo . ElementName , OptionsDesignerInfo . AttributeCodeGenerationStrategy , artifact ) ; if ( String . IsNullOrEmpty ( codeGenStrategy ) || codeGenStrategy . Equals ( Resources . Default ) ) { var cModel = artifact . ConceptualModel ( ) ; if ( cModel != null ) { IList < EdmSchemaError > generatorErrors ; using ( var output = new StringWriter ( CultureInfo . InvariantCulture ) ) { defaultNamespace = GetCodeNamespace ( defaultNamespace , artifact ) ; generatorErrors = new LegacyCodeGenerationDriver ( languageOption , artifact . SchemaVersion ) . GenerateCode ( artifact , defaultNamespace , output ) ; generatedCode = output . ToString ( ) ; } ProcessErrors ( generatorErrors , projectItemUri , artifact ) ; if ( generatorErrors . Count > 0 || string . IsNullOrEmpty ( generatedCode ) ) { generatedCode = GetCodeGenerationErrorComment ( languageOption , inputFileName ) ; } generatedBytes = Utils . StringToBytes ( generatedCode , Encoding . UTF8 ) ; } } else { generatedCode = GetCodeGenerationDisabledComment ( languageOption , inputFileName ) ; generatedBytes = Utils . StringToBytes ( generatedCode , Encoding . UTF8 ) ; } } catch ( Exception e ) { GeneratorErrorCallback ( false , 0 , e . Message , 0 , 0 ) ; ErrorList . BringToFront ( ) ; } finally { if ( tempModelManager != null ) { tempModelManager . Dispose ( ) ; tempModelManager = null ; } } } return generatedBytes ; }
Calls the CodeGen API to generate the code file from the CSDL file
Calls the CodeGen API to generate the code file from the CSDL file
// Check if this is a rename operation here. The SFG gets called during a rename on website projects // and attempts to rollback the code-behind file if the SFG fails, but before the rename of the // code-behind file. We don't want to hose the existing code-behind file so we return back the bytes // of the previous code-behind file. // init Language // ensure that our package is loaded // It would be nice to add an error in the error list, but you need an IServiceProvider to do this // We use our package usually for this, but here, our pacakge failed to load.  Raise a message box // First check the ModelManager to see if the artifact was loaded by the designer or if it was persisted from an earlier code-gen attempt // Since we created the artifact purely for code-gen, we need to mark it as such so the designer knows not to re-use this // artifact later. // First check if the 'CodeGenerationStrategy' option is set to 'Default'.  // If there's no or empty value, we assume 'Default'. // navigate to the conceptual element // set up namespace to use for code-gen. defaultNamespace is computed by VS to account for // folder path in the project, custom tool namespace, and differences between C#, VB, and web-site projects. // generate code // TODO: pass on validation to our designer so that we validate the MSL and SSDL in addition to the CSDL // Insert new errors into the ErrorList window // We do not want to bring the error list to the front if there are code generation errors // since this could interrupt the editing of the model. // in case of errors generate a comment in the code which will indicate  // that the file failed to generate properly
null implies error, else the contents of the file
null implies error else the contents of the file
inputFileName
string
The full path of the CSDL file; this is fed in from the ProjectItem
The full path of the CSDL file ; this is fed in from the ProjectItem
inputFileContent
string
The contents of the CSDL file - this should always be used so that we can gen off of in memory documents
The contents of the CSDL file - this should always be used so that we can gen off of in memory documents
defaultNamespace
string
The default namespace.
The default namespace .