EF Code First - Create Rollback Script for First Migration - entity-framework

We've got a little console app that creates scripts based on to>from migrations ... we're using to do our rollback scripts as well.
With rollback we stick in null and the migration to rollback to.
We've just moved the Console app to a new solution, but I cannot get it to make the first rollback script when the is only one migration in _MigrationHistory.
Any ideas?
public static string CreateScriptBetween(string from, string to, string name)
{
var dbMigrator = new DbMigrator(new EmptyConfiguration());
var scriptor = new MigratorScriptingDecorator(dbMigrator);
var script = "USE MYCOOLSKILLZDB" + Environment.NewLine + Environment.NewLine + "GO" + Environment.NewLine
+ Environment.NewLine;
script += scriptor.ScriptUpdate(from, to);
var filename = FileGenerator.NewNamedFilename(name, "sql");
using (var writer = new StreamWriter(filename, false))
{
writer.Write(script);
}
return filename;
}

Related

Entity Framework Core 2.0 FromSql and SQL Injection

I need to know the correct way to handle SQL Injection when using the FromSQL command.
At runtime, I need to dynamically create a where statement. So I am using FromSql to create the SQL command. Now I know that using use string interpolation is the way to go. However, I need to step through a list of "Where Parameters" to generate the command. Simple enough to do;
foreach (var x in wp)
{
if (!string.IsNullOrEmpty(results))
results = $"{results} and {x.Field} = {x.Value}";
if (string.IsNullOrEmpty(results))
results = $"where {x.Field} = {x.Value}";
}
Problem is that this return a simple string and would not be string interpolation. How can I do this correctly?
Entityframework will parameterize your queries if you put it in the following format:
db.something.FromSql("SELECT * FROM yourTable WHERE AuthorId = {0}", id)
Is x.Field a form field that has a fixed number of possibilities? i.e. title, firstname etc. If so then something like the following:
var sqlstring = new StringBuilder();
var sqlp = new List<SqlParameter>();
var i = 0;
foreach (var x in wp)
{
var param = "#param" + i.ToString();
if (i!=0)
{
sqlstring.Append($" AND {x.Field} = " + param);
sqlp.Add(new SqlParameter(param, x.Value));
}
if (i==0)
{
sqlstring.Append($"WHERE {x.Field} = " + " #param" + i.ToString());
sqlp.Add(new SqlParameter(param, x.Value));
}
i++;
}
You'd then need to do something like this:
db.something.FromSql(sqlstring.ToString(), sqlp.ToArray())
Might be a better/cleaner way but that should work.
My solution to this problem is a VS extension, QueryFirst. QueryFirst generates a C# wrapper for sql that lives in a .sql file. As such, parameters are the only way to get data into your query and SQL injection is near impossible. There are numerous other advantages: you edit your sql in a real environment, it's constantly validated against your db, and using your query in your code is very simple.

Bukkit - Displaying null when getting a string from the config file

So I've been working on a custom feature for my minecraft server, one of the things that I need to do is get an integer from the config file that is specific to each player to display how many Packages(keys) they have (Virtual items)
The issue that I am having is that in the GUI it is displaying 'null' instead of how many they have... Could anyone help me please?
Item in the gui
Code for creating the player's instance in the config (Using a custom file class that was provided to me by a friend of mine.)
#EventHandler
public void playerJoin(PlayerJoinEvent event) {
Main main = Main.getPlugin(Main.class);
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (!main.getDataFolder().exists())
main.getDataFolder().mkdirs();
File file = new File(main.getDataFolder(), "players.yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
if (!config.contains("Users." + uuid + ".Username")) {
try {
System.out.println("Creating entry for " + player + " (" + uuid + ")");
config.set("Users." + uuid + ".Username", player);
config.set("Users." + uuid + ".Packages.Common", 0);
config.set("Users." + uuid + ".Packages.Rare", 0);
config.set("Users." + uuid + ".Packages.Epic", 0);
config.set("Users." + uuid + ".Packages.Legendary", 0);
config.set("Users." + uuid + ".Packages.Exotic", 0);
config.save(file);
System.out.println("Successfully created the entry for " + " (" + uuid + ")");
} catch (Exception e) {
}
}
}
Code for the creation of the item in the gui:
public static String inventoryname = Utils.chat("&fWhite Backpack");
public static Inventory WhiteBackpack(Player player) {
UUID uuid = player.getUniqueId();
Inventory inv = Bukkit.createInventory(null, 27, (inventoryname));
ItemStack common = new ItemStack(Material.INK_SACK);
common.setDurability((byte) 8);
ItemMeta commonMeta = common.getItemMeta();
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l" + Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
common.setItemMeta(commonMeta);
inv.setItem(10, common);
return inv;
}
There are a couple things wrong with your code.
First, you never account for what happens if the config you are loading does not exist. When you do main.getDataFolder().mkdirs(), you account for if the folder is missing, but not the file.
Second, you are doing the following operation:
config.set("Users." + uuid + ".Username", player);
This is incorrect because the player variable is of the type Player, not of the type String. To fix this, you need to instead do the following:
config.set("Users." + uuid + ".Username", player.getName());
Third, you are attempting to write to a file that might not exist. When you initialize you file, you need to also make sure it exists, and if it does not, you need to create it. Right now you have the following:
File file = new File(main.getDataFolder(), "players.yml");
It must be changed to this block of code:
File file = new File(main.getDataFolder(), "players.yml");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could just have it be created when you attempt to save the file later on, but that is not ideal since it's safer to let Bukkit write to a file that already exists.
Fourth, and I'm not necessarily sure that this is a problem per se, but you are trying to access an Integer value from the config file as if it were a String. Try to replace the following:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
with this instead:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getInt("Users." + uuid + ".Packages.Common")));
Hope this gets you moving in the right direction!

dotnet ef migrations add: create migration file only if there are changes

I'm using dotnet ef migrations add {MigrationName} in order to create a new migration.
In case there are no Entities/Context changes this creates a migration with empty Up(MigrationBuilder migrationBuilder) and Down(MigrationBuilder migrationBuilder) functions.
Is there a way for the migrations add command to skip the creation of 'empty' files?
Alternatively, Is there a way to detect if there are changes before running the migrations add command?
I found a solution to this problem.
There is a way to create migrations programmatically instead of using CLI.
After looking at the MigrationsScaffolder source code I managed to modify the code in the first link in order to support my needs:
using (var db = new MyDbContext())
{
var reporter = new OperationReporter(
new OperationReportHandler(
m => Console.WriteLine(" error: " + m),
m => Console.WriteLine(" warn: " + m),
m => Console.WriteLine(" info: " + m),
m => Console.WriteLine("verbose: " + m)));
var designTimeServices = new ServiceCollection()
.AddSingleton(db.GetService<IHistoryRepository>())
.AddSingleton(db.GetService<IMigrationsIdGenerator>())
.AddSingleton(db.GetService<IMigrationsModelDiffer>())
.AddSingleton(db.GetService<IMigrationsAssembly>())
.AddSingleton(db.Model)
.AddSingleton(db.GetService<ICurrentDbContext>())
.AddSingleton(db.GetService<IDatabaseProvider>())
.AddSingleton<MigrationsCodeGeneratorDependencies>()
.AddSingleton<ICSharpHelper, CSharpHelper>()
.AddSingleton<CSharpMigrationOperationGeneratorDependencies>()
.AddSingleton<ICSharpMigrationOperationGenerator, CSharpMigrationOperationGenerator>()
.AddSingleton<CSharpSnapshotGeneratorDependencies>()
.AddSingleton<ICSharpSnapshotGenerator, CSharpSnapshotGenerator>()
.AddSingleton<CSharpMigrationsGeneratorDependencies>()
.AddSingleton<IMigrationsCodeGenerator, CSharpMigrationsGenerator>()
.AddSingleton<IOperationReporter>(reporter)
.AddSingleton<MigrationsScaffolderDependencies>()
.AddSingleton<ISnapshotModelProcessor, SnapshotModelProcessor>()
.AddSingleton<MigrationsScaffolder>()
.BuildServiceProvider();
var scaffolderDependencies = designTimeServices.GetRequiredService<MigrationsScaffolderDependencies>();
var modelSnapshot = scaffolderDependencies.MigrationsAssembly.ModelSnapshot;
var lastModel = scaffolderDependencies.SnapshotModelProcessor.Process(modelSnapshot?.Model);
var upOperations = scaffolderDependencies.MigrationsModelDiffer.GetDifferences(lastModel, scaffolderDependencies.Model);
var downOperations = upOperations.Any() ? scaffolderDependencies.MigrationsModelDiffer.GetDifferences(scaffolderDependencies.Model, lastModel) : new List<MigrationOperation>();
if (upOperations.Count() > 0 || downOperations.Count() > 0)
{
var scaffolder = designTimeServices.GetRequiredService<MigrationsScaffolder>();
var migration = scaffolder.ScaffoldMigration(
"MyMigration",
"MyApp.Data");
File.WriteAllText(
migration.MigrationId + migration.FileExtension,
migration.MigrationCode);
File.WriteAllText(
migration.MigrationId + ".Designer" + migration.FileExtension,
migration.MetadataCode);
File.WriteAllText(migration.SnapshotName + migration.FileExtension,
migration.SnapshotCode);
}
}
I don't know if its possible at all, But empty migrations are helpful also like if you want to run any script manually, for example, create/alter StoredProcedures/Trigger. For this purpose, you can generate an empty migration exclusively for a particular purpose.

How do I use MigratorScriptingDecorator in Entity Framework code first?

I have problems using the MigratorScriptingDecorator.ScriptUpdate in Entity Framework 4.3.1.
When specifying sourceMigration and targetMigration only my initial migration gets written, the rest of my migrations become empty.
I have entered a bug report on Microsoft Connect containing reproducing code.
https://connect.microsoft.com/VisualStudio/feedback/details/731111/migratorscriptingdecorator-in-entity-framework-migrations-does-not-respect-sourcemigration-and-targetmigration
I expect MigratorScriptingDecorator.ScriptUpdate("from", "to") to behave exactly like the corresponding PM command
PM> Update-Database -Script -SourceMigration from -TargetMigration to
Should ScriptUpdate be equivalent to Update-Database -Script?
Are there any other ways of generating update scripts from code?
As noted on the linked Microsoft Connect issue the problem was a reuse of the same DbMigrator on several MigratorScriptingDecorators.
The original code was
DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
var sql = new MigratorScriptingDecorator(efMigrator).ScriptUpdate(migration.Item1, migration.Item2); // <-- problem here, the efMigrator is reused several times
Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
Console.WriteLine(sql);
Console.WriteLine("-------------------------------------");
}
the MigratorScriptingDecorator should be instantiated outside the loop like this:
DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
var scriptMigrator = new MigratorScriptingDecorator(efMigrator); // <-- now only one MigratorScriptingDecorator is created for the DbMigrator
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
var sql = scriptMigrator.ScriptUpdate(migration.Item1, migration.Item2);
Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
Console.WriteLine(sql);
Console.WriteLine("-------------------------------------");
}

Log Fiddler Requests to Database Real-time

Is there any way to log all requests ongoing to a database or can you only log snapshots to a database?
The following example relies upon OLEDB 4.0 which is not available for 64bit processes. You can either select another data provider (e.g. SQLServer) or you can force Fiddler to run in 32bit mode.
Add the following to the Rules file to create a new menu item.
// Log the currently selected sessions in the list to a database.
// Note: The DB must already exist and you must have permissions to write to it.
public static ToolsAction("Log Selected Sessions")
function DoLogSessions(oSessions: Fiddler.Session[]){
if (null == oSessions || oSessions.Length < 1){
MessageBox.Show("Please select some sessions first!");
return;
}
var strMDB = "C:\\log.mdb";
var cnn = null;
var sdr = null;
var cmd = null;
try
{
cnn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strMDB);
cnn.Open();
cmd = new OleDbCommand();
cmd.Connection = cnn;
for (var x = 0; x < oSessions.Length; x++){
var strSQL = "INSERT into tblSessions ([ResponseCode],[URL]) Values (" +
oSessions[x].responseCode + ", '" + oSessions[x].url + "')";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
}
}
catch (ex){
MessageBox.Show(ex);
}
finally
{
if (cnn != null ){
cnn.Close();
}
}
}
Note: To use the Database Objects in Fiddler 2.3.9 and below, you'll need to add system.data to the References list inside Tools | Fiddler Options | Extensions | Scripting. In 2.3.9.1 and later, this reference will occur automatically.
Then, list the new import at the top of your rules script:
import System.Data.OleDb;
see FiddlerScript CookBook