Assembly could not be find in azure function - azure

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.

Related

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

Programmatically open an Excel document with connection to a Tabular Model

I would like to create a spreadsheet programmatically with a connection to my Tabular Model that exists in an Azure Analysis Server when the user clicks on some button. Similar to the option available in Azure to View Tabular Model which creates an odc file which you can open in Excel. My application is hosted on Azure and I am using .NET Core 2.2 as back-end.
I am quite clueless how can I achieve this. Has anyone managed to implement such functionality?
The simplest thing is to just generate and deliver an odc file, which will open with Excel.
First create an .odc file pointing to your AAS server, per docs: Create an Office Data Connection file.
Then add that .odc file to your web app, and serve it through a controller like this:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Text;
namespace WebApplication4.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class OdcController : ControllerBase
{
private IHostingEnvironment hostingEnvironment;
public OdcController(IHostingEnvironment env)
{
hostingEnvironment = env;
}
// GET api/values
[HttpGet]
public ActionResult Get()
{
var fp = Path.Combine(_env.ContentRootPath, "model.odc");
var odcText = System.IO.File.ReadAllText(fp);
//optionally modify odcText
return File(Encoding.ASCII.GetBytes(odcText), "application/octet-stream", "model.odc");
}
}
}

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

Azure function throwing exceptions when called even with default template

I'm baffled by how to just make a simple Azure function. In Visual Studio 2017 (I'm on version 15.5.6) I create a simple project following the instructions here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-develop-vs
My steps:
Make new Azure Functions project and leave the framework at the default of .Net Framework 4.6.1
On the next screen I choose HttpTrigger and the drop down says "Azure Functions v1 (.NET Framework)"
I set the storage to be my azure storage that I already created in the portal and set the authorization to "admin"
Everything compiles fine. I call the function via PostMan and get this error:
"A ScriptHost error has occurred
Exception while executing function: Functions.Function1. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'log'. Microsoft.Azure.WebJobs.Host: No value was provided for parameter 'log'."
For reference, here is the template function they created that I haven't modified at all:
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
namespace TestFunc
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Admin, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
name = name ?? data?.name;
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}
}
}
If I remove the "TraceWriter log" and the call to "log.Info(...." and then try again, I instead get this error:
"A ScriptHost error has occurred
Exception while executing function: Functions.Function1. mscorlib: Exception has been thrown by the target of an invocation. TestFunc: Method not found: 'System.Net.Http.HttpResponseMessage System.Net.Http.HttpRequestMessageExtensions.CreateResponse(System.Net.Http.HttpRequestMessage, System.Net.HttpStatusCode, !!0)'."
I've tried changing the .Net version to 4.7 but nothing changed. I tried changing the function version to v2 instead of v1 (even though it's in beta at the moment) but nothing happened either. The only NuGet package that's added by the template is Microsoft.NET.Sdk.Functions version 1.0.6. There's an update to 1.0.7 available but that doesn't help either.
I have no idea what to try. This is the default template. I have another function project that works fine but that was done a while ago when VS2015 was the latest, and was during the time when you had to have those function.json files to make your precompiled DLL. I was hoping to be able to use the current system as it seems to be the best way going forward but if I can't get this to work I may just go back to the old way of doing things. Thanks.

DocumentDB API output binding DELETE

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);
}

Resources