Move code file under another file in project - c#

I want to move one code file under the group of another, related file, like here:
As you see, SingleObjectViewModel.Commands.cs is hidden in SingleObjectViewModel.cs group. It can be useful in some cases.
I've created SingleDocumentViewModel.Commands.cs but simple drag-n-drop in Visual Studio do not work.
How to achieve it?

I found one way of doing this, but it is not user-friendly and needs to edit project file by hands. I'm not sure it will work in other versions of Visual Studio then mine (MS Visual Studio 2013)
First, unload project (right-click on project, Unload Project).
Then edit csproj file (right-click again, Edit *.csproj)
In editor, replace:
<Compile Include="SingleDocumentViewModel.Commands.cs">
with
<Compile Include="SingleDocumentViewModel.Commands.cs">
<DependentUpon>SingleDocumentViewModel.cs</DependentUpon>
</Compile>
Then save edited file and load project again (right-click on it, Reload project).
Now files are grouped:

Related

Include manually (not through VS) a file into csproj without being overridden

I am trying to develop a project that generates code. One of the code files it generates is sql code and I am trying to include it in one of the projects of my solution.
Since I didn't find yet a solution to do this programmatically, I tried to modify the .csproj manually:
<ItemGroup>
<Build Include="DIL\*.sql" />
</ItemGroup>
What my code does it generate a Test.Sql and places it into the DIL folder without including it in the project. If I then go modifying the .csproj as shown above and reload the .csproj itself I will find the Test.sql being added.
However there will be no Build Include="DIL*.sql" / anymore in the .csproj, meaning that if I generate another sql file it will not be added automatically to the project. Is there a permanent solution to this by any chance? Thanks in advance!

Visual studio creates unusual files automatically when Press CTRL + S [duplicate]

My company uses a combination of some database tables, a web page front end and an "export" application to handle our string resources in our web sites.
The export application used to work just fine when we used VS2008, but since switching to VS2010 the resources now have a designer.cs file "beneath" them in the solution explorer.
The problem is that the "export" application only generates the .resx files and not the underlying designer.cs files.
So, is there a way to not have those designer.cs files, or alternatively some way to automatically re-generate (or even some command the export application could call to re-generate them)
I had a problem where VS 2010 would not regenerate the Designer.cs files, and couldn't find the solution elsewhere.
I was able to regenerate them though, without going to the command line.
To fix the issue in Visual Studio 2010 I did the following:
Deleted the Designer.cs file
Right clicked on the main resx file
Selected Run Custom Tool
That rebuilt the Designer.cs file.
Hope that might help someone else in the future..
From MSDN we have:
Compiling Resources into Assemblies
When you build your application, Visual Studio invokes the
resgen.exe tool to convert your application resources into an
internal
class called Resources. This class is
contained in the Resources.Designer.cs
file which is nested under the
Resources.resx file in Solution
Explorer. The Resources class
encapsulates all your project
resources into static readonly get
properties as a way of providing
strongly-typed resources at run-time.
When you build through the Visual C#
IDE, all the encapsulated resource
data, including both the resources
that were embedded into the .resx file
and the linked files, is compiled
directly into the application assembly
(the .exe or .dll file). In other
words, the Visual C# IDE always uses
the /resource compiler option. If you
build from the command line, you can
specify the /linkresource compiler
option that will enable you to deploy
resources in a separate file from the
main application assembly. This is an
advanced scenario and is only
necessary in certain rare situations.
If you prefer to automatically generate the *.designer.cs files from *.resx files when building the project, the following approach worked for us and it might work for you as well:
Close your solution
Open as an XML file the project file in which you want to automatically generate the designer files. Note that you need to load it as an XML file. You can't edit these settings through the project property page.
Add a target to the project as follows:
<Target Name="GenerateDesignerFiles">
<Message Text="Deleting old Designer Files..."/>
<Delete Files="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).resources')"/>
<Delete Files="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).designer.cs')"/>
<Message Text="Generating Designer Files..."/>
<GenerateResource
Sources="#(EmbeddedResource)"
StronglyTypedLanguage="C#"
StronglyTypedClassName="%(Filename)"
StronglyTypedNamespace="#(EmbeddedResource->'%(CustomToolNamespace)')"
StronglyTypedFileName="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).designer.cs')"
PublicClass="true"
>
</GenerateResource>
<Message Text="Generating Designer Files complete."/>
</Target>
Locate the target named "BeforeBuild". This target may be commented out (the default).
Modify the "BeforeBuild" target as follows:
<Target Name="BeforeBuild">
<CallTarget Targets="GenerateDesignerFiles"/>
</Target>
This solution is based on all resource files being listed as "EmbeddedResource" within an ItemGroup of the project file, e.g.
<ItemGroup>
<EmbeddedResource Include="Resources\Creditor\Display_Creditor.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Display_Creditor.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.Creditor</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="Resources\InboundEmail\Tooltip_InboundEmailDetails.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Tooltip_InboundEmailDetails.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.InboundEmail</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="Resources\Creditor\Tooltip_CreditorDetails.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Tooltip_CreditorDetails.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.Creditor</CustomToolNamespace>
</EmbeddedResource>
</ItemGroup>
Disclaimer: This has been tested with Visual Studio 2013 and C# projects. It may or may not work for other projects and/or other versions of Visual Studio.
Try this:
Right click on resx file
Click on properties
Set the properties:
Copy to output Directory : Copy always
Custom tool : PublicResXFileCodeGenerator
Save and build again.
Problem solved.
Following these steps worked for me.
Delete your designer.cs file.
Click on properties
Out put directory - copy always.
Custom tool: PublicResXFileCodeGenerator
Save and build.
Right click on resx and
Click run custom tool.

Visual Studio: How to "Copy to Output Directory" without copying the folder structure?

I have a few dll files in \lib folder of my project folder. In the property page of dll, I have selected "Build Action" as "Content" and "Copy to Output Directory" as "Copy always".
After build I am actually getting the dll copied but they are inside \bin\Release\lib and not in \bin\Release.
Is there a way to copy dll files to \bin\Release (and not to \bin\Release\lib) without writing a post-build script or resorting to nant etc?
instead of <Content> use <ContentWithTargetPath> and specify target path, like this:
<ItemGroup>
<ContentWithTargetPath Include="lib\some_file.dat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>some_file.dat</TargetPath>
</ContentWithTargetPath>
<None Include="lib\some_file.dat" />
</ItemGroup>
Note that this entry may not be visible from Visual Studio (2012, 2015, 2017), but once manually added to the csproj, it will appear in Visual Studio. The target path will not be editable through the UI though.
Adding a <None> entry for the file will ensure that it still shows up in Visual Studio's UI.
Keep them in $(ProjectDir)\Lib, but add those files "As a link" to the root of your .csproj. Now they will get copied to bin\Debug (or whatever other output folder) without being in lib.
EDIT: This answer was written way back when ContentWithTargetPath was not available in the versions of VS/MSBuild I was using. Leaving this answer here for people who might have to use an older version of VS. Please stop commenting on this, we all know there are better ways now.
If your main intent is to include DLLs without cluttering up the project root directory, another solution is to move the DLLs to a separate Shared Project and add this as a reference in the original project.
(Note that this post doesn't directly answer this question as it doesn't preserve the folder and project structure, but I found this approach useful because I was able to restructure my project in my case and because I wanted to avoid some of the downsides of the other approaches here.)
Steps
Right-click your Solution -> Add -> New Project -> Shared Project
Add the DLLs to this project (in the root directory of this project, not in a "lib" sub-folder)
(Check DLL file properties are set correctly, e.g. Build Action: Content and Copy to Output Directory: Copy Always)
Right-click the original project's References -> Add Reference -> Shared Projects
Select the shared project you created earlier
The setup looks like this:
If you need to copy files from the Libs directory to the root folder VS2017:
<ItemGroup Condition="'$(Platform)' == 'x64'">
<None Include="Libs\x64\**" Link="\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x86'">
<None Include="Libs\x86\**" Link="\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
To any other folder, including Libs(RecursiveDir) folder
<ItemGroup Condition="'$(Platform)' == 'x86'">
<None Include="Libs\x86\**" Link="mycustomfolder\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
Add the dll-files as a reference to the project, and on the reference set "Copy local" to true.
To add my hat into the ring here, if you want to include a whole directory of content and you don't want to track each individual file in Visual Studio, then you can add this in your project file (for me this is a .vcxproj file of a UWP C++ project):
<ItemGroup>
<Content Include="Content\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
Note that the Content directory must be in the same directory as the project file in order to preserve the directory structure.
It seems in VisualStudio 2015 that if the dlls you are 'adding with a link' are in a subfolder of that same project - they will be automatically put a folder, and the output is also placed in a folder like you saw.
If the dlls are in another project or directory on disk not in a subfolder of the project, you can 'Add with a link', and they will be put in the root directory just fine.
The above solutions did not work reliably for me in Visual Studio 2019 Professional v16.8.2. Sometimes the files would copy, sometimes not. After many attempts, it feels like something may have been broken in the latest updates to VS.
This answer shows how to use a post-build script...something the OP asks not to do! So this answer is intended only for those (who like me) were unable to get more traditional methods to work.
Right-click the project and select Add > Existing Item...
Navigate to the lib folder and select the item(s) to add
To the right of Add, click the down arrow and choose Add As Link
Right-click each file in the new "lib" folder in your project, and set "Copy to Output Directory" to "Do not copy"
Open project properties Build Events and add the following Post-build event
,
rem Copy 3rd party DLL(s) to the output directory on successful build
COPY $(ProjectDir)lib\Something.dll $(TargetDir)
COPY $(ProjectDir)lib\SomethingElse.dll $(TargetDir)
Note that you can use wildcards in the post-build event to copy multiple files.
I used this with VS2022:
<ItemGroup>
<ContentWithTargetPath Include="LibFolder\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>%(Filename)%(Extension)</TargetPath>
</ContentWithTargetPath>
</ItemGroup>
Regarding your question, the following steps worked for me in Visual Studio 2019:
In the Visual Studio editor, for your dll, set the "Build Action" setting as "Content" (This might be optional) and "Copy to Output Directory" setting as "Do not copy".
The following will then be generated within the project csproj file:
<ItemGroup>
<Content Include="lib\IncludedDLL.dll" />
</ItemGroup>
Modify the entry to the following instead:
<ItemGroup>
<Content Include="lib\IncludedDLL.dll" />
<Content Include="lib\IncludedDLL.dll">
<Link>IncludedDLL.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
You can set "CopyToOutputDirectory" option within the project csproj file manually to either "Always" or "PreserveNewest".
In the Visual Studio editor, it will still show the file "Copy to Output Directory" setting as "Do not copy", but the file will be copied to the root output directory upon rebuild.
The above change is not needed if you do not want to copy the file to the root output directory, so if that is the case, you can just manually remove the above change within the project csproj file to revert to the non copying behavior.
An alternate method is just to leave the items as type None. In the solution explorer, click on the ones you want to deploy and set the Content property to True.
Note: I did this in VS2019, and things can change from version to version.
To get this to work, now right-click on your project, and select "Unload Project". Then right-click on the unloaded project and select "Edit project_name.vcxproj".
In the editor, go all the way to the bottom of the file and insert this target right right before the trailing </Project> tag:
<Target Name="CopyContent" AfterTargets="Build">
<Copy SourceFiles="#(None)" Condition="'%(None.DeploymentContent)' == 'true'" DestinationFolder="$(OutputPath)" ContinueOnError="true" />
</Target>
Now right click on the unloaded project and select "Reload Project". Select to save and close if you are prompted.
I also set the OutputDirectory to:
$(SolutionDir)bin\$(Configuration)\$(Platform)\
and the IntermediateDirectory to:
$(SolutionDir)obj\$(Configuration)\$(ProjectName)\$(Platform)\
in the Project Properties General page. This puts the output in a "bin" folder, and the intermediates in an "obj" folder in the root of your solution.
Note: The $(SolutionDir) is not defined when you run MSBuild from the command line. There is a trick you can use to define that to the folder where the .sln file lives using GetDirectoryNameOfFileAbove. (left as an exercise for the reader). Also, it looks like in 2019 they are handling this correctly on the command line anyway. Yeah :) The $(SolutionDir) contains a trailing backslash, hence none after it. The results of each must have a trailing backslash.
Now, if you own Pro or above, please don't do this every time you need to create a project. That would be lame. Instead, once you have your project setup just the way you like it, select Project -> Export Template. You give it a name, and the next time you want to create a project just like that one, just choose that name in the New Project dialog. (In older version, I think this was Files -> Export Teamplate....)
I had the same problem with Visual Studio 2010 / C# Project.
For assemblies (i. e. having the .NET interface) use folder "References" under your project in the Solution Explorer. Right click it, choose "Add existing item" and locate your .dll assembly.
Common .dll files can be placed in a subfolder (as "\lib" was mentioned above) and in the properties select:
Build Action = "HelpFiles"
Copy To OutputDirectory = "If Newer"
This worked for me exactly as desired - during build, the .DLLs are copied to the output directory without the "\lib" subfolder.

My unit test project icon is displaying like a class library... how to fix?

I have 2 c# test projects in my VS2012 Update 1 solution, one shows a class library icon, one shows a test project icon. They both work as test project, but the discrepancy is driving me crazy. (short drive). Anybody know how to fix this? I've looked at the .csproj and the .sln files, but nothing is leaping out at me.
Right-click the project in Solution Explorer and choose Edit Project File
Add a new child in the <PropertyGroup> node:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
Save your changes and close the file
Right-click the project in Solution Explorer and choose Reload Project
https://adamprescott.net/2012/03/29/convert-a-class-library-to-a-test-project-in-visual-studio/
If your project is on a new-style .csproj file (less verbose, says like <Project Sdk="Microsoft.NET.Sdk"> as the top line, supports globbing etc), then you can get a test tube icon for your project by either adding Microsoft.NET.Test.Sdk NuGet package to your project, or adding this line to your .csproj file (which amounts to the same thing):
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
</ItemGroup>
(Version number correct at the time of writing - check for what the latest is.)
Pawel's answer is right, but it was truncated by the html parser... Mentioned child node should look like:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
This line could be also directly added to the csproj file (to the main PropertyGroup).
This isn't really a solution, but it seems to be a bug in Visual Studio.
See Microsoft Connect issues here, here and here which you can follow.
There is also a similar question here.
UPDATE:
This seems to be resolved in Visual Studio 2013 preview.
Open up Solution Explorer, right-click, go to properties and under 'Application' there is a drop-down menu called 'Output Type' and change that from Class Library to whatever you want it (most likely an Application).

How can I connect xaml and xaml.cs files

I had a VB projected and converted it to C# using online conversion tools. Now the problem is xaml and xaml.cs file do not connect to each other, that is they don't recognize their dependencies (Red area in Fig). Actually it should appear like Window1 Files (Green Area in the image.) How can I achieve this.
I am trying my hands on WPF so may be a layman sort of question.
This is simple, try to add in project existing items and select the XAML (not .cs, etc.) files in list of formats. In VS2010 thats helps.
If you cannot get the IDE to do it (Papa John's post), then you can do it by editing the project file.
That information is in the .csproj file (which is an XML file -- you can open it in a text editor, or by right-clicking on it, choosing "unload", and then opening it -- choose reload to load it up as a project again).
Here is the information to look for, you would need to add the "DependentUpon" tag.
<Compile Include="TheFile.xaml.cs">
<DependentUpon>TheFile.xaml</DependentUpon>
</Compile>
Easiest Way!!!
I came across the same. I got the way out. Here is how to get the .xaml.cs nested under the .xaml in Solution Explorer:
In Windows File Explorer (outside of Visual Studio), open the folder where the required files are.
Select both files (.xaml and .xaml.cs) together.
Drag it onto your project name in the Solution Explorer.
Its done! :)
Using a Xamarin PCL Solution:
1) Go to your PCL folder and open your MySolution.csproj file
2) There should be several groups of <ItemGroup> tags. One of them declares <EmbeddedResource> tags and another will contain, <Compile> <DependentUpon></DependentUpon></Compile> groups of tags.
3) For MyPage.xaml and MyPage.xaml.cs files to be linked, you must have a group of xmls that declare your xaml page.
<EmbeddedResource Include="MyPage.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
<Compile Include="MyPage.xaml.cs">
<DependentUpon>MyPage.xaml</DependentUpon>
</Compile>
Note that if your page is in a folder you should specify that like so:
<Compile Include="Views\MyPage.xaml.cs">
<DependentUpon>MyPage.xaml</DependentUpon>
</Compile>
<EmbeddedResource Include="Views\MyPage.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
Note that this works with OSX and Windows
Based on Kyle White's comment on the official Xamarin bug report 55591: .xaml files in .NETStandard library appear twice in solution explorer, I found a simple solution to this problem within the linked .NET Standard sample project by Oren Novotny
Within your .csproj file, add the following <ItemGroup>:
<ItemGroup>
<Compile Update="**\*.xaml.cs" DependentUpon="%(Filename)" />
<EmbeddedResource Include="**\*.xaml" SubType="Designer" Generator="MSBuild:UpdateDesignTimeXaml" LogicalName="%(Filename)%(Extension)" />
</ItemGroup>
Afterwards, all xaml files within the project structure will be displayed in the Solution Explorer window automatically - even if you'll ever add new xaml files.
How does this magic work?
The Compile element within the ItemGroup is using wildcards to iterate through all directories, searching for .xaml.cs files and marking them as dependent on the xaml files of the same name. Please note that this works only because the %(Filename) item metadata used for the DependentUpon element contains the left-most file extension, which matches the name of the xaml file by convention.
The EmbeddedResource element will include all xaml files to the project, so that they are visible within the Solution Explorer window while marking them as Designer files, and declaring that the UpdateDesignTimeXaml target defined within the Xamarin.Forms NuGet package should be used to generate code from the markup file.
Using Xamarin Shared Code solution:
1) Go to you project folder after unloading the shared project
2) Find the projitems file and edit that adding the DependentUpon tag as described in other answers above.
3) Save the file
4) Go back to visual studio and you should get a dialog that allows you to reload all or just open the project again.
An even easier and faster solution for Xamarin Forms projects, no need to touch csproj file at all, very quick fix.
Make sure you have Show All Files selected for solution explorer - it may be on by default.
Select all affected files
Right click > Exclude from Project
Select the same files again (should be faded out)
Right Click > Include in Project
They should now all be nested correctly and all the changes necessary to the .csproj file will be done.
You may have an InitializeComponent() does not exist in the current context) error after this.
If that's the case, the simple fix is..
Select all affected items and change Build Action from Page to Embedded Resource
I was able to just restart Visual Studio for Mac 2019 v16.2 and it reconnected my .xaml & .cs files that should've been connected.
If that doesn't work, Hitsa's solution worked for me as well on a separate occasion.
If you get the Nested File VS Extension, you can do this by right clicking similarly named files and choosing to "nest automatically" or you can nest manually.
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.FileNesting
In a Shared Project there is .shproj file instead of a .csproj file and the and items do not exist there.
However I found there is also a .projitems file and adding a section there as described above caused the .xaml and .cs files to be linked
The usual - Close Visual Studio, delete the vs folder in the root folder of your solution and reopen Visual Studio (2019) just worked for me.
For VS 2019, you have only to edit .csproj file and eliminate all references to .xaml.cs file
es:
<ItemGroup>
<Folder Include="Models\" />
<Folder Include="Services\" />
<Folder Include="ViewModels\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Views\MyPage.xaml">
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
</ItemGroup>
I found the problem was when i reloaded a github project from my menu, instead of the actual project file inside that local downloaded repo. Once I selected the .sln file it worked again!

Categories

Resources