Created
February 16, 2022 05:04
-
-
Save elliz/a96830b7970d0d21b611b44b1eed6509 to your computer and use it in GitHub Desktop.
Create a CosmosDb User Defined Function using .NET SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Azure.Cosmos; | |
using Microsoft.Azure.Cosmos.Scripts; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
namespace GoesHere | |
{ | |
public class ClassName | |
{ | |
pubic void DoStuff() | |
{ | |
// assume have CosmosClient | |
var databaseResponse = await cosmosClient.CreateDatabaseIfNotExistsAsycn(...); | |
var cosmosScripts = database.Database.GetContainer(container.Name).Scripts; | |
} | |
private static async Task CreateUdf(Scripts cosmosScripts, string fn) | |
{ | |
var response = await cosmosScripts.CreateUserDefinedFunctionAsync(new UserDefinedFunctionProperties | |
{ | |
Id = fn, | |
Body = Udf.Functions[fn] | |
}); | |
} | |
private static async Task<bool> UdfAlreadyExists(Scripts cosmosScripts, string fn) | |
{ | |
bool udfExists; | |
try | |
{ | |
UserDefinedFunctionResponse udfResponse = await cosmosScripts.ReadUserDefinedFunctionAsync(fn); | |
udfExists = true; | |
} | |
catch (CosmosException ex) | |
{ | |
if (ex.StatusCode == HttpStatusCode.NotFound) | |
{ | |
udfExists = false; | |
} | |
else | |
{ | |
throw; | |
} | |
} | |
return udfExists; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment