/// <summary>Snippet for UpdateExclusionAsync</summary> public async Task UpdateExclusionAsync() { // Snippet: UpdateExclusionAsync(ExclusionNameOneof,LogExclusion,FieldMask,CallSettings) // Additional: UpdateExclusionAsync(ExclusionNameOneof,LogExclusion,FieldMask,CancellationToken) // Create client ConfigServiceV2Client configServiceV2Client = await ConfigServiceV2Client.CreateAsync(); // Initialize request argument(s) ExclusionNameOneof name = ExclusionNameOneof.From(new ExclusionName("[PROJECT]", "[EXCLUSION]")); LogExclusion exclusion = new LogExclusion(); FieldMask updateMask = new FieldMask(); // Make the request LogExclusion response = await configServiceV2Client.UpdateExclusionAsync(name, exclusion, updateMask); // End snippet }
/// <summary>Snippet for UpdateConnectionAsync</summary> public async Task UpdateConnectionResourceNamesAsync() { // Snippet: UpdateConnectionAsync(ConnectionName, Connection, FieldMask, CallSettings) // Additional: UpdateConnectionAsync(ConnectionName, Connection, FieldMask, CancellationToken) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) ConnectionName name = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"); Connection connection = new Connection(); FieldMask updateMask = new FieldMask(); // Make the request Connection response = await connectionServiceClient.UpdateConnectionAsync(name, connection, updateMask); // End snippet }
/// <summary>Snippet for UpdateConnectionAsync</summary> public async Task UpdateConnectionAsync() { // Snippet: UpdateConnectionAsync(string, Connection, FieldMask, CallSettings) // Additional: UpdateConnectionAsync(string, Connection, FieldMask, CancellationToken) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/connections/[CONNECTION]"; Connection connection = new Connection(); FieldMask updateMask = new FieldMask(); // Make the request Connection response = await connectionServiceClient.UpdateConnectionAsync(name, connection, updateMask); // End snippet }
/// <summary>Snippet for UpdateCatalogItemAsync</summary> public async Task UpdateCatalogItemAsync() { // Snippet: UpdateCatalogItemAsync(string, CatalogItem, FieldMask, CallSettings) // Additional: UpdateCatalogItemAsync(string, CatalogItem, FieldMask, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/catalogItems/[CATALOG_ITEM_PATH]"; CatalogItem catalogItem = new CatalogItem(); FieldMask updateMask = new FieldMask(); // Make the request CatalogItem response = await catalogServiceClient.UpdateCatalogItemAsync(name, catalogItem, updateMask); // End snippet }
/// <summary>Snippet for UpdateCatalogItemAsync</summary> public async Task UpdateCatalogItemResourceNamesAsync() { // Snippet: UpdateCatalogItemAsync(CatalogItemPathName, CatalogItem, FieldMask, CallSettings) // Additional: UpdateCatalogItemAsync(CatalogItemPathName, CatalogItem, FieldMask, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) CatalogItemPathName name = CatalogItemPathName.FromProjectLocationCatalogCatalogItemPath("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"); CatalogItem catalogItem = new CatalogItem(); FieldMask updateMask = new FieldMask(); // Make the request CatalogItem response = await catalogServiceClient.UpdateCatalogItemAsync(name, catalogItem, updateMask); // End snippet }
/// <summary>Snippet for UpdatePhoneNumberInstanceAsync</summary> public async Task UpdatePhoneNumberInstanceResourceNamesAsync() { // Snippet: UpdatePhoneNumberInstanceAsync(PhoneNumberInstanceName, PhoneNumberInstance, FieldMask, CallSettings) // Additional: UpdatePhoneNumberInstanceAsync(PhoneNumberInstanceName, PhoneNumberInstance, FieldMask, CancellationToken) // Create client PhoneNumberInstancesClient phoneNumberInstancesClient = await PhoneNumberInstancesClient.CreateAsync(); // Initialize request argument(s) PhoneNumberInstanceName name = PhoneNumberInstanceName.FromProjectPhoneNumberInstance("[PROJECT]", "[PHONE_NUMBER_INSTANCE]"); PhoneNumberInstance phoneNumberInstance = new PhoneNumberInstance(); FieldMask updateMask = new FieldMask(); // Make the request PhoneNumberInstance response = await phoneNumberInstancesClient.UpdatePhoneNumberInstanceAsync(name, phoneNumberInstance, updateMask); // End snippet }
/// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKey2Async_ResourceNames() { // Snippet: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, FieldMask, CallSettings) // Additional: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, FieldMask, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) SshPublicKeyName name = new SshPublicKeyName("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey, updateMask); // End snippet }
/// <summary>Snippet for UpdatePhoneNumberInstanceAsync</summary> public async Task UpdatePhoneNumberInstanceAsync() { // Snippet: UpdatePhoneNumberInstanceAsync(string, PhoneNumberInstance, FieldMask, CallSettings) // Additional: UpdatePhoneNumberInstanceAsync(string, PhoneNumberInstance, FieldMask, CancellationToken) // Create client PhoneNumberInstancesClient phoneNumberInstancesClient = await PhoneNumberInstancesClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/phoneNumberInstances/[PHONE_NUMBER_INSTANCE]"; PhoneNumberInstance phoneNumberInstance = new PhoneNumberInstance(); FieldMask updateMask = new FieldMask(); // Make the request PhoneNumberInstance response = await phoneNumberInstancesClient.UpdatePhoneNumberInstanceAsync(name, phoneNumberInstance, updateMask); // End snippet }
/// <summary>Snippet for UpdateInstanceAsync</summary> public async Task UpdateInstanceAsync() { // Snippet: UpdateInstanceAsync(FieldMask,Instance,CallSettings) // Additional: UpdateInstanceAsync(FieldMask,Instance,CancellationToken) // Create client CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync(); // Initialize request argument(s) FieldMask updateMask = new FieldMask { Paths = { "display_name", "memory_size_gb", }, }; Instance instance = new Instance { DisplayName = "UpdatedDisplayName", MemorySizeGb = 4, }; // Make the request Operation <Instance, OperationMetadata> response = await cloudRedisClient.UpdateInstanceAsync(updateMask, instance); // Poll until the returned long-running operation is complete Operation <Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Instance result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation <Instance, OperationMetadata> retrievedResponse = await cloudRedisClient.PollOnceUpdateInstanceAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Instance retrievedResult = retrievedResponse.Result; } // End snippet }
public NotificationChannel EnableNotificationChannel( string channelName = "projects/your-project-id/notificationChannels/123") { var client = NotificationChannelServiceClient.Create(); NotificationChannel channel = new NotificationChannel(); channel.Enabled = true; channel.Name = channelName; var fieldMask = new FieldMask { Paths = { "enabled" } }; channel = client.UpdateNotificationChannel( updateMask: fieldMask, notificationChannel: channel); Console.WriteLine("Enabled {0}.", channel.Name); return(channel); }
public override Task <CoffeeOrder> UpdateOrder(UpdateOrderRequest request, ServerCallContext context) { this._logger.LogInformation($"Updating order {request.Order.Id}..."); // setup what we're allowed to update. var updateMask = FieldMask.FromFieldNumbers <CoffeeOrder>(CoffeeOrder.SizeFieldNumber); var mask = request.OrderMask.Intersection(updateMask); // mergce mask.Merge(request.Order, _orders[request.Order.Id]); _subscribers.ForEach(async s => { await s.WriteAsync(_orders[request.Order.Id]); }); return(Task.FromResult(_orders[request.Order.Id])); }
// [END kms_disable_cryptokey_version] // [START kms_enable_cryptokey_version] public static void EnableCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // The CryptoKeyVersion to enable. CryptoKeyVersionName versionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId); CryptoKeyVersion version = client.GetCryptoKeyVersion(versionName); version.State = CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled; FieldMask fieldMask = new FieldMask(); fieldMask.Paths.Add("state"); CryptoKeyVersion patchResult = client.UpdateCryptoKeyVersion(version, fieldMask); Console.Write($"Enabled Crypto Key Version: {patchResult.Name}"); }
public void ChangeStageAtomically( string projectId = "YOUR-PROJECT-ID", string incidentId = "an.opaque.random.id") { // Create client IncidentServiceClient incidentServiceClient = IncidentServiceClient.Create(); for (int retry = 0; true; ++retry) { try { // Observe the current state of the incident. Incident incident = incidentServiceClient.GetIncident( new IncidentName(projectId, incidentId).ToString()); Incident incidentChange = new Incident() { // TODO: Remove the name hack. Name = incident.Name.Replace("/-/", $"/{projectId}/"), // Use the ETag to prevent race conditions. Only update the // incident if it hasn't changed since we observed it. Etag = incident.Etag, Stage = Stage.Detected }; // Tell the API which fields to update. FieldMask mask = new FieldMask() { Paths = { "stage" } }; // Call the API to update the incident. incident = incidentServiceClient.UpdateIncident( incidentChange, mask); Console.WriteLine("Changed stage of {0}.", incident.Name); break; } catch (Grpc.Core.RpcException e) when(retry < 3 && e.StatusCode == Grpc.Core.StatusCode.Aborted) { // Somebody else must have updated the incident at the same // time! Try again. } } }
// [END monitoring_uptime_check_list_ips] // [START monitoring_uptime_check_update] public static object UpdateUptimeCheck(string configName, string newHttpPath, string newDisplayName) { var client = UptimeCheckServiceClient.Create(); var config = client.GetUptimeCheckConfig(configName); var fieldMask = new FieldMask(); if (newDisplayName != null) { config.DisplayName = newDisplayName; fieldMask.Paths.Add("display_name"); } if (newHttpPath != null) { config.HttpCheck.Path = newHttpPath; fieldMask.Paths.Add("http_check.path"); } client.UpdateUptimeCheckConfig(config); return(0); }
public IActionResult Put(string id, [FromBody] Dictionary <string, string> labels) { var client = SecretManagerServiceClient.Create(); var secret = new Secret { SecretName = new SecretName(ProjectId, id), }; foreach (var label in labels) { secret.Labels[label.Key] = label.Value; } var fieldMask = FieldMask.FromString("labels"); var updatedSecret = client.UpdateSecret(secret, fieldMask); return(Ok(updatedSecret)); }
public Secret UpdateSecret(string projectId = "my-project", string secretId = "my-secret") { // Create the client. SecretManagerServiceClient client = SecretManagerServiceClient.Create(); // Build the secret with updated fields. Secret secret = new Secret { SecretName = new SecretName(projectId, secretId), }; secret.Labels["secretmanager"] = "rocks"; // Build the field mask. FieldMask fieldMask = FieldMask.FromString("labels"); // Call the API. Secret updatedSecret = client.UpdateSecret(secret, fieldMask); return(updatedSecret); }
// [END monitoring_alert_replace_channels] // [START monitoring_alert_disable_policies] // [START monitoring_alert_enable_policies] static object EnablePolicies(string projectId, string filter, bool enable) { var client = AlertPolicyServiceClient.Create(); var request = new ListAlertPoliciesRequest() { ProjectName = new ProjectName(projectId), Filter = filter }; var response = client.ListAlertPolicies(request); int result = 0; foreach (AlertPolicy policy in response) { try { if (policy.Enabled == enable) { Console.WriteLine("Policy {0} is already {1}.", policy.Name, enable ? "enabled" : "disabled"); continue; } policy.Enabled = enable; var fieldMask = new FieldMask { Paths = { "enabled" } }; client.UpdateAlertPolicy(fieldMask, policy); Console.WriteLine("{0} {1}.", enable ? "Enabled" : "Disabled", policy.Name); } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == StatusCode.InvalidArgument) { Console.WriteLine(e.Message); result -= 1; } } // Return a negative count of how many enable operations failed. return(result); }
public static NotificationConfig UpdateNotificationConfig( string organizationId, string notificationConfigId, string projectId, string topicName) { NotificationConfigName notificationConfigName = new NotificationConfigName(organizationId, notificationConfigId); TopicName pubsubTopic = new TopicName(projectId, topicName); NotificationConfig configToUpdate = new NotificationConfig { NotificationConfigName = notificationConfigName, Description = "updated description", PubsubTopicAsTopicName = pubsubTopic }; FieldMask fieldMask = new FieldMask { Paths = { "description", "pubsub_topic" } }; SecurityCenterClient client = SecurityCenterClient.Create(); NotificationConfig updatedConfig = client.UpdateNotificationConfig(configToUpdate, fieldMask); Console.WriteLine($"Notification config updated: {updatedConfig}"); return(updatedConfig); }
/// <summary>Snippet for UpdateClusterAsync</summary> public async Task UpdateClusterAsync() { // Snippet: UpdateClusterAsync(string,string,string,Cluster,FieldMask,CallSettings) // Additional: UpdateClusterAsync(string,string,string,Cluster,FieldMask,CancellationToken) // Create client ClusterControllerClient clusterControllerClient = await ClusterControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string clusterName = ""; Cluster cluster = new Cluster(); FieldMask updateMask = new FieldMask(); // Make the request Operation <Cluster, ClusterOperationMetadata> response = await clusterControllerClient.UpdateClusterAsync(projectId, region, clusterName, cluster, updateMask); // Poll until the returned long-running operation is complete Operation <Cluster, ClusterOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Cluster result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation <Cluster, ClusterOperationMetadata> retrievedResponse = await clusterControllerClient.PollOnceUpdateClusterAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Cluster retrievedResult = retrievedResponse.Result; } // End snippet }
public CryptoKey UpdateKeyRemoveLabels(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key. CryptoKey key = new CryptoKey { CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId), }; // Build the update mask. FieldMask fieldMask = new FieldMask { Paths = { "labels" }, }; // Call the API. CryptoKey result = client.UpdateCryptoKey(key, fieldMask); // Return the updated key. return(result); }
public override float GetStat(MasterMask blockId, FieldMask stat) { BuildingFieldMask minionStat = (BuildingFieldMask)stat; if (blockId == MasterMask.MM_One) { } else if (blockId == MasterMask.MM_Two) { switch (minionStat) { case BuildingFieldMask.Building_FM2_CurrentHp: return(CurrentHealth); } } else if (blockId == MasterMask.MM_Three) { } else if (blockId == MasterMask.MM_Four) { } return(0); }
public async Task UpdateIntentAsync2() { Mock <Intents.IntentsClient> mockGrpcClient = new Mock <Intents.IntentsClient>(MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()) .Returns(new Mock <Operations.OperationsClient>().Object); UpdateIntentRequest expectedRequest = new UpdateIntentRequest { Intent = new Intent(), LanguageCode = "languageCode-412800396", UpdateMask = new FieldMask(), }; Intent expectedResponse = new Intent { IntentName = new IntentName("[PROJECT]", "[INTENT]"), DisplayName = "displayName1615086568", Priority = 1165461084, IsFallback = false, MlDisabled = true, Action = "action-1422950858", ResetContexts = true, RootFollowupIntentName = "rootFollowupIntentName402253784", ParentFollowupIntentName = "parentFollowupIntentName-1131901680", }; mockGrpcClient.Setup(x => x.UpdateIntentAsync(expectedRequest, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <Intent>(Task.FromResult(expectedResponse), null, null, null, null)); IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null); Intent intent = new Intent(); string languageCode = "languageCode-412800396"; FieldMask updateMask = new FieldMask(); Intent response = await client.UpdateIntentAsync(intent, languageCode, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public CryptoKeyVersion DisableKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key version. CryptoKeyVersion keyVersion = new CryptoKeyVersion { CryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId), State = CryptoKeyVersion.Types.CryptoKeyVersionState.Disabled, }; // Build the update mask. FieldMask fieldMask = new FieldMask { Paths = { "state" }, }; // Call the API. CryptoKeyVersion result = client.UpdateCryptoKeyVersion(keyVersion, fieldMask); // Return the result. return(result); }
/// <summary> /// Deletes a game server cluster /// </summary> /// <param name="projectId">Your Google Cloud Project Id</param> /// <param name="regionId">Region in which the cluster will be created</param> /// <param name="realmId"></param> /// <param name="clusterId">The id of the game server cluster</param> public string UpdateGameServerCluster( string projectId = "YOUR-PROJECT-ID", string regionId = "us-central1-f", string realmId = "YOUR-REALM-ID", string clusterId = "YOUR-GAME-SERVER-CLUSTER-ID") { // Initialize the client var client = GameServerClustersServiceClient.Create(); // Construct the request string parent = $"projects/{projectId}/locations/{regionId}/realms/{realmId}"; string clusterName = $"{parent}/gameServerClusters/{clusterId}"; var cluster = new GameServerCluster { Name = clusterName, Labels = { { "key", "value" } } }; var fieldMask = new FieldMask(); fieldMask.Paths.Add("labels"); // Call the API try { var updatedOperationId = client.UpdateGameServerCluster(cluster, fieldMask); // Inspect the result return($"Game server cluster updated: {cluster.Name}. OperationId: {updatedOperationId}"); } catch (Exception e) { Console.WriteLine($"UpdateGameServerCluster error:"); Console.WriteLine($"{e.Message}"); throw; } }
// [END secretmanager_list_secrets] // [START secretmanager_update_secret] /// <summary> /// Update an existing secret. /// </summary> /// <param name="projectId">ID of the project where the secret resides.</param> /// <param name="secretId">ID of the secret.</param> /// <example> /// Update an existing secret. /// <code>UpdateSecret("my-project", "my-secret")</code> /// </example> public static void UpdateSecret(string projectId, string secretId) { SecretManagerServiceClient client = SecretManagerServiceClient.Create(); // Create the secret to update. var secret = new Secret { SecretName = new SecretName(projectId, secretId), }; secret.Labels["secretmanager"] = "rocks"; // Create the request. var request = new UpdateSecretRequest { Secret = secret, UpdateMask = FieldMask.FromString("labels"), }; // Update the secret var updatedSecret = client.UpdateSecret(request); Console.WriteLine($"Updated secret {updatedSecret.Name}"); }
public CryptoKey UpdateKeyAddRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key. CryptoKey key = new CryptoKey { // Provide the name of the key to update. CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId), // Rotate the key every 30 days. RotationPeriod = new Duration { Seconds = 60 * 60 * 24 * 30, // 30 days }, // Start the first rotation in 24 hours. NextRotationTime = new Timestamp { Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(), } }; // Build the update mask. FieldMask fieldMask = new FieldMask { Paths = { "rotation_period", "next_rotation_time" }, }; // Call the API. CryptoKey result = client.UpdateCryptoKey(key, fieldMask); // Return the updated key. return(result); }
public async Task UpdateAlertPolicyAsync() { Mock <AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new Mock <AlertPolicyService.AlertPolicyServiceClient>(MockBehavior.Strict); UpdateAlertPolicyRequest expectedRequest = new UpdateAlertPolicyRequest { UpdateMask = new FieldMask(), AlertPolicy = new AlertPolicy(), }; AlertPolicy expectedResponse = new AlertPolicy { Name = "name3373707", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.UpdateAlertPolicyAsync(expectedRequest, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <AlertPolicy>(Task.FromResult(expectedResponse), null, null, null, null)); AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null); FieldMask updateMask = new FieldMask(); AlertPolicy alertPolicy = new AlertPolicy(); AlertPolicy response = await client.UpdateAlertPolicyAsync(updateMask, alertPolicy); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public async Task GetDocumentSnapshotsAsync_WithFieldMask() { string docName = "projects/proj/databases/db/documents/col1/doc1"; var mock = CreateMockClient(); var request = new BatchGetDocumentsRequest { Database = "projects/proj/databases/db", Documents = { docName }, Mask = new DocumentMask { FieldPaths = { "a", "b" } } }; var responses = new[] { new BatchGetDocumentsResponse { Missing = docName, ReadTime = CreateProtoTimestamp(1, 2) }, }; mock.Setup(c => c.BatchGetDocuments(request, It.IsAny <CallSettings>())).Returns(new FakeDocumentStream(responses)); var db = FirestoreDb.Create("proj", "db", mock.Object); var fieldMask = new FieldMask("a", "b"); var results = await db.GetDocumentSnapshotsAsync(new[] { db.Document("col1/doc1") }, transactionId : null, fieldMask, default); }
/// <summary> /// Compares a given field for two messages, and captures the differences between them. /// </summary> /// <param name="mask">The fieldmask to store the differences to.</param> /// <param name="fieldName">The field name to compare.</param> /// <param name="original">The original value of the field.</param> /// <param name="modified">The modified value of the field.</param> private static void CompareField(FieldMask mask, string fieldName, IMessage original, IMessage modified) { var descriptor = modified.Descriptor; foreach (var childField in descriptor.Fields.InFieldNumberOrder()) { string childFieldName = GetFullFieldName(fieldName, childField); var originalChildValue = childField.Accessor.GetValue(original); var modifiedChildValue = childField.Accessor.GetValue(modified); if (childField.IsRepeated) { if (!Equals(originalChildValue, modifiedChildValue)) { mask.Paths.Add(childFieldName); } } else { switch (childField.FieldType) { case FieldType.Message: if (!Equals(originalChildValue, modifiedChildValue)) { // For wrapper types, just emit the field name. if (IsWrapperType(childField.MessageType)) { mask.Paths.Add(childFieldName); } else if (originalChildValue == null) { // New value? Emit the field names for all known fields in the message, // recursing for nested messages. AddNewFields(mask, childFieldName, (IMessage)modifiedChildValue); } else if (modifiedChildValue == null) { // Just emit the deleted field name mask.Paths.Add(childFieldName); } else { CompareField(mask, childFieldName, (IMessage)originalChildValue, (IMessage)modifiedChildValue); } } break; case FieldType.Group: throw new NotSupportedException("Groups are not supported in proto3"); default: // Primitives if (childField.HasPresence) { // Presence fields should be handled based on whether the field has // value. bool originalChildHasValue = childField.Accessor.HasValue(original); bool modifiedChildHasValue = childField.Accessor.HasValue(modified); // Both fields have value, but the values don't match. if (originalChildHasValue && modifiedChildHasValue && !Equals(originalChildValue, modifiedChildValue)) { mask.Paths.Add(childFieldName); } else if (originalChildHasValue ^ modifiedChildHasValue) { // Only one of the fields have value. mask.Paths.Add(childFieldName); } } else if (!Equals(originalChildValue, modifiedChildValue)) { mask.Paths.Add(childFieldName); } break; } } } }
/// <summary> /// Recursively adds field names for a new message. Repeated fields, primitive fields and /// unpopulated single message fields are included just by name; populated single message /// fields are processed recursively, only including leaf nodes. /// </summary> /// <param name="fieldName">The current field.</param> /// <param name="mask">The fieldmask that keeps track of changes.</param> /// <param name="message">The message for which new fieldmasks are generated.</param> private static void AddNewFields(FieldMask mask, string fieldName, IMessage message) { var descriptor = message.Descriptor; int fieldCount = mask.Paths.Count; foreach (var field in descriptor.Fields.InFieldNumberOrder()) { string name = GetFullFieldName(fieldName, field); object value = field.Accessor.GetValue(message); if (field.IsRepeated) { if (value is IList && (value as IList).Count > 0) { // Generate fieldmask for a repeated field only if there's at least one // element in the list. Also, don't recurse, since fieldmask doesn't // support index notation. mask.Paths.Add(name); } } else { if (field.FieldType == FieldType.Message) { // For single message fields, recurse if there's a value. if (value != null) { AddNewFields(mask, name, (IMessage)value); } } else if (field.HasPresence) { // The presence fields should first be checked for HasValue. if (field.Accessor.HasValue(message)) { mask.Paths.Add(name); } } else if (IsBasicType(field.FieldType)) { // Add a field mask only if there is a non-default value. var defaultValue = GetDefaultValue(field.FieldType); if (!Equals(defaultValue, value)) { mask.Paths.Add(name); } } else if (field.FieldType == FieldType.Enum) { // Add a field mask only if there is a non-default value. var defaultValue = System.Enum.ToObject(field.EnumType.ClrType, 0); if (!Equals(defaultValue, value)) { mask.Paths.Add(name); } } } } if (fieldCount == mask.Paths.Count) { // We recursed the whole hierarchy, but added no new fields. This should then be // treated as an empty submessage. mask.Paths.Add(fieldName); } }
public float getStat(MasterMask blockId, FieldMask stat) { return getStat((byte)blockId, (int)stat); }
public void setStat(MasterMask blockId, FieldMask stat, float value) { setStat((byte)blockId, (int)stat, value); }