I have a problem with azure function only when I publish.
the code run not in order, all the functions run at the same time.
ex :
var logger = context.GetLogger(nameof(MibProposalRequest));
logger.Log(LogLevel.Warning, $"Début de la fonction : MibProposalRequest {DateTime.UtcNow}");
try
{
var getStringResponse = await this.GetStringAsync(req, logger).ConfigureAwait(false);
if (getStringResponse.Error != null)
{
return new HttpResponseMessage()
{
StatusCode = getStringResponse.Error.StatusCode,
ReasonPhrase = getStringResponse.Error.Message
};
}
else
{
var requestBody = getStringResponse.Response.ToString();
var deserializeRequestBodyResponse = await this.DeserializeRequestBodyAsync(requestBody, logger).ConfigureAwait(false);
if (deserializeRequestBodyResponse.Error != null)
{
return new HttpResponseMessage()
{
StatusCode = deserializeRequestBodyResponse.Error.StatusCode,
ReasonPhrase = deserializeRequestBodyResponse.Error.Message
};
}
In this example I need to get the response of the function GETStringAsync and after go to the function : DeserializeRequestBodyAsync.
If I run the azure function in local (debug) it's all ok, everything it's in order.
First log the function start.
After Get the string
end deserializeObject.
But when I publish the function and I test it, when I'm loocking at the log in portal.azure.
All the function run not in good order.
So sometimes I get an error from deserializeObject function because no string to deserialize.
But its suppose to do the GetStringAsync function first.
Why this append?
Image of the log
as you can see the function start log is not the first to show up why ?
looks like all the code run completely not in order.
should be like this :
Log of vs debug
Everything is good each functions run in good order (so no problems)
Why this append only when the function is published ??
Ps: I tried to run the function not async but nothing change.
PS2: I tried to put all the code in the same function (Run) nothing changed.
PS3: I tried to put task.wait nothing changed.
I need help please 2 days I'm on this.
https://azure.microsoft.com/en-us/updates/general-availability-azure-functions-supports-net-5-in-production/?cdn=disable
From my experience this was a pain to get to work with Azure Functions on .NET 5. Either roll back to 3.1 or wait till 11/9/2021 for .NET 6 to release out of preview. .NEt 6 preview is allowed on Azure for testing.
Are you running .NET 5 in Azure in isolated mode? See link above.
"To support .NET 5, Azure Functions introduces a new isolated process model that runs .NET function apps in a separate worker process outside the Azure Functions host runtime."
I just found a solution in the code:
List<ProposalIdModel> list = (List<ProposalIdModel>)deserializeGuidsAsyncResponse.Response ?? new List<ProposalIdModel>();
Like this the list while never be null.
But it's wired in visual studio in debug no problem, but when I publish sometime the list get null.
So problem solved.
I also update to netCore6.
Related
I have an issue with the following code, working well in a Console App project and not working in a ASP.NET Web Forms project, both targeting .NET Framework 4.7.2.
The goal is to use the last Azure Cosmos DB SDK (v3) to get all documents in a container, without specifying a type (use of dynamic).
I've tried to target both the emulator (the last version 2.4.5) and the Azure Cosmos service.
In the ASP.NET project, the execution of queryResultSetIterator.ReadNextAsync().Result never ends (no timeout).
string endpointUri = "https://localhost:8081";
string primaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
string database = "SendGridEvents";
string collection = "SendGridEvents";
using (CosmosClient client = new CosmosClient(endpointUri, primaryKey))
{
Container container = client.GetDatabase(database).GetContainer(collection);
QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c");
FeedIterator<dynamic> queryResultSetIterator = container.GetItemQueryIterator<dynamic>(queryDefinition);
List<dynamic> documents = new List<dynamic>();
while (queryResultSetIterator.HasMoreResults)
{
FeedResponse<dynamic> currentResultSet = queryResultSetIterator.ReadNextAsync().Result;
foreach (var document in currentResultSet)
{
documents.Add(document);
}
}
}
This is caused due to a deadlock because of the use of the problematic .Result.
There are countless of sources that explain this deadlock but I will link this answer from StackOverflow.
The TL;DR is that you are blocking an otherwise asynchronous call in the UI thread which is causing the deadlock. You need to properly await your call like this:
FeedResponse<dynamic> currentResultSet = await queryResultSetIterator.ReadNextAsync();
You could technically block the call if you used the ConfigureAwait(false) approach but the v3 SDK does not cascade this call all the way to the network calls so it wouldn't make any difference. WebForms allows you to have async handlers so you would be fine to make your method async and try again.
So I have a few different parse servers setup.
One server is just to capture error logs from various applications (I have a LOT out there) in nice uniformed database.
So I might have a specific standalone data migration tool that if it encounters an error, will write out the exception into this Error_log parse table/class. No problem there.
But, if I have an app that uses a Parse Database for itself, I have not been able to figure out how to let it work on it's own parse server configuration for it's own stuff, but write out error logs to this other Parse server instance.
Yes... I could go through the trouble of writing out something via the REST api just for writing out logs,but I am I trying to avoid that and stick with native parse APIs for the particular platform I am on because of the benefits that the APIs give over REST (like save eventually for the none .NET stuff).
EDIT
Some clarification was requested so here I go...
On the app side of things (c# for this example but the same holds true for iOS etc)… I do the usual initialization of the Parse client as such …
ParseClient.Initialize(new ParseClient.Configuration
{
ApplicationId = "MyAppID",
WindowsKey = "MyDotNetKey",
Server = "www.myparseserver.com/app1"
});
So for all calls to save a parse object go through that parse client connection
But what I need to do would be something like this ….
//Main App cloud database
ParseClient1.Initialize(new ParseClient.Configuration
{
ApplicationId = "MyAppID",
WindowsKey = "MyDotNetKey",
Server = "www.myparseserver.com/app1"
});
ParseClient2.Initialize(new ParseClient.Configuration
{
ApplicationId = "MyAppID",
WindowsKey = "MyDotNetKey",
Server = "www.myparseserver.com/errorcollection"
});
try{
ParseConfig config = null;
config = await ParseConfig.GetAsync().ParseClient1;
} catch (Exception ex){
ParseObject MyError = new ParseObject("Error_Log");
MyError["Application"] = "My First App-App2";
MyError["Error"] = ex.message;
await MyError.Save().ParseClient2;
}
Yes - this is all fake code... my point is I want to be able to have multiple ParseClient instances in one app.
Now... I can simply write a routine that writes out errors that resets the ParseClient.Initialization to the error parse server instance and then redo it back to the original (primary app data) instance when it's done... but that is just asking for trouble in a multi threaded environment and will cause conflicts if some other thread in the app goes to write out parse data right at the moment the error method resets the init.
If ParseClient were IDisposable I could probably do that using :
ParseClient ParseErrorServer = new ParseClient();
ParseErrorServer.ApplicationId = "hmmm";
ParseErrorServer.WindwosKey= "hmmm";
ParseErrorServer.Server= "www.hmmm.com/errorcollection";
using ParseErrorServer {
//Do The Work
}
Is that clear as mud yet? ;P
Without alteration I believe none of the Parse SDKs have the ability to initialise multiple instances.
In the iOS SDK for example, is possible to make a new instance (say with a different server url) upon restarting the app but you cannot have multiple. There has also been discussion on the iOS SDK about being able to change the configuration without restart but no one has implemented this yet.
We would happily review a PR for this, however it would require a major and complex overhaul as you would have to manage cache, users etc across multiple instances.
I have been able to get the Microsoft Translator API to work with creating a console project. I could only find examples with using console projects.
When trying to get the Translator API working within a controller I am not having any luck. I am using the same code.
Do I need to add some other type of reference to get the Translator to work with in MVC?
public async Task<string> GetAuthenticationToken(string key)
{
string endpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxxxxxxxxxxxxxx501b7b1ce");
var response = await client.PostAsync(endpoint, null);
var token = await response.Content.ReadAsStringAsync();
return token;
}
}
Error Message
Is there any particular reason you have to create the console application first and then run it as such?
Instead of running the executable from your MVC project, I would recommend calling the TranslatorAsync() function instead.
My guess would be that the process.Start() and process.Close() calls are killing the process before it has a chance to do anything. However, without more specifics on how the function is failing, it's hard to give a better answer.
I had to change
TranslateAsync(productTest, getUserName).Wait;
to
await TranslateAsync(productTest, getUserName);
It’s working now.
Lately the Nemiro.OAuth api is throwing null reference exceptions for some reason. After getting the lates versoin Nemiro.OAuth v1.12.0 and Nemiro.OAuth.loginForms v1.6.0 it started to behave like this, haven't changed my implemented logic in any way.
My file structure in dropbox:
https://www.dropbox.com/home/Apps/MyApplication/MyFolder/SubFolder/Some%20folder1/MyFiles
Old and new uri:
/MyFolder/SubFolder/Some folder1/MyFiles/somefile.png
When I call OAuthUtility.Post it shows following error message:
I'm using following logic to handle the request:
string oldUri = oldPath.ToUri();
string newUri = newPath.ToUri();
var paramCollection = new HttpParameterCollection
{
{"access_token", ACCESS_TOKEN},
{"from_path", oldUri },
{"to_path", newUri },
{"root","auto"}
};
OAuthUtility.Post
(
"https://api.dropboxapi.com/1/fileops/move",
paramCollection
);
I already checked that file exists in dropbox, my access token is valid, also, as you can see the path is correct.. Also it fails for other operations like
https://content.dropboxapi.com/1/files_put/auto{0}/{1}
What could cause this?
Could it be something with new Dropbox api V2?
Update
It actually works, but throws null reference exception at the same time..
That is pretty annoying, that means I need to wrap each operation in try catch block. Also, when I created new console application and executed the same code, it worked without any exceptions. Which means, something is wrong in my project.
0. Dropbox API v1 has been deprecated:
https://blogs.dropbox.com/developers/2016/06/api-v1-deprecated/
...In order to provide our developers with the most up-to-date features and support a single, consistent platform, we’ll be turning off API v1 a year from now, on 6/28/2017.
It remains approximately two months :-) I recommend switching to the new version of the API.
1. Do you pass the URI? But why are you doing this? Just use a string path relative to the root directory of the application. I tried to use a URI, this code does not work for me, the server returns an error 404.
I used relative paths and checked the code and do not see any problems.
If possible, show the full code in which the problem occurs.
Or you can send the project to me by email: aleksey.nemirogmail.com
I have a Console Application project written in C# which I've added Application Insights to with the following NuGet packages.
Microsoft.ApplicationInsights
Microsoft.ApplicationInsights.Agent.Intercept
Microsoft.ApplicationInsights.DependencyCollector
Microsoft.ApplicationInsights.NLogTarget
Microsoft.ApplicationInsights.PerfCounterCollector
Microsoft.ApplicationInsights.Web
Microsoft.ApplicationInsights.WindowsServer
Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel
I've configured my InstrumentationKey in the config file and I'm firing up a TelemetryClient on startup using the with the following code:
var telemetryClient = new TelemetryClient();
telemetryClient.Context.User.Id = Environment.UserName;
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
Everything is working well except AI is not capturing any requests that get sent to Mongo, I can see requests going off to SQL server in the 'Application map' but no sign of any other external requests. Is there any way that I can see telemetry of requests made to Mongo?
EDIT - Thanks to Peter Bons I ended up with pretty much the following which works like a charm and allows me to distinguish between success and failure:
var telemetryClient = new TelemetryClient();
var connectionString = connectionStringSettings.ConnectionString;
var mongoUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
mongoClientSettings.ClusterConfigurator = clusterConfigurator =>
{
clusterConfigurator.Subscribe<CommandSucceededEvent>(e =>
{
telemetryClient.TrackDependency("MongoDB", e.CommandName, DateTime.Now.Subtract(e.Duration), e.Duration, true);
});
clusterConfigurator.Subscribe<CommandFailedEvent>(e =>
{
telemetryClient.TrackDependency("MongoDB", $"{e.CommandName} - {e.ToString()}", DateTime.Now.Subtract(e.Duration), e.Duration, false);
});
};
var mongoClient = new MongoClient(mongoClientSettings);
I am not familiar with MongoDB but as far as I can tell there is no default support for it when it comes to Application Insights. But that does not mean you cannot do this, it will just involve some more code.
Again, I am not familiar with MongoDB but according to http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/ there is built-in support for logging the generated queries. Now, we only need to hook this up to Application Insights.
Since you already know how to use the TelemetryClient we can use the custom tracking methods provided by that class. See https://learn.microsoft.com/nl-nl/azure/application-insights/app-insights-api-custom-events-metrics for the available custom tracking methods.
All you need to do is to insert some code like this:
telemetryClient.TrackDependency(
"MongoDB", // The name of the dependency
query, // Text of the query
DateTime.Now, // Time that query is executed
TimeSpan.FromSeconds(0), // Time taken to execute query
true); // Indicates success
The class telemetryClient is thread-safe so you can reuse it.
Now, according to the referenced blogpost you should be able to do something like this:
var client = new MongoClient(new MongoClientSettings()
{
Server = new MongoServerAddress("localhost"),
ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(e =>
{
telemetryClient.TrackDependency(
"MongoDB", // The name of the dependency
e.Command.ToJson() // Text of the query
DateTime.Now, // Time that query is executed
TimeSpan.FromSeconds(0), // Time taken to execute query
true); // Indicates success
});
}
});
Again, I am not familiar with MongoDB but I hope this is a starting point for your imagination on how to adapt it to your needs using your knowledge of MongoDB.
EDIT:
If there is also a CommandCompletedEvent or similar event as opposed to the CommandStartedEvent event you should probably track the dependency there because you should then be able to calculate (or simpel read) the time spent and maybe get the actual value for the success indicator.