Esempio n. 1
0
        public PublishProfileEditorResources(PublishProfile publishProfile, CancellationToken cancellationToken)
        {
            this.selectedPublishProfile = publishProfile;
            this.selectedPublishProfile.PropertyChanged += this.PublishProfile_PropertyChanged;
            this.cancellationToken = cancellationToken;

            this.CloudTargets = CloudTargetManager.GetTargets();

            var publishProfiles = new List <PublishProfile>();

            var publishDirectory = Directory.GetParent(this.selectedPublishProfile.Path);

            if (Directory.Exists(publishDirectory.FullName))
            {
                foreach (var file in publishDirectory.GetFiles())
                {
                    if (file.Name.EndsWith(PushEnvironment.Extension, StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var             selectedProject = VsUtils.GetSelectedProject();
                            PushEnvironment env             = new PushEnvironment(selectedProject);
                            env.ProfileFilePath = file.FullName;
                            var profile = PublishProfile.Load(env);
                            publishProfiles.Add(profile);
                        }
                        catch (Exception ex)
                        {
                            // Ignore profiles that cannot be loaded.
                            Logger.Warning(string.Format(CultureInfo.InvariantCulture, "Cloud not load profile from {0}: {1}", file.Name, ex));
                        }
                    }
                }
            }

            this.PublishProfiles = publishProfiles.ToArray();
        }
        /// <summary>
        ///     DoWork event handler: Get table names in a background thread.
        ///     This method is called by background worker component on a different thread than the UI thread.
        ///     We use the ModelBuilderEngine to get table names to display
        /// </summary>
        private void bgWorkerPopulateTree_DoWork(object sender, DoWorkEventArgs args)
        {
            // This method will run on a thread other than the UI thread.
            // Be sure not to manipulate any Windows Forms controls created on the UI thread from this method.
            using (new VsUtils.HourglassHelper())
            {
                var result = new ICollection <EntityStoreSchemaFilterEntry> [3];
                try
                {
                    result[0] = _ssdlAggregator.GetTableFilterEntries(args);
                    if (args.Cancel)
                    {
                        return;
                    }

                    result[1] = _ssdlAggregator.GetViewFilterEntries(args);
                    if (args.Cancel)
                    {
                        return;
                    }

                    result[2] = _ssdlAggregator.GetFunctionFilterEntries(args);
                    if (args.Cancel)
                    {
                        return;
                    }
                }
                finally
                {
                    VsUtils.SafeCloseDbConnectionOnFile(
                        Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName, Wizard.ModelBuilderSettings.DesignTimeConnectionString);
                }

                args.Result = result;
            }
        }
Esempio n. 3
0
        private bool IsAfterARename(ProjectItem projectItem)
        {
            var hier = SiteServiceProvider.GetService(typeof(IVsHierarchy)) as IVsHierarchy;

            if (hier != null)
            {
                // check if there is an item in our oldInputNames cache corresponding to the itemID.
                string oldInputName;
                var    itemId = VsUtils.GetProjectItemId(hier, projectItem);
                if (_oldInputNames.TryGetValue(itemId, out oldInputName))
                {
                    // double-check that the new filename is not equal to the old filename. If it's not,
                    // then this is a rename
                    var newName = projectItem.get_FileNames(1);
                    if (!String.IsNullOrEmpty(newName) &&
                        !newName.Equals(oldInputName))
                    {
                        _oldInputNames.Remove(itemId);
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 4
0
        private string GetCodeNamespace(string defaultNamespace, EFArtifact artifact)
        {
            var ns = (defaultNamespace == null ? String.Empty : defaultNamespace.Trim());

            // This is a work-around for Astoria bug SQLBUDT 639143.  They choke when we there is no code namespace, and it is too late for them
            // to fix this bug in the netfx, so we have the below work-around.
            if (string.IsNullOrEmpty(ns))
            {
                if (VsUtils.GetProjectKind(Project) == VsUtils.ProjectKind.VB)
                {
                    var vbRootNamespace = VsUtils.GetProjectPropertyByName(Project, "RootNamespace") as string;
                    if (string.IsNullOrEmpty(vbRootNamespace))
                    {
                        ns = artifact.ConceptualModel().Namespace.Value;
                    }
                }
                else
                {
                    ns = artifact.ConceptualModel().Namespace.Value;
                }
            }

            return(ns);
        }
Esempio n. 5
0
        public ProjectExecutionContext(Project project, IServiceProvider serviceProvider)
        {
            Debug.Assert(project != null, "project is null.");
            Debug.Assert(!VsUtils.IsMiscellaneousProject(project), "project is misc files project.");

            _domain = AppDomain.CreateDomain(
                "ProjectExecutionContextDomain",
                null,
                new AppDomainSetup
            {
                ApplicationBase   = VsUtils.GetProjectTargetDir(project, serviceProvider),
                ConfigurationFile = VsUtils.GetProjectConfigurationFile(project, serviceProvider),
                ShadowCopyFiles   = "true"       // Prevents locking
            });

            var dataDirectory = VsUtils.GetProjectDataDirectory(project, serviceProvider);

            if (dataDirectory != null)
            {
                _domain.SetData("DataDirectory", dataDirectory);
            }

            _executor = new ExecutorWrapper(_domain, VsUtils.GetProjectTargetFileName(project));
        }
Esempio n. 6
0
        internal static void ClearErrorsForDocAcrossLists(Uri uri)
        {
            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");
                    foreach (var vsFileInfo in fileFinder.MatchingFiles)
                    {
                        if (vsFileInfo.Hierarchy == hierarchy)
                        {
                            ClearErrorsForDocAcrossLists(vsFileInfo.Hierarchy, vsFileInfo.ItemId);
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        internal override void DetermineIfArtifactIsVersionSafe()
        {
            // We want to move the user to the latest possible schemas - so if a user opens a v2 edmx
            // file in a project that has a reference to an EF assembly that can handle v3 schema we
            // won't display the model but will show a watermark saying "please upgrade your schema"
            // There are two exceptions to this rule:
            // - a user opens an edmx without a project (a.k.a. Misc project) in that case we always show
            //   the model
            // - a user is targeting .NET Framework 4 and has references to both System.Data.Entity.dll
            //   and EF6 EntityFramework.dll in which case we allow opening both v2 and v3 edmx files

            var project = GetProject();

            Debug.Assert(project != null);

            IsVersionSafe =
                VsUtils.EntityFrameworkSupportedInProject(project, ServiceProvider, allowMiscProject: true) &&
                VsUtils.SchemaVersionSupportedInProject(project, SchemaVersion, ServiceProvider);

            if (IsVersionSafe)
            {
                base.DetermineIfArtifactIsVersionSafe();
            }
        }
Esempio n. 8
0
        public void SchemaVersionSupportedInProject_returns_true_for_v2_and_v3_if_EF4_and_EF6_present()
        {
            var mockDte =
                new MockDTE(
                    ".NETFramework, Version=v4.0",
                    references:
                    new[]
            {
                MockDTE.CreateReference("System.Data.Entity", "4.0.0.0"),
                MockDTE.CreateReference("EntityFramework", "6.0.0.0")
            });

            Assert.False(
                VsUtils.SchemaVersionSupportedInProject(
                    mockDte.Project, EntityFrameworkVersion.Version1, mockDte.ServiceProvider));

            Assert.True(
                VsUtils.SchemaVersionSupportedInProject(
                    mockDte.Project, EntityFrameworkVersion.Version2, mockDte.ServiceProvider));

            Assert.True(
                VsUtils.SchemaVersionSupportedInProject(
                    mockDte.Project, EntityFrameworkVersion.Version3, mockDte.ServiceProvider));
        }
        private static void EnsureCanStartWizard(Project project, IServiceProvider serviceProvider)
        {
            // make sure we can access the data package
            if (serviceProvider.GetService(typeof(IVsDataConnectionManager)) == null)
            {
                VsUtils.ShowErrorDialog(Resources.LoadDataPackageError);
                throw new WizardCancelledException();
            }

            // make sure that our package is loaded
            try
            {
                PackageManager.LoadEDMPackage(serviceProvider);
            }
            catch (Exception ex)
            {
                // an exception occurred loading our package, so raise an error dialog, and cancel the wizard
                var message = Resources.LoadOurPackageError;
#if DEBUG
                message += " " + ex;
#else
                message += " " + ex.Message;
#endif
                VsUtils.ShowErrorDialog(message);
                throw new WizardCancelledException(Resources.LoadOurPackageError, ex);
            }

            if (!VsUtils.EntityFrameworkSupportedInProject(project, serviceProvider, allowMiscProject: false))
            {
                VsUtils.ShowErrorDialog(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.EdmUtils_NotValidTargetFramework));
                Marshal.ThrowExceptionForHR(VSConstants.E_ABORT);
            }
        }
Esempio n. 10
0
        private static void RegisterAssemblyInWebConfig(Project project, string assemblyFullName)
        {
            Debug.Assert(project != null, "project is null");
            Debug.Assert(!string.IsNullOrWhiteSpace(assemblyFullName), "invalid assembly name");

            var statusMessage = String.Format(
                CultureInfo.CurrentCulture,
                Resources.Engine_WebConfigAssemblySuccess,
                assemblyFullName);

            try
            {
                VsUtils.RegisterAssembly(project, assemblyFullName);
            }
            catch (Exception e)
            {
                statusMessage = String.Format(
                    CultureInfo.CurrentCulture,
                    Resources.Engine_WebConfigAssemblyException,
                    assemblyFullName, e.Message);
            }

            VsUtils.LogOutputWindowPaneMessage(project, statusMessage);
        }
Esempio n. 11
0
        void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
        {
            var textBuffer = (ITextBuffer)sender;
            var newVersion = e.AfterVersion.Convert();
            var fileModel  = textBuffer.Properties.GetProperty <FileModel>(Constants.FileModelKey);
            var id         = fileModel.Id;
            var changes    = e.Changes;

            if (changes.Count == 1)
            {
                Server.Client.Send(new ClientMessage.FileChanged(id, newVersion, VsUtils.Convert(changes[0])));
            }
            else
            {
                var builder = ImmutableArray.CreateBuilder <FileChange>(changes.Count);

                foreach (var change in changes)
                {
                    builder.Add(VsUtils.Convert(change));
                }

                Server.Client.Send(new ClientMessage.FileChangedBatch(id, newVersion, builder.MoveToImmutable()));
            }
        }
        // <summary>
        //     Resolves the given 'path' with the given project's macros and validates it based on these rules:
        //     1. The resolved path should not be null or empty
        //     2. We should be able to create a absolute URI from the resolved path OR
        //     2.1 We should be able to create a relative URI, relative to the project from the resolved path
        //     3. If the path is a custom path, it should be included in the project and should be relative to the project.
        //     4. The file must exist.
        // </summary>
        internal static FileInfo ResolveAndValidatePath(Project project, string path, PathValidationErrorMessages errorMessages)
        {
#if DEBUG
            errorMessages.ValidateAllProperties();
#endif
            var resolvedPath = VsUtils.ResolvePathWithMacro(
                null, path,
                new Dictionary <string, string>
            {
                { ExtensibleFileManager.EFTOOLS_USER_MACRONAME, ExtensibleFileManager.UserEFToolsDir.FullName },
                { ExtensibleFileManager.EFTOOLS_VS_MACRONAME, ExtensibleFileManager.VSEFToolsDir.FullName }
            });

            // First check null
            if (String.IsNullOrEmpty(resolvedPath))
            {
                throw new InvalidOperationException(errorMessages.NullFile);
            }

            // resolved path should be a resolvable full path, so try creating a URI. We will need the URI's local path for the next step. This process
            // will strip out any levels of indirection in the path ('..\'). If this is a relative path pointing to a file in the project then this step will
            // be a no-op.
            Uri resolvedUri;
            if (Uri.TryCreate(resolvedPath, UriKind.Absolute, out resolvedUri))
            {
                resolvedPath = resolvedUri.LocalPath;
            }

            // We need to determine if this is a custom path; that is, something the user has typed in that is different from
            // the files in the 'user' and 'vs' directories.
            string temporaryRelativePath;
            if (VsUtils.TryGetRelativePathInParentPath(
                    Path.Combine(ExtensibleFileManager.UserEFToolsDir.FullName, _dbGenFolderName), resolvedPath, out temporaryRelativePath)
                == false
                &&
                VsUtils.TryGetRelativePathInParentPath(
                    Path.Combine(ExtensibleFileManager.VSEFToolsDir.FullName, _dbGenFolderName), resolvedPath, out temporaryRelativePath)
                == false)
            {
                // Attempt to resolve to the project
                try
                {
                    bool projectHasFilename;
                    var  projectPath   = VsUtils.GetProjectPathWithName(project, out projectHasFilename);
                    var  projectDirUri = new Uri(projectPath);
                    Debug.Assert(projectDirUri != null, "The project directory URI is null; why wasn't an exception thrown?");

                    if (projectDirUri != null)
                    {
                        if (false == Uri.TryCreate(projectDirUri, resolvedPath, out resolvedUri))
                        {
                            throw new InvalidOperationException(
                                      String.Format(CultureInfo.CurrentCulture, errorMessages.NonValid, resolvedPath));
                        }
                        resolvedPath = resolvedUri.LocalPath;
                    }
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException(
                              String.Format(CultureInfo.CurrentCulture, errorMessages.ParseError, path, e.Message), e);
                }

                // Now check if the file has been added to the project using the resolved path. We do not allow otherwise.
                if (VsUtils.GetProjectItemForDocument(resolvedPath, Services.ServiceProvider) == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, errorMessages.NotInProject, resolvedPath));
                }
            }

            // If the specified file is not installed or does not exist, then we cannot continue
            var pathFileInfo = new FileInfo(resolvedPath);
            if (false == pathFileInfo.Exists)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture, errorMessages.NonExistant, pathFileInfo.FullName));
            }

            return(pathFileInfo);
        }
        internal static WorkflowApplication CreateDatabaseScriptGenerationWorkflow(
            SynchronizationContext syncContext,
            Project project,
            string artifactPath,
            FileInfo workflowFileInfo,
            string templatePath,
            EdmItemCollection edmItemCollection,
            string existingSsdl,
            string existingMsl,
            string databaseSchemaName,
            string databaseName,
            string providerInvariantName,
            string providerConnectionString,
            string providerManifestToken,
            Version targetVersion,
            Action <WorkflowApplicationCompletedEventArgs> workflowCompletedHandler,
            Func <WorkflowApplicationUnhandledExceptionEventArgs, UnhandledExceptionAction> unhandledExceptionHandler)
        {
            // Inputs are specific to the workflow. No need to provide a strongly typed bag here
            // because the workflow has to define these.
            var inputs = new Dictionary <string, object>
            {
                { EdmConstants.csdlInputName, edmItemCollection },
                { EdmConstants.existingSsdlInputName, existingSsdl },
                { EdmConstants.existingMslInputName, existingMsl }
            };

            // Initialize the AssemblyLoader. This will cache project/website references and proffer assembly
            // references to the XamlSchemaContext as well as the OutputGeneratorActivities
            var assemblyLoader = new DatabaseGenerationAssemblyLoader(project, VsUtils.GetVisualStudioInstallDir());

            // Parameters can be used throughout the workflow. These are more ubiquitous than inputs and
            // so they do not need to be defined ahead of time in the workflow.
            var edmWorkflowSymbolResolver = new EdmParameterBag(
                syncContext, assemblyLoader, targetVersion, providerInvariantName, providerManifestToken, providerConnectionString,
                databaseSchemaName, databaseName, templatePath, artifactPath);

            // Deserialize the XAML file into a Activity
            Activity modelFirstWorkflowElement;

            using (var stream = workflowFileInfo.OpenRead())
            {
                using (
                    var xamlXmlReader = new XamlXmlReader(XmlReader.Create(stream), new DatabaseGenerationXamlSchemaContext(assemblyLoader))
                    )
                {
                    modelFirstWorkflowElement = ActivityXamlServices.Load(xamlXmlReader);
                }
            }

            // Create a WorkflowInstance from the WorkflowElement and pass in the inputs
            var workflowInstance = new WorkflowApplication(modelFirstWorkflowElement, inputs);

            // Attach a SymbolResolver for external parameters; this is like the ParameterBag
            var symbolResolver = new SymbolResolver();

            symbolResolver.Add(typeof(EdmParameterBag).Name, edmWorkflowSymbolResolver);

            workflowInstance.Extensions.Add(symbolResolver);
            workflowInstance.Completed            = workflowCompletedHandler;
            workflowInstance.OnUnhandledException = unhandledExceptionHandler;

            return(workflowInstance);
        }
        internal static bool UpdateEdmxAndEnvironment(ModelBuilderSettings settings)
        {
            var artifact = settings.Artifact as EntityDesignArtifact;

            if (artifact == null)
            {
                Debug.Fail("In trying to UpdateEdmxAndEnvironment(), No Artifact was found in the ModelBuilderSettings");
                return(false);
            }

            // Update the app. or web.config, register build providers etc
            ConfigFileHelper.UpdateConfig(settings);

            if (settings.SsdlStringReader != null &&
                settings.MslStringReader != null)
            {
                // Create the XmlReaders for the ssdl and msl text
                var ssdlXmlReader = XmlReader.Create(settings.SsdlStringReader);
                var mslXmlReader  = XmlReader.Create(settings.MslStringReader);

                // Set up our post event to clear out the error list
                var cmd = new ReplaceSsdlAndMslCommand(ssdlXmlReader, mslXmlReader);
                cmd.PostInvokeEvent += (o, e) =>
                {
                    var errorList = ErrorListHelper.GetSingleDocErrorList(e.CommandProcessorContext.Artifact.Uri);
                    if (errorList != null)
                    {
                        errorList.Clear();
                    }
                };

                // Update the model (all inside 1 transaction so we don't get multiple undo's/redo's)
                var editingContext =
                    PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(settings.Artifact.Uri);
                var cpc = new CommandProcessorContext(
                    editingContext,
                    EfiTransactionOriginator.GenerateDatabaseScriptFromModelId, Resources.Tx_GenerateDatabaseScriptFromModel);
                var cp = new CommandProcessor(cpc, cmd);
                var addUseLegacyProviderCommand = ModelHelper.CreateSetDesignerPropertyValueCommandFromArtifact(
                    cpc.Artifact,
                    OptionsDesignerInfo.ElementName,
                    OptionsDesignerInfo.AttributeUseLegacyProvider,
                    settings.UseLegacyProvider.ToString());
                if (addUseLegacyProviderCommand != null)
                {
                    cp.EnqueueCommand(addUseLegacyProviderCommand);
                }

                // When the user had a v2 edmx file (it can happen when creating a new empty model in a project targeting
                // .NET Framework 4 and the project does not have refereces to any of EF dlls) and selected EF6 in
                // the "create database from model" wizard we need to update the artifact to use v3 schemas otherwise
                // there will be a watermark saying that the edmx is not correct for the EF version and needs to be updated.
                // We only want to run this command if the version really changed to avoid the overhead.
                if (artifact.SchemaVersion != settings.TargetSchemaVersion)
                {
                    cp.EnqueueCommand(new RetargetXmlNamespaceCommand(artifact, settings.TargetSchemaVersion));
                }

                cp.Invoke();
            }

            // First let's get the canonical file path since DTE needs this
            if (!string.IsNullOrEmpty(settings.DdlFileName) &&
                settings.DdlStringReader != null)
            {
                var canonicalFilePath = string.Empty;
                try
                {
                    var fi = new FileInfo(settings.DdlFileName);
                    canonicalFilePath = fi.FullName;
                }
                catch (Exception e)
                {
                    Debug.Fail(
                        "We should have caught this exception '" + e.Message + "' immediately after the user clicked the 'Finish' button");
                    VsUtils.ShowErrorDialog(
                        String.Format(
                            CultureInfo.CurrentCulture, ModelWizard.Properties.Resources.ErrorCouldNotParseDdlFileName, settings.DdlFileName,
                            e.Message));
                    return(false);
                }

                // Output the DDL file, catch any Exceptions, display them, and revert
                // back to the last page of the wizard.
                try
                {
                    OutputDdl(canonicalFilePath, settings.DdlStringReader);
                }
                catch (Exception e)
                {
                    if (e.InnerException == null)
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(
                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorWritingDdl, canonicalFilePath, e.Message));
                    }
                    else
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(
                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorWritingDdlWithInner, canonicalFilePath,
                                e.Message, e.InnerException.Message));
                    }
                    return(false);
                }

                // Add DDL file to the project if it is inside the project
                string relativePath;
                if (VsUtils.TryGetRelativePathInProject(settings.Project, canonicalFilePath, out relativePath))
                {
                    AddDDLFileToProject(settings.Project, canonicalFilePath);
                }

                // Open the DDL file if it is not already open
                IVsUIHierarchy hier;
                uint           itemId;
                IVsWindowFrame frame;
                if (VsShellUtilities.IsDocumentOpen(
                        Services.ServiceProvider, canonicalFilePath, Guid.Empty, out hier, out itemId, out frame) == false)
                {
                    VsShellUtilities.OpenDocument(Services.ServiceProvider, canonicalFilePath);
                }
            }

            return(true);
        }
        internal static void GenerateDatabaseScriptFromModel(EntityDesignArtifact artifact)
        {
            VsUtils.EnsureProvider(artifact);

            var project = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, PackageManager.Package);
            var sp      = Services.ServiceProvider;
            ModelBuilderWizardForm form;

            ModelBuilderWizardForm.WizardMode startMode;
            ModelBuilderSettings settings;

            // Start the hourglass, especially because we'll be incurring a perf hit from validating
            using (new VsUtils.HourglassHelper())
            {
                // Before running the Generate Database wizard, we have to make sure that the C-Side validates
                VisualStudioEdmxValidator.LoadAndValidateFiles(artifact.Uri);

                if (
                    artifact.ArtifactSet.GetAllErrors()
                    .Count(ei => ei.ErrorClass == ErrorClass.Runtime_CSDL || ei.ErrorClass == ErrorClass.Escher_CSDL) > 0)
                {
                    VsUtils.ShowErrorDialog(Resources.DatabaseCreation_ValidationFailed);
                    return;
                }

                // set up ModelBuilderSettings
                settings = SetupSettingsAndModeForDbPages(
                    sp, project, artifact, false,
                    ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary,
                    ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly, out startMode);

                form = new ModelBuilderWizardForm(sp, settings, startMode);
            }

            var originalSchemaVersion = settings.TargetSchemaVersion;

            try
            {
                // start the ModelBuilderWizardForm; this will start the workflow in another thread.
                form.Start();
            }
            catch (Exception e)
            {
                VsUtils.ShowErrorDialog(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        e.Message));
                return;
            }

            // if Wizard was cancelled or the user hit 'X' to close window
            // no need for any further action
            if (form.WizardCancelled ||
                !form.WizardFinished)
            {
                return;
            }

            // If database was configured, add DbContext templates
            if (startMode == ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary)
            {
                var edmxItem = VsUtils.GetProjectItemForDocument(artifact.Uri.LocalPath, sp);
                new DbContextCodeGenerator().AddDbContextTemplates(edmxItem, settings.UseLegacyProvider);

                // We need to reload the artifact if we updated the edmx as part of generating
                // model from the database.
                if (settings.TargetSchemaVersion != originalSchemaVersion)
                {
                    artifact.ReloadArtifact();
                }
            }
        }
        public static TagSpan <TextMarkerTag> MakeTagSpan(ITextSnapshot currentSnapshot, NSpan nSpan, string tagType)
        {
            var span = new SnapshotSpan(currentSnapshot, VsUtils.Convert(nSpan));

            return(new TagSpan <TextMarkerTag>(span, new TextMarkerTag(tagType)));
        }
        internal override bool OnWizardFinish()
        {
            if (Wizard.ModelBuilderSettings.DdlStringReader != null)
            {
                // Make sure that the DDL filename is not null
                if (String.IsNullOrEmpty(txtSaveDdlAs.Text))
                {
                    VsUtils.ShowErrorDialog(Properties.Resources.ErrorDdlFileNameIsNull);
                    return(false);
                }

                // Resolve the project URI
                Uri  projectUri = null;
                bool projectHasFilename;
                var  projectFullName = VsUtils.GetProjectPathWithName(Wizard.Project, out projectHasFilename);

                try
                {
                    if (false == Uri.TryCreate(projectFullName, UriKind.Absolute, out projectUri) ||
                        projectUri == null)
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrorResolvingProjectFile, projectFullName));
                        return(false);
                    }
                }
                catch (UriFormatException)
                {
                    VsUtils.ShowErrorDialog(
                        String.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrorResolvingProjectFile, projectFullName));
                }

                // Attempt to create a URI from the DDL path, either relative to the project URI or absolute.
                Uri ddlUri = null;
                try
                {
                    if (false == Uri.TryCreate(projectUri, txtSaveDdlAs.Text, out ddlUri) ||
                        ddlUri == null)
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(
                                CultureInfo.CurrentCulture, Properties.Resources.ErrorResolvingDdlFileNameException, txtSaveDdlAs.Text));
                        return(false);
                    }
                }
                catch (UriFormatException)
                {
                    VsUtils.ShowErrorDialog(
                        String.Format(
                            CultureInfo.CurrentCulture, Properties.Resources.ErrorResolvingDdlFileNameException, txtSaveDdlAs.Text));
                }

                var ddlFilePath = ddlUri.LocalPath;

                // Validate the file name
                try
                {
                    var ddlFileName = Path.GetFileName(ddlFilePath);
                    if (String.IsNullOrEmpty(ddlFileName))
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrorDdlPathNotFile, ddlFilePath));
                        return(false);
                    }

                    if (!VsUtils.IsValidFileName(ddlFileName))
                    {
                        VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, Resources.ErrorNonValidFileName, ddlFilePath));
                        return(false);
                    }
                }
                catch (ArgumentException)
                {
                    VsUtils.ShowErrorDialog(
                        String.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrorResolvingDdlFileNameException, ddlFilePath));
                    return(false);
                }

                // Add ".sql" if the extension is not already .sql
                if (!Path.GetExtension(ddlFilePath).Equals(_ddlFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    ddlFilePath += _ddlFileExtension;
                }

                // Now we should have a valid, non-null filename
                Debug.Assert(
                    !String.IsNullOrEmpty(ddlFilePath),
                    "DDL filename should either be not null or we should have handled an exception before continuing...");
                if (String.IsNullOrEmpty(ddlFilePath))
                {
                    VsUtils.ShowErrorDialog(Properties.Resources.ErrorDdlFileNameIsNull);
                    return(false);
                }

                // If the parent directory does not exist, then we do not proceed
                try
                {
                    var fileInfo      = new FileInfo(ddlFilePath);
                    var parentDirInfo = fileInfo.Directory;
                    if (parentDirInfo != null)
                    {
                        if (false == parentDirInfo.Exists)
                        {
                            VsUtils.ShowErrorDialog(
                                String.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrorNoDdlParentDir, ddlFilePath));
                            return(false);
                        }
                    }
                }
                catch (Exception e)
                {
                    // various exceptions could occur here, such as PathTooLong or Security. In this case we will display an error.
                    VsUtils.ShowErrorDialog(
                        String.Format(
                            CultureInfo.CurrentCulture, Properties.Resources.ErrorCouldNotParseDdlFileName, ddlFilePath, e.Message));
                    return(false);
                }

                // Display the DDL Overwrite Warning Dialog
                if (File.Exists(ddlFilePath))
                {
                    var displayDdlOverwriteWarning = true;
                    try
                    {
                        var ddlOverwriteWarningString = EdmUtils.GetUserSetting(RegKeyNameDdlOverwriteWarning);
                        if (false == String.IsNullOrEmpty(ddlOverwriteWarningString) &&
                            false == Boolean.TryParse(ddlOverwriteWarningString, out displayDdlOverwriteWarning))
                        {
                            displayDdlOverwriteWarning = true;
                        }
                        if (displayDdlOverwriteWarning)
                        {
                            var cancelledDuringOverwriteDdl = DismissableWarningDialog.ShowWarningDialogAndSaveDismissOption(
                                Resources.DatabaseCreation_DDLOverwriteWarningTitle,
                                String.Format(CultureInfo.CurrentCulture, Resources.DatabaseCreation_WarningOverwriteDdl, ddlFilePath),
                                RegKeyNameDdlOverwriteWarning,
                                DismissableWarningDialog.ButtonMode.YesNo);
                            if (cancelledDuringOverwriteDdl)
                            {
                                return(false);
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        // We should at least alert the user of why this is failing so they can take steps to fix it.
                        VsUtils.ShowMessageBox(
                            Services.ServiceProvider,
                            String.Format(
                                CultureInfo.CurrentCulture, Resources.ErrorReadingWritingUserSetting, RegKeyNameDdlOverwriteWarning,
                                e.Message),
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                            OLEMSGICON.OLEMSGICON_WARNING);
                    }
                }

                // At this point we will save off the DDL Filename into the wizard settings
                Wizard.ModelBuilderSettings.DdlFileName = ddlFilePath;
            }

            if ((Wizard.ModelBuilderSettings.SsdlStringReader != null ||
                 Wizard.ModelBuilderSettings.MslStringReader != null) &&
                (Wizard.ModelBuilderSettings.Artifact != null) &&
                (Wizard.ModelBuilderSettings.Artifact.StorageModel() != null) &&
                (!Wizard.ModelBuilderSettings.Artifact.StorageModel().IsEmpty))
            {
                // Display the SSDL/MSL Overwrite Warning Dialog
                var displayEdmxOverwriteWarning = true;
                try
                {
                    var edmxOverwriteWarningString = EdmUtils.GetUserSetting(RegKeyNameEdmxOverwriteWarning);
                    if (false == String.IsNullOrEmpty(edmxOverwriteWarningString) &&
                        false == Boolean.TryParse(edmxOverwriteWarningString, out displayEdmxOverwriteWarning))
                    {
                        displayEdmxOverwriteWarning = true;
                    }
                    if (displayEdmxOverwriteWarning)
                    {
                        var cancelledDuringOverwriteSsdl = DismissableWarningDialog.ShowWarningDialogAndSaveDismissOption(
                            Resources.DatabaseCreation_EdmxOverwriteWarningTitle,
                            Resources.DatabaseCreation_WarningOverwriteMappings,
                            RegKeyNameEdmxOverwriteWarning,
                            DismissableWarningDialog.ButtonMode.YesNo);
                        if (cancelledDuringOverwriteSsdl)
                        {
                            return(false);
                        }
                    }
                }
                catch (SecurityException e)
                {
                    // We should at least alert the user of why this is failing so they can take steps to fix it.
                    VsUtils.ShowMessageBox(
                        Services.ServiceProvider,
                        String.Format(
                            CultureInfo.CurrentCulture, Resources.ErrorReadingWritingUserSetting, RegKeyNameEdmxOverwriteWarning,
                            e.Message),
                        OLEMSGBUTTON.OLEMSGBUTTON_OK,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                        OLEMSGICON.OLEMSGICON_WARNING);
                }
            }

            using (new VsUtils.HourglassHelper())
            {
                // Now we output the DDL, update app/web.config, update the edmx, and open the SQL file that gets produced
                return(DatabaseGenerationEngine.UpdateEdmxAndEnvironment(Wizard.ModelBuilderSettings));
            }
        }
Esempio n. 18
0
 // <summary>
 //     Ensure we have the correct provider loaded before we reload
 // </summary>
 internal override void ReloadArtifact()
 {
     VsUtils.EnsureProvider(this);
     base.ReloadArtifact();
 }
Esempio n. 19
0
        public void ExecuteActivate()
        {
            var viewModelHelper = ExplorerViewModelHelper as EntityDesignExplorerViewModelHelper;

            Debug.Assert(viewModelHelper != null, "ExplorerViewModelHelper is null or is not type of EntityDesignExplorerViewModelHelper");

            // Function-Import/Function  double-click behavior.
            var selectedExplorerEFElement  = GetSelectedExplorerEFElement();
            var explorerFunctionImport     = selectedExplorerEFElement as ExplorerFunctionImport;
            var explorerFunction           = selectedExplorerEFElement as ExplorerFunction;
            var explorerDiagram            = selectedExplorerEFElement as ExplorerDiagram;
            var explorerConceptualProperty = selectedExplorerEFElement as ExplorerConceptualProperty;
            var explorerEnumType           = selectedExplorerEFElement as ExplorerEnumType;

            var diagramManagercontextItem = EditingContext.Items.GetValue <DiagramManagerContextItem>();

            Debug.Assert(diagramManagercontextItem != null, "Could not find instance of: DiagramManagerContextItem in editing context.");

            if (viewModelHelper != null &&
                explorerFunctionImport != null)
            {
                viewModelHelper.EditFunctionImport(explorerFunctionImport.ModelItem as FunctionImport);
            }
            // if the user double-clicks on the function in the model browser.
            else if (viewModelHelper != null &&
                     explorerFunction != null)
            {
                var function = explorerFunction.ModelItem as Function;
                Debug.Assert(function != null, "ExplorerFunction.ModelItem value is expected to be typeof Function and not null.");

                if (function != null)
                {
                    var schemaVersion = (function.Artifact == null ? null : function.Artifact.SchemaVersion);
                    if (function.IsComposable != null &&
                        function.IsComposable.Value &&
                        !EdmFeatureManager.GetComposableFunctionImportFeatureState(schemaVersion).IsEnabled())
                    {
                        // Composable Function Import for Version <= V2 - give warning message
                        VsUtils.ShowMessageBox(
                            PackageManager.Package,
                            string.Format(
                                CultureInfo.CurrentCulture, Design.Resources.FunctionImport_CannotCreateFromComposableFunction,
                                EntityFrameworkVersion.Version2),
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                            OLEMSGICON.OLEMSGICON_WARNING);
                    }
                    else
                    {
                        // first we detect whether there are existing FunctionImport(s) with the underlying function.
                        var itemBindings            = function.GetDependentBindings();
                        var matchFunctionImportList = new List <FunctionImport>();
                        foreach (var itemBinding in itemBindings)
                        {
                            var functionImportMapping = itemBinding.GetParentOfType(typeof(FunctionImportMapping)) as FunctionImportMapping;
                            if (functionImportMapping != null &&
                                functionImportMapping.FunctionImportName != null &&
                                functionImportMapping.FunctionImportName.Target != null)
                            {
                                matchFunctionImportList.Add(functionImportMapping.FunctionImportName.Target);
                            }
                        }
                        // if we found function imports for the underlying function, navigate to the first function import in alphabetical sorted list
                        if (matchFunctionImportList.Count > 0)
                        {
                            matchFunctionImportList.Sort(EFElement.EFElementDisplayNameComparison);
                            ExplorerNavigationHelper.NavigateTo(matchFunctionImportList[0]);
                        }
                        else
                        {
                            // We could not find any function import for the underlying function, show new function import dialog
                            viewModelHelper.CreateFunctionImport(explorerFunction.ModelItem as Function);
                        }
                    }
                }
            }
            else if (explorerEnumType != null)
            {
                var enumType = explorerEnumType.ModelItem as EnumType;
                Debug.Assert(enumType != null, "ExplorerEnumType's model item is null or is not type of EnumType.");
                EntityDesignViewModelHelper.EditEnumType(
                    Context, EfiTransactionOriginator.ExplorerWindowOriginatorId, new EnumTypeViewModel(enumType));
            }
            // if the selected Explorer is type of ExplorerDiagram.
            else if (explorerDiagram != null &&
                     diagramManagercontextItem != null)
            {
                diagramManagercontextItem.DiagramManager.OpenDiagram(explorerDiagram.DiagramMoniker, true);
            }
            else if (explorerConceptualProperty != null)
            {
                Debug.Assert(
                    explorerConceptualProperty.Parent is ExplorerConceptualEntityType,
                    "Only properties that belong to Entity type are supported.");
                if (explorerConceptualProperty.Parent is ExplorerConceptualEntityType)
                {
                    diagramManagercontextItem.DiagramManager.ActiveDiagram.AddOrShowEFElementInDiagram(explorerConceptualProperty.ModelItem);
                }
            }
            // if the selected Explorer is type of ExplorerConceptualEntityType, ExplorerConceptualAssociation, ExplorerNavigationProperty, ExplorerAssociationSet or ExplorerEntitySet
            else if (diagramManagercontextItem != null &&
                     diagramManagercontextItem.DiagramManager != null &&
                     diagramManagercontextItem.DiagramManager.ActiveDiagram != null)
            {
                Debug.Assert(
                    selectedExplorerEFElement is ExplorerConceptualEntityType ||
                    selectedExplorerEFElement is ExplorerConceptualAssociation ||
                    selectedExplorerEFElement is ExplorerNavigationProperty ||
                    selectedExplorerEFElement is ExplorerAssociationSet ||
                    selectedExplorerEFElement is ExplorerEntitySet ||
                    selectedExplorerEFElement is ExplorerEntityTypeShape,
                    "The selected explorer type:" + selectedExplorerEFElement.GetType().Name + " is not supported.");

                if (selectedExplorerEFElement is ExplorerConceptualEntityType ||
                    selectedExplorerEFElement is ExplorerConceptualAssociation ||
                    selectedExplorerEFElement is ExplorerNavigationProperty ||
                    selectedExplorerEFElement is ExplorerAssociationSet ||
                    selectedExplorerEFElement is ExplorerEntitySet)
                {
                    diagramManagercontextItem.DiagramManager.ActiveDiagram.AddOrShowEFElementInDiagram(selectedExplorerEFElement.ModelItem);
                }
                else if (selectedExplorerEFElement is ExplorerEntityTypeShape)
                {
                    var entityTypeShape = selectedExplorerEFElement.ModelItem as EntityTypeShape;
                    Debug.Assert(entityTypeShape != null, "ExplorerEntityTypeShape does not contain instance of EntityTypeShape");
                    if (entityTypeShape != null)
                    {
                        diagramManagercontextItem.DiagramManager.OpenDiagram(entityTypeShape.Diagram.Id, true);
                        diagramManagercontextItem.DiagramManager.ActiveDiagram.AddOrShowEFElementInDiagram(
                            entityTypeShape.EntityType.Target);
                    }
                }
            }
        }
        internal WizardPageDbConfig(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            _configFileUtils =
                new ConfigFileUtils(wizard.Project, wizard.ServiceProvider, wizard.ModelBuilderSettings.VSApplicationType);

            _identifierUtil =
                new CodeIdentifierUtils(wizard.ModelBuilderSettings.VSApplicationType, VsUtils.GetLanguageForProject(wizard.Project));

            Headline      = Resources.DbConfigPage_Title;
            Logo          = Resources.PageIcon;
            Id            = "WizardPageDbConfigId";
            ShowInfoPanel = false;

            sensitiveInfoTextBox.Text        = Resources.SensitiveDataInfoText;
            disallowSensitiveInfoButton.Text = Resources.DisallowSensitiveDataInfoText;
            allowSensitiveInfoButton.Text    = Resources.AllowSensitiveDataInfoText;
            if (VsUtils.IsWebProject(wizard.ModelBuilderSettings.VSApplicationType))
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabelASP;
            }
            else
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabel;
            }

            // make the App/Web.Config connection name entry non-editable for 'Update Model' and 'Generate Database' scenarios
            if (ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly == Wizard.Mode)
            {
                textBoxAppConfigConnectionName.Enabled = false;
            }

            newDBConnectionButton.Text     = Resources.NewDatabaseConnectionBtn;
            lblEntityConnectionString.Text = Resources.ConnectionStringLabel;
            lblPagePrompt.Text             = Resources.WhichDataConnectionLabel;
            lblPagePrompt.Font             = LabelFont;

            sensitiveInfoTextBox.Enabled        = false;
            disallowSensitiveInfoButton.Enabled = false;
            allowSensitiveInfoButton.Enabled    = false;
            HelpKeyword = null;
        }
        // <summary>
        //     Prompts the user to copy the database file into the project if appropriate
        // </summary>
        // <returns>whether wizard should continue to next page</returns>
        private bool PromptConvertLocalConnection()
        {
            // first check whether connection is Local
            if (!LocalDataUtil.IsLocalDbFileConnectionString(
                    Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                    Wizard.ModelBuilderSettings.DesignTimeConnectionString))
            {
                return(true);
            }

            // if connection is Local but has already been copied into the project should not prompt
            var filePath = LocalDataUtil.GetLocalDbFilePath(
                Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                Wizard.ModelBuilderSettings.DesignTimeConnectionString);

            if (!string.IsNullOrEmpty(filePath))
            {
                var projectItemCollection = LocalDataUtil.GetDefaultCollectionForLocalDataFile(Wizard.ServiceProvider, Wizard.Project);
                var targetPath            = VsUtils.ConstructTargetPathForDatabaseFile(
                    Wizard.Project, projectItemCollection, Path.GetFileName(filePath));
                if (File.Exists(targetPath))
                {
                    return(true);
                }
            }

            // Special case -- Check if this is a SQL Mobile Device
            if (LocalDataUtil.IsSqlMobileDeviceConnectionString(
                    Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                    Wizard.ModelBuilderSettings.DesignTimeConnectionString))
            {
                // For mobile devices, if the connection starts with 'Mobile Device' it means that the connection
                // refers to a location on the device itself. Do not perform conversion.
                return(true);
            }

            // ask user if they want to copy
            var result = VsUtils.ShowMessageBox(
                Wizard.ServiceProvider,
                Resources.LocalDataConvertConnectionText,
                OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                OLEMSGICON.OLEMSGICON_QUERY);

            if (DialogResult.Yes != result)
            {
                return(true);
            }

            try
            {
                return(CopyFileIntoProjectAndConvertConnectionString(filePath));
            }
            catch (FileCopyException e)
            {
                var errMsgWithInnerExceptions = VsUtils.ConstructInnerExceptionErrorMessage(e);
                var errMsg = string.Format(
                    CultureInfo.CurrentCulture, Resources.LocalDataExceptionCopyingFile, e.GetType().FullName, filePath,
                    errMsgWithInnerExceptions);
                VsUtils.ShowErrorDialog(errMsg);
                return(false);
            }
        }
        internal override bool OnWizardFinish()
        {
            using (new VsUtils.HourglassHelper())
            {
                UpdateSettingsFromGui();
            }

            //
            // validate app config connection name
            //
            if (checkBoxSaveInAppConfig.Checked)
            {
                var id = textBoxAppConfigConnectionName.Text;
                if (!EscherAttributeContentValidator.IsValidCsdlEntityContainerName(id) ||
                    !_identifierUtil.IsValidIdentifier(id))
                {
                    VsUtils.ShowErrorDialog(
                        string.Format(CultureInfo.CurrentCulture, Resources.ConnectionStringNonValidIdentifier, id));
                    textBoxAppConfigConnectionName.Focus();
                    _isFocusSet = true;
                    return(false);
                }

                // only check that the connection string name is new if started in
                // 'PerformAllFunctionality' mode
                if (ModelBuilderWizardForm.WizardMode.PerformAllFunctionality == Wizard.Mode)
                {
                    string connectionString;
                    if (ConnectionManager.GetExistingConnectionStrings(_configFileUtils).TryGetValue(id, out connectionString) &&
                        !string.Equals(textBoxConnectionString.Text, connectionString, StringComparison.Ordinal))
                    {
                        VsUtils.ShowErrorDialog(
                            string.Format(CultureInfo.CurrentCulture, Resources.ConnectionStringDuplicateIdentifer, id));
                        textBoxAppConfigConnectionName.Focus();
                        _isFocusSet = true;
                        return(false);
                    }
                }
            }

            // the Model Namespace and the Entity Container name must differ
            if (ModelBuilderWizardForm.ModelNamespaceAndEntityContainerNameSame(Wizard.ModelBuilderSettings))
            {
                var s = Resources.NamespaceAndEntityContainerSame;
                VsUtils.ShowErrorDialog(
                    String.Format(CultureInfo.CurrentCulture, s, Wizard.ModelBuilderSettings.AppConfigConnectionPropertyName));
                textBoxAppConfigConnectionName.Focus();
                _isFocusSet = true;
                return(false);
            }

            try
            {
                // this might cause dataConnection to include some sensitive data into connectionString
                // the Open function also can cause DDEX to put up a prompt for the username/password for an existing connection
                // that does not have any saved password information.
                _dataConnection.Open();

                if (!IsDataValid)
                {
                    sensitiveInfoTextBox.Enabled        = true;
                    allowSensitiveInfoButton.Checked    = false;
                    allowSensitiveInfoButton.Enabled    = true;
                    disallowSensitiveInfoButton.Checked = false;
                    disallowSensitiveInfoButton.Enabled = true;

                    var result = VsUtils.ShowMessageBox(
                        PackageManager.Package,
                        Resources.SensitiveDataInfoText,
                        OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_THIRD,
                        OLEMSGICON.OLEMSGICON_QUERY);

                    switch (result)
                    {
                    case DialogResult.Yes:
                        allowSensitiveInfoButton.Checked = true;
                        break;

                    case DialogResult.No:
                        disallowSensitiveInfoButton.Checked = true;
                        break;

                    default:
                        Wizard.OnValidationStateChanged(this);
                        return(false);
                    }
                }
            }
            catch (DataConnectionOpenCanceledException)
            {
                return(false);
            }
            catch (Exception e)
            {
                // show error dialog
                ModelBuilderWizardForm.ShowDatabaseConnectionErrorDialog(e);

                return(false);
            }
            finally
            {
                if (_dataConnection.State != DataConnectionState.Closed)
                {
                    _dataConnection.Close();
                }
            }

            return(true);
        }
Esempio n. 23
0
        public bool CreateAndLoadBuffer()
        {
            DestroyBuffer();

            var pkg = PackageManager.Package as Package;
            IServiceProvider serviceProvider = pkg;

            var textLinesType = typeof(VSTextManagerInterop.IVsTextLines);
            var riid          = textLinesType.GUID;
            var clsid         = typeof(VSTextManagerInterop.VsTextBufferClass).GUID;

            _underlyingBuffer = pkg.CreateInstance(ref clsid, ref riid, textLinesType);
            Debug.Assert(_underlyingBuffer != null, "Failure while creating buffer.");

            var buffer = _underlyingBuffer as VSTextManagerInterop.IVsTextLines;

            Debug.Assert(buffer != null, "Why does buffer not implement IVsTextLines?");

            var ows = buffer as IObjectWithSite;

            if (ows != null)
            {
                ows.SetSite(serviceProvider.GetService(typeof(IOleServiceProvider)));
            }

            // We want to set the LanguageService SID explicitly to the XML Language Service.
            // We need turn off GUID_VsBufferDetectLangSID before calling LoadDocData so that the
            // TextBuffer does not do the work to detect the LanguageService SID from the file extension.
            var userData = buffer as VSTextManagerInterop.IVsUserData;

            if (userData != null)
            {
                var VsBufferDetectLangSID = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}"); //GUID_VsBufferDetectLangSID;
                VSErrorHandler.ThrowOnFailure(userData.SetData(ref VsBufferDetectLangSID, false));
            }

            var langSid = CommonPackageConstants.xmlEditorLanguageService;

            VSErrorHandler.ThrowOnFailure(buffer.SetLanguageServiceID(ref langSid));

            var persistDocData = buffer as IVsPersistDocData;

            if (persistDocData != null)
            {
                persistDocData.LoadDocData(FileName);
                var artifactUri = new Uri(FileName);

                var artifact = PackageManager.Package.ModelManager.GetArtifact(artifactUri);
                if (artifact != null &&
                    artifact.IsCodeGenArtifact)
                {
                    var standaloneProvider = artifact.XmlModelProvider as StandaloneXmlModelProvider;
                    if (standaloneProvider.ExtensionErrors == null ||
                        standaloneProvider.ExtensionErrors.Count == 0)
                    {
                        // If there is a cached code gen artifact, it will have loaded its text buffer using extensions already.
                        // Therefore we can grab the text buffer from that artifact for our docdata buffer, and dispose the
                        // code gen artifact since it's using a XmlProvider that is standalone and won't be supported by the
                        // designer.
                        var projectItem = VsUtils.GetProjectItem(Hierarchy, ItemId);
                        if (projectItem != null)
                        {
                            if (VSHelpers.CheckOutFilesIfEditable(ServiceProvider, new[] { FileName }))
                            {
                                string artifactText = null;
                                using (var writer = new Utf8StringWriter())
                                {
                                    artifact.XDocument.Save(writer, SaveOptions.None);
                                    artifactText = writer.ToString();
                                }

                                if (!String.IsNullOrWhiteSpace(artifactText))
                                {
                                    VsUtils.SetTextForVsTextLines(VsBuffer, artifactText);
                                }
                            }
                            else
                            {
                                ErrorListHelper.LogExtensionErrors(
                                    new List <ExtensionError>
                                {
                                    new ExtensionError(
                                        string.Format(
                                            CultureInfo.CurrentCulture, Resources.ExtensionError_SourceControlLock,
                                            Path.GetFileName(FileName)),
                                        ErrorCodes.ExtensionsError_BufferNotEditable,
                                        ExtensionErrorSeverity.Error)
                                },
                                    projectItem);
                            }
                        }

                        PackageManager.Package.ModelManager.ClearArtifact(artifactUri);
                    }
                    else
                    {
                        // If the extensions ran into errors whilst loading, we'll need to re-run extensions anyway so we ignore the cache
                        PackageManager.Package.ModelManager.ClearArtifact(artifactUri);
                        DispatchLoadToExtensions();
                    }
                }
                else
                {
                    DispatchLoadToExtensions();
                }
            }

            // DSL exposes the FileNameChanged event which we subscribe to so we can update the moniker inside
            // the text buffer, which is required to update our model as well as keep the XmlModel in sync.
            FileNameChanged += OnFileNameChanged;
            RegisterUndoTracking();
            return(true);
        }
        public override void OnActivated()
        {
            base.OnActivated();

            _onWorkflowCleanup = false;

            Debug.Assert(
                !Wizard.MovingNext || _workflowInstance == null,
                "Possible memory leak: We should have destroyed the old workflow instance when activating WizardPageDbGenSummary");

            if (_workflowInstance == null)
            {
                if (LocalDataUtil.IsSqlMobileConnectionString(Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName))
                {
                    _ddlFileExtension = DatabaseGenerationEngine._sqlceFileExtension;
                }
                else
                {
                    _ddlFileExtension = DatabaseGenerationEngine._ddlFileExtension;
                }

                // Add in the DbConfig page before if we have found a connection
                if (Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly &&
                    _addedDbConfigPage == false)
                {
                    Wizard.InsertPageBefore(Id, new WizardPageDbConfig(Wizard));
                    _addedDbConfigPage = true;
                }

                // Display the default path for the DDL
                var artifactProjectItem = VsUtils.GetProjectItemForDocument(
                    Wizard.ModelBuilderSettings.Artifact.Uri.LocalPath, PackageManager.Package);
                if (artifactProjectItem != null)
                {
                    txtSaveDdlAs.Text = DatabaseGenerationEngine.CreateDefaultDdlFileName(artifactProjectItem) + _ddlFileExtension;
                }

                // Disable all buttons except for Previous and Cancel
                Wizard.EnableButton(ButtonType.Previous, true);
                Wizard.EnableButton(ButtonType.Next, false);
                Wizard.EnableButton(ButtonType.Finish, false);
                Wizard.EnableButton(ButtonType.Cancel, true);

                // Display a status message
                ShowStatus(Properties.Resources.DbGenSummary_StatusDeterminingDDL);

                // Extract the XML from the EDMX file and convert it into an EdmItemCollection for the workflow
                EdmItemCollection edm = null;
                using (new VsUtils.HourglassHelper())
                {
                    IList <EdmSchemaError> schemaErrors;
                    edm = Wizard.ModelBuilderSettings.Artifact.GetEdmItemCollectionFromArtifact(out schemaErrors);

                    Debug.Assert(
                        edm != null && schemaErrors.Count == 0,
                        "EdmItemCollection schema errors found; we should have performed validation on the EdmItemCollection before instantiating the wizard.");
                }

                var existingSsdl = Wizard.ModelBuilderSettings.Artifact.GetSsdlAsString();
                var existingMsl  = Wizard.ModelBuilderSettings.Artifact.GetMslAsString();

                // Attempt to get the workflow path, template path, and database schema name from the artifact. If we don't find them, we'll use defaults.
                var workflowPath       = DatabaseGenerationEngine.GetWorkflowPathFromArtifact(Wizard.ModelBuilderSettings.Artifact);
                var templatePath       = DatabaseGenerationEngine.GetTemplatePathFromArtifact(Wizard.ModelBuilderSettings.Artifact);
                var databaseSchemaName = DatabaseGenerationEngine.GetDatabaseSchemaNameFromArtifact(Wizard.ModelBuilderSettings.Artifact);

                // Save off the SynchronizationContext so we can post methods to the UI event queue when
                // responding to workflow events (since they are executed in a separate thread)
                _synchronizationContext = SynchronizationContext.Current;

                // Invoke the Pipeline/Workflow. The Workflow engine will automatically wrap this in a background thread
                try
                {
                    using (new VsUtils.HourglassHelper())
                    {
                        var resolvedWorkflowFileInfo = DatabaseGenerationEngine.ResolveAndValidateWorkflowPath(
                            Wizard.Project,
                            workflowPath);

                        var resolvedDefaultPath = VsUtils.ResolvePathWithMacro(
                            null, DatabaseGenerationEngine.DefaultWorkflowPath,
                            new Dictionary <string, string>
                        {
                            { ExtensibleFileManager.EFTOOLS_USER_MACRONAME, ExtensibleFileManager.UserEFToolsDir.FullName },
                            { ExtensibleFileManager.EFTOOLS_VS_MACRONAME, ExtensibleFileManager.VSEFToolsDir.FullName }
                        });

                        // Display a security warning if the workflow path specified is different from the default
                        if (!resolvedWorkflowFileInfo.FullName.Equals(
                                Path.GetFullPath(resolvedDefaultPath), StringComparison.OrdinalIgnoreCase))
                        {
                            var displayCustomWorkflowWarning = true;
                            try
                            {
                                var customWorkflowWarningString = EdmUtils.GetUserSetting(RegKeyNameCustomWorkflowWarning);
                                if (false == String.IsNullOrEmpty(customWorkflowWarningString) &&
                                    false == Boolean.TryParse(customWorkflowWarningString, out displayCustomWorkflowWarning))
                                {
                                    displayCustomWorkflowWarning = true;
                                }
                                if (displayCustomWorkflowWarning)
                                {
                                    var cancelledDuringCustomWorkflowWarning = DismissableWarningDialog
                                                                               .ShowWarningDialogAndSaveDismissOption(
                                        Resources.DatabaseCreation_CustomWorkflowWarningTitle,
                                        Resources.DatabaseCreation_WarningCustomWorkflow,
                                        RegKeyNameCustomWorkflowWarning,
                                        DismissableWarningDialog.ButtonMode.OkCancel);
                                    if (cancelledDuringCustomWorkflowWarning)
                                    {
                                        HandleError(
                                            String.Format(
                                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_CustomWorkflowCancelled,
                                                resolvedWorkflowFileInfo.FullName), false);
                                        return;
                                    }
                                }
                            }
                            catch (SecurityException e)
                            {
                                // We should at least alert the user of why this is failing so they can take steps to fix it.
                                VsUtils.ShowMessageBox(
                                    Services.ServiceProvider,
                                    String.Format(
                                        CultureInfo.CurrentCulture, Resources.ErrorReadingWritingUserSetting,
                                        RegKeyNameCustomWorkflowWarning, e.Message),
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                                    OLEMSGICON.OLEMSGICON_WARNING);
                            }
                        }

                        _workflowInstance = DatabaseGenerationEngine.CreateDatabaseScriptGenerationWorkflow(
                            _synchronizationContext,
                            Wizard.Project,
                            Wizard.ModelBuilderSettings.Artifact.Uri.LocalPath,
                            resolvedWorkflowFileInfo,
                            templatePath,
                            edm,
                            existingSsdl,
                            existingMsl,
                            databaseSchemaName,
                            Wizard.ModelBuilderSettings.InitialCatalog,
                            Wizard.ModelBuilderSettings.RuntimeProviderInvariantName,
                            Wizard.ModelBuilderSettings.AppConfigConnectionString,
                            Wizard.ModelBuilderSettings.ProviderManifestToken,
                            Wizard.ModelBuilderSettings.Artifact.SchemaVersion,
                            _workflowInstance_WorkflowCompleted,
                            _workflowInstance_UnhandledException);
                    }

                    Wizard.ModelBuilderSettings.WorkflowInstance = _workflowInstance;

                    _workflowInstance.Run();
                }
                catch (Exception e)
                {
                    HandleError(e.Message, true);

                    if (_workflowInstance != null)
                    {
                        CleanupWorkflow();
                    }
                }
            }
        }
        public void RunStarted(
            object automationObject,
            Dictionary <string, string> replacementsDictionary,
            WizardRunKind runKind,
            object[] customParams)
        {
            // the dte is the handle into the VS environment
            var dte             = (DTE2)automationObject;
            var serviceProvider = new ServiceProvider((IOleServiceProvider)dte);

            // get the current project that the wizard is running in
            var project = VsUtils.GetActiveProject(dte);

            Debug.Assert(project != null, "Unable to retrieve ActiveSolutionProject from DTE");

            EnsureCanStartWizard(project, serviceProvider);

            // get file name the user chose
            string modelName;

            replacementsDictionary.TryGetValue("$rootname$", out modelName);

            Debug.Assert(modelName != null, "Unable to get $rootname$ from replacementsDictionary");

            modelName = SanitizeModelName(modelName);

            PopluateReplacementDictionary(project, replacementsDictionary, modelName);

            _modelBuilderSettings = new ModelBuilderSettings
            {
                VSApplicationType   = VsUtils.GetApplicationType(serviceProvider, project),
                WizardKind          = WizardKind.Generate,
                TargetSchemaVersion =
                    EdmUtils.GetEntityFrameworkVersion(project, serviceProvider, useLatestIfNoEF: false),
                NewItemFolder         = GetFolderNameForNewItems(dte, project),
                Project               = project,
                ModelName             = modelName,
                VsTemplatePath        = customParams[0] as string,
                ReplacementDictionary = replacementsDictionary
            };

            var form = new ModelBuilderWizardForm(
                serviceProvider,
                _modelBuilderSettings,
                ModelBuilderWizardForm.WizardMode.PerformAllFunctionality)
            {
                FileAlreadyExistsError = false
            };

            try
            {
                form.Start();
            }
            catch (Exception ex)
            {
                VsUtils.ShowErrorDialog(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        ex.Message));

                ClearErrors();

                throw new WizardCancelledException();
            }


            // the form.FileAlreadyExistsError flag is set in the WizardPageStart. We do it because if we
            // threw this exception directly from the WizardPageStart it would be swallowed and the
            // "Add New Item" dialog would not show up. Throwing the exception from here will make
            // the "Add New Item" dialog re-appear which allows the user to enter a different model name.
            if (form.FileAlreadyExistsError)
            {
                Marshal.ThrowExceptionForHR(VSConstants.E_ABORT);
            }

            // if they cancelled or they didn't cancel, and we didn't log that Finish was pressed,
            // they must have hit the X or an exception happened so cancel
            if (form.WizardCancelled ||
                !form.WizardFinished)
            {
                ClearErrors();
                throw new WizardCancelledException();
            }

            Debug.Assert(ReferenceEquals(_modelBuilderSettings, form.ModelBuilderSettings));
        }
Esempio n. 26
0
        public void SaveNonExistingProfileAndManifest()
        {
            // Arrange
            string testProjectDir = Path.Combine(Path.GetTempPath(), string.Format("savetest-{0}\\", Guid.NewGuid().ToString("N")));

            Directory.CreateDirectory(testProjectDir);
            var             selectedProject = VsUtils.GetSelectedProject();
            PushEnvironment environment     = new PushEnvironment(selectedProject);

            environment.ProjectDirectory = testProjectDir;


            string publishProfilePath = Path.Combine(testProjectDir, "Properties", "PublishProfiles", "push.cf.pubxml");

            environment.ProfileFilePath = publishProfilePath;
            environment.ProjectName     = "mypush";

            string manifestPath = Path.Combine(testProjectDir, "push.yml");

            PublishProfile publishProfile = PublishProfile.Load(environment);

            publishProfile.Organization      = "doriath";
            publishProfile.Space             = "menegroth";
            publishProfile.User              = "******";
            publishProfile.Password          = "******";
            publishProfile.RefreshToken      = "012345";
            publishProfile.SavedPassword     = true;
            publishProfile.ServerUri         = new Uri("https://my.server.url");
            publishProfile.SkipSSLValidation = false;

            publishProfile.Application.BuildpackUrl = "https://my.buildpack.url";
            publishProfile.Application.Command      = "ls";
            publishProfile.Application.DiskQuota    = 1234;
            publishProfile.Application.Domains.Add("domain.com");
            publishProfile.Application.EnvironmentVariables.Add("my", "var");
            publishProfile.Application.HealthCheckTimeout = 54321;
            publishProfile.Application.Hosts.AddRange(new string[] { "one", "two" });
            publishProfile.Application.InstanceCount = 121;
            publishProfile.Application.Memory        = 42;
            publishProfile.Application.Name          = "myapp";
            publishProfile.Application.NoHostName    = true;
            publishProfile.Application.NoRoute       = true;
            publishProfile.Application.Path          = "/app/path";
            publishProfile.Application.Services.AddRange(new string[] { "s1", "s2" });
            publishProfile.Application.StackName         = "leo";
            publishProfile.Application.UseRandomHostName = true;


            // Act
            publishProfile.Save();

            // Assert
            Assert.IsTrue(File.Exists(publishProfilePath));
            Assert.IsTrue(File.Exists(manifestPath));

            var loadedProfile = PublishProfile.Load(environment);

            Assert.AreEqual(publishProfile.Manifest, loadedProfile.Manifest);
            Assert.AreEqual(publishProfile.Organization, loadedProfile.Organization);
            Assert.AreEqual(publishProfile.Password, loadedProfile.Password);
            Assert.AreEqual(publishProfile.RefreshToken, loadedProfile.RefreshToken);
            Assert.AreEqual(publishProfile.SavedPassword, loadedProfile.SavedPassword);
            Assert.AreEqual(publishProfile.ServerUri, loadedProfile.ServerUri);
            Assert.AreEqual(publishProfile.SkipSSLValidation, loadedProfile.SkipSSLValidation);
            Assert.AreEqual(publishProfile.Space, loadedProfile.Space);
            Assert.AreEqual(publishProfile.User, loadedProfile.User);
            Assert.AreEqual(null, loadedProfile.DeployTargetFile);
            Assert.AreEqual("CloudFoundry", publishProfile.WebPublishMethod);

            Assert.AreEqual(publishProfile.Application.BuildpackUrl, loadedProfile.Application.BuildpackUrl);
            Assert.AreEqual(publishProfile.Application.Command, loadedProfile.Application.Command);
            Assert.AreEqual(publishProfile.Application.DiskQuota, loadedProfile.Application.DiskQuota);
            Assert.AreEqual(publishProfile.Application.Domains[0], loadedProfile.Application.Domains[0]);
            Assert.AreEqual(publishProfile.Application.EnvironmentVariables["my"], loadedProfile.Application.EnvironmentVariables["my"]);
            Assert.AreEqual(publishProfile.Application.HealthCheckTimeout, loadedProfile.Application.HealthCheckTimeout);
            Assert.AreEqual(publishProfile.Application.Hosts[0], loadedProfile.Application.Hosts[0]);
            Assert.AreEqual(publishProfile.Application.Hosts[1], loadedProfile.Application.Hosts[1]);
            Assert.AreEqual(publishProfile.Application.InstanceCount, loadedProfile.Application.InstanceCount);
            Assert.AreEqual(publishProfile.Application.Memory, loadedProfile.Application.Memory);
            Assert.AreEqual(publishProfile.Application.Name, loadedProfile.Application.Name);
            Assert.AreEqual(publishProfile.Application.NoHostName, loadedProfile.Application.NoHostName);
            Assert.AreEqual(publishProfile.Application.NoRoute, loadedProfile.Application.NoRoute);
            Assert.AreEqual(publishProfile.Application.Path, loadedProfile.Application.Path);
            Assert.AreEqual(publishProfile.Application.Services[0], loadedProfile.Application.Services[0]);
            Assert.AreEqual(publishProfile.Application.Services[1], loadedProfile.Application.Services[1]);
            Assert.AreEqual(publishProfile.Application.StackName, loadedProfile.Application.StackName);
            Assert.AreEqual(publishProfile.Application.UseRandomHostName, loadedProfile.Application.UseRandomHostName);
        }
        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();
                    }
                }
            }
        }
Esempio n. 28
0
 protected virtual TWizard ResolveWizard(DTE dte)
 {
     return(VsUtils.SafeResolveMefDependency <TWizard>(dte));
 }
Esempio n. 29
0
        internal static void UpdateModelFromDatabase(EntityDesignArtifact artifact)
        {
            VsUtils.EnsureProvider(artifact);

            var serviceProvider = Services.ServiceProvider;
            var project         = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, serviceProvider);

            // set up ModelBuilderSettings for startMode=PerformDatabaseConfigAndSelectTables
            ModelBuilderWizardForm.WizardMode startMode;
            var settings =
                SetupSettingsAndModeForDbPages(
                    serviceProvider, project, artifact, true,
                    ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables,
                    ModelBuilderWizardForm.WizardMode.PerformSelectTablesOnly, out startMode);

            settings.WizardKind = WizardKind.UpdateModel;

            // use existing storage namespace as new storage namespace
            if (null != artifact.StorageModel() &&
                null != artifact.StorageModel().Namespace &&
                !string.IsNullOrEmpty(artifact.StorageModel().Namespace.Value))
            {
                settings.StorageNamespace = artifact.StorageModel().Namespace.Value;
            }

            // use existing model namespace as new model namespace (this only affects the temporary
            // artifact but there is a situation where the C-side EntityContainer has been given the
            // same name as the default model namespace where not setting this causes the temporary
            // artifact to be unreadable because of symbol clashes)
            if (null != artifact.ConceptualModel() &&
                null != artifact.ConceptualModel().Namespace &&
                !string.IsNullOrEmpty(artifact.ConceptualModel().Namespace.Value))
            {
                settings.ModelNamespace = artifact.ConceptualModel().Namespace.Value;
            }

            settings.ModelBuilderEngine = new UpdateModelFromDatabaseModelBuilderEngine();

            // call the ModelBuilderWizardForm
            var form = new ModelBuilderWizardForm(serviceProvider, settings, startMode);

            try
            {
                form.Start();
            }
            catch (Exception e)
            {
                VsUtils.ShowErrorDialog(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        e.Message));
                return;
            }

            // if Wizard was cancelled or the user hit 'X' to close window
            // no need for any further action
            if (form.WizardCancelled ||
                !form.WizardFinished)
            {
                return;
            }

            // Update the app. or web.config, register build providers etc
            ConfigFileHelper.UpdateConfig(settings);

            // use form.ModelBuilderSettings to look at accumulated info and
            // take appropriate action
            var editingContext       = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(artifact.Uri);
            var shouldReloadArtifact = ProcessAccumulatedInfo(editingContext, artifact, settings);

            // If database was configured, add DbContext templates
            if (startMode == ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables)
            {
                var edmxItem = VsUtils.GetProjectItemForDocument(artifact.Uri.LocalPath, serviceProvider);
                new DbContextCodeGenerator().AddDbContextTemplates(edmxItem, settings.UseLegacyProvider);
            }

            // We can reload only after we added EF references to the project otherwise we would get a watermark
            // saying that the schema version does not match the referenced EF version which would not be true.
            // If we reload becuase there was an extension that potentially modified the artifact then it does not matter.
            if (shouldReloadArtifact)
            {
                artifact.ReloadArtifact();
                artifact.IsDirty = true;
            }
        }
Esempio n. 30
0
        internal static void SqlCeUpgradeService_OnUpgradeProject(IVsHierarchy hierarchy, IVsUpgradeLogger logger)
        {
            if (PackageManager.Package != null &&
                PackageManager.Package.ModelManager != null)
            {
                // since this is about retargeting EDMX files on disk, no need to process other file extensions from any converters
                var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx);
                fileFinder.FindInProject(hierarchy);

                var project = VSHelpers.GetProject(hierarchy);

                // skip the step if it is a miscellaneous project.
                if (project != null &&
                    !VsUtils.IsMiscellaneousProject(project))
                {
                    IDictionary <string, object> documentMap = new Dictionary <string, object>();
                    foreach (var vsFileInfo in fileFinder.MatchingFiles)
                    {
                        try
                        {
                            var projectItem = VsUtils.GetProjectItem(hierarchy, vsFileInfo.ItemId);

                            // Dev 10 bug 648969: skip the process for astoria edmx file.
                            if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1)))
                            {
                                continue;
                            }

                            // Check whether project item is a linked item
                            var isLinkItem = VsUtils.IsLinkProjectItem(projectItem);

                            if (!isLinkItem)
                            {
                                var doc = MetadataConverterDriver.SqlCeInstance.Convert(SafeLoadXmlFromPath(vsFileInfo.Path));
                                if (doc != null)
                                {
                                    documentMap.Add(vsFileInfo.Path, doc);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var errMsg = String.Format(
                                CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, vsFileInfo.Path, ex.Message);
                            logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, vsFileInfo.Path, errMsg);
                            return;
                        }
                    }

                    if (documentMap.Count > 0)
                    {
                        VsUtils.WriteCheckoutXmlFilesInProject(documentMap);
                    }

                    // now update the config file as needed
                    var configFileUtils = new ConfigFileUtils(project, PackageManager.Package);
                    try
                    {
                        var configXmlDoc = configFileUtils.LoadConfig();
                        if (configXmlDoc != null) // check config file exists
                        {
                            if (ConnectionManager.UpdateSqlCeProviderInConnectionStrings(configXmlDoc))
                            {
                                configFileUtils.SaveConfig(configXmlDoc);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var errMsg = String.Format(
                            CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, configFileUtils.GetConfigPath(), ex.Message);
                        logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg);
                    }
                }
            }
        }