csharp 音频淡出课程

AudioFadeOut.cs
using UnityEngine;
using System.Collections;
 
public static class AudioFadeOut {
 
    public static IEnumerator FadeOut (AudioSource audioSource, float FadeTime) {
        float startVolume = audioSource.volume;
 
        while (audioSource.volume > 0) {
            audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
 
            yield return null;
        }
 
        audioSource.Stop ();
        audioSource.volume = startVolume;
    }
 
}

csharp SpriteMissingChecker.cs

SpriteMissingChecker.cs
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;

/// <summary>
/// SpriteRendererのSpriteがnullだったら背景を赤くするEditor拡張
/// </summary>
public class SpriteMissingChecker
{
    [InitializeOnLoadMethod]
    private static void AddHierarchyItemOnGUI()
    {
        EditorApplication.hierarchyWindowItemOnGUI -= HierarchyWindowItemOnGUI;
        EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;

        EditorApplication.projectWindowItemOnGUI -= ProjectWindowItemOnGUI;
        EditorApplication.projectWindowItemOnGUI += ProjectWindowItemOnGUI;
    }

    /// <summary>
    /// ProjectWindow OnGUI
    /// </summary>
    private static void ProjectWindowItemOnGUI(string guid, Rect selectionRect)
    {
        var path = AssetDatabase.GUIDToAssetPath(guid);
        if (Directory.Exists(path) ||
            path.IndexOf(".prefab") < 0)
        {
            return;
        }

        // prefabのみ対象
        var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
        if (IsValid(prefab))
        {
            Draw(selectionRect);
        }
    }

    /// <summary>
    /// HierarchyWindow OnGUI
    /// </summary>
    private static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
    {
        var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
        if (gameObject == null)
        {
            return;
        }

        if (IsValid(gameObject))
        {
            Draw(selectionRect);
        }
    }

    /// <summary>
    /// 見た目の処理
    /// 背景を赤くする
    /// </summary>
    static void Draw(Rect rect)
    {
        var bg = GUI.backgroundColor;
        GUI.backgroundColor = Color.red;
        GUI.Box(rect, "");
        GUI.backgroundColor = bg;
    }

    /// <summary>
    /// 子階層全てのSpriteRendererのSpriteにnullが存在したらtrue
    /// </summary>
    static bool IsValid(GameObject go)
    {
        var arr = go.GetComponentsInChildren<SpriteRenderer>();
        return arr.Any(x => x.sprite == null);
    }
}

csharp 延迟销毁GameObject #Delay #Destroy

延迟销毁GameObject #Delay #Destroy

DelayedDestroy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DelayedDestroy : MonoBehaviour
{
    public float delay = 1f;
    void Start()
    {
        Destroy(gameObject, delay);
    }
}

csharp InControl的输入接口#Input #Pad #Control

InControl的输入接口#Input #Pad #Control

InputBase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class InputBase : MonoBehaviour
{
    //------------------------------------------------------------------------------------------------------------------
    public abstract Vector3 UpdateInput();
}
InputKeyboard.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputKeyboard : InputBase
{
 
    //------------------------------------------------------------------------------------------------------------------
    [Header("Input")] 
    [SerializeField]
    private KeyCode _leftInput;
    [SerializeField]
    private KeyCode _rightInput;
    [SerializeField]
    private KeyCode _upInput;
    [SerializeField]
    private KeyCode _downInput;
    [SerializeField] 
    private float _smoothFactor = .2f;
    
    
    Vector3 dir = Vector3.zero;
    
    //------------------------------------------------------------------------------------------------------------------
    public override Vector3 UpdateInput()
    {
        bool anyKey = false;
        
        if (Input.GetKey(_leftInput))
        {
            dir += Vector3.left * _smoothFactor;
            anyKey = true;
        }
        else if (Input.GetKey(_rightInput))
        {
            dir += Vector3.right * _smoothFactor;
            anyKey = true;
        }

        if (Input.GetKey(_upInput))
        {
            dir += Vector3.forward * _smoothFactor;
            anyKey = true;
        }
        else if (Input.GetKey(_downInput))
        {
            dir += Vector3.back * _smoothFactor;
            anyKey = true;
        }
        
        if(!anyKey)
        {
            dir = Vector3.zero;
        }

        dir.Normalize();
        return dir;
    }
}
InputMouse.cs
using System.Collections;
using System.Collections.Generic;
using InControl;
using UnityEngine;

public class InputMouse : InputBase
{
    //------------------------------------------------------------------------------------------------------------------
    public override Vector3 UpdateInput()
    {
        Vector3 dir = Vector3.zero;

        if (Input.GetMouseButton(0))
        {
            dir = new Vector3(Input.GetAxis("Mouse X"), 0.0f, Input.GetAxis("Mouse Y"));
        }

        return dir;
    }
}
InputVirtualJoystick.cs
using System.Collections;
using System.Collections.Generic;
using InControl;
using UnityEngine;

public class InputVirtualJoystick : InputBase
{
    //------------------------------------------------------------------------------------------------------------------
    public override Vector3 UpdateInput()
    {
        Vector3 dir = Vector3.zero;
        // Use last device which provided input.
        var inputDevice = InputManager.ActiveDevice;

        // Disable and hide touch controls if we use a controller.
        // If "Enable Controls On Touch" is ticked in Touch Manager inspector,
        // controls will be enabled and shown again when the screen is touched.
        if (inputDevice != InputDevice.Null)
        {
            if (inputDevice != TouchManager.Device)
            {
                TouchManager.ControlsEnabled = false;
            }
            else
            {
                dir = new Vector3(inputDevice.Direction.X, 0.0f, inputDevice.Direction.Y);
            }
        }

        return dir;
    }
}
InputVisibility.cs
using System;
using InControl;
using Spectrum;
using UnityEngine;

public class InputVisibility : MonoBehaviour
{
    private TouchManager _touchManager;

    //------------------------------------------------------------------------------------------------------------------
    private void Awake()
    {
        _touchManager = GetComponent<TouchManager>();
    }

    //------------------------------------------------------------------------------------------------------------------
    private void Start()
    {
        God.GameLogic.OnGamePaused += OnGamePaused;
        God.GameLogic.OnGameResumed += OnGameResumed;
    }

    //------------------------------------------------------------------------------------------------------------------
    private void OnGameResumed()
    {
        _touchManager.controlsEnabled = true;
        _touchManager.enableControlsOnTouch = true;   
    }

    //------------------------------------------------------------------------------------------------------------------
    private void OnGamePaused()
    {
        _touchManager.controlsEnabled = false;
        _touchManager.enableControlsOnTouch = false;   
    }    
}

csharp 客户端发送SOAP请求并接收响应

https://stackoverflow.com/questions/4791794/client-to-send-soap-request-and-receive-response <br/> https://hassantariqblog.wordpress.com/2016/09/06/c-sending -soap请求和接收响应,而无需-使用最WSDL-或代理类/

soap
using System.Xml;
using System.Net;
using System.IO;

public static class SOAP
    {
        public static void CallWebService()
        {
            var _url = "http://www.oorsprong.org/websamples.countryinfo/CountryInfoService.wso";
            var _action = "http://www.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?op=ListOfContinentsByName";

            XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
            HttpWebRequest webRequest = CreateWebRequest(_url, _action);
            InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

            // begin async call to web request.
            IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

            // suspend this thread until call is complete. You might want to
            // do something usefull here like update your UI.
            asyncResult.AsyncWaitHandle.WaitOne();

            // get the response from the completed web request.
            string soapResult;
            using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
            {
                using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                {
                    soapResult = rd.ReadToEnd();
                }
                Console.Write(soapResult);
            }
        }

        private static HttpWebRequest CreateWebRequest(string url, string action)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", action);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        private static XmlDocument CreateSoapEnvelope()
        {
            XmlDocument soapEnvelopeDocument = new XmlDocument();
            soapEnvelopeDocument.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                                        <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                                            <soap:Body>
                                            <ListOfContinentsByName xmlns = ""http://www.oorsprong.org/websamples.countryinfo"">
                                            </ListOfContinentsByName>
                                            </soap:Body>
                                        </soap:Envelope>");
            return soapEnvelopeDocument;
        }

        private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
        {
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
        }
    }

csharp 用户输入绘制线

DrawingManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using Ara;
public class PenTrail
{
    public GameObject penTrail;
    public GameObject penSoundObject;
    public int pointCount;
    public float trailSpeed;
}

public class DrawingManager : MonoBehaviour
{
    #region Drawing Data
    public bool isDrawing;
    public float penPosX;
    public float penPosY;
    #endregion
    #region Trail Status
    [Header("TRAIL")]
    public float trailSpeed = 0;
    public RectTransform trailSpeedIndicator;
    bool isSpawned;
    bool isDestoryed;
    #endregion
    #region References
    public AudioManager audioManager;
    public GameObject trailPrefab;
    public GameObject[] trailSound;
    public GameObject trailPool;
    #endregion
    public List<PenTrail> penTrails;
    GameObject currentTrail;
    Vector3 lastPos = Vector3.zero;
    int currentPenDirectionId = 0;
    int additionalSoundCount = 0;
    AraTrail araTrail;

    public TableSimulation tableSimulation;

    void Start()
    {
        penTrails = new List<PenTrail>();
    }
    void Update()
    {
        // tableSimulation.penSoundIndex = currentPenDirectionId;
        tableSimulation.isDrawing = isDrawing;
        TrailSpeed();
        TrailDrawing();
        // if (penTrails.Count > 0)
        //     TrailDirection();
    }
    #region Drawing Functions
    int trailCount = 0;
    void TrailDrawing()
    {
        if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) || Input.GetMouseButton(0))
        {
            if (!isSpawned) // NOTE excuted only once(First frame of pen touch)
            {
                isSpawned = true;
                trailCount = 0;
                PenTrail newPenTrail = new PenTrail();
                // spawn pentrail object 
                GameObject newTrail = Instantiate(trailPrefab, trailPool.transform.position, Quaternion.identity) as GameObject;
                newTrail.transform.SetParent(trailPool.transform);
                // update PenTrail class object and add class to the list for futher serial destroy
                newPenTrail.penTrail = newTrail;
                currentTrail = newTrail;
                penTrails.Add(newPenTrail);
                additionalSoundCount = 0;
                tableSimulation.PenSoundSpanwer();
            }
            trailCount++;
            if (trailCount == 1)
            {
                if (penTrails.Count > 0)
                {   
                    
                    // TrailSound(currentPenDirectionId);
                    // GameObject penSound = Instantiate(audioManager.PenSoundProvider(TrailStyle.currentStyle, currentPenDirectionId), Vector3.zero, Quaternion.identity) as GameObject;
                    // penSound.transform.SetParent(penTrails[penTrails.Count - 1].penTrail.transform);
                    // penTrails[penTrails.Count - 1].penSoundObject = penSound;
                }
            }
            isDrawing = true;
            isDestoryed = false;
            // move target trail object position by user input
            Plane objPlane = new Plane(Camera.main.transform.forward * -1, trailPool.transform.position);
            Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            float rayDistance;
            if (objPlane.Raycast(mRay, out rayDistance))
                currentTrail.transform.position = mRay.GetPoint(rayDistance);
            // Data Handling
            penPosX = Input.mousePosition.x/Screen.width;
            penPosY = Input.mousePosition.y/Screen.height;

            tableSimulation.penPosX = penPosX;
            tableSimulation.penPosY = penPosY;




            // means length of stroke
            penTrails[penTrails.Count - 1].pointCount = penTrails[penTrails.Count - 1].penTrail.GetComponent<AraTrail>().points.Count;
        }
        else
        {
            isDrawing = false;
            isSpawned = false;
            if (!isDestoryed && penTrails.Count > 0)
            {
                isDestoryed = true;
                // audioManager.StopPenSound(penTrails[penTrails.Count - 1].penSoundObject.GetComponent<AudioSource>(), 1.5f);
                Destroy(penTrails[penTrails.Count - 1].penTrail, penTrails[penTrails.Count - 1].penTrail.GetComponent<AraTrail>().time);
                penTrails.Remove(penTrails[penTrails.Count - 1]);
            }
        }
        if (penTrails.Count > 0)
        {
            penTrails[penTrails.Count - 1].trailSpeed = trailSpeed;
            // penTrails[penTrails.Count - 1].penSoundObject.GetComponent<AudioSource>().volume = 1 - penTrails[penTrails.Count - 1].trailSpeed / 100;
            // penTrails[penTrails.Count - 1].penSoundObject.GetComponent<AudioSource>().pitch = 1 - penTrails[penTrails.Count - 1].trailSpeed / 100;
            // Debug.Log(penTrails[penTrails.Count - 1].trailSpeed);
        }

    }
    float lerpTime = 2.2f;
    float currentLerpTime;

    void TrailSpeed()
    {
        if (isDrawing && penTrails.Count > 0)
        {
            if (isSpawned)
            {
                float trailSpeedDelta = ((penTrails[penTrails.Count - 1].penTrail.transform.position - lastPos).magnitude / Time.deltaTime);
                lastPos = penTrails[penTrails.Count - 1].penTrail.transform.position;
                trailSpeed = trailSpeed + trailSpeedDelta * Time.deltaTime;
                currentLerpTime = 0;
                // Debug.Log(trailSpeedDelta);
                if (trailSpeedDelta > 60)
                {
                    if (additionalSoundCount == 0 || additionalSoundCount == 1)
                    {
                        GameObject penSound = Instantiate(audioManager.PenSoundProvider(TrailStyle.currentStyle, currentPenDirectionId), Vector3.zero, Quaternion.identity) as GameObject;
                        penSound.transform.SetParent(penTrails[penTrails.Count - 1].penTrail.transform);
                        penTrails[penTrails.Count - 1].penSoundObject = penSound;
                        additionalSoundCount++;
                        Debug.Log(additionalSoundCount);
                    }

                }
            }
            else
            {
                trailSpeed = 0;
            }
        }
        else
        {
            currentLerpTime += Time.deltaTime;
            if (currentLerpTime > lerpTime)
                currentLerpTime = lerpTime;
            float t = currentLerpTime / lerpTime;
            t = 1f - Mathf.Cos(t * Mathf.PI * 0.5f);
            trailSpeed = Mathf.Lerp(trailSpeed, 0, t * t);
        }
        trailSpeedIndicator.sizeDelta = new Vector2(20, trailSpeed * 5);
    }
    void TrailSound(int soundIndex)
    {
        GameObject penSound = Instantiate(trailSound[soundIndex], Vector3.zero, Quaternion.identity) as GameObject;
        penSound.transform.SetParent(penTrails[penTrails.Count - 1].penTrail.transform);
        penTrails[penTrails.Count - 1].penSoundObject = penSound;
    }
    void TrailDirection()
    {
        Vector3 InitialPenDirection = penTrails[penTrails.Count - 1].penTrail.transform.position - lastPos;
        Debug.Log(penTrails[penTrails.Count - 1].penTrail.transform.position);
        float trailAngle = Quaternion.FromToRotation(InitialPenDirection, Vector3.right).eulerAngles.z;
        if (trailAngle < 60)
        {
            currentPenDirectionId = 0;
        }
        else if (trailAngle >= 60 && trailAngle < 120)
        {
            currentPenDirectionId = 1;
        }
        else if (trailAngle >= 120 && trailAngle < 180)
        {
            currentPenDirectionId = 2;
        }
        else if (trailAngle >= 180 && trailAngle < 240)
        {
            currentPenDirectionId = 3;
        }
        else if (trailAngle >= 240 && trailAngle < 300)
        {
            currentPenDirectionId = 4;
        }
        else
        {
            currentPenDirectionId = 5;
        }

    }
    #endregion

    #region Debugging Functions
    void TrailMonitoring()
    {
        if (isDrawing)
            Debug.Log("Drawing Something, POS : " + Input.mousePosition + "LENGTH :" + penTrails.Count);
        else
            Debug.Log("Not Drawing");
    }
    #endregion
    #region Drawing Data Functions

    #endregion
}

csharp 递归注册搜索

递归搜索注册表项

RecRegSearch.cs
internal static RegistryKey RecursiveRegSearch(RegistryKey subKey, string keyName, string valueName)
{
    try
    {
        if (subKey == null) return null;

        var o = subKey.GetValue(valueName);
        if (o != null)
        {
            // we found the value
            // does it match?
            var value = o.ToString();
            if (value == keyName)
            {
                return subKey;
            }
        }

        // nothing, keep looking
        foreach (var sub in subKey.GetSubKeyNames())
        {
            try
            {
                using (var newKey = subKey.OpenSubKey(sub, false))
                {
                    var searchValue = RecursiveRegSearch(newKey, keyName, valueName);
                    if (searchValue != null) return searchValue;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        return null;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        return null;
    }
}

csharp Azure功能

doc.md
# Key Configuration Files

## Local Settings

The file `local.settings.json` stores app settings, connection strings, and settings used by local development tools.
These should be the same as the application settings in the function app in Azure.
If you have created application settings in Azure, you can download them into your local settings file. 

Because it contains secrets it never gets published, and is excluded from source control.

## Host

The `host.json` metadata file contains global configuration options that affect all functions for a function app.

```json
{
    "version": "2.0"
}
```

These settings apply both when running locally and in Azure.

See [here](https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json) for more.
Can include settings for extensions, health monitoring and logging for example.

## Bindings - `function.json`

In a C# class library project, the bindings are defined as binding attributes 
on the function method. The `function.json` file is then autogenerated based 
on these attributes:

```json
{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.29",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "httpTrigger",
      "methods": ["get", "post"],
      "authLevel": "function",
      "name": "req"
    }
  ],
  "disabled": false,
  "scriptFile": "../bin/functions.dll",
  "entryPoint": "My.Functions.HttpTriggerCSharp.Run"
}
```
examples.cs
// HTTP trigger, with Storage Queue o/p
[FunctionName("HttpTriggerQueueOutput")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [Queue("outqueue"), StorageAccount("AzureWebJobsStorage")] ICollector<string> msg, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    
    // Add a message to the output collection.
    msg.Add(string.Format("Name passed to the function: {0}", name));
}

// Queue trigger, Table o/p
[FunctionName("QueueTriggerTableOutput")]
[return: Table("outTable", Connection = "MY_TABLE_STORAGE_ACCT_APP_SETTING")]
public static Person Run(
    [QueueTrigger("myqueue-items", Connection = "MY_STORAGE_ACCT_APP_SETTING")] JObject order,
    ILogger log)
{
    return new Person() {
            PartitionKey = "Orders",
            RowKey = Guid.NewGuid().ToString(),
            Name = order["Name"].ToString(),
            MobileNumber = order["MobileNumber"].ToString()
    };
}

// Blob trigger
[FunctionName("BlobTrigger")]
public static void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}

// CosmosDB trigger
[FunctionName("CosmosTrigger")]
public static void Run(
  [CosmosDBTrigger(
    databaseName: "ToDoItems",
    collectionName: "Items",
    ConnectionStringSetting = "CosmosDBConnection",
    LeaseCollectionName = "leases",
    CreateLeaseCollectionIfNotExists = true)
  ] IReadOnlyList<Document> documents,
    ILogger log)
{
    if (documents != null && documents.Count > 0)
    {
        log.LogInformation($"Documents modified: {documents.Count}");
        log.LogInformation($"First document Id: {documents[0].Id}");
    }
}
durable.md
# Chaining
![chaining](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/function-chaining.png)

# Fan out / fan in
![fan](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/fan-out-fan-in.png)

# Async HTTP APIs
![async](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/async-http-api.png)

See [Create your first durable function in C#](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-create-first-csharp).

# Monitor
![monitor](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/monitor.png)

# Human interaction
![human](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/approval.png)

# Aggregator (preview)
![aggregator](https://docs.microsoft.com/en-us/azure/azure-functions/durable/media/durable-functions-concepts/aggregator.png)
durable.cs
// Durable function chaining
public static async Task<object> Run(DurableOrchestrationContext context)
{
    try
    {
        var x = await context.CallActivityAsync<object>("F1");
        var y = await context.CallActivityAsync<object>("F2", x);
        var z = await context.CallActivityAsync<object>("F3", y);
        return  await context.CallActivityAsync<object>("F4", z);
    }
    catch (Exception)
    {
        // Error handling or compensation goes here.
    }
}

// Fan out / fan in
public static async Task Run(DurableOrchestrationContext context)
{
    var parallelTasks = new List<Task<int>>();

    // Get a list of N work items to process in parallel.
    object[] workBatch = await context.CallActivityAsync<object[]>("F1");
    for (int i = 0; i < workBatch.Length; i++)
    {
        Task<int> task = context.CallActivityAsync<int>("F2", workBatch[i]);
        parallelTasks.Add(task);
    }

    await Task.WhenAll(parallelTasks);

    // Aggregate all N outputs and send the result to F3.
    int sum = parallelTasks.Sum(t => t.Result);
    await context.CallActivityAsync("F3", sum);
}

// Monitor - Not much of a clue what is going on here

// Human
public static async Task Run(DurableOrchestrationContext context)
{
    await context.CallActivityAsync("RequestApproval");
    using (var timeoutCts = new CancellationTokenSource())
    {
        DateTime dueTime = context.CurrentUtcDateTime.AddHours(72);
        
        // create the durable timer
        Task durableTimeout = context.CreateTimer(dueTime, timeoutCts.Token);

        // wait for approval
        Task<bool> approvalEvent = context.WaitForExternalEvent<bool>("ApprovalEvent");
        
        // check approval
        if (approvalEvent == await Task.WhenAny(approvalEvent, durableTimeout))
        {
            timeoutCts.Cancel();
            await context.CallActivityAsync("ProcessApproval", approvalEvent.Result);
        }
        else
        {
            await context.CallActivityAsync("Escalate");
        }
    }
}

// Aggregator
// Using a Durable Entity function, one can implement this pattern easily as a single function.
[FunctionName("Counter")]
public static void Counter([EntityTrigger] IDurableEntityContext ctx)
{
    int currentValue = ctx.GetState<int>();

    switch (ctx.OperationName.ToLowerInvariant())
    {
        case "add":
            int amount = ctx.GetInput<int>();
            currentValue += operand;
            break;
        case "reset":
            currentValue = 0;
            break;
        case "get":
            ctx.Return(currentValue);
            break;
    }

    ctx.SetState(currentValue);
}
// yeah, not really sure what's going on here

csharp CSharp,Linq - 选择以前的,当前的,净的

CSharp,Linq - 如何选择数组中的先前,当前,净值

SelPcn
var flusso =  Enumerable.Range(1,30).ToArray();

flusso.TakeWhile((_, pos) => pos <= flusso.Count()).Select((_, pos) => flusso.Skip(pos).Take(3)).Where(w => w.Count() == 3).Dump();

csharp DLX_ForecastSalesMultiCreation

创建多预测销售

DLX_ForecastSalesMultiCreationDC
// DLX_SCMBUG2682_FCConfigActiveMng - 20170605 - Mirco Z
[
    DataContractAttribute,
    SysOperationContractProcessingAttribute(classStr(DLX_ForecastSalesMultiCreationUIBuilder))
]
class DLX_ForecastSalesMultiCreationDC
{
    DLX_ForecastToAdd   forecastToAdd;
    ForecastSales       forecastSales;
}

[
    DataMemberAttribute,
    SysOperationControlVisibilityAttribute(false)
]
public ForecastSales parmForecastSales(ForecastSales _forecastSales = forecastSales)
{
    forecastSales = _forecastSales;

    return forecastSales;
}

// DLX_SCMBUG2682_ForecastConfigActiveMng - 20170605 - Mirco Z
[DataMemberAttribute]
public DLX_ForecastToAdd parmForecastToAdd(DLX_ForecastToAdd _forecastToAdd = forecastToAdd)
{
    forecastToAdd = _forecastToAdd;

    return forecastToAdd;
}
DLX_ForecastSalesMultiCreationController
// DLX_SCMBUG2682_FCConfigActiveMng - 20170605 - Mirco Z
class DLX_ForecastSalesMultiCreationController extends SysOperationServiceController
{
    DLX_ForecastSalesMultiCreationDC forecastSalesMultiCreationDC;
}

protected void afterOperation(SysOperationExecutionMode _executionMode, AifAsyncResult _asyncResult)
{
    FormDatasource fds;

    super(_executionMode, _asyncResult);

    if( _asyncResult &&
       (_executionMode == SysOperationExecutionMode::Synchronous) &&
       !_asyncResult.parmHasException() &&
       _asyncResult.parmIsCompleted())
    {
        if (this.parmArgs() && this.parmArgs().record() && this.parmArgs().record().isFormDataSource())
        {
            fds = this.parmArgs().record().dataSource();
            fds.research(true);
        }
    }
}

public void initFromCaller(Args _args)
{
    ForecastSales forecastSales;
    ;

    try
    {
        this.initializeFromArgs(_args);

        if (_args && _args.record() != null )
        {
            forecastSalesMultiCreationDC    = this.getDataContractObject(identifierStr(_forecastSalesMultiCreationDC));

            forecastSales                   = _args.record();

            if (forecastSales.RecId
                && forecastSales.inventTable().configActive()
                && forecastSales.SalesQty == 1 )
            {
                forecastSalesMultiCreationDC.parmForecastSales(forecastSales);
            }
            else
                throw error(strFmt("@SYS26747"));
        }
        else
            throw error(strFmt("@SYS26747"));
    }
    catch (Exception::Error)
    {
        throw (Exception::Error);
    }
}

public static DLX_ForecastSalesMultiCreationController construct()
{
    return new DLX_ForecastSalesMultiCreationController();
}

public static void main(Args args)
{
    DLX_ForecastSalesMultiCreationController forecastSalesMultiCreationController = DLX_ForecastSalesMultiCreationController::construct();
    ;

    forecastSalesMultiCreationController.initFromCaller(args);

    if(forecastSalesMultiCreationController)
    {
        xSysLastValue::deleteLast(forecastSalesMultiCreationController);
        forecastSalesMultiCreationController.startOperation();
        xSysLastValue::deleteLast(forecastSalesMultiCreationController);
    }
}
DLX_ForecastSalesMultiCreationService
// DLX_SCMBUG2682_FCConfigActiveMng - 20170605 - Mirco Z
class DLX_ForecastSalesMultiCreationService extends SysOperationServiceBase
{
}

[SysEntryPointAttribute(true)]
public void forecastMultiCreate(DLX_ForecastSalesMultiCreationDC _forecastSalesMultiCreationDC)
{
    DLX_ForecastSalesMultiCreationMng forecastSalesMultiCreationMng = DLX_ForecastSalesMultiCreationMng::construct();
    ;

    if(forecastSalesMultiCreationMng)
    {
        forecastSalesMultiCreationMng.parmForecastSalesMultiCreationDC(_forecastSalesMultiCreationDC);
        forecastSalesMultiCreationMng.run();
    }
}
DLX_ForecastSalesMultiCreationMng
// DLX_SCMBUG2682_FCConfigActiveMng - 20170605 - Mirco Z
class DLX_ForecastSalesMultiCreationMng
{
    DLX_ForecastSalesMultiCreationDC forecastSalesMultiCreationDC;
}

public InventDim findOrCreateDimForecast(InventDim _inventDim)
{
    InventDim           inventDimNew;
    DLX_SCMParameters   scmPar          = DLX_SCMParameters::find();
    ;

    inventDimNew.clear();
    inventDimNew.data(_inventDim);
    inventDimNew.inventSerialId = scmPar.DefaultSerialNumber;
    inventDimNew                = InventDim::findOrCreate(inventDimNew);

    return inventDimNew;
}

public DLX_ForecastSalesMultiCreationDC parmForecastSalesMultiCreationDC(DLX_ForecastSalesMultiCreationDC _forecastSalesMultiCreationDC = forecastSalesMultiCreationDC)
{
    forecastSalesMultiCreationDC = _forecastSalesMultiCreationDC;

    return forecastSalesMultiCreationDC;
}

public void run()
{
    ForecastSales       forecastSales, forecastSalesNew;
    DLX_ForecastToAdd   forecastToAdd;
    RecordInsertList    recordInsertList                    = new RecordInsertList(tableNum(ForecastSales));
    ;

    try
    {
        if (this.parmForecastSalesMultiCreationDC() )
        {
            forecastSales   = forecastSalesMultiCreationDC.parmForecastSales();

            forecastToAdd   = forecastSalesMultiCreationDC.parmForecastToAdd();

            // create new forecast equal to the origin
            while (forecastToAdd > 0 )
            {
                forecastSalesNew.clear();

                forecastSalesNew.ItemId                 = forecastSales.ItemId;
                forecastSalesNew.ModelId                = forecastSales.ModelId;
                forecastSalesNew.StartDate              = forecastSales.StartDate;
                forecastSalesNew.SalesQty               = forecastSales.SalesQty;
                forecastSalesNew.modifiedField(fieldNum(ForecastSales, SalesQty));
                forecastSalesNew.BADesc_dlx             = forecastSales.BADesc_dlx;
                forecastSalesNew.DNA_DLX                = forecastSales.DNA_DLX;
                forecastSalesNew.TrafficLight_dlx       = forecastSales.TrafficLight_dlx;
                forecastSalesNew.ProdEngStatus_dlx      = forecastSales.ProdEngStatus_dlx;
                forecastSalesNew.ItemRouteId            = forecastSales.ItemRouteId;
                forecastSalesNew.Currency               = forecastSales.Currency;
                forecastSalesNew.Active                 = forecastSales.Active;
                forecastSalesNew.Report                 = forecastSales.Report;

                forecastSalesNew.InventDimId            = this.findOrCreateDimForecast(forecastSales.inventDim()).inventDimId;

                recordInsertList.add(forecastSalesNew);

                forecastToAdd--;
            }

            ttsBegin;
            recordInsertList.insertDatabase();
            ttsCommit;
        }
    }
    catch
    {
        throw error("@SYS70403");
    }
}

public static DLX_ForecastSalesMultiCreationMng construct()
{
    return new DLX_ForecastSalesMultiCreationMng();
}
DLX_ForecastSalesMultiCreationUIBuilder
// DLX_SCMBUG2682_FCConfigActiveMng - 20170605 - Mirco Z
class DLX_ForecastSalesMultiCreationUIBuilder extends SysOperationAutomaticUIBuilder
{
    DLX_ForecastSalesMultiCreationDC    forecastSalesMultiCreationDC;

    DialogField                         dlgForecastToAdd;
}

public void getFromDialog()
{
    super();

    if (dlgForecastToAdd.value() == 0 )
        throw error(strFmt("@PRO2252"));
}

public void postBuild()
{
    super();

    forecastSalesMultiCreationDC    = this.dataContractObject() as DLX_ForecastSalesMultiCreationDC;

    dlgForecastToAdd                = this.bindInfo().getDialogField(forecastSalesMultiCreationDC, methodStr(DLX_ForecastSalesMultiCreationDC, parmForecastToAdd));
}