Entity Framework Power Tools Reverse Engineer Code First into a folder - entity-framework

I'm using Entity Framework Power Tools Reverse Engineer Code First to generate my POCO classes, mapping files, and context from the database. I was able to change the T4 templates to generate a different namespace based on my database schema, but I am not able to find how to create a folder based on the tables schema and place the related POCO classes in the folder.
Could somebody help?
Thanks

The folders for the model (and the mappings) are hard-coded in the tool. Reverse-engineering EfPowerTools.dll shows the following lines in method ReverseEngineerCodeFirst of ReverseEngineerCodeFirstHandler:
string str3 = str2 + ".Models";
string path1_1 = Path.Combine(directory.FullName, "Models");
string str4 = str3 + ".Mapping";
string path1_2 = Path.Combine(path1_1, "Mapping");
So, too bad, you can't change the name and location of these folders.

I'd have to add another answer as I have tried the approach suggested in my previous one and that didn't work. I have changed EF Power Tools in order to output files to different folder or project.
You need to install the following EF Power Tools Extension (https://entityframework.codeplex.com/SourceControl/network/forks/khorvat/EFPowerToolsEx)
Use this code to accomplish the export
var efHost = (EfTextTemplateHost)Host;
var code = new CodeGenerationTools(this);
var dte = efHost.DTE;
EnvDTE.Project ModelProject = null;
foreach(EnvDTE.Project dteProject in dte.Solution)
{
if (dteProject.Name.Equals("YourModelProjectName"))
ModelProject = dteProject;
}
var ModelProjectDirectory = new FileInfo(ModelProject.FullName).Directory;
var ModelProjectNamespace = (string)ModelProject.Properties.Item("RootNamespace").Value;
string ModelNameSpace = ModelProjectNamespace + ".Model";
string outputPath = Path.Combine(ModelProjectDirectory + ModelExportPath + #"Generated\I" + efHost.EntityType.Name + ".cs");
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
if (ModelProject.DTE.SourceControl.IsItemUnderSCC(outputPath) && !ModelProject.DTE.SourceControl.IsItemCheckedOut(outputPath))
ModelProject.DTE.SourceControl.CheckOutItem(outputPath);
File.WriteAllText(outputPath, this.GenerationEnvironment.ToString());
ModelProject.ProjectItems.AddFromFile(outputPath);
this.GenerationEnvironment.Clear();
With this you will be able to export output to another file, folder and even a project.

Update
As mentioned in other answer this approach won't work. So the answer is no longer applied.
You can try resolving the output path and create a folder by doing the following:
<## import namespace="System.IO" #>
var efHost = (EfTextTemplateHost)Host;
var outputPath = Path.Combine(Path.GetDirectoryName(efHost.TemplateFile), "YourFolder");
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
Now to output to different folder you can try using the GenerationEnvironment similar to this:
<## dte processor="T4Toolbox.DteProcessor" #>
<## TransformationContext processor="T4Toolbox.TransformationContextProcessor" #>
<## assembly name="System.Xml" #>
<## assembly name="EnvDTE" #>
<## import namespace="T4Toolbox" #>
ProcessOutputTemplate template = new ProcessOutputTemplate(this.GenerationEnvironment.ToString());
template.Output.File = outputPath;
template.Render();
this.GenerationEnvironment.Clear();
Note: this approach requires the T4 Toolbox installed in the VS 2012/13 - http://www.olegsych.com/t4toolbox/ (http://www.olegsych.com/t4toolbox/gettingstarted/)

I have modified the EFPowerTool extension to support the namespace based directory structure creation. Created a pull request on EF 6.x project at codeplex. Also I have created an experimental branch on github for testing purpose.(There surely are room for fixes/enhancement which can be added and tested before sending updated pull request)
You can download the extension installer with the proposed fix from here(see install dir in source).

Related

"failed to load any lstm-specific dictionaries for lang " tesseract 4.1

I tried to train the tesseract 4.1 using OCRD project but after training completed I copied the lang.traineddata but getting above error.
The tesseractWiki page is very confusing to understand asking to use combine_lang_model after making lstmf file. So Actually I have the lstmf file. I created these file by using tif/box pair.
Please help me for further step.
Related discussions:Failed to load any lstm-specific dictionaries for lang xxx
Suppose your training folder like this:
OCRD/makefile
OCRD/data/foo-ground-truth.
You could try as following steps:
Find the WORDLIST_FILE/NUMBERS_FILE/PUNC_FILE in the makefile, and change them to:
WORDLIST_FILE := data/$(MODEL_NAME).wordlist
NUMBERS_FILE := data/$(MODEL_NAME).numbers
PUNC_FILE := data/$(MODEL_NAME).punc
Suppose your base traineddata is eng.traineddata.
2.1 Download the .wordlist/.numbers/.punc files from the langdata_lstm.
2.2 Place them in OCRD/data
2.3 if the MODEL_NAME = foo, rename them as: foo.wordlist, foo.numbers, foo.punc
if you don't have the base traineddata, you could try this too. But if your base traineddata is afr, you should download the files from langdata_lstm/afr.
make training again
The cause of this error:
In OCRD, the default path of the above three files is $ (OUTPUT_DIR) = data / $ (MODEL_NAME), and all files in this path are automatically generated during the training process.
If the variable START_MODEL is not assigned, the makefile will not generate any related files under this path;
If the variable START_MODEL has been assigned, the foo.lstm-number-dawg、foo.lstm-punc-dawg、foo.lstm-word-dawg and so on will be produced in data / $ (MODEL_NAME). But they are not the right one. So there may be a bug in OCRD.

How to do File creation and manipulation in functional style?

I need to write a program where I run a set of instructions and create a file in a directory. Once the file is created, when the same code block is run again, it should not run the same set of instructions since it has already been executed before, here the file is used as a guard.
var Directory: String = "Dir1"
var dir: File = new File("Directory");
dir.mkdir();
var FileName: String = Directory + File.separator + "samplefile" + ".log"
val FileObj: File = new File(FileName)
if(!FileObj.exists())
// blahblah
else
{
// set of instructions to create the file
}
When the programs runs initially, the file won't be present, so it should run the set of instructions in else and also create the file, and after the first run, the second run it should exit since the file exists.
The problem is that I do not understand new File, and when the file is created? Should I use file.CreateNewFile? Also, how to write this in functional style using case?
It's important to understand that a java.io.File is not a physical file on the file system, but a representation of a pathname -- per the javadoc: "An abstract representation of file and directory pathnames". So new File(...) has nothing to do with creating an actual file - you are just defining a pathname, which may or may not correspond to an existing file.
To create an empty file, you can use:
val file = new File("filepath/filename")
file.createNewFile();
If running on JRE 7 or higher, you can use the new java.nio.file API:
val path = Paths.get("filepath/filename")
Files.createFile(path)
If you're not happy with the default IO APIs, you an consider a number of alternative. Scala-specific ones that I know of are:
scala-io
rapture.io
Or you can use libraries from the Java world, such as Google Guava or Apache Commons IO.
Edit: One thing I did not consider initially: I understood "creating a file" as "creating an empty file"; but if you intend to write something immediately in the file, you generally don't need to create an empty file first.

EF Migrations migrate.exe generate script

I'm playing around with Entity framework and continuous builds. So far i'm able to run a migration or series of migrations without any problem by using migrate.exe and the appropriate arguments.
However, i've hit trouble when trying to get migrate.exe to kick out a script, rather than perform the migration, in the same way as I could get by running
update-database -TargetMigration TestMigration -script
from within Package Manager Console in Visual Studio.
Is there currently a way to do this?
Thanks.
Since the 10/22/2017 you can do it thanks to this PR:
https://github.com/aspnet/EntityFramework6/commit/02ec6b8c9279f93f80eeed1234e5ce0acfce5f31
Here the Entity Framework 6.2 release notes that implements this functionality (see 'Migrate.exe should support -script option' section):
https://blogs.msdn.microsoft.com/dotnet/2017/10/26/entity-framework-6-2-runtime-released/
Follow those steps:
Copy the file migrate.exe from the '\packages\EntityFramework.6.2.0\tools' to the target 'bin' folder (for example on the production server) after that you deployed the new assembly that contains the new migrations
Open the command line in the folder and launch this command:
migrate.exe yourMigrationAssembly.dll
/startupConfigurationFile=”..\web.config”
/scriptFile="migrationOutput.sql"
It will generate the the file "migrationOutput.sql" that contains the SQL you have to execute on your target environment DB based on the migrations that are not yet applied on it.
It is currently not supported. Please add your vote to the issue: Migrations: -Script for Migrate.exe
I encountered the same problem and indeed the option is available in the package manager console in Visual Studio. So I opened up the powershell script and the entity framework dll and built a small executable so you can generate the scripts from command line.The source code is available as-is and without any warranty here;
EF6
EF5
You can write a simple c# console application or use something like Linqpad to generate the script using the Entity Framework Infrastructure objects. You will just need to load the DLL with your DbMigrationsConfiguration class and instantiate it. Here is the code similar to what is working for me:
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
const string ScriptFile = "Migration.sql";
const string ConnectionString = #"Server=.\SqlExpress;Database=...;Trusted_Connection=True;";
const bool AutomaticMigrationDataLossAllowed = false;
var targetDb = new DbConnectionInfo(ConnectionString, "System.Data.SqlClient");
var config = new MyDbMigrationsConfiguration
{
AutomaticMigrationDataLossAllowed = AutomaticMigrationDataLossAllowed,
TargetDatabase = targetDb,
};
var migrator = new DbMigrator(config);
var scripter = new MigratorScriptingDecorator(migrator);
var script = scripter.ScriptUpdate(null, null);
File.WriteAllText(ScriptFile, script);
Console.WriteLine("Migration Script Generated: " + ScriptFile);

From Msi , how to get the list of files packed in each feature?

We have used wix to create Msi. Each Msi will be having 1 or 2 or 3 features such as Appserver feature, Webserver feature and DB server feature.
Now i was asked to get the list of config files presented in each feature.
It is tough to find the list of web.config files associated with each feature through wxs file.
Is it possible find the list of files associated with a feature with particular search pattern?
For ex. Find all the web.config files packed in Appserver feature.
Is there any way easy way ( querying or some other automated script such as powershell) to get the list?
Wix comes with a .NET SDK referred to as the DTF ("deployment tools foundation"). It wraps the windows msi.dll among other things. You can find these .NET Microsoft.Deployment.*.dll assemblies in the SDK subdirectory of the Wix Toolset installation directory. The documentation is in dtf.chm and dtfapi.chm in the doc subdirectory.
As shown in the documentation, you can use this SDK to write code which queries the msi database with SQL. You will be interested in the Feature, FeatureComponents and File tables.
If you haven't explored the internals of an MSI before, you can open it with orca to get a feel for it.
You can do it by making slight modifications to the Get-MsiProperties function described in this PowerShell article.
Please read the original article and create the prescribed comObject.types.ps1xml file.
function global:Get-MsiFeatures {
PARAM (
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="MSI Database Filename",ValueFromPipeline=$true)]
[Alias("Filename","Path","Database","Msi")]
$msiDbName
)
# A quick check to see if the file exist
if(!(Test-Path $msiDbName)){
throw "Could not find " + $msiDbName
}
# Create an empty hashtable to store properties in
$msiFeatures = #{}
# Creating WI object and load MSI database
$wiObject = New-Object -com WindowsInstaller.Installer
$wiDatabase = $wiObject.InvokeMethod("OpenDatabase", (Resolve-Path $msiDbName).Path, 0)
# Open the Property-view
$view = $wiDatabase.InvokeMethod("OpenView", "SELECT * FROM Feature")
$view.InvokeMethod("Execute")
# Loop thru the table
$r = $view.InvokeMethod("Fetch")
while($r -ne $null) {
# Add property and value to hash table
$msiFeatures[$r.InvokeParamProperty("StringData",1)] = $r.InvokeParamProperty("StringData",2)
# Fetch the next row
$r = $view.InvokeMethod("Fetch")
}
$view.InvokeMethod("Close")
# Return the hash table
return $msiFeatures
}

How to get specific version of folder from tfs without creating a workspace?

I would like to get the source code of a project at specific time (changeset). So I need do download whole folder. I would like to do it for different times and handling a different workspace is not very convenient.
I know about TFS Get Specific Version into separate folder (with workspace) and Need command to get a file from TFS without a workspace (one file).
Is there some solution for whole folder without creating a new workspace?
Edit
I have found the accepted answer too ambitious. I needed something more simple.
Assumptions:
I can access TFS from Visual Studio on my computer
I want to get the ChangeSetNumber Changeset from the folder
DesiredFolder in TFS project tProj
I run the following batch from a destination folder in Visual Studio Command Prompt
set workspace_name=TemporaryWorkspace%username%
set changeset= ChangeSetNumber
tf workspace -new %workspace_name% -noprompt
tf workfold -map $/tProj . -workspace:%workspace_name%
tf get $/tProj/DesiredFolder -version:C%changeset% -recursive -noprompt
tf workfold -unmap . -workspace:%workspace_name%
tf workspace -delete %workspace_name% -noprompt
It is necessary to confirm remove source control association when starting the downloaded solution.
I use this syntax for temporary workspaces:
tf workspace -new %JOB_NAME%;%user% -noprompt -server:http://%host%:8080/tfs/%project% -login:%user%,%password%
tf workfold -map $/Release/MilestoneX.X . -workspace:%JOB_NAME% -server:http://%host%:8080/tfs/%project% -login:%user%,%password%
tf get . -version:L%TFS_LABEL% -recursive -noprompt -login:%user%,%password%
tf workfold -unmap . -workspace:%JOB_NAME% -login:%user%,%password%
tf workspace -delete %JOB_NAME%;%user% -noprompt -server:http://%host%:8080/tfs/%project% -login:%user%,%password%
I've discovered that you can do this through the HTTP api that TFS exposes.
The "signature" for the URL is as follows:
http(s)://{server}:{port}/tfs/{collectionName}/{teamProjectName}/_api/_versioncontrol/itemContentZipped?version={versionSpec}&path={escapedPathToFolder}
So, if you have a project named "MyProject" in the DefaultCollection, and want to get the content of a folder called "MyFeature":
http://MyTfsServer:8080/tfs/DefaultCollection/MyProject/_api/_versioncontrol/itemContentZipped?version=C1001&path=%24%2FMyProject%2FMyFeature
I think "version" can be any version spec, which is documented in the TFS API documentation. My example is requesting the version as of change set 1001. I was using the .NET API to get a specific version, which is pretty straightforward, but slow because it can only get one file at a time. I'm trying to figure out if this same functionality is exposed through the .NET API because downloading the files this way is much much faster than getting a single file at a time.
I implemented this as an extension method on Microsoft.TeamFoundation.VersionControl.Client.Item. This returns a stream that contains a zip file. I had used this as part of a custom MSBuild task which then saves the contents of this stream to a file location.
public static class TfsExtensions
{
const String ItemContentZippedFormat = "/_api/_versioncontrol/itemContentZipped?version={0}&path={1}&__v=3";
public static Stream DownloadVersion(this Item folder, VersionSpec version)
{
if (folder.ItemType != ItemType.Folder)
throw new ArgumentException("Item must be a folder", "folder");
var vcs = folder.VersionControlServer;
var collectionName = vcs.TeamProjectCollection.CatalogNode.Resource.DisplayName;
var baseUri = folder.VersionControlServer.TeamFoundationServer.Uri;
if (!baseUri.LocalPath.EndsWith(collectionName, StringComparison.OrdinalIgnoreCase))
baseUri = new Uri(baseUri, baseUri.LocalPath + "/" + collectionName);
var apiPath = String.Format(ItemContentZippedFormat, version.DisplayString, WebUtility.UrlEncode(folder.ServerItem));
var downloadUri = new Uri(baseUri, baseUri.LocalPath + apiPath);
var req = WebRequest.Create(downloadUri);
req.Credentials = CredentialCache.DefaultCredentials;
var response = req.GetResponse();
return response.GetResponseStream();
}
}
I think you should create a temporary Workspace to retrieve the content you want, then delete the Workspace and keep the local items.
A Workspace in TFS is a local view of what's on the server, for a given Workspace you choose which folder(s) you want to retrieve locally and where you'll store the folders/files.
It's not like SourceSafe you're not bound to only one workspace, you can have as many as you want on a given computer.
So I suggest you to create a dedicated Workspace for the operation you want to do and get rid of it when you judge it appropriate.
Use the TF.exe workspace command to create/delete a Workspace from the Shell. Then TF.exe get to retrieve the files.
You can use tf view to get a specific file without creating a workspace.
Retrieves a specific version of a file to a temporary folder on your computer and displays it.
tf vc view [/collection:TeamProjectCollectionUrl]
[/console] [/recursive] [/output:localfile]
[/shelveset:shelvesetname[;owner]] [/noprompt] itemspec
[/version:versionspec] [/login:username,[password]]
Versionspec:
Date/Time D"any .Net Framework-supported format"
or any of the date formats of the local machine
Changeset number Cnnnnnn
Label Llabelname
Latest version T
Workspace Wworkspacename;workspaceowner