DocumentDB API output binding DELETE - node.js

Azure function app with HTTP trigger and 2 DocumentDB bindings - in and out.
On this page there are nice examples of how to add a new document, get existing one and update it. However - no examples on how to delete one!
Is a delete of an existing document possible at all with output bindings? And if not, what would be the best alternative - using Azure SDK within the function?
Thanks.

Yes, to delete a document you have to write an Azure function...here is the pcode if you are using the changefeed.
#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents;
using System.Collections.Generic;
using System;
public static void Run(IReadOnlyList<Document> documents, TraceWriter log)
{
//Get the document Id documents[0].Id);
//set the Request option
call DeleteDocumentAsync(string documentLink, RequestOptions options = null);
}

Related

Assembly could not be find in azure function

I am new to Azure Functions and facing the issue related to assembly.
Problem :
I want to read a PPT file which is being uploaded in Sharepoint.
Using Power Automate to start a flow which sends the file content to Azure function.
Azure function should read the content of PPT file.
I have added DocumentFormat.OpenXml (version - 2.13.0) and System.IO.Packaging (version 6.0.0) to bin folder
the code I have written is compiled without errors but when I run the code to test it gives assembly error, please refer to the images.
I have read that it is a known issue that Azure function removes assembly during runtime and this property _FunctionsSkipCleanOutput can be updated but if this is a solution then how to do this via portal?
I am using Azure Portal only.
#r "Newtonsoft.Json"
#r "System.IO.Packaging.dll"
#r "DocumentFormat.OpenXml.dll"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text;
using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Presentation;
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);
string file=data?.file;
byte[] filarray=Convert.FromBase64String(file);
MemoryStream m=new MemoryStream();
m.Write(filarray,0,filarray.Length);
int count=0;
using (PresentationDocument presnt=PresentationDocument.Open(m,true))
{
PresentationPart p=presnt.PresentationPart;
if(p!=null)
{
count=p.SlideParts.Count();
}
}
//name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty("jogi")
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: Convert.ToString(count);
//:file;
return new OkObjectResult(responseMessage);
}
I couldn't get the above working rather I tried to make the azure function using visual studio code and I could read the PPT file by adding reference to OpenXml.

404 after setting output of Azure Function to Cosmos DB

I use site editor for Azure Function. I modified initial function code, so it is now:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
log.LogInformation(requestBody);
return new OkObjectResult(requestBody);
}
then added an output to Cosmos Db using output parameter $return
when I'm testing my function I get 404 and nothing else
has anybody faced this issue and what can be done?
The problem was that I have set 2 output bindings to my function. Initially it was bound to HTTP and I have added Cosmos Db. I removed HTTP output binding and now it works like a charm

Can Azure function GridTrigger be used along with CosmosDB input binding?

I am a newbie to Azure functions. I am having problem with the below code where CosmosDB binding is not working. If I remove CosmosDB, it works find; I am able to get messages thru eventGridEvent. But as soon as I add CosmosDB, this piece of code fails. I had tried different Collectors (IAsyncCollectory, IReadOnlyCollection, IReadOnlyList, IEnumerable, etc.) some of them compiles fine but when deployed to Azure portal it does nothing (msg: function not found).
I need to retrieve data from CosmosDb and save it to a Queue by using the message coming thru eventGridEvent. I can hardcoded but that is not allowed for my project. Any help will be appreciated team!
[FunctionName("TopicGridTrigger")]
public static void Run([EventGridTrigger()] EventGridEvent eventGridEvent,
[Queue("myqueuetest")] out string queueMessage,
[CosmosDB("MyCarStore", "cars", ConnectionStringSetting = "CosmosDBConnectionString")] IAsyncCollector<MyCar> Items,
ILogger log
)
{
//SOME CODE HERE
}

Query CosmosDB from Azure Function .csx

I want to query a CosmosDB collection to see if a document already exists from within a Azure Function using csx.
As well as the following code I have an implicit binding towards the cosmosDB collection to be able to create new documents. This is done using
binder.BindAsync<IAsyncCollector<string>>(new CosmosDBAttribute("test", "collection")
This a simple version of my function.
#r "System"
#r "Microsoft.Azure.WebJobs.Extensions.CosmosDB"
using System;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
public static async Task<string> Run(string localityId, Binder binder, TraceWriter log)
{
...
string EndpointUrl = "<your endpoint URL>";
string PrimaryKey = "<your primary key>";
DocumentClient client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
...
}
This results in the following error message:
error CS0246: The type or namespace name 'DocumentClient' could not be found (are you missing a using directive or an assembly reference?)
I have installed the extension Microsoft.Azure.WebJobs.Extensions.CosmosDB
I am running on MacOS using the func host start command to test locally.
error CS0246: The type or namespace name 'DocumentClient' could not be found (are you missing a using directive or an assembly reference?)
It seems that you need to reference #r "Microsoft.Azure.Documents.Client". You also could get demo code from Azure Cosmos DB bindings for Azure Functions
#r "Microsoft.Azure.Documents.Client"
using System;
using Microsoft.Azure.Documents;
using System.Collections.Generic;
public static void Run(IReadOnlyList<Document> documents, TraceWriter log)
{
log.Verbose("Documents modified " + documents.Count);
log.Verbose("First document Id " + documents[0].Id);
}
Update:
To use NuGet packages in a C# function, upload a project.json file to the function's folder in the function app's file system. Here is an example project.json file that adds a reference

Restart Web/Api-App on Azure programmatically

How can I restart Web-Apps and API-Apps on Azure programmatically?
(I'd like to call it from another API-App within the same App service plan.)
There's also the "Microsoft Azure Management Libraries" Nuget that allows you to work with Azure services from inside of applications.
See this page for an example on how to create new web sites from inside of an Azure Web site. Restarting web services work in a similar way to creating new services. See this page for a list of available web site related methods.
Also, for authenticating is used certificate base authentication, see this page for more details on that.
Bellow is a short command line program that will restart all websites in all the webspaces you got in your Azure subscription. It works kinda like an iisreset for Azure Web Sites.
The code is based on samples taken from the links earlier mentioned:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.WebSites;
using Microsoft.WindowsAzure;
using System.Security.Cryptography.X509Certificates;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var subscriptionId = "[INSERT_YOUR_SUBSCRIPTION_ID_HERE]";
var cred = new CertificateCloudCredentials(subscriptionId, GetCertificate());
var client = new WebSiteManagementClient(cred);
WebSpacesListResponse webspaces = client.WebSpaces.List();
webspaces.Select(p =>
{
Console.WriteLine("Processing webspace {0}", p.Name);
WebSpacesListWebSitesResponse websitesInWebspace = client.WebSpaces.ListWebSites(p.Name,
new WebSiteListParameters()
{
});
websitesInWebspace.Select(o =>
{
Console.Write(" - Restarting {0} ... ", o.Name);
OperationResponse operation = client.WebSites.Restart(p.Name, o.Name);
Console.WriteLine(operation.StatusCode.ToString());
return o;
}).ToArray();
return p;
}).ToArray();
if(System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press anykey to exit");
Console.Read();
}
}
private static X509Certificate2 GetCertificate()
{
string certPath = Environment.CurrentDirectory + "\\" + "[NAME_OF_PFX_CERTIFICATE]";
var x509Cert = new X509Certificate2(certPath,"[PASSWORD_FOR_PFX_CERTIFICATE]");
return x509Cert;
}
}
}
Another alternative, if you can't find the function you need from the above mentioned library, you can also run powershell commands programmatically from inside of your application. You most likely will need to move, the application that is supposed to run these cmdlets, to a virtual machine to be able to load the needed powershell modules. See this page for more information on running powershell cmdlets programmatically.
You can use Powershell to do this. The relevant commands are:
Start-AzureWebsite -Name “xxxx”
Stop-AzureWebsite -Name “xxxx”
You can find help on these commands at the following links:
https://msdn.microsoft.com/en-us/library/azure/dn495288.aspx
https://msdn.microsoft.com/en-us/library/azure/dn495185.aspx
I think handling the base REST API is much better option. The Azure SDK changes quite a lot and lacks good documentation.
Here is an up-to-date sample code:
https://github.com/davidebbo/AzureWebsitesSamples/
You can adapt it to your needs.

Resources