Ejemplo n.º 1
0
        private static MicrosoftDataEntityDesignDocData GetDocData(EditingContext editingContext)
        {
            Debug.Assert(editingContext != null, "editingContext != null");

            var artifactService = editingContext.GetEFArtifactService();

            return((MicrosoftDataEntityDesignDocData)VSHelpers.GetDocData(ServiceProvider, artifactService.Artifact.Uri.LocalPath));
        }
Ejemplo n.º 2
0
        // <summary>
        //     This will do analysis to determine if a document should be opened
        //     only in the XmlEditor.
        // </summary>
        internal override void DetermineIfArtifactIsDesignerSafe()
        {
            VsUtils.EnsureProvider(this);

            base.DetermineIfArtifactIsDesignerSafe();
            //
            // TODO:  we need to figure out how to deal with errors from the wizard.
            //        when we clear the error list below, we lose errors that we put into the error
            //        list when running the wizard.
            //

            //
            // Now update the VS error list with all of the errors we want to display, which are now in the EFArtifactSet.
            //
            var errorInfos = ArtifactSet.GetAllErrors();

            if (errorInfos.Count > 0)
            {
                var currentProject = VSHelpers.GetProjectForDocument(Uri.LocalPath, PackageManager.Package);
                if (currentProject != null)
                {
                    var hierarchy = VsUtils.GetVsHierarchy(currentProject, Services.ServiceProvider);
                    if (hierarchy != null)
                    {
                        var fileFinder = new VSFileFinder(Uri.LocalPath);
                        fileFinder.FindInProject(hierarchy);

                        Debug.Assert(fileFinder.MatchingFiles.Count <= 1, "Unexpected count of matching files in project");

                        // if the EDMX file is not part of the project.
                        if (fileFinder.MatchingFiles.Count == 0)
                        {
                            var docData = VSHelpers.GetDocData(PackageManager.Package, Uri.LocalPath) as IEntityDesignDocData;
                            ErrorListHelper.AddErrorInfosToErrorList(errorInfos, docData.Hierarchy, docData.ItemId);
                        }
                        else
                        {
                            foreach (var vsFileInfo in fileFinder.MatchingFiles)
                            {
                                if (vsFileInfo.Hierarchy == VsUtils.GetVsHierarchy(currentProject, Services.ServiceProvider))
                                {
                                    var errorList = ErrorListHelper.GetSingleDocErrorList(vsFileInfo.Hierarchy, vsFileInfo.ItemId);
                                    if (errorList != null)
                                    {
                                        errorList.Clear();
                                        ErrorListHelper.AddErrorInfosToErrorList(errorInfos, vsFileInfo.Hierarchy, vsFileInfo.ItemId);
                                    }
                                    else
                                    {
                                        Debug.Fail("errorList is null!");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        private void RefactorRenameTest(string projectName, Action <EntityDesignArtifact, CommandProcessorContext, object> test)
        {
            var modelEdmxFilePath = Path.Combine(TestContext.DeploymentDirectory, @"TestData\Model\v3\PubSimple.edmx");
            var dte             = VsIdeTestHostContext.Dte;
            var serviceProvider = VsIdeTestHostContext.ServiceProvider;

            UITestRunner.Execute(
                () =>
            {
                EntityDesignArtifact entityDesignArtifact = null;
                try
                {
                    var project = dte.CreateProject(
                        TestContext.TestRunDirectory,
                        projectName,
                        DteExtensions.ProjectKind.Executable,
                        DteExtensions.ProjectLanguage.CSharp);

                    var projectItem = dte.AddExistingItem(new FileInfo(modelEdmxFilePath).FullName, project);
                    dte.OpenFile(projectItem.FileNames[0]);
                    entityDesignArtifact =
                        (EntityDesignArtifact) new EFArtifactHelper(EFArtifactHelper.GetEntityDesignModelManager(serviceProvider))
                        .GetNewOrExistingArtifact(TestUtils.FileName2Uri(projectItem.FileNames[0]));

                    var editingContext =
                        _package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(entityDesignArtifact.Uri);
                    var cpc = new CommandProcessorContext(
                        editingContext, "DiagramTest" + projectName, "DiagramTestTxn" + projectName, entityDesignArtifact);

                    var programDocData = VSHelpers.GetDocData(
                        serviceProvider, Path.Combine(Path.GetDirectoryName(project.FullName), "Program.cs"));
                    Debug.Assert(programDocData != null, "Could not get DocData for program file");

                    var textLines = VSHelpers.GetVsTextLinesFromDocData(programDocData);
                    Debug.Assert(textLines != null, "Could not get VsTextLines for program DocData");

                    VsUtils.SetTextForVsTextLines(textLines, string.Format(PubSimpleProgramText, projectName));
                    test(entityDesignArtifact, cpc, programDocData);
                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(ex.ToString());
                    throw;
                }
                finally
                {
                    if (entityDesignArtifact != null)
                    {
                        entityDesignArtifact.Dispose();
                    }

                    dte.CloseSolution(false);
                }
            });
        }
Ejemplo n.º 4
0
        internal override EntityDesignerViewModel LoadModel(
            SerializationResult serializationResult, Partition partition, string fileName, ISchemaResolver schemaResolver,
            ValidationController validationController, ISerializerLocator serializerLocator)
        {
            var docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData;

            docData.CreateAndLoadBuffer();

            EntityDesignerViewModel evm = null;

            var serializationContext = new SerializationContext(GetDirectory(partition.Store), fileName, serializationResult);
            var transactionContext   = new TransactionContext();

            transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext);

            using (var t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileName, true, transactionContext))
            {
                var uri     = Tools.XmlDesignerBase.Base.Util.Utils.FileName2Uri(fileName);
                var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(uri);
                evm =
                    ModelTranslatorContextItem.GetEntityModelTranslator(context).TranslateModelToDslModel(null, partition) as
                    EntityDesignerViewModel;

                if (evm == null)
                {
                    serializationResult.Failed = true;
                }
                else
                {
                    if (t.IsActive)
                    {
                        t.Commit();
                    }
                }
            }

            // Validate imported model
            if (!serializationResult.Failed &&
                (validationController != null))
            {
                validationController.Validate(partition, ValidationCategories.Load);
            }
            return(evm);
        }
Ejemplo n.º 5
0
        private bool IsDependentTTFile(VSFileFinder.VSFileInfo fileInfo)
        {
            string contents = null;
            var    docData  = VSHelpers.GetDocData(ServiceProvider, fileInfo.Path);

            if (docData == null)
            {
                // load file from disk
                try
                {
                    contents = File.ReadAllText(fileInfo.Path);
                }
                catch (Exception e)
                {
                    var errorMsg = String.Format(CultureInfo.CurrentCulture, Resources.ErrorOccurredLoadingFile, fileInfo.Path, e.Message);
                    VsUtils.LogOutputWindowPaneMessage(VSHelpers.GetProject(Hierarchy), errorMsg);
                    contents = null;
                }
            }
            else
            {
                // read buffer contents
                var tl = VSHelpers.GetVsTextLinesFromDocData(docData);
                Debug.Assert(tl != null, "Couldn't get text lines from doc data for .tt file");
                if (tl != null)
                {
                    contents = VSHelpers.GetTextFromVsTextLines(tl);
                }
            }

            //
            // BUGBUG 592011:  replace this with something smarter.  Use T4 parser to identify all input files.
            //
            if (contents != null)
            {
                var fi = new FileInfo(FileName);
                return(contents.Contains(fi.Name));
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 6
0
        internal override void SaveModelAndDiagram(
            SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string modelFileName, EntityDesignerDiagram diagram,
            string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
        {
            // only save the model
            base.SaveModel(serializationResult, modelRoot, modelFileName, encoding, writeOptionalPropertiesWithDefaultValue);

            if (!serializationResult.Failed)
            {
                // flip our dirty bit (as long as we aren't trying to save the auto-recovery backup file)
                var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext);
                Debug.Assert(artifact != null, "Failed to get a valid EFArtifact from the context");

                IEntityDesignDocData docData = null;
                var fileName = String.Empty;
                if (artifact != null)
                {
                    fileName = artifact.Uri.LocalPath;
                }

                docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData;
                Debug.Assert(docData != null, "Couldn't locate our DocData");
                if (artifact != null &&
                    docData != null &&
                    !string.Equals(docData.BackupFileName, modelFileName, StringComparison.OrdinalIgnoreCase))
                {
                    artifact.IsDirty = false;
                }

                // SaveDiagram file if the file exists
                // TODO: What happened if saving diagram file failed? Should we rollback the model file?
                var diagramDocData =
                    VSHelpers.GetDocData(PackageManager.Package, fileName + EntityDesignArtifact.ExtensionDiagram) as XmlModelDocData;
                if (diagramDocData != null)
                {
                    int saveIsCancelled;
                    diagramDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out diagramFileName, out saveIsCancelled);
                }
            }
        }
Ejemplo n.º 7
0
        internal override MemoryStream InternalSaveModel(
            SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string fileName, Encoding encoding,
            bool writeOptionalPropertiesWithDefaultValue)
        {
            IEntityDesignDocData docData = null;
            MemoryStream         stream  = null;

            Debug.Assert(modelRoot.EditingContext != null, "Designer model root has a null EditingContext");
            if (modelRoot.EditingContext != null)
            {
                // find our doc data; don't use the passed in fileName as this will be the new name
                // during a SaveAs operation
                var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext);
                if (artifact != null)
                {
                    docData = VSHelpers.GetDocData(PackageManager.Package, artifact.Uri.LocalPath) as IEntityDesignDocData;
                }

                Debug.Assert(docData != null, "Couldn't locate our DocData");
                if (docData != null)
                {
                    var text = docData.GetBufferTextForSaving();
                    if (!string.IsNullOrEmpty(text))
                    {
                        stream = FileUtils.StringToStream(text, encoding) as MemoryStream;
                    }
                }
            }

            // if we don't have a stream, then we couldn't serialize for some reason
            if (stream == null)
            {
                serializationResult.Failed = true;
            }

            return(stream);
        }
        public void RunFinished()
        {
            if (_edmxItem == null)
            {
                if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModelCodeFirst ||
                    _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase)
                {
                    Debug.Assert(
                        _modelBuilderSettings.ModelBuilderEngine == null ^
                        _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase,
                        "Model should be null for Empty Model and not null CodeFirst from database");

                    AddCodeFirstItems();
                }

                return;
            }

            var fileExtension = Path.GetExtension(_edmxItem.FileNames[1]);

            Debug.Assert(
                _modelBuilderSettings.Project.Equals(_edmxItem.ContainingProject),
                "ActiveSolutionProject is not the EDMX file's containing project");
            using (new VsUtils.HourglassHelper())
            {
                var    package = PackageManager.Package;
                Window window  = null;

                try
                {
                    ConfigFileHelper.UpdateConfig(_modelBuilderSettings);

                    // save the model generated in the wizard UI.
                    if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                    {
                        var writingModelWatch = new Stopwatch();
                        writingModelWatch.Start();
                        var modelEdmx = ((EdmxModelBuilderEngine)_modelBuilderSettings.ModelBuilderEngine).Edmx;

                        if (!string.Equals(fileExtension, EntityDesignArtifact.ExtensionEdmx, StringComparison.OrdinalIgnoreCase))
                        {
                            // convert the file if this isn't EDMX
                            var edmxFileInfo      = new FileInfo(_edmxItem.FileNames[1]);
                            var conversionContext = new ModelConversionContextImpl(
                                _edmxItem.ContainingProject,
                                _edmxItem,
                                edmxFileInfo,
                                _modelBuilderSettings.TargetSchemaVersion,
                                modelEdmx);
                            VSArtifact.DispatchToConversionExtensions(
                                EscherExtensionPointManager.LoadModelConversionExtensions(),
                                fileExtension,
                                conversionContext,
                                loading: false);
                            File.WriteAllText(edmxFileInfo.FullName, conversionContext.OriginalDocument);
                        }
                        else
                        {
                            // we need to use XmlWriter to output so that XmlDeclaration is preserved.
                            using (var modelWriter = XmlWriter.Create(
                                       _edmxItem.FileNames[1],
                                       new XmlWriterSettings {
                                Indent = true
                            }))
                            {
                                modelEdmx.WriteTo(modelWriter);
                            }
                        }

                        writingModelWatch.Stop();
                        VsUtils.LogOutputWindowPaneMessage(
                            _edmxItem.ContainingProject,
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Properties.Resources.WritingModelTimeMsg,
                                writingModelWatch.Elapsed));
                    }

                    // set the ItemType for the generated .edmx file
                    if (_modelBuilderSettings.VSApplicationType != VisualStudioProjectSystem.Website &&
                        string.Equals(
                            fileExtension,
                            EntityDesignArtifact.ExtensionEdmx,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        _edmxItem.Properties.Item(ItemTypePropertyName).Value = EntityDeployBuildActionName;
                    }

                    // now open created file in VS using default viewer
                    window = _edmxItem.Open(Constants.vsViewKindPrimary);
                    Debug.Assert(window != null, "Unable to get window for created edmx file");
                }
                finally
                {
                    package.ModelGenErrorCache.RemoveErrors(_edmxItem.FileNames[1]);
                }

                // Construct an editing context and make all final edits that require the file is opened.
                var edmxFileUri    = new Uri(_edmxItem.FileNames[1]);
                var designArtifact =
                    package.ModelManager.GetNewOrExistingArtifact(
                        edmxFileUri, new VSXmlModelProvider(package, package)) as EntityDesignArtifact;
                Debug.Assert(
                    designArtifact != null,
                    "artifact should be of type EntityDesignArtifact but received type " + designArtifact.GetType().FullName);
                Debug.Assert(
                    designArtifact.StorageModel != null, "designArtifact StorageModel cannot be null for Uri " + edmxFileUri.AbsolutePath);
                Debug.Assert(
                    designArtifact.ConceptualModel != null,
                    "designArtifact ConceptualModel cannot be null for Uri " + edmxFileUri.AbsolutePath);

                if (designArtifact != null &&
                    designArtifact.StorageModel != null &&
                    designArtifact.ConceptualModel != null)
                {
                    var designerSafeBeforeAddingTemplates = designArtifact.IsDesignerSafe;

                    var editingContext =
                        package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(designArtifact.Uri);
                    Debug.Assert(editingContext != null, "Null EditingContext for artifact " + edmxFileUri.AbsolutePath);
                    if (editingContext != null)
                    {
                        // Add DbContext templates when generation is GenerateFromDatabase. (connection is configured)
                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                        {
                            new DbContextCodeGenerator().AddDbContextTemplates(
                                _edmxItem,
                                _modelBuilderSettings.UseLegacyProvider);
                        }

                        // Create FunctionImports for every new Function
                        var cp = PrepareCommandsAndIntegrityChecks(_modelBuilderSettings, editingContext, designArtifact);

                        if (DbContextCodeGenerator.TemplateSupported(_edmxItem.ContainingProject, package))
                        {
                            // Add command setting CodeGenerationStrategy to "None" for EmptyModel. (connection is not yet configured)
                            // NOTE: For EmptyModel, the templates will be added after the connection is configured.
                            //       (i.e. during "Generate Database from Model" or "Refresh from Database")
                            if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModel)
                            {
                                var cmd = EdmUtils.SetCodeGenStrategyToNoneCommand(designArtifact);
                                if (cmd != null)
                                {
                                    if (cp == null)
                                    {
                                        var cpc = new CommandProcessorContext(
                                            editingContext,
                                            EfiTransactionOriginator.CreateNewModelId,
                                            Resources.Tx_SetCodeGenerationStrategy);
                                        cp = new CommandProcessor(cpc, cmd);
                                    }
                                    else
                                    {
                                        cp.EnqueueCommand(cmd);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Templates not supported, add reference to SDE. (.NET Framework 3.5)
                            VsUtils.AddProjectReference(_edmxItem.ContainingProject, "System.Data.Entity");
                        }

                        if (cp != null)
                        {
                            cp.Invoke();
                        }

                        // save the artifact to make it look as though updates were part of creation
                        _edmxItem.Save();

                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase &&
                            !designerSafeBeforeAddingTemplates)
                        {
                            // If the artifact became safe after adding references we need to reload it (this can happen
                            // on .NET Framework 4 where we would originally create a v3 edmx if the user selected EF6 -
                            // the artifact will be flagged as invalid since there is no runtime which could handle v3
                            // but after we added references to EF6 the artifacts becomes valid and need to be reloaded).
                            designArtifact.DetermineIfArtifactIsDesignerSafe();
                            if (designArtifact.IsDesignerSafe)
                            {
                                Debug.Assert(!designArtifact.IsDirty, "Reloading dirty artifact - changes will be lost.");

                                // Since the artifact was originally not valid we did not create the diagram for it.
                                // Using ReloadDocData will cause the diagram to be recreated. Note we don't need to
                                // reload the artifact itself since it has not changed.
                                ((DocData)
                                 VSHelpers.GetDocData(package, designArtifact.Uri.LocalPath)).ReloadDocData(0);
                            }
                        }
                    }

                    if (window != null)
                    {
                        window.Activate();
                    }
                }
            }
        }
Ejemplo n.º 9
0
        internal override bool IsXmlValid()
        {
            // If there is a VSXmlModelProvider, we should be able to find a docdata for it.
            // In any other case, it doesn't matter whether there is document data or not.
            var docData = VSHelpers.GetDocData(PackageManager.Package, Uri.LocalPath);

            Debug.Assert(
                !(XmlModelProvider is VSXmlModelProvider) || docData != null, "Using a VSXmlModelProvider but docData is null for Artifact!");

            try
            {
                XmlDocument xmldoc;
                if (docData != null)
                {
                    var textLines = VSHelpers.GetVsTextLinesFromDocData(docData);
                    Debug.Assert(textLines != null, "Failed to get IVSTextLines from docdata");

                    xmldoc = EdmUtils.SafeLoadXmlFromString(VSHelpers.GetTextFromVsTextLines(textLines));
                }
                else
                {
                    // If there is no docdata then attempt to create the XmlDocument from the internal
                    // XLinq tree in the artifact
                    xmldoc = new XmlDocument();
                    xmldoc.Load(XDocument.CreateReader());
                }
                // For the most part, the Edmx schema version of an artifact should be in sync with the schema version
                // that is compatible with the project's target framework; except when the user adds an existing edmx to a project (the version could be different).
                // For all cases, we always want to validate using the XSD's version that matches the artifact's version.
                var documentSchemaVersion = base.SchemaVersion;
                Debug.Assert(
                    EntityFrameworkVersion.IsValidVersion(documentSchemaVersion),
                    "The EF Schema Version is not valid. Value:"
                    + (documentSchemaVersion != null ? documentSchemaVersion.ToString() : "null"));

                // does the XML parse? If not, the load call below will throw
                if (EntityFrameworkVersion.IsValidVersion(documentSchemaVersion))
                {
                    var nsMgr = SchemaManager.GetEdmxNamespaceManager(xmldoc.NameTable, documentSchemaVersion);
                    // Do XSD validation on the document.
                    xmldoc.Schemas = EscherAttributeContentValidator.GetInstance(documentSchemaVersion).EdmxSchemaSet;
                    var svec = new SchemaValidationErrorCollector();

                    // remove runtime specific lines
                    // find the ConceptualModel Schema node
                    RemoveRunTimeNode(xmldoc, "/edmx:Edmx/edmx:Configurations", nsMgr);
                    RemoveRunTimeNode(xmldoc, "/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels", nsMgr);
                    RemoveRunTimeNode(xmldoc, "/edmx:Edmx/edmx:Runtime/edmx:StorageModels", nsMgr);
                    RemoveRunTimeNode(xmldoc, "/edmx:Edmx/edmx:Runtime/edmx:Mappings", nsMgr);

                    xmldoc.Validate(svec.ValidationCallBack);

                    return(svec.ErrorCount == 0);
                }
            }
            catch
            {
            }

            return(false);
        }
        internal static void NavigateTo(EFObject efobject)
        {
            if (efobject.RuntimeModelRoot() == null)
            {
                // nothing to navigate to, so just return;
                return;
            }

            if (efobject.RuntimeModelRoot() is StorageEntityModel)
            {
                // s-space object, so just return;
                return;
            }

            var selectionService = Services.DslMonitorSelectionService;

            Debug.Assert(selectionService != null, "Could not retrieve IMonitorSelectionService from Escher package.");
            var foundDSLElementMatchInDiagram = false;

            if (selectionService != null)
            {
                var singleDiagramDocView = selectionService.CurrentDocumentView as SingleDiagramDocView;

                if (singleDiagramDocView != null)
                {
                    foundDSLElementMatchInDiagram = NavigateToDSLNodeInDiagram(
                        singleDiagramDocView.Diagram as EntityDesignerDiagram, efobject);
                    if (foundDSLElementMatchInDiagram)
                    {
                        // The code below is added to ensure that the right doc-view is shown and activated.
                        singleDiagramDocView.Frame.Show();
                        return;
                    }
                }
            }

            // Retrieves the doc data for the efobject.
            var docdata = VSHelpers.GetDocData(Services.ServiceProvider, efobject.Uri.LocalPath) as ModelingDocData;

            Debug.Assert(docdata != null, "Could not find get doc data for artifact with URI:" + efobject.Uri.LocalPath);
            if (docdata != null)
            {
                foreach (var docView in docdata.DocViews)
                {
                    var singleDiagramDocView = docView as SingleDiagramDocView;
                    Debug.Assert(
                        singleDiagramDocView != null,
                        "Why the doc view is not type of SingleDiagramDocView? Actual type:" + docView.GetType().Name);
                    if (docView != null)
                    {
                        foundDSLElementMatchInDiagram = NavigateToDSLNodeInDiagram(
                            singleDiagramDocView.Diagram as EntityDesignerDiagram, efobject);
                        if (foundDSLElementMatchInDiagram)
                        {
                            // The code below is added to ensure that the right doc-view is shown and activated.
                            singleDiagramDocView.Frame.Show();
                            return;
                        }
                    }
                }
            }
        }