How to use EF code first migration to generate scripts from powershell - entity-framework-6

I have a need to email our DBA when a deployment, that utilizes EF6 code-based migrations, goes out. I am able to use the migrate.exe tool with the verbose flag, through powershell, to get the scripts but each command is truncated after 10222 characters. This usually only effects the model hash for the migrationHistory. Does anyone know of a way to generate the full sql script for EF6 migrations through Powershell
thanks
T

Figured out that migrate.exe is wrapping the toolingfacade class So I created the object passing in the required variables as well as setting the verbosedelegate. The nice thing about this is that I could run the updatescript function instead if I just wanted to get the sql scripts
[Reflection.Assembly]::LoadFrom("EntityFramework.dll") | Out-Null
$con = New-Object -TypeName System.Data.Entity.Infrastructure.DbConnectionInfo -ArgumentList #("constring", "System.Data.SqlClient")
$tools = New-Object -TypeName System.Data.Entity.Migrations.Design.ToolingFacade -ArgumentList #("dbcondllname", "dbcondllname",$null,"workingdr",$null,$null,$con)
$tools.LogVerboseDelegate = {param($sql)
Write-Verbose $sql -verbose #dumps the sql to RM log
}
$tools.Update($null,$false)

Related

How do I get the Flyway version number of a database

I want to pull out the pre-deployment Flyway version number of my production database so I can use this in my continuous deployment pipeline (Jenkins) in case I do a rollback later.
How can I achieve this?
One option would be to query the flyway history table, but I can't work out a fail-safe way of achieving this.
I have fashioned an answer, although it feels like a big of a hack. I run --dryRunOutput in migrate as a means to get flyway to output the version number to the screen, as info doesn't do this for some reason.
I read the output into a file (because DOS makes it hard to pipe or pass into a variable) then isolate the output line starting with "Current". I then pick the second token using : as my delimeter. There's probably an easier way, and I wish I could use flyway info instead of migrate as my method feels hacky, but at least it works for now.
flyway -dryRunOutput=test.sql migrate | FIND "Current" >currentversion.txt
for /f "delims=" %%x in (currentversion.txt) do set CURRENTVERSIONLINE=%%x
for /f "tokens=1,2 delims=:" %%a in ("%CURRENTVERSIONLINE%") do set CURRENTVERSION=%%b
echo Version : %CURRENTVERSION%
The following one-liner does what you want:
flyway info | grep Success | tail -1 | cut -f3 "-d|" | xargs

Unable to start process from powershell

Folks
I am trying to invoke a batch script from a power shell file and the invocation works fine if executed manually.
Start-Process C:\USR\test.bat
However i created a service in C# which is able to delete and write logs using the powershell script however it simply ignores this step and nothing happens. Is it because this script is invoked by a windows service ?
if (Test-Path \\xxxsharepathfullper\FileWatcher\target\watcher.mon) {
echo "File removed" >> C:\USR\logger.txt
Start-Process C:\USR\test.bat
Remove-Item \\xxxsharepathfullper\FileWatcher\target\watcher.mon
}
else {
}
Execution policy is unrestricted
Check access rights on a share, maybe your admin user don't have rights to access it.
You can try run the process as administrator and log any error:
Start-Process -FilePath "C:\USR\test.bat" -RedirectStandardError "testError.txt" -verb RunAs

Can we Scaffold DbContext from selected tables of an existing database [duplicate]

This question already has answers here:
Entity Framework 7 Database First configuration (MVC 6)
(2 answers)
Closed last year.
As in previous versions of Entity Framework, is it possible in Entity Framework Core to reverse engineer only the selected tables of an existing database to create model classes out of them. This official ASP.NET site reverse engineers the entire database. In past, as shown in this ASP.NET tutorial, using old EF you could reverse engineer only the selected tables/Views if you chose to.
One can solve the problem by usage of dotnet ef dbcontext scaffold command with multiple -t (--table) parameters. It allows to specify all the tables, which needed by imported (scaffolded). The feature is described initially here.
It is possible to specify the exact tables in a schema to use when scaffolding database and to omit the rest. The command-line examples that follow show the parameters needed for filtering tables.
.NET Core CLI:
dotnet ef dbcontext scaffold
"server=localhost;port=3306;user=root;password=mypass;database=sakila"
MySql.Data.EntityFrameworkCore -o sakila
-t actor -t film -t film_actor -t language -f
Package Manager Console in Visual Studio:
Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila"
MySql.Data.EntityFrameworkCore -OutputDir Sakila
-Tables actor,film,film_actor,language -f
Force tag will update the existing selected models/files in the output
directory.
Scaffold-DbContext "Server=(localdb)\v11.0;Database=MyDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -t User, Role -f
.NET Core CLI:
dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f
Package Manager Console in Visual Studio:
Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,film_actor,language -f
EF Core,MS SQL PM :
Scaffold-DbContext "server=PC\SQL2012;user=test;password=test123;database=student" Microsoft.EntityFrameworkCore.SqlServer -OutputDir student-Tables stu.names,stu.grades -f
For more reference Visit entityframework-core-scaffold
Package Manger Console (MySql)
Scaffold-DbContext "server=localhost;port=3306;user=root;password=yourpassword;database=sakila" MySql.EntityFrameworkCore -OutputDir Models -Tables actor,film,film_actor,language -f
Package Manager Console (MSSQL)
Scaffold-DbContext "Server=desktop-vd5sscb;Initial Catalog=databaseName;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f
Package Manager Console (Sqlite)
Scaffold-DbContext "data source = yourdbname" Microsoft.EntityFrameworkCore.Sqlite -OutputDir Models -f
For Sqlite The default db dir is your project folder... where controller folders are located
Considering, If you have n number of tables, initially at design time, your database design architecture should group those tables in their suitable schemas
For eg: For Database “Company” you can have many tables, when you design database group these tables into schemas like: Users, ProductA, ProductB, ProductC etc
Then assuming you are working on ProductA tables only then you can simply add -Schemas flag and scaffold only tables in ProductA
Another example could be suppose you are working on authorisation based project only and you want to implement identity auth with ef, then you can simply scaffold “Users” schema instead of products and make your oAuth APIs work.
Scaffold-DbContext ... -Schemas Users
These are just few use cases where you can use scaffolding effectively.
The parameter -Tables table1, table2, table3 works for me for more tables.
The -o Model parameter is the output that creates the folder to which the model is generated.
The -force parameter regenerates the model each time it is started, such as updating the database.
The -Context DbE parameter renames the database context class.
Package manager console
Scaffold-DbContext name=ConnectionStrings:DbE Microsoft.EntityFrameworkCore.SqlServer -o Model -force -Tables T_Users_Of_Chat -Context DbE

dsmod user pwd fails in Powershell script with parameter is incorrect

Does anyone know why the following line in a PS script would fail:
dsmod user $dn -pwd $password -mustchpwd no
I have verified that $dn is valid and $password complies with history and complexity requirements. $password does not contain any un-escaped illegal characters.
Here is what makes this strange:
The same exact command (with variables substituted) works from an
interactive PS terminal
Another dsmod is called immediately next in the script to enable the identity: e.g. dsmod user $dn -disabled no. This works without issue, so I know the $dn variable is valid.
The same exact command, as written, works in another script whose only purpose is to reset the password.
This works on some of our client systems, but not on all.
When this is executed in the script, PS returns:
dsmod failed:The parameter is incorrect.
Any thoughts would be appreciated. Incidentally, if this helps, the script is executing via a server-less bind with the actual domain controller.
Regards
As you've tagged this with powershell, I'm a bit puzzled as to why you're not using the Set-ADUser and set-adaccountpassword cmdlets.
Set-ADAccountPassword –Identity $dn -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $password –Force);
Set-ADUser -Identity $dn -ChangePasswordAtNextLogon;
This was a case wherein the context account that the PowerShell script was executing did not have enough elevated permissions to perform the action. Elevating the account to the Administrators group eliminated the behavior.

Powershell ISE appears to hang with interactive commands.

I've just downloaded Powershell 2.0 and I'm using the ISE. In general I really like it but I am looking for a workaround on a gotcha. There are a lot of legacy commands which are interactive. For example xcopy will prompt the user by default if it is told to overwrite a file.
In the Powershell ISE this appears to hang
mkdir c:\tmp
cd c:\tmp
dir > tmp.txt
mkdir sub
xcopy .\tmp.txt sub # fine
xcopy .\tmp.txt sub # "hang" while it waits for a user response.
The second xcopy is prompting the user for permission to overwrite C:\tmp\sub\tmp.txt, but the prompt is not displayed in the ISE output window.
I can run this fine from cmd.exe but then what use is ISE? How do I know when I need which one?
In a nutshell, Interactive console applications are not supported in ISE (see link below). As a workaround, you can "prevent" copy-item from overwriting a file by checking first if the file exists using test-path.
http://blogs.msdn.com/powershell/archive/2009/02/04/console-application-non-support-in-the-ise.aspx
Why would you be using XCOPY from PowerShell ISE? Use Copy-Item instead:
Copy-Item -Path c:\tmp\tmp.txt -Destination c:\tmp\sub
It will overwrite any existing file without warning, unless the existing file is hidden, system, or read-only. If you want to overwrite those as well, you can add the -force parameter.
See the topic "Working with Files and Folders" in the PowerShell ISE help file for more info, or see all the commands at MSDN.

Resources