Controlling values in .NET 6 templates - c#

I have a .NET 6 solution template that I maintain. Like other templates, if the user chooses "Foo" as the name of the solution, the C# namespaces have the sourceName value replaced with Foo, along with class names that have the sourceName value in them. For instance, if you choose to have EF in the output, you'll get an IFooDbContext.
However, if you run the template with a period in the name, bad things happen. For example, dotnet new mytemplate -n Foo.Bar, I get a class called IFoo.BarDbContext, which is clearly not valid C#.
Is there a way in the dotnet templating system to remove the period so that if comes out as IFooBarDbContext? I've spent about an hour looking around on Google prior to posting this question, but didn't see anything obvious. If the answer is no, I'll just require that the user specify the name of the DbContext should they choose to include EF.
Thanks in advance!

Ultimately, I was still not able to figure out a good way to do this. My Entity Framework DbContext class, in the template, is named in a way that it will be replaced with the project name when creating a new project. I decided to just rename the DbContext class to ApplicationDbContext. Now, with or without a dot in the name doesn't matter, as the EF DbContext class is not renamed. The end user can rename the DbContext themselves if they want to via a new parameter that I'm adding in; otherwise it just stays as ApplicationDbContext.
Thanks for taking a look, but I'm going to go ahead and move on from this, having found a solution that will work.

Related

Basic EntityFramework Testing

I'm relatively new to EntityFramework and really want to get into testing things before I get too much further into things and have a huge codebase to retrospectively write tests for. I've not used it much and so methods are fairly basic, like below;
public Employee GetEmployee(int employeeID)
{
using (DatabaseContext db = new DatabaseContext())
{
return db.Employees.SingleOrDefault(e => e.idEmployee == employeeID);
}
}
This is fine in my app, but in my test project, it doesn't work because the test project doesn't seem to read the app.config file and so there's no connection string for DatabaseContext to use. I've read a bit about testing, nothing seems really definitive, though this post is the "official" way to do things (it's linked to from MSDN. The post seems fairly involved though and would require me to do things a lot differently than what I currently am, unless I've misunderstood some of it?
Could someone help clear this up for me? I can't even cheat and copy app.config across to the test project, it still doesn't read it (I've also tried renaming to MyApp.exe.config and still no luck). Is my GetEmployee method wrong? Should I do something more like the linked post? Or is there some way to test that I've not found yet?
#FizzBuzz - here is another article the discusses how to setup your unit test projects to work with entity framework:
How to get Entity Framework to read my app.config file in Unit Test project
You can read one approach for integration testing here.
About the config issue setting Copy to Output Directory property to Copy Always should do the work.
There are to options to resolve the issue you are facing.
Option 1: Create a mock for the app.config values. for mocking you can use Rhino Mock
Option 2: In your Unit Test project : Right click on the project > Add > Existing Item >
Select File > Add it as a link.
If you don't want to go with your live database (and right so!), then you basically have two options:
Use another database (must be of the same kind as your live db,
since EF doesn't allow for changing the db system, only its
location) and add another app.config to your unit test project
(which is the same as in your live project except that the db
connection string is different).
Use the NDbUnit framework, which
allows for defining the data in xml files. Here also you'll need an
individual app.config for your test project, if you don't want to hardcode the test data connection string. (This approach is only
advisable, if your live db has no or only very few schema changes,
because NDbUnit is quite allergic to these.) I wrote a blog post (with sample solution) about this approach here.
A third approach would be to mock all EF stuff, but this quickly gets overly complicated (you can find this also in a previous part of the above mentioned post, if you're interested).
HTH
Thomas
Thanks for the information people, found some interesting hints and tips through the various links supplied. In the end, I tried out this article from MSDN, funnily enough! Though it says it's for EF6, it does actually work for previous versions. The reason it indicates EF6 is for async stuff.

Why am I getting DbContext Has Changed exception when using NUnit?

I'm using Entity Framework 5 in my project. And I wanted to test some new funcionalities.
What happened is that eventhough my db is UPDATED, (when I add a migration it does not add anything else) and eventhough if I run my project it runs just fine. When I try to test the project with NUNIT I get this exception:
System.InvalidOperationException : The model backing the 'DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
Has any of you have this problem? If so how can I solve it?
Well, my original answer got deleted, guess because it wasn't really an answer as much as a statement that I had the same problem. At this point I have found an answer of sorts, so maybe this one will pass muster.
Of course, I only assume we are having the same issue, but it seems pretty likely since the symptoms are exactly the same. What I discovered is the connection string for my repository was not getting set correctly even though I had set it up "correctly" in a config file using the MyTestProject.dll.config naming convention. Seems like NUnit isn't using the connection string from the config for some reason.
I've set up a temporary solution where I use a different constructor that forces the correct connection string for my repository when creating it for NUnit. Easy to implement this since I'm using DI to create the repository and just need to ask the factory for a different flavor when testing. Working now to figure out why NUnit doesn't use the config file as it seems like it should.
Maybe not a complete answer, but at least this solution got me back to where I can test... We'll see if this one gets deleted.

namespace and table sharing the same name (oops!)

First - I admit to my mistake!
But I need to know if I should try to fix it, or just live with the consequences.
I created a new solution (C#, VS2010) - let's call it 'F.PIA', for ease of reference. One of the things this solution does is work with a SQL Server table that - yep, you guessed it - is also named 'PIA'. So everything about my project - including the main namespace - is F.PIA.
I'm using F.A.PIA, to access the PIA table; this assembly includes a Table and a public partial class PIA.
In my solution, I can distinguish the two, but I find references to F.A.PIA to be clumsy (the actual names are significantly longer than that example).
So I tried to Refactor, w/o success. I'm pretty sure the renaming changes something in the DataSetDesigner, or doesn't change something there (or a related item) - but I'm not nearly proficient enough to figure out what, exactly, goes wrong - nor how to fix it. (Yes, I did have a working backup before the Refactor - YAY.)
Should I just leave it as is, and learn from my mistake for next time? or is there a way to rename everything except the references to my table, and get everything to behave?
Thanks! -- Scott M
Options:
Create namespace alias for the C# namespace by the using directive.
Create a class wrapper which handles the PIA table and provides a more user friendly way of accessing that table.
Fully quailify the namespace items for the C# namespace.
Rename the table, refactor, then change the name back.
Create a new solution which does not have the naming collisions.
Live with the idiosyncrasis as is...

How to use IObjectWithChangeTracker Interface?

I have been searching EVERYWHERE for this IObjectWithChangeTracker Interface that I think I need for a problem in my current project and I FINALLY discover (via this) that it isn't actually built into .Net
What I still can't figure out is how in the world do I use it!! I can't find the code anywhere, I have no idea what these T4 things are. Or where I find them. Someone help?
That site is specific for silverlight - entity framework already has self tracking entities.You can attach new objects you create as modified, deleted, etc, but altering a current object automatically tracks its state. So - what are you trying to do? : )
t4 files are code generation files. You can basically include a template (.tt file) in your project and when you run your project, the file is processed and generally create one or more code output files.
See:
http://msdn.microsoft.com/en-us/library/bb126445.aspx

How to strongly type properties in JavaScript that map to models in C#?

I'm not even sure if I worded the question right, but I'll try and explain as clearly as possible with an example:
In the following example scenario:
1) Take a class such as this:
public class foo
{
public string firstName {get;set;}
public string lastName {get;set}
}
2) Serialize that into JSON, pass it over the wire to the Browser.
3) Browser de-serializes this and turns the JSON into a JavaScript object so that you can then access the properties like this:
var foo = deSerialize("*******the JSON from above**************");
alert(foo.firstName);
alert(foo.lastName);
What if now a new developer comes along working on this project decides that firstName is no longer a suitable property name. Lets say they use ReSharper to rename this property, since ReSharper does a pretty good job at finding (almost) all the references to the property and renaming them appropriately.
However ReSharper will not be able to rename the references within the JavaScript code (#3) since it has no way of knowing that these also really mean the same thing. Which means the programmer is left with the responsibility of manually finding these references and renaming those too.
The risk is that if this is forgotten, no one will know about this error until someone tests that part of the code, or worse, slip through to the customer.
Back to the actual question:
I have been trying to think of a solution to this to some how strongly type these property names when used in javascript, so that a tool like ReSharper can successfully rename ALL usages of the property (and accurately)?
Here is what I have been thinking for example (This would obviously not work unless i make some kind of static properties)
var foo = deSerialize("*******the JSON from above**************");
alert(foo.<%=foo.firstName.GetPropertyName()%>)
alert(foo.<%=foo.lastName.GetPropertyName()%>)
But that is obviously not practical. Does anyone have any thoughts on this?
Thanks, and kudos to all of the talented people answering questions on this site.
This is kind of an experiment of mine, so any suggestions would be welcome.
Most refactoring tools have a mode where they examine a fulltext search of the codebase to find usages. (I know ReSharper has that option.) That would solve at least part of the problem. Comprehensive integration tests would also go a long way to solving some of the issues you mention.
Another way to solve the issue would be to couple less tightly your wire format (i.e. the JSON) and your type hierarchy.

Categories