Azure Function Portal C# Script cannot fetch nuget package for Microsoft.Azure.Cosmos

Siegfried Heintze 1,861 Reputation points
2022-10-15T19:01:19.02+00:00

I'm developing a windows Azure Function App in the portal.azure.com.
This C# script runs... However, if I remove the first comment, it fails with these errors in:

2022-10-15T18:47:59Z [Error] Compilation service error
2022-10-15T18:47:59Z [Error] Function loader reset. Failed compilation result will not be cached.
2022-10-15T18:47:59Z [Error] Executed 'Functions.HttpTrigger1' (Failed, Id=2981443d-4689-4fa0-96eb-de778929cc87, Duration=141ms)

I tried removing the "nuget:" and that did not help. Please guide me in developing a script that writes to an azure cosmos DocumentDb database.

#r "Newtonsoft.Json"  
//#r "nuget: Microsoft.Azure.Cosmos"  
  
using System.Net;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.Extensions.Primitives;  
using Newtonsoft.Json;  
using System;  
using static System.Environment;  
  
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)  
{  
    log.LogInformation("C# HTTP trigger function processed a request.");  
    var cosmosDocDbEndPointUri=GetEnvironmentVariable("COSMOS_ENDPOINT");  
    var cosmosDbKey=GetEnvironmentVariable("COSMOS_ACCOUNTKEY");  
    var settings = $"FUNCTIONS_WORKER_RUNTIME={GetEnvironmentVariable("FUNCTIONS_WORKER_RUNTIME")} COSMOS_ENDPOINT={cosmosDocDbEndPointUri}";  
  
    var cdt = DateTime.Now.ToString("dddd MMMM dd, yyyy hh:mm:ss tt zzz");  
    var status = $"{cdt} {settings}";  
    string name = req.Query["name"];  
    //using (var cosmosClient = new CosmosClient(cosmosDocDbEndPointUri, cosmosDbKey, new CosmosClientOptions() { ApplicationName = "WDFWScrapeCreelReports" }));  
  
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
    dynamic data = JsonConvert.DeserializeObject(requestBody);  
    name = name ?? data?.name;  
  
    string responseMessage = string.IsNullOrEmpty(name)  
        ? $"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response. {status}"  
                : $"Hello, {name}. This HTTP triggered function executed successfully. {status}";  
  
            return new OkObjectResult(responseMessage);  
}  

Wed Oct 12 2022 Morning Update:
Thanks for those references:

C# class library functions can include the NuGet packages for binding extensions directly in the class library project. For other non-.NET languages and C# script, the recommended way to install extensions is either by using extension bundles or by using Azure Functions Core Tools locally. If you can't use extension bundles and are only able to work in the portal, you need to use Advanced Tools (Kudu) to manually create the extensions.csproj file directly in the site. Make sure to first remove the extensionBundle element from the host.json file.

  1. For working in the portal on C# scripts: After studying "functions-how-to-use-azure-function-app-settings" I'm not clear on the contents of the extensions.csproj file. Can you show me an example? Where is the documentation on how to create this file?
  2. It says to remove the extensionBundle element from the host.json file. Where is this host.json file? I don't see it in the portal function editor.
  3. Yikes... Maybe I should consider abandoning the portal in favor of using Azure Functions Core Tools (AFCT) locally... Prior to making this initial post I had already tried to create a C# script using AFCT. Please point me to the documentation for using AFCT to create a C# script and deploy it. Step by step instructions (including nuget packages) would be really nice! I could only find a brief reference to the "--csx" switch.

Fri Oct 21 2022 Early Afternoon Update:
Thanks for that guidance. I tried to follow your directions. Since I already had the csproj from a console mode program that does the same thing as my script, I just pasted the contents of the csproj file into the extensions.csproj in the portal as per the instructions.

  1. I'm not clear about the "<OutputType>Exe</OutputType>" however. What should this be? I removed that and did the build as per the instructions and received no errors from the build.
  2. What about the source code for the run.csx... I removed the #r and got: 2022-10-21T20:40:26Z [Warning] You may be referencing NuGet packages incorrectly. Learn more: https://go.microsoft.com/fwlink/?linkid=2091419
    2022-10-21T20:40:26Z [Error] run.csx(7,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
    2022-10-21T20:40:26Z [Error] run.csx(10,23): error CS0234: The type or namespace name 'Cosmos' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)
    2022-10-21T20:40:26Z [Error] run.csx(25,20): error CS0103: The name 'JsonConvert' does not exist in the current context
    2022-10-21T20:40:27Z [Error] Function compilation error
    2022-10-21T20:40:27Z [Error] run.csx(7,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
    2022-10-21T20:40:27Z [Error] run.csx(10,23): error CS0234: The type or namespace name 'Cosmos' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)
    2022-10-21T20:40:27Z [Error] run.csx(25,20): error CS0103: The name 'JsonConvert' does not exist in the current context
    2022-10-21T20:40:27Z [Error] Executed 'Functions.HttpTrigger1' (Failed, Id=96aa5c9a-a38d-442b-bc34-fb5626348b39, Duration=399ms)

What should the top of my run.csx file look like?

This syntax does not work either:

#r "nuget: Newtonsoft.Json, 13.0.1"  
#r "nuget: Microsoft.Azure.Cosmos, 3.31.0"  

This is the syntax that was working in my CSX script running in github until I broke it by adding the Microsoft.Azure.Cosmos.

Here is my extensions.csproj file:

<Project Sdk="Microsoft.NET.Sdk">  
  
  <PropertyGroup>  
      
    <TargetFramework>net6.0</TargetFramework>  
    <ImplicitUsings>enable</ImplicitUsings>  
    <Nullable>enable</Nullable>  
    <LangVersion>preview</LangVersion>  
  </PropertyGroup>  
  
  <ItemGroup>  
    <PackageReference Include="Azure.Identity" Version="1.7.0" />  
    <PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.4.0" />  
    <PackageReference Include="Azure.Storage.Blobs" Version="12.13.1" />  
    <PackageReference Include="Azure.Storage.Files.Shares" Version="12.11.0" />  
    <PackageReference Include="Core.HttpClient" Version="3.1.9.12" />  
    <PackageReference Include="HtmlAgilityPack" Version="1.11.46" />  
    <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.31.0" />  
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />  
    <PackageReference Include="StopWatch" Version="1.0.6" />  
    <PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />  
  </ItemGroup>  
  
</Project>  

So I tried adding <OutputType>Library</OutputType> to the extensions.csproj and recompiling and now I get

2022-10-21T21:03:41Z   [Information]   Executing 'Functions.HttpTrigger1' (Reason='This function was programmatically called via the host APIs.', Id=f96a5c6f-51e7-4e97-8c8e-13026a6784ce)  
2022-10-21T21:03:41Z   [Error]   run.csx(2,1): error CS0006: Metadata file 'Microsoft.Azure.Cosmos' could not be found  
2022-10-21T21:03:41Z   [Error]   run.csx(10,23): error CS0234: The type or namespace name 'Cosmos' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)  
2022-10-21T21:03:41Z   [Error]   Function compilation error  
2022-10-21T21:03:41Z   [Error]   run.csx(2,1): error CS0006: Metadata file 'Microsoft.Azure.Cosmos' could not be found  
2022-10-21T21:03:41Z   [Error]   run.csx(10,23): error CS0234: The type or namespace name 'Cosmos' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)  
2022-10-21T21:03:41Z   [Error]   Executed 'Functions.HttpTrigger1' (Failed, Id=f96a5c6f-51e7-4e97-8c8e-13026a6784ce, Duration=348ms)  

Thanks!

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,299 questions
0 comments No comments
{count} votes

Accepted answer
  1. MuthuKumaranMurugaachari-MSFT 22,146 Reputation points
    2022-10-17T21:03:12.643+00:00

    @Siegfried Heintze Thank you for reaching out to Microsoft Q&A. Based on your statement, you are using C# script function and when referencing NuGet package "Microsoft.Azure.Cosmos", it fails with compilation error.

    I followed Create a function app doc to create C# script function with the same reference and failed with the same error.

    251221-image.png

    This is due to a behavior that only supported set of extension packages are available by default in addition to Newtonsoft.Json and the same is explained in the Using NuGet packages doc. For NuGet package references, you have option to either use extension bundles or manually create extensions.csproj file directly in the site and remove the extensionBundle element from the host.json file.

    251147-image.png

    Please follow Manually install extensions for detailed steps to manually install NuGet package. I hope this answers your question related to NuGet package reference.

    Regarding Azure Cosmos, you can refer samples available in GitHub: https://github.com/Azure-Samples/cosmos-dotnet-getting-started and https://github.com/Azure-Samples/cosmos-db-sql-api-dotnet-samples and doc: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-dotnet?tabs=azure-cli%2Cwindows for .NET to write custom code.

    Feel free to add a comment if you have any other questions or face issues. We would be happy to assist you. Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community.


0 additional answers

Sort by: Most helpful