c# – Visual Studio: NU1008 Central Package Management problem


The build system thinks that your solution has Central Package Management (CPM) enabled while your package references are not configured to support said setup.

If you did not change anything in your setup, something must be setting ManagePackageVersionsCentrally configuration property to True for you outside of your project files. The most probable culprit is Directory.Packages.props but it could be other files like Directory.Build.props or Directory.Build.targets.

Note that these files are searched recursively in parent directories from the project that is being built (documentation).

The property might even be set as an environment variable on your system.

It’s also possible that some package pulls such configuration, albeit that should not be the case if you did not change anything in the projects/references.

Note also that the tooling that supports CPM was released in May 2022 so it’s quite probable that some of the tooling you use got updated as this feature did not exist 3 years ago. You wouldn’t be getting this error from pre-CPM tooling. dotnet gets updated as part of Windows Update automatically – I’m quite confident that if you used dotnet --version, you’d see a newer version than that of ~3 years ago.

That being said, these are only pointers where to look, any exact solution would be specific to your case and not a general answer. If neither of these pointers help, you’ll probably have to check the diagnostic logs of dotnet restore or whatever command triggers the error for you.

You might want to start with printing out the value of ManagePackageVersionsCentrally variable during build to ensure this answer is not totally off, though. See How to output a variable value to the log from MSBuild.

Enhance Pull Request Reviews with In-Depth Feedback


Visual Studio 2022 has taken the pull request experience to the next level by making reviews interactive. We previously enabled viewing your pull request comments inline in your working files. Now, the latest update empowers you to add comments directly within the IDE, streamlining the review process. Now, pull request reviewers can conduct deep reviews with the navigational power of the IDE and stay in their focused environment.

We heard from your feedback that the web experience for reviewing pull requests can only go so far. When you need to really understand your colleagues’ proposed changes, it’s best to checkout their branch and use the navigation and build tools in VS. Once you’re on their branch and you’ve identified some feedback, you can add the comment directly without having to map it back to the code in the web. This extends previous functionality where you could view and reply to only existing comments.

Enabling this feature

To start using the new commenting feature, first ensure you have enabled the feature flags:

  • Tools > Options > Preview Features > Pull Request Comments
  • Tools > Options > Pull Request Add Comment.

Once these are activated, checkout any branch with an active pull request and click on Show comments in files in the InfoBar to activate the pull request comments experience in the editor. Alternatively, you can enable comments by using the top level menu Git > ADO/GitHub > Show Comments in Files or from the PR dropdown menu next to the view all commits link in the Git Changes window.

Git Changes window showing Branch has an active pull request. Show comments in files. Open in browser

Adding comments to pull request files

Simply click on the Add Comment icon in the margin, or right-click the line you’d like to comment on and select Git > Add Comment from the context menu.

image hovering the add comment button

The comment icon will only appear in files that are part of the pull request. For GitHub pull requests, comments can only be added to lines surrounding and including the changes.

We appreciate your feedback!

This is another step in our journey to deliver a powerful and integrated pull request experience. We started with supporting the create a pull request workflow, enabled viewing pull request comments on your checked out branches, and now, you can add new review comments, as well!

We won’t stop there. Your continuous suggestions and insights play a crucial role in shaping the tools we build. We’re thrilled to bring you this enhancement and are eager to hear how it improves your workflow.

Visual Studio clean up C/C++ includes and precompiled headers


We have a large code base in C++ that makes uses of precompiled headers. Visual Studio 17.8 introduced a “clean up” feature for C++ which (in part) looks for transitively included headers and suggests that they be directly included.

Does anyone have any suggestions about how to get the clean up feature playing nicely with precompiled headers? Anything that’s coming from the precompiled header will be identified as transitive and the suggestion will be to make it a direct include. Is this good advice though? It would seem to just create duplicates (at best) of the needed includes. Which, maybe, defeats the idea behind precompiled headers. Do this enough and you won’t need the precompiled header at all. Again, this is going against the purpose of precompiled headers!

The clean up feature looks nice in principle, but if it’s going to complain about includes from precompiled headers than it will be difficult to identify good advice from “false positives” and probably just get switched off.

I’d be interested to hear about other developer’s experiences with this new(ish) feature.

c++ – How to build OpenCV for static linking in Visual Studio on Windows


I’ve been spending the better part of a day trying to figure this out, but to no avail.
I’ve scoured the internet for documentation and tutorials, and I still can’t make it work.

I am able to build OpenCV just fine, but no matter what I do, when I try to build my project and statically link against generated .lib files, I always get unresolved external symbols from the linker.

Let me guide you through the process I followed, and maybe you can spot what I’m doing wrong.

  1. Clone the repository.
    I went straight to the github, and made sure to select a release tag before cloning https://github.com/opencv/opencv/tree/4.11.0
    I saw a tutorial on YouTube where they cloned opencv_contrib as well, so I grabbed that too; again, from a release tag https://github.com/opencv/opencv_contrib/tree/4.11.0

  2. I installed CMake 4.0.0 (the GUI version)
    For “where is the source”, I selected the root of the opencv repository.
    Then pressed “configure” to generate the initial set of CMake options.
    Selected Visual Studio 17 2022 and platform x64 on the prompt.
    After that, I made sure to set the following options:

    • BUILD_SHARED_LIBRARIES: FALSE
    • BUILD_WITH_STATIC_CRT: TRUE
    • OPENCV_EXTRA_MODULES_PATH: point to opencv_contrib/modules
    • BUILD_opencv_world: TRUE & FALSE (tried both options in separate builds)
  3. I then generated the OpenCV VS sln, selected options Debug and x64 and built the ALL_BUILD solution.

  4. When the build was done, Visual Studio generated the following directories: bin, lib and x64.
    Since I want to statically link my project against OpenCV, I only grab the lib directory, and paste it in MyProject/MyProject/OpenCV/lib.

  5. I also grab opencv/include (from the original repository) and paste it in MyProject/MyProject/OpenCV/include.

  6. I open my project sln, and set the following options in the solution configuration:

    • C/C++ > Preprocessor > Preprocessor Definitions: add OPENCV_STATIC
    • C/C++ > General > Additional Include Directories: point it to ./OpenCV/include
    • C/C++ > Code Generation > Runtime Library: Multi-threaded Debug (/MTd)
    • Linker > General > Additional Library Directories: point it to ./OpenCV/lib
    • Linker > Input > Additional Dependencies:
      • (when compiled with BUILD_opencv_world=True) opencv_world4110d.lib
      • (when compiled with BUILD_opencv_world=False) opencv_core4110d.lib, opencv_imgproc4110d.lib, opencv_imgcodecs4110d.lib, opencv_highgui4110d.lib

    note: I made sure configuration is Debug x64

  7. Saved the configuration and built MyProject.

As source code for the project I chose samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp

Whatever I do, the linker keeps saying it has unresolved external symbols. There are around 200 of them when building a world lib, and 400 when building with world off.

Some other things I have tried:

  • without opencv_contrib/modules (i.e. do not point CMake to the directory when generating)
  • WITH_IPP = False (I saw a few mentions of IPP in the logs, so I thought I’d give that a try)
  • tried adding all *.lib files in the lib directory to Additional Dependencies, just in case I missed any
  • tried installing OpenCV by building the INSTALL solution
  • double and triple checked the solution configuration and paths that point to OpenCV
  • generate with option OPENCV_GENERATE_PKGCONFIG = True (saw a comment mention that worked for them, but I think that flag is for linux builds)

I’m not sure what else to try at this point. If you see anything wrong with what I’m doing, or have a new suggestion, please let me know.

Thank you.

Edit: examples of log messages:

opencv_world4110d.lib(copy.obj) : error LNK2019: unresolved external symbol ippicviCopy_8u_C1R_L referenced in function "public: void __cdecl cv::Mat::copyTo(class cv::debug_build_guard::_OutputArray const &)const " (?copyTo@Mat@cv@@QEBAXAEBV_OutputArray@debug_build_guard@2@@Z)
opencv_world4110d.lib(color_yuv.dispatch.obj) : error LNK2001: unresolved external symbol ippicviCopy_8u_C1R_L
opencv_world4110d.lib(grfmt_png.obj) : error LNK2019: unresolved external symbol crc32 referenced in function "private: void __cdecl cv::PngEncoder::writeChunk(struct _iobuf *,char const *,unsigned char *,unsigned int)" (?writeChunk@PngEncoder@cv@@AEAAXPEAU_iobuf@@PEBDPEAEI@Z)
opencv_world4110d.lib(persistence.obj) : error LNK2019: unresolved external symbol gzputs referenced in function "public: virtual void __cdecl cv::FileStorage::Impl::puts(char const *)" (?puts@Impl@FileStorage@cv@@UEAAXPEBD@Z)

Find the IDE features you need with GitHub Copilot and Search


Ever find yourself needing to locate a specific menu item, command, or option in Visual Studio, but you don’t know its name or location? Do you often struggle to find detailed instructions on using certain features effectively?

Now, there’s a solution to get you the information you need right in the IDE.

image highlighting ask copilot in feature search

Visual Studio now makes it easy to access GitHub Copilot Chat from Feature Search (Ctrl+Q). Clicking “Ask Copilot” will send your query to GitHub Copilot Chat and get detailed responses, without leaving Visual Studio and search for docs online.

This tool interprets the semantic meaning of your query, considers your Visual Studio version, and provides accurate answers. This means no more guessing the correct terminology or navigating through multiple menus.

For instance, typing ‘prettify file’ in the traditional search might not bring up the ‘format document’ option. However, GitHub Copilot Chat understands the intent behind your query and can guide you to the correct setting with all the information you need to use it.

How it works

Notice the @vs label in the sent chat message? When your search query gets sent over to the GitHub Copilot chat, the @vs agent is called. This @vs agent has in-depth knowledge about the workings of Visual Studio, with strong context on the features available in the current version you’re using and how those work.

The @vs agent works in the Visual Studio GitHub Copilot Chat even if you’re not starting from Feature Search. You can invoke the agent on your own by adding @vs to your chat message.

Appreciation for your feedback

Your insights help us improve Visual Studio, making it an even more powerful tool for developers. We are immensely grateful for your contributions and look forward to your continued support.

Your feedback is invaluable in shaping Visual Studio’s future. By sharing your thoughts, ideas, and any issues you encounter through Developer Community, you help us improve and shape the future of Visual Studio.

visual studio – .NET Maui CollectionView Not Showing All Data in Windows


I have a problem with CollectionView in Windows. The XAML is

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="LibraryAppM.Views.EnquiryPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:library="clr-namespace:LibraryM;assembly=LibraryM"
    xmlns:local="clr-namespace:LibraryAppM.ViewModels.Enquiry"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
    x:Name="enquiry"
    Title="Richard's Library System"
    x:DataType="local:EnquiryViewModel">
    <ContentPage.BindingContext>
        <local:EnquiryViewModel />
    </ContentPage.BindingContext>
    <ContentPage.Behaviors>
        <toolkit:EventToCommandBehavior
            BindingContext="{Binding Path=BindingContext, Source={x:Reference enquiry}, x:DataType=ContentPage}"
            Command="{Binding GetAuthorsCommand}"
            EventName="Appearing" />
    </ContentPage.Behaviors>
    <Grid
        Padding="10,0,10,0"
        RowDefinitions="Auto,Auto,Auto,Auto,*"
        RowSpacing="10">
        <Image
            Grid.Row="0"
            Aspect="AspectFit"
            HeightRequest="185"
            SemanticProperties.Description="A picture of library shelves"
            Source="lib_pic.jpg" />
        <Label
            Grid.Row="1"
            FontSize="20"
            Text="Enquiry Page" />
        <toolkit:Expander Grid.Row="2" IsExpanded="{Binding IsOpened}">
            <toolkit:Expander.Header>
                <HorizontalStackLayout MaximumHeightRequest="42">
                    <Label
                        FontSize="16"
                        HorizontalOptions="Start"
                        Text="{Binding SelectedText}" />
                    <Label
                        HorizontalOptions="Start"
                        Text="&#9660;"
                        VerticalOptions="Center" />
                </HorizontalStackLayout>
            </toolkit:Expander.Header>
            <CollectionView
                HeightRequest="190"
                ItemsSource="{Binding DataList}"
                SelectedItem="{Binding SelectedItem}"
                SelectionChangedCommand="{Binding SelectionCommand}"
                SelectionMode="Single">
                <CollectionView.ItemTemplate>
                    <DataTemplate x:DataType="library:Author">
                        <Label FontSize="16" Text="{Binding FullName}" />
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </toolkit:Expander>
        <Grid
            Grid.Row="3"
            ColumnDefinitions="5*,10,Auto"
            RowDefinitions="Auto">
            <Label
                Grid.Column="0"
                HorizontalOptions="Start"
                Text="Title" />
            <Label
                Grid.Column="2"
                HorizontalOptions="Center"
                Text="Return Date" />
        </Grid>
        <CollectionView
            Grid.Row="5"
            ItemsSource="{Binding BookList}"
            VerticalScrollBarVisibility="Never">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout ItemSpacing="3" Orientation="Vertical" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="library:Book">
                    <Grid ColumnDefinitions="Auto,*,Auto">
                        <Label
                            Grid.Column="0"
                            HorizontalOptions="Start"
                            Text="{Binding Title}" />
                        <Label
                            Grid.Column="2"
                            HorizontalOptions="End"
                            Text="{Binding ReturnDate}" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</ContentPage>

The list scrolls but the last few items are missing. If I now add Padding to the Grid in the second CollectionView (for example <Grid ColumnDefinitions="Auto,*,Auto" Padding="20"> some of the missing items appear. This view works without the Padding modification in Android. I’m on VS 17.13.3 and Windows 11.

Boost your GitHub productivity with our new multi-account support!


Managing your GitHub identity in Visual Studio 2022 just got easier! Our latest update overhauls the GitHub account management experience and improves how you work with multiple accounts, especially for GitHub Copilot and version control scenarios. In this post, we’ll detail how these changes will make your GitHub workflow smoother, from the moment you start using Visual Studio to your everyday coding.

Onboarding Improvements

The latest Visual Studio 2022 update streamlines your GitHub experience right from the very start. You can now Sign in with your GitHub account during the first launch experience:

Image firstlaunchwithgithub

If you would rather configure your account at a later stage, you can also sign in with GitHub accounts directly from the Visual Studio shell, regardless of whether a Microsoft account is present.

Image signinfromshell

Please note that roaming settings are not currently available for GitHub accounts. You’ll need to add a Microsoft account if you want to roam your Visual Studio settings across devices.

Multiple GitHub Accounts

We’re happy to announce that you can now add and manage multiple GitHub accounts! Multi-account support was a top request from you, and the latest update enables it for all Visual Studio 2022 users.

You can add multiple public GitHub accounts effortlessly from all the same identity controls you normally interact with. For instance, you can open the profile card, click on “Add another account,” sign in to your GitHub account, and repeat as needed!

Image addaccountanimation

Seamless Switching Between Accounts

Once you successfully add your first GitHub account, Visual Studio will automatically If you have multiple accounts, switching the active accounts is effortless; just open the profile card, access the account options and select the “Set as active account” button.

Image copilotbecomesactive 2

GitHub Copilot Integration

The active GitHub account drives the activation of GitHub Copilot. If your active account is subscribed to GitHub Copilot Free, GitHub Copilot for Individuals or GitHub Copilot for Business, the Copilot feature will activate automatically.

You can check the GitHub Copilot badge to quickly assess if your active account has valid entitlements, as its status will indicate whether GitHub Copilot is active.

Image copilotbecomesactive

Version Control Integration

Managing multiple accounts also impacts version control-related scenarios. If you are working on GitHub pull requests or issues, Visual Studio prompt you to set a GitHub account and will remember your preference for each repository.

Image vc dialog

That means that you won’t need to worry about switching accounts for regular Git operations like push, pull, and fetch. between it and the repository preferences,

Conclusion

We’ve been working hard to make your GitHub experience in Visual Studio 2022 even better, and we think you’ll love these updates!  From easier onboarding and managing multiple GitHub accounts to automatic GitHub Copilot activation and smart Git handling, this update has you covered.

Thank you for your continuous feedback, which helps us make Visual Studio better with every release.  Please remember that you can keep sharing your thoughts and suggestions by visiting our developer community portal.

c# – WebService automated testing – consuming service in Visual Studio yields auth problem for one endpoint


I have been tasked with automating tests for a webservice. Pretty straight forward. What I did was:

  • Add service reference in my project.
  • Write code to execute tests with MSTest unit test framework. While doing this, realize the service is not. Um. Entirely tight. I had to make some changes to Reference.cs to handle responses which are defined in the wsdl as having datetime values but are not present. Keep track of changes so when I have to reload the wsdl, I will know what I have changed. Don’t love. Don’t see alternative. Should not be relevant.
  • Finish creating tests for several of the endpoints in the service.

Get to one which is yielding behavior I do not understand. What I observe when testing what I wrote.

When I run the test which includes the new service call, I receive an error:
Message: 
Test method CcbWebServicesTestingNet.TestDevelopment.AddCustmerDonorConsent threw exception:
System.ServiceModel.FaultException: Parameter contactCustomerResponse in method AddCustomerDonorConsent in service CustomerManagement is null!

Relevant troubleshooting info:

  • Run the same endpoint in SOAPUI with the same inputs. Returns response properly. Cool problem is in my code, of course.
  • Test my code with fiddler open. When I get to the bad call, see enter image description here

Ok unauthorized. Exact same authorization code. And … why is NULL response coming back from my call instead of an auth error as with when I change the user name to user name plus some random characters to demonstrate failure. When I change the user name to something clearly invalid and run a working test, I receive this error:

Test method CcbWebServicesTestingNet.TestDevelopment.AddCustmerDonorConsent threw exception:
System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘NTLM’. —> System.Net.WebException: The remote server returned an error: (401) Unauthorized.

The code that does the auth work is in this class for the ContactCustomer client type.

    using System.ServiceModel;
using CcbWebServicesTestingNet.ServiceRefCreditCard;
using CcbWebServicesTestingNet.ServiceRefCustomerManagement;
using CcbWebServicesTestingNet.ServiceRefDonor;

namespace CcbWebServicesTestingNet.Model
{
    public static class ComponentClient
    {
        private enum ClientType
        {
            ContactCustomer,
            CustomerCreditCard,
            Donor
        }
        private static BasicHttpBinding _binding;
        private static EndpointAddress _address;
        private static readonly Settings Settings = new Settings();
        public static CustomerCreditCard_PortClient GetClientCreditCardClient()
        {
            SetParameters(ClientType.CustomerCreditCard);
            CustomerCreditCard_PortClient client = new CustomerCreditCard_PortClient(_binding, _address);
            if (client.ClientCredentials != null)
            {
                client.ClientCredentials.Windows.ClientCredential.Domain = Settings.AuthDomain;
                client.ClientCredentials.Windows.ClientCredential.UserName = Settings.AuthUserName;
                client.ClientCredentials.Windows.ClientCredential.Password = Settings.AuthPassword;
            }

            return client;
        }

        public static Donor_PortClient GetClientDonorClient()
        {
            SetParameters(ClientType.Donor);
            Donor_PortClient client = new Donor_PortClient(_binding, _address);
            if (client.ClientCredentials != null)
            {
                client.ClientCredentials.Windows.ClientCredential.Domain = Settings.AuthDomain;
                client.ClientCredentials.Windows.ClientCredential.UserName = Settings.AuthUserName;
                client.ClientCredentials.Windows.ClientCredential.Password = Settings.AuthPassword;
            }

            return client;
        }
        public static CustomerManagement_PortClient GetContactCustomerClient()
        {
            SetParameters(ClientType.ContactCustomer);  
            CustomerManagement_PortClient client = new CustomerManagement_PortClient(_binding, _address);
            if (client.ClientCredentials != null)
            {
                client.ClientCredentials.Windows.ClientCredential.Domain = Settings.AuthDomain;
                client.ClientCredentials.Windows.ClientCredential.UserName = Settings.AuthUserName;
                client.ClientCredentials.Windows.ClientCredential.Password = Settings.AuthPassword;
            }

            return client;
        }

        private static void SetParameters(ClientType clientType)
        {
            string url;
            switch (clientType)
            {
                case ClientType.CustomerCreditCard:
                    url = Settings.CreditCardUrl;
                    break;
                case ClientType.Donor:
                    url = Settings.DonorUrl;
                    break;
                default:
                    url = Settings.CustomerManagementUrl; 
                    break;
            }
            

            _binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            // Configure transport security
            _binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
            _binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Ntlm;
            _binding.Security.Transport.Realm = "";

            // Configure message security
            _binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            _binding.MaxReceivedMessageSize = 65536 * 2;

            _address = new EndpointAddress(url);
        }

        
    }
}

Does anyone have suggestions for what I can look at for troubleshooting? This is new work for me, doing SOAP automation. So don’t assume I know stuff. Any suggestions welcome. Thanks!

Introducing automatic documentation comment generation in Visual Studio


We are excited to announce that Copilot is now automatically integrated into Visual Studio’s editor to help you generate doc comments for functions. This new feature aims to streamline your documentation process and enhance your coding experience.

To access these updates, you will need a GitHub Copilot subscription. If you don’t already have GitHub Copilot, you can sign up for free here.

If you have automatic doc comment generation enabled via your settings, you can simply type what would trigger your doc comment format (such as ///) and Copilot suggestions will automatically fill out the function description based on the contents of the function, including a summary and any parameters and return types (if available). You can then accept these suggestions using a single tab, just like regular Copilot code completions.

To access this feature, you will need to have automatically generating doc comments enabled.

For C++ projects, you can configure the generated documentation comment styles using the following setting in Tools > Options. Both XML and Doxygen style comments are supported by this feature.

Tools > Option, Coding Style, General to enable for C++

For C#, you would need to enable the following setting in your Tools > Options

Tools > Option, C#, Advanced, Comments for C#

Share your feedback

This feature is available for Visual Studio 17.14 Preview 2 for both C# and C++ project files. We encourage you to explore this feature and see how GitHub Copilot can transform and simplify your coding experience.

We deeply appreciate the continuous feedback from our users, which drives us to improve and innovate. Your input is invaluable in making Visual Studio better with each update. Happy coding!

c# – Windows Forms App (.NET) does not show up as an option in Visual Studio 2022


Check the Visual Studio installer. There are many versions of .NET, and for Windows specific development like the old Windows Forms you need some options checked.

enter image description hereClick “modify”.

Then if you select the workload shown “.NET desktop development”, you should be good to go.

enter image description here

Under the hood, it will probably install the old .NET *Framework* (4.8) SDK, among other stuff.

In the new project templates, you’ll find it under “C# / Windows / Desktop” :

enter image description here

For completeness, see which individual components I have installed, I can create new windows forms with both .NET Framework 4.8 or with modern .NET 8 or .NET 9.

enter image description here

Here is the .csproj (I can open it directly in VS):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>