csharp UTC日期

在数据库中以UTC格式存储日期并将其拉出并在本地时间显示。

Get Data
tempJobWash = db.JobWash.Where(x => x.JobWashId == id).Select(x => new
                            {
RequiredDate = x.RequiredDate
   }).ToList().Select(j => new
                            {
                               RequiredDate = (j.ArrivedDate.HasValue ? j.ArrivedDate.Value.ToISOString(DateTimeKind.Utc) : null)
                           }).FirstOrDefault();
Display
<div data-contains="requiredDate" class="formSectionQuarterContainer  smalllivesearch input-group date" id="requiredDate">
        <fieldset>
            <div class="smallFormLabel">
                <span>Required By</span>
                <input value="{{{displayFormattedDate this.info.JobWash.RequiredDate this.dateFormat}}}" class="requiredDateDate" id="requiredDateDate" />
                <input value="{{{displayBPFormattedTime this.info.JobWash.RequiredDate }}}" class="requiredDateTime" id="requiredDateTime" />

            </div>
        </fieldset>
    </div>
Update - js
var requiredDateField = mainDiv.find('input.requiredDateDate').first();
       
        if (requiredDateField.data("DateTimePicker").date() == undefined)
        {
            nitec.notifications.warning("Please provide Required Date");
            return;
        };

        var requiredDate = requiredDateField.data("DateTimePicker").date();
Update - csharp
var jobWashFound = ctx.JobWash.Where(x => x.JobWashId == JobWashDetails.JobWashId).FirstOrDefault();
if (jobWashFound != null)
{       
jobWashFound.WashDate = JobWashDetails.WashDate.Value.ToUniversalTime();
ctx.SaveChanges();
}

csharp 将数组转换为其他类型

convert array to other type.cs
553

Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray();

csharp [CLASS]把手

handlebars
using HandlebarsDotNet;

static void useHanglebars() {
  var createdTemplate = parseDataToTemplate(requestTemplate,
                        new
                        {
                            username = env.username,
                            password = env.password,
                            rowID = rowID,
                            srNum = srNum,
                            srStatus = toStatus
                        }, null)
  } 



 public static string parseDataToTemplate(string templatePath, object dataParameters, params string[] partialPath)
        {
            // We have to load main template
            var loadTemplate = File.ReadAllText(templatePath);

            // If there are partials to be registered
            if (partialPath != null)
            {
                var loadPartial = File.ReadAllText(partialPath[0]);
                Handlebars.RegisterTemplate(partialPath[1], loadPartial);
            }

            var template = Handlebars.Compile(loadTemplate);
            var html = template(dataParameters);

            return html;
        }

csharp 安全地读取文件

即使打开文件也能安全地读取文件

readFilesSafe

    public static string[] WriteSafeReadAllLines(string path)
    {
        using (var f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var sr = new StreamReader(f))
        {
            List<string> file = new List<string>();
            while (!sr.EndOfStream) file.Add(sr.ReadLine());
            return file.ToArray();
        }
    }

csharp XmlSerializer对象

XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(XmlReportNightrush));

//from string
using (TextReader reader = new StringReader(xml))
{
    XmlReportNightrush result = (XmlReportNightrush)serializer.Deserialize(reader);
    return result;
}
//from file
//using (FileStream fileStream = new FileStream(@"name.xml", FileMode.Open))
//{
//    XmlReportNightrush result = (XmlReportNightrush)serializer.Deserialize(fileStream);
//    return result;
//}

csharp VerificarconexiónBD

Verifica si la cadenadeconexiónescorrecta y en caso de error intenta informar del motivo。

verify
public static bool VerifyConnection(string connetionString)
        {
            SqlConnection cnn;
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                cnn.Close();
                return true;
            }
            catch (Exception e)
            {
                if (e.ToString().Contains("No se ha encontrado la ruta de acceso de la red"))
                {
                    MessageBox.Show("Error al conectarse al servidor.", "Error");
                }
                else if(e.ToString().Contains("No se puede abrir la base de datos"))
                {
                    MessageBox.Show("Error al conectarse a la base de datos.", "Error");
                }
                else if (e.ToString().Contains("Error de inicio de sesión del usuario"))
                {
                    MessageBox.Show("Error en el inicio de sesión del usuario.", "Error");
                }
                else
                {
                    MessageBox.Show(e.ToString(), "Error");
                }
                return false;
            }
        }

csharp 钥匙库

create add secret and auth.sh
# Create key vault
az group create --name "keyvault" --location northeurope
az keyvault create --name "ric01-test-keyvault" --resource-group "keyvault" --enable-soft-delete true --location northeurope

# Add a secret
az keyvault secret set --vault-name "ric01-test-keyvault" --name "AppSecret" --value "MySecret"
az keyvault secret show --name "AppSecret" --vault-name "ric01-test-keyvault"

# Assign identity to webapp
az webapp identity assign --name "myapp" --resource-group "keyvault"

# {                                                       
#   "identityIds": null,                                  
#   "principalId": "0bddedc9-xxxx-xxxx-xxxx-77c891a16a18",
#   "tenantId": "f447e5ca-xxxx-xxxx-xxxx-370ff157fdb6",   
#   "type": "SystemAssigned"                              
# }                                                       

# Allow webapp identity to access key vault
az keyvault set-policy --name "ric01-test-keyvault" --object-id "0bddedc9-xxxx-xxxx-xxxx-77c891a16a18" --secret-permissions get list
basic usage.cs
string clientId = "...";
string clientSecret = "...";
string tenantId = "...";
string subscriptionId = "...";

AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud).WithDefaultSubscription(subscriptionId);

\!h KeyVaultClient kvClient = new KeyVaultClient(async (authority, resource, scope) =>
{
    var adCredential = new ClientCredential(clientId, clientSecret);
    var authenticationContext = new AuthenticationContext(authority, null);
    return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
});

// Save a secret
// url == https://<your-unique-keyvault-name>.vault.azure.net/secrets/
\!h await kvClient.SetSecretAsync($"{kvURL}", secretName, secretValue);

// Retrieve a secret
\!h var keyvaultSecret = await kvClient.GetSecretAsync($"{kvURL}", secretName).ConfigureAwait(false);

csharp 服务总线

simple queue operations.cs
// create client
IQueueClient queueClient = new QueueClient("Endpoint=sb://sb-doubledecker-ric-eun.servicebus.windows.net/;SharedAcce...", "myQueue");

// send a message to a queue
var message = new Message(Encoding.UTF8.GetBytes("Message content"));
\!h await queueClient.SendAsync(message);

// receive messages from queue
// Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
    // Maximum number of concurrent calls
    MaxConcurrentCalls = 1,
    // Automatically complete the messages after returning from user callback.
    // False indicates the complete operation is handled by the user callback.
    AutoComplete = false
};

// Register the function that processes messages.
\!h queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

// message handler
static async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
    // sequence
    message.SystemProperties.SequenceNumber;
    
    // body
    Encoding.UTF8.GetString(message.Body);

    // Complete the message so that it is not received again.
    // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
    \!h await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}

// handle exceptions
static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
{
    // encountered exception
    exceptionReceivedEventArgs.Exception;
    
    return Task.CompletedTask;
}

// close client
await queueClient.CloseAsync();
simple topic operations.cs
ITopicClient topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

// send
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
await topicClient.SendAsync(message);

// subscribe
ISubscriptionClient subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
    MaxConcurrentCalls = 1,
    AutoComplete = false
};

// Register the function that processes messages.
subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

static async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
    // Process the message...

    // Complete the message so that it is not received again.
    await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
}

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 延迟销毁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);
    }
}