0

I am trying to use Cosmos DB Document client in my Azure Function App. I have followed the steps mentioned here- How can I use NuGet packages in my Azure Functions?

I have the dependecy in project.json-

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "Microsoft.Azure.DocumentDB.Core": "2.1.3"
      }
    }
   }
}

The project.json is placed inside the function app and the app service editor path is like this-

https://<functionappname>.scm.azurewebsites.net/dev/wwwroot/<functionname>/project.json

This is my function code-

#r "Newtonsoft.Json"
#r "Microsoft.Azure.Documents.Client"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Formatting;
using System.Threading;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;


public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    string endPoint = <ep>;
    string databaseId = <dbID>;
    string collectionId = <cid>;
    string documentId = <did>;
    string resourceLink = string.Format("dbs/{0}/colls/{1}/docs/{2}", databaseId, collectionId, documentId);
    string primaryKey = <pk>;
    IDocumentClient documentClient = new DocumentClient(new Uri(endPoint), primaryKey);

    var response = documentClient.ReadDocumentAsync(resourceLink).Result;
    return new OkObjectResult(response);
}

When I Save and Run the app, I don't get any error or response. If I remove the CosmosDB reference codes it works. Below is the code-

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Formatting;
using System.Threading;


public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    return new OkObjectResult("response");
}

Am I missing something or doing this incorrectly? The same code works if I use it on a Console application. Any help with this please?

Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78
  • Is that Azure functions 1.0? Why don't you use Azure Functions 2.0 and reference the package normally from nuget? – Nick Chapsas Nov 29 '18 at 10:27
  • @NickChapsas I think it's 2.0 since I am directly doing this on the Azure portal (not Visual Studio). The documentations tell that I can do it from the KUDU console. – Souvik Ghosh Nov 29 '18 at 10:29

2 Answers2

1

To work in the Portal it's easier if you add a Function with the Cosmos DB Trigger, that will pull the Cosmos DB Extension into the Function App, and then you can delete the created Function and create a new one and pull the DocumentClient:

Searching for Trigger

Adding the Extension

Once the Extension is added, you can pull the client adding #r "Microsoft.Azure.DocumentDB.Core" on the top of your Function's code:

#r "Newtonsoft.Json"
#r "Microsoft.Azure.DocumentDB.Core"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;

private static DocumentClient client = new DocumentClient(new Uri("yourendpoint"), "yourkey");


public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
Matias Quaranta
  • 13,907
  • 1
  • 22
  • 47
0

Function 2.0 uses function.proj as below.

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.1.3"/>
    </ItemGroup>
</Project>

And remove extra #r "Microsoft.Azure.Documents.Client" as the assembly has been added.

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
  • Thanks. But it did not work. I am getting namespace not found error. I removed the project.json and created the function.csproj as you mentioned. – Souvik Ghosh Nov 29 '18 at 11:52
  • @SouvikGhosh Hmm, should be `function.proj`. Is it a typo or you create a .csproj? – Jerry Liu Nov 29 '18 at 11:57
  • Sorry it was a typo. So I changed the file to `function.proj`. I tried keeping it in `wwwroot/` and also `wwwroot//` but neither of them worked. FYI, I have a `function.json` file in the function which was auto generated. – Souvik Ghosh Nov 29 '18 at 12:54
  • @SouvikGhosh `function.json` is generated along with template code to configure bindings so it's not related. Put `function.proj` under wwwroot// should be enough.We can see restore and installation process in log stream, and a file `project.assets.json` will be generated under wwwroot// once the installation finishes. Go to kudu `D:\home\LogFiles\Application\Functions\Host` to check logs. Try to restart function app if no package restore runs for `function.proj`. – Jerry Liu Nov 29 '18 at 14:07
  • The packages got installed and `project.assets.json` got generated with the nuget package details. Somehow still it fails with error- 500. Removing the `Azure.Documents` and related code makes the function run. Am I using the namespaces correctly? I tried using `try-catch` to log the error in log stream (also at the beginning) but I got nothing. Thanks for your patience. – Souvik Ghosh Nov 30 '18 at 06:59
  • @SouvikGhosh Right, 500 means your code has been compiled successfully and some exception occurs during runtime. Go to `D:\home\LogFiles\Application\Functions\Host` for detailed logs. – Jerry Liu Nov 30 '18 at 07:04