csharp 次のフレームまで待机するコルーチン

Coroutine.cs
using System.Collections;
using UnityEngine;

IEnumerator Coroutine () {
    yield return new WaitForEndOfFrame ();
    Debug.Log ("次のフレームで実行");
}

void Execute(){
    StartCoroutine(Coroutine());
}

csharp 多态的扩展框架

https://community.dynamics.com/365/financeandoperations/b/daxmusings/posts/ax2012-extension-framework

Code
/*  attribute class */
class IVS_PLTransTypeAttribute extends SysAttribute
{
    IVS_PLTransType transType;
}

public void new(IVS_PLTransType _transType)
{
    super();

    this.parmTransType(_transType);
}

public IVS_PLTransType parmTransType(IVS_PLTransType _transType = transType)
{
    transType = _transType;

    return transType;
}

/* parent class */
abstract class IVS_PLLedgerJournal
{
    IVS_PLNum plNum;
    List      createdJournals;
    boolean   isReversed;
}

public static IVS_PLLedgerJournal construct(IVS_PLNum _plNum, IVS_PLTransType _transType)
{
    IVS_PLLedgerJournal ledgerJournal = SysExtensionAppClassFactory::getClassFromSysAttribute(classStr(IVS_PLLedgerJournal), new IVS_PLTransTypeAttribute(_transType));
    IVS_InterbranchPLLine interbranchPLLine;
    List createdJournals = new List(Types::Class);
    boolean isReversed;

    select firstOnly interbranchPLLine
        where interbranchPLLine.PLNum == _plNum;

    isReversed = interbranchPLLine.Amount < 0 ? true : false;

    ledgerJournal.parmPlNum(_plNum);
    ledgerJournal.parmCreatedJournals(createdJournals);
    ledgerJournal.parmIsReversed(isReversed);

    return ledgerJournal;
}
public abstract List createJournal(boolean _isValidation = false)
{
}

/* child class */
[IVS_PLTransTypeAttribute(IVS_PLTransType::BranchToBranch)]
public class IVS_PLLedgerJournalBranchToBranch extends IVS_PLLedgerJournal
{
}

csharp UniTask示例

UniTaskTest.cs
using UniRx.Async;
using UnityEngine;
public class VanishUniTask : MonoBehaviour {
    public async void Vanish () {
        await UniTask.Delay (1000);
        gameObject.SetActive (false);
    }
}

csharp ZkScanner匹配用户指纹

ZkScanner匹配用户指纹

ZkScanner Matching Users Fingerprint.cs
// Matching fingerprint tempates
// Continuation to https://github.com/zaagan/ZKTecoFingerPrintScanner-Implementation
//

/*
Step 1 : Load the fingerprint templates to the device memory
         1.1 Convert base64 encoded template to byte array
         1.2 Add the template to device memory along with users unique ID
*/
int fID = 1; // Can be the users unique ID
byte[] regTemplate = zkfp.Base64String2Blob("Users fingerprint");
DataHolder.fpInstance.AddRegTemplate(fID, regTemplate);


/* 
Step 2 : Fingerprint matching (After the user has provided his/her fingerprint)
         
         This snippet should be used after line 217 in
         https://github.com/zaagan/ZKTecoFingerPrintScanner-Implementation/blob/master/ZKTecoFingerPrintScanner-Implementation/Controls/FingerPrintControl.cs         
*/

byte[] CapTmp = new byte[2048];
int fid = 0;
int score = 0;
int ret = DataHolder.fpInstance.Identify(CapTmp, ref fid, ref score);
if (fid > 0)
{
   // Match successful.
}
else
{
     // Match failed.
}

csharp 的DeltaTimeで待机

DeltaTime.cs
private float count;
void Update(){
    count += Time.deltaTime;
    
    if(count >= 1.0f){
        count = 0.0f;
        Debug.Log("1秒おきに処理");
    }
}

csharp DO虚拟延迟

Delay.cs
using DG.Tweening;
using UnityEngine;

public class Delay : MonoBehaviour {
    Tween doTween;

    //  1秒後に実行
    public void DelayAction () {
        doTween = DOVirtual.DelayedCall (1f, () => DoSomething ());
    }

    //  キャンセルする(DoSomethingは呼ばれない)
    public void Cancel () {
        doTween.Kill ();
    }

    //  待機をやめて即座に実行する
    public void Immediate () {
        doTween.Complete (true);
    }

    void DoSomething () {
        Debug.Log ("処理");
    }
}

csharp async / awaitの例

VanishAsync.cs
using System.Threading.Tasks;
using UnityEngine;

public class VanishAsync : MonoBehaviour {
    public async void Vanish () {
        await Task.Delay (1000);
        gameObject.SetActive (false);
    }
}

csharp コルーチンの例

VanishCoroutine.cs
using System.Collections;
using UnityEngine;

public class VanishCoroutine : MonoBehaviour {
    public void Vanish () {
        StartCoroutine (WaitVanish ());
    }

    IEnumerator WaitVanish () {
        yield return new WaitForSeconds (1);
        gameObject.SetActive (false);
    }
}

csharp Importar desde CSV

Importacióndelos datos de un CSV a una tabla SQL Server。 <br/> <br/> Programa principal que llama a las funciones pertinentes para realizarlaimportación。

importCSV
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                log.writeLog("info", "-------------------------------------------");
                log.writeLog("info", "Comienza la importacion a BD...");

                string conexionBD = ConfigurationManager.ConnectionStrings["ConexionBD"].ToString();
                //importaciones para la precarga de datos en BD
                string rutaFicheroPaises = ConfigurationManager.AppSettings["RutaFicheroPaises"].ToString();
                Importar.ImportarDesdeCSV(conexionBD, rutaFicheroPaises, "NucPais");

                string rutaFicheroProvincias = ConfigurationManager.AppSettings["RutaFicheroProvincias"].ToString();
                Importar.ImportarDesdeCSV(conexionBD, rutaFicheroProvincias, "NucProvincia");

                string rutaFicheroMunicipios = ConfigurationManager.AppSettings["RutaFicheroMunicipios"].ToString();
                Importar.ImportarDesdeCSV(conexionBD, rutaFicheroMunicipios, "NucMunicipio");

                string rutaFicheroCodigos = ConfigurationManager.AppSettings["RutaFicheroCodigos"].ToString();
                Importar.ImportarDesdeCSV(conexionBD, rutaFicheroCodigos, "Codigo");

                log.writeLog("info", "Fin de la importacion a BD");
                log.writeLog("info", "-------------------------------------------");
            }
            catch (Exception ex)
            {
                log.writeLog("error", "Error al importar. Error: " + ex.ToString());
                log.writeLog("info", "Fin de la importacion a BD");
                log.writeLog("info", "-------------------------------------------");
            }
            
        }
        

public static class Importar
    {
        //public static void ImportarAgente()
        //{
        //    DevExpress.Xpo.XpoDefault.Session = new Session();
        //    PoliciaXPO.Data.PolAgente agente = new PoliciaXPO.Data.PolAgente();
        //    agente.Nombre = "Carlos";
        //    agente.Save();
        //}

        public static void ImportarDesdeCSV(string conexion, string ruta, string tablename)
        {
            var table = new DataTable();
            bool ok = false;

            using (SqlConnection connection = new SqlConnection(conexion))
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                try
                {
                    if (tablename == "NucMunicipio")
                    {
                        table = leerFicheroMunicipios(ruta, conexion);
                        ok = true;
                    }
                    else if (tablename == "NucProvincia")
                    {
                        table = leerFicheroProvincias(ruta);
                        ok = true;
                    }
                    else if (tablename == "NucPais")
                    {
                        table = leerFicheroPaises(ruta);
                        ok = true;
                    }
                    else if (tablename == "Codigo")
                    {
                        table = leerFicheroCodigos(ruta);
                        ok = true;
                    }

                    if (ok)
                    {
                        SqlBulkCopy copy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction);
                        copy.DestinationTableName = tablename;
                        copy.WriteToServer(table);
                        transaction.Commit();
                        log.writeLog("info", "Importacion a la tabla '" + tablename + "' correcta.");
                    }

                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    log.writeLog("error", "Error al importar en la tabla: " + tablename + ". Error: " + ex.ToString());
                }
            }
        }

        //crea una tabla y la rellena con el fichero
        private static DataTable leerFicheroPaises(string filename)
        {
            var table = new DataTable();

            //columnas
            table.Columns.Add("Oid", typeof(Guid));
            table.Columns.Add("DebeAuditar", typeof(Boolean));
            table.Columns.Add("LastUser", typeof(string));
            table.Columns.Add("OwnerUser", typeof(string));
            table.Columns.Add("LastMod", typeof(DateTime));
            table.Columns.Add("CreationDate", typeof(DateTime));
            table.Columns.Add("Codigo", typeof(string));
            table.Columns.Add("Nombre", typeof(string));
            table.Columns.Add("OptimisticLockField", typeof(int));

            //filas
            StreamReader reader = new StreamReader(File.OpenRead(filename), Encoding.Default);
            string line = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                //saltamos los nombres de las columnas
                line = reader.ReadLine();
                if (!String.IsNullOrWhiteSpace(line))
                {
                    string[] values = line.Split(',');
                    table.Rows.Add(Guid.NewGuid().ToString(), true, "Administrador", "Administrador", DateTime.Now.ToString(), DateTime.Now.ToString(), values[0], values[1], false);
                }
            }

            return table;
        }

        private static DataTable leerFicheroProvincias(string filename)
        {
            var table = new DataTable();

            //columnas
            table.Columns.Add("Oid", typeof(Guid));
            table.Columns.Add("DebeAuditar", typeof(Boolean));
            table.Columns.Add("LastUser", typeof(string));
            table.Columns.Add("OwnerUser", typeof(string));
            table.Columns.Add("LastMod", typeof(DateTime));
            table.Columns.Add("CreationDate", typeof(DateTime));
            table.Columns.Add("Codigo", typeof(string));
            table.Columns.Add("Nombre", typeof(string));
            table.Columns.Add("OptimisticLockField", typeof(int));

            //filas
            StreamReader reader = new StreamReader(File.OpenRead(filename), Encoding.Default);
            string line = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                //saltamos los nombres de las columnas
                line = reader.ReadLine();
                if (!String.IsNullOrWhiteSpace(line))
                {
                    string[] values = line.Split(',');
                    table.Rows.Add(Guid.NewGuid().ToString(), true, "Administrador", "Administrador", DateTime.Now.ToString(), DateTime.Now.ToString(), values[0], values[1], false);
                }
            }

            return table;
        }

        private static DataTable leerFicheroMunicipios(string filename, string conexion)
        {
            var table = new DataTable();

            //columnas
            table.Columns.Add("Oid", typeof(Guid));
            table.Columns.Add("DebeAuditar", typeof(Boolean));
            table.Columns.Add("LastUser", typeof(string));
            table.Columns.Add("OwnerUser", typeof(string));
            table.Columns.Add("LastMod", typeof(DateTime));
            table.Columns.Add("CreationDate", typeof(DateTime));
            table.Columns.Add("Codigo", typeof(string));
            table.Columns.Add("Nombre", typeof(string));
            table.Columns.Add("Provincia", typeof(Guid));
            table.Columns.Add("OptimisticLockField", typeof(int));

            //filas
            StreamReader reader = new StreamReader(File.OpenRead(filename), Encoding.Default);
            string line = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                //saltamos los nombres de las columnas
                line = reader.ReadLine();
                if (!String.IsNullOrWhiteSpace(line))
                {
                    string[] values = line.Split(',');
                    Guid guidProv = GetGuidProvincia("07", conexion);

                    table.Rows.Add(Guid.NewGuid().ToString(), true, "Administrador", "Administrador", DateTime.Now.ToString(), DateTime.Now.ToString(), values[0], values[1], guidProv, false);
                }
            }

            return table;
        }

        private static Guid GetGuidProvincia(string codProvincia, string conexion)
        {
            Guid oid = new Guid();
            SqlConnection conn = new SqlConnection(conexion);
            conn.Open();

            SqlCommand command = new SqlCommand("Select Oid from [NucProvincia] Where Codigo = @prov", conn);
            command.Parameters.AddWithValue("@prov", codProvincia);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    oid = (Guid)reader["Oid"];
                }
            }
            return oid;
        }

        private static DataTable leerFicheroCodigos(string filename)
        {
            var table = new DataTable();

            //columnas
            table.Columns.Add("Oid", typeof(Guid));
            table.Columns.Add("DebeAuditar", typeof(Boolean));
            table.Columns.Add("LastUser", typeof(string));
            table.Columns.Add("OwnerUser", typeof(string));
            table.Columns.Add("LastMod", typeof(DateTime));
            table.Columns.Add("CreationDate", typeof(DateTime));
            table.Columns.Add("Grupo", typeof(string));
            table.Columns.Add("Subgrupo", typeof(string));
            table.Columns.Add("Identificador", typeof(string));
            table.Columns.Add("Descripcion", typeof(string));
            table.Columns.Add("OptimisticLockField", typeof(int));

            //filas
            StreamReader reader = new StreamReader(File.OpenRead(filename), Encoding.Default);
            string line = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                //saltamos los nombres de las columnas
                line = reader.ReadLine();
                if (!String.IsNullOrWhiteSpace(line))
                {
                    string[] values = line.Split(',');
                    table.Rows.Add(Guid.NewGuid().ToString(), true, "Administrador", "Administrador", DateTime.Now.ToString(), DateTime.Now.ToString(), values[0], null, values[1], values[2], false);
                }
            }

            return table;
        }
    }

csharp leer excel

leerExcel
using (OleDbConnection conn = new OleDbConnection())
            {
                string fileNameWithPath = @ConfigurationManager.AppSettings["ExcelSIP"].ToString();
                DataTable dt = new DataTable();
                string fileExtension = Path.GetExtension(fileNameWithPath);
                if (fileExtension == ".xls" | fileExtension == ".XLS")
                    conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameWithPath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
                if (fileExtension == ".xlsx" | fileExtension == ".XLSX")
                    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileNameWithPath + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
                using (OleDbCommand comm = new OleDbCommand())
                {
                    comm.CommandText = "Select * from [Hoja1$]";
                    comm.Connection = conn;
                    using (OleDbDataAdapter da = new OleDbDataAdapter())
                    {
                        da.SelectCommand = comm;
                        da.Fill(dt);
                        foreach (DataRow row in dt.Rows)
                        {
                            string oficina = row[6].ToString();
                            if (!listaOficinasEnviadas.Contains(oficina))
                            {
                                crearExcel(oficina);
                                mandarCorreo(oficina);
                                listaOficinasEnviadas.Add(oficina);
                            }
                        }
                    }
                }
            }