Change name of generated Context file with EF PowerTools Reverse Engineer Code First - entity-framework

I have been attempting to figure out how to make the EF Power Tools - Reverse Engineer Code First use a different name for the generated Context-file, than what it uses now.
Example
I have a database called My_Awesome_Dev_Database. When I run Reverse-engineer against that, the file that is generated will be called:
My_Awesome_Dev_DatabaseContext.cs
What it would like to do is specify what the file is to be called, for instance:
MyAwesomeDatabaseContext.cs
Attempts so far
I have tried looking through the EF.Utilities.CS.ttinclude file, to figure out how the filename is generated - but I have been unsuccessful so far.
Does anyone know ?
Thanks in advance!

Currently the generated context file naming convention is hard-coded and non configurable.
All the logic is inside the ReverseEngineerCodeFirstHandler class (the source is on CodePlex).
It sets the context file name and path with
var contextFilePath = Path.Combine(modelsDirectory,
modelGenerator.EntityContainer.Name + contextHost.FileExtension);
var contextItem = project.AddNewFile(contextFilePath, contextContents);
So the file name is coming from modelGenerator.EntityContainer.Name which gets created upper in the method with:
var contextName =
connection.Database.Replace(" ", string.Empty)
.Replace(".", string.Empty) + "Context";
var modelGenerator =
new EntityModelSchemaGenerator(storeGenerator.EntityContainer,
"DefaultNamespace", contextName);
So as you can see the tool just takes the db name removes the spaces and dots and use it as the context name which will end up as the generated file name.
You can open an issue or - because Entity Framework is open source - take the code, add this configuration option, and send back a pull request.

Related

Bukkit - Why is it displaying null (using a config file)

So, I am making a custom plugin for my server, and one of my features requires me to set an integer in a gui that shows how many 'CommonPackages' a user has. The issue that I am having is that when I am getting the String from my config (My config uses a custom file creation/management class that was given to me by a friend) it is saying that it is null in the gui, I do not get any errors in the console, please may someone help me? The item in the gui and the code for setting the item in the gui.
Item in the gui
gui creation code:
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("players." + uuid + ".Packages.Common"))); //How I access my custom configs.
common.setItemMeta(commonMeta);
inv.setItem(10, common);
return inv;
}
Without the code of your method to get the config I can only say that the string in the actual file is not present.
As the Bukkit documentation states:
If the String does not exist and no default value was specified, this will return null.
So either the key just does not exist in the file or you pointed to the wrong file. The configuration should be well formated, too. (no tabs, only spaces)

TypeLite generate external modules?

I am trying to generate external modules rather than a type definition file. I believe I need to do the following:
Change the extension of the file to .ts instead of .d.ts.
Generate one file per module.
Add the key word "Export" in front of each interface and enum.
I was easily able to change the extension of the file by changing the "output extension" setting in the tt file.
I cannot figure out how to split the modules into separate files.
I cannot figure out how to add the Export key word to each interface.
TypeLITE doesn't support generating multiple files. This feature has been requested by several users, but I am not aware of a simple way to generate multiple files from the single tt file.
export keyword can't be added without changing source code of the library (TsGenerator.cs). This is very specific requirement, so I probably won't add it to the library.
TypeLite is a good project but lacking in Documentation and examples, it's open source so anyone can contribute and make it better.
As for creating a file per class i solved it using the code below.
private static void GenerateTypeScriptContracts(string assemblyFile, string outputPath)
{
// Clean TS Folder
System.IO.DirectoryInfo di = new DirectoryInfo(outputPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
// --
var assembly = Assembly.LoadFrom(assemblyFile);
// If you want a subset of classes from this assembly, filter them here
var models = assembly.GetTypes();
foreach (var model in models)
{
var generator = new TypeScriptFluent()
.WithConvertor<Guid>(c => "string")
.WithMemberFormatter((identifier) => Char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1));
generator.ModelBuilder.Add(model);
// Generate TS interface definitions
var tsClassDefinitions = generator.Generate(TsGeneratorOutput.Properties | TsGeneratorOutput.Fields);
File.WriteAllText(Path.Combine(outputPath, "I" + model.FullName.Replace("ProjectName.DtoModels.", "") + ".ts"), tsClassDefinitions);
}
}

How can l use Entity Framework without App.config

I want to use Entity Framework without app.config file.
I want to define a string variable Connection String in my code and use that to connect to the database.
Please show me the way if it is possible.
You're not mentioning what approach you're using (database-first, model-first, code-first) - but basically, in the end, you need to define a string variable and assign it a valid EF connection string
string myConnectionString = "...(define a valid EF connection string here)......";
Example for database-first approach:
string myConnectionString = #"metadata=.\Model1.csdl|.\Model1.ssdl|.\Model1.msl;provider=System.Data.SqlClient;provider connection string="";data source=.;initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""";
and then use that to create your ObjectContext (database- and model-first) or DbContext (code-first)
using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
// do your EF magic here.....
}
But quite honestly - I think this is a really bad idea since this makes it impossible for you to move your application to another machine - no one else can install and run this, since the connection string is hard-coded into your C# code..... the whole point of having config files is so that you can change / adapt things like connection strings so that they are not tied to a single machine/location but can be adapted to the particular needs of a given user / customer....

How can I Diff a Svn Repository using SharpSvn

My question is quite simple and with the SharpSvn Api, it should be easy as well. Here what I did:
path = "c:\project";
using (SvnLookClient client = new SvnLookClient())
{
SvnLookOrigin o = new SvnLookOrigin(path);
Collection<SvnChangedEventArgs> changeList;
client.GetChanged(o, out changeList); // <-- Exception
}
and when I call the GetChanged, I get an exception:
Can't open file 'c:\project\format': The system cannot find the file specified.
So, Maybe there is something I'm missing? Or maybe it's not the right way to do find out the list of files and folders that were modified in the local repository?
Thanks in advance.
The SvnLookClient class in SharpSvn is the equivalent to the 'svnlook' console application. It is a low level tool that enables repository hooks to look into specific transactions of a repository using direct file access.
You probably want to use the SvnClient class to look at a WorkingCopy and most likely its Status() or in some cases simpler GetStatus() function to see what changed.
The path that the SvnLookOrigin constructor wants is actually:
path = "c:\project\.svn\";
That is, it wants that special ".svn" directory not just the root of where the source is checked out to.
Although you probably do want to listen to Bert and do something like:
path = "c:\project";
using (SvnLookClient client = new SvnLookClient())
{
SvnLookOrigin o = new SvnLookOrigin(path);
Collection<SvnChangedEventArgs> changeList;
client.GetStatus(o, out changeList); // Should now return the differences between this working copy and the remote status.
}

Is it possible to retrieve connection string inside DDL generation template in VS2010?

I am playing around with creating a T4 template for the "DDL Generation Template option" (model first) process in Visual Studio 2010 RC. Is it possible to retrieve the connection string that is associated with that process? If I right click on the .edmx file and choose "Generate Database from Model..." I have the option of choosing a data connection. That connection string is saved to the app.config (assuming that the option is checked). So I am wondering if it is possible to retrieve that connection string inside the T4 template. I would like to generate different information from the template based on the connection string.
More generally, is it possible to get any context information in this situation? So far, the only thing I have successfully retrieved is the .NET data provider name.
Note - I have studied the ideas provided by Craig but am only getting the name of the IDE (devenv.exe), which quite possibly means I am just doing something wrong.
In case this helps anyone else, here is a snippet I created to read the Entity Framework connection string from inside T4. You pass it the model name (which is also the name of the connection string). It finds and parses just the connection bit I need. It also throws helpful errors when it does not succeed.
To use:
A. Paste this at the top of your template if you aren't already referencing these assemblies:
<## assembly name="EnvDTE" #>
<## assembly name="System.Configuration" #>
B. Paste this ugly (but compact) code at the end of your template:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
C. Use it like such:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
I posted my question on one of the MSDN forums and got a response from Lingzhi Sun who pointed me in the direction of a couple of links at skysanders.net. The second of these links has a very nice example of getting to the app/web.config file and, specifically the part I wanted, the connection strings. It doesn't give any information on the specific connection string for the scenario I described in the original question, but this gets me close enough.
Accessing app.config/web.config from T4 template
Accessing app.config/web.config from T4 template - Take 2
Well, the EF connection string will always have the same name as the model, right? The DB connection string will be embedded in the EF connection string. So I'd say you should be able to get it, at least indirectly, via the EF connection string.
Because you're not running in the assembly, have to specify the config file name.
So it would be something like:
var config = ConfigurationManager.OpenExeConfiguration(name);
var cs = config.ConnectoinStrings[modelName];
Note that name, here, is supposed to be an EXE name. But in the IDE, your config fine is going to be called App.config rather than MyApp.dll.config. So you may have to play around with this to get it to work -- try using "App" as the EXE name!
Worst case is open it as a file and then use the config manager.