#r "Microsoft.WindowsAzure.Storage"
using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
public static async Task Run(UnityGameObject gameObj, CloudTable table, IAsyncCollector<Notification> notification, TraceWriter log)
{
//RowKey of the table object to be changed
string rowKey = gameObj.RowKey;
//Retrieve the table object by its RowKey
TableOperation operation = TableOperation.Retrieve<UnityGameObject>("UnityPartitionKey", rowKey);
TableResult result = table.Execute(operation);
//Create a UnityGameObject so to set its parameters
UnityGameObject existingGameObj = (UnityGameObject)result.Result;
existingGameObj.RowKey = rowKey;
existingGameObj.X = gameObj.X;
existingGameObj.Y = gameObj.Y;
existingGameObj.Z = gameObj.Z;
//Replace the table appropriate table Entity with the value of the UnityGameObject
operation = TableOperation.Replace(existingGameObj);
table.Execute(operation);
log.Verbose($"Updated object position");
//Serialize the UnityGameObject
string wnsNotificationPayload = JsonConvert.SerializeObject(existingGameObj);
log.Info($"{wnsNotificationPayload}");
var headers = new Dictionary<string, string>();
headers["X-WNS-Type"] = @"wns/raw";
//Send the raw notification to subscribed devices
await notification.AddAsync(new WindowsNotification(wnsNotificationPayload, headers));
log.Verbose($"Sent notification");
}
// This UnityGameObject represent a Table Entity
public class UnityGameObject : TableEntity
{
public string Type { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public string RowKey { get; set; }
}
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using UnityEngine;
クラス内に次の変数を挿入します。
/// <summary>
/// allows this class to behave like a singleton
/// </summary>
public static TableToScene instance;
/// <summary>
/// Insert here you Azure Storage name
/// </summary>
private string accountName = " -- Insert your Azure Storage name -- ";
/// <summary>
/// Insert here you Azure Storage key
/// </summary>
private string accountKey = " -- Insert your Azure Storage key -- ";
/// <summary>
/// Triggers before initialization
/// </summary>
void Awake()
{
// static instance of this class
instance = this;
}
/// <summary>
/// Use this for initialization
/// </summary>
void Start()
{
// Call method to populate the scene with new objects as
// pecified in the Azure Table
PopulateSceneFromTableAsync();
}
/// <summary>
/// Populate the scene with new objects as specified in the Azure Table
/// </summary>
private async void PopulateSceneFromTableAsync()
{
// Obtain credentials for the Azure Storage
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
// Storage account
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
// Storage client
CloudTableClient client = account.CreateCloudTableClient();
// Table reference
CloudTable table = client.GetTableReference("SceneObjectsTable");
TableContinuationToken token = null;
// Query the table for every existing Entity
do
{
// Queries the whole table by breaking it into segments
// (would happen only if the table had huge number of Entities)
TableQuerySegment<AzureTableEntity> queryResult = await table.ExecuteQuerySegmentedAsync(new TableQuery<AzureTableEntity>(), token);
foreach (AzureTableEntity entity in queryResult.Results)
{
GameObject newSceneGameObject = null;
Color newColor;
// check for the Entity Type and spawn in the scene the appropriate Primitive
switch (entity.Type)
{
case "Cube":
// Create a Cube in the scene
newSceneGameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
newColor = Color.blue;
break;
case "Sphere":
// Create a Sphere in the scene
newSceneGameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
newColor = Color.red;
break;
case "Cylinder":
// Create a Cylinder in the scene
newSceneGameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
newColor = Color.yellow;
break;
default:
newColor = Color.white;
break;
}
newSceneGameObject.name = entity.RowKey;
newSceneGameObject.GetComponent<MeshRenderer>().material = new Material(Shader.Find("Diffuse"))
{
color = newColor
};
//check for the Entity X,Y,Z and move the Primitive at those coordinates
newSceneGameObject.transform.position = new Vector3((float)entity.X, (float)entity.Y, (float)entity.Z);
}
// if the token is null, it means there are no more segments left to query
token = queryResult.ContinuationToken;
}
while (token != null);
}
/// <summary>
/// This objects is used to serialize and deserialize the Azure Table Entity
/// </summary>
[System.Serializable]
public class AzureTableEntity : TableEntity
{
public AzureTableEntity(string partitionKey, string rowKey)
: base(partitionKey, rowKey) { }
public AzureTableEntity() { }
public string Type { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
using Newtonsoft.Json;
using System.Collections;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
次の変数を挿入します。
/// <summary>
/// Allows this class to behave like a singleton
/// </summary>
public static CloudScene instance;
/// <summary>
/// Insert here you Azure Function Url
/// </summary>
private string azureFunctionEndpoint = "--Insert here you Azure Function Endpoint--";
/// <summary>
/// Flag for object being moved
/// </summary>
private bool gameObjHasMoved;
/// <summary>
/// Transform of the object being dragged by the mouse
/// </summary>
private Transform gameObjHeld;
/// <summary>
/// Class hosted in the TableToScene script
/// </summary>
private AzureTableEntity azureTableEntity;
/// <summary>
/// Triggers before initialization
/// </summary>
void Awake()
{
// static instance of this class
instance = this;
}
/// <summary>
/// Use this for initialization
/// </summary>
void Start()
{
// initialise an AzureTableEntity
azureTableEntity = new AzureTableEntity();
}
/// <summary>
/// Update is called once per frame
/// </summary>
void Update()
{
//Enable Drag if button is held down
if (Input.GetMouseButton(0))
{
// Get the mouse position
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 objPos = Camera.main.ScreenToWorldPoint(mousePosition);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Raycast from the current mouse position to the object overlapped by the mouse
if (Physics.Raycast(ray, out hit))
{
// update the position of the object "hit" by the mouse
hit.transform.position = objPos;
gameObjHasMoved = true;
gameObjHeld = hit.transform;
}
}
// check if the left button mouse is released while holding an object
if (Input.GetMouseButtonUp(0) && gameObjHasMoved)
{
gameObjHasMoved = false;
// Call the Azure Function that will update the appropriate Entity in the Azure Table
// and send a Notification to all subscribed Apps
Debug.Log("Calling Azure Function");
StartCoroutine(UpdateCloudScene(gameObjHeld.name, gameObjHeld.position.x, gameObjHeld.position.y, gameObjHeld.position.z));
}
}
次に、以下のように UpdateCloudScene() メソッドを追加します。
private IEnumerator UpdateCloudScene(string objName, double xPos, double yPos, double zPos)
{
WWWForm form = new WWWForm();
// set the properties of the AzureTableEntity
azureTableEntity.RowKey = objName;
azureTableEntity.X = xPos;
azureTableEntity.Y = yPos;
azureTableEntity.Z = zPos;
// Serialize the AzureTableEntity object to be sent to Azure
string jsonObject = JsonConvert.SerializeObject(azureTableEntity);
using (UnityWebRequest www = UnityWebRequest.Post(azureFunctionEndpoint, jsonObject))
{
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(jsonObject);
www.uploadHandler = new UploadHandlerRaw(jsonToSend);
www.uploadHandler.contentType = "application/json";
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
string response = www.responseCode.ToString();
}
}
//using Microsoft.WindowsAzure.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections;
using UnityEngine;
#if UNITY_WSA_10_0 && !UNITY_EDITOR
using Windows.Networking.PushNotifications;
#endif
次の変数を挿入します。
/// <summary>
/// allows this class to behave like a singleton
/// </summary>
public static NotificationReceiver instance;
/// <summary>
/// Value set by the notification, new object position
/// </summary>
Vector3 newObjPosition;
/// <summary>
/// Value set by the notification, object name
/// </summary>
string gameObjectName;
/// <summary>
/// Value set by the notification, new object position
/// </summary>
bool notifReceived;
/// <summary>
/// Insert here your Notification Hub Service name
/// </summary>
private string hubName = " -- Insert the name of your service -- ";
/// <summary>
/// Insert here your Notification Hub Service "Listen endpoint"
/// </summary>
private string hubListenEndpoint = "-Insert your Notification Hub Service Listen endpoint-";
/// <summary>
/// Triggers before initialization
/// </summary>
void Awake()
{
// static instance of this class
instance = this;
}
/// <summary>
/// Use this for initialization
/// </summary>
void Start()
{
// Register the App at launch
InitNotificationsAsync();
// Begin listening for notifications
StartCoroutine(WaitForNotification());
}
/// <summary>
/// This notification listener is necessary to avoid clashes
/// between the notification hub and the main thread
/// </summary>
private IEnumerator WaitForNotification()
{
while (true)
{
// Checks for notifications each second
yield return new WaitForSeconds(1f);
if (notifReceived)
{
// If a notification is arrived, moved the appropriate object to the new position
GameObject.Find(gameObjectName).transform.position = newObjPosition;
// Reset the flag
notifReceived = false;
}
}
}
///// <summary>
///// Handler called when a Push Notification is received
///// </summary>
//private void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
//{
// Debug.Log("New Push Notification Received");
//
// if (args.NotificationType == PushNotificationType.Raw)
// {
// // Raw content of the Notification
// string jsonContent = args.RawNotification.Content;
//
// // Deserialise the Raw content into an AzureTableEntity object
// AzureTableEntity ate = JsonConvert.DeserializeObject<AzureTableEntity>(jsonContent);
//
// // The name of the Game Object to be moved
// gameObjectName = ate.RowKey;
//
// // The position where the Game Object has to be moved
// newObjPosition = new Vector3((float)ate.X, (float)ate.Y, (float)ate.Z);
//
// // Flag thats a notification has been received
// notifReceived = true;
// }
//}
/// <summary>
/// Handler called when a Push Notification is received
/// </summary>
private void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
Debug.Log("New Push Notification Received");
if (args.NotificationType == PushNotificationType.Raw)
{
// Raw content of the Notification
string jsonContent = args.RawNotification.Content;
// Deserialize the Raw content into an AzureTableEntity object
AzureTableEntity ate = JsonConvert.DeserializeObject<AzureTableEntity>(jsonContent);
// The name of the Game Object to be moved
gameObjectName = ate.RowKey;
// The position where the Game Object has to be moved
newObjPosition = new Vector3((float)ate.X, (float)ate.Y, (float)ate.Z);
// Flag thats a notification has been received
notifReceived = true;
}
}