예제 #1
0
        internal static ProjectItem FindOrCreateAppDataFolder(IServiceProvider serviceProvider, Project project)
        {
            var projectSystem = VsUtils.GetApplicationType(serviceProvider, project);

            if (VisualStudioProjectSystem.WebApplication != projectSystem &&
                VisualStudioProjectSystem.Website != projectSystem)
            {
                Debug.Fail("can only be called for Web App or Web Site projects");
                return(null);
            }

            // see if App_Data folder already exists
            foreach (ProjectItem projectItem in project.ProjectItems)
            {
                if (0 == string.Compare(projectItem.Name, DATAFOLDERNAME, StringComparison.OrdinalIgnoreCase))
                {
                    return(projectItem);
                }
            }

            // No data folder found. Create one.
            var dataFolderProjectItem = project.ProjectItems.AddFolder(DATAFOLDERNAME, Constants.vsProjectItemKindPhysicalFolder);

            Debug.Assert(dataFolderProjectItem != null, "Adding the App_Data folder failed for project " + project.UniqueName);
            return(dataFolderProjectItem);
        }
예제 #2
0
        private void LoadDesignerInfoAndDescriptors(EditingContext editingContext, EFArtifact artifact)
        {
            if (artifact != null &&
                artifact.DesignerInfo() != null)
            {
                DesignerInfo connectionDesignerInfo = null;
                DesignerInfo optionsDesignerInfo    = null;

                var foundConnectionDesignerInfo = artifact.DesignerInfo()
                                                  .TryGetDesignerInfo(ConnectionDesignerInfo.ElementName, out connectionDesignerInfo);

                if (foundConnectionDesignerInfo)
                {
                    var connectionDesigner = connectionDesignerInfo as ConnectionDesignerInfo;
                    Debug.Assert(connectionDesigner != null, "DesignerInfo with element name 'Connection' must be a ConnectionDesignerInfo");

                    if (connectionDesigner != null)
                    {
                        // if the owner of the edmx file is a website, then we can
                        // only have one possible value (EmbedInOutputAssembly) for metadata artifact processing
                        // however the item template just adds CopyToOutputDirectory, so we need to fix it
                        var project = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, PackageManager.Package);
                        if (project != null)
                        {
                            var appType = VsUtils.GetApplicationType(Services.ServiceProvider, project);
                            if (appType == VisualStudioProjectSystem.Website)
                            {
                                var mapDefault = ConnectionManager.GetMetadataArtifactProcessingDefault();
                                if (connectionDesigner.MetadataArtifactProcessingProperty != null &&
                                    connectionDesigner.MetadataArtifactProcessingProperty.ValueAttr.Value != mapDefault)
                                {
                                    var cpc = new CommandProcessorContext(
                                        editingContext, EfiTransactionOriginator.PropertyWindowOriginatorId,
                                        Resources.Tx_ChangeMetadataArtifactProcessing);
                                    var cmd =
                                        new UpdateDefaultableValueCommand <string>(
                                            connectionDesigner.MetadataArtifactProcessingProperty.ValueAttr, mapDefault);
                                    CommandProcessor.InvokeSingleCommand(cpc, cmd);
                                }
                            }
                        }

                        _EFConnectionDesignerInfoDescriptor = new EFConnectionDesignerInfoDescriptor();
                        _EFConnectionDesignerInfoDescriptor.Initialize(connectionDesigner, editingContext);
                    }
                }

                var foundOptionsDesignerInfo = artifact.DesignerInfo()
                                               .TryGetDesignerInfo(OptionsDesignerInfo.ElementName, out optionsDesignerInfo);

                if (foundOptionsDesignerInfo)
                {
                    _EFOptionsDesignerInfoDescriptor = new EFOptionsDesignerInfoDescriptor();
                    _EFOptionsDesignerInfoDescriptor.Initialize(optionsDesignerInfo as OptionsDesignerInfo, editingContext);
                }
            }
        }
        protected override void PopulateMappingForSelectedObject(EFEntityModelDescriptor selectedObject)
        {
            var documentPath = selectedObject.EditingContext.GetEFArtifactService().Artifact.Uri.LocalPath;
            var project      = VSHelpers.GetProjectForDocument(documentPath, PackageManager.Package);

            if (project != null)
            {
                var appType = VsUtils.GetApplicationType(Services.ServiceProvider, project);
                if (appType != VisualStudioProjectSystem.Website)
                {
                    AddMapping(
                        ConnectionDesignerInfo.MAP_CopyToOutputDirectory, Resources.PropertyWindow_DisplayName_MAP_CopyToOutputDirectory);
                }
            }
            else
            {
                AddMapping(ConnectionDesignerInfo.MAP_CopyToOutputDirectory, Resources.PropertyWindow_DisplayName_MAP_CopyToOutputDirectory);
            }
            AddMapping(ConnectionDesignerInfo.MAP_EmbedInOutputAssembly, Resources.PropertyWindow_DisplayName_MAP_EmbedInOutputAssembly);
        }
예제 #4
0
        internal static ProjectItems GetDefaultCollectionForLocalDataFile(IServiceProvider serviceProvider, Project project)
        {
            // if Web Site project then default location is App_Data directory
            var projectSystem = VsUtils.GetApplicationType(serviceProvider, project);

            if (VisualStudioProjectSystem.WebApplication == projectSystem ||
                VisualStudioProjectSystem.Website == projectSystem)
            {
                var dataFolderProjectItem = FindOrCreateAppDataFolder(serviceProvider, project);
                if (null == dataFolderProjectItem)
                {
                    Debug.Fail("Could not find or create App_Data Folder for project " + project.UniqueName);
                }
                else
                {
                    return(dataFolderProjectItem.ProjectItems);
                }
            }

            // if not Web App or Web Site then default location is just root of project
            return(project.ProjectItems);
        }
예제 #5
0
        int IVsEditorFactoryNotify.NotifyItemAdded(uint grfEFN, IVsHierarchy pHier, uint itemid, string pszMkDocument)
        {
            object o;
            var    hr = pHier.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out o);

            if (NativeMethods.Succeeded(hr))
            {
                var projectItem = o as ProjectItem;
                if (projectItem != null &&
                    VsUtils.EntityFrameworkSupportedInProject(projectItem.ContainingProject, ServiceProvider, allowMiscProject: false))
                {
                    if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1)))
                    {
                        // if the EDMX has a data services node, don't add the SingleFileGenerator, etc.
                        return(VSConstants.S_OK);
                    }

                    IOleServiceProvider oleSP;
                    pHier.GetSite(out oleSP);
                    using (var sp = new ServiceProvider(oleSP))
                    {
                        var appType = VsUtils.GetApplicationType(sp, projectItem.ContainingProject);

                        // set the project item properties
                        SetProjectItemProperties(projectItem, appType);
                    }

                    if (grfEFN != (uint)__EFNFLAGS.EFN_ClonedFromTemplate)
                    {
                        // we're not adding from template i.e. Add Existing Item
                        var referenceFileNames = GetReferencesFromTemplateForProject(projectItem.ContainingProject);
                        AddMissingReferences(projectItem, referenceFileNames);
                        AddBuildProvider(projectItem);
                    }
                }
            }

            return(VSConstants.S_OK);
        }
        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));
        }
예제 #7
0
        internal static void SetupSettingsAndModeForDbPages(
            IServiceProvider sp,
            Project project,
            EFArtifact artifact,
            bool checkDatabaseConnection,
            ModelBuilderWizardForm.WizardMode noConnectionMode,
            ModelBuilderWizardForm.WizardMode existingConnectionMode,
            out ModelBuilderWizardForm.WizardMode startMode,
            out ModelBuilderSettings settings)
        {
            var conceptualEntityModel = artifact.ConceptualModel();

            Debug.Assert(conceptualEntityModel != null, "Null Conceptual Entity Model");
            var entityContainer = conceptualEntityModel.FirstEntityContainer as ConceptualEntityContainer;

            Debug.Assert(entityContainer != null, "Null Conceptual Entity Container");
            var entityContainerName = entityContainer.LocalName.Value;

            // set up ModelBuilderSettings for startMode=noConnectionMode
            startMode = noConnectionMode;
            settings  = new ModelBuilderSettings();
            var appType = VsUtils.GetApplicationType(sp, project);

            settings.VSApplicationType = appType;
            settings.AppConfigConnectionPropertyName = entityContainerName;
            settings.Artifact          = artifact;
            settings.UseLegacyProvider = ModelHelper.GetDesignerPropertyValueFromArtifactAsBool(
                OptionsDesignerInfo.ElementName,
                OptionsDesignerInfo.AttributeUseLegacyProvider,
                OptionsDesignerInfo.UseLegacyProviderDefault,
                artifact);
            settings.TargetSchemaVersion = artifact.SchemaVersion;
            settings.Project             = project;
            settings.ModelPath           = artifact.Uri.LocalPath;

            // Get the provider manifest token from the existing SSDL.
            // We don't want to attempt to get it from provider services since this requires a connection
            // which will severely impact the performance of Model First in disconnected scenarios.
            settings.ProviderManifestToken = DatabaseGenerationEngine.GetProviderManifestTokenDisconnected(artifact);

            // Change startMode and settings appropriately depending on whether there is an existing connection string and whether we can/should connect
            // to the database
            var connectionString = ConnectionManager.GetConnectionStringObject(project, entityContainerName);

            if (connectionString != null)
            {
                var ecsb = connectionString.Builder;
                var runtimeProviderName                = ecsb.Provider;
                var runtimeProviderConnectionString    = ecsb.ProviderConnectionString;
                var designTimeProviderConnectionString = connectionString.GetDesignTimeProviderConnectionString(project);
                var initialCatalog = String.Empty;

                if (checkDatabaseConnection)
                {
                    // This path will check to make sure that we can connect to an existing database before changing the start mode to 'existingConnection'
                    IVsDataConnection dataConnection = null;
                    try
                    {
                        var dataConnectionManager = sp.GetService(typeof(IVsDataConnectionManager)) as IVsDataConnectionManager;
                        Debug.Assert(dataConnectionManager != null, "Could not find IVsDataConnectionManager");

                        var dataProviderManager = sp.GetService(typeof(IVsDataProviderManager)) as IVsDataProviderManager;
                        Debug.Assert(dataProviderManager != null, "Could not find IVsDataProviderManager");

                        if (dataConnectionManager != null &&
                            dataProviderManager != null)
                        {
                            // this will either get an existing connection or attempt to create a new one
                            dataConnection = DataConnectionUtils.GetDataConnection(
                                dataConnectionManager,
                                dataProviderManager,
                                connectionString.DesignTimeProviderInvariantName,
                                designTimeProviderConnectionString);
                            Debug.Assert(
                                dataConnection != null,
                                "Could not find the IVsDataConnection; an exception should have been thrown if this was the case");
                            if (dataConnection != null)
                            {
                                VsUtils.EnsureProvider(runtimeProviderName, settings.UseLegacyProvider, project, sp);

                                if (CanCreateAndOpenConnection(
                                        new StoreSchemaConnectionFactory(),
                                        runtimeProviderName,
                                        connectionString.DesignTimeProviderInvariantName,
                                        designTimeProviderConnectionString))
                                {
                                    startMode      = existingConnectionMode;
                                    initialCatalog = DataConnectionUtils.GetInitialCatalog(dataProviderManager, dataConnection);
                                }
                            }
                        }
                    }
                    catch
                    {
                        // do nothing - we will go to WizardPageDbConfig which is
                        // what we want if the DB connection fails
                    }
                    finally
                    {
                        // Close the IVsDataConnection
                        if (dataConnection != null)
                        {
                            try
                            {
                                dataConnection.Close();
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                else
                {
                    // This path will just parse the existing connection string in order to change the start mode. This is ideal for features
                    // that do not need a database connection -- the information in the connection string is enough.
                    startMode      = existingConnectionMode;
                    initialCatalog = DataConnectionUtils.GetInitialCatalog(
                        connectionString.DesignTimeProviderInvariantName, designTimeProviderConnectionString);
                }

                if (startMode == existingConnectionMode)
                {
                    // the invariant name and connection string came from app.config, so they are "runtime" invariant names and not "design-time"
                    // (Note: it is OK for InitialCatalog to be null at this stage e.g. from a provider who do not support the concept of Initial Catalog)
                    settings.SetInvariantNamesAndConnectionStrings(
                        project,
                        runtimeProviderName,
                        runtimeProviderConnectionString,
                        runtimeProviderConnectionString,
                        false);
                    settings.InitialCatalog = initialCatalog;
                    settings.AppConfigConnectionPropertyName = entityContainerName;
                    settings.SaveConnectionStringInAppConfig = false;

                    VsUtils.EnsureProvider(runtimeProviderName, settings.UseLegacyProvider, project, sp);
                }
            }
        }
예제 #8
0
 public VisualStudioProjectSystem GetApplicationType(IServiceProvider serviceProvider, Project project)
 {
     return(VsUtils.GetApplicationType(serviceProvider, project));
 }