Visual Studio opens my class-file (.cs) in the designer mode - c#

I've created a class that extends DbConnection in a brand new project.
public class FakeDbConnection : DbConnection { ... }
In the Solution Explorer the class looks like this:
And when double-clicking it wants to open it in design mode which won't work. Opening up the .csproj-file reveals the problem
<ItemGroup>
<Compile Include="FakeADO\FakeDbConnection.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
Even if I remove the SubType tag VS2010 immediately re-adds it. Very annoying.
How can I stop VS2010 from opening up my .cs file in designer mode and just open it up as a regular code file?

As described in an answer to this question you can do this:
[System.ComponentModel.DesignerCategory("Code")]
class FakeDbConnection: DbConnection { ... }
Important: The attribute needs to be fully qualified otherwise VS2010 will ignore this.
Important (thanks to jmbpiano): The attribute only applies to the first class in the file.

The inheritance hierarchy indicates that this class (DbConnection) inherits from System.ComponentModel.Component. Try right click the file and View Source instead.
As always you can check MSDN! Here is the documentation for DbConnection.

Thats because DBConnection inherits "Component".
About disabling VS to add "Subtype" in csproj-file - I don't think thats possible.
You can still aceess the code, by right-clicking in designer -> show code (I think "F7" is the shortcut key for that)

Related

Access source generated class property/method in main code MSVS 2022

I created my first source generator (ISourceGenerator) with public property and public method.
Let this class be like this:
public partial class MyClass1 // Manually written code
{
}
public partial class MyClass1 //Source Generated code
{
public string GeneratedProperty { get; set; }
public string GeneratedMethod() => "lala";
}
Both of these classes are located in the same namespace (for example, MyNamespace - it doesn't matter really).
So, I'm trying this:
var myClass = new MyClass1(); // Correct
Console.WriteLine(myClass.GeneratedMethod()); //Wrong, "MyClass1 doesn't contain definition for GeneratedMethod..."
When I say MSVS generate sources as files in the concrete directory, I have the code above working well.
So, I want to have an ability to use generated code "on fly" when I write code without generation source files each time manually. Also earlier manually generated source files are not deleted when I'm generating new source files.
Is it possible?
Thank you.
UPD. I have this message from Visual Studio:
"Warning CS8032 An instance of analyzer Generators.Factory.AbstractFactoryGenerator cannot be created from ...\bin\Debug\netstandard2.0\SourceGeneratorsLibrary.dll: Exception has been thrown by the target of an invocation."
Maybe this significant?
UPD2. https://pastebin.com/qtvrugu3 - this is my Source Generator code. Pls, don't blame me, It's just my first steps.
As far as I know, programming is case sensitive, well at least C# so myClass() is different from MyClass(). also hence you are using the string data type, try casting it as string via
Convert.ToString(MyClass1().GeneratedMethod());
or
MyClass1().GeneratedMethod().ToString();
hope this answers you question.
It seems you have developed your analyzer but not actually referenced it from a project?
To use your analyzer you simply add it as as project reference, but make sure it's marked up as an analyzer in the .csproj file:
<ItemGroup>
<ProjectReference Include="MyGenerator\MyGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
Or something like that, adjusted to your solution.

MvvmCross.Exceptions.MvxException: Failed to create setup instance

I'm upgrading from MvvMCross 5.7 to 6.0.0.
When I try to run the app, it shows the splash screen and just after that, vs2017 gives me the following error:
MvvmCross.Exceptions.MvxException: Failed to create setup instance
The error always is in the same line, no matter which file I set as mainlauncher.
Example:
using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using MvvmCross.Platforms.Android.Views;
namespace ClaveiSGApp.Droid.Views
{
[Activity(Label = "App", MainLauncher = true)]
public class MainView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.MainView);
}
}
}
The error always is in base.OnCreate(bundle);
Do you have any ideas?
(Let me know if you need more info/code about something)
From the error you're getting, it looks like something bad is happening in CreateSetup method in MvxSetupSingleton (GitHub). I'm guessing here a bit, but I would assume that there's something wrong with how the RegisterSetupType<TMvxSetup> is being called (or it's not being called at all) - you can find this method in MvxSetup (GitHub). Tracking down where the registration happens, it gave me two possible places: MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and MvxAndroidApplication<TMvxAndroidSetup, TApplication>.
Going forward with this thinking, and assuming you do use SplashScreen in your app. I would suggest updating your SplashScreen activity to inherit from MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and check if that helps - you would also need to make your SplashScreen is MainLauncher. Your code could look like this:
[Activity(Label = "FirstDemo.Forms.Splash", Theme = "#style/MainTheme", MainLauncher = true, NoHistory = true)]
public class SplashScreen : MvxFormsSplashScreenAppCompatActivity<MvxFormsAndroidSetup<Core.App, App>, Core.App, App>
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
protected override void RunAppStart(Bundle bundle)
{
StartActivity(typeof(MainActivity));
base.RunAppStart(bundle);
}
}
If the above is not clear, check out blog post by Nick Randolph (a contributor to MvvmCross), that writes about setting up a brand new project with MvvmCross v6. I know you're upgrading - so it's not the same, but you can at least check if you have made all the changes that are required to run the app. Here's his GitHub repo, with the sample code that I pasted in
After I few days, searching, seeing gihub files and talking with Nick Randolph as #Ale_lipa suggested.
I noticed that the problem was on the .csproj file under the .Droid project. It was trying to compile files that I manually removed from the project and didn't even exist.
I changed it to match the file that Nick has in his repository.
This is the final look:
<ItemGroup>
<Compile Include="SplashScreen.cs" />
<Compile Include="MainApplication.cs" />
<Compile Include="Resources\Resource.Designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Views\FirstView.cs" />
</ItemGroup>
Now everything works fine.
I followed the exact steps on the blog post series by Nick Randolph referenced in other answers, and received the same problem as the question specifies [Failed to create setup instance] but in the Xamarin.Forms article. This was due to mixing code from a different part of the example. My specific issue was because the ActivityAttribute that declared MainLauncher=true derived from MvxFormsAppCompatActivity<TViewModel> instead of MvxFormsAppCompatActivity<TMvxAndroidSetup, TApplication, TFormsApplication, TViewModel> Looks like the OP #Brugui sample code may have had the same flaw.

Rename classes using Visual Studio Project Template

I have created a Visual Studio template using this link: http://msdn.microsoft.com/en-us/library/ms185301.aspx.
I am able to create a dialog where the user enters a custom message and it gets displayed:
namespace TemplateProject
{
class WriteMessage
{
static void Main(string[] args)
{
Console.WriteLine("$custommessage$");
}
}
}
What I want to do it allow the user to rename the class names so I want to do something like:
But you see I'm getting errors of "Unexpected character $"
How can I do this?
EDIT
I see from this link: http://msdn.microsoft.com/en-us/library/eehb4faa(v=vs.110).aspx that
To enable parameter substitution in templates:
In the .vstemplate file of the template, locate the ProjectItem element that corresponds to the item for which you want to enable parameter replacement.
Set the ReplaceParameters attribute of the ProjectItem element to true.
BUT above I have not yet generated the template yet as I am still defining the classes. I understnad that the above step needs to be done in order to get the parameter substitution enabled for a File-->New Project scenario.
It looks like you have your template file as a cs file, which is causing Visual Studio to attempt to build it directly.
From what I can tell you should create a functioning Project, export it, and then modify the resulting template to add any replacements you need.

Adding custom format to a template parameters Visual studio project

I have defined a Visual Studio template called classDB.cs. I would like the default name for the class to appear as [projectname]DB.cs, where [projectname] is the name of the current project (as entered in the Create Project dialog). Is there a way to achieve this? I tried setting the name of the class to $safeprojectname$DB.cs, but that didn't work.
UPDATE
I modified my project template but give's this error when it's generating the project
here's the template class
namespace $safeprojectname$.Models
{
public class $safeprojectname$DB : DbContext
{
}
}
I have been battling with a similar error to this for days, and I finally figured it out. Visual Studio escapes the $ in the .csproj file. So you will have a node that looks like this:
<Compile Include="Models\%24safeprojectname%24DB.cs" />
Open up the .csproj file in a text editor, and change it to:
<Compile Include="Models\$safeprojectname$DB.cs" />
And save the file. Your project will reload, but it won't try to escape the filename again! Export your template, and you should find that the parameter now gets replaced.
Try a template like this:
using System;
//...
namespace $rootnamespace$ {
class $safeitemname$DB {
}
}
Works for me.
Make sure you update the correct template (should be located under C:\Users\[user]\Documents\Visual Studio 2010\Templates\ItemTemplates on Windows 7) and restart Visual Studio.
EDIT
The above code is for an Item Template, but that shouldn't differ from a Project Template. According to MSDN, the $safeitemname$ and $safeprojectname$ parameters behaves the same:
safeitemname
The name provided by the user in the Add New Item dialog box, with all unsafe characters and spaces removed.
safeprojectname
The name provided by the user in the New Project dialog box, with all unsafe characters and spaces removed.

The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined

For a little background:
I have a DLL project with the following structure:
Rivworks.Model (project)
\Negotiation (folder)
Model.edmx (model from DB #1)
\NegotiationAutos (folder)
Model.edmx (model from DB #2)
I have moved the connection strings from this project's app.config to the web.config file. They are not in the ConnectionString section. Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].
<FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</RivWorkEntities_connString>
I have 2 classes, one for each Context and they look like this:
namespace RivWorks.Model
{
public class RivWorksStore
{
private RivWorks.Model.Negotiation.Entities _dbNegotiation;
public RivWorksStore(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.Negotiation.Entities NegotiationEntities()
{
return _dbNegotiation;
}
}
}
namespace RivWorks.Model
{
public class FeedStoreReadOnly
{
private RivWorks.Model.NegotiationAutos.Entities _dbFeed;
public FeedStoreReadOnly(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
{
return _dbFeed;
}
}
}
You will note that the MetaData is being rewritten to a short version.
When I comment out that line in each class I get this error:
Unable to load the specified metadata resource.
When I leave that line in in each class I get this error:
Schema specified is not valid. Errors:
Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.
I know it is something simple, something obvious. Any suggestions welcome...
Hijacking this, since it is the top Google result for the error message.
In case anyone else encounters this while only using a single model/context: I once ran into this problem because the assembly containing the model/context was renamed and a copy with the previous name remained in the bin directory of the application. The solution was to delete the old assembly file.
Your two EDMX files probably have the same entity container name. You need to change (at least) one of them.
In the GUI designer, open Model Browser. Look for a node that says "EntityContainer: Entities". Click it. In Properties, change Name to something else. Save and rebuild.
I had the problem too but my solution was to clean the bin directory and then remove the connection string with the entity container name. Then I could rename my entities and put back the connection string.
I renamed my project but the old file was still in the bin folder. I just had to delete the old DLL from the bin folder.
I have found a way to save multiple containers with the same name (namespaced of course).
In EF5 and VS2012 you can set three different namespaces. First you can click on the edmx file in the solution browser and in the properties windows you can set the "Custom Tool Namespace", you can click on the *.Context.tt file right below the edmx and set another namespace there, and finally thanks to a lead from Mr Stuntz awesome answer I realized that by opening the edmx file and clicking in the white space you get another namespace field under Schema in the properties window.
Think we're done, not quite, I know you can see the Entity Container Name field and will try to change the name there but that doesn't seem to work, you get a little error that pops up. Ensure that all your edmx files have an individual namespace there. (I ensured I had a unique namespace in all three places)
Then go to your Model Browser and right click on EntityContainer: Entity to go to properties and change the name of your container(s). From that window with the namespace set everywhere I was able to get multiple contexts with the same name. I was dealing with things like blahcontext and blahcontextcontainer all of a sudden even though they were in different folders.
When you see that its a namespace problem. Or lack thereof.
In my case, the problem was caused by my connection string in Web.config being named the same thing as my entities container class.
Change
<add name="ConflictingNameEntities" connectionString="metadata=res://*/blahblah
to
<add name="ConflictingNameEntitiesConnection" connectionString="metadata=res://*/blahblah
and regenerate the container class by right-clicking ConflictingNameModel.Context.tt in Solution Explorer and clicking "Run Custom Tool".
I just ran into this. It looks like somehow Entity Framework got into a bad state in terms of what tables it thought it needed to add.
Normally EF will not recognize that a new table has to be created until you put the line
public virtual DbSet<NewTable> NewTable { get; set; }
inside your context class.
However, EF somehow got into a bad state where the mere presence of the NewTable class in my solution was triggering it to think that it needed to generate that table. So by the time the above line in the context triggered it to create a NewTable table, it already thought it had done it, hence the error about duplicate entities.
I just removed the NewTable class from my solution, commented things out so it would compile again (thankfully there wasn't too much of this), then added a new migration to make sure it was blank as it should have been. Then once things were back into a more predictable state, I re-added the NewTable class back into the solution and adding the migration worked fine.
If you are using web deployment from Visual Studio sometimes doesn't delete the old dlls. I had the same problem, change to Web Deployment Package and didn't give me problems.
I had a same problem in my asp.net website, to resolve the problem I purposely added compile time error in one of the cs file in the app code by removing a semicolon, then I rectified the compilation problem by adding semicolon again.
This process caused application to compile again.After this error got vanished.
The other cause of this problem, your add model in any solution project and change your model project.
--PROJECT A --> MODEL.EDMX
--- WEB CONFIG -->Entity Connection
--PROJECT B
--- WEB CONFIG -->Entity Connection
Later, I think this structure is bad and Change project.
--PROJECT A
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT B
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT C (CLASS LIBRARY) --> MODEL.EDMX
--- APP.CONFIG -->Entity Connection
Everything was fine but I get an error.
Error Detail : The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
Because I forgot change Web.Config files.
OLD WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;persist security info=True;user id=1;password=1;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
NEW WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*/EntityModel.Model.csdl|res://*/EntityModel.Model.ssdl|res://*/EntityModel.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;user id=sa;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This Problem is Simple but may cause loss of time. I wanted to give an example. I hope is useful.
Thanks.
To solve the issue Entity 6.2.0, VS 2017, single edmx
I changed the name of my model.edmx to another name, built the project, then changed it back to the original name.
In my case, probably after merging a version back, my startup project file (csproj) got corrupted.
Al the Entity classes where added:
<Compile Include="Class.cs">
<DependentUpon>MyModel.tt</DependentUpon>
</Compile>
After removing all relevant entries by hand the problem was solved.
Strange problems have strange answers, so please do not blame.
first, take a quick look at this part of code
I got a problem the problem
The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
with this class name 'ShippingSpeed_Month_Speed'
The solution for me was just renaming 'speeds' to 'speedsx'.
So, you MAY need to rename something like the ending name of the relation or navigational property which is the same ending of the same table name or the ending name of the DbSet<>
I'm answering to document what worked for me and hoping to benefit others.
Thanks
No bin, just aspx/edmx ? Just move the shema files (mode.edmx + model.designer.vb) refresh and put them back ! IIS/aspnet probably corrupt for x reason.

Categories