Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix --useSqlite for mac scenarios (#2241) #2244

Merged
merged 1 commit into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions eng/common/cross/toolchain.cmake
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
set(CROSS_ROOTFS $ENV{ROOTFS_DIR})

# reset platform variables (e.g. cmake 3.25 sets LINUX=1)
unset(LINUX)
unset(FREEBSD)
unset(ILLUMOS)
unset(ANDROID)
unset(TIZEN)

set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH})
if(EXISTS ${CROSS_ROOTFS}/bin/freebsd-version)
set(CMAKE_SYSTEM_NAME FreeBSD)
Expand Down
2 changes: 1 addition & 1 deletion eng/common/sdk-task.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ try {
$GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty
}
if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) {
$GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.4.1" -MemberType NoteProperty
$GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.3.1" -MemberType NoteProperty
}
if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") {
$xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true
Expand Down
6 changes: 0 additions & 6 deletions eng/common/templates/steps/source-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,6 @@ steps:
targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}'
fi

runtimeOsArgs=
if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then
runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}'
fi

publishArgs=
if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then
publishArgs='--publish'
Expand All @@ -85,7 +80,6 @@ steps:
$internalRuntimeDownloadArgs \
$internalRestoreArgs \
$targetRidArgs \
$runtimeOsArgs \
/p:SourceBuildNonPortable=${{ parameters.platform.nonPortable }} \
/p:ArcadeBuildFromSource=true \
/p:AssetManifestFileName=$assetManifestFileName
Expand Down
4 changes: 2 additions & 2 deletions eng/common/tools.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,8 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements =

# If the version of msbuild is going to be xcopied,
# use this version. Version matches a package here:
# https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=17.4.1&view=overview
$defaultXCopyMSBuildVersion = '17.4.1'
# https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=17.3.1view=overview
$defaultXCopyMSBuildVersion = '17.3.1'

if (!$vsRequirements) {
if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') {
Expand Down
2 changes: 1 addition & 1 deletion eng/common/tools.sh
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ global_json_file="${repo_root}global.json"
# determine if global.json contains a "runtimes" entry
global_json_has_runtimes=false
if command -v jq &> /dev/null; then
if jq -e '.tools | has("runtimes")' "$global_json_file" &> /dev/null; then
if jq -er '. | select(has("runtimes"))' "$global_json_file" &> /dev/null; then
global_json_has_runtimes=true
fi
elif [[ "$(cat "$global_json_file")" =~ \"runtimes\"[[:space:]\:]*\{ ]]; then
Expand Down
8 changes: 4 additions & 4 deletions scripts/install-aspnet-codegenerator.cmd
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
set VERSION=8.0.0-dev
set VERSION=7.0.3
set DEFAULT_NUPKG_PATH=%userprofile%\.nuget\packages
set SRC_DIR=%cd%
set NUPKG=artifacts/packages/Debug/Shipping/
call taskkill /f /im dotnet.exe
call rd /Q /S artifacts
call build
call dotnet tool uninstall -g dotnet-aspnet-codegenerator
call dotnet tool uninstall -g dotnet-aspnet-codegenerator

call cd %DEFAULT_NUPKG_PATH%
call C:
Expand All @@ -18,7 +18,7 @@ call rd /Q /S microsoft.visualstudio.web.codegeneration.templating
call rd /Q /S microsoft.visualstudio.web.codegeneration.utils
call rd /Q /S microsoft.visualstudio.web.codegenerators.mvc
call D:
call cd %SRC_DIR%/%NUPKG%
call cd %SRC_DIR%/%NUPKG%
call dotnet tool install -g dotnet-aspnet-codegenerator --add-source %SRC_DIR%\%NUPKG% --version %VERSION%
call cd %SRC_DIR%
call taskkill /f /im dotnet.exe
call taskkill /f /im dotnet.exe
34 changes: 20 additions & 14 deletions src/Scaffolding/VS.Web.CG.EFCore/EntityFrameworkModelProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.DotNet.Scaffolding.Shared;
using Microsoft.DotNet.Scaffolding.Shared.Project;
using Microsoft.DotNet.Scaffolding.Shared.ProjectModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.DotNet.Scaffolding.Shared;
using Microsoft.DotNet.Scaffolding.Shared.ProjectModel;
using Microsoft.VisualStudio.Web.CodeGeneration.DotNet;
using Microsoft.DotNet.Scaffolding.Shared.Project;

namespace Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore
{
Expand Down Expand Up @@ -44,7 +44,7 @@ internal class EntityFrameworkModelProcessor
private EditSyntaxTreeResult _programEditResult;
private IFileSystem _fileSystem;

public EntityFrameworkModelProcessor (
public EntityFrameworkModelProcessor(
string dbContextFullTypeName,
ModelType modelTypeSymbol,
string areaName,
Expand Down Expand Up @@ -95,7 +95,7 @@ public async Task Process()
{
throw new InvalidOperationException(string.Format(MessageStrings.ModelTypeNotFound, "Program"));
}

if (!dbContextSymbols.Any())
{
await GenerateNewDbContextAndRegisterProgramFile(programType, _applicationInfo);
Expand Down Expand Up @@ -224,8 +224,8 @@ public async Task Process()
}


public ContextProcessingStatus ContextProcessingStatus { get; private set;}
public ModelMetadata ModelMetadata { get; private set;}
public ContextProcessingStatus ContextProcessingStatus { get; private set; }
public ModelMetadata ModelMetadata { get; private set; }

/// <summary>
/// Writes the DbContext to disk using the given Roslyn SyntaxTree.
Expand Down Expand Up @@ -270,9 +270,9 @@ private async Task EnsureDbContextInLibraryIsValid(ModelType dbContextSymbol)
return c;
});

var dbContextType = _reflectedTypesProvider.GetReflectedType(_dbContextFullTypeName, lookInDependencies:true);
var dbContextType = _reflectedTypesProvider.GetReflectedType(_dbContextFullTypeName, lookInDependencies: true);

if (_reflectedTypesProvider.GetCompilationErrors() != null
if (_reflectedTypesProvider.GetCompilationErrors() != null
&& _reflectedTypesProvider.GetCompilationErrors().Any())
{
throw new InvalidOperationException(string.Format(
Expand All @@ -299,7 +299,7 @@ private async Task EnsureDbContextInLibraryIsValid(ModelType dbContextSymbol)
private async Task AddModelTypeToExistingDbContextIfNeeded(ModelType dbContextSymbol, IApplicationInfo appInfo)
{
bool nullabledEnabled = "enable".Equals(_projectContext.Nullable, StringComparison.OrdinalIgnoreCase);
var addResult = _dbContextEditorServices.AddModelToContext(dbContextSymbol, _modelTypeSymbol, new Dictionary<string, string> { { "nullableEnabled", nullabledEnabled.ToString()} });
var addResult = _dbContextEditorServices.AddModelToContext(dbContextSymbol, _modelTypeSymbol, new Dictionary<string, string> { { "nullableEnabled", nullabledEnabled.ToString() } });
var projectCompilation = await _workspace.CurrentSolution.Projects
.First(project => project.AssemblyName == _projectContext.AssemblyName)
.GetCompilationAsync();
Expand Down Expand Up @@ -368,7 +368,10 @@ private async Task GenerateNewDbContextAndRegisterProgramFile(ModelType programT
};

// Validate for necessary ef packages (based on database type)
EFValidationUtil.ValidateEFDependencies(_projectContext.PackageDependencies, _databaseProvider);
if (CalledFromCommandline)
{
EFValidationUtil.ValidateEFDependencies(_projectContext.PackageDependencies, _databaseProvider);
}

// Create a new Context
_logger.LogMessage(string.Format(MessageStrings.GeneratingDbContext, _dbContextFullTypeName));
Expand Down Expand Up @@ -438,8 +441,11 @@ private async Task GenerateNewDbContextAndRegister(ModelType startupType, ModelT
Edited = false
};

// Validate for necessary ef packages (based on database type)
EFValidationUtil.ValidateEFDependencies(_projectContext.PackageDependencies, _databaseProvider);
if (CalledFromCommandline)
{
// Validate for necessary ef packages (based on database type)
EFValidationUtil.ValidateEFDependencies(_projectContext.PackageDependencies, _databaseProvider);
}

// Create a new Context
_logger.LogMessage(string.Format(MessageStrings.GeneratingDbContext, _dbContextFullTypeName));
Expand Down Expand Up @@ -526,7 +532,7 @@ private ModelMetadata GetModelMetadata(Type dbContextType, Type modelType, Type
{
entityType = dbContextInstance.Model.FindEntityType(modelType);
}
catch(Exception ex)
catch (Exception ex)
{
// We got an exception from the DbContext while finding the entityType.
// The error here is useful to the user for taking corrective actions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public abstract class CommonCommandLineModel
[Option(Name = "useSqLite", ShortName = "sqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite { get; set; }

//adding UseSqlite2 for backwards compat. for VS Mac scenarios (casing issue).
[Obsolete("Use --databaseProvider or -dbProvider to configure database type instead")]
[Option(Name = "useSqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite2 { get; set; }

[Option(Name = "databaseProvider", ShortName = "dbProvider", Description = "Database provider to use. Options include 'sqlserver' (default), 'sqlite', 'cosmos', 'postgres'.")]
public string DatabaseProviderString { get; set; }
public DbProvider DatabaseProvider { get; set; }
Expand Down Expand Up @@ -72,7 +77,7 @@ public static void ValidateCommandline(this CommonCommandLineModel model, ILogge
}

#pragma warning disable CS0618 // Type or member is obsolete
if (model.UseSqlite)
if (model.UseSqlite || model.UseSqlite2)
{
#pragma warning restore CS0618 // Type or member is obsolete
//instead of throwing an error, letting the devs know that its obsolete.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public override async Task Generate(CommandLineGeneratorModel controllerGenerato
{
EFValidationUtil.ValidateEFDependencies(ProjectContext.PackageDependencies, controllerGeneratorModel.DatabaseProvider);
}

string outputPath = ValidateAndGetOutputPath(controllerGeneratorModel);
_areaName = GetAreaName(ApplicationInfo.ApplicationBasePath, outputPath);

Expand Down Expand Up @@ -101,7 +101,7 @@ public override async Task Generate(CommandLineGeneratorModel controllerGenerato

if (modelTypeAndContextModel.ContextProcessingResult.ContextProcessingStatus == ContextProcessingStatus.ContextAddedButRequiresConfig)
{
throw new Exception(string.Format("{0} {1}" ,MessageStrings.ScaffoldingSuccessful_unregistered,
throw new Exception(string.Format("{0} {1}", MessageStrings.ScaffoldingSuccessful_unregistered,
MessageStrings.Scaffolding_additionalSteps));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.DotNet.Scaffolding.Shared;
using Microsoft.VisualStudio.Web.CodeGeneration.CommandLine;


namespace Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Identity
{
public class IdentityGeneratorCommandLineModel
Expand All @@ -13,6 +14,11 @@ public class IdentityGeneratorCommandLineModel
[Option(Name = "useSqLite", ShortName = "sqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite { get; set; }

//adding UseSqlite2 for backwards compat. for VS Mac scenarios (casing issue).
[Obsolete("Use --databaseProvider or -dbProvider to configure database type instead")]
[Option(Name = "useSqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite2 { get; set; }

[Option(Name = "databaseProvider", ShortName = "dbProvider", Description = "Database provider to use. Options include 'sqlserver' (default), 'sqlite', 'cosmos', 'postgres'.")]
public string DatabaseProviderString { get; set; }
public DbProvider DatabaseProvider { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public IdentityGeneratorTemplateModelBuilder(
internal string UserClassNamespace { get; private set; }

private Type _userType;
internal Type UserType
internal Type UserType
{
get
{
Expand Down Expand Up @@ -182,7 +182,7 @@ public async Task<IdentityGeneratorTemplateModel> ValidateAndBuild()
{
NamedFiles = _commandlineModel.Files.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
else if(!string.IsNullOrEmpty(_commandlineModel.ExcludeFiles))
else if (!string.IsNullOrEmpty(_commandlineModel.ExcludeFiles))
{
string contentVersion;
if (templateModel is IdentityGeneratorTemplateModel2 templateModel2)
Expand All @@ -208,7 +208,7 @@ public async Task<IdentityGeneratorTemplateModel> ValidateAndBuild()
{
throw new InvalidOperationException(string.Join(Environment.NewLine, errors));
}

//get files to overwrite
NamedFiles = allFiles.Except(excludedFiles);
}
Expand Down Expand Up @@ -448,12 +448,12 @@ private bool HasExistingNonEmptyWwwRootDirectory
}
}

private void ValidateIndividualFileOptions()
private void ValidateIndividualFileOptions()
{
//Both options should not be selected. Users should either scaffold a particular set of files OR exclude a particular set of files.
if(IsFilesSpecified && IsExcludeSpecificed)
if (IsFilesSpecified && IsExcludeSpecificed)
{
throw new InvalidOperationException(string.Format(MessageStrings.InvalidOptionCombination,"--files", "--excludeFiles"));
throw new InvalidOperationException(string.Format(MessageStrings.InvalidOptionCombination, "--files", "--excludeFiles"));
}
}
private void ValidateDefaultUIOption()
Expand All @@ -462,12 +462,12 @@ private void ValidateDefaultUIOption()

if (IsFilesSpecified)
{
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination,"--files", "--useDefaultUI"));
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination, "--files", "--useDefaultUI"));
}

if(IsExcludeSpecificed)
if (IsExcludeSpecificed)
{
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination,"--excludeFiles", "--useDefaultUI"));
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination, "--excludeFiles", "--useDefaultUI"));
}

if (IsUsingExistingDbContext)
Expand Down Expand Up @@ -533,7 +533,7 @@ private string GetNamespaceFromTypeName(string dbContext)

private string GetClassNameFromTypeName(string dbContext)
{
return dbContext.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries).Last();
return dbContext.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Last();
}

private void ValidateExistingDbContext(Type existingDbContext)
Expand Down Expand Up @@ -669,7 +669,7 @@ private async Task<Type> FindExistingType(string type)
Environment.NewLine,
string.Join(Environment.NewLine, _reflectedTypesProvider.GetCompilationErrors())));
}

}
//get all types and return the one with the same name. There should be no duplicates so only one should match.
return _reflectedTypesProvider.GetAllTypesInProject().FirstOrDefault(
Expand All @@ -691,7 +691,7 @@ private void ValidateCommandLine(IdentityGeneratorCommandLineModel model)
}

#pragma warning disable CS0618 // Type or member is obsolete
if (model.UseSqlite)
if (model.UseSqlite || model.UseSqlite2)
{
#pragma warning restore CS0618 // Type or member is obsolete
//instead of throwing an error, letting the devs know that its obsolete.
Expand All @@ -710,15 +710,15 @@ private void ValidateCommandLine(IdentityGeneratorCommandLineModel model)
errorStrings.Add(string.Format(MessageStrings.InvalidDatabaseProvider, model.DatabaseProviderString));
errorStrings.Add($"Supported database providers include : {dbList}");
}

if (!string.IsNullOrEmpty(model.RootNamespace) && !RoslynUtilities.IsValidNamespace(model.RootNamespace))
{
errorStrings.Add(string.Format(MessageStrings.InvalidNamespaceName, model.RootNamespace));
}

if (!string.IsNullOrEmpty(model.Layout) && model.GenerateLayout)
{
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination,"--layout", "--generateLayout"));
errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination, "--layout", "--generateLayout"));
}

if (!string.IsNullOrEmpty(model.BootstrapVersion) && !IdentityGenerator.ValidBootstrapVersions.Contains(model.BootstrapVersion.Trim(' ', '\n')))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ public class MinimalApiGeneratorCommandLineModel
[Option(Name = "useSqLite", ShortName = "sqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite { get; set; }

//adding UseSqlite2 for backwards compat. for VS Mac scenarios (casing issue).
[Obsolete("Use --databaseProvider or -dbProvider to configure database type instead")]
[Option(Name = "useSqlite", Description = "Flag to specify if DbContext should use SQLite instead of SQL Server.")]
public bool UseSqlite2 { get; set; }

[Option(Name = "databaseProvider", ShortName = "dbProvider", Description = "Database provider to use. Options include 'sqlserver' (default), 'sqlite', 'cosmos', 'postgres'.")]
public string DatabaseProviderString { get; set; }
public DbProvider DatabaseProvider { get; set; }
Expand Down Expand Up @@ -66,7 +71,7 @@ public static void ValidateCommandline(this MinimalApiGeneratorCommandLineModel
}

#pragma warning disable CS0618 // Type or member is obsolete
if (model.UseSqlite)
if (model.UseSqlite || model.UseSqlite2)
{
#pragma warning restore CS0618 // Type or member is obsolete
//instead of throwing an error, letting the devs know that its obsolete.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,14 @@ internal async Task GenerateViews(RazorPageGeneratorModel razorPageGeneratorMode
}

ModelTypeAndContextModel modelTypeAndContextModel = null;
razorPageGeneratorModel.ValidateCommandline(_logger);
string outputPath = ValidateAndGetOutputPath(razorPageGeneratorModel, string.Empty);

if (CalledFromCommandline)
{
EFValidationUtil.ValidateEFDependencies(_projectContext.PackageDependencies, razorPageGeneratorModel.DatabaseProvider);
}

modelTypeAndContextModel = await ModelMetadataUtilities.ValidateModelAndGetEFMetadata(
razorPageGeneratorModel,
_entityFrameworkService,
Expand Down
Loading