How can I access to read/write/modify/delete Playfab data with Azure functions?
Below Steps will help you in accessing the azure functions with Playfab
Create Azure Function in VS Code
Deploy the azure function to portal and register your function with cloud script
Below is the sample example code for calling cloud script using azure functions from your playfab.
//This snippet assumes that your game client is already logged into PlayFab.
using PlayFab;
using PlayFab.CloudScriptModels;
private void CallCSharpExecuteFunction()
{
PlayFabCloudScriptAPI.ExecuteFunction(new ExecuteFunctionRequest()
{
Entity = new PlayFab.CloudScriptModels.EntityKey()
{
Id = PlayFabSettings.staticPlayer.EntityId, //Get this from when you logged in,
Type = PlayFabSettings.staticPlayer.EntityType, //Get this from when you logged in
},
FunctionName = "HelloWorld", //This should be the name of your Azure Function that you created.
FunctionParameter = new Dictionary<string, object>() { { "inputValue", "Test" } }, //This is the data that you would want to pass into your function.
GeneratePlayStreamEvent = false //Set this to true if you would like this call to show up in PlayStream
}, (ExecuteFunctionResult result) =>
{
if (result.FunctionResultTooLarge ?? false)
{
Debug.Log("This can happen if you exceed the limit that can be returned from an Azure Function, See PlayFab Limits Page for details.");
return;
}
Debug.Log($"The {result.FunctionName} function took {result.ExecutionTimeMilliseconds} to complete");
Debug.Log($"Result: {result.FunctionResult.ToString()}");
}, (PlayFabError error) =>
{
Debug.Log($"Opps Something went wrong: {error.GenerateErrorReport()}");
});
}
PlayFab CloudScript Context, Variables and Server SDKs
You will need to install the PlayFab SDK via Package Manager. To do this open Terminal or CMD Console in Visual Studio Code and type: dotnet add package PlayFabAllSDK
We have created some helpers that will ship with the cSharpSDK.
You need to edit your .csproj file and include <DefineConstants>NETCOREAPP2_0</DefineConstants> in your default PropertyGroup or NETCOREAPP3_1 if you are using the latest.
Execution of a script can occur through several methods (APIs, Scheduled Tasks, PlayStream Event, Segment Entering and Exit method). The context of the execution is important to implement your CloudScript. See the Using CloudScript context models tutorial for details on how to use the context of the script.
For further information check Cloud Script Using Azure Functions and Playfab Cloud Script
Related
I keep getting an error in application insight when trying to run my Azure function, it works locally on my computer but does not work in Azure. Here is the error message:
System.InvalidOperationException at Microsoft.Azure.WebJobs.Extensions.CosmosDB.CosmosDBTriggerAttributeBindingProvider.ResolveConnectionString
I have added CosmosDbTrigger as a connection string in the settings configurations, so I do not understand what's wrong. The function is triggered when a change is made in the cosmos db so if I change something in the db, and am running the function localy on my pc it works, It's only in the azure portal it keeps failing. The triggers are also working, so I think it's only the function that's the problem.
As there are many other discussions happening with similar issue from this link and check this link and try re checking your configuration file.
internal string ResolveConnectionString(string unresolvedConnectionString, string propertyName)
{
// First, resolve the string.
if (!string.IsNullOrEmpty(unresolvedConnectionString))
{
string resolvedString = _configuration.GetConnectionStringOrSetting(unresolvedConnectionString);
if (string.IsNullOrEmpty(resolvedString))
{
throw new InvalidOperationException($"Unable to resolve app setting for property '{nameof(CosmosDBTriggerAttribute)}.{propertyName}'. Make sure the app setting exists and has a valid value.");
}
return resolvedString;
}
// If that didn't exist, fall back to options.
return _options.ConnectionString;
}
Also, check your _options.ConnectionString value and set that dynamically.
builder.Services.PostConfigure<CosmosDBOptions>(options =>
{
options.ConnectionString = "dynamically set the connection string value here";
});
I am new to Azure App Service.
I've created a view in Azure database to get data across several tables. Now I want to use the data from this view in my Cordova App using the Azure Mobile Service (MobileService.GetTable...). I found several articles in the web that describe how to do that in Classic Azure Portal. But I need a solution for the NEW Azure App Service with Node.js Backend.
What is the syntax to return data from a view as an Azure table?
var table = module.exports = require('azure-mobile-apps').table();
table.read(function (context) {
// *** Need code to return data from sql view ***
//return context.execute();
});
And it would be great to use a parameter to filter data in the view before returning.
Thanks,
Uwe
You are pretty much right there. You need to just create a table controller to access the view. Ensure you have the system columns defined (version, updatedAt, createdAt, deleted and id). Also, ensure the right thing happens when you update the view (e.g. with an INSERT, UPDATE, DELETE) as that will tell you what needs to be done with the controller (for example, if you can't insert/update/delete, then make it read-only).
Reference blog post for you: https://shellmonger.com/2016/04/15/30-days-of-zumo-v2-azure-mobile-apps-day-8-table-controller-basics/
Things can be so easy sometimes ;-)
All I need to do is to write the following lines to my table controller:
var table = require('azure-mobile-apps').table();
table.databaseTableName = 'ViewName';
module.exports = table;
Thanks for your help!
Had a similar issue but fixed it now, am using a .Net backend thou.
1. Log into azure portal and select the database you want to create the view in Then select the query Editor in the left pane.
2. Use the sql to create the query.
3.Create a table in the asp.net backend that matches your fields in your view.
4.Go to your asp.net backend and create a custom Api and write the following codes:
public class HelloCustomController : ApiController
{
MobileServiceContext context;
public HelloCustomController()
{
context = new MobileServiceContext();
}
[HttpGet]
public async Task<List<vwUser>> Get()
{
try
{
var users = context.Database.SqlQuery<vwUser>("Select * from
dbo.vwUser);
return await users.ToListAsync();
}
catch(Exception ex)
{
return new List<vwUser>()
{
new vwUser
{
UserName=ex.Message
}
};
}
}
4.You edit my codes to select from your view.
5. Create a similar class in your mobile app that matches what u created in your backend.
5. You can then access your view by calling it in your mobile app with the following codes:
var users= await client.InvokeApiAsync<vwUser>("HelloCustom",HttpMethod.Get,null);
Thanks Guys. This is my fisrt answer to this beautiful community that carried me from day 1 of programming till now that am a bit conversant.
I'm trying to work with Azure Webjobs, I understand the way its works but I don't understand why I need to use two connection strings, one is for the queue for holding the messages but
why there is another one called "AzureWebJobsDashboard" ?
What its purpose?
And where I get this connection string from ?
At the moment I have one Web App and one Webjob at the same solution, I'm experiment only locally ( without publishing anything ), the one thing I got up in the cloud is the Storage account that holds the queue.
I even try to put the same connection string in both places ( AzureWebJobsDashboard,AzureWebJobsStorage) but its throw exception :
"Cannot bind parameter 'log' when using this trigger."
Thank you.
There are two connection strings because the WebJobs SDK writes some logs in the storage account. It gives you the possibility of having one storage account just for data (AzureWebJobsStorage) and the another one for logs (AzureWebJobsDashboard). They can be the same. Also, you need two of them because you can have multiple job hosts using different data accounts but sending logs to the same dashboard.
The error you are getting is not related to the connection strings but to one of the functions in your code. One of them has a log parameter that is not of the right type. Can you share the code?
Okay, anyone coming here looking for an actual answer of "where do I get the ConnectionString from"... here you go.
On the new Azure portal, you should have a Storage Account resource; mine starts with "portalvhds" followed by a bunch of alphanumerics. Click that so see a resource Dashboard on the right, followed immediately by a Settings window. Look for the Keys submenu under General -- click that. The whole connection string is there (actually there are two, Primary and Secondary; I don't currently understand the difference, but let's go with Primary, shall we?).
Copy and paste that in your App.config file on the connectionString attribute of the AzureWebJobsDashboard and AzureWebJobsStorage items. This presumes for your environment you only have one Storage Account, and so you want that same storage to be used for data and logs.
I tried this, and at least the WebJob ran without throwing an error.
#RayHAz - Expanding upon your above answer (thanks)...
I tried this https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started
but in .Net Core 2.1, was getting exceptions about how it couldn't find the connection string.
Long story short, I ended up with the following, which worked for me:
appsettings.json, in a .Net Core 2.1 Console app:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "---your Azure storage connection string here---",
"AzureWebJobsDashboard":"---the same connectionstring---"
}
}
... and my Program.cs file...
using System;
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace YourWebJobConsoleAppProjectNamespaceHere
{
public class Program
{
public static IConfiguration Configuration;
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", true);
Configuration = builder.Build();
var azureWebJobsStorageConnectionString = Configuration.GetConnectionString("AzureWebJobsStorage");
var azureWebJobsDashboardConnectionString = Configuration.GetConnectionString("AzureWebJobsDashboard");
var config = new JobHostConfiguration
{
DashboardConnectionString = azureWebJobsDashboardConnectionString,
StorageConnectionString = azureWebJobsStorageConnectionString
};
var loggerFactory = new LoggerFactory();
config.LoggerFactory = loggerFactory.AddConsole();
var host = new JobHost(config);
host.RunAndBlock();
}
}
}
I have written a custom Windows Service that writes data to a custom Event Log (in the Windows Event Viewer).
For dev'ing the biz logic that the service uses, I created a Windows Form which simulates the Start/Stop methods of the Windows Service.
When executing the biz logic via the Windows Forms, info is successfully written to my custom Event Log. However, when I run the same biz logic from the custom Windows Service, information is failing to be written to the Event Log.
To be clear, I have written a library (.dll) that does all the work that I want my custom service to do - including the create/write to the custom Event Log. My Form application references this library as does my Windows Service.
Thinking the problem is a security issue, I manually set the custom Windows Service to "Log on" as "Administrator", but the service still did not write to the Event Log.
I'm stuck on how to even troubleshoot this problem since I can't debug and step into the code when I run the service (if there is a way to debug a service, please share).
Do you have any ideas as to what could be causing my service to fail to write to the event log?
I use it like this. There can be some typos. Writed it on my phone browser...
public class MyClass
{
private EventLog eventLog = new EventLog();
public void MyClass()
{
if (!System.Diagnostics.EventLog.SourceExists("MyLogSource"))
System.Diagnostics.EventLog.CreateEventSource("MyLogSource", "MyLogSource_Log");
eventLog.Source = "MyLogSource";
eventLog.Log = "MyLogSource_Log";
}
private void MyLogWrite()
{
eventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
To debug a running service you need to attach to the process. See here for the steps.
You could also add parameter checking to the Main entry point and have a combination service and console app which would start based on some flag. See this SO post for a good example but here's a snippet:
using System;
using System.ServiceProcess;
namespace WindowsService1
{
static class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("Starting service...");
ServiceBase.Run(new ServiceBase[] { new Service1() });
}
else
{
Console.WriteLine("Hi, not from service: " + args[0]);
}
}
}
}
The above starts the app in console mode if there any parameters exist and in service mode if there are no parameters. Of course it can be much fancier but that's the gist of the switch.
I discovered why my service wasn't writing to the Event Log.
The problem had nothing to do with any part of the code/security/etc that was attempting to write to the EL. The problem was that my service wasn't successfully collecting the information that is written to the EL - therefore, the service wasn't even attempting to write the log.
Now that I fixed the code that collects the data, data is successfully writing to the event log.
I'm open to having this question closed since the question was amiss to the real problem.
When checking in a document I execute a web service within the ItemCheckingInEvent. In Dev, no problems. I deployed the app out and it turns out I don't have enough privileges to read a configuration file. My code reads a config file to create the WCF proxy. The real issue is how can I get a return back from my function if I use the SPSecurity.RunWithElevatedPrivileges function?
For example:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// exec service call
});
// need data from service call here
Just declare your working object before the elevated delegate, and assign it inside:
object myServiceData = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
myServiceData = DoServiceStuff();
});
//do things with myServiceData