Executing Azure Stored Procedure from Azure Triggering Function - azure

I wrote a stored procedure for deleting records from cosmosDB based on updation date of the document.
The cosmosDB collection is having large number (say 500) of partition keys so that I have to execute the stored procedure 500 times.
I am trying to execute an azure stored procedure from Azure time triggering function.
Below are the codes written in azure triggering function:
Added new file project.json
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.Azure.DocumentDB": "2.0.0"
}
}
}
}
run.csx fle is updated as below.
#r "Microsoft.Azure.Documents.Client"
using System;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
public static async Task Run(TimerInfo myTimer, IEnumerable<dynamic>
inputDocument, TraceWriter log)
{
log.Info($"C# Timer trigger function started at: {DateTime.Now}");
// Get the date 6 months before from Current Time in IST and convert to Epoch value.
TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India
Standard Time");
DateTime indianTime =
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow.AddDays(-180),
INDIAN_ZONE);
long epochTime = (long)(indianTime - new DateTime(1970, 1,
1)).TotalSeconds;
DocumentClient client;
string endpoint = "https://***cosmosdb.documents.azure.com:443/";
string key = "****";
client = new DocumentClient(new Uri(endpoint), key);
foreach (var doc in inputDocument)
{
string partKey = doc.NUM;
StoredProcedureResponse<bool> sprocResponse = await
client.ExecuteStoredProcedureAsync<bool>(
"/dbs/DB_NAME/colls/COLLECTION_NAME/sprocs/STORED PROC_NAME/",new
RequestOptions { PartitionKey = new PartitionKey(partKey) });
log.Info($"Cosmos DB is updated at: {DateTime.Now}");
}
}
I am getting the below error while compiling the above code.
2019-08-22T15:30:01.759 [Error] Exception while executing function: Functions.TimerTriggerCSharp1. Microsoft.Azure.WebJobs.Script: One or more errors occurred. Microsoft.Azure.Documents.Client: Failed to deserialize stored procedure response or convert it to type 'System.Boolean': Unexpected character encountered while parsing value: {. Path '', line 1, position 1. Newtonsoft.Json: Unexpected character encountered while parsing value: {. Path '', line 1, position 1.
2019-08-22T15:30:01.822 [Error] Function completed (Failure, Id=02da4d71-8207-4227-9c79-1cc277439c20, Duration=1814ms)
I have to pass a date parameter and array of partition keys while executing the stored procedure.
I am totally stuck in this stage. what could be done to resolve this issue ?

The error message means that your script code of your Azure Function is not correct.
Remove all private and static declarations inside your function.
private static DocumentClient client;
static string endpoint;
static string key
==>
DocumentClient client;
string endpoint;
string key;
General advise: Do not author Functions in the Azure portal (in .csx). Do yourself a favor and use a proper IDE such as VS Code.

If you are using the Portal, you need to pull in the dependency at the top of your Function like so:
#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
And please, use a newer version of the SDK, 1.7.1 is from more than 3 years ago: https://www.nuget.org/packages/Microsoft.Azure.DocumentDB/

Related

Unable to Connect from Azure Function to Azure Cosmos DB. Getting "Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object

Got a .Net code from Udemy course and ran in my local. Wrote an Azure Function which connects to Azure Cosmos DB and creates an item. But not getting connected to Azure Cosmos DB. See below the code and error. Appreciate any help. In the debug, found out some issue with the line
_container.CreateItemAsync(_blobdetails, newPartitionKey(_message.VideoName)).GetAwaiter().GetResult();
Code :
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace ReceiveMessages
{
public static class Process
{
private static string blob_connection_string = "<blob connection string>";
private static string source_container_name = "unprocessed";
private static string destination_container_name = "processed";
private static readonly string _connection_string = "<cosmos connection string>";
private static readonly string _database_name = "appdb";
private static readonly string _container_name = "video";
[FunctionName("ProcessVideos")]
public static async Task Run([ServiceBusTrigger("videoqueue", Connection = "connection")]ServiceBusReceivedMessage myQueueItem, ILogger log)
{
try
{
ReceivedMessage _message = JsonSerializer.Deserialize<ReceivedMessage>(Encoding.UTF8.GetString(myQueueItem.Body));
BlobServiceClient _client = new BlobServiceClient(blob_connection_string);
BlobContainerClient _source_container_client = _client.GetBlobContainerClient(source_container_name);
BlobClient _source_blob_client = _source_container_client.GetBlobClient(_message.VideoName);
BlobContainerClient _destination_container_client = _client.GetBlobContainerClient(destination_container_name);
BlobClient _destination_blob_client = _destination_container_client.GetBlobClient(_message.VideoName);
CosmosClient _cosmosclient = new CosmosClient(_connection_string, new CosmosClientOptions());
Container _container = _cosmosclient.GetContainer(_database_name, _container_name);
BlobDownloadInfo _info = _source_blob_client.Download();
// Copy the blob to the destination container
await _destination_blob_client.StartCopyFromUriAsync(_source_blob_client.Uri);
log.LogInformation(_info.Details.LastModified.ToString());
log.LogInformation(_info.ContentLength.ToString());
BlobDetails _blobdetails = new BlobDetails();
_blobdetails.BlobName = _message.VideoName;
_blobdetails.BlobLocation = "https://videostorage100.blob.core.windows.net/processed/" + _message.VideoName;
_blobdetails.ContentLength = _info.ContentLength.ToString();
_blobdetails.LastModified = _info.Details.LastModified.ToString();
_blobdetails.id = Guid.NewGuid().ToString();
_container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName)).GetAwaiter().GetResult();
Console.WriteLine("Item created");
// Delete the blob from the unprocessed container
_source_blob_client.Delete();
// Add the details of the blob to an Azure Cosmos DB account
}
catch (Exception ex)
{
string s = ex.Message;
}
}
}
}
* Executed 'ProcessVideos' (Failed, Id=53b3d0b2-d46a-4ba9-bf26-d8de76af0bce, Duration=41001ms)
[2022-03-19T23:07:25.845Z] Executed 'ProcessVideos' (Failed, Id=48b50a3d-f69f-436f-accf-5140c3d7f8a0, Duration=41001ms)
[2022-03-19T23:07:25.854Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object.{"name":"CreateItemAsync","id":"c16e23cd-badc-4f0b-a940-3fac7f52c4f7","caller info":{"member":"OperationHelperWithRootTraceAsync","file":"ClientContextCore.cs","line":219},"start time":"11:06:46:894","duration in milliseconds":36808.7271,"data":{"Client Configuration":{"Client Created Time Utc":"2022-03-19T23:06:45.5706176Z","NumberOfClientsCreated":3,"User Agent":"cosmos-netstandard-sdk/3.19.0|3.19.1|08|X64|Microsoft Windows 10.0.19043|.NET Core 3.1.20|N|","ConnectionConfig":{"gw":"(cps:50, urto:10, p:False, httpf: False)","rntbd":"(cto: 5, icto: -1, mrpc: 30, mcpe: 65535, erd: False, pr: ReuseUnicastPort)","other":"(ed:False, be:False)"},"ConsistencyConfig":"(consistency: NotSet, prgns:[])"}},"children":[{"name":"ItemSerialize","id":"647e3fbb-bd9f-4b12-9367-3ed1f6c4d436","caller info":{"member":"ExtractPartitionKeyAndProcessItemStreamAsync","file":"ContainerCore.Items.cs","line":931},"start time":"11:06:46:921","duration in milliseconds":20.2124},{"name":"Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler","id":"23650859-deb4-44e1-a696-daeeab7564c8","start time":"11:06:47:893","duration in milliseconds":35799.6699,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.DiagnosticsHandler","id":"f18265a9-2a93-46c8-aa05-78b69ed30086","start time":"11:06:47:927","duration in milliseconds":35763.5861,"data":{"CPU Load History":{"CPU History":"(2022-03-19T23:06:47.9376170Z 38.049)"}},"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.RetryHandler","id":"876ad64c-0dc3-42a2-9a47-4054ec301b57","start time":"11:06:47:945","duration in milliseconds":35744.6099,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.RouterHandler","id":"01ca2b19-39c0-477d-ad85-f930397e682a","start time":"11:06:47:954","duration in milliseconds":35729.8987,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.TransportHandler","id":"e372af16-b68c-438d-9ae1-2fdaad2d5f23","start time":"11:06:47:955","duration in milliseconds":35720.3525,"children":[{"name":"Microsoft.Azure.Documents.ServerStoreModel Transport Request","id":"9995478e-5933-4b21-8c08-cf03501ebe03","caller info":{"member":"ProcessMessageAsync","file":"TransportHandler.cs","line":109},"start time":"11:06:47:963","duration in milliseconds":35704.0196,"data":{"Client Side Request Stats":{"Id":"AggregatedClientSideRequestStatistics","ContactedReplicas":[{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14059/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901445077053s/"},{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14352/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901532421814s/"},{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14095/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901532421816s/"}],"RegionsContacted":["https://videodbupdate-westus.documents.azure.com/"],"FailedReplicas":[],"AddressResolutionStatistics":[{"StartTimeUTC":"2022-03-19T23:06:48.3431877Z","EndTimeUTC":"2022-03-19T23:06:48.4598190Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:06:54.7678280Z","EndTimeUTC":"2022-03-19T23:06:54.8820135Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:01.6288211Z","EndTimeUTC":"2022-03-19T23:07:01.7399788Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:09.6372169Z","EndTimeUTC":"2022-03-19T23:07:09.7484346Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:17.9939496Z","EndTimeUTC":"2022-03-19T23:07:18.1025134Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"}],"*
*[2022-03-19T23:07:25.848Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: ServiceUnavailable (503); Substatus: 0; ActivityId: 349d6ef1-4696-4ec8-88c9-5913129164ec; Reason: (Service is currently unavailable. More info: https://aka.ms/cosmosdb-tsg-service-unavailable
[2022-03-19T23:07:26.012Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: ServiceUnavailable (503); Substatus: 0; ActivityId: 40f51724-2bf3-46b2-ac99-c9030aed41c6; Reason: (Service is currently unavailable. More info: https://aka.ms/cosmosdb-tsg-service-unavailable
[2022-03-19T23:07:26.040Z] ActivityId: 349d6ef1-4696-4ec8-88c9-5913129164ec, Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, Windows/10.0.19043 cosmos-netstandard-sdk/3.19.1);. Microsoft.Azure.Cosmos.Direct: Message: The requested resource is no longer available at the server.*
This was fixed in SDK 3.20: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/changelog.md#-3200---2021-06-21
Please upgrade to the recommended version to get this and other fixes.
More fixes
You are creating a client (both Blob and Cosmos) per Function execution, that goes against the recommendations and will bring problems as the number of queue messages increase, please follow https://learn.microsoft.com/azure/azure-functions/manage-connections?tabs=csharp#static-clients and use Singleton/static instances. We have a complete example on how to use DI and Functions with the CosmosClient at https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/AzureFunctions.
Also, do not block threads, since your Function is already async, do await _container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName)) instead.
These 2 points is what will generate these Service Unavailable errors in most cases.
ALSO VERY IMPORTANT, YOUR POST CONTAINED SERVICE KEYS AND CONNECTIONSTRINGS (I EDITED TO REMOVE THEM BUT THEY WERE ALREADY EXPOSED), ROTATE THEM IMMEDIATELY

Azure connection attempt failed

I'm using the following code to connect. I can connect to other Azure Resources ok.
But for one resource I get the following error: URL and Key are correct.
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"}
The Code is as follows
_searchClient = new SearchServiceClient(searchServiceName, new
SearchCredentials(apiKey));
_httpClient.DefaultRequestHeaders.Add("api-key", apiKey);
_searchServiceEndpoint = String.Format("https://{0}.{1}",
searchServiceName, _searchClient.SearchDnsSuffix);
bool result = RunAsync().GetAwaiter().GetResult();
Any ideas? thx in advance? How can I troubleshoot this?
I will show how this is done in c#
you will need a appsettings.json
you will need this code in the program.cs file
there are a lot of other files in the example from the document
that you may need to use , learn and edit for ur usecase
When working in c# and azure, always know what is unique about the file structured your solution first. This is why we build the examples from the docs as we learn the solution. Next we must study the different blocks of code that when executed deliver one feature or functionality to the solution as a whole.
appsettings.json
{
"SearchServiceName": "[Put your search service name here]",
"SearchIndexName": "hotels",
"SearchServiceAdminApiKey": "[Put your primary or secondary Admin API key here]",
"SearchServiceQueryApiKey": "[Put your primary or secondary Query API key here]"
}
Program.cs
namespace AzureSearch.SDKHowTo
{
using System;
using System.Linq;
using System.Threading;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Spatial;
// This sample shows how to delete, create, upload documents and query an index
static void Main(string[] args)
{
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
SearchServiceClient serviceClient = CreateSearchServiceClient(configuration);
string indexName = configuration["SearchIndexName"];
Console.WriteLine("{0}", "Deleting index...\n");
DeleteIndexIfExists(indexName, serviceClient);
Console.WriteLine("{0}", "Creating index...\n");
CreateIndex(indexName, serviceClient);
ISearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);
Console.WriteLine("{0}", "Uploading documents...\n");
UploadDocuments(indexClient);
ISearchIndexClient indexClientForQueries = CreateSearchIndexClient(indexName, configuration);
RunQueries(indexClientForQueries);
Console.WriteLine("{0}", "Complete. Press any key to end application...\n");
Console.ReadKey();
}
private static SearchServiceClient CreateSearchServiceClient(IConfigurationRoot configuration)
{
string searchServiceName = configuration["SearchServiceName"];
string adminApiKey = configuration["SearchServiceAdminApiKey"];
SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(adminApiKey));
return serviceClient;
}
private static SearchIndexClient CreateSearchIndexClient(string indexName, IConfigurationRoot configuration)
{
string searchServiceName = configuration["SearchServiceName"];
string queryApiKey = configuration["SearchServiceQueryApiKey"];
SearchIndexClient indexClient = new SearchIndexClient(searchServiceName, indexName, new SearchCredentials(queryApiKey));
return indexClient;
}
private static void DeleteIndexIfExists(string indexName, SearchServiceClient serviceClient)
{
if (serviceClient.Indexes.Exists(indexName))
{
serviceClient.Indexes.Delete(indexName);
}
}
private static void CreateIndex(string indexName, SearchServiceClient serviceClient)
{
var definition = new Index()
{
Name = indexName,
Fields = FieldBuilder.BuildForType<Hotel>()
};
serviceClient.Indexes.Create(definition);
}}
Azure concepts to learn
How and why we create azure clients
Why do we use appsettings.json
What is some example file structures for azure search solutions
What coding lanague do you want to use to build that solutio
do u want to use the azure sdk
How to find and create api keys
C# concepts to learn
What is an interface and how do you use it
How to import one file in the file structure into another
How the main function works
How to call variables in to a function
How to call a function with a function
How to write server side code vs client side code
How to deploy c# code to azure
What version of c# are u using What’s is asp.net and what version will u use
What is asp.net core and what version will u use
As u can see azure and c# have a high learning curve.
Luckily you have stack overflow and documentation to research all of the above questions and more:)
For how u would troubleshoot...what I do is research each block of code in the documentation example and run all of the code locally. Then I test each block of code one at a time. Ur always testing data flowing thought the block of code. So you can just console log the result of a block a code by creating a test varable and print that varable to the console.
Because each block of Code represents one feature or functionality, each test will output either a pass or fail delivery of that feature or functionality. Thus you can design functionality, implement that design and create a test for new Feature.

Azure Functions dynamic input / output binding based on Service Bus trigger message content

I'm trying to create Azure Function 2.0 with multiple bindings. The function gets triggered by Azure Service Bus Queue message and I would like to read Blob based on this message content. I've already tried below code:
public static class Functions
{
[FunctionName(nameof(MyFunctionName))]
public static async Task MyFunctionName(
[ServiceBusTrigger(Consts.QueueName, Connection = Consts.ServiceBusConnection)] string message,
[Blob("container/{message}-xyz.txt", FileAccess.Read, Connection = "StorageConnName")] string blobContent
)
{
// processing the blob content
}
}
but I'm getting following error:
Microsoft.Azure.WebJobs.Host: Error indexing method 'MyFunctionName'. Microsoft.Azure.WebJobs.Host: Unable to resolve binding parameter 'message'. Binding expressions must map to either a value provided by the trigger or a property of the value the trigger is bound to, or must be a system binding expression (e.g. sys.randguid, sys.utcnow, etc.).
I saw somewhere that dynamic bindings can be used but perhaps it's not possible to create input binding based on another input binding. Any ideas?
I'm actually surprise that did not work. There are lots of quirks with bindings. Please give this a shot:
public static class Functions
{
[FunctionName(nameof(MyFunctionName))]
public static async Task MyFunctionName(
[ServiceBusTrigger(Consts.QueueName, Connection = Consts.ServiceBusConnection)] MyConcreteMessage message,
[Blob("container/{message}-xyz.txt", FileAccess.Read, Connection = "StorageConnName")] string blobContent
)
{
// processing the blob content
}
}
Create a DTO:
public class MyConcreteMessage
{
public string message {get;set;}
}
Ensure that the message that you are using in the servicebus is something like this:
{
"message": "MyAwesomeFile"
}
It should now be able to read your binding container/{message}-xyz.txt and recognize that message

Azure Function 1.x to 2.x upgrade - Issue with GetQueryNameValuePairs

I have an HTTP Trigger Azure Function which is currently in 1.x. The code is as below:
using System.Net;
using System.Threading.Tasks;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
// 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);
}
While trying to upgrade it to 2.x, I am getting an issue with GetQueryNameValuePairs
I am getting error - 'HttpRequestMessage' does not contain a definition for 'GetQueryNameValuePairs'
Is there no support for this method in 2.0? How can this be accomplished in .net standard?
Function runtime 1.x is on Full .Net Framework, while 2.x runs on .NET Core env and our function code targets at .NET Standard.
For this class HttpRequestMessage, it doesn't have GetQueryNameValuePairs method in .NET Standard assembly.
Migrating from 1.x to 2.x usually needs work of code modification. Since it's just a template, I suggest you delete it and recreate a Http Trigger in 2.x runtime. You may see a different template work with .NET Standard.
Here is the sample code that looks up query string parameters in Functions V2.x
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
public static IActionResult Run(HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
if (req.Query.TryGetValue("name", out StringValues value))
{
return new OkObjectResult($"Hello, {value.ToString()}");
}
return new BadRequestObjectResult("Please pass a name on the query string");
}
In Functions v2 this has changed to req.GetQueryParameterDictionary();

How to troubleshoot Flaky Azure function app behaviour?

I am trying out Azure Function Apps.
The first one following the example in a tutorial with Open Weather map, stopped working after I used log.WriteLine(), which correctly threw a compiler error. I changed to log.Info() and it kept complaining about TraceWriter not containing a definition for WriteLine.
After a lengthy troubleshooting session, I created a new function, copying all the content of the broken one, and it worked immediately.
Created a new function, as before, and began making changes to the Run() method, and running this function yields:
"The resource you are looking for has been removed, had its name
changed, or is temporarily unavailable."
Bearing in mind, the function URL is based on the default key Azure generates when the function is created: https://.azurewebsites.net/api/WeatherWhereYouAre?code=my1really2RAndom3defauLT4Key5from6Azure==
Created yet another function, with no changes from the default "Hello Azure" sample, and it yields a 500 error with:
"Exception while executing function: Functions.HttpTriggerCSharp2 ->
One or more errors occurred. -> Exception binding parameter 'req' ->
Input string was not in a correct format."
This is the content of the project.json file:
{
"frameworks": {
"net46": {
"dependencies": {
"Microsoft.IdentityModel.Clients.ActiveDirectory": "3.16.0",
"Microsoft.Azure.KeyVault": "2.3.2",
"Microsoft.AspNet.WebApi.Client": "5.2.3"
}
}
}
}
And the run.csx:
using System.Net;
public static async Task<HttpResponseMessage> Run(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);
}
EDIT
In the above image, note that this is httpTriggerFSharp1, but the exception is HttpTriggerCSharp2 (which is the only one that works!)
Is there a way I can properly troubleshoot these?
For the default HttpTrigger template for C#, you could call it as follows:
Get https://brucefunapp.azurewebsites.net/api/HttpTriggerCSharp3?name=bruce&code=ItDhLMxwDYmTvMTYzVbbALtL5GEcmaL5DlzSaD4FRIuFdh17ZkY71g==
Or
Post https://brucefunapp.azurewebsites.net/api/HttpTriggerCSharp3?code=ItDhLMxwDYmTvMTYzVbbALtL5GEcmaL5DlzSaD4FRIuFdh17ZkY71g==
Content-type: application/json
{"name": "bruce"}
For more details about Azure Functions C# script, you could refer to here.
Is there a way I can properly troubleshoot these?
Per my understanding, you could leverage Precompiled functions and use Visual Studio 2017 Tools for Azure Functions for creating, local debugging, and publishing to Azure.

Resources