private NewImplementProcessRecordAsync()

in powershell/cmdlets/class.ts [808:923]


  private NewImplementProcessRecordAsync() {
    const $this = this;
    const operationParameters = $this.operationParameters;
    const pipeline = $this.$<Property>('Pipeline');
    this.serializationMode = this.bodyParameter ? (this.operation.operationType === OperationType.Create ? ClientRuntime.SerializationMode.IncludeCreate : (this.operation.operationType === OperationType.Update ? ClientRuntime.SerializationMode.IncludeUpdate : undefined)) : undefined;
    if (this.operation.commandType === CommandType.GetPut || this.operation.commandType === CommandType.ManagedIdentityUpdate) {
      this.serializationMode = ClientRuntime.SerializationMode.IncludeCreateOrUpdate;
    }

    const PRA = this.add(new Method('ProcessRecordAsync', System.Threading.Tasks.Task(), {
      access: Access.Protected, async: Modifier.Async,
      description: 'Performs execution of the command, working asynchronously if required.',
      returnsDescription: `A <see cref="${System.Threading.Tasks.Task()}" /> that will be complete when handling of the method is completed.`
    }));

    // we don't want to use SynchContext here.
    PRA.push(Using('NoSynchronizationContext', ''));
    PRA.add(function* () {
      if ($this.apProp && $this.bodyParameter && $this.bodyParameterInfo) {
        // yield `${ClientRuntime}.DictionaryExtensions.HashTableToDictionary<${$this.bodyParameterInfo.type.declaration},${$this.bodyParameterInfo.valueType.declaration}>(${$this.apProp.value},${$this.bodyParameter.Cast($this.bodyParameterInfo.type)});`;
        let vt = $this.bodyParameterInfo.valueType.declaration;
        if (vt.endsWith('SwitchParameter')) {
          vt = 'bool';
        }
        yield `${ClientRuntime}.DictionaryExtensions.HashTableToDictionary<${vt}>(${$this.apProp.value},${$this.bodyParameter}.AdditionalProperties);`;
      }

      // construct the call to the operation
      if (!$this.state.project.azure) {
        yield $this.eventListener.signal(Events.CmdletProcessRecordAsyncStart);
      }

      yield $this.eventListener.signal(Events.CmdletGetPipeline);

      if ($this.state.project.azure) {
        yield pipeline.assign(new LiteralExpression(`${$this.state.project.serviceNamespace.moduleClass.declaration}.Instance.CreatePipeline(${$this.invocationInfo}, ${$this.correlationId}, ${$this.processRecordId}, this.ParameterSetName, this.ExtensibleParameters)`));
      } else {
        yield pipeline.assign(new LiteralExpression(`${$this.state.project.serviceNamespace.moduleClass.declaration}.Instance.CreatePipeline(${$this.invocationInfo}, this.ParameterSetName, this.ExtensibleParameters)`));
      }

      yield If(IsNotNull($this.$<Property>('HttpPipelinePrepend')), pipeline.invokeMethod('Prepend', toExpression(`(this.CommandRuntime as Microsoft.Rest.ClientRuntime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(${$this.$<Property>('HttpPipelinePrepend')}) ?? ${$this.$<Property>('HttpPipelinePrepend')}`)));
      yield If(IsNotNull($this.$<Property>('HttpPipelineAppend')), pipeline.invokeMethod('Append', toExpression(`(this.CommandRuntime as Microsoft.Rest.ClientRuntime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(${$this.$<Property>('HttpPipelineAppend')}) ?? ${$this.$<Property>('HttpPipelineAppend')}`)));

      yield '// get the client instance';
      // Add input pipeline if it is configured by developers.
      if ($this.operation.extensions.inputPipe) {
        const handlers = <Array<HandlerDirective>>$this.operation.extensions.inputPipe;
        // default priority is 100
        handlers.sort((a, b) => { return (a.priority || 100) - (b.priority || 100); });
        for (const { index, handler } of handlers.map((handler, index) => ({ index, handler }))) {
          yield `var handler_${index} = new ${handler.name}();`;
          if (index > 0) {
            yield `handler_${index - 1}.SetNextHandler(handler_${index});`;
          }
        }
        yield 'handler_0.Process(this);';
      }
      const vps = $this.operation.details.csharp.virtualParameters || {
        body: [],
        operation: [],
      };
      for (const vParam of [...vps.body, ...vps.operation]) {
        if (vParam.hidden) {
          const td = $this.state.project.schemaDefinitionResolver.resolveTypeDeclaration(<NewSchema>vParam.schema, true, $this.state, true);
          yield If(`true == this.MyInvocation?.BoundParameters?.ContainsKey("${vParam.name}")`, `${vParam.name} = (${td.declaration})this.MyInvocation.BoundParameters["${vParam.name}"];`);
        }
      }

      // is there a body parameter we should include?
      // if ($this.bodyParameter) {
      //   operationParameters.push({ name: 'body', expression: $this.bodyParameter, isPathParam: false });
      // }

      yield Try(function* () {
        // make the call.
        let preProcess: PreProcess;
        switch ($this.operation.commandType) {
          case CommandType.ManagedIdentityUpdate:
            preProcess = !$this.disableTransformIdentityType && $this.ContainsIdentityTypeParameter() ? $this.ManagedIdentityUpdateCmdletPreProcess : undefined;
            break;
          case CommandType.GetPut:
            preProcess = $this.GetPutPreProcess;
            break;
          case CommandType.ManagedIdentityNew:
            preProcess = !$this.disableTransformIdentityType && $this.ContainsIdentityTypeParameter() && $this.ContainsUserAssignedIdentityParameter() ? $this.ManagedIdentityPreProcessForNewVerbCmdlet : undefined;
            break;
          case CommandType.Atomic:
          default:
            preProcess = $this.ContainsUserAssignedIdentityParameter() ? $this.ManagedUserAssignedIdentityPreProcess : undefined;
            break;
        }
        const actualCall = function* () {
          yield $this.eventListener.signal(Events.CmdletBeforeAPICall);
          yield $this.ImplementCall(preProcess);
          yield $this.eventListener.signal(Events.CmdletAfterAPICall);
        };

        if ($this.state.project.azure && operationParameters.find(each => each.expression && each.expression.value === 'SubscriptionId') && $this.operation.details.csharp.verb.toLowerCase() === 'get') {
          yield 'foreach( var SubscriptionId in this.SubscriptionId )';
          yield BlockStatement(actualCall);
        } else {
          yield actualCall;
        }
      });
      const ure = new Parameter('urexception', { declaration: `${ClientRuntime.fullName}.UndeclaredResponseException` });
      yield Catch(ure, function* () {
        yield `WriteError(new global::System.Management.Automation.ErrorRecord(${ure.value}, ${ure.value}.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ${operationParameters.filter(e => valueOf(e.expression) !== 'null').map(each => `${each.name}=${each.expression}`).join(',')}})
{
  ErrorDetails = new global::System.Management.Automation.ErrorDetails(${ure.value}.Message) { RecommendedAction = ${ure.value}.Action }
});`;
      });
      yield Finally(function* () {
        yield $this.eventListener.signalNoCheck(Events.CmdletProcessRecordAsyncEnd);
      });
    });
  }