Error msb1003 укажите проект или файл решения

The instructions for a sample application that I am trying to build as me to type dotnet restore at the command line. dotnet --version reports 2.1.300 When I do this I get the following e...

The instructions for a sample application that I am trying to build as me to type

dotnet restore 

at the command line.

dotnet --version 

reports

2.1.300

When I do this I get the following error

MSBUILD : error MSB1003: Specify a project or solution file.
The current working directory does not contain a project or solution file.

The folder I am executing the command in contains .cs files but no .sln or .csproj file.

Does .NetCore require a .csproj file ?

The code comes from an answer to my question here but the github project has since been deleted.

I did try creating a .csproj file but i had trouble guessing what packages to put in it.

[Update]

I added the following .csproj file

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

</Project>

Then I get the following namespaces missing

 Microsoft.IdentityModel
 Azure
 KeyVaultClient
 ClientAssertinCertificate
 Newtonsoft
 Org

I know how to use package manager but how do I figure out the right versions of everything?

Here is program.cs

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace dotnetconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(@"This Application must be run after running the powershell script Setup.ps1!
                                This DotNet Console Application authenticates to Key Vault!
                                It also creates a Secret Key Value Pair!
                                And then it gets the Secret Key Value Pair!");

            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);
            string KEYVAULT_URI = String.Empty;
            string APPLICATION_ID = String.Empty;
            string CERT_THUMBPRINT = String.Empty;
            if(isWindows)
            {
                KEYVAULT_URI = System.Environment.GetEnvironmentVariable("VAULT_NAME", EnvironmentVariableTarget.User);
                APPLICATION_ID = System.Environment.GetEnvironmentVariable("APPLICATION_ID", EnvironmentVariableTarget.User);
                CERT_THUMBPRINT = System.Environment.GetEnvironmentVariable("CERT_THUMBPRINT", EnvironmentVariableTarget.User);    
            }
            else 
            {
                var result = GetVariablesFromJSON();
                APPLICATION_ID = result.Item1;
                CERT_THUMBPRINT = result.Item2;
                KEYVAULT_URI = result.Item3;
            }            
            KeyVault keyVaultObj = new KeyVault(APPLICATION_ID, CERT_THUMBPRINT);
            var VaultName = "https://" + KEYVAULT_URI + ".vault.azure.net/";            
            var waitHandle = keyVaultObj.CreateSecretKeyValuePair(VaultName);    
            Console.WriteLine("Vault URI is! {0}", VaultName);
            Console.WriteLine("Wait method is invoked to wait for Secret Key Value pair to be created");
            waitHandle.Wait();
            Console.WriteLine("Secret Key Value pair is now created");            
            keyVaultObj.GetResult(VaultName);
        }

        private static Tuple<string, string, string> GetVariablesFromJSON()
        {
            var ServicePrincipalJSON = Directory.GetCurrentDirectory() + "/ServicePrincipal.json";
            var CertThumbprintJSON = Directory.GetCurrentDirectory() + "/CertThumbprint.txt";
            var VaultJSON = Directory.GetCurrentDirectory() + "/KeyVault.json";
            if(File.Exists(ServicePrincipalJSON) && File.Exists(CertThumbprintJSON) && File.Exists(VaultJSON))
            {
                return new Tuple<string, string, string>(ProcessFile(ServicePrincipalJSON, "appId", true), ProcessFile(CertThumbprintJSON, "", false), ProcessFile(VaultJSON, "name", true));
            } 

            return new Tuple<string, string, string>("", "", "");
        }

        private static string ProcessFile(string fileName, string valueToLookFor, bool isJson)
        {
            var result = "";
            using (StreamReader ContentsOfFile = File.OpenText(fileName))
            {
                if(isJson){
                    var stuff = (JObject)JsonConvert.DeserializeObject(ContentsOfFile.ReadToEnd());
                    result = stuff[valueToLookFor].Value<string>();
                }
                else {
                    var contents = ContentsOfFile.ReadToEnd();
                    contents = contents.Split("=")[1];
                    result = Regex.Replace(contents, @"t|n|r", "");
                }
            }            
            return result;
        }
    }
}

Here is Util.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;

public class Util
{
    public static X509Certificate2 ConvertFromPfxToPem(string filename)
    {
        using (System.IO.FileStream fs = System.IO.File.OpenRead(filename))
        {
            byte[] data = new byte[fs.Length];
            byte[] res = null;
            fs.Read(data, 0, data.Length);
            if (data[0] != 0x30)
            {
                res = GetPem("CERTIFICATE", data);
            }
            X509Certificate2 x509 = new X509Certificate2(res); //Exception hit here
            return x509;
        }      
    }   

    private static byte[] GetPem(string type, byte[] data)
    {
        string pem = Encoding.UTF8.GetString(data);
        string header = String.Format("-----BEGIN {0}-----", type);
        string footer = String.Format("-----END {0}-----", type);
        int start = pem.IndexOf(header) + header.Length;
        int end = pem.IndexOf(footer, start);
        string base64 = pem.Substring(start, (end - start));
        base64 = base64.Replace(System.Environment.NewLine, "");
        base64 = base64.Replace('-', '+');
        base64 = base64.Replace('_', '/');
        return Convert.FromBase64String(base64);
    }

    public static RSACryptoServiceProvider PemFileReader(){
        RsaPrivateCrtKeyParameters keyParams;
        using (var reader = File.OpenText("cert.pem")) // file containing RSA PKCS1 private key
        {
            keyParams = ((RsaPrivateCrtKeyParameters)new PemReader(reader).ReadObject());
        }

        RSAParameters rsaParameters = new RSAParameters();

        rsaParameters.Modulus = keyParams.Modulus.ToByteArrayUnsigned();
        rsaParameters.P = keyParams.P.ToByteArrayUnsigned();
        rsaParameters.Q = keyParams.Q.ToByteArrayUnsigned();
        rsaParameters.DP = keyParams.DP.ToByteArrayUnsigned();
        rsaParameters.DQ = keyParams.DQ.ToByteArrayUnsigned();
        rsaParameters.InverseQ = keyParams.QInv.ToByteArrayUnsigned();
        rsaParameters.D = keyParams.Exponent.ToByteArrayUnsigned();
        rsaParameters.Exponent = keyParams.PublicExponent.ToByteArrayUnsigned();

        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048);
        rsaKey.ImportParameters(rsaParameters);
        return rsaKey;
    }
}

Here is KeyVault.cs

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.KeyVault;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault.Models;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

namespace dotnetconsole
{
    public class KeyVault
    {
        KeyVaultClient _keyVaultClient;
        string APPLICATION_ID, CERT_THUMBPRINT;
        public KeyVault(string APPLICATION_ID, string CERT_THUMBPRINT) {
            this.APPLICATION_ID = APPLICATION_ID;
            this.CERT_THUMBPRINT = CERT_THUMBPRINT;
            _keyVaultClient = new KeyVaultClient(this.GetAccessToken);
        }

        public static ClientAssertionCertificate AssertionCert { get; set; }

        // This method is used to get a token from Azure Active Directory. 
        public async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);

            X509Certificate2 certByThumbprint = new X509Certificate2();
            if(isWindows){
                certByThumbprint = FindCertificateByThumbprint(this.CERT_THUMBPRINT);
            } else {
                // If it's a pem file then we take the private key portion and create a 
                // RSACryptoServiceProvider and then we create a x509Certificate2 class from the cert portion 
                // and then we combine them both to become one x509Certificate2
                RSACryptoServiceProvider rsaCryptoServiceProvider = Util.PemFileReader();
                certByThumbprint = Util.ConvertFromPfxToPem("cert.pem");
                certByThumbprint = certByThumbprint.CopyWithPrivateKey(rsaCryptoServiceProvider);
            }

            AssertionCert = new ClientAssertionCertificate(this.APPLICATION_ID, certByThumbprint);
            var result = await context.AcquireTokenAsync(resource, AssertionCert);
            return result.AccessToken;
        }


        public async Task CreateSecretKeyValuePair(string vaultBaseURL)
        {
            System.Console.WriteLine("Authenticating to Key Vault using ADAL Callback to create Secret Key Value Pair");
            System.Console.WriteLine(vaultBaseURL);
            KeyVaultClient kvClient = new KeyVaultClient(this.GetAccessToken);
            await kvClient.SetSecretAsync(vaultBaseURL, "TestKey", "TestSecret");
        }

        // In this method we first get a token from Azure Active Directory by using the self signed cert we created in our powershell commands
        // And then we pass that token to Azure Key Vault to authenticate the service principal to get access to the secrets
        // Finally we retrieve the secret value that was created previously 
        public void GetResult(string keyvaultUri)
        {
            try
            {
                var result = this._keyVaultClient.GetSecretAsync(keyvaultUri, "TestKey").Result.Value;
                System.Console.WriteLine("Secret Key retrieved is {0} and value is {1}, ", "TestKey", result);    
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        // In Windows this method would find the certificate that's stored in the certificate manager under current user
        // Given a thumbprint this method finds the certificate       
        public static X509Certificate2 FindCertificateByThumbprint(string findValue)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint,
                    findValue, false); // Don't validate certs, since the test root isn't installed.
                if (col == null || col.Count == 0 )
                    return null;
                return col[0];
            }
            finally
            {
                store.Close();
            }
        }
    }
}

[Update]
Now I can run dotnet restore but dotnet run gives errors

As follows

KeyVault.cs(2,17): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(3,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(6,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(3,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(4,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(10,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(11,17): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(7,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(8,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(9,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(10,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(11,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(22,23): error CS0246: The type or namespace name 'ClientAssertionCertificate' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(14,9): error CS0246: The type or namespace name 'KeyVaultClient' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]

    The build failed. Please fix the build errors and run again.

[Update]

Tools ->Nuget Package Manager -> Manage Packages for solution reports an error

Microsoft Visual Studio
The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

[Update]

I saved everything, closed the .sln file and reopened it. Then I was able to get into Nuget Package Manager.

[Update]

I have installed Microsoft.Azure.KeyVault(3.0.0) and Newtonsoft.Json(11.0.2)
I am having problems with Microsoft.IdentityModel.Clients.ActiveDirectory
When I tried Microsoft.IdentityModel it was the wrong framework.

Package 'Microsoft.IdentityModel 6.1.7600.16394' was restored using ''.NETFramework, Version=v4.61'
instead of the projecttargetframework '.NETCoreApp,Version=v2.1' 
This package may not be fully compatible with your project

[Update]
Googled «using Microsoft.IdentityModel.Clients.ActiveDirectory core»

Found this link
and ran in PM

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 3.19.8

[Update]
Tried googling the Bouncy Castle using statement and found

Install-Package BouncyCastle.NetCore -Version 1.8.2

[Update]

Rebuild All succeeds, now I have a run time error in line 47 of

var waitHandle = keyVaultObj.CreateSecretKeyValuePair(VaultName);

  System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at dotnetconsole.Program.Main(String[] args) in C:dev2018key-vault-dotnet-quickstartProgram.cs:line 47

Inner Exception 1:
ArgumentNullException: Value cannot be null.

I have dotnet core version 1.0.0-rc4-004597 installed. I have creating with dotnet commands


~/Unity3D
⇨ cd GameReviewer
cd: no such file or directory: GameReviewer

~/Unity3D
⇨ mkdir GameReviewer

~/Unity3D
⇨ cd GameReviewer

~/Unity3D/GameReviewer
⇨ yo aspnet

     _-----_     ╭──────────────────────────╮
    |       |    │      Welcome to the      │
    |--(o)--|    │  marvellous ASP.NET Core │
   `---------´   │        generator!        │
    ( _´U`_ )    ╰──────────────────────────╯
    /___A___   /
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

? What type of application do you want to create? Web Application Basic [without Membership and Authorization]
? Which UI framework would you like to use? Bootstrap (3.3.6)
? What's the name of your ASP.NET application? GameReviewer
   create GameReviewer/Dockerfile
   create GameReviewer/.bowerrc
   create GameReviewer/bundleconfig.json
   create GameReviewer/.gitignore
   create GameReviewer/bower.json
   create GameReviewer/appsettings.json
   create GameReviewer/project.json
   create GameReviewer/Program.cs
   create GameReviewer/Properties/launchSettings.json
   create GameReviewer/README.md
   create GameReviewer/Startup.cs
   create GameReviewer/web.config
   create GameReviewer/Controllers/HomeController.cs
   create GameReviewer/Views/_ViewImports.cshtml
   create GameReviewer/Views/_ViewStart.cshtml
   create GameReviewer/Views/Home/About.cshtml
   create GameReviewer/Views/Home/Contact.cshtml
   create GameReviewer/Views/Home/Index.cshtml
   create GameReviewer/Views/Shared/_Layout.cshtml
   create GameReviewer/Views/Shared/Error.cshtml
   create GameReviewer/wwwroot/css/site.css
   create GameReviewer/wwwroot/css/site.min.css
   create GameReviewer/wwwroot/favicon.ico
   create GameReviewer/wwwroot/images/banner1.svg
   create GameReviewer/wwwroot/images/banner2.svg
   create GameReviewer/wwwroot/images/banner3.svg
   create GameReviewer/wwwroot/images/banner4.svg
   create GameReviewer/wwwroot/js/site.js
   create GameReviewer/wwwroot/js/site.min.js


I'm all done. Running bower install for you to install the required dependencies. If this fails, try running the command yourself.


bower cached        https://github.com/twbs/bootstrap.git#3.3.6
bower validate      3.3.6 against https://github.com/twbs/bootstrap.git#3.3.6
bower cached        https://github.com/jzaefferer/jquery-validation.git#1.15.0
bower validate      1.15.0 against https://github.com/jzaefferer/jquery-validation.git#1.15.0
bower cached        https://github.com/aspnet/jquery-validation-unobtrusive.git#3.2.6
bower validate      3.2.6 against https://github.com/aspnet/jquery-validation-unobtrusive.git#3.2.6
bower cached        https://github.com/jquery/jquery-dist.git#2.2.3
bower validate      2.2.3 against https://github.com/jquery/jquery-dist.git#2.2.3
bower install       jquery-validation-unobtrusive#3.2.6
bower install       jquery-validation#1.15.0
bower install       jquery#2.2.3
bower install       bootstrap#3.3.6

jquery-validation-unobtrusive#3.2.6 wwwroot/lib/jquery-validation-unobtrusive
├── jquery#2.2.3
└── jquery-validation#1.15.0

jquery-validation#1.15.0 wwwroot/lib/jquery-validation
└── jquery#2.2.3

jquery#2.2.3 wwwroot/lib/jquery

bootstrap#3.3.6 wwwroot/lib/bootstrap
└── jquery#2.2.3


Your project is now created, you can use the following commands to get going
    cd "GameReviewer"
    dotnet restore
    dotnet build (optional, build will also happen when it's run)
    dotnet run



~/Unity3D/GameReviewer
⇨ cd GameReviewer

~/Unity3D/GameReviewer/GameReviewer
⇨ dotnet restore
MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

Содержание

  1. MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file. #1309
  2. Comments
  3. MSB1003: Specify a project or solution file #697
  4. Comments
  5. MSBUILD: ошибка MSB1003: укажите файл проекта или решения
  6. MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file. #857
  7. Comments
  8. Footer
  9. Exception: MSBUILD : error MSB1003: Specify a project or solution file #399
  10. Comments

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file. #1309

Steps to reproduce the issue

  1. Create a default docker file created by visual studio 2019 for Linux container
  2. Add «RUN dotnet test» command (dot net CLI command to run all unit tests inside docker container) in the docker file.
  3. Right-click on DockerFile and select «Build docker image» option in visual studio 2019
  4. Getting error — MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

**Below is the docker file — **

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY [«LinedataAnalytics/LinedataAnalytics.csproj», «LinedataAnalytics/»]
RUN dotnet restore «LinedataAnalytics/LinedataAnalytics.csproj»
COPY . .
WORKDIR «/src/LinedataAnalytics»
RUN dotnet build «LinedataAnalytics.csproj» -c Release -o /app

FROM build AS publish
RUN dotnet publish «LinedataAnalytics.csproj» -c Release -o /app

FROM base AS final
WORKDIR /app
COPY —from=publish /app .

WORKDIR /app
RUN dotnet test

The text was updated successfully, but these errors were encountered:

Источник

MSB1003: Specify a project or solution file #697

I followed the step-by-step in Azure Portal when creating a new Azure Function using VSC.

At the local debugging step when hitting F5, I get the following error:

Repro steps:
Follow the steps as detailed in the Azure Portal when creating a Function for the first time:

  • Install VCO extensions: Azure Functions and C#
  • Create a new function
  • Hit f5

Additional info (autogenerated):

The text was updated successfully, but these errors were encountered:

Sorry that you’re running into problems with the extension.

Did you create a Functions project before creating a new function? When creating a function, you’ll be prompted to select the folder that will contain the function. It seems like you don’t have a .csproj file should be generated when you press F5.

Thanks. Hope we’ll get you up and running soon!

Thanks for your reply @nturinski

If I go to the root of that folder and manually run dotnet clean and dotnet build it runs without errors:

@veuncent, the launch file seems good, but do you have this task.json?

I cloned your repo and recreated the project (via Create New Project ) whcih generated the appropriate tasks.json, settings.json, and launch.json.

I do have the task.json as well:

Here is a screenshot of my workspace:

We just released a new version of the Functions extension, v0.12.0. I tried to follow the «Create your first function using Visual Studio Code» tutorial using the new extension, I didn’t seem to run into the issue you were seeing. I couldn’t repro it either with the 0.11.0 release however. This is what I did. Let us know if your steps were different.

  1. start VS Code and select the Azure icon on the Activity bar. In Functions’ explorer, select the «folder» icon to create a new project. Select a location and folder to create the project. If you don’t have a folder already, create a new one in the «Select Folder» dialog.
  2. In the command palette, select C# for «Select a language for your function project»
  3. In the command palette, select Add to workspace for «Select how you would like to open your project». This step is missing in the tutorial. I’ve entered a bug to fix it.
  4. You might be prompted to resolve C# dependencies. Please click the Restore button to continue setting up the C# dependencies.
  5. In the Functions explorer, select the lightening icon to create a Function.
  6. In the command palette, chose your project folder created in step 1 above when asked for the project folder
  7. Select HttpTrigger for «Select a function template»
  8. Give a function name for «Provide a function name (Press ‘Enter’ to confirm or ‘Escape’ to cancel)
  9. Confirm for «Provide a namespace (Press ‘Enter’ to confirm or ‘Escape’ to cancel)
  10. AccessRights could be Anonymous (which was what I used)

You should be good to go with F5. Let us know if you still get any build error. Thanks.

I just hit the same issue using v0.12.0 that I just installed today. I was following along with the Create your first function using Visual Studio Code docs. The error was similar for both JavaScript and C# projects, and the command it runs for both seems to have a weird character I wasn’t expecting that could be causing the issue.

Here’s a section from the Task Terminal log after creating and trying to run a JS and then a C# Functions project.

As mentioned by @veuncent, if I run dotnet clean and dotnet build in a PowerShell Terminal window in VS Code, they both run successfully. I also successfully ran func host start from the Terminal window.

It may be a separate issue, but running the function that way doesn’t seem to find the default Function and the HTTP address/port it provided didn’t seem to work.

Источник

MSBUILD: ошибка MSB1003: укажите файл проекта или решения

Инструкции для примера приложения, которое я пытаюсь создать, так как я набираю

в командной строке.

Когда я это сделаю, я получаю следующую ошибку

Папка, в которой я выполняю команду, содержит файлы .cs, но не файлы .sln или .csproj.

Требуется ли .NetCore файл .csproj?

Код взят из ответа на мой вопрос здесь, но с тех пор проект github был удален.

Я попытался создать файл .csproj, но у меня возникли проблемы с предположением, какие пакеты в него поместить.

Я добавил следующий файл .csproj

Затем мне не хватает следующих пространств имен

Я знаю, как использовать диспетчер пакетов, но как мне определить правильные версии всего?

[Обновлять] Теперь я могу запустить dotnet restore, но dotnet run выдает ошибки

Инструменты -> Диспетчер пакетов Nuget -> Управление пакетами для решения сообщает об ошибке

Я сохранил все, закрыл файл .sln и снова открыл его. Затем я смог войти в диспетчер пакетов Nuget.

Я установил Microsoft.Azure.KeyVault (3.0.0) и Newtonsoft.Json (11.0.2) У меня проблемы с Microsoft.IdentityModel.Clients.ActiveDirectory Когда я попробовал Microsoft.IdentityModel, это был неправильный фреймворк.

[Обновлять] Погуглил «с использованием ядра Microsoft.IdentityModel.Clients.ActiveDirectory»

Найдено эта ссылка и побежал в личку

[Обновлять] Пытался поискать в Google Bouncy Castle с помощью оператора и нашел

Восстановить все успешно, теперь у меня ошибка времени выполнения в строке 47 из

var waitHandle = keyVaultObj.CreateSecretKeyValuePair (VaultName);

Содержит ли текущий рабочий каталог файл проекта или решения?

Из какого каталога вы запускаете эту команду?

Спасибо, обновил вопрос. В предоставленном мне коде нет файла .csproj или .sln.

Тогда это нужно сначала исправить .

Спасибо, я свяжусь с моим поставщиком.

Как вы создали этот проект? Поделитесь снимком экрана со структурой вашего проекта.

Спасибо, Эдвард, я обновил проект, чтобы показать.

Источник

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file. #857

I am a novice, but I successfully submitted the first exercise. When I try to run a test for the second one «two-fer», I get the following error:

c:ProgramsExercism>dotnet test
MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

I tried to move the content of c:UsersuserExercismcsharptwo-fer one level up, and it did not help. Now I am stuck. Please help.

The text was updated successfully, but these errors were encountered:

It seems as if you had run the dotnet test command from within exercism s installation directory. You need to run it from within the folder where exercism.exe has downloaded the exercise to.

Also please make sure to not move around the code. When submitting the CLI is very strict on the location of the code and you won’t be able to submit if the location does not match the CLIs expectations.

Thank you, NobbZ. It seems to be working now. Can I debug the code with Visual Studio though?

I do not use VS nor windows, but as far as I know you should be able to open the exercism dotnet projects in VS.

@exercism/csharp @exercism/fsharp @exercism/windows can you confirm?

What do you use? Yes, I confirm. Should I do it somewhere else.

I use Arch Linux and vscodium or emacs, depending on my moods 😉

And do I understand your confirmation correctly, that you actually tried to use VS and it just worked? And what do you want to do somewhere else?

It worked. Should I confirm the use of tags @exercism/csharp @exercism/fsharp @exercism/windows by clicking somewhere?

No, I was actually asking the members of the 3 mentioned teams if they can confirm whether or not Visual Studio should be able to open the dotnet related exercises without further config/manual intervention.

Oh, great. Yes, some more detailed instructions on all steps of using Excercism would be a good thing. But the brevity is fine also.

To use exercism? Personally I think everything is documented quite understandable and very verbose at times, I’d prefer a more slick set of istructions that does not do so much hand holding…

To use the actual toolstack of the track? Maybe, depends on the track…

And what I missed to say in the last point, if you feel that bits and pieces in the documentation are not clear or understandable enough, just open an issue at https://github.com/exercism/exercism and pinpoint the part of the documentation that could be improved and try to explain what you do not quite understand with that part.

It will be delegated from there to the proper sub-repository of the project if necessary.

Got it. Thank you.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Exception: MSBUILD : error MSB1003: Specify a project or solution file #399

Here is my result for a test console application in netcoreapp1.1

The text was updated successfully, but these errors were encountered:

@gbolahanonamusi, thanks for the bug report. Could you provide a repro project? Which version of BenchmarkDotNet do you use?

We need your .csproj and Visual Studio verson

Exe netcoreapp1.1 win7-x86

Microsoft Visual Studio Community 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Ok, so the first problem is that you want to test it for .NET Core, Classic and Mono, but your .csproj contains only netcoreapp1.1 in target framework.

Please change it to:
netcoreapp1.1;net45 and let me know the output

you want to test it for .NET Core, Classic and Mono, but your .csproj contains only netcoreapp1.1 in target framework.

@adamsitnik, could you automatically detect such situation and print a warning with useful instructions?

On net45 im getting this error

But same error on netcoreapp1.1

I recently encountered a similar issue using .NET Core 2 preview, Visual Studio 2017 15.3 preview 6 and BenchmarkDotNet 0.10.9.

I managed to track it down to the fact that during a previous run of BDN that was aborted, no cleanup was performed, so project.json files generated by BDN remained within the directory tree of the solution.
This made BDN think that I am using .json files for my projects, whereas I am using .csproj .

I looked at the source and saw how BDN determines whether we’re using .json or .csproj and I think it’s extremely brittle, since it relies on preview being present in the name of the runtime and recursively (!) scans the directory structure for project.json files.

I think that this solution is less than ideal, it took me quite a while to figure out what was going wrong. I propose two things to make it easier for people in the future:

  • During build indicate what the automatically detected toolchain was, optionally how BDN reached that conclusion.
  • Make the choice of toolchain something that needs to be explicitly configured while setting up the benchmark. I understand the need for easy setup and sane defaults in configuration, but I believe that is only a feasible route when we can determine the runtime with certainty.

Источник

Большая часть информации Baidu обрабатывается шаг за шагом в соответствии с подсказками. Мы можем запускать их шаг за шагом в соответствии с их руководствами. См. Как создать приложение ядра .net.https://www.cnblogs.com/jixiaosa/archive/2019/03/01/10457588.html, Но когда ты закончишь, Нани? ? ? ? ? ? ? Есть много маленьких вопросительных знаков? Если ваш каталог не является рабочим каталогом, ваш файл конфигурации необходимо сгенерировать вручную.

Код, созданный с использованием шаблона в vs code, не имеет имени файла с суффиксом .csproj, указанного во второй строке аргументов. Имя файла здесь необходимо вручную указать в соответствии с относительным адресом файла в рабочем каталоге. Не игнорируйте подсказки на английском языке, которые нужно вводить вручную.

 // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "shell",
            "args": [
                "build",
                // Ask dotnet build to generate full paths for file names.
                "MLTest/MLTest.csproj",
                "/property:GenerateFullPaths=true",
                // Do not generate summary otherwise it leads to duplicate errors in Problems panel
                "/consoleloggerparameters:NoSummary"
            ],
            "group": "build",
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }
    ]

Затем продолжите запуск, и вы обнаружите, что операция прошла успешно, но файл dll не может быть найден, поэтому вот адрес шаблона, который необходимо изменить: ссылка: вот конфигурация: программа внутри — та что я модифицировал, нужно указать файл сборки каталога сборки. Параметр $ {workspace}, если вы не изменяете системные настройки, по умолчанию он указывает текущую самую внешнюю рабочую папку, поэтому честно введите адрес успешно сгенерированного файла выше для его успешного запуска.

{
    // Используйте IntelliSense для понимания связанных атрибутов. 
         // Наведите курсор, чтобы увидеть описания существующих свойств.
         // Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "WARNING01": "*********************************************************************************",
            "WARNING02": "The C# extension was unable to automatically decode projects in the current",
            "WARNING03": "workspace to create a runnable launch.json file. A template launch.json file has",
            "WARNING04": "been created as a placeholder.",
            "WARNING05": "",
            "WARNING06": "If OmniSharp is currently unable to load your project, you can attempt to resolve",
            "WARNING07": "this by restoring any missing project dependencies (example: run 'dotnet restore')",
            "WARNING08": "and by fixing any reported errors from building the projects in your workspace.",
            "WARNING09": "If this allows OmniSharp to now load your project then --",
            "WARNING10": "  * Delete this file",
            "WARNING11": "  * Open the Visual Studio Code command palette (View->Command Palette)",
            "WARNING12": "  * run the command: '.NET: Generate Assets for Build and Debug'.",
            "WARNING13": "",
            "WARNING14": "If your project requires a more complex launch configuration, you may wish to delete",
            "WARNING15": "this configuration and pick a different template using the 'Add Configuration...'",
            "WARNING16": "button at the bottom of this file.",
            "WARNING17": "*********************************************************************************",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/MLTest/bin/Debug/netcoreapp3.0/MLTest.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:pickProcess}"
        }
    ]
}

Моя структура каталогов выглядит так: Для справки:

конечный результат:

Привет, у меня есть решение, в котором есть несколько проектов, в которых я надеюсь автоматизировать сборку и развертывание веб-приложения в рамках проекта.

На моем HD каталог выглядит как C: Users mleip source repos edocs.utils.bluebeam-api edocs.utils.bluebeam-api.Caller edocs.utils.CDEComms, однако, когда я запускаю приведенный ниже yaml я получил

 MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.




trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  buildConfiguration: 'Release'

steps:
- script: dotnet restore 
- powershell:  |
    Write-Host "Your parameter is now: $env:Param"
    Write-Host "When outputting standard variable build id: $(Build.BuildId)"
    Write-Host "When outputting standard variable build id via env: $env:BuildNumber"
    Write-Host "The repo name is: $(Build.Repository.Name)"
    Write-Host "The build definition name is: $(Build.DefinitionName)"
- script: dotnet build --configuration $(buildConfiguration)
  displayName: 'dotnet build $(buildConfiguration)'
- task: DotNetCoreCLI@2
  inputs:
    command: 'build'
    projects:  '**/edocs.utils.bluebeam-api.Caller/edocs.utils.CDEComms/edocs.utils.CDEComms.csproj'

До сих пор я пробовал несколько комбинаций dir для определения того, где azure должен располагать файл сборки, однако каждый раз, когда он терпит неудачу. В решении есть несколько проектов. CDEComms — единственный проект в этой папке, поэтому я совершенно не понимаю, что происходит.

Я новичок в создании конвейеров, и я буду очень признателен за любую помощь в том, почему это не удается.

2 ответа

Лучший ответ

Чтобы сузить круг вопросов, попробуйте просто указать **/*.csproj в файле YAML, чтобы проверить результат сборки. И установите для переменной system.debug значение True, чтобы проверить правильность пути в C:hostedtoolcachewindowsdotnetdotnet.exe build {path}. Кроме того, клонируйте репозиторий на локальный компьютер, чтобы запустить его локально и проверить результат.


1

Cece Dong — MSFT
18 Фев 2021 в 09:20

Из предоставленного вами описания вам сначала нужно будет отправить свой код / ​​решение, то есть содержимое вашего диска C: в ваш репозиторий.


0

Potatojaisiladki
3 Фев 2021 в 09:44

Инструкции для примера приложения, которое я пытаюсь создать, так как я набираю

dotnet restore 

В командной строке.

dotnet --version 

Отчеты

2.1.300

Когда я это сделаю, я получаю следующую ошибку

MSBUILD : error MSB1003: Specify a project or solution file.
The current working directory does not contain a project or solution file.

Папка, в которой я выполняю команду, содержит файлы .cs, но не файлы .sln или .csproj.

Требуется ли .NetCore файл .csproj?

Код взят из ответа на мой вопрос здесь, но с тех пор проект github был удален.

Я попытался создать файл .csproj, но у меня возникли проблемы с предположением, какие пакеты в него поместить.

[Обновлять]

Я добавил следующий файл .csproj

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

</Project>

Затем мне не хватает следующих пространств имен

 Microsoft.IdentityModel
 Azure
 KeyVaultClient
 ClientAssertinCertificate
 Newtonsoft
 Org

Я знаю, как использовать диспетчер пакетов, но как мне определить правильные версии всего?

Вот program.cs

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace dotnetconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(@"This Application must be run after running the powershell script Setup.ps1!
                                This DotNet Console Application authenticates to Key Vault!
                                It also creates a Secret Key Value Pair!
                                And then it gets the Secret Key Value Pair!");

            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);
            string KEYVAULT_URI = String.Empty;
            string APPLICATION_ID = String.Empty;
            string CERT_THUMBPRINT = String.Empty;
            if (isWindows)
            {
                KEYVAULT_URI = System.Environment.GetEnvironmentVariable("VAULT_NAME", EnvironmentVariableTarget.User);
                APPLICATION_ID = System.Environment.GetEnvironmentVariable("APPLICATION_ID", EnvironmentVariableTarget.User);
                CERT_THUMBPRINT = System.Environment.GetEnvironmentVariable("CERT_THUMBPRINT", EnvironmentVariableTarget.User);    
            }
            else 
            {
                var result = GetVariablesFromJSON();
                APPLICATION_ID = result.Item1;
                CERT_THUMBPRINT = result.Item2;
                KEYVAULT_URI = result.Item3;
            }            
            KeyVault keyVaultObj = new KeyVault(APPLICATION_ID, CERT_THUMBPRINT);
            var VaultName = "https://" + KEYVAULT_URI + ".vault.azure.net/";            
            var waitHandle = keyVaultObj.CreateSecretKeyValuePair(VaultName);    
            Console.WriteLine("Vault URI is! {0}", VaultName);
            Console.WriteLine("Wait method is invoked to wait for Secret Key Value pair to be created");
            waitHandle.Wait();
            Console.WriteLine("Secret Key Value pair is now created");            
            keyVaultObj.GetResult(VaultName);
        }

        private static Tuple<string, string, string> GetVariablesFromJSON()
        {
            var ServicePrincipalJSON = Directory.GetCurrentDirectory() + "/ServicePrincipal.json";
            var CertThumbprintJSON = Directory.GetCurrentDirectory() + "/CertThumbprint.txt";
            var VaultJSON = Directory.GetCurrentDirectory() + "/KeyVault.json";
            if (File.Exists(ServicePrincipalJSON) && File.Exists(CertThumbprintJSON) && File.Exists(VaultJSON))
            {
                return new Tuple<string, string, string>(ProcessFile(ServicePrincipalJSON, "appId", true), ProcessFile(CertThumbprintJSON, "", false), ProcessFile(VaultJSON, "name", true));
            } 

            return new Tuple<string, string, string>("", "", "");
        }

        private static string ProcessFile(string fileName, string valueToLookFor, bool isJson)
        {
            var result = "";
            using (StreamReader ContentsOfFile = File.OpenText(fileName))
            {
                if (isJson){
                    var stuff = (JObject)JsonConvert.DeserializeObject(ContentsOfFile.ReadToEnd());
                    result = stuff[valueToLookFor].Value<string>();
                }
                else {
                    var contents = ContentsOfFile.ReadToEnd();
                    contents = contents.Split(" = ")[1];
                    result = Regex.Replace(contents, @"t|n|r", "");
                }
            }            
            return result;
        }
    }
}

Вот Util.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;

public class Util
{
    public static X509Certificate2 ConvertFromPfxToPem(string filename)
    {
        using (System.IO.FileStream fs = System.IO.File.OpenRead(filename))
        {
            byte[] data = new byte[fs.Length];
            byte[] res = null;
            fs.Read(data, 0, data.Length);
            if (data[0] != 0x30)
            {
                res = GetPem("CERTIFICATE", data);
            }
            X509Certificate2 x509 = new X509Certificate2(res); //Exception hit here
            return x509;
        }      
    }   

    private static byte[] GetPem(string type, byte[] data)
    {
        string pem = Encoding.UTF8.GetString(data);
        string header = String.Format("-----BEGIN {0}-----", type);
        string footer = String.Format("-----END {0}-----", type);
        int start = pem.IndexOf(header) + header.Length;
        int end = pem.IndexOf(footer, start);
        string base64 = pem.Substring(start, (end - start));
        base64 = base64.Replace(System.Environment.NewLine, "");
        base64 = base64.Replace('-', '+');
        base64 = base64.Replace('_', '/');
        return Convert.FromBase64String(base64);
    }

    public static RSACryptoServiceProvider PemFileReader(){
        RsaPrivateCrtKeyParameters keyParams;
        using (var reader = File.OpenText("cert.pem")) // file containing RSA PKCS1 private key
        {
            keyParams = ((RsaPrivateCrtKeyParameters)new PemReader(reader).ReadObject());
        }

        RSAParameters rsaParameters = new RSAParameters();

        rsaParameters.Modulus = keyParams.Modulus.ToByteArrayUnsigned();
        rsaParameters.P = keyParams.P.ToByteArrayUnsigned();
        rsaParameters.Q = keyParams.Q.ToByteArrayUnsigned();
        rsaParameters.DP = keyParams.DP.ToByteArrayUnsigned();
        rsaParameters.DQ = keyParams.DQ.ToByteArrayUnsigned();
        rsaParameters.InverseQ = keyParams.QInv.ToByteArrayUnsigned();
        rsaParameters.D = keyParams.Exponent.ToByteArrayUnsigned();
        rsaParameters.Exponent = keyParams.PublicExponent.ToByteArrayUnsigned();

        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048);
        rsaKey.ImportParameters(rsaParameters);
        return rsaKey;
    }
}

Вот KeyVault.cs

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.KeyVault;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault.Models;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

namespace dotnetconsole
{
    public class KeyVault
    {
        KeyVaultClient _keyVaultClient;
        string APPLICATION_ID, CERT_THUMBPRINT;
        public KeyVault(string APPLICATION_ID, string CERT_THUMBPRINT) {
            this.APPLICATION_ID = APPLICATION_ID;
            this.CERT_THUMBPRINT = CERT_THUMBPRINT;
            _keyVaultClient = new KeyVaultClient(this.GetAccessToken);
        }

        public static ClientAssertionCertificate AssertionCert { get; set; }

        // This method is used to get a token from Azure Active Directory. 
        public async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);

            X509Certificate2 certByThumbprint = new X509Certificate2();
            if (isWindows){
                certByThumbprint = FindCertificateByThumbprint(this.CERT_THUMBPRINT);
            } else {
                // If it's a pem file then we take the private key portion and create a 
                // RSACryptoServiceProvider and then we create a x509Certificate2 class from the cert portion 
                // and then we combine them both to become one x509Certificate2
                RSACryptoServiceProvider rsaCryptoServiceProvider = Util.PemFileReader();
                certByThumbprint = Util.ConvertFromPfxToPem("cert.pem");
                certByThumbprint = certByThumbprint.CopyWithPrivateKey(rsaCryptoServiceProvider);
            }

            AssertionCert = new ClientAssertionCertificate(this.APPLICATION_ID, certByThumbprint);
            var result = await context.AcquireTokenAsync(resource, AssertionCert);
            return result.AccessToken;
        }


        public async Task CreateSecretKeyValuePair(string vaultBaseURL)
        {
            System.Console.WriteLine("Authenticating to Key Vault using ADAL Callback to create Secret Key Value Pair");
            System.Console.WriteLine(vaultBaseURL);
            KeyVaultClient kvClient = new KeyVaultClient(this.GetAccessToken);
            await kvClient.SetSecretAsync(vaultBaseURL, "TestKey", "TestSecret");
        }

        // In this method we first get a token from Azure Active Directory by using the self signed cert we created in our powershell commands
        // And then we pass that token to Azure Key Vault to authenticate the service principal to get access to the secrets
        // Finally we retrieve the secret value that was created previously 
        public void GetResult(string keyvaultUri)
        {
            try
            {
                var result = this._keyVaultClient.GetSecretAsync(keyvaultUri, "TestKey").Result.Value;
                System.Console.WriteLine("Secret Key retrieved is {0} and value is {1}, ", "TestKey", result);    
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        // In Windows this method would find the certificate that's stored in the certificate manager under current user
        // Given a thumbprint this method finds the certificate       
        public static X509Certificate2 FindCertificateByThumbprint(string findValue)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint,
                    findValue, false); // Don't validate certs, since the test root isn't installed.
                if (col == null || col.Count == 0 )
                    return null;
                return col[0];
            }
            finally
            {
                store.Close();
            }
        }
    }
}

[Обновлять]
Теперь я могу запустить dotnet restore, но dotnet run выдает ошибки

Следующим образом

KeyVault.cs(2,17): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(3,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(6,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(3,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(4,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(10,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Program.cs(11,17): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(7,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(8,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(9,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(10,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    Util.cs(11,7): error CS0246: The type or namespace name 'Org' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(22,23): error CS0246: The type or namespace name 'ClientAssertionCertificate' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]
    KeyVault.cs(14,9): error CS0246: The type or namespace name 'KeyVaultClient' could not be found (are you missing a using directive or an assembly reference?) [C:dev2018key-vault-dotnet-quickstartMyKeyVault.csproj]

    The build failed. Please fix the build errors and run again.

[Обновлять]

Инструменты -> Диспетчер пакетов Nuget -> Управление пакетами для решения сообщает об ошибке

Microsoft Visual Studio
The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

[Обновлять]

Я сохранил все, закрыл файл .sln и снова открыл его. Затем я смог войти в диспетчер пакетов Nuget.

[Обновлять]

Я установил Microsoft.Azure.KeyVault (3.0.0) и Newtonsoft.Json (11.0.2)
У меня проблемы с Microsoft.IdentityModel.Clients.ActiveDirectory
Когда я попробовал Microsoft.IdentityModel, это был неправильный фреймворк.

Package 'Microsoft.IdentityModel 6.1.7600.16394' was restored using ''.NETFramework, Version=v4.61'
instead of the projecttargetframework '.NETCoreApp,Version=v2.1' 
This package may not be fully compatible with your project

[Обновлять]
Погуглил «с использованием ядра Microsoft.IdentityModel.Clients.ActiveDirectory»

Найдено эта ссылка
и побежал в личку

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 3.19.8

[Обновлять]
Пытался поискать в Google Bouncy Castle с помощью оператора и нашел

Install-Package BouncyCastle.NetCore -Version 1.8.2

[Обновлять]

Восстановить все успешно, теперь у меня ошибка времени выполнения в строке 47 из

Var waitHandle = keyVaultObj.CreateSecretKeyValuePair (VaultName);

  System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at dotnetconsole.Program.Main(String[] args) in C:dev2018key-vault-dotnet-quickstartProgram.cs:line 47

Inner Exception 1:
ArgumentNullException: Value cannot be null.

After moving my .NET Core project into a subfolder in the solution I am no longer able to Debug it using VS Code.

If I move tasks.json and launch.json into the project folder and open VS Code there I am able to debug, but I would like to be able to open the entire solution in VS Code.

The error message I am getting is this:

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

The error seems to state that my task runner can no longer find my project, so I tried adding this to tasks.json:

{    
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [ ],
            "isBuildCommand": true,
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        }
    ],

    // My addition
    "options": {
        "cwd": "${workspaceRoot}/myProjectFolder"
    }
}

Doing this I am able to start the task, but I then get the following error:

Exception thrown: 'System.IO.FileNotFoundException' in 
Microsoft.Extensions.Configuration.FileExtensions.dll

How do I configure the .NET Core debugger to be able to run a project that resides in a sub folder?

asked Apr 13, 2017 at 13:20

severin's user avatar

severinseverin

5,0439 gold badges34 silver badges46 bronze badges

2

The problem is your tasks.json, you should copy your subfolder .vscode/tasks.json in the parent directory.

When you create your tasks.json from the parent directory, it make a tasks.json like as your tasks.json example.

But if you copy the tasks.json created in the subfolder It should be some like this:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/<change to your subfolder>/<your project>.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

So there is the .csproj file, it say in the error.

kenorb's user avatar

kenorb

149k80 gold badges668 silver badges723 bronze badges

answered Aug 9, 2018 at 3:29

Juan Pablo's user avatar

Juan PabloJuan Pablo

7769 silver badges18 bronze badges

The reason for the FileNotFoundException pointed by mrtedweb, the program not finding the appsettings.json can be solved without changing the program code.

Just edit launch.json, modifying the cwd configuration to point to the project subfolder instead of the root workspace which is the default, from
cwd: ${workspaceRoot} to, ${workspaceRoot}/TheProject.

// C:Solution.vscodelaunch.json
{
    "version": "0.2.0",
    "configurations": [
           {
                "name": ".NET Core Launch (console)",
                "type": "coreclr",
                "request": "launch",
                "preLaunchTask": "build",
                "program": "${workspaceRoot}/TheProject/bin/Debug/netcoreapp1.1/TheProject.dll",
                "args": [],
                "cwd": "${workspaceRoot}/TheProject",
                "stopAtEntry": false,
                "console": "internalConsole",
                "env": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_URLS": "http://localhost:5050"                
                }            
            }
    ]
}

With this launch.json, it’s possible to run the application from VS Code opening it from a root solution folder with the project inside a subfolder.

C:Solution>code .

And it can also be run from the commandline without changing the paths in the program from the project subfolder.

C:SolutionTheProject>dotnet run TheProject.csproj

answered Jul 7, 2017 at 21:16

Germán's user avatar

GermánGermán

1,1738 silver badges11 bronze badges

It can no longer locate the appsettings.json file since the project was moved to a subfolder. This can be easily fixed in the StartUp.cs file by adding the following variable to the constructor:

var filePath = Path.Combine(env.ContentRootPath, "<project folder name>", "appsettings.json");

Note: You will need to specify the value for <project folder name>.

Then update the line that reads

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

to read:

.AddJsonFile(filePath, optional: false, reloadOnChange: true)

Also, verify the launch.json file is targeting the proper program file.

"program": "${workspaceRoot}/<project name>/bin/Debug/netcoreapp1.1/<program name>.dll"

Note: You will need to specify the values for <project name>, and <program name>.

answered Apr 26, 2017 at 19:20

mrtedweb's user avatar

mrtedwebmrtedweb

7832 gold badges9 silver badges18 bronze badges

After moving my .NET Core project into a subfolder in the solution I am no longer able to Debug it using VS Code.

If I move tasks.json and launch.json into the project folder and open VS Code there I am able to debug, but I would like to be able to open the entire solution in VS Code.

The error message I am getting is this:

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

The error seems to state that my task runner can no longer find my project, so I tried adding this to tasks.json:

{    
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [ ],
            "isBuildCommand": true,
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        }
    ],

    // My addition
    "options": {
        "cwd": "${workspaceRoot}/myProjectFolder"
    }
}

Doing this I am able to start the task, but I then get the following error:

Exception thrown: 'System.IO.FileNotFoundException' in 
Microsoft.Extensions.Configuration.FileExtensions.dll

How do I configure the .NET Core debugger to be able to run a project that resides in a sub folder?

asked Apr 13, 2017 at 13:20

severin's user avatar

severinseverin

5,0439 gold badges34 silver badges46 bronze badges

2

The problem is your tasks.json, you should copy your subfolder .vscode/tasks.json in the parent directory.

When you create your tasks.json from the parent directory, it make a tasks.json like as your tasks.json example.

But if you copy the tasks.json created in the subfolder It should be some like this:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/<change to your subfolder>/<your project>.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

So there is the .csproj file, it say in the error.

kenorb's user avatar

kenorb

149k80 gold badges668 silver badges723 bronze badges

answered Aug 9, 2018 at 3:29

Juan Pablo's user avatar

Juan PabloJuan Pablo

7769 silver badges18 bronze badges

The reason for the FileNotFoundException pointed by mrtedweb, the program not finding the appsettings.json can be solved without changing the program code.

Just edit launch.json, modifying the cwd configuration to point to the project subfolder instead of the root workspace which is the default, from
cwd: ${workspaceRoot} to, ${workspaceRoot}/TheProject.

// C:Solution.vscodelaunch.json
{
    "version": "0.2.0",
    "configurations": [
           {
                "name": ".NET Core Launch (console)",
                "type": "coreclr",
                "request": "launch",
                "preLaunchTask": "build",
                "program": "${workspaceRoot}/TheProject/bin/Debug/netcoreapp1.1/TheProject.dll",
                "args": [],
                "cwd": "${workspaceRoot}/TheProject",
                "stopAtEntry": false,
                "console": "internalConsole",
                "env": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_URLS": "http://localhost:5050"                
                }            
            }
    ]
}

With this launch.json, it’s possible to run the application from VS Code opening it from a root solution folder with the project inside a subfolder.

C:Solution>code .

And it can also be run from the commandline without changing the paths in the program from the project subfolder.

C:SolutionTheProject>dotnet run TheProject.csproj

answered Jul 7, 2017 at 21:16

Germán's user avatar

GermánGermán

1,1738 silver badges11 bronze badges

It can no longer locate the appsettings.json file since the project was moved to a subfolder. This can be easily fixed in the StartUp.cs file by adding the following variable to the constructor:

var filePath = Path.Combine(env.ContentRootPath, "<project folder name>", "appsettings.json");

Note: You will need to specify the value for <project folder name>.

Then update the line that reads

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

to read:

.AddJsonFile(filePath, optional: false, reloadOnChange: true)

Also, verify the launch.json file is targeting the proper program file.

"program": "${workspaceRoot}/<project name>/bin/Debug/netcoreapp1.1/<program name>.dll"

Note: You will need to specify the values for <project name>, and <program name>.

answered Apr 26, 2017 at 19:20

mrtedweb's user avatar

mrtedwebmrtedweb

7832 gold badges9 silver badges18 bronze badges

Понравилась статья? Поделить с друзьями:
  • Error mp2t no data received
  • Error moving file osu что это
  • Error moupg cdlptask cancel 982 result 0xc1800104
  • Error mounting system managed device
  • Error mounting mount wrong fs type bad option bad superblock