public void RunStarted_creates_valid_context_name_if_safeitemname_is_not_valid_identifier() { var mockVsUtils = new Mock <IVsUtils>(); var wizard = new OneEFWizard(vsUtils: mockVsUtils.Object); var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(new[] { new KeyValuePair <string, string>(string.Empty, string.Empty) }); var settings = new ModelBuilderSettings { VSApplicationType = VisualStudioProjectSystem.WebApplication }; var replacenentsDictionary = new Dictionary <string, string> { { "$safeitemname$", "3My.Con text" }, { "$rootnamespace$", "Project" } }; wizard.RunStarted(settings, mockCodeGenerator.Object, replacenentsDictionary); mockCodeGenerator.Verify( g => g.Generate( It.IsAny <DbModel>(), "Project", /*contextClassName*/ "_3MyContext", /*connectionStringName*/ "_3MyContext"), Times.Once()); }
internal void RunStarted(ModelBuilderSettings modelBuilderSettings, CodeFirstModelGenerator codeFirstModelGenerator, Dictionary <string, string> replacementsDictionary) { try { var contextClassName = new CodeIdentifierUtils( modelBuilderSettings.VSApplicationType, _vsUtils.GetLanguageForProject(modelBuilderSettings.Project)) .CreateValidIdentifier(replacementsDictionary["$safeitemname$"]); _generatedCode = codeFirstModelGenerator.Generate( modelBuilderSettings.ModelBuilderEngine != null ? modelBuilderSettings.ModelBuilderEngine.Model : null, replacementsDictionary["$rootnamespace$"], contextClassName, modelBuilderSettings.SaveConnectionStringInAppConfig ? modelBuilderSettings.AppConfigConnectionPropertyName : contextClassName).ToList(); Debug.Assert(_generatedCode.Count > 0, "code has not been generated"); replacementsDictionary["$contextfilecontents$"] = _generatedCode[0].Value; } catch (CodeFirstModelGenerationException e) { _vsUtils.ShowErrorDialog( string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", e.Message, Environment.NewLine, e.InnerException)); } }
private static void UpdateConfig(ICollection<string> metadataFiles, ModelBuilderSettings settings) { var statusMessage = VsUtils.IsWebProject(settings.VSApplicationType) ? String.Format(CultureInfo.CurrentCulture, Resources.Engine_WebConfigSuccess, VsUtils.WebConfigFileName) : String.Format(CultureInfo.CurrentCulture, Resources.Engine_AppConfigSuccess, VsUtils.AppConfigFileName); try { var manager = PackageManager.Package.ConnectionManager; manager.AddConnectionString( settings.Project, settings.VSApplicationType, metadataFiles, settings.AppConfigConnectionPropertyName, settings.AppConfigConnectionString, settings.RuntimeProviderInvariantName); } catch (Exception e) { statusMessage = String.Format( CultureInfo.CurrentCulture, VsUtils.IsWebProject(settings.VSApplicationType) ? Resources.Engine_WebConfigException : Resources.Engine_AppConfigException, e.Message); } VsUtils.LogOutputWindowPaneMessage(settings.Project, statusMessage); }
public void RunStarted_uses_context_class_name_if_SaveConnectionStringInAppConfig_false() { var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(new[] { new KeyValuePair <string, string>() }); var modelBuilderSettings = new ModelBuilderSettings { SaveConnectionStringInAppConfig = false, AppConfigConnectionPropertyName = "ConnString" }; var replacementsDictionary = new Dictionary <string, string> { { "$safeitemname$", "MyContext" }, { "$rootnamespace$", "Project.Data" } }; new OneEFWizard(vsUtils: Mock.Of <IVsUtils>()) .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary); mockCodeGenerator.Verify(g => g.Generate(It.IsAny <DbModel>(), "Project.Data", "MyContext", "MyContext"), Times.Once()); }
internal GatherAndReturnSprocInfo(IList<EntityStoreSchemaFilterEntry> newFunctionEntries, ModelBuilderSettings modelBuilderSettings) { Debug.Assert(null != newFunctionEntries, "newFunctionEntries should not be null"); Debug.Assert(null != modelBuilderSettings, "modelBuilderSettings should not be null"); _newFunctionEntries = newFunctionEntries; _modelBuilderSettings = modelBuilderSettings; }
public void OnDeactivate_does_not_update_settings_if_model_file_already_exists() { var mockDte = new MockDTE(".NETFramework, Version=v4.5", references: new Reference[0]); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", Project = mockDte.Project }; var wizard = ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider); var mockWizardPageStart = new Mock <WizardPageStart>(wizard, null) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); Assert.Null(modelBuilderSettings.ModelPath); Assert.True(wizard.FileAlreadyExistsError); }
public void OnDeactivate_updates_model_settings_if_model_file_does_not_exist_for_empty_model() { var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", ReplacementDictionary = new Dictionary <string, string>(), TargetSchemaVersion = EntityFrameworkVersion.Version3 }; var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality); var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(true); mockWizardPageStart .Protected() .Setup <int>("GetSelectedOptionIndex") .Returns(WizardPageStart.GenerateEmptyModelIndex); mockWizardPageStart.Object.OnDeactivate(); Assert.Equal(ModelGenerationOption.EmptyModel, modelBuilderSettings.GenerationOption); Assert.False(wizard.FileAlreadyExistsError); Assert.Equal(@"C:\temp\myModel.edmx", modelBuilderSettings.ModelPath); Assert.True(modelBuilderSettings.ReplacementDictionary.Any()); Assert.Null(modelBuilderSettings.ModelBuilderEngine); }
public void OnDeactivate_creates_and_verifies_model_path() { var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel" }; var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality); var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); mockWizardPageStart .Protected() .Verify("VerifyModelFilePath", Times.Once(), @"C:\temp\myModel.edmx"); }
public void RunStarted_saves_context_generated_code_replacementsDictionary_as_contextfilecontents() { var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(new[] { new KeyValuePair <string, string>("MyContext", "context code") }); var modelBuilderSettings = new ModelBuilderSettings { SaveConnectionStringInAppConfig = true, AppConfigConnectionPropertyName = "ConnString" }; var replacementsDictionary = new Dictionary <string, string> { { "$safeitemname$", "MyContext" }, { "$rootnamespace$", "Project.Data" } }; new OneEFWizard(vsUtils: Mock.Of <IVsUtils>()) .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary); Assert.Equal("context code", replacementsDictionary["$contextfilecontents$"]); }
// internal for testing, settings parameter to allow testing without messing with the static variable internal void RunFinished(ModelBuilderSettings settings, string targetDirectory) { // null indicates an error when generating code if (_generatedCode == null) { return; } var project = settings.Project; var filesToSave = _generatedCode.Skip(1) .ToDictionary(kvp => Path.Combine(targetDirectory, kvp.Key), kvp => (object)kvp.Value); try { _vsUtils.WriteCheckoutTextFilesInProject(filesToSave); } finally { // even if saving fails we actually might have created some files // and we should add them to the project AddFilesToProject(project, filesToSave.Keys); } _configFileUtils = _configFileUtils ?? new ConfigFileUtils( project, PackageManager.Package, settings.VSApplicationType); UpdateConfigFile(settings); }
private void UpdateConfigFile(ModelBuilderSettings settings) { if (!settings.SaveConnectionStringInAppConfig) { return; } var connectionString = ConnectionManager.InjectEFAttributesIntoConnectionString( settings.AppConfigConnectionString, settings.RuntimeProviderInvariantName); _configFileUtils.GetOrCreateConfigFile(); var existingConnectionStrings = ConnectionManager.GetExistingConnectionStrings(_configFileUtils); string existingConnectionString; if (existingConnectionStrings.TryGetValue(settings.AppConfigConnectionPropertyName, out existingConnectionString) && string.Equals(existingConnectionString, connectionString)) { // An element with the same name and connectionString already exists - no need to update. // This can happen if the user chooses an existing connection and connection name on the WizardPageDbConfig page. return; } var configXml = _configFileUtils.LoadConfig(); ConnectionManager.AddConnectionStringElement( configXml, settings.AppConfigConnectionPropertyName, connectionString, settings.RuntimeProviderInvariantName); _configFileUtils.SaveConfig(configXml); }
protected static void GenerateModel(ModelBuilderSettings settings) { using (new VsUtils.HourglassHelper()) { var mbe = settings.ModelBuilderEngine; mbe.GenerateModel(settings); } }
// method to compare Model Namespace and Entity Container names - centralized for maintenance internal static bool ModelNamespaceAndEntityContainerNameSame(ModelBuilderSettings modelBuilderSettings) { var entityContainerName = modelBuilderSettings.AppConfigConnectionPropertyName; var modelNamespaceName = modelBuilderSettings.ModelNamespace; return(!string.IsNullOrEmpty(entityContainerName) && !string.IsNullOrEmpty(modelNamespaceName) && entityContainerName.ToUpper(CultureInfo.CurrentCulture) == modelNamespaceName.ToUpper(CultureInfo.CurrentCulture)); }
public ModelGenerator(ModelBuilderSettings settings, string storeModelNamespace) { Debug.Assert(settings != null, "settings != null"); Debug.Assert( !string.IsNullOrWhiteSpace(storeModelNamespace), "namespace must not be null or empty string."); _settings = settings; _storeModelNamespace = storeModelNamespace; }
private static bool CodeFirstAllowed(ModelBuilderSettings settings) { Debug.Assert(settings != null, "settings must not be null"); // OneEF supported only for EF6 or if the project does not have any references to EF var entityFrameworkAssemblyVersion = VsUtils.GetInstalledEntityFrameworkAssemblyVersion(settings.Project); return(entityFrameworkAssemblyVersion == null || entityFrameworkAssemblyVersion >= RuntimeVersion.Version6); }
public virtual void GenerateModel(ModelBuilderSettings settings, IVsUtils vsUtils = null, ModelBuilderEngineHostContext hostContext = null) { if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase && String.IsNullOrEmpty(settings.DesignTimeConnectionString)) { throw new ArgumentOutOfRangeException(Resources.Engine_EmptyConnStringErrorMsg); } var generatingModelWatch = Stopwatch.StartNew(); hostContext = hostContext ?? new VSModelBuilderEngineHostContext(settings); vsUtils = vsUtils ?? new VsUtilsWrapper(); // Clear out the ModelGenErrorCache before ModelGen begins PackageManager.Package.ModelGenErrorCache.RemoveErrors(settings.ModelPath); var errors = new List<EdmSchemaError>(); try { var storeModelNamespace = GetStoreNamespace(settings); Model = GenerateModels(storeModelNamespace, settings, errors); ProcessModel(Model, storeModelNamespace, settings, hostContext, errors); hostContext.LogMessage( FormatMessage( errors.Any() ? Resources.Engine_ModelGenErrors : Resources.Engine_ModelGenSuccess, Path.GetFileName(settings.ModelPath))); if (errors.Any()) { PackageManager.Package.ModelGenErrorCache.AddErrors(settings.ModelPath, errors); } } catch (Exception e) { hostContext.LogMessage(FormatMessage(Resources.Engine_ModelGenException, e)); // The exception we re-throw will get swallowed in the message pump and therefore we need to show the message box here. // It will also prevent the form.WizardFinished from being set to true which will cause cancelling the wizard and // therefore block adding new project items to the project as well as ModelObjectItemWizardFrom.RunFinished method. vsUtils.ShowErrorDialog(FormatMessage(Resources.Engine_ModelGenExceptionMessageBox, e.GetType().Name, e.Message)); throw; } finally { generatingModelWatch.Stop(); hostContext.LogMessage(FormatMessage(Resources.LoadingDBMetadataTimeMsg, settings.LoadingDBMetatdataTime)); hostContext.LogMessage(FormatMessage(Resources.GeneratingModelTimeMsg, generatingModelWatch.Elapsed)); } }
protected virtual void UpdateDesignerInfo(EdmxHelper edmxHelper, ModelBuilderSettings settings) { Debug.Assert(edmxHelper != null); edmxHelper.UpdateDesignerOptionProperty( OptionsDesignerInfo.AttributeEnablePluralization, settings.UsePluralizationService); edmxHelper.UpdateDesignerOptionProperty( OptionsDesignerInfo.AttributeIncludeForeignKeysInModel, settings.IncludeForeignKeysInModel); edmxHelper.UpdateDesignerOptionProperty( OptionsDesignerInfo.AttributeUseLegacyProvider, settings.UseLegacyProvider); }
// <summary> // Helper method used to show the ProgressDialog and collect return type information about sprocs // </summary> // <param name="owner">Window that owns the dialog</param> // <param name="newFunctionEntries">list of Functions for which we should collect information</param> // <param name="modelBuilderSettings">ModelBuilderSettings where collected information will be stored</param> public static DialogResult ShowProgressDialog( IWin32Window owner, IList<EntityStoreSchemaFilterEntry> newFunctionEntries, ModelBuilderSettings modelBuilderSettings) { var args = new GatherAndReturnSprocInfo(newFunctionEntries, modelBuilderSettings); using (var pd = new ProgressDialog( Design.Resources.RetrievingSprocReturnTypeProgressDialogTitle, Design.Resources.RetrievingSprocReturnTypeProgressDialogDescription, Design.Resources.RetrievingSprocReturnTypeProgressDialogInitialStatus, GatherAndStoreSchemaProcedureInformation, args)) { return pd.ShowDialog(owner); } }
public static ModelBuilderWizardForm CreateWizard(ModelGenerationOption generationOption = (ModelGenerationOption)(-1), Project project = null, string modelPath = null, IServiceProvider serviceProvider = null) { var modelBuilderSettings = new ModelBuilderSettings { Project = project ?? MockDTE.CreateProject(), GenerationOption = generationOption, ModelPath = modelPath }; return CreateWizard(modelBuilderSettings, serviceProvider); }
/// <summary> /// Constructor to start the wizard in the specified mode /// </summary> public ModelBuilderWizardForm( IServiceProvider serviceProvider, ModelBuilderSettings modelBuilderSettings, WizardMode wizardMode) { _wizardMode = wizardMode; _serviceProvider = serviceProvider; Debug.Assert(modelBuilderSettings.Project != null, "modelBuilderSettings.Project != null"); _modelBuilderSettings = modelBuilderSettings; Initialize(); }
public static ModelBuilderWizardForm CreateWizard(ModelGenerationOption generationOption = (ModelGenerationOption)(-1), Project project = null, string modelPath = null, IServiceProvider serviceProvider = null) { var modelBuilderSettings = new ModelBuilderSettings { Project = project ?? MockDTE.CreateProject(), GenerationOption = generationOption, ModelPath = modelPath }; return(CreateWizard(modelBuilderSettings, serviceProvider)); }
public static ModelBuilderWizardForm CreateWizard(ModelBuilderSettings modelBuilderSettings, IServiceProvider serviceProvider = null) { var mockWizard = new Mock <ModelBuilderWizardForm>( serviceProvider ?? Mock.Of <IServiceProvider>(), modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality) { CallBase = true }; mockWizard.Protected().Setup("InitializeWizardPages"); return(mockWizard.Object); }
// internal virtual to allow mocking protected override void ProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings, ModelBuilderEngineHostContext hostContext, List<EdmSchemaError> errors) { Edmx = XDocument.Parse(_initialModelContentsFactory.GetInitialModelContents(settings.TargetSchemaVersion)); var edmxHelper = new EdmxHelper(Edmx); edmxHelper.UpdateEdmxFromModel(model, storeModelNamespace, settings.ModelNamespace, errors); // load extensions that want to update model after the wizard has run. hostContext.DispatchToModelGenerationExtensions(); UpdateDesignerInfo(edmxHelper, settings); }
public static ModelBuilderWizardForm CreateWizard(ModelBuilderSettings modelBuilderSettings, IServiceProvider serviceProvider = null) { var mockWizard = new Mock<ModelBuilderWizardForm>( serviceProvider ?? Mock.Of<IServiceProvider>(), modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality) { CallBase = true }; mockWizard.Protected().Setup("InitializeWizardPages"); return mockWizard.Object; }
// <summary> // Constructor to start the wizard in the specified mode // </summary> public ModelBuilderWizardForm( IServiceProvider serviceProvider, ModelBuilderSettings modelBuilderSettings, WizardMode wizardMode) { _wizardMode = wizardMode; _serviceProvider = serviceProvider; Debug.Assert(modelBuilderSettings.Project != null, "modelBuilderSettings.Project != null"); _modelBuilderSettings = modelBuilderSettings; Initialize(); }
// internal static to make it more testable internal static CommandProcessor PrepareCommandsAndIntegrityChecks( ModelBuilderSettings modelBuilderSettings, EditingContext editingContext, EntityDesignArtifact designArtifact) { Debug.Assert(modelBuilderSettings != null, "modelBuilderSettings != null"); Debug.Assert(editingContext != null, "editingContext != null"); Debug.Assert(designArtifact != null, "artifact != null"); var commands = new List <Command>(); if (modelBuilderSettings.NewFunctionSchemaProcedures != null && modelBuilderSettings.NewFunctionSchemaProcedures.Count > 0) { // user selected to create new FunctionImports, but don't create the composable ones as these have already been created by the runtime ProgressDialogHelper.ProcessStoredProcedureReturnTypeInformation( designArtifact, modelBuilderSettings.NewFunctionSchemaProcedures, commands, shouldCreateComposableFunctionImports: false); } else { commands.AddRange(CreateRemoveFunctionImportCommands(designArtifact)); } // for SqlServer and SqlServerCe we need to add integrity checks - see the comment below if (commands.Count > 0 || designArtifact.IsSqlFamilyProvider()) { // set up CommandProcessorContext var cpc = new CommandProcessorContext( editingContext, EfiTransactionOriginator.CreateNewModelId, Resources.Tx_CreateFunctionImport); // We propagate facets by default only for Sql Server or Sql Server CE since for other providers facets in C-Space might be intentionally // out of sync with facets from S-Space and we should not break this. For Sql Server and Sql Server CE facets should be in sync in most cases. if (designArtifact.IsSqlFamilyProvider()) { // Add integrity check to enforce synchronizing C-side Property facets to S-side values PropagateStoragePropertyFacetsToConceptualModel.AddRule(cpc, designArtifact); } return(new CommandProcessor(cpc, commands)); } // no commands or integrity checks to run return(null); }
internal static ICollection<EntityStoreSchemaFilterEntry> GetFunctionsFilterEntries( ModelBuilderSettings settings, DoWorkEventArgs args) { ICollection<EntityStoreSchemaFilterEntry> entries; if (EdmFeatureManager.GetComposableFunctionImportFeatureState(settings.TargetSchemaVersion).IsEnabled()) { entries = ExecuteDatabaseMetadataQuery( SelectFunctionsESqlQuery, EntityStoreSchemaFilterObjectTypes.Function, settings, args); } else { entries = ExecuteDatabaseMetadataQuery( SelectFunctionsESqlQueryBeforeV3, EntityStoreSchemaFilterObjectTypes.Function, settings, args); } return entries; }
public void OnDeactivate_updates_model_settings_if_model_file_does_not_exist_for_generate_from_database() { var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", ReplacementDictionary = new Dictionary <string, string>(), TargetSchemaVersion = EntityFrameworkVersion.Version3, VsTemplatePath = "fake.vstemplate" }; var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality); var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(true); mockWizardPageStart .Protected() .Setup <int>("GetSelectedOptionIndex") .Returns(WizardPageStart.GenerateFromDatabaseIndex); mockWizardPageStart .Protected() .Setup <string>("GetEdmxTemplateContent", ItExpr.IsAny <string>()) .Returns("vstemplate contents"); mockWizardPageStart.Object.OnDeactivate(); Assert.Equal(ModelGenerationOption.GenerateFromDatabase, modelBuilderSettings.GenerationOption); Assert.False(wizard.FileAlreadyExistsError); Assert.Equal(@"C:\temp\myModel.edmx", modelBuilderSettings.ModelPath); // replacement dictionary updated lazily Assert.False(modelBuilderSettings.ReplacementDictionary.Any()); Assert.NotNull(modelBuilderSettings.ModelBuilderEngine); mockWizardPageStart .Protected() .Verify("GetEdmxTemplateContent", Times.Once(), "fake.vstemplate"); }
private static ModelBuilderWizardForm CreateModelBuilderWizardForm(ModelGenerationOption modelGenerationOption) { var mockDte = new MockDTE(".NETFramework, Version=v4.5", references: new Reference[0]); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", ReplacementDictionary = new Dictionary <string, string>(), TargetSchemaVersion = EntityFrameworkVersion.Version3, VsTemplatePath = "fake.vstemplate", Project = mockDte.Project, GenerationOption = modelGenerationOption }; var wizard = ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider); return(wizard); }
private static void Run_OnDeactivate_creates_and_verifies_model_path( ModelGenerationOption generationOption, LangEnum language, bool isWebSite, string expectedExtension) { var mockDte = new MockDTE( ".NETFramework, Version=v4.5", isWebSite ? MockDTE.CreateWebSite( properties: new Dictionary <string, object> { { "CurrentWebsiteLanguage", language == LangEnum.CSharp ? "C#" : "VB" } }, assemblyReferences: new AssemblyReference[0]) : MockDTE.CreateProject( kind: language == LangEnum.CSharp ? MockDTE.CSharpProjectKind : MockDTE.VBProjectKind, assemblyReferences: new Reference[0])); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", Project = mockDte.Project, GenerationOption = generationOption }; var mockWizardPageStart = new Mock <WizardPageStart>(ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider), null) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); mockWizardPageStart .Protected() .Verify("VerifyModelFilePath", Times.Once(), @"C:\temp\myModel" + expectedExtension); }
internal static bool ValidateNamespace(TextBox modelNamespaceTextBox, ModelBuilderSettings modelBuilderSettings) { if (!EdmUtils.IsValidModelNamespace(modelNamespaceTextBox.Text)) { var s = ModelWizard.Properties.Resources.ConnectionStringNonValidIdentifier; VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelNamespaceTextBox.Text)); modelNamespaceTextBox.Focus(); return(false); } // the Model Namespace and the Entity Container name must differ if (ModelBuilderWizardForm.ModelNamespaceAndEntityContainerNameSame(modelBuilderSettings)) { var s = ModelWizard.Properties.Resources.NamespaceAndEntityContainerSame; VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelBuilderSettings.AppConfigConnectionPropertyName)); modelNamespaceTextBox.Focus(); return(false); } return(true); }
private static string GetNewModelFileExtension(ModelBuilderSettings settings) { switch (settings.GenerationOption) { case ModelGenerationOption.GenerateFromDatabase: case ModelGenerationOption.EmptyModel: return("edmx"); default: Debug.Assert( settings.GenerationOption == ModelGenerationOption.EmptyModelCodeFirst || settings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase, "unexpected generation option"); return (VsUtils.GetLanguageForProject(settings.Project) == LangEnum.VisualBasic ? FileExtensions.VbExt : FileExtensions.CsExt); } }
private static ModelBuilderSettings SetupBaseModelBuilderSettings(EFArtifact artifact) { var settings = new ModelBuilderSettings { Artifact = artifact, GenerationOption = ModelGenerationOption.GenerateFromDatabase, SaveConnectionStringInAppConfig = false, VSApplicationType = VisualStudioProjectSystem.WindowsApplication, WizardKind = WizardKind.UpdateModel }; var hostContext = new Mock <ModelBuilderEngineHostContext>(); hostContext.Setup(hc => hc.LogMessage(It.IsAny <string>())).Callback(Console.WriteLine); hostContext.Setup(hc => hc.DispatchToModelGenerationExtensions()).Callback(() => { }); var modelBuilderEngine = new Mock <UpdateModelFromDatabaseModelBuilderEngine>(); settings.ModelBuilderEngine = modelBuilderEngine.Object; return(settings); }
// <summary> // Updates app. or web.config to include connection strings, registers the build provider // for WebSite projects and the assembly for WebApp projects // </summary> internal static void UpdateConfig(ModelBuilderSettings settings) { var metadataFileNames = ConnectionManager.GetMetadataFileNamesFromArtifactFileName(settings.Project, settings.ModelPath, PackageManager.Package); if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase || settings.GenerationOption == ModelGenerationOption.GenerateDatabaseScript) { if (settings.SaveConnectionStringInAppConfig) { UpdateConfig(metadataFileNames, settings); } } // regardless of GenerationOption we always need to register the build // provider for web site projects and the assembly for web app projects if (settings.VSApplicationType == VisualStudioProjectSystem.Website) { var containingProject = settings.Project; RegisterBuildProvidersInWebConfig(containingProject); // Ensure that System.Data.Entity.Design reference assemblies are added in the web.config. // Get the correct assembly name based on target framework var targetInfo = PackageManager.Package.GetService(typeof(SVsFrameworkMultiTargeting)) as IVsFrameworkMultiTargeting; var openScope = PackageManager.Package.GetService(typeof(SVsSmartOpenScope)) as IVsSmartOpenScope; Debug.Assert(targetInfo != null, "Unable to get IVsFrameworkMultiTargeting from service provider"); if (targetInfo != null && openScope != null) { var targetFrameworkMoniker = VsUtils.GetTargetFrameworkMonikerForProject(containingProject, PackageManager.Package); var provider = new VsTargetFrameworkProvider(targetInfo, targetFrameworkMoniker, openScope); var dataEntityDesignAssembly = provider.GetReflectionAssembly(new AssemblyName("System.Data.Entity.Design")); if (dataEntityDesignAssembly != null) { RegisterAssemblyInWebConfig(containingProject, dataEntityDesignAssembly.FullName); } } } }
public void RunFinished_checks_out_files_and_creates_project_items() { var mockProjectItems = new Mock <ProjectItems>(); var mockProject = new Mock <Project>(); mockProject.Setup(p => p.ProjectItems).Returns(mockProjectItems.Object); var mockVsUtils = new Mock <IVsUtils>(); var settings = new ModelBuilderSettings { Project = mockProject.Object }; var mockConfig = new Mock <ConfigFileUtils>(Mock.Of <Project>(), Mock.Of <IServiceProvider>(), VisualStudioProjectSystem.WindowsApplication, null, null); var generatedCode = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("context", string.Empty), new KeyValuePair <string, string>(Path.GetFileName(Assembly.GetExecutingAssembly().Location), string.Empty), new KeyValuePair <string, string>(Path.GetRandomFileName(), string.Empty) }; new OneEFWizard(configFileUtils: mockConfig.Object, vsUtils: mockVsUtils.Object, generatedCode: generatedCode) .RunFinished(settings, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); // need to Skip(1) since the first item is the DbContext file which is being added as a project item mockVsUtils.Verify( u => u.WriteCheckoutTextFilesInProject( It.Is <Dictionary <string, object> >( fileMap => fileMap.Keys.Select(Path.GetFileName) .SequenceEqual(generatedCode.Skip(1).Select(i => i.Key))))); var existingFilePath = Assembly.GetExecutingAssembly().Location; mockProjectItems.Verify(i => i.AddFromFile(existingFilePath), Times.Once()); // verify we only added the file that existed mockProjectItems.Verify(i => i.AddFromFile(It.IsAny <string>()), Times.Once()); }
public void OnDeactivate_does_not_update_settings_if_model_file_already_exists() { var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel" }; var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality); var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object) { CallBase = true }; mockWizardPageStart .Protected() .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); Assert.Null(modelBuilderSettings.ModelPath); Assert.True(wizard.FileAlreadyExistsError); }
// internal static to make it more testable internal static CommandProcessor PrepareCommandsAndIntegrityChecks( ModelBuilderSettings modelBuilderSettings, EditingContext editingContext, EntityDesignArtifact designArtifact) { Debug.Assert(modelBuilderSettings != null, "modelBuilderSettings != null"); Debug.Assert(editingContext != null, "editingContext != null"); Debug.Assert(designArtifact != null, "artifact != null"); var commands = new List<Command>(); if (modelBuilderSettings.NewFunctionSchemaProcedures != null && modelBuilderSettings.NewFunctionSchemaProcedures.Count > 0) { // user selected to create new FunctionImports, but don't create the composable ones as these have already been created by the runtime ProgressDialogHelper.ProcessStoredProcedureReturnTypeInformation( designArtifact, modelBuilderSettings.NewFunctionSchemaProcedures, commands, shouldCreateComposableFunctionImports: false); } else { commands.AddRange(CreateRemoveFunctionImportCommands(designArtifact)); } // for SqlServer and SqlServerCe we need to add integrity checks - see the comment below if (commands.Count > 0 || designArtifact.IsSqlFamilyProvider()) { // set up CommandProcessorContext var cpc = new CommandProcessorContext( editingContext, EfiTransactionOriginator.CreateNewModelId, Resources.Tx_CreateFunctionImport); // We propagate facets by default only for Sql Server or Sql Server CE since for other providers facets in C-Space might be intentionally // out of sync with facets from S-Space and we should not break this. For Sql Server and Sql Server CE facets should be in sync in most cases. if (designArtifact.IsSqlFamilyProvider()) { // Add integrity check to enforce synchronizing C-side Property facets to S-side values PropagateStoragePropertyFacetsToConceptualModel.AddRule(cpc, designArtifact); } return new CommandProcessor(cpc, commands); } // no commands or integrity checks to run return null; }
// for testing only internal ModelObjectItemWizard(ModelBuilderSettings settings) { _modelBuilderSettings = settings; }
/// <summary> /// Gets the model container. /// </summary> /// <returns></returns> public ModelContainer GetModelContainer() { var location2 = @"f:\business\CMS\Comlib.mvc\"; var comlib2 = @"f:\business\CommonLibrary.NET\CommonLibraryNet_LATEST"; var location = @"C:\Dev\business\cms\Commonlibrary.CMS_CMS\"; var comlib = @"C:\Dev\business\CommonLibrary.NET\CommonLibraryNet_LATEST"; // Settings for the Code model builders. ModelBuilderSettings settings = new ModelBuilderSettings() { ModelCodeLocation = location + @"\src\lib\CommonLibrary.Web.Modules\Src\_Models\", ModelInstallLocation = location + @"\Install\", ModelCodeLocationTemplate = comlib + @"\src\Lib\CommonLibrary.NET\CodeGen\Templates\Default", ModelDbStoredProcTemplates = comlib + @"\src\Lib\CommonLibrary.NET\CodeGen\Templates\DefaultSql", DbAction_Create = DbCreateType.DropCreate, Connection = _conn, AssemblyName = "CommonLibrary.Extensions" }; ModelContainer models = new ModelContainer() { Settings = settings, ExtendedSettings = new Dictionary <string, object>() { }, // Model definition. AllModels = new List <Model>() { new Model("ModelBase") .AddProperty <int>("Id").Required.Key .AddProperty <DateTime>("CreateDate").Required .AddProperty <DateTime>("UpdateDate").Required .AddProperty <string>("CreateUser").Required.MaxLength("20") .AddProperty <string>("UpdateUser").Required.MaxLength("20") .AddProperty <string>("UpdateComment").Required.MaxLength("150"), new Model("Address") .AddProperty <string>("Street").Range("-1", "60") .AddProperty <string>("City").Range("-1", "30") .AddProperty <string>("State").Range("-1", "20") .AddProperty <string>("Country").Range("-1", "20") .AddProperty <string>("Zip").Range("-1", "10") .AddProperty <int>("CityId") .AddProperty <int>("StateId") .AddProperty <int>("CountryId") .AddProperty <bool>("IsOnline").Mod, new Model("User") .BuildTable("Users").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Users") .InheritsFrom("ModelBase") .AddProperty <string>("UserName").Required.Range("3", "20").NoCode .AddProperty <string>("UserNameLowered").Required.Range("3", "20").NoCode .AddProperty <string>("Email").Required.Range("7", "50").NoCode .AddProperty <string>("EmailLowered").Required.Range("7", "50").NoCode .AddProperty <string>("Password").Required.Range("5", "100").NoCode .AddProperty <string>("Roles").Range("0", "50") .AddProperty <string>("MobilePhone").Range("10", "20") .AddProperty <string>("SecurityQuestion").MaxLength("150") .AddProperty <string>("SecurityAnswer").MaxLength("150") .AddProperty <string>("Comment").MaxLength("50") .AddProperty <bool>("IsApproved") .AddProperty <bool>("IsLockedOut") .AddProperty <string>("LockOutReason").MaxLength("50") .AddProperty <DateTime>("LastLoginDate").Required .AddProperty <DateTime>("LastPasswordChangedDate").Required .AddProperty <DateTime>("LastPasswordResetDate").Required .AddProperty <DateTime>("LastLockOutDate").Required.Mod, new Model("Log") .BuildCode().BuildTable("Logs").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Logs") .InheritsFrom("ModelBase") .AddProperty <string>("Application").MaxLength("255") .AddProperty <string>("Computer").MaxLength("255") .AddProperty <int>("LogLevel") .AddProperty <StringClob>("Exception").Range("-1", "-1") .AddProperty <StringClob>("Message").Range("-1", "-1") .AddProperty <string>("UserName").MaxLength("20").Mod, new Model("Config") .BuildTable("Configs").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Configs") .InheritsFrom("ModelBase") .AddProperty <string>("App").MaxLength("30") .AddProperty <string>("Name").MaxLength("30") .AddProperty <string>("Section").MaxLength("50") .AddProperty <string>("Key").MaxLength("50") .AddProperty <StringClob>("Val").Range("-1", "-1") .AddProperty <string>("ValType").MaxLength("20").Mod, new Model("Page") .BuildCode().BuildTable("Pages").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Pages") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Description").Range("-1", "100") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <int>("IsPublished") .AddProperty <string>("Keywords").Required.Range("-1", "80") .AddProperty <string>("Slug").Range("-1", "150") .AddProperty <string>("AccessRoles").Range("-1", "50") .AddProperty <int>("Parent") .AddProperty <bool>("IsPublic") .AddProperty <bool>("IsFrontPage").Mod, new Model("Part") .BuildCode().BuildTable("Parts").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Parts") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Description").Range("-1", "100") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <string>("AccessRoles").Range("-1", "50") .AddProperty <string>("RefTag").Range("-1", "40") .AddProperty <bool>("IsPublic").Mod, new Model("Post") .BuildCode().BuildTable("Posts").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Posts") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <string>("Description").Required.Range("-1", "200") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <DateTime>("PublishDate") .AddProperty <bool>("IsPublished") .AddProperty <bool>("IsPublic") .AddProperty <int>("CategoryId") .AddProperty <string>("Author").NoCode.NotPersisted .AddProperty <string>("Tags").Range("-1", "80") .AddProperty <string>("Slug").Range("-1", "150") .AddProperty <string>("RefKey").Range("-1", "20") .AddProperty <bool>("IsFavorite") .AddProperty <bool>("IsCommentEnabled") .AddProperty <bool>("IsCommentModerated") .AddProperty <bool>("IsRatable") .AddProperty <int>("Year").GetterOnly.NoCode .AddProperty <int>("Month").GetterOnly.NoCode .AddProperty <int>("CommentCount") .AddProperty <int>("ViewCount") .AddProperty <int>("AverageRating") .AddProperty <int>("TotalLiked") .AddProperty <int>("TotalDisLiked") .AddProperty <bool>("HasMediaFiles") .AddProperty <int>("TotalMediaFiles").Mod, new Model("Event") .BuildCode().BuildTable("Events").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Events") .InheritsFrom("ModelBase") .HasComposition("Address") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <string>("Description").Required.Range("-1", "200") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <DateTime>("PublishDate").NoCode.NotPersisted .AddProperty <bool>("IsPublished") .AddProperty <bool>("IsPublic") .AddProperty <int>("CategoryId") .AddProperty <DateTime>("StartDate").Required .AddProperty <DateTime>("EndDate").Required .AddProperty <int>("StartTime") .AddProperty <int>("EndTime") .AddProperty <int>("Year").GetterOnly.NoCode .AddProperty <int>("Month").GetterOnly.NoCode .AddProperty <int>("Day").GetterOnly.NoCode .AddProperty <bool>("IsFeatured") .AddProperty <bool>("IsTravelRequired") .AddProperty <bool>("IsConference") .AddProperty <bool>("IsAllTimes").NoCode .AddProperty <double>("Cost") .AddProperty <int>("Skill") .AddProperty <int>("Seats") .AddProperty <bool>("IsAgeApplicable") .AddProperty <int>("AgeFrom") .AddProperty <int>("AgeTo") .AddProperty <string>("Email").Range("-1", "30").RegExConst("RegexPatterns.Email") .AddProperty <string>("Phone").Range("-1", "14").RegExConst("RegexPatterns.PhoneUS") .AddProperty <string>("Url").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <string>("Tags").Range("-1", "80") .AddProperty <string>("RefKey").Range("-1", "20") .AddProperty <int>("AverageRating") .AddProperty <int>("TotalLiked") .AddProperty <int>("TotalDisLiked") .AddProperty <int>("TotalBookMarked") .AddProperty <int>("TotalAbuseReports") .AddProperty <bool>("HasMediaFiles") .AddProperty <int>("TotalMediaFiles").Mod, new Model("Link") .BuildCode().BuildTable("Links").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Links") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "100") .AddProperty <string>("Group").Required.Range("1", "100") .AddProperty <string>("Url").Range("-1", "150").RegEx("RegexPatterns.Url") .AddProperty <string>("Description").Range("-1", "50") .AddProperty <int>("SortIndex").Required.Range("-1", "100000").Mod, new Model("Tag") .BuildCode().BuildTable("Tags").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Tags") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <int>("GroupId") .AddProperty <string>("Name").Range("1", "20") .AddProperty <int>("RefId").Mod, new Model("Feedback") .BuildCode().BuildTable("Feedbacks").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Feedbacks") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Range("-1", "150") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <string>("Group").Required.Range("1", "50") .AddProperty <string>("Name").Range("-1", "20") .AddProperty <string>("Email").Range("-1", "30").RegExConst("RegexPatterns.Email") .AddProperty <string>("Url").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <bool>("IsApproved").Mod, new Model("Faq") .BuildCode().BuildTable("Faqs").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Faqs") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Range("-1", "150") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <string>("Group").Required.Range("1", "50").Mod, new Model("Profile") .BuildCode().BuildTable("Profiles").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Profiles") .InheritsFrom("ModelBase") .HasComposition("Address") .AddProperty <int>("UserId") .AddProperty <string>("UserName").Range("-1", "20") .AddProperty <StringClob>("About").Required.Range("-1", "-1") .AddProperty <string>("FirstName").Range("-1", "20") .AddProperty <string>("LastName").MaxLength("20") .AddProperty <string>("Alias").MaxLength("50") .AddProperty <bool>("IsFeatured") .AddProperty <string>("Email").Range("-1", "50").RegExConst("RegexPatterns.Email") .AddProperty <string>("WebSite").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <string>("ImageUrl").Range("-1", "150").RegExConst("RegexPatterns.Url").NoCode .AddProperty <string>("AddressDisplayLevel").Range("-1", "10") .AddProperty <int>("ImageRefId") .AddProperty <bool>("EnableDisplayOfName") .AddProperty <bool>("IsGravatarEnabled") .AddProperty <bool>("IsAddressEnabled") .AddProperty <bool>("EnableMessages") .AddProperty <bool>("HasMediaFiles") .AddProperty <int>("TotalMediaFiles").Mod, new Model("Widget") .BuildCode().BuildTable("Widgets").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Widgets") .InheritsFrom("ModelBase") .AddProperty <string>("Name").Range("-1", "150") .AddProperty <StringClob>("Description").Range("-1", "-1") .AddProperty <string>("FullTypeName").Range("-1", "150") .AddProperty <string>("Path").Range("-1", "150") .AddProperty <string>("Version").MaxLength("20") .AddProperty <string>("Author").MaxLength("20") .AddProperty <string>("AuthorUrl").MaxLength("150").RegExConst("RegexPatterns.Url") .AddProperty <string>("Email").Range("-1", "30").RegExConst("RegexPatterns.Email") .AddProperty <string>("Url").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <StringClob>("IncludeProperties").Required.Range("-1", "-1") .AddProperty <StringClob>("ExcludeProperties").Required.Range("-1", "-1") .AddProperty <StringClob>("StringClobProperties").Required.Range("-1", "-1") .AddProperty <string>("PathToEditor").Range("-1", "150") .AddProperty <string>("DeclaringType").Range("-1", "150") .AddProperty <string>("DeclaringAssembly").Range("-1", "150") .AddProperty <int>("SortIndex") .AddProperty <bool>("IsCacheable") .AddProperty <bool>("IsEditable").Mod, // There should be a WidgetSettings class but for the sake of simplicity for this 1st version. // the settings will be stored into an string "Args" field and parsed. // Will handle the settings as a patch or something. new Model("WidgetInstance") .BuildCode().BuildTable("WidgetInstances").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Widgets") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <int>("WidgetId") .AddProperty <string>("Header").Range("-1", "150") .AddProperty <string>("Zone").MaxLength("50") .AddProperty <string>("DefName").Range("1", "30") .AddProperty <string>("Roles").MaxLength("50") .AddProperty <StringClob>("StateData").Range("-1", "-1") .AddProperty <int>("SortIndex") .AddProperty <bool>("IsActive").Mod, new Model("MenuEntry") .BuildCode().BuildTable("MenuEntrys").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.MenuEntrys") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "50") .AddProperty <string>("Url").Range("-1", "150") .AddProperty <string>("Description").Range("-1", "50") .AddProperty <string>("Roles").Range("-1", "50") .AddProperty <string>("ParentItem").MaxLength("50") .AddProperty <int>("RefId") .AddProperty <bool>("IsRerouted") .AddProperty <bool>("IsPublic").NoCode.GetterOnly .AddProperty <int>("SortIndex").Required.Range("-1", "100000").Mod, new Model("Theme") .BuildCode().BuildTable("Themes").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Themes") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "50") .AddProperty <string>("Description").Required.Range("-1", "150") .AddProperty <string>("Path").Range("-1", "150") .AddProperty <string>("Layouts").MaxLength("100") .AddProperty <string>("Zones").MaxLength("50") .AddProperty <string>("SelectedLayout").MaxLength("30") .AddProperty <bool>("IsActive") .AddProperty <string>("Author").MaxLength("20") .AddProperty <string>("Version").MaxLength("20") .AddProperty <string>("Email").Range("-1", "30").RegExConst("RegexPatterns.Email") .AddProperty <string>("Url").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <int>("SortIndex").Required.Range("-1", "100000").Mod, new Model("Flag") .BuildCode().BuildTable("Flags").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Flags") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <int>("RefId") .AddProperty <int>("FlagType") .AddProperty <string>("Model").MaxLength("30") .AddProperty <string>("Url").MaxLength("200") .AddProperty <string>("FlaggedByUser").MaxLength("20") .AddProperty <DateTime>("FlaggedDate").Mod, new Model("Favorite") .BuildCode().BuildTable("Favorites").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Favorites") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <int>("UserId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <int>("RefId") .AddProperty <string>("Model").MaxLength("30") .AddProperty <string>("Url").MaxLength("200").Mod, new Model("Comment") .BuildCode().BuildTable("Comments").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Comments") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <int>("GroupId") .AddProperty <int>("RefId") .AddProperty <string>("Title").Required.Range("1", "50") .AddProperty <StringClob>("Content").Range("-1", "-1") .AddProperty <int>("UserId") .AddProperty <string>("Name").MaxLength("30") .AddProperty <string>("Email").Required.MaxLength("150").RegExConst("RegexPatterns.Email") .AddProperty <string>("Url").MaxLength("150").RegExConst("RegexPatterns.Url") .AddProperty <string>("ImageUrl").MaxLength("150") .AddProperty <bool>("IsGravatarEnabled") .AddProperty <bool>("IsApproved") .AddProperty <int>("Rating").Mod, new Model("Resource") .BuildCode().BuildTable("Resources").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Resources") .InheritsFrom("ModelBase") .AddProperty <string>("AppName").MaxLength("30") .AddProperty <string>("Language").MaxLength("20") .AddProperty <string>("ResourceType").MaxLength("20") .AddProperty <string>("Section").MaxLength("50") .AddProperty <string>("Key").MaxLength("50") .AddProperty <string>("ValType").MaxLength("20") .AddProperty <string>("Name").MaxLength("80") .AddProperty <string>("Description").MaxLength("200") .AddProperty <string>("Example").MaxLength("50").Mod, new Model("OptionDef") .BuildCode().BuildTable("OptionDefs").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.OptionDefs") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Section").MaxLength("50") .AddProperty <string>("Key").MaxLength("50") .AddProperty <string>("ValType").MaxLength("20") .AddProperty <StringClob>("Values").Range("-1", "-1") .AddProperty <string>("DefaultValue").MaxLength("200") .AddProperty <string>("DisplayStyle").MaxLength("20") .AddProperty <bool>("IsRequired") .AddProperty <bool>("IsBasicType") .AddProperty <int>("SortIndex").Mod, new Model("MediaFile") .BuildCode().BuildTable("MediaFiles").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Media") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "50") .AddProperty <string>("FullName").Range("1", "200").NoCode .AddProperty <string>("DirectoryName").Required.Range("1", "25") .AddProperty <string>("Extension").Required.Range("1", "5") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Description").Required.Range("1", "200") .AddProperty <DateTime>("LastWriteTime") .AddProperty <int>("Length") .AddProperty <Image>("Contents").Required.Range("-1", "-1").NoCode .AddProperty <Image>("ContentsForThumbNail").Required.Range("-1", "-1") .AddProperty <int>("Height") .AddProperty <int>("Width") .AddProperty <int>("SortIndex") .AddProperty <int>("RefGroupId") .AddProperty <int>("RefId") .AddProperty <int>("RefImageId") .AddProperty <int>("ParentId") .AddProperty <int>("FileType") .AddProperty <bool>("IsPublic") .AddProperty <bool>("IsExternalFile") .AddProperty <string>("ExternalFileSource").Range("-1", "20") .AddProperty <bool>("HasThumbnail").Mod, new Model("MediaFolder") .BuildCode().BuildTable("MediaFolders").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Media") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "50") .AddProperty <string>("FullName").Required.Range("1", "200") .AddProperty <string>("DirectoryName").Required.Range("1", "25") .AddProperty <string>("Extension").Required.Range("1", "5") .AddProperty <string>("Description").Required.Range("1", "200") .AddProperty <int>("Length") .AddProperty <DateTime>("LastWriteTime") .AddProperty <int>("SortIndex") .AddProperty <int>("ParentId") .AddProperty <int>("FileType") .AddProperty <bool>("IsPublic") .AddProperty <bool>("HasMediaFiles") .AddProperty <int>("TotalMediaFiles") .AddProperty <bool>("IsExternalFile") .AddProperty <string>("ExternalFileSource").Range("-1", "20") .AddProperty <bool>("HasThumbnail").Mod, new Model("Category") .BuildCode().BuildTable("Categorys").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.Web.Modules.Categorys") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Name").Required.Range("1", "25") .AddProperty <string>("Description").Required.Range("1", "20") .AddProperty <string>("Group").MaxLength("25") .AddProperty <int>("SortIndex") .AddProperty <int>("Count") .AddProperty <int>("ParentId").Mod, new Model("Country") .BuildCode().BuildTable("Countrys").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.LocationSupport") .InheritsFrom("ModelBase") .AddProperty <string>("CountryCode").MaxLength("10") .AddProperty <string>("Name").MaxLength("100") .AddProperty <string>("Abbreviation").MaxLength("30") .AddProperty <string>("AliasRefName").MaxLength("100") .AddProperty <bool>("IsActive") .AddProperty <bool>("IsAlias") .AddProperty <int>("AliasRefId").Mod, new Model("State") .BuildCode().BuildTable("States").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.LocationSupport") .InheritsFrom("ModelBase") .AddProperty <int>("CountryId") .AddProperty <string>("CountryName").MaxLength("100") .AddProperty <string>("Name").MaxLength("100") .AddProperty <string>("Abbreviation").MaxLength("30") .AddProperty <string>("AliasRefName").MaxLength("100") .AddProperty <bool>("IsActive") .AddProperty <bool>("IsAlias") .AddProperty <int>("AliasRefId").Mod, new Model("City") .BuildCode().BuildTable("Citys").BuildInstallSqlFile().NoValidation() .BuildActiveRecordEntity().NameSpaceIs("ComLib.LocationSupport") .InheritsFrom("ModelBase") .AddProperty <int>("StateId") .AddProperty <string>("StateName").MaxLength("100") .AddProperty <int>("ParentId") .AddProperty <bool>("IsPopular") .AddProperty <int>("CountryId") .AddProperty <string>("CountryName").MaxLength("100") .AddProperty <string>("Name").MaxLength("100") .AddProperty <string>("Abbreviation").MaxLength("30") .AddProperty <string>("AliasRefName").MaxLength("100") .AddProperty <bool>("IsActive") .AddProperty <bool>("IsAlias") .AddProperty <int>("AliasRefId").Mod } }; return(models); }
public ModelContext GetContext() { var location = ""; var comlib = ""; var _conn = new ConnectionInfo(""); // Settings for the Code model builders. var settings = new ModelBuilderSettings() { ModelCodeLocation = location + @"\src\lib\CommonLibraryNet.Web.Modules\Src\_Models\", ModelInstallLocation = location + @"\Install\", ModelCodeLocationTemplate = comlib + @"\src\Lib\CommonLibrary.NET\CodeGen\Templates\Default", ModelDbStoredProcTemplates = comlib + @"\src\Lib\CommonLibrary.NET\CodeGen\Templates\DefaultSql", DbAction_Create = DbCreateType.DropCreate, Connection = _conn, AssemblyName = "CommonLibrary.Extensions" }; var models = new ModelContainer() { Settings = settings, ExtendedSettings = new Dictionary <string, object>() { }, // Model definition. AllModels = new List <Model>() { new Model("ModelBase") .AddProperty <int>("Id").Required.Key .AddProperty <DateTime>("CreateDate").Required .AddProperty <DateTime>("UpdateDate").Required .AddProperty <string>("CreateUser").Required.MaxLength("20") .AddProperty <string>("UpdateUser").Required.MaxLength("20") .AddProperty <string>("UpdateComment").Required.MaxLength("150"), new Model("Rating") .AddProperty <int>("AverageRating") .AddProperty <int>("TotalLiked") .AddProperty <int>("TotalDisLiked") .AddProperty <int>("TotalBookMarked") .AddProperty <int>("TotalAbuseReports"), new Model("Address") .AddProperty <string>("Street").Range("-1", "40") .AddProperty <string>("City").Range("-1", "30") .AddProperty <string>("State").Range("-1", "20") .AddProperty <string>("Country").Range("-1", "20") .AddProperty <string>("Zip").Range("-1", "10") .AddProperty <int>("CityId") .AddProperty <int>("StateId") .AddProperty <int>("CountryId") .AddProperty <bool>("IsOnline").Mod, new Model("Page") .BuildCode().BuildTable("Pages").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Pages") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Description").Range("-1", "100") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <int>("IsPublished") .AddProperty <string>("Keywords").Required.Range("-1", "80") .AddProperty <string>("Slug").Range("-1", "150") .AddProperty <string>("AccessRoles").Range("-1", "50") .AddProperty <int>("Parent") .AddProperty <bool>("IsPublic") .AddProperty <bool>("IsFrontPage").Mod, new Model("Part") .BuildCode().BuildTable("Parts").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Parts") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Description").Range("-1", "100") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <string>("AccessRoles").Range("-1", "50") .AddProperty <bool>("IsPublic").Mod, new Model("Post") .BuildCode().BuildTable("Posts").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Posts") .InheritsFrom("ModelBase") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <string>("Description").Required.Range("-1", "200") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <DateTime>("PublishDate") .AddProperty <bool>("IsPublished") .AddProperty <string>("Author").NoCode.NotPersisted .AddProperty <string>("Tags").Range("-1", "80") .AddProperty <string>("Slug").Range("-1", "150") .AddProperty <bool>("IsFavorite") .AddProperty <bool>("IsPublic") .AddProperty <bool>("IsCommentEnabled") .AddProperty <bool>("IsCommentModerated") .AddProperty <bool>("IsRatable") .AddProperty <int>("Year").GetterOnly.NoCode .AddProperty <int>("Month").GetterOnly.NoCode .AddProperty <int>("CommentCount") .AddProperty <int>("ViewCount") .AddProperty <int>("AverageRating") .AddProperty <int>("TotalLiked") .AddProperty <int>("TotalDisLiked").Mod, new Model("Event") .BuildCode().BuildTable("Events").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Events") .InheritsFrom("ModelBase") .HasComposition("Address") .HasInclude("Rating") .AddProperty <int>("AppId") .AddProperty <string>("Title").Required.Range("1", "150") .AddProperty <string>("Description").Required.Range("-1", "200") .AddProperty <StringClob>("Content").Required.Range("-1", "-1") .AddProperty <DateTime>("PublishDate").NoCode.NotPersisted .AddProperty <bool>("IsPublished") .AddProperty <DateTime>("StartDate").Required .AddProperty <DateTime>("EndDate").Required .AddProperty <int>("StartTime") .AddProperty <int>("EndTime") .AddProperty <string>("Email").Range("-1", "30").RegExConst("RegexPatterns.Email") .AddProperty <string>("Phone").Range("-1", "14").RegExConst("RegexPatterns.PhoneUS") .AddProperty <string>("Url").Range("-1", "150").RegExConst("RegexPatterns.Url") .AddProperty <string>("Tags").Range("-1", "80").Mod } }; return(new ModelContext() { AllModels = models }); }
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)); }
private static void Run_OnDeactivate_creates_and_verifies_model_path( ModelGenerationOption generationOption, LangEnum language, bool isWebSite, string expectedExtension) { var mockDte = new MockDTE( ".NETFramework, Version=v4.5", isWebSite ? MockDTE.CreateWebSite( properties: new Dictionary<string, object> { { "CurrentWebsiteLanguage", language == LangEnum.CSharp ? "C#" : "VB" } }, assemblyReferences: new AssemblyReference[0]) : MockDTE.CreateProject( kind: language == LangEnum.CSharp ? MockDTE.CSharpProjectKind : MockDTE.VBProjectKind, assemblyReferences: new Reference[0])); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", Project = mockDte.Project, GenerationOption = generationOption }; var mockWizardPageStart = new Mock<WizardPageStart>(ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider), null) { CallBase = true }; mockWizardPageStart .Protected() .Setup<bool>("VerifyModelFilePath", ItExpr.IsAny<string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); mockWizardPageStart .Protected() .Verify("VerifyModelFilePath", Times.Once(), @"C:\temp\myModel" + expectedExtension); }
// method to compare Model Namespace and Entity Container names - centralized for maintenance internal static bool ModelNamespaceAndEntityContainerNameSame(ModelBuilderSettings modelBuilderSettings) { var entityContainerName = modelBuilderSettings.AppConfigConnectionPropertyName; var modelNamespaceName = modelBuilderSettings.ModelNamespace; return (!string.IsNullOrEmpty(entityContainerName) && !string.IsNullOrEmpty(modelNamespaceName) && entityContainerName.ToUpper(CultureInfo.CurrentCulture) == modelNamespaceName.ToUpper(CultureInfo.CurrentCulture)); }
internal void UpdateDesignerInfoInvoker(EdmxHelper edmxHelper, ModelBuilderSettings settings) { UpdateDesignerInfo(edmxHelper, settings); }
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)); }
private static ModelBuilderWizardForm CreateModelBuilderWizardForm(ModelGenerationOption modelGenerationOption) { var mockDte = new MockDTE(".NETFramework, Version=v4.5", references: new Reference[0]); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", ReplacementDictionary = new Dictionary<string, string>(), TargetSchemaVersion = EntityFrameworkVersion.Version3, VsTemplatePath = "fake.vstemplate", Project = mockDte.Project, GenerationOption = modelGenerationOption }; var wizard = ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider); return wizard; }
public void RunStarted_creates_valid_context_name_if_safeitemname_is_not_valid_identifier() { var mockVsUtils = new Mock<IVsUtils>(); var wizard = new OneEFWizard(vsUtils: mockVsUtils.Object); var mockCodeGenerator = new Mock<CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny<DbModel>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(new[] { new KeyValuePair<string, string>(string.Empty, string.Empty) }); var settings = new ModelBuilderSettings { VSApplicationType = VisualStudioProjectSystem.WebApplication }; var replacenentsDictionary = new Dictionary<string, string> { { "$safeitemname$", "3My.Con text" }, { "$rootnamespace$", "Project" } }; wizard.RunStarted(settings, mockCodeGenerator.Object, replacenentsDictionary); mockCodeGenerator.Verify( g => g.Generate( It.IsAny<DbModel>(), "Project", /*contextClassName*/ "_3MyContext", /*connectionStringName*/ "_3MyContext"), Times.Once()); }
public void RunStarted_uses_context_class_name_if_SaveConnectionStringInAppConfig_false() { var mockCodeGenerator = new Mock<CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny<DbModel>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(new[] { new KeyValuePair<string, string>() }); var modelBuilderSettings = new ModelBuilderSettings { SaveConnectionStringInAppConfig = false, AppConfigConnectionPropertyName = "ConnString" }; var replacementsDictionary = new Dictionary<string, string> { { "$safeitemname$", "MyContext" }, { "$rootnamespace$", "Project.Data" } }; new OneEFWizard(vsUtils: Mock.Of<IVsUtils>()) .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary); mockCodeGenerator.Verify(g => g.Generate(It.IsAny<DbModel>(), "Project.Data", "MyContext", "MyContext"), Times.Once()); }
public void RunStarted_saves_context_generated_code_replacementsDictionary_as_contextfilecontents() { var mockCodeGenerator = new Mock<CodeFirstModelGenerator>(MockDTE.CreateProject()); mockCodeGenerator .Setup(g => g.Generate(It.IsAny<DbModel>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(new[] { new KeyValuePair<string, string>("MyContext", "context code") }); var modelBuilderSettings = new ModelBuilderSettings { SaveConnectionStringInAppConfig = true, AppConfigConnectionPropertyName = "ConnString" }; var replacementsDictionary = new Dictionary<string, string> { { "$safeitemname$", "MyContext" }, { "$rootnamespace$", "Project.Data" } }; new OneEFWizard(vsUtils:Mock.Of<IVsUtils>()) .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary); Assert.Equal("context code", replacementsDictionary["$contextfilecontents$"]); }
public void RunFinished_checks_out_files_and_creates_project_items() { var mockProjectItems = new Mock<ProjectItems>(); var mockProject = new Mock<Project>(); mockProject.Setup(p => p.ProjectItems).Returns(mockProjectItems.Object); var mockVsUtils = new Mock<IVsUtils>(); var settings = new ModelBuilderSettings {Project = mockProject.Object }; var mockConfig = new Mock<ConfigFileUtils>(Mock.Of<Project>(), Mock.Of<IServiceProvider>(), VisualStudioProjectSystem.WindowsApplication, null, null); var generatedCode = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("context", string.Empty), new KeyValuePair<string, string>(Path.GetFileName(Assembly.GetExecutingAssembly().Location), string.Empty), new KeyValuePair<string, string>(Path.GetRandomFileName(), string.Empty) }; new OneEFWizard(configFileUtils: mockConfig.Object, vsUtils: mockVsUtils.Object, generatedCode: generatedCode) .RunFinished(settings, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); // need to Skip(1) since the first item is the DbContext file which is being added as a project item mockVsUtils.Verify( u => u.WriteCheckoutTextFilesInProject( It.Is<Dictionary<string, object>>( fileMap => fileMap.Keys.Select(Path.GetFileName) .SequenceEqual(generatedCode.Skip(1).Select(i => i.Key))))); var existingFilePath = Assembly.GetExecutingAssembly().Location; mockProjectItems.Verify(i => i.AddFromFile(existingFilePath), Times.Once()); // verify we only added the file that existed mockProjectItems.Verify(i => i.AddFromFile(It.IsAny<string>()), Times.Once()); }
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; }
public void OnDeactivate_does_not_update_settings_if_model_file_already_exists() { var mockDte = new MockDTE(".NETFramework, Version=v4.5", references: new Reference[0]); var modelBuilderSettings = new ModelBuilderSettings { NewItemFolder = @"C:\temp", ModelName = "myModel", Project = mockDte.Project }; var wizard = ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider); var mockWizardPageStart = new Mock<WizardPageStart>(wizard, null) { CallBase = true }; mockWizardPageStart .Protected() .Setup<bool>("VerifyModelFilePath", ItExpr.IsAny<string>()) .Returns(false); mockWizardPageStart.Object.OnDeactivate(); Assert.Null(modelBuilderSettings.ModelPath); Assert.True(wizard.FileAlreadyExistsError); }
private static string CreateModelFileInfo(ModelBuilderSettings settings, string extension) { return(Path.ChangeExtension(Path.Combine(settings.NewItemFolder, settings.ModelName), extension)); }
protected abstract void ProcessModel( DbModel model, string storeModelNamespace, ModelBuilderSettings settings, ModelBuilderEngineHostContext hostContext, List<EdmSchemaError> errors);
private ModelContainer GetModelContainer() { var baseLocComLib = @"F:\Business\CommonLibrary.NET\CommonLibraryNet.LATEST\"; var baseLocCode = @"F:\Business\CommonLibrary.NET\CommonLibraryNet.LATEST\src\Apps\CommonLibrary.SampleApp\"; // Settings for the Code model builders. ModelBuilderSettings settings = new ModelBuilderSettings() { ModelCodeLocation = baseLocCode + @"Generated\src", ModelInstallLocation = baseLocCode + @"Generated\install", ModelCodeLocationTemplate = baseLocComLib + @"src\lib\CommonLibrary.NET\CodeGen\Templates\Default", ModelDbStoredProcTemplates = baseLocComLib + @"src\lib\CommonLibrary.NET\CodeGen\Templates\DefaultSql", DbAction_Create = DbCreateType.Create, Connection = new ConnectionInfo("Server=kishore1;Database=testdb;User=testuser1;Password=password;", "System.Data.SqlClient"), AssemblyName = "CommonLibrary.Extensions" }; //<doc:example> ModelContainer models = new ModelContainer() { Settings = settings, ExtendedSettings = new Dictionary <string, object>() { }, // Model definition. AllModels = new List <Model>() { new Model("ModelBase") .AddProperty <int>("Id").Required.Key .AddProperty <DateTime>("CreateDate").Required .AddProperty <DateTime>("UpdateDate").Required .AddProperty <string>("CreateUser").Required.MaxLength("20") .AddProperty <string>("UpdateUser").Required.MaxLength("20") .AddProperty <string>("UpdateComment").Required.MaxLength("150") .AddProperty <bool>("IsActive").Required.DefaultTo(1).Mod, new Model("Address") .AddProperty <string>("Street").Range("-1", "40") .AddProperty <string>("City").Range("-1", "30") .AddProperty <string>("State").Range("-1", "20") .AddProperty <string>("Country").Range("-1", "20") .AddProperty <string>("Zip").Range("-1", "10") .AddProperty <int>("CityId") .AddProperty <int>("StateId") .AddProperty <int>("CountryId") .AddProperty <bool>("IsOnline").Mod, new Model("User") .BuildCode().BuildTable("Users").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Account") .InheritsFrom("ModelBase") .AddProperty <string>("UserName").Required.Range("3", "20") .AddProperty <string>("UserNameLowered").Required.Range("3", "20") .AddProperty <string>("Email").Required.Range("7", "30") .AddProperty <string>("EmailLowered").Required.Range("7", "30") .AddProperty <string>("Password").Required.Range("5", "100") .AddProperty <string>("Roles").Range("-1", "50") .AddProperty <string>("MobilePhone").Range("10", "20") .AddProperty <string>("SecurityQuestion").Range("-1", "150") .AddProperty <string>("SecurityAnswer").Range("-1", "150") .AddProperty <string>("Comment").Range("-1", "50") .AddProperty <bool>("IsApproved") .AddProperty <bool>("IsLockedOut") .AddProperty <string>("LockOutReason").Range("-1", "50") .AddProperty <DateTime>("LastLoginDate").Required .AddProperty <DateTime>("LastPasswordChangedDate").Required .AddProperty <DateTime>("LastPasswordResetDate").Required .AddProperty <DateTime>("LastLockOutDate").Required.Mod, new Model("Comment") .BuildCode().BuildTable("Comments").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Comments") .InheritsFrom("ModelBase") .AddProperty <int>("RefId") .AddProperty <string>("Title").Required.Range("1", "100") .AddProperty <string>("Content").Required.Range("3", "250") .AddProperty <int>("Rating").Mod, new Model("Event") .BuildCode().BuildTable("Events").BuildInstallSqlFile() .BuildActiveRecordEntity().NameSpaceIs("ComLib.WebModules.Events") .InheritsFrom("ModelBase") .HasOne("User").OnKey("UserId") .HasMany("Comment").OnForeignKey("RefId") .HasComposition("Address") .AddProperty <int>("UserId") .AddProperty <string>("Title").Required.Range("2", "150") .AddProperty <string>("Summary").Required.Range("-1", "200") .AddProperty <StringClob>("Description").Required.Range("2", "-1") .AddProperty <DateTime>("StartDate").Required .AddProperty <DateTime>("EndDate").Required .AddProperty <int>("StartTime") .AddProperty <int>("EndTime") .AddProperty <string>("Email").Range("-1", "30").RegEx("RegexPatterns.Email") .AddProperty <string>("Phone").Range("-1", "10").RegEx("RegexPatterns.PhoneUS") .AddProperty <string>("Url").Range("-1", "150").RegEx("RegexPatterns.Url") .AddProperty <string>("Keywords").Range("-1", "150").RegEx("RegexPatterns.Url") .AddProperty <int>("AverageRating") .AddProperty <int>("TotalLiked") .AddProperty <int>("TotalDisLiked") .AddProperty <int>("TotalBookMarked") .AddProperty <int>("TotalAbuseReports").Mod, } }; //</doc:example> return(models); }
private static string GetStoreNamespace(ModelBuilderSettings settings) { return string.IsNullOrEmpty(settings.StorageNamespace) ? String.Format( CultureInfo.CurrentCulture, Resources.SelectTablesPage_DefaultStorageNamespaceFormat, settings.ModelNamespace) : settings.StorageNamespace; }
// internal virtual to allow mocking internal virtual DbModel GenerateModels(string storeModelNamespace, ModelBuilderSettings settings, List<EdmSchemaError> errors) { return new ModelGenerator(settings, storeModelNamespace).GenerateModel(errors); }
internal VSModelBuilderEngineHostContext(ModelBuilderSettings settings) { _settings = settings; }
internal static bool ValidateNamespace(TextBox modelNamespaceTextBox, ModelBuilderSettings modelBuilderSettings) { if (!EdmUtils.IsValidModelNamespace(modelNamespaceTextBox.Text)) { var s = ModelWizard.Properties.Resources.ConnectionStringNonValidIdentifier; VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelNamespaceTextBox.Text)); modelNamespaceTextBox.Focus(); return false; } // the Model Namespace and the Entity Container name must differ if (ModelBuilderWizardForm.ModelNamespaceAndEntityContainerNameSame(modelBuilderSettings)) { var s = ModelWizard.Properties.Resources.NamespaceAndEntityContainerSame; VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelBuilderSettings.AppConfigConnectionPropertyName)); modelNamespaceTextBox.Focus(); return false; } return true; }