text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using NADD.Models; using Rotativa.AspNetCore; namespace NADD.Controllers { public class AvaliacaosController : Controller { private readonly Contexto _context; public AvaliacaosController(Contexto context) { _context = context; } // GET: Avaliacaos public async Task<IActionResult> Index() { var contexto = _context.Avaliacao.Include(a => a.Disciplinas); return View(await contexto.ToListAsync()); } // GET: Avaliacaos/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var avaliacao = await _context.Avaliacao .Include(a => a.Disciplinas) .FirstOrDefaultAsync(m => m.AvaliacaoId == id); if (avaliacao == null) { return NotFound(); } ViewData["Professor"] = _context.Professor.Where(a => a.ProfessorId == avaliacao.ProfessorId).Select(a => a.NomeProfessor).FirstOrDefault(); return View(avaliacao); } //POST [ActionName("AvaliacaoPDF")] public IActionResult VisualizarPDF(long? id) { var aval = _context.Avaliacao.Where(a => a.AvaliacaoId == id).FirstOrDefault(); ViewBag.proftest = _context.Professor.Where(a => a.ProfessorId == aval.ProfessorId).Select(a => a.NomeProfessor).FirstOrDefault(); var avali = _context.Avaliacao.Where(a => a.AvaliacaoId == id).ToList(); return new ViewAsPdf("PDF", avali) { FileName = "relatorio.pdf"} ; } // GET: Avaliacaos/Create public IActionResult Create() { //Disciplina ViewData["DisciplinaId"] = new SelectList(_context.Disciplina, "DisciplinaId", "NomeDisciplina"); //Professores ViewBag.prof = _context.Professor.ToList(); ViewData["ProfessorId"] = new SelectList(ViewBag.prof, "ProfessorId", "NomeProfessor"); //Cursos //IEnumerable<object> curs = ViewBag.curso; ViewBag.curso = _context.Curso.ToList(); ViewData["CursoId"] = new SelectList(ViewBag.curso, "CursoId", "NomeCurso"); return View(); } // POST: Avaliacaos/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("AvaliacaoId,NomeAvaliador,ProfessorId,PeriodoAno,ValorProvaExp,ValorQuestExp,RefBibliograficas,PQuestMultdisc,Eqdistvquest,Ppquestcontext,Observacao,QtyQuestoes,Media,TotValor,DisciplinaId")] Avaliacao avaliacao) { if (ModelState.IsValid) { _context.Add(avaliacao); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["ProfessorId"] = new SelectList(ViewBag.prof, "ProfessorId", "NomeProfessor", avaliacao.ProfessorId); ViewData["DisciplinaId"] = new SelectList(_context.Disciplina, "DisciplinaId", "NomeDisciplina", avaliacao.DisciplinaId); return View(avaliacao); } public JsonResult GetMembers(int id) { return Json(new SelectList(_context.Disciplina.Where(empt => (empt.CursoId == id)), "DisciplinaId", "NomeDisciplina")); } // GET: Avaliacaos/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var avaliacao = await _context.Avaliacao.FindAsync(id); if (avaliacao == null) { return NotFound(); } ViewBag.curso = _context.Curso.ToList(); ViewData["CursoId"] = new SelectList(ViewBag.curso, "CursoId", "NomeCurso"); ViewBag.prof = _context.Professor.ToList(); ViewData["ProfessorId"] = new SelectList(ViewBag.prof, "ProfessorId", "NomeProfessor", avaliacao.ProfessorId); ViewData["DisciplinaId"] = new SelectList(_context.Disciplina, "DisciplinaId", "NomeDisciplina", avaliacao.DisciplinaId); return View(avaliacao); } // POST: Avaliacaos/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("AvaliacaoId,NomeAvaliador,ProfessorId,PeriodoAno,ValorProvaExp,ValorQuestExp,RefBibliograficas,PQuestMultdisc,Eqdistvquest,Ppquestcontext,Observacao,QtyQuestoes,Media,TotValor,DisciplinaId")] Avaliacao avaliacao) { if (id != avaliacao.AvaliacaoId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(avaliacao); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AvaliacaoExists(avaliacao.AvaliacaoId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } //ViewData["CursoId"] = new SelectList(ViewBag.curso, "CursoId", "NomeCurso"); ViewData["ProfessorId"] = new SelectList(ViewBag.prof, "ProfessorId", "NomeProfessor", avaliacao.ProfessorId); ViewData["DisciplinaId"] = new SelectList(_context.Disciplina, "DisciplinaId", "NomeDisciplina", avaliacao.DisciplinaId); return View(avaliacao); } // GET: Avaliacaos/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var avaliacao = await _context.Avaliacao .Include(a => a.Disciplinas) .FirstOrDefaultAsync(m => m.AvaliacaoId == id); if (avaliacao == null) { return NotFound(); } return View(avaliacao); } // POST: Avaliacaos/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var avaliacao = await _context.Avaliacao.FindAsync(id); _context.Avaliacao.Remove(avaliacao); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool AvaliacaoExists(int id) { return _context.Avaliacao.Any(e => e.AvaliacaoId == id); } } }
using System; using StructureMap; namespace MvcApplication.Models.ViewModels { public class ViewModelFactory : IViewModelFactory { #region Constructors public ViewModelFactory(IContainer container) { if(container == null) throw new ArgumentNullException(nameof(container)); this.Container = container; } #endregion #region Properties protected internal virtual IContainer Container { get; } #endregion #region Methods public virtual T Create<T>() { return this.Container.GetInstance<T>(); } #endregion } }
using UnityEngine; using System.Collections; public class monsterbehavior : MonoBehaviour { private int pathnum; public float speed = 1.0F; public bool[] freeze; //the freeze modifier public float[] freezetimer; //the indepent freeze timer for each level public int freezenum; //the freeze modifiers number public float[] poisontimer; //the poision modifier public int poisonpointer; public float poisondmg; private float startTime; private float journeyLength; //private Vector3 thispos; private Vector3 nextpos; public float health; public float fullhealth; maincharacontrol c2 = null; private GameObject gbar; private GameObject hbar; private bool deathflag; // Use this for initialization void Start () { freeze = new bool[8]; freezetimer = new float[8]; for (int i=1;i<=7;i++) //initialize freeze modifier { freeze[i] = false; freezetimer[i] = 0; } poisontimer = new float[151]; for (int i = 1; i <= 150; i++) //initialize poison modifier { poisontimer[i] = 0; } poisonpointer = 0; //health = 80; pathnum = 1; speed = 0.1F; startTime = Time.time; c2 = GameObject.Find("avatar").GetComponent<maincharacontrol>(); gbar = transform.Find("gbar").gameObject; hbar = transform.Find("healthbar").gameObject; deathflag = true; } // Update is called once per frame void Update () { //update health bar gbar.transform.localScale = new Vector3(health / fullhealth*0.8F, 0.101F,0.101F); gbar.transform.position = hbar.transform.position + Vector3.left * (fullhealth-health)/(fullhealth*2)*0.8F*2; //thispos = c2.basevector.transform.position+Vector3.right * c2.pathx[pathnum] * 2 + Vector3.back * c2.pathy[pathnum] * 2; //thispos = transform.position; nextpos = c2.basevector.transform.position+Vector3.right * c2.pathx[pathnum + 1] * 2 + Vector3.back * c2.pathy[pathnum + 1] * 2; //update freeze time freezenum = 0; for (int i=1;i<=7;i++) { if (freeze[i]) { //check its timer freezetimer[i] -= Time.deltaTime; if (freezetimer[i] > 0) { //still slow freezenum += i; } else { //defreeze freeze[i] = false; } } } //update poison timer int ii = 1; poisondmg = 0; while (ii <= poisonpointer) { if (poisontimer[ii] <= 0) { //this poison has ended for (int j = ii; j < poisonpointer; j++) { //move all the poisontimer a little bit forward poisontimer[j] = poisontimer[j + 1]; } poisonpointer--; } else { poisontimer[ii] -= Time.deltaTime; poisondmg += 1; } ii++; } health -= poisondmg * 0.02F; if ((health <= 0)&&(deathflag)) { deathflag = false; c2.monstercount -= 1; c2.endflag = true; c2.totalenergy += 5; c2.curenergy += 5; Destroy(this.gameObject); } if ((Vector3.Distance(transform.position,nextpos)<0.05)) { pathnum += 1; } transform.position = Vector3.MoveTowards(transform.position, nextpos, speed-0.01F*freezenum); //Debug.Log(speed - 0.01F * freezenum); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PreguntaSingleton { private List<Pregunta> nivel1; private List<Pregunta> nivel2; private List<Pregunta> nivel3; private List<Pregunta> nivel1Final; private List<Pregunta> nivel2Final; private List<Pregunta> nivel3Final; private List<Pregunta> elegidas; private static PreguntaSingleton instance; private PreguntaSingleton() { nivel1 = new List<Pregunta>(); nivel2 = new List<Pregunta>(); nivel3 = new List<Pregunta>(); nivel1Final = new List<Pregunta>(); nivel2Final = new List<Pregunta>(); nivel3Final = new List<Pregunta>(); elegidas = new List<Pregunta>(); } public static PreguntaSingleton GetInstance() { if (instance == null) { instance = new PreguntaSingleton(); } return instance; } public Pregunta GetPreguntaNivel1() { return nivel1[(Random.Range(0, nivel1.Count))]; } public Pregunta GetPreguntaNivel2() { return nivel2[(Random.Range(0, nivel2.Count))]; } public Pregunta GetPreguntaNivel3() { return nivel3[(Random.Range(0, nivel3.Count))]; } public void SetPreguntaNivel1(string titulo,string[] respuestas) { nivel1.Add(new Pregunta(titulo,respuestas)); } public void SetPreguntaNivel2(string titulo, string[] respuestas) { nivel2.Add(new Pregunta(titulo, respuestas)); } public void SetPreguntaNivel3(string titulo, string[] respuestas) { nivel3.Add(new Pregunta(titulo, respuestas)); } public Pregunta GetPreguntaNivel1Final() { return nivel1Final[(Random.Range(0, nivel1Final.Count))]; } public Pregunta GetPreguntaNivel2Final() { return nivel2Final[(Random.Range(0, nivel2Final.Count))]; } public Pregunta GetPreguntaNivel3Final() { return nivel3Final[(Random.Range(0, nivel3Final.Count))]; } public void SetPreguntaDefinitiva(Pregunta pregunta) { elegidas.Add(pregunta); } public void SetPreguntaNivel1Final(string titulo, string[] respuestas) { nivel1Final.Add(new Pregunta(titulo, respuestas)); } public void SetPreguntaNivel2Final(string titulo, string[] respuestas) { nivel2Final.Add(new Pregunta(titulo, respuestas)); } public void SetPreguntaNivel3Final(string titulo, string[] respuestas) { nivel3Final.Add(new Pregunta(titulo, respuestas)); } public void ResetRespuestas() { elegidas.Clear(); } public string GetRespuestas() { string temp=""; foreach (Pregunta pregunta in elegidas){ temp += pregunta.ToString()+","; } return temp; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; namespace C1ILDGen { class WatcherSqlClient { #region Fields private SqlConnection sqlConnection; //SQl connection database private String strSrvrName; //Stores the name of the server private String strDBName; //Stores the name of the Database private Boolean bTrustedConnect; //Authenticationm ode private String strUserName; //Stores the name of the user private String strPWD; //Stores user the password private String strConnectString; //Database connection string private int nCommandTimeOut = 0; //Time out value private int nErrorID; //Stores error id private String strErrorQuery; //Stores the error Query private String strErrorMessage; //Stores the error message #endregion #region StaticFields /// <summary> /// No error. /// </summary> public static int nConnectionError = 0; /// <summary> /// The error occured in a query. /// </summary> public static int nQueryError = 1; /// <summary> /// The error occured in a stored procedure. /// </summary> public static int nStoredProcedureError = 1; /// <summary> /// The error occured in a view. /// </summary> public static int nViewError = 2; #endregion #region Events /// <summary> /// Event is launched when an error occurs. To know the type of the error, use the ErrorId property. /// <seealso cref="ErrorId"/> /// </summary> public event EventHandler ErrorOccured; #endregion #region Constructors /// <summary> /// General Constructor for the class. /// The connection string will be generated from the values sent. /// </summary> /// <param name="strServerName">Name of the server</param> /// <param name="strDBName">Name of the database</param> /// <param name="bTrustedConnect">Use Windows Authentification or not</param> /// <remarks>if bTrustedConnection is set to true, strLogin and strPassword are useless</remarks> /// <param name="strUserName">Login value to access the database</param> /// <param name="strPassword">Password value to access the database</param> public WatcherSqlClient(string strServerName, string strDatabaseName, bool bTrustedConnection, string strLogin, string strPassword) { strSrvrName = strServerName; strDBName = strDatabaseName; bTrustedConnect = bTrustedConnection; strUserName = strLogin; strPWD = strPassword; strConnectString = "server=\'" + strServerName + "\';Database=\'" + strDatabaseName + "\';"; if (bTrustedConnection) { strConnectString += "trusted_connection=\'yes\';"; strConnectString += "integrated security=SSPI;persist security info=False;Pooling=true;Max Pool Size=1;Min Pool Size=1"; } else { //strConnectString += "user id=\'" + strLogin + "\';password=\'" + strPassword + "\';Pooling=true;Max Pool Size=1;Min Pool Size=1"; strConnectString = @"Data Source=" + strServerName + ";Initial Catalog=" + strDatabaseName + "; user ID=" + strLogin + ";Password=" + strPassword + ";"; } sqlConnection = new SqlConnection(strConnectString); OpenConnection(); } /// <summary> /// General Constructor for the class. /// The connection string will be generated from the values sent. /// </summary> /// <param name="strServerName">Name of the server</param> /// <param name="strDBName">Name of the database</param> /// <param name="bTrustedConnect">Use Windows Authentification or not</param> /// <remarks>if bTrustedConnection is set to true, strLogin and strPassword are useless</remarks> /// <param name="strUserName">Login value to access the database</param> /// <param name="strPassword">Password value to access the database</param> public WatcherSqlClient(string strServerName, string strDatabaseName, bool bTrustedConnection, string strLogin, string strPassword, string connectionString) { strSrvrName = strServerName; strDBName = strDatabaseName; bTrustedConnect = bTrustedConnection; strUserName = strLogin; strPWD = strPassword; strConnectString = "server=\'" + strServerName + "\';Database=\'" + strDatabaseName + "\';"; if (bTrustedConnection) { strConnectString += connectionString; } else { strConnectString += "user id=\'" + strLogin + "\';password=\'" + strPassword + "\';Pooling=true;Max Pool Size=1;Min Pool Size=1"; } sqlConnection = new SqlConnection(strConnectString); OpenConnection(); } public SqlConnection Connection { get { return sqlConnection; } } /// <summary> /// Constructor for the class. /// The connection string will be created with Windows Authentification. /// </summary> /// <param name="strServerName">Name of the server</param> /// <param name="strDBName">Name of the database</param> public WatcherSqlClient(string strServerName, string strDatabaseName) : this(strServerName, strDatabaseName, true, "", "") { } /// <summary> /// Constructor for the class. /// The connection string will be created using Login/Password authentification /// </summary> /// <param name="strServerName">Name of the server</param> /// <param name="strDBName">Name of the database</param> /// <param name="strUserName">Login value to access the database</param> /// <param name="strPassword">Password value to access the database</param> public WatcherSqlClient(string strServerName, string strDatabaseName, string strLogin, string strPassword) : this(strServerName, strDatabaseName, false, strLogin, strPassword) { } /// <summary> /// Constructor for the class. /// The connection string must be provided. /// </summary> /// <param name="strConnectString">The full connection string to use to access the database</param> public WatcherSqlClient(String strConnectionString) { strSrvrName = @""; strDBName = @""; bTrustedConnect = false; strUserName = ""; strPWD = ""; strConnectString = strConnectionString; sqlConnection = new SqlConnection(strConnectString); // OpenConnection(); } #endregion #region Properties /// <summary> /// Gets the error id when a problems occurs /// </summary> /// <value>Id of the error</value> /// <remarks>ErrorId only makes sense after the ErrorOccured event has been triggered. The value can be tested with the static fields</remarks> //XXX should use enumeration public int ErrorId { get { return nErrorID; } } /// <summary> /// Gets the name of the query or the stored procedure that causes the system to crash /// </summary> /// <value>Id of the error</value> /// <remarks>ErrorQuery only makes sense after an ErrorOccured event of type nQueryError, nStoredProcedureError or nViewError has been triggered.</remarks> public String ErrorQuery { get { return strErrorQuery; } } /// <summary> /// Gets system error message thrown when the system crashed /// </summary> /// <value>System message error</value> /// <remarks>ErrorQuery only makes sense after an ErrorOccured event of type nQueryError, nStoredProcedureError or nViewError has been triggered.</remarks> public String ErrorMessage { get { return strErrorMessage; } } /// <summary> /// Gets or sets the connection string used to connect to the database.</summary> /// <value>Connection string to connect to the database</value> /// <remarks>The connection string should be set at creation time only</remarks> public String ConnectionString { get { return strConnectString; } set { strConnectString = value; } } /// <summary> /// Gets or sets the command time out for all the queries and stored procedures</summary> /// <value>Number of seconds to wait until stopping the execution of the query or stored procedure</value> /// <remarks>The default value is set to 3600</remarks> public int CommandTimeOut { get { return nCommandTimeOut; } set { nCommandTimeOut = value; } } #endregion #region ConnectionMethods /// <summary> /// Open the connection. /// </summary> /// <remarks>The connection is opened on a per use basis, don't bother opening it in the beginning</remarks> public void OpenConnection() { try { //connection has already been created with the strConnectString if (sqlConnection.State == ConnectionState.Closed) sqlConnection.Open(); } catch (Exception e) { SetErrorMessage(nConnectionError, "", e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); throw new Exception(e.Message); } } /// <summary> /// Close the connection. /// </summary> public void CloseConnection() { if (sqlConnection != null) sqlConnection.Close(); } /// <summary> /// Release resources. /// </summary> public void DisposeConnection() { // make sure connection is closed if (sqlConnection != null) { sqlConnection.Dispose(); sqlConnection = null; } } #endregion #region SQLMethods /// <summary> /// Connects to the database and attempts to execute a SELECT query. /// </summary> /// <param name="strQuery">The SELECT query to execute</param> /// <param name="strTableName">The name of the table that will be filled in the returned DataSet</param> /// <returns>A DataSet with the result of the querry</returns> /// <remarks>If a problem occurs, the ErrorOccured event will be triggered and the ErrorId, ErrorQuery, ErrorMessage values will be set</remarks> public DataSet Query(String strQuery, String strTableName) { DataSet dataSet = new DataSet(); try { SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConnection); sqlCmd.CommandTimeout = nCommandTimeOut; SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd); sqlDataAdapter.Fill(dataSet, strTableName); sqlDataAdapter.Dispose(); sqlCmd.Dispose(); } catch (Exception e) { SetErrorMessage(nQueryError, strQuery, e.Message); dataSet.Tables.Add(new DataTable()); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return (dataSet); } public DataSet Query(String strQuery, String tableName, SqlTransaction sqlTrans) { DataSet dataSet = new DataSet(); try { SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConnection); sqlCmd.Transaction = sqlTrans; sqlCmd.CommandTimeout = nCommandTimeOut; SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd); sqlDataAdapter.Fill(dataSet, tableName); sqlDataAdapter.Dispose(); sqlCmd.Dispose(); } catch (Exception e) { SetErrorMessage(nQueryError, strQuery, e.Message); dataSet.Tables.Add(new DataTable()); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return (dataSet); } /// <summary> /// Connects to the database and attempts to execute an INSERT/UPDATE query. /// </summary> /// <param name="strQuery">The INSERT/UPDATE query to execute</param> /// <remarks>If a problem occurs, the ErrorOccured event will be triggered and the ErrorId, ErrorQuery, ErrorMessage values will be set</remarks> public void Query(String strQuery) { try { SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConnection); sqlCmd.CommandTimeout = nCommandTimeOut; sqlCmd.ExecuteNonQuery(); // sqlCmd.Dispose(); } catch (Exception e) { SetErrorMessage(nQueryError, strQuery, e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } } /// <summary> /// Connects to the database and attempts to execute an INSERT/UPDATE query. /// </summary> /// <param name="strQuery">The INSERT/UPDATE query to execute</param> /// <remarks>If a problem occurs, the ErrorOccured event will be triggered and the ErrorId, ErrorQuery, ErrorMessage values will be set</remarks> public void Query(String strQuery, SqlTransaction sqlTrans) { try { SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConnection); sqlCmd.CommandTimeout = nCommandTimeOut; sqlCmd.Transaction = sqlTrans; sqlCmd.ExecuteNonQuery(); sqlCmd.Dispose(); } catch (Exception e) { SetErrorMessage(nQueryError, strQuery, e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } } /// <summary> /// Connects to the database and attempts to execute a COUNT query. /// </summary> /// <param name="strQuery">The COUNT query to execute</param> /// <remarks>If a problem occurs, the ErrorOccured event will be triggered and the ErrorId, ErrorQuery, ErrorMessage values will be set</remarks> public int CountQuery(String strQuery, SqlTransaction sqlTrans) { int nCount = -1; try { SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConnection); sqlCmd.CommandTimeout = nCommandTimeOut; sqlCmd.Transaction = sqlTrans; object oCount = sqlCmd.ExecuteScalar(); if (oCount != null) nCount = (int)oCount; sqlCmd.Dispose(); } catch (Exception e) { SetErrorMessage(nQueryError, strQuery, e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return (nCount); } #endregion #region StoredProcedureMethods /// <summary> /// Create command object used to call stored procedure. /// </summary> /// <param name="strProcedureName">Name of stored procedure.</param> /// <param name="parameters">Parameters for stored procedure.</param> /// <returns>SqlCommand object.</returns> private SqlCommand CreateProcedureCommand(string strProcedureName, SqlParameter[] parameters) { SqlCommand sqlCmd = new SqlCommand(strProcedureName, sqlConnection); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.CommandTimeout = nCommandTimeOut; // add proc parameters if (parameters != null) { foreach (SqlParameter sqlParameter in parameters) sqlCmd.Parameters.Add(sqlParameter); } // return param sqlCmd.Parameters.Add( new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return sqlCmd; } /// <summary> /// Run stored procedure. /// </summary> /// <param name="strProcedureName">Name of the stored procedure.</param> /// <returns>Stored procedure return value.</returns> public int RunStoredProcedure(string strProcedureName) { int nRetVal = -1; try { SqlCommand sqlCmd = CreateProcedureCommand(strProcedureName, null); sqlCmd.ExecuteNonQuery(); nRetVal = (int)sqlCmd.Parameters["ReturnValue"].Value; } catch (Exception e) { SetErrorMessage(nStoredProcedureError, strProcedureName, e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return (nRetVal); } /// <summary> /// Run stored procedure. /// </summary> /// <param name="strProcedureName">Name of the stored procedure.</param> /// <param name="parameters">Stored procedure parameters.</param> /// <returns>Stored procedure return value.</returns> public int RunStoredProcedure(string strProcedureName, SqlParameter[] parameters, SqlTransaction sqlTrans) { int nRetVal = -1; try { SqlCommand sqlCmd = CreateProcedureCommand(strProcedureName, parameters); if (sqlTrans != null) sqlCmd.Transaction = sqlTrans; sqlCmd.ExecuteNonQuery(); nRetVal = (int)sqlCmd.Parameters["ReturnValue"].Value; } catch (Exception e) { SetErrorMessage(nStoredProcedureError, strProcedureName, e.Message); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return nRetVal; } /// <summary> /// Run stored procedure. /// </summary> /// <param name="strProcedureName">Name of the stored procedure.</param> /// <param name="dataSet">Return result of procedure.</param> /// <returns>Stored procedure return value.</returns> public int RunStoredProcedure(string strProcedureName, out DataSet dataSet) { int nRetVal = -1; dataSet = new DataSet(); try { SqlCommand sqlCmd = CreateProcedureCommand(strProcedureName, null); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd); sqlDataAdapter.Fill(dataSet); nRetVal = (int)sqlCmd.Parameters["ReturnValue"].Value; } catch (Exception e) { SetErrorMessage(nStoredProcedureError, strProcedureName, e.Message); dataSet.Tables.Add(new DataTable()); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return nRetVal; } /// <summary> /// Run stored procedure. /// </summary> /// <param name="strProcedureName">Name of the stored procedure.</param> /// <param name="parameters">Stored procedure parameters.</param> /// <param name="dataSet">Return result of procedure.</param> /// <returns>Stored procedure return value.</returns> public int RunStoredProcedure(string strProcedureName, SqlParameter[] parameters, out DataSet dataSet) { int nRetVal = -1; dataSet = new DataSet(); try { SqlCommand sqlCmd = CreateProcedureCommand(strProcedureName, parameters); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd); sqlDataAdapter.Fill(dataSet); nRetVal = (int)sqlCmd.Parameters["ReturnValue"].Value; } catch (Exception e) { SetErrorMessage(nStoredProcedureError, strProcedureName, e.Message); dataSet.Tables.Add(new DataTable()); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return nRetVal; } /// <summary> /// Create input parameter. /// </summary> /// <param name="strParameterName">Name of param.</param> /// <param name="parameterType">Param type.</param> /// <param name="nParameterSize">Param size.</param> /// <param name="parameterValue">Param value.</param> /// <returns>New input parameter.</returns> public SqlParameter CreateInParameter(string strParameterName, SqlDbType parameterType, int nParameterSize, object parameterValue) { return CreateParameter(strParameterName, parameterType, nParameterSize, ParameterDirection.Input, parameterValue); } /// <summary> /// Create output param. /// </summary> /// <param name="strParameterName">Name of param.</param> /// <param name="parameterType">Param type.</param> /// <param name="nParameterSize">Param size.</param> /// <returns>New output parameter.</returns> public SqlParameter CreateOutParameter(string strParameterName, SqlDbType parameterType, int nParameterSize) { return CreateParameter(strParameterName, parameterType, nParameterSize, ParameterDirection.Output, null); } /// <summary> /// Create return param. /// </summary> /// <returns>New return parameter.</returns> public SqlParameter CreateReturnParameter() { return CreateParameter("returnname", SqlDbType.Int, 4, ParameterDirection.ReturnValue, null); } /// <summary> /// Make stored procedure parameter. /// </summary> /// <param name="strParameterName">Name of param.</param> /// <param name="parameterType">Param type.</param> /// <param name="nParameterSize">Param size.</param> /// <param name="Direction">Param direction.</param> /// <param name="parameterValue">Param value.</param> /// <returns>New parameter.</returns> public SqlParameter CreateParameter(string strParameterName, SqlDbType parameterType, Int32 nParameterSize, ParameterDirection Direction, object parameterValue) { SqlParameter sqlParameter; if (nParameterSize > 0) { sqlParameter = new SqlParameter(strParameterName, parameterType, nParameterSize); } else { sqlParameter = new SqlParameter(strParameterName, parameterType); } sqlParameter.Direction = Direction; if (!(Direction == ParameterDirection.Output && parameterValue == null)) { sqlParameter.Value = parameterValue; } return sqlParameter; } #endregion #region ViewMethods /// <summary> /// Run view. /// </summary> /// <param name="strViewName">Name of the view.</param> /// <param name="dataSet">Return result of view.</param> /// <returns>View return value.</returns> public int RunView(string strViewName, out DataSet dataSet) { int nRetVal = -1; dataSet = new DataSet(); try { SqlCommand sqlCmd = CreateViewCommand(strViewName); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd); sqlDataAdapter.Fill(dataSet); nRetVal = (int)sqlCmd.Parameters["ReturnValue"].Value; } catch (Exception e) { SetErrorMessage(nViewError, strViewName, e.Message); dataSet.Tables.Add(new DataTable()); if (ErrorOccured != null) ErrorOccured(this, new EventArgs()); } return nRetVal; } /// <summary> /// Create command object used to call view. /// </summary> /// <param name="viewName">Name of view.</param> /// <returns>SqlCommand object.</returns> private SqlCommand CreateViewCommand(string strViewName) { SqlCommand sqlCmd = new SqlCommand(strViewName, sqlConnection); //sqlCmd.CommandType = CommandType.TableDirect; return sqlCmd; } #endregion /// <summary> /// Sets the error id,error queryand error message /// </summary> /// <param name="nErrorID">Error id</param> /// <param name="strErrorQuery">Query failed</param> /// <param name="strErrorMessage">Error message</param> void SetErrorMessage(int nErrorId, string strErrQuery, string strErrMessage) { nErrorID = nErrorId; strErrorQuery = strErrQuery; strErrorMessage = strErrMessage; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using MyDir; public class CharacterController{ private GameObject character; private Move move; private ClickOp click; private bool is_devil; private bool is_on_boat = false; private CoastController coast; // Use this for initialization public CharacterController(string name){ if(name == "priest"){ character = Object.Instantiate(Resources.Load("Prefab/Priest",typeof(GameObject)),Vector3.zero,Quaternion.identity,null) as GameObject; is_devil = false; }else if(name == "devil"){ character = Object.Instantiate(Resources.Load("Prefab/Devil",typeof(GameObject)),Vector3.zero,Quaternion.identity,null) as GameObject; is_devil = true; } move = character.AddComponent(typeof(Move))as Move; click = character.AddComponent(typeof(ClickOp))as ClickOp; click.setController(this); } public void setName(string _name){ character.name = _name; } public string getName(){ return character.name; } public bool Is_Devil(){ return is_devil; } public bool Is_On_Boat(){ return is_on_boat; } public void setPos(Vector3 pos){ character.transform.position = pos; } public Vector3 getPos(){ return character.transform.position; } public void Move_to_pos(Vector3 pos){ move.setDest (pos); } public CoastController getCoastController() { return coast; } public void getOnBoat(BoatController boatCtrl) { coast = null; character.transform.parent = boatCtrl.getGameobj().transform; is_on_boat = true; } public void getOnCoast(CoastController coastCtrl) { coast = coastCtrl; character.transform.parent = null; is_on_boat = false; } public void reset() { move.reset (); coast = (Director.getInstace ().current as FirstController).fromCoast; getOnCoast (coast); setPos (coast.getEmptyPos()); coast.getOnCoast (this); } void Start () { } // Update is called once per frame void Update () { } }
using System; using System.Runtime.InteropServices; namespace Mixed_Mode_Calling_App { public class Program { // Replace the file path shown here with the // file path on your computer. For .NET Core, the typical (default) path // for a 64-bit DLL might look like this: // C:\Users\username\source\repos\Mixed_Mode_Debugging\x64\Debug\Mixed_Mode_Debugging.dll // Here, we show a typical path for a DLL targeting the **x86** option. [DllImport(@"D:\Projects\VS\Mixed_Mode_Debugging\x64\Debug\Mixed_Mode_Debugging.dll", EntryPoint = "mixed_mode_multiply", CallingConvention = CallingConvention.StdCall)] public static extern int Multiply(int x, int y); public static void Main(string[] args) { int result = Multiply(7, 7); Console.WriteLine("The answer is {0}", result); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OOPPrinciplesPart1 { interface IComment { string Comment { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Model.Security.MembershipManagement; using Model.DataEntity; using Model.Locale; using Business.Helper; using Uxnet.Web.Module.Common; namespace eIVOGo.Module.SAM { public partial class SocialWelfareAgenciesManger : System.Web.UI.UserControl,IPostBackEventHandler { public class dataType { public int OrgID; public string OrgCode; public string OrgName; public string OrgAddr; public string OrgPhone; public int? OrgCurrentLevel; public string OrgStatus; } protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) { this.gvEntity.PreRender += new EventHandler(this.gvEntity_PreRender); } private void getData() { using (UserManager um = new UserManager()) { var data = from oc in um.GetTable<OrganizationCategory>() where (oc.CategoryID == (int)Naming.CategoryID.COMP_WELFARE && oc.Organization.OrganizationStatus != null) select new dataType { OrgID = oc.Organization.CompanyID, OrgCode = oc.Organization.ReceiptNo, OrgName = oc.Organization.CompanyName, OrgAddr = oc.Organization.Addr, OrgPhone = oc.Organization.Phone, OrgCurrentLevel=oc.Organization.OrganizationStatus.CurrentLevel, OrgStatus=oc.Organization.OrganizationStatus.LevelExpression.Description }; if (data.Count() > 0) { int count = data.Count(); this.lblError.Visible = false; this.gvEntity.PageIndex = PagingControl.GetCurrentPageIndex(this.gvEntity, 0); this.gvEntity.DataSource = data.ToList(); this.gvEntity.DataBind(); PagingControl paging = (PagingControl)this.gvEntity.BottomPagerRow.Cells[0].FindControl("pagingIndex"); paging.RecordCount = count; paging.CurrentPageIndex = this.gvEntity.PageIndex; } else { this.lblError.Text = "尚未建立社福機構資料!!"; this.lblError.Visible = true; this.gvEntity.DataSource = null; this.gvEntity.DataBind(); } } } #region "Gridview Event" void gvEntity_PreRender(object sender, EventArgs e) { getData(); } #endregion protected void btnAdd_Click(object sender, EventArgs e) { Response.Redirect("modifySocialWelfareAgencies.aspx"); } #region IPostBackEventHandler Members public void RaisePostBackEvent(string eventArgument) { string OrgID = ""; if (eventArgument.StartsWith("U:")) { OrgID = eventArgument.Substring(2).Trim(); Response.Redirect("modifySocialWelfareAgencies.aspx?PID=" + OrgID); } else if (eventArgument.StartsWith("D:")) { OrgID = eventArgument.Substring(2).Trim(); doEnableOrDisable(int.Parse(OrgID)); } } private void doEnableOrDisable(int id) { using (UserManager mgr = new UserManager()) { int? clevel = mgr.GetTable<OrganizationStatus>().Where(os => os.CompanyID == id).FirstOrDefault().CurrentLevel; if (clevel == (int)Naming.MemberStatusDefinition.Checked) { mgr.GetTable<OrganizationStatus>().Where(os => os.CompanyID == id).FirstOrDefault().CurrentLevel = (int)Naming.MemberStatusDefinition.Mark_To_Delete; } else if (clevel == (int)Naming.MemberStatusDefinition.Mark_To_Delete) { mgr.GetTable<OrganizationStatus>().Where(os => os.CompanyID == id).FirstOrDefault().CurrentLevel = (int)Naming.MemberStatusDefinition.Checked; } mgr.SubmitChanges(); getData(); } } #endregion } }
using System; using System.Collections.Generic; namespace Windore.Settings.Base { public interface ISettingsManager { object GetSettingValue(string category, string settingName); void SetSettingValue(string category, string settingName, object newValue); void SetSettingValueFromString(string category, string settingName, string stringValue); string GetSettingValueAsString(string category, string settingName) ; bool CheckStringValueForSetting(string category, string settingName, string stringValue, out string message); Type GetSettingType(string category, string settingName); Dictionary<string, List<string>> GetSettings(); } }
using System; using System.ComponentModel; using System.Linq; using DynamicPermission.AspNetCore.Context; using DynamicPermission.AspNetCore.Entities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; namespace DynamicPermission.AspNetCore.Controllers { [AllowAnonymous] [DisplayName("AppSettingController(just for show)")] public class AppSettingController : Controller { private readonly AppDbContext _dbContext; private readonly IMemoryCache _memoryCache; public AppSettingController(AppDbContext dbContext, IMemoryCache memoryCache) { _dbContext = dbContext; _memoryCache = memoryCache; } [DisplayName("Index")] public IActionResult Index() { var model = _dbContext.AppSettings.ToList(); return View(model); } [HttpGet] [DisplayName("RoleValidationGuid")] public IActionResult RoleValidationGuid() { var roleValidationGuidSiteSetting = _dbContext.AppSettings.FirstOrDefault(t => t.Key == "RoleValidationGuid"); return View(roleValidationGuidSiteSetting); } [HttpGet] [DisplayName("GenerateNewGuid")] public IActionResult GenerateNewGuid() { var roleValidationGuidSiteSetting = _dbContext.AppSettings.FirstOrDefault(t => t.Key == "RoleValidationGuid"); if (roleValidationGuidSiteSetting == null) { _dbContext.AppSettings.Add(new AppSetting { Key = "RoleValidationGuid", Value = Guid.NewGuid().ToString(), LastTimeChanged = DateTime.Now }); } else { roleValidationGuidSiteSetting.Value = Guid.NewGuid().ToString(); roleValidationGuidSiteSetting.LastTimeChanged = DateTime.Now; _dbContext.Update(roleValidationGuidSiteSetting); } _dbContext.SaveChanges(); _memoryCache.Remove("RoleValidationGuid"); return RedirectToAction("Index"); } } }
// ReSharper disable InconsistentNaming // ReSharper disable once CheckNamespace // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace Tests.TestClasses1 { public enum PubEnum { A, B, C } internal enum IntEnum { A, B, C } public class PubC { public class PubNCofPub { } internal class IntNCofPub { } private class PriNCofPub { } } internal class IntC { public class PubNCofInt { } internal class IntNCofInt { } private class PriNCofInt { } } public static class PubStC { } internal static class IntStC { } public abstract class PubAC { } internal abstract class IntAC { } public sealed class PubSeC { } internal sealed class IntSeC { } public interface IPub { } internal interface IInt { } public struct PubStruct { } internal struct IntStruct { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace Tai_Shi_Xuan_Ji_Yi.ChartControl { public class SeriesPointCollection : ObservableCollection<SeriesPoint> { #region Variables SeriesPoint ptMaxByX = null, ptMaxByY = null; #endregion #region Constructors //public SeriesPointCollection() //{ // points = new List<SeriesPoint>(); //} #endregion #region public SeriesPoint MaxByX { get { return ptMaxByX; } } public SeriesPoint MaxByY { get { return ptMaxByY; } } #endregion #region Methods public double MaxPointValue() { return this.Max<SeriesPoint>(t => t.Value); } private static int SortCompare(SeriesPoint Arg1, SeriesPoint Arg2) { if (Arg1.Value < Arg2.Value) return -1; else if (Arg1.Value > Arg2.Value) return 1; else return 0; } #endregion #region Events protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { SeriesPoint pt = e.NewItems[0] as SeriesPoint; if (e.Action == NotifyCollectionChangedAction.Add) { if(ptMaxByX == null) { ptMaxByX = pt; } else { if(ptMaxByX.DateTimeValue != null) { if (ptMaxByX.DateTimeValue < pt.DateTimeValue) ptMaxByX = pt; } else { if (ptMaxByX.Argument < pt.Argument) ptMaxByX = pt; } } if (ptMaxByY == null) ptMaxByY = pt; else { if (ptMaxByY.Value < pt.Value) ptMaxByY = pt; } } else { ptMaxByX = this.OrderByDescending(t => t.Argument).First(); ptMaxByY = this.OrderByDescending(t => t.Value).First(); } base.OnCollectionChanged(e); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmsChapter1 { public class _1_1_14_Lg { /* * Write a static method lg() that takes an int value N as argument and returns the largest int not larger than the base-2 logarithm of N . Do not use Math . */ // I used divide because I do not want to use times method which may cause overflow at the last step. public int FindLg(int input) { int i = input; int res = 0; while (i > 0) { i /= 2; res++; } return res-1; // if input is 0, there is no valid res. reutnr -1 is fine. } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PortalTraveller : MonoBehaviour { public Vector3 previousOffsetFromPortal; public virtual void Teleport(Transform originPortal, Transform destPortal, Vector3 pos, Quaternion rot) { transform.position = pos; transform.rotation = rot; } public virtual void EnterPortalThreshold() { } public virtual void ExitPortalThreshold() { } }
namespace HackHW2018.FSM.Player { public static class PlayerIndex { public static readonly string PlayerOne = "player-one"; public static readonly string PlayerTwo = "player-two"; public static readonly string PlayerThree = "player-three"; public static readonly string PlayerFour = "player-four"; public static readonly string[] Ids = new string[] { PlayerOne, PlayerTwo, PlayerThree, PlayerFour }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Shooter { class CommonOptions { static List<FileInfo> _maps; public static string AskInput(string name, int length, int x, int y) { OptionTextbox t = new OptionTextbox(name, length); Menu m = new Menu("", t, new Option("-"), new Option("Create game", 0), new Option("Back", 1)); switch (m.Start(x, y)) { case 0: m.Clear(); return t.Text; default: m.Clear(); return null; } } public static IScreen StartNewGame(bool story, int players, Map map) { OptionTextbox[] textboxes = new OptionTextbox[players]; for (int i = 0; i < players; i++) textboxes[i] = new OptionTextbox("Player " + (i + 1), 12); Menu m = new Menu(new Option("-"), new Option("Start Game", 0), new Option("Back", 1)); m.Options.InsertRange(0, textboxes); switch (m.Start(35, 7)) { case 0: for (int i = 0; i < players; i++) if (string.IsNullOrEmpty(textboxes[i].Text)) { m.Clear(); Menu msub = new Menu(Label.CreateLabelArrayFromText( "\nYou have to specify a name in\norder to start a new game.")); msub.Start(-1, 20); msub.Clear(); return StartNewGame(story, players, map); } Game g = new Game(); for (int i = 0; i < players; i++) { Player p = new Player(i); p.Name = textboxes[i].Text; g.Players[i] = p; } for (int i = players; i < 4; i++) g.Players[i] = null; if (story) g.LoadStoryMode(); else g.Map = map; g.CustomGame = !story; if (Game.Network != null) { Game.Network.Dispose(); Game.Network = null; } return new Shop(g); } m.Clear(); return null; } public static Map SelectMap(int x, int players) { int offset = 0, option = 0; string savePath = "maps"; if (!Directory.Exists(savePath)) return null; IOption[] options = new IOption[14]; if (_maps == null) _maps = new List<FileInfo>(); else _maps.Clear(); _maps.AddRange(new DirectoryInfo(savePath).GetFiles("*.map")); for (int i = 0; i < _maps.Count; i++) using (StreamReader r = new StreamReader(_maps[i].OpenRead())) { string raw = r.ReadToEnd(); if (players == 1 && raw.IndexOf('E') < 0) { _maps.RemoveAt(i); i--; } else if (raw.IndexOf(players.ToString()) < 0) { _maps.RemoveAt(i); i--; } } OptionDual d = new OptionDual(); d.FirstValue = -2; d.SecondValue = -1; Menu m; options[0] = d; options[1] = new Option("-"); options[12] = new Option("-"); options[13] = new Option(" Back ", _maps.Count); do { if (option == -2) offset--; else if (option == -1) offset++; if (offset > 0) d.FirstButton = "Previous"; else d.FirstButton = "-"; if (offset < _maps.Count / 10) d.SecondButton = "Next"; else d.SecondButton = "-"; for (int i = 0; i < 10 && (i + offset * 10) < _maps.Count; i++) { string name = _maps[i + offset * 10].Name.Replace(".map", ""); if (players > 1) { using (StreamReader r = new StreamReader(_maps[i + offset * 10].OpenRead())) { string raw = r.ReadToEnd(); if (raw.IndexOf('E') >= 0) name += " (co-op)"; else name += " (vs)"; } } options[i + 2] = new Option(name, i + offset * 10); } if (offset == _maps.Count / 10) for (int i = (_maps.Count % 10); i < 10; i++) options[i + 2] = new Option("-", 0); m = new Menu(options); m.Clear(); } while ((option = m.Start(x, 3)) < 0); m.Clear(); if (option == _maps.Count) return null; else return new Map(_maps[option].FullName); } public static void DisplayConnectionError(object reason) { string errReason = ""; if (reason is Exception) errReason = (reason as Exception).Message; else errReason = (string)reason; Menu m = new Menu("Connection lost", Label.CreateLabelArrayFromText("Connection to host has ended. The error message was:\n " + errReason)); m.Start(-1, 5, false); } } }
using FeelingGoodApp.Models; using FeelingGoodApp.Services.Models; using System.Threading.Tasks; namespace FeelingGoodApp.Services { public interface INutritionService { Task<UserNutrition> GetName(); Task<NutritionFactsResults> GetFieldsAsync(string item_name); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using ERP_BLL; using ERP_MODEL; using System.Web.Http; namespace ERP_Api.Controllers { public class DepartmentApiController : ApiController { DepartmentBll blldePart = new DepartmentBll(); [HttpPost] public int AddDepart(DepartmentModel department) { return blldePart.AddDepart(department); } [HttpDelete] /// <summary> /// 删除部门 /// </summary> /// <returns></returns> public int DelDepart(int Departid) { return blldePart.DelDepart(Departid); } [HttpPut] /// <summary> /// 修改部门 /// </summary> /// <param name="Roleid"></param> /// <returns></returns> public int UpdRole(DepartmentModel department) { return blldePart.UpdRole(department); } [HttpGet] /// <summary> /// 显示部门 /// </summary> /// <returns></returns> public List<DepartmentModel> ShowRole() { return blldePart.ShowRole(); } } }
/* The MIT License (MIT) Copyright (c) 2015 Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Script.Serialization; // The following using statements were added for this sample. using System.Collections.Concurrent; using TodoListService.Models; using System.Security.Claims; using System.Threading.Tasks; using System.Globalization; using System.Configuration; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.Web; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Threading; using TodoListService.DAL; using System.Web.Http.Cors; namespace TodoListService.Controllers { [Authorize] [EnableCors(origins: "*", headers: "*", methods: "*")] public class TodoListController : ApiController { // // The Client ID is used by the application to uniquely identify itself to Azure AD. // The App Key is a credential used by the application to authenticate to Azure AD. // The Tenant is the name of the Azure AD tenant in which this application is registered. // The AAD Instance is the instance of Azure, for example public Azure or Azure China. // The Authority is the sign-in URL of the tenant. // // // The Client ID is used by the application to uniquely identify itself to Azure AD. // The client secret is the credentials for the WebServer Client private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; private static string authority = ConfigurationManager.AppSettings["ida:Authority"]; // Base address of the WebAPI private static string OBOWebAPIBase = ConfigurationManager.AppSettings["ida:OBOWebAPIBase"]; // // To Do items list for all users. Since the list is stored in memory, it will go away if the service is cycled. // private TodoListServiceContext db = new TodoListServiceContext(); // Error Constants const String SERVICE_UNAVAILABLE = "temporarily_unavailable"; // GET api/todolist public IEnumerable<TodoItem> Get() { // // The Scope claim tells you what permissions the client application has in the service. // In this case we look for a scope value of user_impersonation, or full access to the service as the user. var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope"); if (scopeClaim == null || (!scopeClaim.Value.Contains("user_impersonation"))) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" }); } // A user's To Do list is keyed off of the NameIdentifier claim, which contains an immutable, unique identifier for the user. Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name); return from todo in db.TodoItems where todo.Owner == subject.Value select todo; } // POST api/todolist public async Task Post(TodoItem todo) { if (!ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation")) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" }); } // // Call the WebAPIOBO On Behalf Of the user who called the To Do list web API. // string augmentedTitle = null; string custommessage = await CallGraphAPIOnBehalfOfUser(); if (custommessage != null) { augmentedTitle = String.Format("{0}, Message: {1}", todo.Title, custommessage); } else { augmentedTitle = todo.Title; } if (null != todo && !string.IsNullOrWhiteSpace(todo.Title)) { db.TodoItems.Add(new TodoItem { Title = augmentedTitle, Owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value }); db.SaveChanges(); } } public static async Task<string> CallGraphAPIOnBehalfOfUser() { string accessToken = null; AuthenticationResult result = null; AuthenticationContext authContext = null; HttpClient httpClient = new HttpClient(); string custommessage = ""; // // Use ADAL to get a token On Behalf Of the current user. To do this we will need: // The Resource ID of the service we want to call. // The current user's access token, from the current request's authorization header. // The credentials of this application. // The username (UPN or email) of the user calling the API // ClientCredential clientCred = new ClientCredential(clientId, clientSecret); var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value; string userAccessToken = bootstrapContext.Token; UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName); string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value; authContext = new AuthenticationContext(authority, false); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = await authContext.AcquireTokenAsync(OBOWebAPIBase, clientCred, userAssertion); //result = await authContext.AcquireTokenAsync(...); accessToken = result.AccessToken; } catch (AdalException ex) { if (ex.ErrorCode == "temporarily_unavailable") { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); if (accessToken == null) { // An unexpected error occurred. return (null); } // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // Call the WebAPIOBO. HttpResponseMessage response = await httpClient.GetAsync(OBOWebAPIBase + "/api/WebAPIOBO"); if (response.IsSuccessStatusCode) { // Read the response and databind to the GridView to display To Do items. string s = await response.Content.ReadAsStringAsync(); JavaScriptSerializer serializer = new JavaScriptSerializer(); custommessage = serializer.Deserialize<string>(s); return custommessage; } else { custommessage = "Unsuccessful OBO operation : " + response.ReasonPhrase; } // An unexpected error occurred calling the Graph API. Return a null profile. return (null); } } }
namespace TrafficControl.DAL.RestSharp { public class UpdateUserInfoDTO { public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public bool EmailNotification { get; set; } public bool SMSNotification { get; set; } } }
using System.Threading; using System.Threading.Tasks; using LubyClocker.CrossCuting.Shared; using LubyClocker.CrossCuting.Shared.Exceptions; using LubyClocker.Infra.Data.Context; using MediatR; namespace LubyClocker.Application.BoundedContexts.Developers.Commands.Delete { public class DeleteDeveloperCommandHandler : IRequestHandler<DeleteDeveloperCommand, bool> { private readonly LubyClockerContext _context; public DeleteDeveloperCommandHandler(LubyClockerContext context) { _context = context; } public async Task<bool> Handle(DeleteDeveloperCommand request, CancellationToken cancellationToken) { var entity = await _context.Developers.FindAsync(request.Id); if (entity == null) { throw new InvalidRequestException(MainResource.ResourceNotExists); } _context.Developers.Remove(entity); await _context.SaveChangesAsync(cancellationToken); return true; } } }
using System; using PurificationPioneer.Scriptable; using PurificationPioneer.Utility; using UnityEngine; using UnityEngine.UI; namespace PurificationPioneer.Script { public class HeroOptionUi : MonoBehaviour { public Image heroIcon; public Button clickBtn; public void InitValues(HeroConfigAsset heroConfig, Action<int> onClick) { this.heroIcon.sprite = heroConfig.icon; clickBtn.onClick.AddListener(()=>onClick(heroConfig.characterId)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Linq; using System.Diagnostics; using System.Threading; namespace CREA2014 { public class TestBlock : Block { public TestBlock() : base(null) { } public TestBlock(long _index) : base(null) { index = _index; } private long index; public override long Index { get { return index; } } public override Creahash PrevId { get { return null; } } public override Difficulty<Creahash> Difficulty { get { return null; } } public override Transaction[] Transactions { get { return new Transaction[] { }; } } public const string guidString = "4c5f058d31606b4d9830bc713f6162f0"; public override Guid Guid { get { return new Guid(guidString); } } protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo { get { return (msrw) => new MainDataInfomation[]{ new MainDataInfomation(typeof(long), () => index, (o) => index = (long)o), }; } } } public static class BlockChainTest { //UtxoDBのテスト public static void Test1() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoDB utxodb = new UtxoDB(basepath); string path = utxodb.GetPath(); if (File.Exists(path)) File.Delete(path); utxodb.Open(); byte[] emptyBytes = utxodb.GetUtxoData(0); if (emptyBytes.Length != 0) throw new Exception("test1_1"); byte[] utxoBytesIn1 = new byte[1024]; for (int i = 0; i < utxoBytesIn1.Length; i++) utxoBytesIn1[i] = (byte)256.RandomNum(); int overallLangth = utxoBytesIn1.Length + 4; long position1 = utxodb.AddUtxoData(utxoBytesIn1); if (position1 != 0) throw new Exception("test1_2"); long position2 = utxodb.AddUtxoData(utxoBytesIn1); if (position2 != overallLangth) throw new Exception("test1_3"); byte[] utxoBytesOut1 = utxodb.GetUtxoData(position1); if (!utxoBytesIn1.BytesEquals(utxoBytesOut1)) throw new Exception("test1_4"); byte[] utxoBytesOut2 = utxodb.GetUtxoData(position2); if (!utxoBytesIn1.BytesEquals(utxoBytesOut2)) throw new Exception("test1_5"); byte[] utxoBytesIn2 = new byte[utxoBytesIn1.Length]; for (int i = 0; i < utxoBytesIn2.Length; i++) utxoBytesIn2[i] = (byte)256.RandomNum(); utxodb.UpdateUtxoData(position1, utxoBytesIn2); byte[] utxoBytesOut3 = utxodb.GetUtxoData(position1); if (!utxoBytesIn2.BytesEquals(utxoBytesOut3)) throw new Exception("test1_6"); byte[] utxoBytesOut4 = utxodb.GetUtxoData(position2); if (!utxoBytesIn1.BytesEquals(utxoBytesOut4)) throw new Exception("test1_7"); utxodb.UpdateUtxoData(position2, utxoBytesIn2); byte[] utxoBytesOut5 = utxodb.GetUtxoData(position1); if (!utxoBytesIn2.BytesEquals(utxoBytesOut5)) throw new Exception("test1_8"); byte[] utxoBytesOut6 = utxodb.GetUtxoData(position2); if (!utxoBytesIn2.BytesEquals(utxoBytesOut6)) throw new Exception("test1_9"); byte[] emptyBytes2 = utxodb.GetUtxoData(overallLangth * 2); utxodb.Close(); Console.WriteLine("test1_succeeded"); } //UtxoFileItemのテスト public static void Test2() { int size1 = 16; UtxoFileItem ufiIn = new UtxoFileItem(size1); for (int i = 0; i < ufiIn.utxos.Length; i++) { if (ufiIn.utxos[i].blockIndex != 0) throw new Exception("test2_11"); if (ufiIn.utxos[i].txIndex != 0) throw new Exception("test2_12"); if (ufiIn.utxos[i].txOutIndex != 0) throw new Exception("test2_13"); if (ufiIn.utxos[i].amount.rawAmount != 0) throw new Exception("test2_14"); } if (ufiIn.utxos.Length != size1) throw new Exception("test2_1"); if (ufiIn.Size != size1) throw new Exception("test2_2"); if (ufiIn.nextPosition != -1) throw new Exception("test2_3"); for (int i = 0; i < ufiIn.utxos.Length; i++) ufiIn.utxos[i] = new Utxo(65536.RandomNum(), 65536.RandomNum(), 65536.RandomNum(), new Creacoin(65536.RandomNum())); byte[] ufiBytes = ufiIn.ToBinary(); if (ufiBytes.Length != 397) throw new Exception("test2_16"); UtxoFileItem ufiOut = SHAREDDATA.FromBinary<UtxoFileItem>(ufiBytes); if (ufiIn.utxos.Length != ufiOut.utxos.Length) throw new Exception("test2_4"); if (ufiIn.Size != ufiOut.Size) throw new Exception("test2_5"); if (ufiIn.nextPosition != ufiOut.nextPosition) throw new Exception("test2_6"); for (int i = 0; i < ufiIn.utxos.Length; i++) { if (ufiIn.utxos[i].blockIndex != ufiOut.utxos[i].blockIndex) throw new Exception("test2_7"); if (ufiIn.utxos[i].txIndex != ufiOut.utxos[i].txIndex) throw new Exception("test2_8"); if (ufiIn.utxos[i].txOutIndex != ufiOut.utxos[i].txOutIndex) throw new Exception("test2_9"); if (ufiIn.utxos[i].amount.rawAmount != ufiOut.utxos[i].amount.rawAmount) throw new Exception("test2_10"); } for (int i = 0; i < ufiIn.utxos.Length; i++) ufiOut.utxos[i] = new Utxo(65536.RandomNum(), 65536.RandomNum(), 65536.RandomNum(), new Creacoin(65536.RandomNum())); byte[] ufiBytes2 = ufiOut.ToBinary(); if (ufiBytes.Length != ufiBytes2.Length) throw new Exception("test2_15"); Console.WriteLine("test2_succeeded"); } //UtxoFilePointersのテスト public static void Test3() { UtxoFilePointers ufp = new UtxoFilePointers(); Dictionary<Sha256Ripemd160Hash, long> afps = ufp.GetAll(); if (afps.Count != 0) throw new Exception("test3_1"); Sha256Ripemd160Hash hash1 = new Sha256Ripemd160Hash(new byte[] { (byte)256.RandomNum() }); Sha256Ripemd160Hash hash2 = new Sha256Ripemd160Hash(new byte[] { (byte)256.RandomNum() }); Sha256Ripemd160Hash hash3 = new Sha256Ripemd160Hash(new byte[] { (byte)256.RandomNum() }); long position1 = 56636.RandomNum(); long position2 = 56636.RandomNum(); long position3 = 56636.RandomNum(); long? positionNull = ufp.Get(hash1); if (positionNull.HasValue) throw new Exception("test3_2"); ufp.Add(hash1, position1); ufp.Add(hash2, position2); ufp.Add(hash3, position3); bool flag = false; try { ufp.Add(hash1, position1); } catch (InvalidOperationException) { flag = true; } if (!flag) throw new Exception("test3_3"); Dictionary<Sha256Ripemd160Hash, long> afps2 = ufp.GetAll(); if (afps2.Count != 3) throw new Exception("test3_4"); if (!afps2.Keys.Contains(hash1)) throw new Exception("test3_5"); if (!afps2.Keys.Contains(hash2)) throw new Exception("test3_6"); if (!afps2.Keys.Contains(hash3)) throw new Exception("test3_7"); if (afps2[hash1] != position1) throw new Exception("test3_8"); if (afps2[hash2] != position2) throw new Exception("test3_9"); if (afps2[hash3] != position3) throw new Exception("test3_10"); long? position1Out = ufp.Get(hash1); long? position2Out = ufp.Get(hash2); long? position3Out = ufp.Get(hash3); if (!position1Out.HasValue || position1Out.Value != position1) throw new Exception("test3_11"); if (!position2Out.HasValue || position2Out.Value != position2) throw new Exception("test3_12"); if (!position3Out.HasValue || position3Out.Value != position3) throw new Exception("test3_13"); ufp.Remove(hash1); bool flag2 = false; try { ufp.Remove(hash1); } catch (InvalidOperationException) { flag2 = true; } if (!flag2) throw new Exception("test3_14"); Dictionary<Sha256Ripemd160Hash, long> afps3 = ufp.GetAll(); if (afps3.Count != 2) throw new Exception("test3_15"); ufp.Update(hash2, position1); long? position1Out2 = ufp.Get(hash2); if (!position1Out2.HasValue || position1Out2.Value != position1) throw new Exception("test3_16"); bool flag3 = false; try { ufp.Update(hash1, position2); } catch (InvalidOperationException) { flag3 = true; } if (!flag3) throw new Exception("test3_17"); Dictionary<Sha256Ripemd160Hash, long> afps4 = ufp.GetAll(); if (afps4.Count != 2) throw new Exception("test3_18"); ufp.AddOrUpdate(hash2, position3); long? position1Out3 = ufp.Get(hash2); if (!position1Out3.HasValue || position1Out3.Value != position3) throw new Exception("test3_19"); Dictionary<Sha256Ripemd160Hash, long> afps5 = ufp.GetAll(); if (afps5.Count != 2) throw new Exception("test3_20"); ufp.AddOrUpdate(hash1, position3); long? position1Out4 = ufp.Get(hash1); if (!position1Out4.HasValue || position1Out4.Value != position3) throw new Exception("test3_21"); Dictionary<Sha256Ripemd160Hash, long> afps6 = ufp.GetAll(); if (afps5.Count != 3) throw new Exception("test3_22"); byte[] ufpBytes = ufp.ToBinary(); UtxoFilePointers ufp2 = SHAREDDATA.FromBinary<UtxoFilePointers>(ufpBytes); Dictionary<Sha256Ripemd160Hash, long> afps7 = ufp2.GetAll(); if (afps6.Count != afps7.Count) throw new Exception("test3_23"); foreach (var key in afps6.Keys) { if (!afps7.Keys.Contains(key)) throw new Exception("test3_24"); if (afps6[key] != afps7[key]) throw new Exception("test3_25"); } Console.WriteLine("test3_succeeded"); } //UtxoManagerのテスト1 public static void Test4() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); UtxoManager utxom = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); if (File.Exists(ufadbPath)) throw new Exception("test4_9"); utxodb.Open(); Sha256Ripemd160Hash address1 = new Sha256Ripemd160Hash(new byte[] { 0 }); Sha256Ripemd160Hash address2 = new Sha256Ripemd160Hash(new byte[] { 1 }); Sha256Ripemd160Hash address3 = new Sha256Ripemd160Hash(new byte[] { 2 }); Utxo utxoNull = utxom.FindUtxo(address1, 65536.RandomNum(), 65536.RandomNum(), 65536.RandomNum()); if (utxoNull != null) throw new Exception("test4_1"); long bi1 = 65536.RandomNum(); int ti1 = 65536.RandomNum(); int toi1 = 65536.RandomNum(); Creacoin c1 = new Creacoin(65536.RandomNum()); long bi2 = 65536.RandomNum(); int ti2 = 65536.RandomNum(); int toi2 = 65536.RandomNum(); Creacoin c2 = new Creacoin(65536.RandomNum()); long bi3 = 65536.RandomNum(); int ti3 = 65536.RandomNum(); int toi3 = 65536.RandomNum(); Creacoin c3 = new Creacoin(65536.RandomNum()); utxom.AddUtxo(address1, bi1, ti1, toi1, c1); utxom.AddUtxo(address2, bi1, ti1, toi1, c1); utxom.AddUtxo(address3, bi1, ti1, toi1, c1); utxom.AddUtxo(address1, bi2, ti2, toi2, c2); utxom.AddUtxo(address2, bi2, ti2, toi2, c2); utxom.AddUtxo(address3, bi2, ti2, toi2, c2); utxom.AddUtxo(address1, bi3, ti3, toi3, c3); utxom.AddUtxo(address2, bi3, ti3, toi3, c3); utxom.AddUtxo(address3, bi3, ti3, toi3, c3); //2014/12/17追加 GetAllUtxosLatestFirstの試験 List<Utxo> utxos1 = utxom.GetAllUtxosLatestFirst(address1); List<Utxo> utxos2 = utxom.GetAllUtxosLatestFirst(address2); List<Utxo> utxos3 = utxom.GetAllUtxosLatestFirst(address3); if (utxos1.Count != 3) throw new Exception("test4_19"); if (utxos2.Count != 3) throw new Exception("test4_20"); if (utxos3.Count != 3) throw new Exception("test4_21"); long max = Math.Max(Math.Max(bi1, bi2), bi3); if (utxos1[0].blockIndex != max) throw new Exception("test4_22"); if (utxos2[0].blockIndex != max) throw new Exception("test4_23"); if (utxos3[0].blockIndex != max) throw new Exception("test4_24"); //2014/12/17追加(終) Utxo utxo1 = utxom.FindUtxo(address1, bi1, ti1, toi1); if (utxo1 == null) throw new Exception("test4_2"); if (utxo1.blockIndex != bi1) throw new Exception("test4_3"); if (utxo1.txIndex != ti1) throw new Exception("test4_4"); if (utxo1.txOutIndex != toi1) throw new Exception("test4_5"); if (utxo1.amount.rawAmount != c1.rawAmount) throw new Exception("test4_6"); utxom.AddUtxo(address1, bi1, ti1, toi1, c1); utxom.RemoveUtxo(address1, bi1, ti1, toi1); utxom.RemoveUtxo(address1, bi1, ti1, toi1); bool flag = false; try { utxom.RemoveUtxo(address1, bi1, ti1, toi1); } catch (InvalidOperationException) { flag = true; } if (!flag) throw new Exception("test4_7"); Utxo utxoNull2 = utxom.FindUtxo(address1, bi1, ti1, toi1); if (utxoNull2 != null) throw new Exception("test4_8"); utxom.SaveUFPTemp(); utxodb.Close(); if (!File.Exists(ufpdbPath)) throw new Exception("test4_9"); if (!File.Exists(ufptempdbPath)) throw new Exception("test4_10"); if (!File.Exists(utxodbPath)) throw new Exception("test4_11"); UtxoManager utxom2 = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); if (File.Exists(ufptempdbPath)) throw new Exception("test4_13"); utxodb.Open(); Utxo utxo2 = utxom.FindUtxo(address2, bi1, ti1, toi1); if (utxo2 == null) throw new Exception("test4_14"); if (utxo2.blockIndex != bi1) throw new Exception("test4_15"); if (utxo2.txIndex != ti1) throw new Exception("test4_16"); if (utxo2.txOutIndex != toi1) throw new Exception("test4_17"); if (utxo2.amount.rawAmount != c1.rawAmount) throw new Exception("test4_18"); utxodb.Close(); Console.WriteLine("test4_succeeded"); } //UtxoManagerのテスト2 public static void Test5() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); UtxoManager utxom = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); Sha256Ripemd160Hash address = new Sha256Ripemd160Hash(new byte[] { 0 }); int length = 100; long[] bis = new long[length]; int[] tis = new int[length]; int[] tois = new int[length]; Creacoin[] cs = new Creacoin[length]; for (int i = 0; i < length; i++) { bis[i] = 65536.RandomNum(); tis[i] = 65536.RandomNum(); tois[i] = 65536.RandomNum(); cs[i] = new Creacoin(65536.RandomNum()); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); utxodb.Open(); for (int i = 0; i < length; i++) utxom.AddUtxo(address, bis[i], tis[i], tois[i], cs[i]); utxom.SaveUFPTemp(); utxodb.Close(); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test5_5", stopwatch.ElapsedMilliseconds.ToString() + "ms")); UtxoManager utxom2 = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); Utxo[] utxos = new Utxo[length]; stopwatch.Reset(); stopwatch.Start(); utxodb.Open(); for (int i = 0; i < length; i++) utxos[i] = utxom.FindUtxo(address, bis[i], tis[i], tois[i]); utxodb.Close(); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test5_6", stopwatch.ElapsedMilliseconds.ToString() + "ms")); for (int i = 0; i < length; i++) { if (utxos[i].blockIndex != bis[i]) throw new Exception("test5_1"); if (utxos[i].txIndex != tis[i]) throw new Exception("test5_2"); if (utxos[i].txOutIndex != tois[i]) throw new Exception("test5_3"); if (utxos[i].amount.rawAmount != cs[i].rawAmount) throw new Exception("test5_4"); } } //UtxoManagerのテスト3 public static void Test6() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); UtxoManager utxom = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); int length = 100; Sha256Ripemd160Hash[] addrs = new Sha256Ripemd160Hash[length]; long[] bis = new long[length]; int[] tis = new int[length]; int[] tois = new int[length]; Creacoin[] cs = new Creacoin[length]; for (int i = 0; i < length; i++) { addrs[i] = new Sha256Ripemd160Hash(BitConverter.GetBytes(i)); bis[i] = 65536.RandomNum(); tis[i] = 65536.RandomNum(); tois[i] = 65536.RandomNum(); cs[i] = new Creacoin(65536.RandomNum()); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); utxodb.Open(); for (int i = 0; i < length; i++) utxom.AddUtxo(addrs[i], bis[i], tis[i], tois[i], cs[i]); utxom.SaveUFPTemp(); utxodb.Close(); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test6_5", stopwatch.ElapsedMilliseconds.ToString() + "ms")); UtxoManager utxom2 = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); Utxo[] utxos = new Utxo[length]; stopwatch.Reset(); stopwatch.Start(); utxodb.Open(); for (int i = 0; i < length; i++) utxos[i] = utxom.FindUtxo(addrs[i], bis[i], tis[i], tois[i]); utxodb.Close(); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test6_6", stopwatch.ElapsedMilliseconds.ToString() + "ms")); for (int i = 0; i < length; i++) { if (utxos[i].blockIndex != bis[i]) throw new Exception("test6_1"); if (utxos[i].txIndex != tis[i]) throw new Exception("test6_2"); if (utxos[i].txOutIndex != tois[i]) throw new Exception("test6_3"); if (utxos[i].amount.rawAmount != cs[i].rawAmount) throw new Exception("test6_4"); } } //BlockDBのテスト public static void Test7() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockDB blkdb = new BlockDB(basepath); string path1 = blkdb.GetPath(0); string path2 = blkdb.GetPath(1); if (File.Exists(path1)) File.Delete(path1); if (File.Exists(path2)) File.Delete(path2); byte[] emptyBytes = blkdb.GetBlockData(0, 0); if (emptyBytes.Length != 0) throw new Exception("test1_1"); byte[][] emptyBytess = blkdb.GetBlockDatas(0, new long[10]); for (int i = 0; i < emptyBytess.Length; i++) if (emptyBytess[i].Length != 0) throw new Exception("test1_2"); byte[] blkBytesIn1 = new byte[1024]; for (int i = 0; i < blkBytesIn1.Length; i++) blkBytesIn1[i] = (byte)256.RandomNum(); int overallLangth = blkBytesIn1.Length + 4; long position1 = blkdb.AddBlockData(0, blkBytesIn1); if (position1 != 0) throw new Exception("test1_3"); long position2 = blkdb.AddBlockData(1, blkBytesIn1); if (position2 != 0) throw new Exception("test1_4"); byte[][] blkBytessIn1 = new byte[10][]; for (int i = 0; i < blkBytessIn1.Length; i++) { blkBytessIn1[i] = new byte[blkBytesIn1.Length]; for (int j = 0; j < blkBytessIn1[i].Length; j++) blkBytessIn1[i][j] = (byte)256.RandomNum(); } long[] positions1 = blkdb.AddBlockDatas(0, blkBytessIn1); for (int i = 0; i < blkBytessIn1.Length; i++) if (positions1[i] != overallLangth * (i + 1)) throw new Exception("test1_5"); long[] positions2 = blkdb.AddBlockDatas(1, blkBytessIn1); for (int i = 0; i < blkBytessIn1.Length; i++) if (positions2[i] != overallLangth * (i + 1)) throw new Exception("test1_6"); byte[] blkBytesOut1 = blkdb.GetBlockData(0, position1); if (!blkBytesIn1.BytesEquals(blkBytesOut1)) throw new Exception("test1_7"); byte[] utxoBytesOut2 = blkdb.GetBlockData(1, position1); if (!blkBytesIn1.BytesEquals(utxoBytesOut2)) throw new Exception("test1_8"); byte[][] blkBytessOut1 = blkdb.GetBlockDatas(0, positions1); for (int i = 0; i < blkBytessIn1.Length; i++) if (!blkBytessIn1[i].BytesEquals(blkBytessOut1[i])) throw new Exception("test1_9"); byte[][] blkBytessOut2 = blkdb.GetBlockDatas(1, positions2); for (int i = 0; i < blkBytessIn1.Length; i++) if (!blkBytessIn1[i].BytesEquals(blkBytessOut2[i])) throw new Exception("test1_10"); byte[] emptyBytes2 = blkdb.GetBlockData(0, overallLangth * 11); if (emptyBytes2.Length != 0) throw new Exception("test1_11"); byte[] emptyBytes3 = blkdb.GetBlockData(1, overallLangth * 11); if (emptyBytes3.Length != 0) throw new Exception("test1_12"); Console.WriteLine("test7_succeeded"); } //BlockFilePointersDBのテスト public static void Test8() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string path = bfpdb.GetPath(); if (File.Exists(path)) File.Delete(path); for (int i = 0; i < 10; i++) { long position = bfpdb.GetBlockFilePointerData(256.RandomNum()); if (position != -1) throw new Exception("test8_1"); } long[] bindexes = 256.RandomNums().Take(10).Select((elem) => (long)elem).ToArray(); for (int i = 0; i < bindexes.Length; i++) bfpdb.UpdateBlockFilePointerData(bindexes[i], bindexes[i]); long[] bindexesSorted = bindexes.ToList().Pipe((list) => list.Sort()).ToArray(); int pointer = 0; for (int i = 0; i < 256; i++) { long position = bfpdb.GetBlockFilePointerData(i); if (pointer < bindexesSorted.Length && i == bindexesSorted[pointer]) { if (position != bindexesSorted[pointer]) throw new Exception("test8_2"); pointer++; } else { if (position != -1) throw new Exception("test8_3"); } } for (int i = 0; i < 10; i++) { int[] random = 256.RandomNums(); long[] bindexes2 = random.Take(10).Select((elem) => (long)elem).ToArray(); long[] positions2 = random.Skip(10).Take(10).Select((elem) => (long)elem).ToArray(); for (int j = 0; j < bindexes2.Length; j++) bfpdb.UpdateBlockFilePointerData(bindexes2[j], positions2[j]); for (int j = 0; j < bindexes2.Length; j++) { long positionOut = bfpdb.GetBlockFilePointerData(bindexes2[j]); if (positionOut != positions2[j]) throw new Exception("test8_4"); } } Console.WriteLine("test8_succeeded"); } //BlockManagerのテスト1 public static void Test9() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); BlockManager blkmanager = new BlockManager(bmdb, bdb, bfpdb, 10, 10, 3); if (blkmanager.headBlockIndex != -1) throw new InvalidOperationException("test9_1"); if (blkmanager.finalizedBlockIndex != -1) throw new InvalidOperationException("test9_2"); if (blkmanager.mainBlocksCurrent.value != 0) throw new InvalidOperationException("test9_16"); if (blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] != null) throw new InvalidOperationException("test9_3"); bool flag = false; try { blkmanager.GetMainBlock(-1); } catch (InvalidOperationException) { flag = true; } if (!flag) throw new Exception("test9_5"); bool flag2 = false; try { blkmanager.GetMainBlock(1); } catch (InvalidOperationException) { flag2 = true; } if (!flag2) throw new Exception("test9_6"); bool flag9 = false; try { blkmanager.GetMainBlock(0); } catch (InvalidOperationException) { flag9 = true; } if (!flag9) throw new Exception("test9_28"); blkmanager.AddMainBlock(new GenesisBlock()); if (blkmanager.headBlockIndex != 0) throw new InvalidOperationException("test9_29"); if (blkmanager.finalizedBlockIndex != 0) throw new InvalidOperationException("test9_30"); if (blkmanager.mainBlocksCurrent.value != 1) throw new InvalidOperationException("test9_31"); if (blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] == null) throw new InvalidOperationException("test9_32"); if (!(blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] is GenesisBlock)) throw new InvalidOperationException("test9_33"); Block block1 = blkmanager.GetMainBlock(0); Block block2 = blkmanager.GetHeadBlock(); if (!(block1 is GenesisBlock)) throw new Exception("test9_10"); if (!(block2 is GenesisBlock)) throw new Exception("test9_11"); bool flag3 = false; try { blkmanager.DeleteMainBlock(-1); } catch (InvalidOperationException) { flag3 = true; } if (!flag3) throw new Exception("test9_7"); bool flag4 = false; try { blkmanager.DeleteMainBlock(1); } catch (InvalidOperationException) { flag4 = true; } if (!flag4) throw new Exception("test9_8"); bool flag5 = false; try { blkmanager.DeleteMainBlock(0); } catch (InvalidOperationException) { flag5 = true; } if (!flag5) throw new Exception("test9_9"); TestBlock testblk1 = new TestBlock(1); blkmanager.AddMainBlock(testblk1); if (blkmanager.headBlockIndex != 1) throw new InvalidOperationException("test9_12"); if (blkmanager.finalizedBlockIndex != 0) throw new InvalidOperationException("test9_13"); if (blkmanager.mainBlocksCurrent.value != 2) throw new InvalidOperationException("test9_17"); if (blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] == null) throw new InvalidOperationException("test9_14"); if (!(blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] is TestBlock)) throw new InvalidOperationException("test9_15"); blkmanager.DeleteMainBlock(1); if (blkmanager.headBlockIndex != 0) throw new InvalidOperationException("test9_18"); if (blkmanager.finalizedBlockIndex != 0) throw new InvalidOperationException("test9_19"); if (blkmanager.mainBlocksCurrent.value != 1) throw new InvalidOperationException("test9_20"); if (blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] == null) throw new InvalidOperationException("test9_21"); if (!(blkmanager.mainBlocks[blkmanager.mainBlocksCurrent.value] is GenesisBlock)) throw new InvalidOperationException("test9_22"); TestBlock testblk2 = new TestBlock(2); bool flag6 = false; try { blkmanager.AddMainBlock(testblk2); } catch (InvalidOperationException) { flag6 = true; } if (!flag6) throw new Exception("test9_23"); for (int i = 1; i < 18; i++) { TestBlock testblk = new TestBlock(i); blkmanager.AddMainBlock(testblk); } for (int i = 17; i > 0; i--) { if (i == 14) { bool flag7 = false; try { blkmanager.DeleteMainBlock(i); } catch (InvalidOperationException) { flag7 = true; } if (!flag7) throw new Exception("test9_24"); break; } blkmanager.DeleteMainBlock(i); } Block block3 = blkmanager.GetHeadBlock(); if (block3.Index != 14) throw new Exception("test9_25"); for (int i = 17; i > 0; i--) { if (i > 14) { bool flag8 = false; try { blkmanager.GetMainBlock(i); } catch (InvalidOperationException) { flag8 = true; } if (!flag8) throw new Exception("test9_26"); continue; } Block block4 = blkmanager.GetMainBlock(i); if (block4.Index != i) throw new Exception("test9_27"); } Console.WriteLine("test9_succeeded"); } //TransactionOutput、TransactionInput、CoinbaseTransaction、TransferTransactionのテスト public static void Test10() { Ecdsa256KeyPair keypair1 = new Ecdsa256KeyPair(true); Ecdsa256KeyPair keypair2 = new Ecdsa256KeyPair(true); Ecdsa256KeyPair keypair3 = new Ecdsa256KeyPair(true); Sha256Ripemd160Hash address1 = new Sha256Ripemd160Hash(keypair1.pubKey.pubKey); CurrencyUnit amount1 = new Creacoin(50.0m); Sha256Ripemd160Hash address2 = new Sha256Ripemd160Hash(keypair2.pubKey.pubKey); CurrencyUnit amount2 = new Creacoin(25.0m); Sha256Ripemd160Hash address3 = new Sha256Ripemd160Hash(keypair3.pubKey.pubKey); CurrencyUnit amount3 = new Yumina(0.01m); TransactionOutput txOut1 = new TransactionOutput(); txOut1.LoadVersion0(address1, amount1); TransactionOutput txOut2 = new TransactionOutput(); txOut2.LoadVersion0(address2, amount2); TransactionOutput txOut3 = new TransactionOutput(); txOut3.LoadVersion0(address3, amount3); if (txOut1.Address != address1) throw new Exception("test10_1"); if (txOut1.Amount != amount1) throw new Exception("test10_2"); byte[] txOutBytes = txOut1.ToBinary(); if (txOutBytes.Length != 29) throw new Exception("test10_3"); TransactionOutput txOutRestore = SHAREDDATA.FromBinary<TransactionOutput>(txOutBytes, 0); if (!txOut1.Address.Equals(txOutRestore.Address)) throw new Exception("test10_4"); if (txOut1.Amount.rawAmount != txOutRestore.Amount.rawAmount) throw new Exception("test10_5"); TransactionInput txIn1 = new TransactionInput(); txIn1.LoadVersion0(0, 0, 0, keypair1.pubKey); TransactionInput txIn2 = new TransactionInput(); txIn2.LoadVersion0(1, 0, 0, keypair2.pubKey); TransactionInput txIn3 = new TransactionInput(); txIn3.LoadVersion0(2, 0, 0, keypair3.pubKey); if (txIn1.PrevTxBlockIndex != 0) throw new Exception("test10_6"); if (txIn1.PrevTxIndex != 0) throw new Exception("test10_7"); if (txIn1.PrevTxOutputIndex != 0) throw new Exception("test10_8"); if (txIn1.SenderPubKey != keypair1.pubKey) throw new Exception("test10_9"); TransactionOutput[] txOuts = new TransactionOutput[] { txOut1, txOut2, txOut3 }; CoinbaseTransaction cTx = new CoinbaseTransaction(); cTx.LoadVersion0(txOuts); if (cTx.TxOutputs != txOuts) throw new Exception("test10_10"); if (cTx.TxInputs.Length != 0) throw new Exception("test10_11"); byte[] cTxBytes = cTx.ToBinary(); if (cTxBytes.Length != 97) throw new Exception("test10_12"); CoinbaseTransaction cTxRestore = SHAREDDATA.FromBinary<CoinbaseTransaction>(cTxBytes); if (!cTx.Id.Equals(cTxRestore.Id)) throw new Exception("test10_13"); if (cTx.Verify()) throw new Exception("test10_14"); if (cTx.VerifyNotExistDustTxOutput()) throw new Exception("test10_15"); if (!cTx.VerifyNumberOfTxInputs()) throw new Exception("test10_16"); if (!cTx.VerifyNumberOfTxOutputs()) throw new Exception("test10_17"); TransactionOutput[] txOuts2 = new TransactionOutput[11]; for (int i = 0; i < txOuts2.Length; i++) txOuts2[i] = txOut1; CoinbaseTransaction cTx2 = new CoinbaseTransaction(); cTx2.LoadVersion0(txOuts2); if (cTx2.Verify()) throw new Exception("test10_18"); if (!cTx2.VerifyNotExistDustTxOutput()) throw new Exception("test10_19"); if (!cTx2.VerifyNumberOfTxInputs()) throw new Exception("test10_20"); if (cTx2.VerifyNumberOfTxOutputs()) throw new Exception("test10_21"); TransactionOutput[] txOuts3 = new TransactionOutput[] { txOut1, txOut2 }; CoinbaseTransaction cTx3 = new CoinbaseTransaction(); cTx3.LoadVersion0(txOuts3); if (!cTx3.Verify()) throw new Exception("test10_22"); if (!cTx3.VerifyNotExistDustTxOutput()) throw new Exception("test10_23"); if (!cTx3.VerifyNumberOfTxInputs()) throw new Exception("test10_24"); if (!cTx3.VerifyNumberOfTxOutputs()) throw new Exception("test10_25"); TransactionInput[] txIns = new TransactionInput[] { txIn1, txIn2, txIn3 }; TransferTransaction tTx1 = new TransferTransaction(); tTx1.LoadVersion0(txIns, txOuts); tTx1.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey }); if (tTx1.TxInputs != txIns) throw new Exception("test10_26"); if (tTx1.TxOutputs != txOuts) throw new Exception("test10_27"); byte[] txInBytes = txIn1.ToBinary(); if (txInBytes.Length != 153) throw new Exception("test10_28"); TransactionInput txInRestore = SHAREDDATA.FromBinary<TransactionInput>(txInBytes, 0); if (txIn1.PrevTxBlockIndex != txInRestore.PrevTxBlockIndex) throw new Exception("test10_29"); if (txIn1.PrevTxIndex != txInRestore.PrevTxIndex) throw new Exception("test10_30"); if (txIn1.PrevTxOutputIndex != txInRestore.PrevTxOutputIndex) throw new Exception("test10_31"); if (!txIn1.SenderPubKey.pubKey.BytesEquals(txInRestore.SenderPubKey.pubKey)) throw new Exception("test10_32"); if (!txIn1.SenderSignature.signature.BytesEquals(txInRestore.SenderSignature.signature)) throw new Exception("test10_33"); byte[] tTxBytes = tTx1.ToBinary(); if (tTxBytes.Length != 557) throw new Exception("test10_34"); TransferTransaction tTxRestore = SHAREDDATA.FromBinary<TransferTransaction>(tTxBytes); if (!tTx1.Id.Equals(tTxRestore.Id)) throw new Exception("test10_35"); if (tTx1.Verify(txOuts)) throw new Exception("test10_36"); if (tTx1.VerifyNotExistDustTxOutput()) throw new Exception("test10_37"); if (!tTx1.VerifyNumberOfTxInputs()) throw new Exception("test10_38"); if (!tTx1.VerifyNumberOfTxOutputs()) throw new Exception("test10_39"); if (!tTx1.VerifySignature(txOuts)) throw new Exception("test10_40"); if (!tTx1.VerifyPubKey(txOuts)) throw new Exception("test10_41"); if (!tTx1.VerifyAmount(txOuts)) throw new Exception("test10_42"); if (tTx1.GetFee(txOuts).rawAmount != 0) throw new Exception("test10_43"); TransactionOutput[] txOuts4 = new TransactionOutput[] { txOut2, txOut1, txOut3 }; if (tTx1.Verify(txOuts4)) throw new Exception("test10_44"); if (tTx1.VerifySignature(txOuts4)) throw new Exception("test10_45"); if (tTx1.VerifyPubKey(txOuts4)) throw new Exception("test10_46"); byte temp2 = tTx1.TxInputs[0].SenderSignature.signature[0]; tTx1.TxInputs[0].SenderSignature.signature[0] = 0; if (tTx1.Verify(txOuts)) throw new Exception("test10_47"); if (tTx1.VerifySignature(txOuts)) throw new Exception("test10_48"); if (!tTx1.VerifyPubKey(txOuts)) throw new Exception("test10_49"); tTx1.TxInputs[0].SenderSignature.signature[0] = temp2; TransferTransaction tTx2 = new TransferTransaction(); tTx2.LoadVersion0(txIns, txOuts); tTx2.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair2.privKey, keypair1.privKey, keypair3.privKey }); if (tTx2.Verify(txOuts)) throw new Exception("test10_50"); if (tTx2.VerifySignature(txOuts)) throw new Exception("test10_51"); if (!tTx2.VerifyPubKey(txOuts)) throw new Exception("test10_52"); TransferTransaction tTx3 = new TransferTransaction(); tTx3.LoadVersion0(txIns, txOuts); tTx3.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey }); byte temp = tTx3.TxInputs[0].SenderPubKey.pubKey[0]; tTx3.TxInputs[0].SenderPubKey.pubKey[0] = 0; if (tTx3.Verify(txOuts)) throw new Exception("test10_50"); if (tTx3.VerifySignature(txOuts)) throw new Exception("test10_51"); if (tTx3.VerifyPubKey(txOuts)) throw new Exception("test10_52"); tTx3.TxInputs[0].SenderPubKey.pubKey[0] = temp; TransferTransaction tTx4 = new TransferTransaction(); tTx4.LoadVersion0(txIns, txOuts2); tTx4.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey }); if (tTx4.Verify(txOuts)) throw new Exception("test10_53"); if (!tTx4.VerifyNotExistDustTxOutput()) throw new Exception("test10_54"); if (!tTx4.VerifyNumberOfTxInputs()) throw new Exception("test10_55"); if (tTx4.VerifyNumberOfTxOutputs()) throw new Exception("test10_56"); if (!tTx4.VerifySignature(txOuts)) throw new Exception("test10_57"); if (!tTx4.VerifyPubKey(txOuts)) throw new Exception("test10_58"); if (tTx4.VerifyAmount(txOuts)) throw new Exception("test10_59"); if (tTx4.GetFee(txOuts).rawAmount != -47499990000) throw new Exception("test10_60"); TransferTransaction tTx5 = new TransferTransaction(); tTx5.LoadVersion0(txIns, txOuts3); tTx5.Sign(txOuts, new DSAPRIVKEYBASE[] { keypair1.privKey, keypair2.privKey, keypair3.privKey }); if (!tTx5.Verify(txOuts)) throw new Exception("test10_61"); if (!tTx5.VerifyNotExistDustTxOutput()) throw new Exception("test10_62"); if (!tTx5.VerifyNumberOfTxInputs()) throw new Exception("test10_63"); if (!tTx5.VerifyNumberOfTxOutputs()) throw new Exception("test10_64"); if (!tTx5.VerifySignature(txOuts)) throw new Exception("test10_65"); if (!tTx5.VerifyPubKey(txOuts)) throw new Exception("test10_66"); if (!tTx5.VerifyAmount(txOuts)) throw new Exception("test10_67"); if (tTx5.GetFee(txOuts).rawAmount != 10000) throw new Exception("test10_68"); TransactionInput[] txIns2 = new TransactionInput[101]; for (int i = 0; i < txIns2.Length; i++) txIns2[i] = txIn1; TransactionOutput[] txOuts5 = new TransactionOutput[txIns2.Length]; for (int i = 0; i < txOuts5.Length; i++) txOuts5[i] = txOut1; Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[txIns2.Length]; for (int i = 0; i < privKeys.Length; i++) privKeys[i] = keypair1.privKey; TransferTransaction tTx6 = new TransferTransaction(); tTx6.LoadVersion0(txIns2, txOuts3); tTx6.Sign(txOuts5, privKeys); if (tTx6.Verify(txOuts5)) throw new Exception("test10_61"); if (!tTx6.VerifyNotExistDustTxOutput()) throw new Exception("test10_62"); if (tTx6.VerifyNumberOfTxInputs()) throw new Exception("test10_63"); if (!tTx6.VerifyNumberOfTxOutputs()) throw new Exception("test10_64"); if (!tTx6.VerifySignature(txOuts5)) throw new Exception("test10_65"); if (!tTx6.VerifyPubKey(txOuts5)) throw new Exception("test10_66"); if (!tTx6.VerifyAmount(txOuts5)) throw new Exception("test10_67"); if (tTx6.GetFee(txOuts5).rawAmount != 497500000000) throw new Exception("test10_68"); byte[] cTxBytes2 = SHAREDDATA.ToBinary<Transaction>(cTx); if (cTxBytes2.Length != 117) throw new Exception("test10_69"); CoinbaseTransaction cTxRestore2 = SHAREDDATA.FromBinary<Transaction>(cTxBytes2) as CoinbaseTransaction; if (!cTx.Id.Equals(cTxRestore2.Id)) throw new Exception("test10_70"); byte[] tTxBytes2 = SHAREDDATA.ToBinary<Transaction>(tTx6); if (tTxBytes2.Length != 15445) throw new Exception("test10_71"); TransferTransaction tTxRestore2 = SHAREDDATA.FromBinary<Transaction>(tTxBytes2) as TransferTransaction; if (!tTx6.Id.Equals(tTxRestore2.Id)) throw new Exception("test10_72"); Sha256Sha256Hash ctxid = new Sha256Sha256Hash(cTxBytes); if (!ctxid.Equals(cTx.Id)) throw new Exception("test10_73"); Sha256Sha256Hash ttxid = new Sha256Sha256Hash(tTx6.ToBinary()); if (!ttxid.Equals(tTx6.Id)) throw new Exception("test10_74"); Console.WriteLine("test10_succeeded"); } //Blockのテスト1 public static void Test11() { GenesisBlock gblk = new GenesisBlock(); if (gblk.Index != 0) throw new Exception("test11_1"); if (gblk.PrevId != null) throw new Exception("test11_2"); if (gblk.Difficulty.Diff != 0.00000011) throw new Exception("test11_3"); if (gblk.Transactions.Length != 0) throw new Exception("test11_4"); byte[] gblkBytes = gblk.ToBinary(); if (gblkBytes.Length != 68) throw new Exception("test11_5"); GenesisBlock gblkRestore = SHAREDDATA.FromBinary<GenesisBlock>(gblkBytes); if (!gblk.Id.Equals(gblkRestore.Id)) throw new Exception("test11_6"); byte[] gblkBytes2 = SHAREDDATA.ToBinary<Block>(gblk); if (gblkBytes2.Length != 88) throw new Exception("test11_7"); GenesisBlock gblkRestore2 = SHAREDDATA.FromBinary<Block>(gblkBytes2) as GenesisBlock; if (!gblk.Id.Equals(gblkRestore2.Id)) throw new Exception("test11_8"); BlockHeader bh = new BlockHeader(); bool flag = false; try { bh.LoadVersion0(0, null, DateTime.Now, null, new byte[10]); } catch (ArgumentOutOfRangeException) { flag = true; } if (!flag) throw new Exception("test11_9"); bool flag2 = false; try { bh.LoadVersion0(1, null, DateTime.Now, null, new byte[9]); } catch (ArgumentOutOfRangeException) { flag2 = true; } if (!flag2) throw new Exception("test11_10"); Difficulty<Creahash> diff = new Difficulty<Creahash>(HASHBASE.FromHash<Creahash>(new byte[] { 0, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 })); Sha256Sha256Hash hash = new Sha256Sha256Hash(new byte[] { 1 }); DateTime dt = DateTime.Now; byte[] nonce = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; bh.LoadVersion0(1, gblk.Id, DateTime.Now, diff, new byte[10]); bool flag3 = false; try { bh.UpdateNonce(new byte[11]); } catch (ArgumentOutOfRangeException) { flag3 = true; } if (!flag3) throw new Exception("test11_11"); bh.UpdateMerkleRootHash(hash); bh.UpdateTimestamp(dt); bh.UpdateNonce(nonce); if (bh.index != 1) throw new Exception("test11_12"); if (bh.prevBlockHash != gblk.Id) throw new Exception("test11_13"); if (bh.merkleRootHash != hash) throw new Exception("test11_14"); if (bh.timestamp != dt) throw new Exception("test11_15"); if (bh.difficulty != diff) throw new Exception("test11_16"); if (bh.nonce != nonce) throw new Exception("test11_17"); byte[] bhBytes = bh.ToBinary(); if (bhBytes.Length != 95) throw new Exception("test11_18"); BlockHeader bhRestore = SHAREDDATA.FromBinary<BlockHeader>(bhBytes); if (bh.index != bhRestore.index) throw new Exception("test11_19"); if (!bh.prevBlockHash.Equals(bhRestore.prevBlockHash)) throw new Exception("test11_20"); if (!bh.merkleRootHash.Equals(bhRestore.merkleRootHash)) throw new Exception("test11_21"); if (bh.timestamp != bhRestore.timestamp) throw new Exception("test11_22"); if (bh.difficulty.Diff != bhRestore.difficulty.Diff) throw new Exception("test11_23"); if (!bh.nonce.BytesEquals(bhRestore.nonce)) throw new Exception("test11_24"); bool flag4 = false; try { TransactionalBlock.GetBlockType(0, 0); } catch (ArgumentOutOfRangeException) { flag4 = true; } if (!flag4) throw new Exception("test11_25"); Type type1 = TransactionalBlock.GetBlockType(60 * 24 - 1, 0); Type type2 = TransactionalBlock.GetBlockType(60 * 24, 0); Type type3 = TransactionalBlock.GetBlockType(60 * 24 + 1, 0); if (type1 != typeof(NormalBlock)) throw new Exception("test11_26"); if (type2 != typeof(FoundationalBlock)) throw new Exception("test11_27"); if (type3 != typeof(NormalBlock)) throw new Exception("test11_28"); bool flag5 = false; try { TransactionalBlock.GetRewardToAll(0, 0); } catch (ArgumentOutOfRangeException) { flag5 = true; } if (!flag5) throw new Exception("test11_29"); bool flag6 = false; try { TransactionalBlock.GetRewardToMiner(0, 0); } catch (ArgumentOutOfRangeException) { flag6 = true; } if (!flag6) throw new Exception("test11_30"); bool flag7 = false; try { TransactionalBlock.GetRewardToFoundation(0, 0); } catch (ArgumentOutOfRangeException) { flag7 = true; } if (!flag7) throw new Exception("test11_31"); bool flag8 = false; try { TransactionalBlock.GetRewardToFoundationInterval(0, 0); } catch (ArgumentOutOfRangeException) { flag8 = true; } if (!flag8) throw new Exception("test11_32"); bool flag9 = false; try { TransactionalBlock.GetRewardToFoundationInterval(1, 0); } catch (ArgumentException) { flag9 = true; } if (!flag9) throw new Exception("test11_33"); CurrencyUnit initial = new Creacoin(60.0m); decimal rate = 1.25m; for (int i = 0; i < 8; i++) { CurrencyUnit reward1 = i != 0 ? TransactionalBlock.GetRewardToAll((60 * 24 * 365 * i) - 1, 0) : null; CurrencyUnit reward2 = i != 0 ? TransactionalBlock.GetRewardToAll(60 * 24 * 365 * i, 0) : null; CurrencyUnit reward3 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * i) + 1, 0); CurrencyUnit reward7 = i != 0 ? TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * i) - 1, 0) : null; CurrencyUnit reward8 = i != 0 ? TransactionalBlock.GetRewardToMiner(60 * 24 * 365 * i, 0) : null; CurrencyUnit reward9 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * i) + 1, 0); CurrencyUnit reward10 = i != 0 ? TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * i) - 1, 0) : null; CurrencyUnit reward11 = i != 0 ? TransactionalBlock.GetRewardToFoundation(60 * 24 * 365 * i, 0) : null; CurrencyUnit reward12 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * i) + 1, 0); CurrencyUnit reward19 = i != 0 ? TransactionalBlock.GetRewardToFoundationInterval(((365 * i) - 1) * 60 * 24, 0) : null; CurrencyUnit reward20 = i != 0 ? TransactionalBlock.GetRewardToFoundationInterval(60 * 24 * 365 * i, 0) : null; CurrencyUnit reward21 = TransactionalBlock.GetRewardToFoundationInterval(((365 * i) + 1) * 60 * 24, 0); if (i != 0 && reward1.rawAmount != initial.rawAmount * rate) throw new Exception("test11_34"); if (i != 0 && reward7.rawAmount != initial.rawAmount * rate * 0.9m) throw new Exception("test11_35"); if (i != 0 && reward10.rawAmount != initial.rawAmount * rate * 0.1m) throw new Exception("test11_36"); if (i != 0 && reward19.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m) throw new Exception("test11_37"); rate *= 0.8m; if (i != 0 && reward2.rawAmount != initial.rawAmount * rate) throw new Exception("test11_38"); if (i != 0 && reward8.rawAmount != initial.rawAmount * rate * 0.9m) throw new Exception("test11_39"); if (i != 0 && reward11.rawAmount != initial.rawAmount * rate * 0.1m) throw new Exception("test11_40"); if (i != 0 && reward20.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m) throw new Exception("test11_41"); if (reward3.rawAmount != initial.rawAmount * rate) throw new Exception("test11_42"); if (reward9.rawAmount != initial.rawAmount * rate * 0.9m) throw new Exception("test11_43"); if (reward12.rawAmount != initial.rawAmount * rate * 0.1m) throw new Exception("test11_44"); if (reward21.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m) throw new Exception("test11_45"); } CurrencyUnit reward4 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * 8) - 1, 0); CurrencyUnit reward5 = TransactionalBlock.GetRewardToAll(60 * 24 * 365 * 8, 0); CurrencyUnit reward6 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * 8) + 1, 0); CurrencyUnit reward13 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * 8) - 1, 0); CurrencyUnit reward14 = TransactionalBlock.GetRewardToMiner(60 * 24 * 365 * 8, 0); CurrencyUnit reward15 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * 8) + 1, 0); CurrencyUnit reward16 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * 8) - 1, 0); CurrencyUnit reward17 = TransactionalBlock.GetRewardToFoundation(60 * 24 * 365 * 8, 0); CurrencyUnit reward18 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * 8) + 1, 0); CurrencyUnit reward22 = TransactionalBlock.GetRewardToFoundationInterval(((365 * 8) - 1) * 60 * 24, 0); CurrencyUnit reward23 = TransactionalBlock.GetRewardToFoundationInterval(60 * 24 * 365 * 8, 0); CurrencyUnit reward24 = TransactionalBlock.GetRewardToFoundationInterval(((365 * 8) + 1) * 60 * 24, 0); if (reward4.rawAmount != initial.rawAmount * rate) throw new Exception("test11_46"); if (reward13.rawAmount != initial.rawAmount * rate * 0.9m) throw new Exception("test11_47"); if (reward16.rawAmount != initial.rawAmount * rate * 0.1m) throw new Exception("test11_48"); if (reward22.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m) throw new Exception("test11_49"); if (reward5.rawAmount != 0) throw new Exception("test11_50"); if (reward14.rawAmount != 0) throw new Exception("test11_51"); if (reward17.rawAmount != 0) throw new Exception("test11_52"); if (reward23.rawAmount != 0) throw new Exception("test11_53"); if (reward6.rawAmount != 0) throw new Exception("test11_54"); if (reward15.rawAmount != 0) throw new Exception("test11_55"); if (reward18.rawAmount != 0) throw new Exception("test11_56"); if (reward24.rawAmount != 0) throw new Exception("test11_57"); Console.WriteLine("test11_succeeded"); } //Blockのテスト2 public static void Test12() { BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; if (i > 0) { NormalBlock nblk = blks[i] as NormalBlock; byte[] nblkBytes = nblk.ToBinary(); NormalBlock nblkRestore = SHAREDDATA.FromBinary<NormalBlock>(nblkBytes); if (!nblk.Id.Equals(nblkRestore.Id)) throw new Exception("test12_1"); byte[] nblkBytes2 = SHAREDDATA.ToBinary<Block>(blks[i]); NormalBlock nblkRestore2 = SHAREDDATA.FromBinary<Block>(nblkBytes2) as NormalBlock; if (!nblk.Id.Equals(nblkRestore2.Id)) throw new Exception("test12_2"); } } GenesisBlock gblk = blks[0] as GenesisBlock; Creahash gblkid = new Creahash(gblk.ToBinary()); if (!gblk.Id.Equals(gblkid)) throw new Exception("test12_3"); NormalBlock nblk2 = blks[1] as NormalBlock; Creahash nblkid = new Creahash(nblk2.header.ToBinary()); if (!nblk2.Id.Equals(nblkid)) throw new Exception("test12_4"); nblk2.UpdateTimestamp(DateTime.Now); Creahash nblkid2 = new Creahash(nblk2.header.ToBinary()); if (!nblk2.Id.Equals(nblkid2)) throw new Exception("test12_5"); nblk2.UpdateNonce(new byte[10]); Creahash nblkid3 = new Creahash(nblk2.header.ToBinary()); if (!nblk2.Id.Equals(nblkid3)) throw new Exception("test12_6"); nblk2.UpdateMerkleRootHash(); Creahash nblkid4 = new Creahash(nblk2.header.ToBinary()); if (!nblk2.Id.Equals(nblkid4)) throw new Exception("test12_7"); if (!nblk2.VerifyBlockType()) throw new Exception("test12_8"); FoundationalBlock fblk = new FoundationalBlock(); fblk.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, nblk2.coinbaseTxToMiner, nblk2.transferTxs); byte[] fblkBytes = fblk.ToBinary(); FoundationalBlock fblkRestore = SHAREDDATA.FromBinary<FoundationalBlock>(fblkBytes); if (!fblk.Id.Equals(fblkRestore.Id)) throw new Exception("test12_9"); byte[] fblkBytes2 = SHAREDDATA.ToBinary<Block>(fblk); FoundationalBlock fblkRestore2 = SHAREDDATA.FromBinary<Block>(fblkBytes2) as FoundationalBlock; if (!fblk.Id.Equals(fblkRestore2.Id)) throw new Exception("test12_10"); if (fblk.VerifyBlockType()) throw new Exception("test12_11"); if (!nblk2.VerifyMerkleRootHash()) throw new Exception("test12_12"); byte[] nblkBytes3 = nblk2.ToBinary(); NormalBlock nblk3 = SHAREDDATA.FromBinary<NormalBlock>(nblkBytes3); nblk3.header.merkleRootHash.hash[0] ^= 255; if (nblk3.VerifyMerkleRootHash()) throw new Exception("test12_13"); byte[] nonce = new byte[10]; while (true) { nblk2.UpdateNonce(nonce); if (nblk2.Id.hash[0] == 0 && nblk2.Id.hash[1] <= 127) { if (!nblk2.VerifyId()) throw new Exception("test12_14"); break; } if (nblk2.VerifyId()) throw new Exception("test12_15"); int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } TransferTransaction[] transferTxs1 = new TransferTransaction[99]; for (int i = 0; i < transferTxs1.Length; i++) transferTxs1[i] = (blks[2] as TransactionalBlock).transferTxs[0]; TransferTransaction[] transferTxs2 = new TransferTransaction[100]; for (int i = 0; i < transferTxs2.Length; i++) transferTxs2[i] = (blks[2] as TransactionalBlock).transferTxs[0]; NormalBlock nblk4 = new NormalBlock(); nblk4.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, transferTxs1); NormalBlock nblk5 = new NormalBlock(); nblk5.LoadVersion0(nblk2.header, nblk2.coinbaseTxToMiner, transferTxs2); if (!nblk4.VerifyNumberOfTxs()) throw new Exception("test12_16"); if (nblk5.VerifyNumberOfTxs()) throw new Exception("test12_17"); for (int i = 1; i < blks.Length; i++) { TransactionalBlock tblk = blks[i] as TransactionalBlock; CurrencyUnit amount = tblk.GetActualRewardToMinerAndTxFee(); CurrencyUnit amount2 = tblk.GetValidRewardToMinerAndTxFee(blkCons[i].prevTxOutss); CurrencyUnit amount3 = tblk.GetValidTxFee(blkCons[i].prevTxOutss); if (amount.rawAmount != (long)5400000000 + blkCons[i].feeRawAmount) throw new Exception("test12_18"); if (amount2.rawAmount != amount.rawAmount) throw new Exception("test12_19"); if (amount3.rawAmount != blkCons[i].feeRawAmount) throw new Exception("test12_20"); if (!tblk.VerifyRewardAndTxFee(blkCons[i].prevTxOutss)) throw new Exception("test12_21"); if (!tblk.VerifyTransferTransaction(blkCons[i].prevTxOutss)) throw new Exception("test12_22"); bool flag = false; TransactionOutput[][] invalidPrevTxOutss = new TransactionOutput[blkCons[i].prevTxOutss.Length][]; for (int j = 0; j < invalidPrevTxOutss.Length; j++) { invalidPrevTxOutss[j] = new TransactionOutput[blkCons[i].prevTxOutss[j].Length]; for (int k = 0; k < invalidPrevTxOutss[j].Length; k++) { if (j == 1 && k == 0) { invalidPrevTxOutss[j][k] = new TransactionOutput(); invalidPrevTxOutss[j][k].LoadVersion0(new Sha256Ripemd160Hash(), new CurrencyUnit(0)); flag = true; } else invalidPrevTxOutss[j][k] = blkCons[i].prevTxOutss[j][k]; } } if (flag) { if (tblk.VerifyRewardAndTxFee(invalidPrevTxOutss)) throw new Exception("test12_23"); if (tblk.VerifyTransferTransaction(invalidPrevTxOutss)) throw new Exception("test12_24"); } } Console.WriteLine("test12_succeeded"); } //BlockManagerのテスト2 public static void Test13() { BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[100]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; } string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); BlockManager blkmanager = new BlockManager(bmdb, bdb, bfpdb, 1000, 1000, 300); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < blks.Length; i++) blkmanager.AddMainBlock(blks[i]); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test13_1", stopwatch.ElapsedMilliseconds.ToString() + "ms")); FileInfo fi = new FileInfo(bdbPath); Console.WriteLine(string.Join(":", "test13_1", fi.Length.ToString() + "bytes")); Block[] blks2 = new Block[blks.Length]; stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < blks.Length; i++) blks2[i] = blkmanager.GetMainBlock(i); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test13_2", stopwatch.ElapsedMilliseconds.ToString() + "ms")); for (int i = 0; i < blks.Length; i++) if (!blks2[i].Id.Equals(blks[i].Id)) throw new Exception("test13_3"); Console.WriteLine("test13_succeeded"); } //BlockManagerのテスト3 public static void Test14() { BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[100]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; } string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); BlockManager blkmanager = new BlockManager(bmdb, bdb, bfpdb, 10, 10, 3); for (int i = 0; i < blks.Length; i++) blkmanager.AddMainBlock(blks[i]); Block[] blks2 = new Block[blks.Length]; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < blks.Length; i++) blks2[i] = blkmanager.GetMainBlock(i); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test14_1", stopwatch.ElapsedMilliseconds.ToString() + "ms")); for (int i = 0; i < blks.Length; i++) if (!blks2[i].Id.Equals(blks[i].Id)) throw new Exception("test14_2"); Console.WriteLine("test14_succeeded"); } //UtxoManagerのテスト4 public static void Test15() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); UtxoManager utxom = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[100]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } for (int i = 0; i < blks.Length; i++) { utxodb.Open(); utxom.ApplyBlock(blks[i], blkCons[i].prevTxOutss); utxom.SaveUFPTemp(); utxodb.Close(); utxodb.Open(); foreach (var address in blkCons[i].unspentTxOuts.Keys) foreach (var toc in blkCons[i].unspentTxOuts[address]) if (utxom.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test15_1"); foreach (var address in blkCons[i].spentTxOuts.Keys) foreach (var toc in blkCons[i].spentTxOuts[address]) if (utxom.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test15_2"); utxodb.Close(); Console.WriteLine("block" + i.ToString() + " apply tested."); } for (int i = blks.Length - 1; i > 0; i--) { utxodb.Open(); utxom.RevertBlock(blks[i], blkCons[i].prevTxOutss); utxom.SaveUFPTemp(); utxodb.Close(); utxodb.Open(); foreach (var address in blkCons[i - 1].unspentTxOuts.Keys) foreach (var toc in blkCons[i - 1].unspentTxOuts[address]) if (utxom.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test15_3"); foreach (var address in blkCons[i - 1].spentTxOuts.Keys) foreach (var toc in blkCons[i - 1].spentTxOuts[address]) if (utxom.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test15_4"); utxodb.Close(); Console.WriteLine("block" + i.ToString() + " revert tested."); } Console.WriteLine("test15_succeeded"); } //UtxoManagerのテスト5 public static void Test16() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); UtxoManager utxom = new UtxoManager(ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[100]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < blks.Length; i++) { utxodb.Open(); utxom.ApplyBlock(blks[i], blkCons[i].prevTxOutss); utxom.SaveUFPTemp(); utxodb.Close(); } stopwatch.Stop(); Console.WriteLine(string.Join(":", "test16_1", stopwatch.ElapsedMilliseconds.ToString() + "ms")); Console.WriteLine("test16_succeeded"); } //BlockChainのテスト(分岐がない場合・採掘) public static void Test17() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[100]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; Console.WriteLine("block" + i.ToString() + " mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < blks.Length; i++) blockchain.UpdateChain(blks2[i]); stopwatch.Stop(); Console.WriteLine(string.Join(":", "test17_1", stopwatch.ElapsedMilliseconds.ToString() + "ms")); Console.WriteLine("test17_succeeded"); } //BlockChainのテスト(分岐がない場合・無効ブロックなどを追加しようとした場合) public static void Test18() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; Console.WriteLine("block" + i.ToString() + " mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } if (blockchain.blocksCurrent.value != 0) throw new Exception("test18_1"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_2"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_3"); } TransactionalBlock blk1 = blks2[1] as TransactionalBlock; TransactionalBlock blk2 = blks2[2] as TransactionalBlock; Creahash hashzero = new Creahash(); BlockHeader bh5 = new BlockHeader(); bh5.LoadVersion0(100, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]); BlockHeader bh6 = new BlockHeader(); bh6.LoadVersion0(101, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]); TransactionalBlock blk100 = new NormalBlock(); blk100.LoadVersion0(bh5, blk1.coinbaseTxToMiner, blk1.transferTxs); blk100.UpdateMerkleRootHash(); TransactionalBlock blk101 = new NormalBlock(); blk101.LoadVersion0(bh6, blk1.coinbaseTxToMiner, blk1.transferTxs); blk101.UpdateMerkleRootHash(); blockchain.pendingBlocks[101] = new Dictionary<Creahash, Block>(); blockchain.rejectedBlocks[101] = new Dictionary<Creahash, Block>(); BlockChain.UpdateChainReturnType type1 = blockchain.UpdateChain(blks[0]); if (type1 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test18_5"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_6"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_7"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_8"); } bool flag2 = false; try { blockchain.UpdateChain(blk101); } catch (InvalidOperationException) { flag2 = true; } if (!flag2) throw new Exception("test18_9"); BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blk100); if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test18_10"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_11"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_12"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_13"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_14"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_15"); } if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_16"); } BlockHeader bh1 = new BlockHeader(); bh1.LoadVersion0(1, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]); TransactionalBlock blk1_2 = new NormalBlock(); blk1_2.LoadVersion0(bh1, blk1.coinbaseTxToMiner, blk1.transferTxs); blk1_2.UpdateMerkleRootHash(); BlockChain.UpdateChainReturnType type3 = blockchain.UpdateChain(blk1_2); if (type3 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test18_17"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_18"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_19"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_20"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id)) throw new Exception("test18_21"); } else if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_22"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_23"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_24"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_25"); } if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_26"); } BlockHeader bh2 = new BlockHeader(); bh2.LoadVersion0(1, blks[0].Id, DateTime.Now, blk1.Difficulty, new byte[10]); TransactionalBlock blk1_3 = new NormalBlock(); blk1_3.LoadVersion0(bh2, blk1.coinbaseTxToMiner, blk1.transferTxs); blk1_3.UpdateMerkleRootHash(); BlockChain.UpdateChainReturnType type4 = blockchain.UpdateChain(blk1_3); if (type4 != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test18_27"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_28"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_29"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_30"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id)) throw new Exception("test18_31"); if (blockchain.rejectedBlocks[i] == null) throw new Exception("test18_32"); if (blockchain.rejectedBlocks[i].Count != 1) throw new Exception("test18_33"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id)) throw new Exception("test18_34"); } else if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_35"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_36"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_37"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_38"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_39"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_40"); } } TransactionalBlock blk1_4 = TransactionalBlock.GetBlockTemplate(1, blk1.coinbaseTxToMiner, blk2.transferTxs, _indexToBlock, 0); while (true) { blk1_4.UpdateTimestamp(DateTime.Now); blk1_4.UpdateNonce(nonce); if (blk1_4.Id.CompareTo(blk1_4.header.difficulty.Target) <= 0) { Console.WriteLine("block1_4 mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } BlockChain.UpdateChainReturnType type5 = blockchain.UpdateChain(blk1_4); if (type5 != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test18_41"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_42"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_43"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_44"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id)) throw new Exception("test18_45"); if (blockchain.rejectedBlocks[i] == null) throw new Exception("test18_46"); if (blockchain.rejectedBlocks[i].Count != 2) throw new Exception("test18_47"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id)) throw new Exception("test18_48"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id)) throw new Exception("test18_49"); } else if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_50"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_51"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_52"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_53"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_54"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_55"); } } BlockChain.UpdateChainReturnType type8 = blockchain.UpdateChain(blk1_3); if (type8 != BlockChain.UpdateChainReturnType.invariable) throw new Exception("test18_56"); if (blockchain.blocksCurrent.value != 1) throw new Exception("test18_57"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_58"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_59"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id)) throw new Exception("test18_60"); if (blockchain.rejectedBlocks[i] == null) throw new Exception("test18_61"); if (blockchain.rejectedBlocks[i].Count != 2) throw new Exception("test18_62"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id)) throw new Exception("test18_63"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id)) throw new Exception("test18_64"); } else if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_65"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_66"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_67"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_68"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_69"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_70"); } } BlockChain.UpdateChainReturnType type6 = blockchain.UpdateChain(blk1); if (type6 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test18_71"); BlockChain.UpdateChainReturnType type7 = blockchain.UpdateChain(blk1_3); if (type7 != BlockChain.UpdateChainReturnType.invariable) throw new Exception("test18_72"); if (blockchain.blocksCurrent.value != 2) throw new Exception("test18_73"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_74"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_75"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id)) throw new Exception("test18_76"); if (blockchain.rejectedBlocks[i] == null) throw new Exception("test18_77"); if (blockchain.rejectedBlocks[i].Count != 2) throw new Exception("test18_78"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id)) throw new Exception("test18_79"); if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id)) throw new Exception("test18_80"); } else if (i == 101) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test18_81"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test18_82"); if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id)) throw new Exception("test18_83"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_84"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test18_85"); if (blockchain.rejectedBlocks[i] != null) throw new Exception("test18_86"); } } BlockHeader bh3 = new BlockHeader(); bh3.LoadVersion0(2, hashzero, DateTime.Now, blk2.Difficulty, new byte[10]); TransactionalBlock blk2_2 = new NormalBlock(); blk2_2.LoadVersion0(bh3, blk2.coinbaseTxToMiner, blk2.transferTxs); blk2_2.UpdateMerkleRootHash(); BlockChain.UpdateChainReturnType type9 = blockchain.UpdateChain(blk2_2); if (type9 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test18_87"); BlockHeader bh4 = new BlockHeader(); bh4.LoadVersion0(2, blk1_2.Id, DateTime.Now, blk2.Difficulty, new byte[10]); TransactionalBlock blk2_3 = new NormalBlock(); blk2_3.LoadVersion0(bh4, blk2.coinbaseTxToMiner, blk2.transferTxs); blk2_3.UpdateMerkleRootHash(); BlockChain.UpdateChainReturnType type10 = blockchain.UpdateChain(blk2_3); if (type10 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test18_88"); BlockHeader bh7 = new BlockHeader(); bh7.LoadVersion0(2, blk1_3.Id, DateTime.Now, blk2.Difficulty, new byte[10]); TransactionalBlock blk2_4 = new NormalBlock(); blk2_4.LoadVersion0(bh7, blk2.coinbaseTxToMiner, blk2.transferTxs); blk2_4.UpdateMerkleRootHash(); BlockChain.UpdateChainReturnType type13 = blockchain.UpdateChain(blk2_4); if (type13 != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test18_91"); for (int i = 2; i < blks2.Length; i++) { BlockChain.UpdateChainReturnType type11 = blockchain.UpdateChain(blks2[i]); if (type11 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test18_89"); } TransactionalBlock blk10 = TransactionalBlock.GetBlockTemplate(10, blk2.coinbaseTxToMiner, blk2.transferTxs, _indexToBlock, 0); while (true) { blk10.UpdateTimestamp(DateTime.Now); blk10.UpdateNonce(nonce); if (blk10.Id.CompareTo(blk10.header.difficulty.Target) <= 0) { Console.WriteLine("block10 mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } BlockChain.UpdateChainReturnType type12 = blockchain.UpdateChain(blk10); if (type12 != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test18_90"); Console.WriteLine("test18_succeeded"); } //BlockChainのテスト(分岐がない場合・採掘・順番通りに追加されなかった場合) public static void Test19() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[8]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; Console.WriteLine("block" + i.ToString() + " mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks2[2]); if (type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_1"); if (blockchain.blocksCurrent.value != 0) throw new Exception("test19_2"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 3) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test19_3"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test19_4"); if (!blockchain.pendingBlocks[i].Keys.Contains(blks2[2].Id)) throw new Exception("test19_5"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test19_6"); } if (blockchain.rejectedBlocks[i] != null) throw new Exception("test19_7"); } BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks2[1]); if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_8"); if (blockchain.blocksCurrent.value != 0) throw new Exception("test19_9"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test19_10"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test19_11"); if (!blockchain.pendingBlocks[i].Keys.Contains(blks2[1].Id)) throw new Exception("test19_12"); } else if (i == 3) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test19_13"); if (blockchain.pendingBlocks[i].Count != 1) throw new Exception("test19_14"); if (!blockchain.pendingBlocks[i].Keys.Contains(blks2[2].Id)) throw new Exception("test19_15"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test19_16"); } if (blockchain.rejectedBlocks[i] != null) throw new Exception("test19_17"); } BlockChain.UpdateChainReturnType type3 = blockchain.UpdateChain(blks2[0]); if (type3 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test19_18"); if (blockchain.headBlockIndex != 2) throw new Exception("test19_19"); if (blockchain.blocksCurrent.value != 3) throw new Exception("test19_20"); for (int i = 0; i < blockchain.pendingBlocks.Length; i++) { if (i == 2 || i == 3) { if (blockchain.pendingBlocks[i] == null) throw new Exception("test19_21"); if (blockchain.pendingBlocks[i].Count != 0) throw new Exception("test19_22"); } else { if (blockchain.pendingBlocks[i] != null) throw new Exception("test19_23"); } if (blockchain.rejectedBlocks[i] != null) throw new Exception("test19_24"); } BlockChain.UpdateChainReturnType type4 = blockchain.UpdateChain(blks2[6]); BlockChain.UpdateChainReturnType type5 = blockchain.UpdateChain(blks2[7]); BlockChain.UpdateChainReturnType type6 = blockchain.UpdateChain(blks2[4]); BlockChain.UpdateChainReturnType type7 = blockchain.UpdateChain(blks2[5]); BlockChain.UpdateChainReturnType type8 = blockchain.UpdateChain(blks2[3]); if (type4 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_25"); if (type5 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_26"); if (type6 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_27"); if (type7 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test19_28"); if (type8 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test19_29"); if (blockchain.headBlockIndex != 7) throw new Exception("test19_30"); utxodb.Open(); foreach (var address in blkCons[7].unspentTxOuts.Keys) foreach (var toc in blkCons[7].unspentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test19_31"); foreach (var address in blkCons[7].spentTxOuts.Keys) foreach (var toc in blkCons[7].spentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test19_32"); utxodb.Close(); Console.WriteLine("test19_succeeded"); } //BlockChainのテスト(分岐がある場合・採掘) public static void Test20() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; double cumulativeDiff1 = 0.0; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } Console.WriteLine(); Block[] blks3 = new Block[blks.Length]; double cumulativeDiff2 = 0.0; Func<long, TransactionalBlock> _indexToBlock2 = (index) => blks3[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks3[i] = blks[i]; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk3 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock2, 0); nonce = new byte[10]; while (true) { tblk3.UpdateTimestamp(DateTime.Now); tblk3.UpdateNonce(nonce); if (tblk3.Id.CompareTo(tblk3.header.difficulty.Target) <= 0) { blks3[i] = tblk3; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 mined. " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; Thread.Sleep(1); } } if (cumulativeDiff2 >= cumulativeDiff1) { Console.WriteLine("test20_not_tested."); return; } cumulativeDiff1 = 0.0; int minIndex = 0; for (int i = 0; i < blks.Length; i++) { cumulativeDiff1 += blks2[i].Difficulty.Diff; if (cumulativeDiff1 > cumulativeDiff2) { minIndex = i; break; } } for (int i = 0; i < blks.Length; i++) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks3[i]); if (type != BlockChain.UpdateChainReturnType.updated) throw new Exception("test20_1"); } for (int i = 1; i < minIndex; i++) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks2[i]); if (type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test20_2"); } BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks2[minIndex]); if (type2 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test20_3"); utxodb.Open(); foreach (var address in blkCons[minIndex].unspentTxOuts.Keys) foreach (var toc in blkCons[minIndex].unspentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test20_4"); foreach (var address in blkCons[minIndex].spentTxOuts.Keys) foreach (var toc in blkCons[minIndex].spentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test20_5"); utxodb.Close(); Console.WriteLine("test20_succeeded"); } //BlockChainのテスト(分岐がある場合・採掘・交互に追加していく場合) public static void Test21() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; double cumulativeDiff1 = 0.0; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } Console.WriteLine(); Block[] blks3 = new Block[blks.Length]; double cumulativeDiff2 = 0.0; Func<long, TransactionalBlock> _indexToBlock2 = (index) => blks3[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks3[i] = blks[i]; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk3 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock2, 0); nonce = new byte[10]; while (true) { tblk3.UpdateTimestamp(DateTime.Now); tblk3.UpdateNonce(nonce); if (tblk3.Id.CompareTo(tblk3.header.difficulty.Target) <= 0) { blks3[i] = tblk3; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 mined. " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } cumulativeDiff1 = 0.0; cumulativeDiff2 = 0.0; blockchain.UpdateChain(blks2[0]); for (int i = 1; i < blks.Length; i++) { cumulativeDiff1 += blks2[i].Difficulty.Diff; BlockChain.UpdateChainReturnType type1 = blockchain.UpdateChain(blks2[i]); if (cumulativeDiff1 > cumulativeDiff2) { if (type1 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test21_1"); } else { if (type1 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test21_3"); } cumulativeDiff2 += blks3[i].Difficulty.Diff; BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks3[i]); if (cumulativeDiff2 > cumulativeDiff1) { if (type2 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test21_2"); } else { if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test21_4"); } } utxodb.Open(); foreach (var address in blkCons[9].unspentTxOuts.Keys) foreach (var toc in blkCons[9].unspentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test21_5"); foreach (var address in blkCons[9].spentTxOuts.Keys) foreach (var toc in blkCons[9].spentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test21_6"); utxodb.Close(); Console.WriteLine("test21_succeeded"); } //BlockChainのテスト(分岐がある場合・採掘・順番通りに追加されなかった場合) public static void Test22() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; double[] cumulativeDiffs0 = new double[blks.Length]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; cumulativeDiffs0[i] = i == 0 ? blks[i].Difficulty.Diff : cumulativeDiffs0[i - 1] + blks[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; double[] cumulativeDiffs1 = new double[blks.Length]; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; cumulativeDiffs1[i] = blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiffs1[i].ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; cumulativeDiffs1[i] = cumulativeDiffs1[i - 1] + blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiffs1[i].ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } int forkIndex1 = 0; int forkIndex2 = 0; int[] forkIndexes = (blks.Length - 1).RandomNums(); if (forkIndexes[0] < forkIndexes[1]) { forkIndex1 = forkIndexes[0] + 1; forkIndex2 = forkIndexes[1] + 1; } else { forkIndex1 = forkIndexes[1] + 1; forkIndex2 = forkIndexes[0] + 1; } Block[] blks3 = new Block[blks.Length]; double[] cumulativeDiffs2 = new double[blks.Length]; Func<long, TransactionalBlock> _indexToBlock2 = (index) => index >= forkIndex1 ? blks3[index] as TransactionalBlock : blks2[index] as TransactionalBlock; for (int i = forkIndex1; i < blks.Length; i++) { TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk3 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock2, 0); nonce = new byte[10]; while (true) { tblk3.UpdateTimestamp(DateTime.Now); tblk3.UpdateNonce(nonce); if (tblk3.Id.CompareTo(tblk3.header.difficulty.Target) <= 0) { blks3[i] = tblk3; if (i == forkIndex1) cumulativeDiffs2[i] = cumulativeDiffs1[i - 1] + blks3[i].Difficulty.Diff; else cumulativeDiffs2[i] = cumulativeDiffs2[i - 1] + blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 mined. " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiffs2[i].ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } Block[] blks4 = new Block[blks.Length]; double[] cumulativeDiffs3 = new double[blks.Length]; Func<long, TransactionalBlock> _indexToBlock3 = (index) => index >= forkIndex2 ? blks4[index] as TransactionalBlock : blks2[index] as TransactionalBlock; for (int i = forkIndex2; i < blks.Length; i++) { TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk3 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock3, 0); nonce = new byte[10]; while (true) { tblk3.UpdateTimestamp(DateTime.Now); tblk3.UpdateNonce(nonce); if (tblk3.Id.CompareTo(tblk3.header.difficulty.Target) <= 0) { blks4[i] = tblk3; if (i == forkIndex2) cumulativeDiffs3[i] = cumulativeDiffs1[i - 1] + blks4[i].Difficulty.Diff; else cumulativeDiffs3[i] = cumulativeDiffs3[i - 1] + blks4[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_3 mined. " + blks4[i].Difficulty.Diff.ToString() + " " + cumulativeDiffs3[i].ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } bool?[] map1 = new bool?[blks.Length]; bool?[] map2 = new bool?[blks.Length]; bool?[] map3 = new bool?[blks.Length]; bool?[] map4 = new bool?[blks.Length]; for (int i = 0; i < blks.Length; i++) { map1[i] = i == 0 ? (bool?)null : false; map2[i] = i == 0 ? (bool?)null : false; map3[i] = i < forkIndex1 ? (bool?)null : false; map4[i] = i < forkIndex2 ? (bool?)null : false; } blockchain.UpdateChain(blks[0]); int[] randomnums = (4 * blks.Length).RandomNums(); double cumulativeDiff = 0.0; int main = 0; int rejectedIndex = 0; for (int i = 0; i < randomnums.Length; i++) { int keiretsu = randomnums[i] / blks.Length; int index = randomnums[i] % blks.Length; if ((keiretsu == 0 && map1[index] == null) || (keiretsu == 1 && map2[index] == null) || (keiretsu == 2 && map3[index] == null) || (keiretsu == 3 && map4[index] == null)) continue; if (keiretsu == 0) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks[index]); bool flag = false; for (int j = index - 1; j > 0; j--) if (!map1[j].Value) { flag = true; break; } if (!flag && index != 1) { if (type != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test22_1"); } else { if (!flag) { int headIndex = index; for (int j = index + 1; j < blks.Length; j++) if (map1[j].Value) headIndex = j; else break; if (cumulativeDiff >= cumulativeDiffs0[headIndex]) flag = true; else rejectedIndex = headIndex; } if (flag && type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test22_2"); if (!flag && type != BlockChain.UpdateChainReturnType.updatedAndRejected) throw new Exception("test22_3"); } map1[index] = true; } else if (keiretsu == 1) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks2[index]); bool flag = false; for (int j = index - 1; j > 0; j--) if (!map2[j].Value) { flag = true; break; } if (!flag) { int headIndex1 = index; for (int j = index + 1; j < blks.Length; j++) if (map2[j].Value) headIndex1 = j; else break; double cdiff = cumulativeDiffs1[headIndex1]; int m = 1; if (headIndex1 + 1 >= forkIndex1 && map3[forkIndex1].Value) { int headIndex2 = forkIndex1; for (int j = forkIndex1 + 1; j < blks.Length; j++) if (map3[j].Value) headIndex2 = j; else break; //<未実装>等しい場合の対処 if (cumulativeDiffs2[headIndex2] > cdiff) { cdiff = cumulativeDiffs2[headIndex2]; m = 2; } else if (cumulativeDiffs2[headIndex2] == cdiff) { Console.WriteLine("not_implemented_test_case"); return; } } if (headIndex1 + 1 >= forkIndex2 && map4[forkIndex2].Value) { int headIndex3 = forkIndex2; for (int j = forkIndex2 + 1; j < blks.Length; j++) if (map4[j].Value) headIndex3 = j; else break; //<未実装>等しい場合の対処 if (cumulativeDiffs3[headIndex3] > cdiff) { cdiff = cumulativeDiffs3[headIndex3]; m = 3; } else if (cumulativeDiffs3[headIndex3] == cdiff) { Console.WriteLine("not_implemented_test_case"); return; } } if (cumulativeDiff >= cdiff) flag = true; else { cumulativeDiff = cdiff; main = m; } } if (flag && type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test22_4"); if (!flag && type != BlockChain.UpdateChainReturnType.updated) throw new Exception("test22_5"); map2[index] = true; } else if (keiretsu == 2) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks3[index]); bool flag = false; for (int j = index - 1; j >= forkIndex1; j--) if (!map3[j].Value) { flag = true; break; } if (!flag) for (int j = forkIndex1 - 1; j > 0; j--) if (!map2[j].Value) { flag = true; break; } if (!flag) { int headIndex = index; for (int j = index + 1; j < blks.Length; j++) if (map3[j].Value) headIndex = j; else break; if (cumulativeDiff >= cumulativeDiffs2[headIndex]) flag = true; else { cumulativeDiff = cumulativeDiffs2[headIndex]; main = 2; } } if (flag && type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test22_6"); if (!flag && type != BlockChain.UpdateChainReturnType.updated) throw new Exception("test22_7"); map3[index] = true; } else if (keiretsu == 3) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks4[index]); bool flag = false; for (int j = index - 1; j >= forkIndex2; j--) if (!map4[j].Value) { flag = true; break; } if (!flag) for (int j = forkIndex2 - 1; j > 0; j--) if (!map2[j].Value) { flag = true; break; } if (!flag) { int headIndex = index; for (int j = index + 1; j < blks.Length; j++) if (map4[j].Value) headIndex = j; else break; if (cumulativeDiff >= cumulativeDiffs3[headIndex]) flag = true; else { cumulativeDiff = cumulativeDiffs3[headIndex]; main = 3; } } if (flag && type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test22_8"); if (!flag && type != BlockChain.UpdateChainReturnType.updated) throw new Exception("test22_9"); map4[index] = true; } bool flag2 = true; for (int j = 1; j < blks.Length; j++) { if (map1[j].Value) { if (flag2 && j <= rejectedIndex) { if (blockchain.rejectedBlocks[j + 1] == null || !blockchain.rejectedBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_10"); if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_11"); } else { if (blockchain.rejectedBlocks[j + 1] != null && blockchain.rejectedBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_12"); if (blockchain.pendingBlocks[j + 1] == null || !blockchain.pendingBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_13"); } } else { flag2 = false; if (blockchain.rejectedBlocks[j + 1] != null && blockchain.rejectedBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_14"); if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks[j].Id)) throw new Exception("test22_15"); } } bool flag3 = true; for (int j = 1; j < blks.Length; j++) { if (blockchain.rejectedBlocks[j + 1] != null && blockchain.rejectedBlocks[j + 1].Keys.Contains(blks2[j].Id)) throw new Exception("test22_16"); if (map2[j].Value) { if (flag3 && (main == 1 || (main == 2 && j < forkIndex1) || (main == 3 && j < forkIndex2))) { if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks2[j].Id)) throw new Exception("test22_17"); } else { if (blockchain.pendingBlocks[j + 1] == null || !blockchain.pendingBlocks[j + 1].Keys.Contains(blks2[j].Id)) throw new Exception("test22_18"); } } else { flag3 = false; if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks2[j].Id)) throw new Exception("test22_19"); } } bool flag4 = true; for (int j = forkIndex1; j < blks.Length; j++) { if (blockchain.rejectedBlocks[j + 1] != null && blockchain.rejectedBlocks[j + 1].Keys.Contains(blks3[j].Id)) throw new Exception("test22_20"); if (map3[j].Value) { if (flag4 && main == 2) { if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks3[j].Id)) throw new Exception("test22_21"); } else { if (blockchain.pendingBlocks[j + 1] == null || !blockchain.pendingBlocks[j + 1].Keys.Contains(blks3[j].Id)) throw new Exception("test22_22"); } } else { flag4 = false; if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks3[j].Id)) throw new Exception("test22_23"); } } bool flag5 = true; for (int j = forkIndex2; j < blks.Length; j++) { if (blockchain.rejectedBlocks[j + 1] != null && blockchain.rejectedBlocks[j + 1].Keys.Contains(blks4[j].Id)) throw new Exception("test22_24"); if (map4[j].Value) { if (flag5 && main == 3) { if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks4[j].Id)) throw new Exception("test22_25"); } else { if (blockchain.pendingBlocks[j + 1] == null || !blockchain.pendingBlocks[j + 1].Keys.Contains(blks4[j].Id)) throw new Exception("test22_26"); } } else { flag5 = false; if (blockchain.pendingBlocks[j + 1] != null && blockchain.pendingBlocks[j + 1].Keys.Contains(blks4[j].Id)) throw new Exception("test22_27"); } } } Block headBlock = blockchain.GetHeadBlock(); if (main == 1) { if (!headBlock.Id.Equals(blks2[9].Id)) throw new Exception("test22_28"); } else if (main == 2) { if (!headBlock.Id.Equals(blks3[9].Id)) throw new Exception("test22_29"); } else if (main == 3) { if (!headBlock.Id.Equals(blks4[9].Id)) throw new Exception("test22_30"); } else throw new InvalidOperationException(); utxodb.Open(); foreach (var address in blkCons[9].unspentTxOuts.Keys) foreach (var toc in blkCons[9].unspentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) == null) throw new Exception("test22_31"); foreach (var address in blkCons[9].spentTxOuts.Keys) foreach (var toc in blkCons[9].spentTxOuts[address]) if (blockchain.FindUtxo(address, toc.bIndex, toc.txIndex, toc.txOutIndex) != null) throw new Exception("test22_32"); utxodb.Close(); Console.WriteLine("test22_succeeded"); } //BlockChainのテスト(分岐がある場合・採掘・長過ぎる場合) public static void Test23() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb, 100, 3, 1000, 1000); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; double cumulativeDiff1 = 0.0; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } Console.WriteLine(); Block[] blks3 = new Block[blks.Length]; double cumulativeDiff2 = 0.0; Func<long, TransactionalBlock> _indexToBlock2 = (index) => blks3[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks3[i] = blks[i]; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk3 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock2, 0); nonce = new byte[10]; while (true) { tblk3.UpdateTimestamp(DateTime.Now); tblk3.UpdateNonce(nonce); if (tblk3.Id.CompareTo(tblk3.header.difficulty.Target) <= 0) { blks3[i] = tblk3; cumulativeDiff2 += blks3[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_2 mined. " + blks3[i].Difficulty.Diff.ToString() + " " + cumulativeDiff2.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } for (int i = 0; i < blks.Length; i++) blockchain.UpdateChain(blks2[i]); for (int i = blks.Length - 1; i >= blks.Length - 3; i--) { BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blks3[i]); if (i == blks.Length - 3) { if (type != BlockChain.UpdateChainReturnType.rejected) throw new Exception("test23_1"); for (int j = 0; j < blks.Length - 3; j++) if (blockchain.rejectedBlocks[j + 1] != null) throw new Exception("test23_2"); for (int j = blks.Length - 3; j < blks.Length; j++) if (blockchain.rejectedBlocks[j + 1] == null || !blockchain.rejectedBlocks[j + 1].Keys.Contains(blks3[j].Id)) throw new Exception("test23_3"); for (int j = 0; j <= blks.Length - 3; j++) if (blockchain.pendingBlocks[j + 1] != null) throw new Exception("test23_4"); for (int j = blks.Length - 3 + 1; j < blks.Length; j++) if (blockchain.pendingBlocks[j + 1] == null || blockchain.pendingBlocks[j + 1].Keys.Count != 0) throw new Exception("test23_5"); } else { if (type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test23_6"); } } Console.WriteLine("test23_succeeded"); } //BlockChainのテスト(分岐がある場合・採掘・後ろが無効な場合) public static void Test24() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb, 100, 300, 1000, 1000); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; double cumulativeDiff1 = 0.0; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; cumulativeDiff1 += blks2[i].Difficulty.Diff; Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } TransactionalBlock tblk2_1 = blks2[1] as TransactionalBlock; TransactionalBlock tblk2_2 = blks2[2] as TransactionalBlock; TransactionalBlock blk3_2 = TransactionalBlock.GetBlockTemplate(2, tblk2_2.coinbaseTxToMiner, tblk2_2.transferTxs, _indexToBlock, 0); while (true) { blk3_2.UpdateTimestamp(DateTime.Now); blk3_2.UpdateNonce(nonce); if (blk3_2.Id.CompareTo(blk3_2.header.difficulty.Target) <= 0) { Console.WriteLine("block3_2 mined. " + blk3_2.Difficulty.Diff.ToString()); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } BlockHeader bh3 = new BlockHeader(); bh3.LoadVersion0(3, blk3_2.Id, DateTime.Now, blks2[1].Difficulty, new byte[10]); NormalBlock blk3_3 = new NormalBlock(); blk3_3.LoadVersion0(bh3, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs); blk3_3.UpdateMerkleRootHash(); int forkLength = (int)Math.Floor(cumulativeDiff1 / blks2[1].Difficulty.Diff + 10); TransactionalBlock[] blks3 = new TransactionalBlock[forkLength]; blks3[0] = blk3_3; for (int i = 1; i < blks3.Length; i++) { BlockHeader bh = new BlockHeader(); bh.LoadVersion0(i + 3, blks3[i - 1].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]); NormalBlock blk3 = new NormalBlock(); blk3.LoadVersion0(bh, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs); blk3.UpdateMerkleRootHash(); blks3[i] = blk3; } BlockHeader bh4 = new BlockHeader(); bh4.LoadVersion0(4, blk3_3.Id, DateTime.Now, blks2[1].Difficulty, new byte[10]); NormalBlock blk4 = new NormalBlock(); blk4.LoadVersion0(bh4, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs); blk4.UpdateMerkleRootHash(); BlockHeader bh10 = new BlockHeader(); bh10.LoadVersion0(10, blks2[9].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]); NormalBlock blk5_10 = new NormalBlock(); blk5_10.LoadVersion0(bh10, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs); blk5_10.UpdateMerkleRootHash(); TransactionalBlock[] blks5 = new TransactionalBlock[5]; blks5[0] = blk5_10; for (int i = 1; i < blks5.Length; i++) { BlockHeader bh = new BlockHeader(); bh.LoadVersion0(i + 10, blks5[i - 1].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]); NormalBlock blk5 = new NormalBlock(); blk5.LoadVersion0(bh, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs); blk5.UpdateMerkleRootHash(); blks5[i] = blk5; } BlockChain.UpdateChainReturnType type5 = blockchain.UpdateChain(blks2[0]); if (type5 != BlockChain.UpdateChainReturnType.updated) throw new Exception("test24_5"); BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blk4); if (type != BlockChain.UpdateChainReturnType.pending) throw new Exception("test24_1"); for (int i = 2; i < blks2.Length; i++) { BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks2[i]); if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test24_2"); } for (int i = 0; i < blks5.Length; i++) { BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks5[i]); if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test24_3"); } BlockChain.UpdateChainReturnType type3 = blockchain.UpdateChain(blk3_2); if (type3 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test24_1"); for (int i = 0; i < blks3.Length; i++) { BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks3[i]); if (type2 != BlockChain.UpdateChainReturnType.pending) throw new Exception("test24_4"); } BlockChain.UpdateChainReturnType type4 = blockchain.UpdateChain(blks2[1]); if (type4 != BlockChain.UpdateChainReturnType.updatedAndRejected) throw new Exception("test24_6"); if (blockchain.blocksCurrent.value != 10) throw new Exception("test19_2"); Console.WriteLine("test24_succeeded"); } //2014/12/17追加 BlockChainの試験(口座残高) public static void Test25() { string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath); string bcadbPath = bcadb.GetPath(); if (File.Exists(bcadbPath)) File.Delete(bcadbPath); BlockManagerDB bmdb = new BlockManagerDB(basepath); string bmdbPath = bmdb.GetPath(); if (File.Exists(bmdbPath)) File.Delete(bmdbPath); BlockDB bdb = new BlockDB(basepath); string bdbPath = bdb.GetPath(0); if (File.Exists(bdbPath)) File.Delete(bdbPath); BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath); string bfpPath = bfpdb.GetPath(); if (File.Exists(bfpPath)) File.Delete(bfpPath); UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath); string ufadbPath = ufadb.GetPath(); if (File.Exists(ufadbPath)) File.Delete(ufadbPath); UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath); string ufpdbPath = ufpdb.GetPath(); if (File.Exists(ufpdbPath)) File.Delete(ufpdbPath); UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath); string ufptempdbPath = ufptempdb.GetPath(); if (File.Exists(ufptempdbPath)) File.Delete(ufptempdbPath); UtxoDB utxodb = new UtxoDB(basepath); string utxodbPath = utxodb.GetPath(); if (File.Exists(utxodbPath)) File.Delete(utxodbPath); BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb); BlockGenerator bg = new BlockGenerator(); Block[] blks = new Block[10]; BlockContext[] blkCons = new BlockContext[blks.Length]; for (int i = 0; i < blks.Length; i++) { blkCons[i] = bg.CreateNextValidBlock(); blks[i] = blkCons[i].block; Console.WriteLine("block" + i.ToString() + " created."); } Block[] blks2 = new Block[blks.Length]; byte[] nonce = null; Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock; for (int i = 0; i < blks.Length; i++) { if (i == 0) { blks2[i] = blks[i]; continue; } TransactionalBlock tblk = blks[i] as TransactionalBlock; TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0); nonce = new byte[10]; while (true) { tblk2.UpdateTimestamp(DateTime.Now); tblk2.UpdateNonce(nonce); if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0) { blks2[i] = tblk2; Console.WriteLine("block" + i.ToString() + " mined."); break; } int index = nonce.Length.RandomNum(); int value = 256.RandomNum(); nonce[index] = (byte)value; } } if (blockchain.registeredAddresses.Count != 0) throw new Exception("test25_1"); AddressEvent ae = new AddressEvent(new Sha256Ripemd160Hash()); blockchain.AddAddressEvent(ae); if (blockchain.registeredAddresses.Count != 1) throw new Exception("test25_2"); if (!blockchain.registeredAddresses.Keys.Contains(ae)) throw new Exception("test25_3"); if (blockchain.registeredAddresses[ae].Count != 0) throw new Exception("test25_4"); AddressEvent aeret = blockchain.RemoveAddressEvent(new Sha256Ripemd160Hash()); if (ae != aeret) throw new Exception("test25_5"); if (blockchain.registeredAddresses.Count != 0) throw new Exception("test25_6"); blockchain.AddAddressEvent(ae); Dictionary<Sha256Ripemd160Hash, Tuple<CurrencyUnit, CurrencyUnit>> balances = new Dictionary<Sha256Ripemd160Hash, Tuple<CurrencyUnit, CurrencyUnit>>(); foreach (var address in bg.addresses) { AddressEvent addressEvent = new AddressEvent(address); addressEvent.BalanceUpdated += (sender, e) => { balances[addressEvent.address] = e; }; blockchain.AddAddressEvent(addressEvent); } int counter = 0; blockchain.BalanceUpdated += (sender, e) => { counter++; }; for (int i = 0; i < blks.Length; i++) { blockchain.UpdateChain(blks2[i]); if (counter != i) throw new Exception("test25_7"); foreach (var address in bg.addresses) { long usable = 0; long unusable = 0; foreach (var txoutcon in blkCons[i].unspentTxOuts[address]) if (txoutcon.bIndex + 6 > i) unusable += txoutcon.amount.rawAmount; else usable += txoutcon.amount.rawAmount; if (balances[address].Item1.rawAmount != usable) throw new Exception("test25_2"); if (balances[address].Item2.rawAmount != unusable) throw new Exception("test25_2"); } } Console.WriteLine("test25_succeeded"); } } public class TransactionOutputContext { public TransactionOutputContext(long _bIndex, int _txIndex, int _txOutIndex, CurrencyUnit _amount, Sha256Ripemd160Hash _address, Ecdsa256KeyPair _keyPair) { bIndex = _bIndex; txIndex = _txIndex; txOutIndex = _txOutIndex; amount = _amount; address = _address; keyPair = _keyPair; } public long bIndex { get; set; } public int txIndex { get; set; } public int txOutIndex { get; set; } public CurrencyUnit amount { get; set; } public Sha256Ripemd160Hash address { get; set; } public Ecdsa256KeyPair keyPair { get; set; } public TransactionOutput GenerateTrasactionOutput() { TransactionOutput txOut = new TransactionOutput(); txOut.LoadVersion0(address, amount); return txOut; } public TransactionInput GenerateTransactionInput() { TransactionInput txIn = new TransactionInput(); txIn.LoadVersion0(bIndex, txIndex, txOutIndex, keyPair.pubKey); return txIn; } } public class BlockContext { public BlockContext(Block _block, TransactionOutput[][] _prevTxOutss, long _feesRawAmount, Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> _unspentTxOuts, Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> _spentTxOuts) { block = _block; prevTxOutss = _prevTxOutss; feeRawAmount = _feesRawAmount; unspentTxOuts = _unspentTxOuts; spentTxOuts = _spentTxOuts; } public Block block { get; set; } public TransactionOutput[][] prevTxOutss { get; set; } public long feeRawAmount { get; set; } public Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOuts { get; set; } public Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOuts { get; set; } } public class BlockGenerator { public BlockGenerator(int _numOfKeyPairs = 10, int _numOfCoinbaseTxOuts = 5, int _maxNumOfSpendTxs = 5, int _maxNumOfSpendTxOuts = 2, double _avgIORatio = 1.5) { numOfKeyPairs = _numOfKeyPairs; numOfCoinbaseTxOuts = _numOfCoinbaseTxOuts; maxNumOfSpendTxs = _maxNumOfSpendTxs; maxNumOfSpendTxOuts = _maxNumOfSpendTxOuts; avgIORatio = _avgIORatio; keyPairs = new Ecdsa256KeyPair[numOfKeyPairs]; addresses = new Sha256Ripemd160Hash[numOfKeyPairs]; for (int i = 0; i < keyPairs.Length; i++) { keyPairs[i] = new Ecdsa256KeyPair(true); addresses[i] = new Sha256Ripemd160Hash(keyPairs[i].pubKey.pubKey); } currentBIndex = -1; unspentTxOuts = new List<TransactionOutputContext>(); spentTxOuts = new List<TransactionOutputContext>(); blks = new List<Block>(); unspentTxOutsDict = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); spentTxOutsDict = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); for (int i = 0; i < keyPairs.Length; i++) { unspentTxOutsDict.Add(addresses[i], new List<TransactionOutputContext>()); spentTxOutsDict.Add(addresses[i], new List<TransactionOutputContext>()); } } private readonly int numOfKeyPairs; private readonly int numOfCoinbaseTxOuts; private readonly int maxNumOfSpendTxs; private readonly int maxNumOfSpendTxOuts; private readonly double avgIORatio; public Ecdsa256KeyPair[] keyPairs; public Sha256Ripemd160Hash[] addresses; public long currentBIndex; public List<TransactionOutputContext> unspentTxOuts; public List<TransactionOutputContext> spentTxOuts; public List<Block> blks; public Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDict; public Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDict; public BlockContext CreateNextValidBlock() { currentBIndex++; if (currentBIndex == 0) { Block blk = new GenesisBlock(); blks.Add(blk); Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); for (int i = 0; i < keyPairs.Length; i++) { unspentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>()); foreach (var toc in unspentTxOutsDict[addresses[i]]) unspentTxOutsDictClone2[addresses[i]].Add(toc); spentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>()); foreach (var toc in spentTxOutsDict[addresses[i]]) spentTxOutsDictClone2[addresses[i]].Add(toc); } return new BlockContext(blk, new TransactionOutput[][] { }, 0, unspentTxOutsDictClone2, spentTxOutsDictClone2); } int numOfSpendTxs = maxNumOfSpendTxs.RandomNum() + 1; int[] numOfSpendTxOutss = new int[numOfSpendTxs]; for (int i = 0; i < numOfSpendTxOutss.Length; i++) numOfSpendTxOutss[i] = maxNumOfSpendTxOuts.RandomNum() + 1; TransactionOutputContext[][] spendTxOutss = new TransactionOutputContext[numOfSpendTxs][]; for (int i = 0; i < spendTxOutss.Length; i++) { if (unspentTxOuts.Count == 0) break; spendTxOutss[i] = new TransactionOutputContext[numOfSpendTxOutss[i]]; for (int j = 0; j < spendTxOutss[i].Length; j++) { int index = unspentTxOuts.Count.RandomNum(); spendTxOutss[i][j] = unspentTxOuts[index]; spentTxOutsDict[unspentTxOuts[index].address].Add(unspentTxOuts[index]); unspentTxOutsDict[unspentTxOuts[index].address].Remove(unspentTxOuts[index]); spentTxOuts.Add(unspentTxOuts[index]); unspentTxOuts.RemoveAt(index); if (unspentTxOuts.Count == 0) break; } } long fee = 0; List<TransferTransaction> transferTxs = new List<TransferTransaction>(); List<TransactionOutput[]> prevTxOutsList = new List<TransactionOutput[]>(); for (int i = 0; i < spendTxOutss.Length; i++) { if (spendTxOutss[i] == null) break; long sumRawAmount = 0; List<TransactionInput> txInputsList = new List<TransactionInput>(); for (int j = 0; j < spendTxOutss[i].Length; j++) { if (spendTxOutss[i][j] == null) break; txInputsList.Add(spendTxOutss[i][j].GenerateTransactionInput()); sumRawAmount += spendTxOutss[i][j].amount.rawAmount; } TransactionInput[] txIns = txInputsList.ToArray(); int num = sumRawAmount > 1000000 ? (int)Math.Ceiling(((avgIORatio - 1) * 2) * 1.RandomDouble() * txIns.Length) : 1; TransactionOutputContext[] txOutsCon = new TransactionOutputContext[num]; TransactionOutput[] txOuts = new TransactionOutput[num]; for (int j = 0; j < txOutsCon.Length; j++) { long outAmount = 0; if (sumRawAmount > 1000000) { long sumRawAmountDivided = sumRawAmount / 1000000; int subtract = ((int)sumRawAmountDivided / 2).RandomNum() + 1; outAmount = (long)subtract * 1000000; } else outAmount = sumRawAmount; sumRawAmount -= outAmount; int index = numOfKeyPairs.RandomNum(); txOutsCon[j] = new TransactionOutputContext(currentBIndex, i + 1, j, new CurrencyUnit(outAmount), addresses[index], keyPairs[index]); txOuts[j] = txOutsCon[j].GenerateTrasactionOutput(); } fee += sumRawAmount; for (int j = 0; j < txOutsCon.Length; j++) { unspentTxOutsDict[txOutsCon[j].address].Add(txOutsCon[j]); unspentTxOuts.Add(txOutsCon[j]); } TransactionOutput[] prevTxOuts = new TransactionOutput[txIns.Length]; Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[txIns.Length]; for (int j = 0; j < prevTxOuts.Length; j++) { prevTxOuts[j] = spendTxOutss[i][j].GenerateTrasactionOutput(); privKeys[j] = spendTxOutss[i][j].keyPair.privKey; } TransferTransaction tTx = new TransferTransaction(); tTx.LoadVersion0(txIns, txOuts); tTx.Sign(prevTxOuts, privKeys); transferTxs.Add(tTx); prevTxOutsList.Add(prevTxOuts); } long rewardAndFee = TransactionalBlock.GetRewardToMiner(currentBIndex, 0).rawAmount + fee; TransactionOutputContext[] coinbaseTxOutsCon = new TransactionOutputContext[numOfCoinbaseTxOuts]; TransactionOutput[] coinbaseTxOuts = new TransactionOutput[numOfCoinbaseTxOuts]; for (int i = 0; i < coinbaseTxOutsCon.Length; i++) { long outAmount2 = 0; if (i != coinbaseTxOutsCon.Length - 1) { long rewardAndFeeDevided = rewardAndFee / 1000000; int subtract2 = ((int)rewardAndFeeDevided / 2).RandomNum() + 1; outAmount2 = (long)subtract2 * 1000000; rewardAndFee -= outAmount2; } else outAmount2 = rewardAndFee; int index = numOfKeyPairs.RandomNum(); coinbaseTxOutsCon[i] = new TransactionOutputContext(currentBIndex, 0, i, new CurrencyUnit(outAmount2), addresses[index], keyPairs[index]); coinbaseTxOuts[i] = coinbaseTxOutsCon[i].GenerateTrasactionOutput(); } CoinbaseTransaction coinbaseTx = new CoinbaseTransaction(); coinbaseTx.LoadVersion0(coinbaseTxOuts); for (int i = 0; i < coinbaseTxOutsCon.Length; i++) { unspentTxOutsDict[coinbaseTxOutsCon[i].address].Add(coinbaseTxOutsCon[i]); unspentTxOuts.Add(coinbaseTxOutsCon[i]); } prevTxOutsList.Insert(0, new TransactionOutput[] { }); Difficulty<Creahash> diff = new Difficulty<Creahash>(HASHBASE.FromHash<Creahash>(new byte[] { 0, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 })); byte[] nonce = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; BlockHeader bh = new BlockHeader(); bh.LoadVersion0(currentBIndex, blks[blks.Count - 1].Id, DateTime.Now, diff, nonce); NormalBlock nblk = new NormalBlock(); nblk.LoadVersion0(bh, coinbaseTx, transferTxs.ToArray()); nblk.UpdateMerkleRootHash(); blks.Add(nblk); Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>(); for (int i = 0; i < keyPairs.Length; i++) { unspentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>()); foreach (var toc in unspentTxOutsDict[addresses[i]]) unspentTxOutsDictClone[addresses[i]].Add(toc); spentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>()); foreach (var toc in spentTxOutsDict[addresses[i]]) spentTxOutsDictClone[addresses[i]].Add(toc); } BlockContext blkCon = new BlockContext(nblk, prevTxOutsList.ToArray(), fee, unspentTxOutsDictClone, spentTxOutsDictClone); return blkCon; } } }
using Application.Common.Validation; using Application.V1.Posts.Queries; using Domain.Enums; using System; using System.Threading.Tasks; namespace Application.V1.Posts.Validators { public class GetPostsValidator : IValidationHandler<GetPosts.Query> { public async Task<ValidationResult> Validate(GetPosts.Query request) { foreach (var drivetrain in request.Drivetrains) { if (!Enum.IsDefined(typeof(Drivetrain), drivetrain)) return ValidationResult.Fail("One or more invalid drivetrains"); } foreach (var transmission in request.Transmissions) { if (!Enum.IsDefined(typeof(Transmission), transmission)) return ValidationResult.Fail("One or more invalid transmissions"); } foreach (var bodystyle in request.BodyStyles) { if (!Enum.IsDefined(typeof(BodyStyle), bodystyle)) return ValidationResult.Fail("One or more invalid body styles"); } return ValidationResult.Success; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Accounting.Entity { public class TransactionMaster : BaseObject { public TransactionMaster() : base() { } #region Fields private int numTransMID; private DateTime dtTransDate; private string strVoucherNo; private string strVoucherPayee; private int numVoucherType; private int numTransMethodID; private int numMethodRefID; private string strMethodRefNo; private string strTransDesc; private string strApprovedBy; private DateTime dtApprovedDate; private string strModule=""; #endregion #region Properties public int TransactionMasterID { get { return numTransMID; } set { numTransMID = value; } } public DateTime TransactionDate { get { return dtTransDate; } set { dtTransDate = value; } } public string VoucherNo { get { return strVoucherNo; } set { strVoucherNo = value; } } public string VoucherPayee { get { return strVoucherPayee; } set { strVoucherPayee = value; } } public int VoucherType { get { return numVoucherType; } set { numVoucherType = value; } } public int TransactionMethodID { get { return numTransMethodID; } set { numTransMethodID = value; } } public int MethodRefID { get { return numMethodRefID; } set { numMethodRefID = value; } } public string MethodRefNo { get { return strMethodRefNo; } set { strMethodRefNo = value; } } public string TransactionDescription { get { return strTransDesc; } set { strTransDesc = value; } } public string ApprovedBy { get { return strApprovedBy; } set { strApprovedBy = value; } } public DateTime ApprovedDate { get { return dtApprovedDate; } set { dtApprovedDate = value; } } public string Module { get { return strModule; } set { strModule = value; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using CT.Data; using CT.Manager; using CT.Data.Instance; using CT.Helper; namespace CT.Net { public enum ServerPackets { welcomeFromServer = 1, registerConfirm, loadPlayer, buildingAdded, //,processAttack, processDefense, giveFewRandomBases, giveAttackableBaseData, updateResources, updateGems, giveUpdatedPlayerData //,givePreloadUpdate } public enum ClientPackets { welcomeReceived = 1, registerCheck, loadPlayerRequest, addBuilding, upgradeBuilding, buildingFixed, reportAttack, reportDefense, defenderProcessedCombat, requestFewRandomBases, requestAttackableBaseData, addUnit, removeUnit, addResources, subtractResources, addGems, subtractGems, moveBuilding, updateMineStored, updateStorageValue, leavingBase, disconnecting, addBuilder, requestPlayerDataUpdate //,requestPreloadUpdate } public class Packet : IDisposable { List<byte> buffer; byte[] readableBuffer; int readPos; public Packet() { buffer = new List<byte>(); readPos = 0; } public Packet(int id) : this() { Write(id); } public Packet(byte[] data) : this() { SetBytes(data); } #region Functions public void SetBytes(byte[] data) { Write(data); readableBuffer = buffer.ToArray(); } public void WriteLength() { buffer.InsertRange(0, BitConverter.GetBytes(buffer.Count)); } public void InsertInt(int value) { buffer.InsertRange(0, BitConverter.GetBytes(value)); } public byte[] ToArray() { return readableBuffer = buffer.ToArray(); } public int Length() { return buffer.Count; } public int UnreadLength() { return Length() - readPos; } public void Reset(bool should = true) { if (should) { buffer.Clear(); readableBuffer = null; readPos = 0; } else readPos = -4; } #endregion #region Write Data #region Conventional public void Write(byte value) { buffer.Add(value); } public void Write(byte[] values) { buffer.AddRange(values); } public void Write(short value) { buffer.AddRange(BitConverter.GetBytes(value)); } public void Write(int value) { buffer.AddRange(BitConverter.GetBytes(value)); } public void Write(long value) { buffer.AddRange(BitConverter.GetBytes(value)); } public void Write(float value) { buffer.AddRange(BitConverter.GetBytes(value)); } public void Write(bool value) { buffer.AddRange(BitConverter.GetBytes(value)); } public void Write(string value) { Write(value == null); if (value == null) return; Write(value.Length); var bytes = Encoding.ASCII.GetBytes(value); Write(bytes); } #endregion #region Special public void Write(KeyValuePair<int, int> value) { Write(value.Key); Write(value.Value); } public void Write(DateTime value) { Write(value.Year); Write(value.Month); Write(value.Day); Write(value.Hour); Write(value.Minute); Write(value.Second); } public void Write(Vector3 value) { Write(value.x); Write(value.y); Write(value.z); } public void Write(GameTime value) { Write(value.hours); Write(value.minutes); Write(value.seconds); } public void Write(BuildingInstanceData value) { bool empty = value == null; Write(empty); if (empty) return; Write(value.ID); //Write(value.Base.ID); //for checking Write(value.data.name); Write(value.level); Write(value.tileX); Write(value.tileY); Write(value.destroyed); string type = value.data.Type.ToName(); Write(type); switch (value.data.Type) { case BuildingData.BuildingType.ArmyHolder: break; case BuildingData.BuildingType.Bunker: //var bunker = value as BunkerInstanceData; //Write(bunker.squads.Count); //foreach (var unit in bunker.squads) Write(unit); break; case BuildingData.BuildingType.Lab: var lab = value as LabInstanceData; Write(lab.workingOnUnit); Write(lab.timeLeft); break; case BuildingData.BuildingType.MainHall: var hall = value as MainHallInstanceData; Write(hall.storedGold); Write(hall.storedElixir); Write(hall.CurrentData.goldCapacity); Write(hall.CurrentData.elixirCapacity); break; case BuildingData.BuildingType.Mine: var mine = value as MineInstanceData; Write(mine.stored); Write(mine.Data.resourceType == BuildingData.ResourceType.Gold); break; case BuildingData.BuildingType.Storage: var storage = value as StorageInstanceData; Write(storage.stored); Write(storage.Data.storageType == StorageData.StoreType.Gold); Write(storage.CurrentData.capacity); break; case BuildingData.BuildingType.TrainingZone: //var zone = value as TrainingZoneInstanceData; //Write(zone.trainingUnitName); //Write(zone.timeLeft); //Write(zone.slots.Count); //foreach (var slot in zone.slots) Write(slot); break; case BuildingData.BuildingType.Turret: break; case BuildingData.BuildingType.Wall: break; case BuildingData.BuildingType.Trap: break; } } #endregion #endregion #region Read Data #region Conventional public byte ReadByte(bool moveReadPos = true) { if (buffer.Count > readPos) { byte value = readableBuffer[readPos]; if (moveReadPos) readPos++; return value; } else throw new Exception("Could not read value of type 'byte'!"); } public byte[] ReadBytes(int length, bool moveReadPos = true) { if (buffer.Count > readPos) { byte[] value = buffer.GetRange(readPos, length).ToArray(); if (moveReadPos) readPos += length; return value; } else throw new Exception("Could not read value of type 'byte[]'!"); } public short ReadShort(bool moveReadPos = true) { if (buffer.Count > readPos) { short value = BitConverter.ToInt16(readableBuffer, readPos); if (moveReadPos) readPos += 2; //short is 2 bytes return value; } else throw new Exception("Could not read value of type 'short'!"); } public int ReadInt(bool moveReadPos = true) { if (buffer.Count > readPos) { int value = BitConverter.ToInt32(readableBuffer, readPos); if (moveReadPos) readPos += 4; //int is 4 bytes return value; } else throw new Exception("Could not read value of type 'int'!"); } public long ReadLong(bool moveReadPos = true) { if (buffer.Count > readPos) { long value = BitConverter.ToInt64(readableBuffer, readPos); if (moveReadPos) readPos += 8; return value; } else throw new Exception("Could not read value of type 'long'!"); } public float ReadFloat(bool moveReadPos = true) { if (buffer.Count > readPos) { float value = BitConverter.ToSingle(readableBuffer, readPos); if (moveReadPos) readPos += 4; return value; } else throw new Exception("Could not read value of type 'float'!"); } public bool ReadBool(bool moveReadPos = true) { if (buffer.Count > readPos) { bool value = BitConverter.ToBoolean(readableBuffer, readPos); if (moveReadPos) readPos++; return value; } else throw new Exception("Could not read value of type 'bool'!"); } public string ReadString(bool moveReadPos = true) { try { bool empty = ReadBool(); if (empty) return null; int length = ReadInt(); string value = Encoding.ASCII.GetString(readableBuffer, readPos, length); if (moveReadPos && value.Length > 0) readPos += length; return value; } catch { throw new Exception("Could not read value of type 'string'!"); } } #endregion #region Special public DateTime ReadDateTime() { int year = ReadInt(); int month = ReadInt(); int day = ReadInt(); int hour = ReadInt(); int minute = ReadInt(); int second = ReadInt(); return new DateTime(year, month, day, hour, minute, second); } public GameTime ReadGameTime() { return new GameTime(ReadInt(), ReadInt(), ReadInt()); } public ConstructionData ReadConstructionData(List<BuildingInstanceData> buildings) { int id = ReadInt(); //int baseID = ReadInt(); may do add at some point var time = ReadGameTime(); int x = ReadInt(); int y = ReadInt(); bool isUpgrade = ReadBool(); if (isUpgrade) { int toUpgradeID = ReadInt(); var toUpgrade = buildings.Where(b => b.ID == toUpgradeID).First(); return new ConstructionData(toUpgrade, time); } string buildingName = ReadString(); var building = LoadManager.buildingsDictionary[buildingName]; //var buildingOn = buildings.Where(b => b.ID == buildingOnID).FirstOrDefault(); return new ConstructionData(id, building, time, x, y); } public BuildingInstanceData ReadBuildingInstance() { bool empty = ReadBool(); if (empty) return null; int id = ReadInt(); //int baseID = ReadInt(); // may do use at some point string dataName = ReadString(); int level = ReadInt(); int tileX = ReadInt(); int tileY = ReadInt(); bool destroyed = ReadBool(); string type = ReadString(); var data = LoadManager.buildingsDictionary[dataName]; switch (type) { case "Army Holder": var armyHolderData = data as ArmyHoldData; return new ArmyHolderInstanceData(id, armyHolderData, level, tileX, tileY, destroyed); case "Bunker": var bunkerData = data as BunkerData; int squadsCount = ReadInt(); var squads = new List<ArmySquad>(); for (int i = 0; i < squadsCount; i++) squads.Add(ReadSquad()); return new BunkerInstanceData(id, bunkerData, level, squads, tileX, tileY, destroyed); case "Lab": var lab = data as LabData; string unit = ReadString(); GameTime timeLeft = ReadGameTime(); return new LabInstanceData(id, lab, level, unit, timeLeft, tileX, tileY, destroyed); case "Main Hall": var hall = data as MainHallData; int gold = ReadInt(); int elixir = ReadInt(); return new MainHallInstanceData(id, hall, level, gold, elixir, tileX, tileY, destroyed); case "Mine": var mine = data as MineData; int stored = ReadInt(); return new MineInstanceData(id, mine, level, stored, tileX, tileY, destroyed); case "Storage": var storage = data as StorageData; stored = ReadInt(); return new StorageInstanceData(id, storage, level, stored, tileX, tileY, destroyed); case "Training Zone": var zone = data as TrainingZoneData; string trainingUnit = ReadString(); GameTime trainTimeLeft = ReadGameTime(); int slotsCount = ReadInt(); var slots = new List<TrainingZoneInstanceData.TrainSlot>(); for (int i = 0; i < slotsCount; i++) slots.Add(new TrainingZoneInstanceData.TrainSlot(ReadSquad())); return new TrainingZoneInstanceData(id, zone, level, trainingUnit, trainTimeLeft, slots, tileX, tileY, destroyed); case "Turret": var turret = data as DefensiveData; return new TurretInstanceData(id, turret, level, tileX, tileY, destroyed); case "Trap": var trap = data as TrapData; return new TrapInstanceData(id, trap, level, tileX, tileY, destroyed); case "Wall": var wall = data as WallData; return new WallInstanceData(id, wall, level, tileX, tileY, destroyed); case "Decoration": var deco = data as DecorationData; return new DecorationInstanceData(id, deco, level, tileX, tileY, destroyed); } return null; } public ArmySquad ReadSquad() { int id = ReadInt(); string name = ReadString(); int amount = ReadInt(); return new ArmySquad(id, name, amount); } public ArmyData ReadArmy() { int squadCount = ReadInt(); var squads = new List<ArmySquad>(); for (int i = 0; i < squadCount; i++) squads.Add(ReadSquad()); return new ArmyData(squads); } public DefenseReport ReadDefenseReport(BaseData _base) { int id = ReadInt(); string invasionName = ReadString(); int lostGold = ReadInt(); int lostElixir = ReadInt(); int armyCount = ReadInt(); var army = new List<ArmySquad>(); for (int i = 0; i < armyCount; i++) army.Add(new ArmySquad(ReadString(), ReadInt())); return new DefenseReport(id, _base, invasionName, lostGold, lostElixir, army); } public AttackReport ReadAttackReport(BaseData _base) { int id = ReadInt(); string attackerUsername = ReadString(); int takenGold = ReadInt(); int takenElixir = ReadInt(); int armyCount = ReadInt(); var army = new List<ArmySquad>(); for (int i = 0; i < armyCount; i++) army.Add(new ArmySquad(ReadString(), ReadInt())); return new AttackReport(id, _base, attackerUsername, takenGold, takenElixir, army); } public BaseData ReadBase() { bool empty = ReadBool(); if (empty) return null; int id = ReadInt(); //string username = ReadString(); //may do for checking bool isHome = ReadBool(); DateTime lastVisited = ReadDateTime(); var army = ReadArmy(); int buildingsCount = ReadInt(); var buildings = new List<BuildingInstanceData>(); for (int i = 0; i < buildingsCount; i++) buildings.Add(ReadBuildingInstance()); int builders = ReadInt(); int constructionCount = ReadInt(); var constructions = new List<ConstructionData>(); for (int i = 0; i < constructionCount; i++) constructions.Add(ReadConstructionData(buildings)); var data = new BaseData(id, lastVisited, army, buildings, builders, constructions, isHome); int defenseCount = ReadInt(); for (int i = 0; i < defenseCount; i++) data.defenses.Add(ReadDefenseReport(data)); int attackCount = ReadInt(); for (int i = 0; i < attackCount; i++) data.attacks.Add(ReadAttackReport(data)); return data; } public PlayerData ReadPlayerData() { bool empty = ReadBool(); if (empty) return null; //Debug.Log("Player past the empty!"); string username = ReadString(); int pasLen = ReadInt(); byte[] password = ReadBytes(pasLen); Sprite icon = LoadManager.iconsDictionary[ReadString()]; Faction.Type faction = (Faction.Type)Enum.Parse(typeof(Faction.Type), ReadString()); int gems = ReadInt(); DateTime lastOnline = ReadDateTime(); int coloniesCount = ReadInt(); BaseData homeBase = null; List<BaseData> colonies = new List<BaseData>(coloniesCount); for (int i = 0; i < coloniesCount; i++) { var baseData = ReadBase(); if (baseData.IsHome) homeBase = baseData; else colonies.Add(baseData); } //Debug.Log("Player almost retrieved!"); var data = new PlayerData(username, password, faction, icon, gems, lastOnline, homeBase, colonies); if (data == null) Debug.Log("Something went wrong"); //else Debug.Log("Player created!"); return data; } #endregion #endregion bool disposed = false; protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { buffer = null; readableBuffer = null; readPos = 0; } disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
using FluentAssertions; using NUnit.Framework; using StreetFinder.AbbreviationsFilter; namespace Tests.UnitTests { [TestFixture] public class AbbreviationTokenExpanderTests { [Test] public void Abbreviation_at_the_beginning_should_be_expanded() { // Arrange var abbreviationTokenExpander = new AbbreviationTokenExpander(); // Act abbreviationTokenExpander.Add("prof"); abbreviationTokenExpander.Add("abc"); // Assert abbreviationTokenExpander.ElementAt(0).Should().Be("prof"); abbreviationTokenExpander.ElementAt(1).Should().Be("professor"); abbreviationTokenExpander.ElementAt(2).Should().Be("abc"); } [Test] public void Abbreviation_at_the_end_should_be_expanded() { // Arrange var abbreviationTokenExpander = new AbbreviationTokenExpander(); // Act abbreviationTokenExpander.Add("abc"); abbreviationTokenExpander.Add("str"); // Assert abbreviationTokenExpander.ElementAt(0).Should().Be("abc"); abbreviationTokenExpander.ElementAt(1).Should().Be("str"); abbreviationTokenExpander.ElementAt(2).Should().Be("strasse"); abbreviationTokenExpander.ElementAt(3).Should().Be("straße"); } [Test] public void A_token_ending_with_str_should_be_expanded_to_str() { // Arrange var abbreviationTokenExpander = new AbbreviationTokenExpander(); // Act abbreviationTokenExpander.Add("abc"); abbreviationTokenExpander.Add("foostr"); // Assert abbreviationTokenExpander.ElementAt(0).Should().Be("abc"); abbreviationTokenExpander.ElementAt(1).Should().Be("foostr"); abbreviationTokenExpander.ElementAt(2).Should().Be("strasse"); abbreviationTokenExpander.ElementAt(3).Should().Be("straße"); } } }
using System; using System.Collections.Generic; using System.Linq; using Cauldron.DocHavoc; using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; using Handelabra.Sentinels.UnitTest; using NUnit.Framework; namespace CauldronTests { [TestFixture()] public class DocHavocTests : BaseTest { protected HeroTurnTakerController DocHavoc => FindHero("DocHavoc"); [Test] public void TestDocHavocLoads() { // Arrange & Act SetupGameController("BaronBlade", "Cauldron.DocHavoc", "Megalopolis"); // Assert Assert.AreEqual(3, this.GameController.TurnTakerControllers.Count()); Assert.IsNotNull(DocHavoc); Assert.IsInstanceOf(typeof(DocHavocCharacterCardController), DocHavoc.CharacterCardController); Assert.AreEqual(30, DocHavoc.CharacterCard.HitPoints); } [Test] public void TestDocHavocInnatePowerSuccess() { // Arrange SetupGameController("BaronBlade", "Cauldron.DocHavoc", "Ra", "Megalopolis"); StartGame(); GoToUsePowerPhase(DocHavoc); DecisionSelectTarget = ra.CharacterCard; DecisionSelectTurnTaker = ra.HeroTurnTaker; QuickHandStorage(ra); QuickHPStorage(ra); // Act UsePower(DocHavoc.CharacterCard); // Assert QuickHPCheck(-3); QuickHandCheck(1); } [Test] public void TestDocHavocInnatePowerFail() { // Arrange SetupGameController("BaronBlade", "Legacy", "Cauldron.DocHavoc", "Megalopolis"); StartGame(); GoToPlayCardPhase(legacy); PutInHand("NextEvolution"); Card nextEvolution = GetCardFromHand("NextEvolution"); PlayCard(nextEvolution); GoToUsePowerPhase(legacy); DecisionSelectDamageType = DamageType.Toxic; UsePower(nextEvolution); GoToUsePowerPhase(DocHavoc); DecisionSelectTarget = legacy.CharacterCard; DecisionSelectTurnTaker = legacy.HeroTurnTaker; QuickHandStorage(legacy); QuickHPStorage(legacy); // Act UsePower(DocHavoc.CharacterCard); // Assert QuickHPCheck(0); // Legacy immune to toxic, no change to HP QuickHandCheck(0); // Hand size should still be 4 as Legacy could only draw a card if he sustained damage } [Test] public void TestIncapacitateOption1() { // Arrange SetupGameController("BaronBlade", "Legacy", "Ra", "Cauldron.DocHavoc", "Megalopolis"); StartGame(); SetHitPoints(DocHavoc.CharacterCard, 1); DealDamage(baron, DocHavoc, 2, DamageType.Melee); DealDamage(baron, legacy, 2, DamageType.Melee); DealDamage(baron, ra, 2, DamageType.Melee); Card[] healTargets = new Card[] { legacy.CharacterCard, ra.CharacterCard }; QuickHPStorage(healTargets); QuickHPUpdate(); DecisionSelectCards = healTargets; GoToUseIncapacitatedAbilityPhase(DocHavoc); // Act UseIncapacitatedAbility(DocHavoc, 0); // Assert AssertIncapacitated(DocHavoc); QuickHPCheck(1, 1); } [Test] public void TestIncapacitateOption2() { // Arrange SetupGameController("BaronBlade", "Legacy", "Ra", "Cauldron.DocHavoc", "Megalopolis"); StartGame(); SetHitPoints(DocHavoc.CharacterCard, 1); DealDamage(baron, DocHavoc, 2, DamageType.Melee); DecisionSelectTarget = legacy.CharacterCard; QuickHandStorage(legacy); // Act UseIncapacitatedAbility(DocHavoc, 1); // Assert AssertIncapacitated(DocHavoc); QuickHandCheck(1); } [Test] public void TestIncapacitateOption3() { // Arrange SetupGameController("BaronBlade", "Cauldron.DocHavoc", "Legacy", "Ra", "MobileDefensePlatform"); StartGame(); SetHitPoints(DocHavoc.CharacterCard, 1); DealDamage(baron, DocHavoc, 2, DamageType.Melee); QuickHPStorage(new[] { legacy.CharacterCard, ra.CharacterCard }); // Act GoToUseIncapacitatedAbilityPhase(DocHavoc); UseIncapacitatedAbility(DocHavoc, 2); GoToStartOfTurn(env); PutIntoPlay("BattalionGunner"); // End of env. each hero target takes 1 damage GoToEndOfTurn(env); // Assert AssertIncapacitated(DocHavoc); QuickHPCheck(0, 0); } [Test] public void TestDocsFlask() { // Arrange SetupGameController("BaronBlade", "Cauldron.DocHavoc", "Ra", "Megalopolis"); StartGame(); // Reduce Ra's, Havoc's HP by 2 DealDamage(baron, DocHavoc, 2, DamageType.Melee); DealDamage(baron, ra, 2, DamageType.Melee); QuickHPStorage(ra, DocHavoc); // Act PutInHand(DocsFlaskCardController.Identifier); Card docsFlask = GetCardFromHand(DocsFlaskCardController.Identifier); //GoToPlayCardPhase(DocHavoc); PlayCard(docsFlask); DecisionSelectCard = ra.CharacterCard; // Procs flask to heal Ra +1 HP GoToStartOfTurn(DocHavoc); // Now use power portion of Doc's Flask GoToUsePowerPhase(DocHavoc); UsePower(docsFlask); // Assert AssertTriggersWhere((Func<ITrigger, bool>)(t => t.Types.Contains(TriggerType.GainHP))); QuickHPCheck(2, 1); } [Test] public void TestFieldDressing() { // Arrange SetupGameController("BaronBlade", "Cauldron.DocHavoc", "Ra", "Megalopolis"); // We need to make an explicit hand so two FieldDressings aren't in hand so it doesn't play another FieldDressing which will throw off the Asserts MakeCustomHeroHand(DocHavoc, new List<string>() { FieldDressingCardController.Identifier, PhosphorBlastCardController.Identifier, PhosphorBlastCardController.Identifier, PhosphorBlastCardController.Identifier }); StartGame(); // Reduce Ra's, Havoc's HP by 2 DealDamage(baron, DocHavoc, 2, DamageType.Melee); DealDamage(baron, ra, 2, DamageType.Melee); QuickHPStorage(ra, DocHavoc); QuickHandStorage(DocHavoc); // Act Card phosphorBlast = GetCard(PhosphorBlastCardController.Identifier); DecisionSelectCardToPlay = phosphorBlast; GoToPlayCardPhase(DocHavoc); Card fieldDressing = GetCardFromHand(FieldDressingCardController.Identifier); PlayCard(fieldDressing); // Assert QuickHPCheck(1, 1); QuickHandCheck(-2); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Data; namespace DotNetNuke.Tests.Core.Controllers.Messaging.Mocks { internal class SubscriptionTypeDataReaderMockHelper { internal static IDataReader CreateEmptySubscriptionTypeReader() { return CreateSubscriptionTypeTable().CreateDataReader(); } private static DataTable CreateSubscriptionTypeTable() { var table = new DataTable(); var idColumn = table.Columns.Add("SubscriptionTypeId", typeof(int)); table.Columns.Add("SubscriptionName", typeof(string)); table.Columns.Add("FriendlyName", typeof(string)); table.Columns.Add("DesktopModuleId", typeof(int)); table.PrimaryKey = new[] { idColumn }; return table; } } }
using System; using System.Windows; using System.IO.Ports; using System.Windows.Forms; using System.IO; using System.Text; namespace SerialPortTest.DataSource { class FakeDataSource : IDataSource { Timer timer; Action<string> appendDataFunction; public FakeDataSource(Action<string> appendDataFunction) { this.appendDataFunction = appendDataFunction; } public void Start() { InitDataGeneratorTimer(); } public void InitDataGeneratorTimer() { timer = new Timer(); timer.Tick += WriteDate; timer.Interval = 30; timer.Start(); } private void WriteDate(object sender, EventArgs e) { string data = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "|0.003\n"; appendDataFunction(data); } public void OnClose() { } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace TourApi.Models { public class Tour { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public DateTimeOffset Date { get; set; } public Guid ClientId { get; set; } public Guid ExcursionId { get; set; } } }
using Hayalpc.Fatura.Common.Dtos; using Hayalpc.Fatura.CoreApi.Services.Interfaces; using Hayalpc.Fatura.Data; using Hayalpc.Fatura.Data.Models; using Hayalpc.Library.Common.Results; using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hayalpc.Fatura.CoreApi.Services { public class CategoryService : ICategoryService { private readonly IRepository<Category> repository; private readonly IMemoryCache cache; public CategoryService(IRepository<Category> repository, IMemoryCache cache) { this.repository = repository; this.cache = cache; } public IDataResult<List<CategoryDto>> Get() { var cacheKey = "Category-Get"; var list = cache.Get<List<CategoryDto>>(cacheKey); if(list == null) { list = repository.GetQuery().Select(x => new CategoryDto { Id = x.Id, Code = x.Code, Name = x.Name, Description = x.Description, }).ToList(); cache.Set(cacheKey, list, TimeSpan.FromHours(1)); } return new SuccessDataResult<List<CategoryDto>>(list,list.Count); } } }
using System.Collections.Generic; namespace ServerApp.RoomNames { interface IRoomNamesRepository { /// <summary> /// Получить список комнат пользователя /// </summary> /// <param name="login">Логин пользователя</param> /// <returns>Список названий комнат</returns> List<RoomNames> Retrieve(string login); /// <summary> /// Получить список всех комнат /// </summary> /// <returns>Список названий комнат</returns> List<RoomNames> Retrieve(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class SceenEffectApplier : MonoBehaviour { public Material screenEffectMat; private void OnRenderImage(RenderTexture source, RenderTexture destination) { Graphics.Blit(source, destination, screenEffectMat); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using Entities.Concrete; using Entities.DTOs; using Microsoft.EntityFrameworkCore; namespace DataAccess.Concrete.EntityFramework { public class EfBrandDal:EfEntityRepositoryBase<Brand,NorthwindContext>,IBrandDal { public async Task<List<BrandDetailDto>> GetBrandsDetails(Expression<Func<BrandDetailDto, bool>> filter = null) { using (NorthwindContext context = new NorthwindContext()) { var result = from brand in context.Brands select new BrandDetailDto { BrandId = brand.Id, BrandName = brand.Name, Images = (from images in context.BrandsImages where images.BrandId==brand.Id select images.ImagePath).ToList() }; return filter == null ? await result.ToListAsync() : await result.Where(filter).ToListAsync(); } } } }
/* // main // Author: // Dzyuba Vlad, IP-42 */ using System; using System.Threading; namespace Main { public class MainClass { // parameters const int N = 8; const int AllP = 8; const int ReadP = 4; const int H = N / AllP; // calc data static int[,] mt, mu, mo, mz; static int[] b, a, d; static int e; // control objects static Semaphore[] semaphores1 = new Semaphore[ReadP]; static EventWaitHandle readingEnd = new EventWaitHandle(false, EventResetMode.ManualReset); static Mutex resMutex = new Mutex(); static Semaphore[] semaphores2 = new Semaphore[AllP]; static EventWaitHandle dCalcEnd = new EventWaitHandle(false, EventResetMode.ManualReset); static Object criticalSection = new Object(); static Semaphore[] semaphores3 = new Semaphore[AllP]; public static void Main(string[] args) { Thread[] threads = new Thread[AllP]; ReadFunc[] readFuncs = new ReadFunc[ReadP] { new T1Read(), new T2Read(), new T3Read(), new T4Read() }; for (int i = 0; i < ReadP; i++) { semaphores1[i] = new Semaphore(0, 1); threads[i] = new Thread(new ThreadCalcWithRead(readFuncs[i], i).Run); } for (int i = ReadP; i < AllP; i++) { threads[i] = new Thread(new ThreadCalc(i).Run); } for (int i = 0; i < AllP; i++) { semaphores2[i] = new Semaphore(0, 1); semaphores3[i] = new Semaphore(0, 1); threads[i].Start(); } for (int i = 0; i < ReadP; i++) { semaphores1[i].WaitOne(); semaphores1[i] = null; } d = new int[N]; readingEnd.Set(); for (int i = 0; i < AllP; i++) { semaphores2[i].WaitOne(); semaphores2[i] = null; } a = new int[N]; dCalcEnd.Set(); for (int i = 0; i < AllP; i++) { semaphores3[i].WaitOne(); semaphores3[i] = null; } if (N < 20) { for (int i = 0; i < N; i++) { Console.Write(a[i]); Console.Write(" "); } Console.WriteLine(); } } class ThreadCalc { protected int partIndex; public ThreadCalc(int partIndex) { this.partIndex = partIndex; } public virtual void Run() { readingEnd.WaitOne(); int[] bi; resMutex.WaitOne(); bi = b; resMutex.ReleaseMutex(); for (int i = H * partIndex; i < H * (partIndex + 1); i++) { d[i] = 0; for (int j = 0; j < N; j++) { d[i] += bi[j] * mo[j, i]; } } semaphores2[partIndex].Release(); dCalcEnd.WaitOne(); int[,] mzi; int[] di; int ei; lock (criticalSection) { ei = e; di = d; mzi = mz; } for (int i = H * partIndex; i < H * (partIndex + 1); i++) { a[i] = 0; for (int j = 0; j < N; j++) { int zt = ei * mu[j, i]; for (int k = 0; k < N; k++) { zt += mzi[j, k] * mt[k, i]; } a[i] += di[i] * zt; } } semaphores3[partIndex].Release(); } } class ThreadCalcWithRead : ThreadCalc { ReadFunc readFunc; public ThreadCalcWithRead( ReadFunc readFunc , int partIndex) : base(partIndex) { this.readFunc = readFunc; } public override void Run() { readFunc.Read(); semaphores1[partIndex].Release(); base.Run(); } } interface ReadFunc { void Read(); } class T1Read : ReadFunc { public void Read() { mt = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mt[i, j] = 1; } } e = 1; } } class T2Read : ReadFunc { public void Read() { mu = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mu[i, j] = 1; } } } } class T3Read : ReadFunc { public void Read() { mo = new int[N, N]; mz = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mo[i, j] = 1; mz[i, j] = 1; } } } } class T4Read : ReadFunc { public void Read() { b = new int[N]; for (int i = 0; i < N; i++) { b[i] = 1; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Library.DomainModels; using Library.Services.Interface; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Library.API.Controllers { [Route("api/[controller]")] [ApiController] //[Authorize] public class BooksController : ControllerBase { private readonly IBookService _bookService; public BooksController(IBookService bookService) { _bookService = bookService; } //CREATE [HttpPost] public async Task<Book> AddBook(string title,int authorId) { return await _bookService.AddBook(title , authorId); } //READ [HttpGet] public async Task<IEnumerable<Book>> GetAllBooks() { return await _bookService.GetAllBooks(); } [HttpGet("id")] public async Task<IActionResult> GetBookById(int id) { var book = await _bookService.GetBookById(id); return Ok(book); } [HttpGet("title")] public async Task<IEnumerable<Book>> GetBookByName(string title) { return await _bookService.GetBookByName(title); } //[HttpGet("createdOnDate")] //public async Task<IEnumerable<Book>> GetBookByDate(DateTime createdOnDate) //{ // return await _bookService.GetBookByDate(createdOnDate); //} //UPDATE [HttpPatch("id")] public async Task<Book> UpdateBookTitle(int id,string newTitle) { return await _bookService.UpdateBookTitle(id,newTitle); } [HttpPatch] public async Task<Book> UpdateIsAvailable(int id,bool newStatus) { return await _bookService.UpdateIsAvailable(id,newStatus); } //DELETE //Delete with id parameter [HttpDelete("id")] public async Task<IActionResult> RemoveBook(int id) { await _bookService.GetBookById(id); return Ok(); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; #nullable disable namespace Repository.Models { public partial class Cinephiliacs_ForumContext : DbContext { public Cinephiliacs_ForumContext() { } public Cinephiliacs_ForumContext(DbContextOptions<Cinephiliacs_ForumContext> options) : base(options) { } public virtual DbSet<Comment> Comments { get; set; } public virtual DbSet<Discussion> Discussions { get; set; } public virtual DbSet<DiscussionFollow> DiscussionFollows { get; set; } public virtual DbSet<DiscussionTopic> DiscussionTopics { get; set; } public virtual DbSet<Setting> Settings { get; set; } public virtual DbSet<Topic> Topics { get; set; } public virtual DbSet<UserLike> UserLikes { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS"); modelBuilder.Entity<Comment>(entity => { entity.ToTable("comments"); entity.Property(e => e.CommentId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("commentID"); entity.Property(e => e.CommentText) .IsRequired() .HasMaxLength(300) .IsUnicode(false) .HasColumnName("comment_text"); entity.Property(e => e.CreationTime) .HasColumnType("datetime") .HasColumnName("creation_time"); entity.Property(e => e.DiscussionId) .IsRequired() .HasMaxLength(50) .IsUnicode(false) .HasColumnName("discussionID"); entity.Property(e => e.IsSpoiler).HasColumnName("is_spoiler"); entity.Property(e => e.Likes) .HasColumnName("likes") .HasDefaultValueSql("((0))"); entity.Property(e => e.ParentCommentid) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("parent_commentid"); entity.Property(e => e.UserId) .IsRequired() .HasMaxLength(50) .IsUnicode(false) .HasColumnName("userID"); entity.HasOne(d => d.Discussion) .WithMany(p => p.Comments) .HasForeignKey(d => d.DiscussionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__comments__discus__7B5B524B"); }); modelBuilder.Entity<Discussion>(entity => { entity.ToTable("discussions"); entity.Property(e => e.DiscussionId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("discussionID"); entity.Property(e => e.CreationTime) .HasColumnType("datetime") .HasColumnName("creation_time"); entity.Property(e => e.MovieId) .IsRequired() .HasMaxLength(20) .IsUnicode(false) .HasColumnName("movieID"); entity.Property(e => e.Subject) .IsRequired() .HasMaxLength(100) .IsUnicode(false) .HasColumnName("subject"); entity.Property(e => e.Totalikes) .HasColumnName("totalikes") .HasDefaultValueSql("((0))"); entity.Property(e => e.UserId) .IsRequired() .HasMaxLength(50) .IsUnicode(false) .HasColumnName("userID"); }); modelBuilder.Entity<DiscussionFollow>(entity => { entity.HasKey(e => new { e.DiscussionId, e.UserId }) .HasName("discussionID_userID_pk"); entity.ToTable("discussion_follows"); entity.Property(e => e.DiscussionId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("discussionID"); entity.Property(e => e.UserId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("userID"); entity.HasOne(d => d.Discussion) .WithMany(p => p.DiscussionFollows) .HasForeignKey(d => d.DiscussionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__discussio__discu__114A936A"); }); modelBuilder.Entity<DiscussionTopic>(entity => { entity.HasKey(e => new { e.DiscussionId, e.TopicId }) .HasName("discussionID_topic_pk"); entity.ToTable("discussion_topics"); entity.Property(e => e.DiscussionId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("discussionID"); entity.Property(e => e.TopicId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("topicID"); entity.HasOne(d => d.Discussion) .WithMany(p => p.DiscussionTopics) .HasForeignKey(d => d.DiscussionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__discussio__discu__778AC167"); entity.HasOne(d => d.Topic) .WithMany(p => p.DiscussionTopics) .HasForeignKey(d => d.TopicId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__discussio__topic__787EE5A0"); }); modelBuilder.Entity<Setting>(entity => { entity.HasKey(e => e.Setting1) .HasName("PK__settings__25A3BB9AE55A1B57"); entity.ToTable("settings"); entity.Property(e => e.Setting1) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("setting"); entity.Property(e => e.IntValue).HasColumnName("intValue"); entity.Property(e => e.StringValue) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("stringValue"); }); modelBuilder.Entity<Topic>(entity => { entity.ToTable("topics"); entity.Property(e => e.TopicId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("topicID"); entity.Property(e => e.TopicName) .IsRequired() .HasMaxLength(25) .IsUnicode(false) .HasColumnName("topic_name"); }); modelBuilder.Entity<UserLike>(entity => { entity.HasKey(e => new { e.CommentId, e.UserId }) .HasName("commentID_userID_pk"); entity.ToTable("user_likes"); entity.Property(e => e.CommentId) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("commentID"); entity.Property(e => e.UserId) .HasMaxLength(50) .HasColumnName("userID"); entity.HasOne(d => d.Comment) .WithMany(p => p.UserLikes) .HasForeignKey(d => d.CommentId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__user_like__comme__1CBC4616"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using System; using System.Linq.Expressions; namespace Bb.Expressions { public class Variable { public string Name { get; set; } public Type Type { get; set; } public ParameterExpression Instance { get; internal set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LemonadeStand { public class WeatherConditions { Random random; public bool greatWeather; public bool goodWeather; public bool badWeather; public bool terribleWeather; public int temperature; public int actualWeather; public string condition; public string textOfTemperature; public string precipitation; private bool precipitationActivity; private int naturalDisaster; bool isCloudy; bool isSunny; int outcome; string currentPrecipitation; public string precipitationAmount; public List<string> typeOfPrecipitation = new List<string>() { "snow", "snow","hail", "rain","rain" }; public WeatherConditions() { random = new Random(); outcome = 0; IsCloudy(6); IsSunny(6); HasPrecipitation(15); GetTemperature(outcome); GeneratePrecipitation(); GeneratePrecipitationAmount(6); CheckWeatherFavor(); } public void GetActualWeather() { int actualTemperature; int negativeWeatherModify = random.Next(0, 2); int weatherModifyer = random.Next(0, 4); if(negativeWeatherModify == 0) { actualTemperature = temperature - weatherModifyer; } else { actualTemperature = temperature + weatherModifyer; } actualWeather = actualTemperature; } public void CheckWeatherFavor() { if (temperature >= 60 /*&& isSunny == true*/) { greatWeather = true; goodWeather = false; badWeather = false; terribleWeather = false; } else if (temperature >= 55 /*&& isCloudy == true && isSunny == false && precipitationActivity == false*/) { greatWeather = false; goodWeather = true; badWeather = false; terribleWeather = false; } else if (temperature < 55 /*&& isCloudy == true && isSunny == false*/) { greatWeather = false; goodWeather = false; badWeather = true; terribleWeather = false; } else if (temperature < 55 && isCloudy == true /*&& isSunny == false*/ && precipitationAmount == "heavy") { greatWeather = false; goodWeather = false; badWeather = false; terribleWeather = true; } else { greatWeather = false; goodWeather = true; badWeather = false; terribleWeather = false; } } public void HasPrecipitation(int die) { if (isCloudy == true) { if(MainMenu.RollDie(0, die) > 1) { precipitationActivity = true; } } else { precipitation = "no precipitation"; } } public void IsCloudy(int die) { if(MainMenu.RollDie(0, die) < 4) { outcome = 0; condition = "cloudy"; isCloudy = true; } else { condition = "sunny"; isCloudy = false; } } public bool IsSunny(int die) { //created a parameter and now need to define it without affecting the outcome: if (isCloudy == true) { return false; } else { outcome = 60; condition = "clear"; return true; } } //public List<string> GrabDailyWeather() //{ // IsCloudy(6); // IsSunny(6); // HasPrecipitation(6); // GetTemperature(outcome); // GeneratePrecipitation(); // string textOfTemperature = Convert.ToString(temperature); // List<string> dayForecastAnalysis = new List<string>() // { // textOfTemperature, currentPrecipitation // }; // return dayForecastAnalysis; //} public void GetTemperature(int outcome) { temperature = random.Next(outcome,100); } public void GeneratePrecipitation() { if (temperature < 32 && precipitationActivity == true) { precipitation = typeOfPrecipitation[MainMenu.RollDie(0, 2)]; } else if (temperature == 32 && precipitationActivity == true) { precipitation = typeOfPrecipitation[MainMenu.RollDie(0, 4)]; } else if (temperature > 32 && precipitationActivity == true) { precipitation = typeOfPrecipitation[MainMenu.RollDie(3, 4)]; } else { precipitation = "no precipitation"; } } public void GeneratePrecipitationAmount(int die) { if(MainMenu.RollDie(0, die) <= die /2 && precipitationActivity == true) { precipitationAmount = "light"; } else if (MainMenu.RollDie(0, die) >= die /2 && precipitationActivity == true) { precipitationAmount = "mild"; } else if (MainMenu.RollDie(0, die) == die / 2 && precipitationActivity == true) { precipitationAmount = "heavy"; } else if (MainMenu.RollDie(0, die) <= die && precipitationActivity == true) { precipitationAmount = "unknown"; } } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("SpellPath")] public class SpellPath : MonoClass { public SpellPath(IntPtr address) : this(address, "SpellPath") { } public SpellPath(IntPtr address, string className) : base(address, className) { } public Vector3 m_FirstNodeOffset { get { return base.method_2<Vector3>("m_FirstNodeOffset"); } } public Vector3 m_LastNodeOffset { get { return base.method_2<Vector3>("m_LastNodeOffset"); } } public string m_PathName { get { return base.method_4("m_PathName"); } } public SpellPathType m_Type { get { return base.method_2<SpellPathType>("m_Type"); } } } }
 using Modelo; using Servico; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Apresentacao { public partial class FormClienteCadastro : Form { private ClienteServico clienteServico = new ClienteServico(); private AnimalServico animalServico = new AnimalServico(); private bool Editar = false; Cliente cliente = new Cliente(); public FormClienteCadastro(Cliente clienteEdit) { InitializeComponent(); this.cliente = clienteEdit; txtNome.Text = cliente.Nome; txtTelefone.Text = cliente.Telefone.ToString(); txtCidade.Text = cliente.Cidade; txtCpf.Text = cliente.Cpf.ToString(); txtEndereco.Text = cliente.Endereco; txtEspecie.Enabled = false; txtIdade.Enabled = false; txtNomeAnimal.Enabled = false; txtPelagem.Enabled = false; Editar = true; btnSalvar.Text = "Modificar"; } public FormClienteCadastro() { InitializeComponent(); } private void btnSalvar_Click(object sender, EventArgs e) { if (Editar) { clienteServico.EditarCliente( new Modelo.Cliente() { ClienteId = cliente.ClienteId, Nome = txtNome.Text, Telefone = txtTelefone.Text, Endereco = txtEndereco.Text, Cidade = txtCidade.Text, Cpf = txtCpf.Text, }); this.Close(); } if (Editar == false) { long novoIdCliente = clienteServico.GravarCliente( new Modelo.Cliente() { Nome = txtNome.Text, Telefone = txtTelefone.Text, Endereco = txtEndereco.Text, Cidade = txtCidade.Text, Cpf = txtCpf.Text, }); animalServico.GravarAnimal(new Modelo.Animal() { ClienteId = novoIdCliente, Nome = txtNomeAnimal.Text, Especie = txtEspecie.Text, Idade = Convert.ToInt32(txtIdade.Text), Pelagem = txtPelagem.Text, }); txtNome.Clear(); txtTelefone.Clear(); txtEndereco.Clear(); txtCidade.Clear(); txtCpf.Clear(); txtNomeAnimal.Clear(); txtEspecie.Clear(); txtIdade.Clear(); txtPelagem.Clear(); } } } }
using System; namespace HaloSharp.Model { public interface IRateLimit { int RequestCount { get; set; } TimeSpan Timeout { get; set; } TimeSpan TimeSpan { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webcorp.Model; namespace Webcorp.rx_mvvm { public class DeleteViewModelMessage<T>: IDeleteViewModelMessage<T> where T :IEntity { public DeleteViewModelMessage() { } public DeleteViewModelMessage(T viewModel) { Model = viewModel; } public T Model { get; set; } } }
using MediatR; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.DebugAdapter.Protocol { namespace Requests { [Parallel] [Method(RequestNames.RestartFrame, Direction.ClientToServer)] [GenerateHandler] [GenerateHandlerMethods] [GenerateRequestMethods] public record RestartFrameArguments : IRequest<RestartFrameResponse> { /// <summary> /// Restart this stackframe. /// </summary> public long FrameId { get; init; } } public record RestartFrameResponse; } }
using System.Collections.Generic; using TrafficControl.DAL.RestSharp.Types; namespace TrafficControl.DAL.RestSharp { /// <summary> /// Interface /// </summary> public interface ITCApi { #region Account bool LogIn(string email, string encryptedPassWord); bool CreateUser(string email, string password, string confirmedpassword, string firstname, string lastname, int roles, string number); bool CreateUser(User usr); bool ChangePassword(string oPassword, string nPassword, string cPassword); User GetUser(); bool UpdateUser(User usr); bool UpdateUser(string email, string password, string name, bool smsNotification, bool emailnotifikation); #endregion #region Cases ICollection<Case> GetMyCases(); Case GetCase(long id); bool ClaimCase(long id); bool CreateCase(long installtionId, ObserverSelection observer, string errorDescription); bool UpdateCase(Case myCase); ICollection<Case> GetCases(); #endregion #region Installations ICollection<Installation> GetInstallations(); Installation GetInstallation(long id); bool UpdateInstalltion(Installation obj); #endregion #region Position ICollection<Position> GetPositions(); Position GetPosition(long id); bool UpdatePosition(Position position); #endregion } }
using System; using Foundation; namespace MedApp1 { [Preserve] [Serializable] public class Medicine { public string Name { get; set; } public DateTime FromDate { get; set; } public DateTime TillDate { get; set; } public Medicine(string name,DateTime fdate, DateTime tdate) { Name = name; FromDate = fdate; TillDate = tdate; } public Medicine() { } } }
using System; using System.Windows.Input; namespace GitlabManager.Framework { /// <summary> /// Generic Delegate implementation of the ICommand interface. /// /// Inspiration: Adonis UI Demo Template /// https://github.com/benruehl/adonis-ui/blob/master/src/AdonisUI.Demo/Framework/Command.cs /// => Modified, so that it supports generics /// #LOC /// </summary> /// <typeparam name="T">CommandParameter Type</typeparam> public class AppDelegateCommand<T> : ICommand { private readonly Predicate<T> _canExecute; private readonly Action<T> _execute; public AppDelegateCommand(Action<T> execute, Predicate<T> canExecute = null) { _execute = execute; _canExecute = canExecute; } /// <summary> /// Checks if a command can be executed /// </summary> /// <param name="parameter">Command Parameter with Type T</param> /// <returns></returns> public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } if (parameter is T castedParameter) { return _canExecute(castedParameter); } return false; } /// <summary> /// Execute the specified command action /// </summary> /// <param name="parameter"></param> public void Execute(object parameter) { _execute((T) parameter); } public event EventHandler CanExecuteChanged; } }
using UnityEngine; using System.Collections; public class Room { private int roomId; private ArrayList tiles; public Room(int roomId) { this.roomId = roomId; tiles = new ArrayList(); } public void addTile(Tile tile){ tiles.Add(tile); } public int getRoomId(){ return roomId; } public int getTileCount(){ return tiles.Count; } public void highlightRoomTiles(){ // TODO rename to select? foreach(Tile tile in tiles){ TilePartialBehaviour behaviour = tile.tileObject.GetComponent<TilePartialBehaviour>(); behaviour.select(); } } }
namespace Delegates { enum ExamplesEnumeration { DelegatesBasicSyntaxShow, DelegateShortSyntax, DelegateNonStatic, DelegateWithParameters, DelegateCombined, DelegateAnonymousMethod, DelegateAnonymousMethodReturn, DelegateLambdaExpression, DelegateAnounymousMethodVsLambda, BuildInDelegateAction, BuildInDelegateGenericAction, BuildInDelegateFunction, BuildInDelegatePredicate, CallbackShow, CuratorAgentExampleShow, } }
using System; using System.IO; namespace WUBSinger { class Program { public static void Main(string[] args) { var songs = new string[] { "icantquityou", "endoftheworld", "itsasmallworld" }; Console.WriteLine("Welcome to Singer!"); while (true) { Console.WriteLine("Please choose a song you'd like to sing"); Console.WriteLine("1 for I can't quit you by Led Zeppelin"); Console.WriteLine("2 for End of the world"); Console.WriteLine("3 for It's a small world"); Console.WriteLine("Type quit to quit the application"); var response = Console.ReadLine(); if (response.ToLower() == "quit") { break; } var song = 0; if (!int.TryParse(response, out song)) { Console.WriteLine("Invalid input, please try again"); continue; } song--; var fileName = "../../" + songs[song] + ".txt"; /* if(!File.Exists(fileName)) { Console.WriteLine("File not found, try again"); continue; }*/ var lines = File.ReadAllLines(fileName); Console.WriteLine("==========="); foreach (var line in lines) { Singer.WriteLine(line); } Console.WriteLine("==========="); } } } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Web; namespace GetLabourManager.Configuration { public class EmployeeCategoryGroupingConfiguration:EntityTypeConfiguration<EmployeeCategoryGrouping> { public EmployeeCategoryGroupingConfiguration() { Property(x => x.Category).IsRequired(); Property(x => x.Group).IsRequired(); } } }
using DuaControl.Web.Data.Entities; using DuaControl.Web.Models; using System.Collections.Generic; using System.Linq; namespace Asp.Web.Common.Mapper { public class MappingProfile : AutoMapper.Profile { public MappingProfile() { // ----- User ----- CreateMap<User, UserViewModel>() .ForMember(dest => dest.AuthorizedRoleIds, mo => mo.MapFrom(src => src.UserRoles != null ? src.UserRoles.Select(r => r.RoleId).ToList() : new List<int>())); //CreateMap<User, UserCreateUpdateViewModel>(); //CreateMap<UserCreateUpdateViewModel, User>() // .ForMember(dest => dest.UserName, mo => mo.MapFrom(src => src.UserName.ToLowerInvariant())) // .ForMember(dest => dest.LastLoginDate, opt => opt.Ignore()) // .ForMember(dest => dest.CreatedBy, opt => opt.Ignore()) // .ForMember(dest => dest.CreatedOn, opt => opt.Ignore()) // .ForMember(dest => dest.ModifiedBy, opt => opt.Ignore()) // .ForMember(dest => dest.ModifiedOn, opt => opt.Ignore()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VKDesktop.Api { class Access { public static string access_token = ""; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MiniNGUI { public class UIDrawCall : MonoBehaviour { const int geomSize = 1000; public static List<Vector3> verts = new List<Vector3>(geomSize); public Material mMaterial; public Texture mTexture; public Shader mShader; Mesh mMesh; MeshFilter mMeshFilter; public MeshRenderer mRenderer; public void UpdateGeometry() { if (mMesh == null) { mMesh = new Mesh { hideFlags = HideFlags.DontSave, name = (mMaterial != null) ? "[NGUI]" + mMaterial.name : "[NGUI] Mesh" }; mMesh.MarkDynamic(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace testconnection { public partial class Form1 : Form { TcpClient client; NetworkStream nStream; BinaryWriter sw; BinaryReader sr; IPAddress local_address; Task startRecieveTask; Task readmsgfromserver; Button[] btns; string[] letters; //Label label1; int wordLength; public Form1() { InitializeComponent(); btns = new Button[26] { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z }; letters = new string[26] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; } private void RecieveMessage() { string msg; while (true) { if ((msg = sr.ReadString()) != null) { if (msg == "no") { MessageBox.Show("refused"); sr.Close(); sw.Close(); nStream.Close(); break; } else { DialogResult result = MessageBox.Show(msg, "info", MessageBoxButtons.OKCancel); if (result == DialogResult.OK) { sw.Write("yes"); panel2.Visible = false; readmsgfromserver.Start(); break; } else { sw.Write("no"); sr.Close(); sw.Close(); nStream.Close(); break; } } } } } void readMsg() { string msg; while (true) { if ((msg = sr.ReadString()) != null)//nStream.DataAvailable) { //msg = sr.ReadString(); var commaIndicator = msg.IndexOf(','); var underscoreIndicator = msg.IndexOf('_'); if (msg == "0") { MessageBox.Show("server is out! You Win"); closeConnection(); } else if (msg.Contains("length:")) { wordLength = int.Parse(msg.Split(':')[1]); label1.Text = ""; for (int i = 0; i < wordLength; i++) label1.Text += "_"; label2.Text = msg.Split(':')[2]; } else { if (commaIndicator == -1) { if (msg == label1.Text) { label3.Text = "Server turn"; panel1.Enabled = false; } else { if (underscoreIndicator == -1) { label1.Text = msg; MessageBox.Show("You win"); closeConnection(); } else { label1.Text = msg; label3.Text = "Your turn"; panel1.Enabled = true; } } } else { string[] words = msg.Split(','); int index = Array.IndexOf(letters, words[0]); btns[index].Enabled = false; btns[index].BackColor = Color.Gainsboro; if (words[1] == label1.Text) { label3.Text = "Your turn"; panel1.Enabled = true; } else { if (words[1].IndexOf("_") == -1) { MessageBox.Show("you lose"); closeConnection(); } else { label1.Text = words[1]; panel1.Enabled = false; label3.Text = "Server turn"; } } } } } } } private void Form1_Load(object sender, EventArgs e) { label1.Text = ""; label2.Text = ""; panel1.Enabled = false; } void closeConnection() { sw.Close(); sr.Close(); nStream.Close(); panel2.Visible = true; label1.Text = ""; label2.Text = ""; panel1.Enabled = false; foreach (var item in btns) { item.Enabled = true; item.BackColor = Color.White; } //this.Close(); } private void button27_Click(object sender, EventArgs e) { sw.Write("0"); closeConnection(); } private void button28_Click_1(object sender, EventArgs e) { try { client = new TcpClient(); byte[] ip_byte = { 127, 0, 0, 1 }; local_address = new IPAddress(ip_byte); client.Connect(local_address, 2000); nStream = client.GetStream(); sr = new BinaryReader(nStream); sw = new BinaryWriter(nStream); startRecieveTask = new Task(RecieveMessage); startRecieveTask.Start(); readmsgfromserver = new Task(readMsg); } catch { MessageBox.Show("Server is not open"); } } private void button1_Click(object sender, EventArgs e) { var btn = (Button)sender; var val = btn.Text; int index = Array.IndexOf(letters, val); btns[index].Enabled = false; btns[index].BackColor = Color.Gainsboro; sw.Write(val); } } }
using System; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using LePapeoGenNHibernate.Exceptions; using LePapeoGenNHibernate.EN.LePapeo; using LePapeoGenNHibernate.CAD.LePapeo; namespace LePapeoGenNHibernate.CEN.LePapeo { /* * Definition of the class RestauranteCEN * */ public partial class RestauranteCEN { private IRestauranteCAD _IRestauranteCAD; public RestauranteCEN() { this._IRestauranteCAD = new RestauranteCAD (); } public RestauranteCEN(IRestauranteCAD _IRestauranteCAD) { this._IRestauranteCAD = _IRestauranteCAD; } public IRestauranteCAD get_IRestauranteCAD () { return this._IRestauranteCAD; } public int New_ (string p_email, String p_pass, Nullable<DateTime> p_fecha_inscripcion, string p_nombre, Nullable<DateTime> p_fecha_apertura, string p_tipoCocina, int p_max_comen, int p_current_comen, float p_precio_medio, string p_descripcion, string p_menu) { RestauranteEN restauranteEN = null; int oid; //Initialized RestauranteEN restauranteEN = new RestauranteEN (); restauranteEN.Email = p_email; restauranteEN.Pass = Utils.Util.GetEncondeMD5 (p_pass); restauranteEN.Fecha_inscripcion = p_fecha_inscripcion; restauranteEN.Nombre = p_nombre; restauranteEN.Fecha_apertura = p_fecha_apertura; if (p_tipoCocina != null) { // El argumento p_tipoCocina -> Property tipoCocina es oid = false // Lista de oids id restauranteEN.TipoCocina = new LePapeoGenNHibernate.EN.LePapeo.TipoCocinaEN (); restauranteEN.TipoCocina.Tipo = p_tipoCocina; } restauranteEN.Max_comen = p_max_comen; restauranteEN.Current_comen = p_current_comen; restauranteEN.Precio_medio = p_precio_medio; restauranteEN.Descripcion = p_descripcion; restauranteEN.Menu = p_menu; //Call to RestauranteCAD oid = _IRestauranteCAD.New_ (restauranteEN); return oid; } public void Destroy (int id ) { _IRestauranteCAD.Destroy (id); } public RestauranteEN ReadOID (int id ) { RestauranteEN restauranteEN = null; restauranteEN = _IRestauranteCAD.ReadOID (id); return restauranteEN; } public System.Collections.Generic.IList<RestauranteEN> ReadAll (int first, int size) { System.Collections.Generic.IList<RestauranteEN> list = null; list = _IRestauranteCAD.ReadAll (first, size); return list; } public void AgregarDireccion (int p_Restaurante_OID, int p_direccion_OID) { //Call to RestauranteCAD _IRestauranteCAD.AgregarDireccion (p_Restaurante_OID, p_direccion_OID); } public void DesvincularDireccion (int p_Restaurante_OID, int p_direccion_OID) { //Call to RestauranteCAD _IRestauranteCAD.DesvincularDireccion (p_Restaurante_OID, p_direccion_OID); } public void AgregarHorarioSemana (int p_Restaurante_OID, int p_horarioSemana_OID) { //Call to RestauranteCAD _IRestauranteCAD.AgregarHorarioSemana (p_Restaurante_OID, p_horarioSemana_OID); } public void DesvincularHorarioSemana (int p_Restaurante_OID, int p_horarioSemana_OID) { //Call to RestauranteCAD _IRestauranteCAD.DesvincularHorarioSemana (p_Restaurante_OID, p_horarioSemana_OID); } public LePapeoGenNHibernate.EN.LePapeo.HorarioSemanaEN GetHorarioSemana (int p_restaurante) { return _IRestauranteCAD.GetHorarioSemana (p_restaurante); } public LePapeoGenNHibernate.EN.LePapeo.DireccionEN GetDireccion (int p_restaurante) { return _IRestauranteCAD.GetDireccion (p_restaurante); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euro2016Skupine { public class DB { #region Private Fields private string connectionString; private SqlConnection connection; private static DB instance; #endregion #region Properties /// <summary> /// Putanja i ostali parametri za spajanje na bazu podataka. /// </summary> public string ConnectionString { get { return connectionString; } private set { connectionString = value; } } /// <summary> /// Konekcija prema bazi podataka. /// </summary> public SqlConnection Connection { get { return connection; } private set { connection = value; } } /// <summary> /// Singleton instanca klase za rad sa bazom podataka. /// </summary> public static DB Instance { get { if (instance == null) { instance = new DB(); } return instance; } } #endregion #region Constructors /// <summary> /// Privatni konstruktor klase potreban za singleton implementaciju. /// </summary> private DB() { ConnectionString = @"Server=31.147.204.119\PISERVER,1433;Database=Baza_0101;User=student;Password=student;"; Connection = new SqlConnection(ConnectionString); Connection.Open(); } /// <summary> /// Destruktor klase. /// </summary> ~DB() { Connection = null; } #endregion #region Methods /// <summary> /// Dohvaća podatke u obliku DataReader objekta na temelju prosljeđenog ///u pita. /// </summary> /// <param name="sqlUpit">SQL upit.</param> /// <returns>Rezultat upita.</returns> public DbDataReader DohvatiDataReader(string sqlUpit) { SqlCommand command = new SqlCommand(sqlUpit, Connection); return command.ExecuteReader(); } /// <summary> /// Dohvaća skalarnu vrijednost na temelju prosljeđenog upita. /// </summary> /// <param name="sqlUpit">SQL upit.</param> /// <returns>Skalarna vrijednost kao rezultat upita.</returns> public object DohvatiVrijednost(string sqlUpit) { SqlCommand command = new SqlCommand(sqlUpit, Connection); return command.ExecuteScalar(); } /// <summary> /// Izvršava prosljeđeni SQL izraz (INSERT, UPDATE, DELETE). /// </summary> /// <param name="sqlUpit">SQL izraz.</param> /// <returns>Broj redaka koji su promijenjeni.</returns> public int IzvrsiUpit(string sqlUpit) { SqlCommand command = new SqlCommand(sqlUpit, Connection); return command.ExecuteNonQuery(); } #endregion } }
using System.Threading.Tasks; using LannisterAPI.Models; using Microsoft.AspNetCore.Mvc; namespace LannisterAPI.Controllers { [Produces("application/json")] public class ProfileController : Controller { [HttpGet] [Route("profiles/{userId}")] [ProducesResponseType(typeof(ProfileOwnerProfile), 200)] [ProducesResponseType(typeof(UserProfile), 200)] [ProducesResponseType(typeof(Error), 400)] public async Task<IActionResult> GetUserProfile(string userId) { return Ok(); } [HttpPost] [Route("profiles/{userId}/invitations")] [ProducesResponseType(200)] [ProducesResponseType(typeof(Error), 400)] public async Task<IActionResult> RespondOnTrackingInvitation([FromBody] RespondOnTrackingInvitationRequest request) { return Ok(); } } }
using UnityEngine; using System.Collections; public static class GameState { public enum GameMode { Playing, Disappearing, Falling } public static GameMode Mode = GameMode.Playing; public static int ActionsTaken = 0; public static void ResetGame() { if (Mode == GameMode.Playing) { ActionsTaken = 0; Board.ShowingBoard2 = true; Board.GenerateBoard(); } } }
using UnityEngine; using System.Collections; using System.Linq; using UnityEngine.UI; public class CharacterUnlockController : MonoBehaviour { public AudioClip crashSound; public AudioClip whiteLightSound; public AudioClip unlockSound; public AudioClip discoverySound; public GameObject menu; public AudioClip pauseSound; enum State{ IDLE, ACTIVE, END } State _state = State.IDLE; AudioSource audioSource; Image panel; Text characterText; byte fadeAlpha = 240; CharacterCollection.CharacterModel character; // Use this for initialization void Start () { audioSource = GetComponent<AudioSource>(); panel = transform.GetComponentInChildren<Image>(); characterText = transform.Find("Character Text").GetComponent<Text>(); character = GameStats.GetUnlockedCharacter(); if(character != null){ foreach(GameObject player in GameObject.FindGameObjectsWithTag("Player")){ int counter = int.Parse(player.name.Replace("Character ","")); player.GetComponentInChildren<SpriteSwitch>().SetSpriteSheet(character.costumes[counter].characterSpriteSheetName); } } CharacterCollection.UnlockCharacter(character); } // Update is called once per frame void Update () { if(_state == State.ACTIVE){ if(Input.GetButtonDown("Start") || Input.GetButtonDown("Confirm") || Input.GetButtonDown("Cancel")){ menu = Instantiate(menu, Vector3.zero, Quaternion.identity) as GameObject; menu.transform.SetParent(GameObject.Find("Canvas").transform); audioSource.PlayOneShot(pauseSound,1f); _state = State.END; } } } public void EnableSceneNavigation(){ _state = State.ACTIVE; } public void ShowCharacters(){ GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); foreach(GameObject player in players){ player.GetComponentInChildren<SpriteRenderer>().color = new Color32(255,255,255,255); } } public void ShowWhite(){ panel.color = new Color32(255,255,255,255); PlaySound(whiteLightSound); } public void FadeWhite(){ fadeAlpha -= 20; panel.color = new Color32(255,255,255,fadeAlpha); if(fadeAlpha != 0){ Invoke("FadeWhite",0.2f); }else{ panel.color = new Color32(255,255,255,0); } } public void PlayTaunt(){ PlaySound(character.taunt); } public void PlayUnlcokMusic(){ PlaySound(unlockSound); } public void PlayDiscoverySound(){ PlaySound(discoverySound); } public void ShowCharacterText(){ characterText.text = character.displayName.ToUpper();; PlaySound(crashSound); PlayTaunt(); } void ShowUnlockedText(){ characterText.text += "\nUNLOCKED"; PlaySound(crashSound); } void PlaySound(AudioClip sound){ audioSource.PlayOneShot(sound); } }
using AquaServiceSPA.Models; namespace AquaServiceSPA.Services { public interface IAquaCalcService { double K2SO4ContentK { get; } double K2SO4SolubilityGramsPer100Ml { get; } double KH2PO4ContentK { get; } double KH2PO4SolubilityGramsPer100Ml { get; } double KH2PO4ContentP { get; } double KNO3ContentK { get; } double KNO3ContentN { get; } double MgSO47H2OContentMg { get; } double MgSO4SolubilityGramsPer100Ml { get; } double KNO3SolubilityGramsPer100Ml { get; } double Co2Concentration(double kh, double ph); double ConcentrationIn1Ml( double liters, double gramsInSolution, double mlSolution, double precentInSalt); double GramsSalt(double ppmsUp, double liters, double percentageInSalt); double OptimalConcentrationIn1Ml(double liters, double gramsInsolution, double mlSolution, double precententInSalt, double saltSolubility); double Percent(double value); double Ppm(double percentInSalt, double liters); double SeingleDose(double weeklyDodeInMl, double soulubilityPer100Ml); double Solubility(double gramsSalt, double solubilityPer100Grams); double SolubilityInWater(double litersWater, double solubilityPer100Grams); MacroResult MacroCompute(Macro Macro); ExpressResult ExpressCalc(Express express); } }
using UnityEngine; public class Shot : MonoBehaviour { [SerializeField] private float speed = 5; public float hitPoints = 1; public float cooldown = 0.1f; [SerializeField] private Rigidbody2D rigidbody; //public Rigidbody2D rb { get; private set; } // Start is called before the first frame update void Start() { rigidbody.AddForce(Vector3.up * speed, ForceMode2D.Impulse); Destroy(gameObject, 2); } // Update is called once per frame }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cv_7_rozhrani { class Program { static void Main(string[] args) { Circle c1 = new Circle(5); Circle c2 = new Circle(7); Rectangle r1 = new Rectangle(6, 7); Rectangle r2 = new Rectangle(3, 12); Console.WriteLine(c1.ToString()); Console.WriteLine(c2.ToString()); Console.WriteLine(r1.ToString()); Console.WriteLine(r2.ToString()); string circles = "První kruh má "; if (c1.GreaterArea(c2)) circles += "větší"; else circles += "menší"; circles += " obsah, než druhý kruh"; string rectangles = "První obdélník má "; if (r1.GreaterCircumference(r2)) rectangles += "větší"; else rectangles += "menší"; rectangles += " obvod, než druhý obdélník"; Console.WriteLine(circles); Console.WriteLine(rectangles); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Text; using Modelo; using System.Linq; using Microsoft.EntityFrameworkCore; namespace Persistencia { public class MedicamentoDAL { private EFContext context; public IList<Medicamento> TodosOsMedicamentos() { using (var context = new EFContext()) { return context.Medicamentos.ToList<Medicamento>(); } } public IList<Medicamento> DescricaoMedicamentos() { using (var context = new EFContext()) { return context.Medicamentos.FromSql("SELECT MedicamentoId,Descricao FROM Medicamentos").ToList(); } } public void GravarMedicamento(Medicamento medicamento) { using (var context = new EFContext()) { context.Medicamentos.Add(medicamento); context.SaveChanges(); } } public void ExcluirMedicamento(int id) { using (var context = new EFContext()) { var medicamento = new Medicamento { MedicamentoId = id }; context.Medicamentos.Remove(medicamento); context.SaveChanges(); } } public void EditarMedicamento(Medicamento medicamento) { using (var context = new EFContext()) { context.Update(medicamento); context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.Windows.Navigation; namespace ControleDeGastos.Views { public partial class EditCurrency : PhoneApplicationPage { private string param1; IList<TB_MOEDA> ListCurrency = (new CurrencyViewModel()).GetCurrency(); public EditCurrency() { InitializeComponent(); } private void newCurrency() { if (txtName.Text != null /*&& novoTipo != null*/) { string connection = App.Connection; using (var ctx = new ControleDeGastosDataContext(App.Connection)) { TB_MOEDA novaMoeda = new TB_MOEDA() { MOE_NOME = txtName.Text, MOE_SIGLA = txtSigla.Text, MOE_PADRAO = (bool) checkDefault.IsChecked, MOE_COTACAO = Convert.ToDecimal(txtCotacao.Text), MOE_FLAG_ATIVA = true }; ctx.TB_MOEDAs.InsertOnSubmit(novaMoeda); ctx.SubmitChanges(); } NavigationService.GoBack(); } else { MessageBox.Show("Digite um nome"); } } private void loadExistingCurrencyInfo() { foreach (TB_MOEDA Currency in ListCurrency) { if (Currency.MOE_ID == Convert.ToInt32(param1)) { txtName.Text = Currency.MOE_NOME; txtSigla.Text = Currency.MOE_SIGLA; checkDefault.IsChecked = Currency.MOE_PADRAO; txtCotacao.Text = Currency.MOE_COTACAO.ToString(); break; } } } private void editExistingCurrency() { string connection = App.Connection; using (var ctx = new ControleDeGastosDataContext(App.Connection)) { IQueryable<TB_MOEDA> currencyQuery = from TB_MOEDAs in ctx.TB_MOEDAs where TB_MOEDAs.MOE_ID.Equals(param1) select TB_MOEDAs; TB_MOEDA moedaToUpdate = currencyQuery.FirstOrDefault(); moedaToUpdate.MOE_NOME = txtName.Text; moedaToUpdate.MOE_SIGLA = txtSigla.Text; moedaToUpdate.MOE_PADRAO = (bool)checkDefault.IsChecked; moedaToUpdate.MOE_COTACAO = Convert.ToDecimal(txtCotacao.Text); moedaToUpdate.MOE_FLAG_ATIVA = true; ctx.SubmitChanges(); } NavigationService.GoBack(); } private bool checkInfo() { if (txtName.Text.Equals("")) { MessageBox.Show("Ops... Preencha o campo de nome da moeda!!!"); return false; } else { if (txtSigla.Text.Equals("")) { MessageBox.Show("Ops... Preencha o campo de sigla da moeda!!!"); return false; } else { return true; } } } private void appBarConfirmarButton_Click(object sender, EventArgs e) { if (checkInfo()) { if (param1.Equals("-1")) { newCurrency(); } else { editExistingCurrency(); } } } private void appBarCancelarButton_Click(object sender, EventArgs e) { NavigationService.GoBack(); } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); loadExistingCurrencyInfo(); } } }
using System; using System.Web.Mvc; using Psub.DataService.DTO; using Psub.DataAccess.Attributes; using Psub.DataService.Abstract; namespace Psub.Controllers { public class RelayDataController : Controller { private readonly IRelayDataService _relayDataService; public RelayDataController(IRelayDataService relayDataService) { _relayDataService = relayDataService; } public ActionResult Create(int id) { if (Request.IsAuthenticated) { return View(new RelayDataDTO { ControlObject = new ControlObjectDTO { Id = id } }); } return RedirectToAction("AccessIsClosed", "Exception"); } [HttpPost] [TransactionPerRequest] public ActionResult Create(RelayDataDTO relayDataDTO) { if (Request.IsAuthenticated) { relayDataDTO.Id = 0; _relayDataService.SaveOrUpdate(relayDataDTO); return RedirectToAction("Details", "ControlObject", new { id = relayDataDTO.ControlObject.Id }); } return RedirectToAction("AccessIsClosed", "Exception"); } public ActionResult Edit(int id) { if (Request.IsAuthenticated) { return View(_relayDataService.GetRelayDataDTOById(id)); } return RedirectToAction("AccessIsClosed", "Exception"); } [HttpPost] [TransactionPerRequest] public ActionResult Edit(RelayDataDTO relayDataDTO) { if (Request.IsAuthenticated) { _relayDataService.SaveOrUpdate(relayDataDTO); return RedirectToAction("Details", "ControlObject", new { id = _relayDataService.GetControlObjectIdByRelayDataId(relayDataDTO.Id) }); } return RedirectToAction("AccessIsClosed", "Exception"); } [HttpPost] [TransactionPerRequest] public JsonResult Delete(int id) { if (Request.IsAuthenticated) { try { _relayDataService.Delete(id); return Json(true); } catch (Exception) { return Json(false); } } return Json(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Xml; using System.IO; using System.Text; using System.Xml.Linq; namespace DataO.EF { public sealed class Datas { public string XmlPath { get; set; } private int WomanCount { get; set; } public Datas(string _xmlPath) { XmlPath = _xmlPath; } public List<string> FilesNameM(string path, string partialname) { string[] listeOfFiles = Directory.GetFiles(path); /*var query = from l1 in listeOfFiles where l1.ToString().Contains("m") select l1;*/ var fluentQuery = listeOfFiles.Where(e => e.ToString().Contains(partialname)).Select(e => e).ToList(); return fluentQuery; } public IEnumerable<XElement> getXmlData() { XElement xml = XElement.Load(XmlPath); IEnumerable<XElement> Employees = xml.Elements("Employee"); return Employees; } public string getWomenData() { string answer = ""; var fluentQuery = this.getXmlData().Where(e => e.Element("Sex").Value.ToString().ToUpper() == "FEMALE").Select(e => e.Element("Name").Value); answer = "Voici la liste des femmes:" + Environment.NewLine; foreach (var item in fluentQuery) { WomanCount++; answer += item.ToString() + "\r\n"; } answer += "Voici leur nombre: " + WomanCount + Environment.NewLine; return answer; } public string getEmployeeCity() { string answer = ""; var fluentQuery = this.getXmlData().Where(e => e.Element("Address").Element("City").Value == "Alta").Select(e => e.Element("Name").Value); answer = "Voici la liste des personnes habitant à Alta:" + Environment.NewLine; foreach (var item in fluentQuery) { WomanCount++; answer += item.ToString() + "\r\n"; } return answer; } public void addElementToXml() { XElement xml = XElement.Load(XmlPath); xml.Add(" "); xml.Save(XmlPath); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AlienBullet : MonoBehaviour { public Vector3 thrust; // direction of movement public Quaternion heading; public GameObject globalOBJ; // global game object public GameObject explosion; // Start is called before the first frame update void Start() { globalOBJ = GameObject.FindWithTag("Global"); // travel straight in the Z-axis thrust.z = -400.0f; heading.z = 1; // do not passively decelerate GetComponent<Rigidbody>().drag = 0; // set the direction it will travel in GetComponent<Rigidbody>().MoveRotation(heading); // apply thrust once, no need to apply it again GetComponent<Rigidbody>().AddRelativeForce(thrust); } // Update is called once per frame void Update() { // Check if the bullet is outside the screen Vector3 currentPos = gameObject.transform.position; if (currentPos.z < -20f) { Destroy(gameObject); return; } } void OnCollisionEnter(Collision collision) { Collider collider = collision.collider; if (collider.CompareTag("Ship")) { // Kill the ship collider.gameObject.GetComponent<Ship>().Kill(); //Debug.Log("Remaining lives: " + collider.gameObject.GetComponent<Ship>().remainingLives); Destroy(gameObject); } else if (collider.CompareTag("Shield")) { // Generate explosion and debris Vector3 spawnPos = gameObject.transform.position; Instantiate(explosion, spawnPos, Quaternion.identity); collider.gameObject.GetComponent<Shield>().HitUpdate(); Destroy(gameObject); } else if (collider.CompareTag("AlienBullet")) { // Destroy the bullet Destroy(gameObject); } else if (collider.CompareTag("ShipBullet")) { // Destroy the bullet Destroy(gameObject); } else if (collider.CompareTag("Platform")) { // Generate explosion and debris Vector3 spawnPos = gameObject.transform.position; Instantiate(explosion, spawnPos, Quaternion.identity); Destroy(gameObject); } } }
using mytry.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace mytry.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HomePage : MasterDetailPage { List<Pages> pages = new List<Pages> { new Pages{Name="List Events", ImageSource="Event.png", Page=new EventList()}, new Pages{Name="List Volunteer", ImageSource="Voulnteer.png", Page = new VolunteerList()}, new Pages{Name="My Events",ImageSource="VolOnEve.png",Page=new EventVolunteerList() } }; public HomePage() { InitializeComponent(); lstMaster.ItemsSource = pages; IsPresented = true; } private void lstMaster_ItemTapped(object sender, ItemTappedEventArgs e) { Pages p = e.Item as Pages; //p.Page.BindingContext = this.BindingContext as Volunteer; if(p.Name=="List Events") p.Page.BindingContext = new EventV (); Navigation.PushAsync(p.Page); } private void btnEditProfile_Clicked(object sender, EventArgs e) { DisplayAlert("Sorry!", "This Feature is coming soon", "Ok"); } } }
namespace SFA.DAS.Notifications.Api { public static class EnvironmentExtensions { public static bool IsDevelopment(this string environment) { return environment == null || environment == "LOCAL"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Pada1.BBCore.Tasks; using Pada1.BBCore; using UnityEngine.AI; namespace BBUnity.Actions { [Action("EnemyBehaviour/AvoidAction")] [Help("Goes out of the way of stuff")] public class AvoidAction : GOAction { [InParam("agent")] public NavMeshAgent agent; [InParam("enemyBody")] public EnemyBody enemyBody; [InParam("stats")] public EnemyStatistics stats; AIUtilities utilities; public AISteering steering; public override void OnStart() { agent.isStopped = false; if (utilities != null) utilities = ScriptCollection.GetScript<AIUtilities>(); if (steering == null) steering = new AISteering(stats, enemyBody); } public override TaskStatus OnUpdate() { if (!IsHeadingForCollision()) return TaskStatus.COMPLETED; agent.destination = steering.AvoidanceSteering(gameObject.transform.forward); Vector3 moveTo = gameObject.transform.forward * (stats.GetStatValue(StatName.Speed) * stats.GetMultValue(MultiplierName.speed)) * Time.deltaTime; agent.Move(moveTo); return TaskStatus.RUNNING; } bool IsHeadingForCollision() { Vector3 dir = Vector3.zero; if (utilities.IsInRange(enemyBody.aiManager.playerTarget, gameObject.transform, enemyBody.aiManager.avoidDistance)) { dir = enemyBody.aiManager.playerTarget.position - gameObject.transform.position; dir = dir.normalized; RaycastHit hit; if (Physics.SphereCast(gameObject.transform.position, 0.5f, dir, out hit, 3f, enemyBody.aiManager.enemyMask)) { Debug.DrawRay(gameObject.transform.position, dir, Color.yellow); return true; } } return false; } } }
using EnvDTE; using EnvDTE80; namespace CloseAllTabs { public class SolutionExplorerFocus { private DTE2 _dte; private Options _options; private SolutionEvents _solEvents; private SolutionExplorerFocus(DTE2 dte, Options options) { _dte = dte; _options = options; _solEvents = _dte.Events.SolutionEvents; _solEvents.AfterClosing += Execute; } public static SolutionExplorerFocus Instance { get; private set; } public static void Initialize(DTE2 dte, Options options) { Instance = new SolutionExplorerFocus(dte, options); } private void Execute() { if (!_options.FocusSolutionExplorer) return; var solExp = _dte.Windows.Item(Constants.vsWindowKindSolutionExplorer); if (solExp != null) { solExp.Activate(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WeddingPlanner.Models; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; using Google.Maps; using Google.Maps.StaticMaps; using Google.Maps.Geocoding; namespace WeddingPlanner.Controllers { public class WeddingController : Controller { private MyContext dbContext; public WeddingController(MyContext context) { dbContext = context; } [Route("Wedding/newwedding")] [HttpGet] public IActionResult NewWedding() { if (HttpContext.Session.GetString("Session") == null) { return RedirectToAction("Index"); } else { ViewBag.Userid = HttpContext.Session.GetInt32("UserID"); return View(); } } [Route("Wedding/btAddWed")] [HttpPost] public IActionResult btAddWed(Wedding newWed) { if (ModelState.IsValid) { dbContext.Add(newWed); dbContext.SaveChanges(); return RedirectToAction("DetailWed", new { id = newWed.WeddingId }); } else { return View("NewWedding"); } } [Route("Wedding/detail/{id}")] [HttpGet] public IActionResult DetailWed(int id) { Wedding a = dbContext.Weddings.FirstOrDefault(pro => pro.WeddingId == id); ViewBag.WeddingInfo = a; var ListGuest = dbContext.Weddings .Include(per => per.WeddingtoUser) .ThenInclude(x => x.User) .FirstOrDefault(y => y.WeddingId == id); ViewBag.ListGuest = ListGuest; GoogleSigned.AssignAllServices(new GoogleSigned("ENTER-GOOGLE-MAPS-API-KEY-HERE")); var formattedWedAddress = a.WeddingStreetAddress + " " + a.WeddingCity + ", " + a.WeddingState + " " + a.WeddingZipcode; var request = new GeocodingRequest(); request.Address = formattedWedAddress; var response = new GeocodingService().GetResponse(request); if (response.Status == ServiceResponseStatus.Ok && response.Results.Count() > 0) { var result = response.Results.First(); Console.WriteLine("Full Address: " + result.FormattedAddress); Console.WriteLine("Latitude: " + result.Geometry.Location.Latitude); Console.WriteLine("Longitude: " + result.Geometry.Location.Longitude); Console.WriteLine(); ViewBag.Lati = result.Geometry.Location.Latitude; ViewBag.Long = result.Geometry.Location.Longitude; } else { Console.WriteLine("Unable to geocode. Status={0} and ErrorMessage={1}", response.Status, response.ErrorMessage); } return View(); } [Route("Wedding/DeleteWedding/{wedid}")] [HttpGet] public IActionResult DeleteWedding(int wedid) { Wedding a = dbContext.Weddings.FirstOrDefault(wed => wed.WeddingId == wedid); dbContext.Remove(a); dbContext.SaveChanges(); return Redirect("/User/Dashboard"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class offlinetrafficlight : MonoBehaviour { public float constantY; public float constantY1; public float timeRemainY; public float timeRemainY1; public GameObject YL; private void Start() { timeRemainY = constantY; timeRemainY1 = constantY1; } // Update is called once per frame void Update() { if(timeRemainY > 0) timeRemainY -= Time.deltaTime; YL.SetActive(true); if (timeRemainY < 0 && timeRemainY1 > 0) { YL.SetActive(false); timeRemainY1 -= Time.deltaTime; } else if(timeRemainY < 0 && timeRemainY1 < 0) { timeRemainY = constantY; timeRemainY1 = constantY1; } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Media; namespace Sekwencja { /// <summary> /// Główna klasa projektu. Odpowiedzialna za utworzenie okna z grą, obsługę całej gry i odczytywania ruchów gracza z klawiatury. /// </summary> public partial class Form1 : Form { /// <summary> /// Zmienna klasy game_info, przechowuje informacje o aktualnym stanie gry itp. /// </summary> game_info game = new game_info(); /// <summary> /// Zmienna klasy user_input, przechowuje informacje o danych wprowadzanych przez gracza. /// </summary> user_input input = new user_input(); /// <summary> /// Konstruktor klasy Form1. Przypisywane są w nim wszystkie labele (bloki planszy) i uruchamiana metoda startująca grę. /// </summary> public Form1() { InitializeComponent(); game.labels = new Label[36] {label1, label2, label3, label4, label5, label6, label7, label8, label9, label10, label11, label12, label13, label14, label15, label16, label17, label18, label19, label20, label21, label22, label23, label24, label25, label26, label27, label28, label29, label30, label31, label32, label33, label34, label35, label36}; start_game(); } /// <summary> /// Uruchomienie metody generowania sekwencji i pokazanie jej na ekranie (rozpoczęcie gry). /// </summary> private void start_game() { game.generate_seq(); show_seq(); } /// <summary> /// Pokazanie sekwencji na ekranie /// </summary> private void show_seq() { input.enabled = false; int current_pos; current_pos = 35; //start to zawsze prawy dolny róg, czyli labels[35] game.labels[35].BackColor = Color.Green; //czas na zapamiętanie sekwencji zależny od ilości ruchów timer2.Interval = 500 * game.number_of_moves; if (game.level_stopwatch_started == false) //sprawdzenie, czy rozpoczęto już pomiar czasu { game.level_time.Start(); //rozpoczęcie pomiaru czasu poziomu game.level_stopwatch_started = true; } for (int i = 0; i < game.number_of_moves; i++) { switch (game.seq[i]) { case "up": game.labels[current_pos].Text = "\u2191"; //strzałka w górę current_pos -= 6; game.labels[current_pos].BackColor = Color.Green; break; case "down": game.labels[current_pos].Text = "\u2193"; //strzałka w dół current_pos += 6; game.labels[current_pos].BackColor = Color.Green; break; case "left": game.labels[current_pos].Text = "\u2190"; //strzałka w lewo current_pos -= 1; game.labels[current_pos].BackColor = Color.Green; break; case "right": game.labels[current_pos].Text = "\u2192"; //strzałka w prawo current_pos += 1; game.labels[current_pos].BackColor = Color.Green; break; } } timer2.Start(); } /// <summary> /// Funkcja wymazująca sekwencję z planszy /// </summary> private void clear_screen() { for (int i = 0; i < 36; i++) { game.labels[i].BackColor = Color.SteelBlue; game.labels[i].Text = ""; } game.labels[35].BackColor = Color.Green; input.enabled = true; } /// <summary> /// Funkcja sprawdzająca poprawność ruchów gracza i ukończenie poziomu. Zawiera także odtwarzanie dźwięków. /// </summary> private void check_input() { bool flag; flag = true; //sprawdzenie, czy gracz popełnił błąd for (int i=0; i<game.number_of_moves;i++) { if (input.keyboard_input[i] != game.seq[i]) { flag = false; } } //jeśli gracz poprawnie wykonał wszystkie ruchy if (flag == true) { //sprawdzenie czy skończony został cały poziom if (game.number_of_moves == game.max_moves) { //zaktualizowanie wyświetlanej na ekranie punktacji game.score += game.number_of_moves + 25; points_label.Text = "PUNKTY: " + game.score.ToString(); //powiadomienie o ukończeniu poziomu notification_label.ForeColor = Color.Green; notification_label.Text = "Ukończono poziom " + game.level.ToString()+". Dodano 25 punktów."; //wyświetlenie czasu przejścia zakończonego poziomu na ekranie game.level_time.Stop(); TimeSpan ts = new TimeSpan(); ts = game.level_time.Elapsed; string elapsedTime = String.Format("{0}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10); level_time_label.Text = "CZAS: " + elapsedTime; //reset stopera odmierzającego czas poziomu game.level_time.Reset(); game.level_stopwatch_started = false; //przygotowanie do kolejnego poziomu if(game.level == 1 || game.level == 2) { game.number_of_moves = 3; game.level += 1; game.max_moves += 4; input.count_input = 0; input.current_pos = 35; level_label.Text = "POZIOM: " + game.level; //odtworzenie dźwięku new SoundPlayer(Properties.Resources.zapsplat_success).Play(); //timer3 i wewnątrz niego clear_screen() timer3.Interval = 500; timer3.Start(); //timer4 i wewnątrz niego start_game() timer4.Interval = 1500; timer4.Start(); } else if(game.level == 3) { //zaktualizowanie tekstu w obszarze powiadomień notification_label.ForeColor = Color.Green; notification_label.Text = "Gratulacje! Ukończono wszystkie poziomy."; //odtworzenie dźwięku new SoundPlayer(Properties.Resources.zapsplat_success).Play(); } } //jeśli nie ukończono jeszcze poziomu else { //wyświetlenie na ekranie punktacji game.score += game.number_of_moves; points_label.Text = "PUNKTY: " + game.score.ToString(); //zwiększenie liczby ruchów game.number_of_moves += 1; input.count_input = 0; input.current_pos = 35; //timer do wyczyszczenia ekranu timer3.Interval = 500; timer3.Start(); //timer do pokazania sekwencji timer1.Interval = 1000; timer1.Start(); } } //jeśli sekwencja jest nieprawidłowa else { //zaktualizowanie tekstu w obszarze powiadomień notification_label.ForeColor = Color.Crimson; notification_label.Text = "Nieprawidłowa sekwencja! Możesz zrestartować lub zakończyć grę używając menu poniżej."; //odtworzenie dźwięku new SoundPlayer(Properties.Resources.zapsplat_fail).Play(); } } //odczyt klawiszy strzałek /// <summary> /// "Odczyt" klawiszy strzałek - wymagany do działania ProcessCmdKey /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_KeyPress(object sender, KeyPressEventArgs e) { } //nadpisanie ProcessCmdKey aby możliwe było odczytywanie klawiszy strzałek /// <summary> /// Nadpisanie ProcessCmdKey aby możliwe było bezpośrednie odczytywanie klawiszy strzałek. /// Przekazuje ona do zapisu ruchy gracza i dzięki niej wyświetlane są w czasie rzeczywistym ruchy gracza na planszy. /// </summary> /// <param name="msg"></param> /// <param name="keyData"></param> /// <returns></returns> protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool invalid = false; if (input.enabled == true) { //zapisywanie ruchów gracza i pokazywanie ich na ekranie switch (keyData) { case Keys.Down: //sprawdzenie czy ruch jest nieprawidłowy if (input.current_pos >= 30) invalid = true; else { input.keyboard_input[input.count_input] = "down"; game.labels[input.current_pos].Text = "\u2193"; input.current_pos += 6; game.labels[input.current_pos].BackColor = Color.Green; } break; case Keys.Up: //sprawdzenie czy ruch jest nieprawidłowy if (input.current_pos <= 5) invalid = true; else { input.keyboard_input[input.count_input] = "up"; game.labels[input.current_pos].Text = "\u2191"; input.current_pos -= 6; game.labels[input.current_pos].BackColor = Color.Green; } break; case Keys.Right: //sprawdzenie czy ruch jest nieprawidłowy if (input.current_pos == 5 || input.current_pos == 11 || input.current_pos == 17 || input.current_pos == 23 || input.current_pos == 29 || input.current_pos == 35) invalid = true; else { input.keyboard_input[input.count_input] = "right"; game.labels[input.current_pos].Text = "\u2192"; input.current_pos += 1; game.labels[input.current_pos].BackColor = Color.Green; } break; case Keys.Left: //sprawdzenie czy ruch jest nieprawidłowy if (input.current_pos == 0 || input.current_pos == 6 || input.current_pos == 12 || input.current_pos == 18 || input.current_pos == 24 || input.current_pos == 30) invalid = true; else { input.keyboard_input[input.count_input] = "left"; game.labels[input.current_pos].Text = "\u2190"; input.current_pos -= 1; game.labels[input.current_pos].BackColor = Color.Green; } break; } if (invalid == false) //wykonaj tylko jeśli ruch jest prawidłowy { input.count_input += 1; if (input.count_input == game.number_of_moves) { input.enabled = false; check_input(); } } } return base.ProcessCmdKey(ref msg, keyData); } /// <summary> /// Metoda służąca do restartu gry. (Reset informacji o grze, zatrzymanie timerów itp.) /// </summary> private void restart_game() { //reset informacji o grze (czas poziomu, poziom, liczba ruchów itp.) game.reset_game_info(); //zatrzymanie timerów timer1.Stop(); timer2.Stop(); timer3.Stop(); //zresetowanie wszystkich ruchów gracza input.reset_input(); //wyczyszczenie ekranu clear_screen(); //przywrócenie domyślnych wyświetlanych wartości (czas, poziom, punkty) level_time_label.Text = "CZAS: X"; level_label.Text = "POZIOM: 1"; points_label.Text = "PUNKTY: 0"; notification_label.Text = ""; //ponowne rozpoczęcie gry start_game(); } /// <summary> /// Zakończenie działania aplikacji. /// </summary> private void end_game() { Application.Exit(); } /// <summary> /// Metoda uruchamiana po kliknięciu na napis menu. Powoduje pokazanie opcji w menu (koniec i restart). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menu_label_Click(object sender, EventArgs e) { koniec_label.Visible = true; koniec_label.Enabled = true; restart_label.Visible = true; restart_label.Enabled = true; } /// <summary> /// Metoda uruchamiana po kliknięciu na napis restart. Uruchamia ona metodę restart_game() i ukrywa opcję menu. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void restart_label_Click(object sender, EventArgs e) { restart_game(); koniec_label.Visible = false; koniec_label.Enabled = false; restart_label.Visible = false; restart_label.Enabled = false; } /// <summary> /// Metoda uruchamiana po kliknięciu na napis koniec. Uruchamia metodę end_game(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void koniec_label_Click(object sender, EventArgs e) { end_game(); koniec_label.Visible = false; koniec_label.Enabled = false; restart_label.Visible = false; restart_label.Enabled = false; } /// <summary> /// Timer do pokazania sekwencji. Uruchamia metodę show_seq(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { timer1.Stop(); show_seq(); } /// <summary> /// Timer do wymazania sekwencji z ekranu. Uruchamia metodę clear_screen(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer2_Tick(object sender, EventArgs e) { clear_screen(); timer2.Stop(); } /// <summary> /// Timer do wymazania sekwencji z ekranu przed przejściem do kolejnego poziomu. Uruchamia metodę clear_screen(). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer3_Tick(object sender, EventArgs e) { timer3.Stop(); clear_screen(); } /// <summary> /// Timer do uruchomienia metody start_game() startującej kolejny poziom i usunięcia tekstu z notification_label. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer4_Tick(object sender, EventArgs e) { timer4.Stop(); //usunięcie powiadomienia o ukończeniu poziomu notification_label.Text = ""; start_game(); } /// <summary> /// Metoda pokazująca okienko z informacjami o licencjach zasobów po kliknięciu na 'Licencje'. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void license_label_Click(object sender, EventArgs e) { MessageBox.Show("Licencje:\n"+ "Efekty dźwiękowe pobrane ze strony www.zapsplat.com\n" + "Napisy menu stworzone za pomocą darmowego generatora www.cooltext.com"); } } }
using System; using System.Windows; using System.Windows.Controls; namespace Emanate.Vso.Admin.Devices { public partial class VsoDeviceView { private VsoDeviceViewModel viewModel; public VsoDeviceView() { DataContextChanged += InputConfigurationControl_DataContextChanged; InitializeComponent(); } private void InputConfigurationControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { viewModel = (VsoDeviceViewModel)e.NewValue; //await viewModel.Initialize(); PasswordInput.Password = viewModel.Password; //DataContext = viewModel; } private void PasswordInputInitialized(object sender, EventArgs e) { var passwordBox = sender as PasswordBox; if (passwordBox == null) return; if (viewModel != null) passwordBox.Password = viewModel.Password; passwordBox.PasswordChanged += passwordBox_PasswordChanged; } void passwordBox_PasswordChanged(object sender, RoutedEventArgs e) { var passwordBox = sender as PasswordBox; if (passwordBox == null) return; viewModel.Password = passwordBox.Password; } } }
using System; namespace Politicizer.Api.Models { public class History { public bool active {get; set;} public DateTime active_at {get; set;} public bool awaiting_signature {get; set;} public string house_passage_result {get; set;} public DateTime house_passage_result_at {get; set;} public string senate_passage_result {get; set;} public DateTime senate_passage_result_at {get; set;} public bool enacted {get; set;} public bool vetoed {get; set;} } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades.Estoque.Suprimentos; using PDV.DAO.Enum; using System.Collections.Generic; using System.Data; namespace PDV.CONTROLER.Funcoes { public class FuncoesConversaoUnidadeMedida { public static bool Salvar(ConversaoUnidadeDeMedida Conversao, TipoOperacao Op) { using (SQLQuery oSQL = new SQLQuery()) { switch(Op) { case TipoOperacao.INSERT: oSQL.SQL = @"INSERT INTO CONVERSAOUNIDADEDEMEDIDA (IDCONVERSAOUNIDADEDEMEDIDA, IDPRODUTO, IDUNIDADEDEMEDIDAENTRADA, IDUNIDADEDEMEDIDASAIDA, FATOR) VALUES (@IDCONVERSAOUNIDADEDEMEDIDA, @IDPRODUTO, @IDUNIDADEDEMEDIDAENTRADA, @IDUNIDADEDEMEDIDASAIDA, @FATOR)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE CONVERSAOUNIDADEDEMEDIDA SET IDPRODUTO = @IDPRODUTO, IDUNIDADEDEMEDIDAENTRADA = @IDUNIDADEDEMEDIDAENTRADA, IDUNIDADEDEMEDIDASAIDA = IDUNIDADEDEMEDIDASAIDA, FATOR = @FATOR WHERE IDCONVERSAOUNIDADEDEMEDIDA = @IDCONVERSAOUNIDADEDEMEDIDA"; break; } oSQL.ParamByName["IDCONVERSAOUNIDADEDEMEDIDA"] = Conversao.IDConversaoUnidadeDeMedida; oSQL.ParamByName["IDPRODUTO"] = Conversao.IDProduto; oSQL.ParamByName["IDUNIDADEDEMEDIDAENTRADA"] = Conversao.IDUnidadeDeMedidaEntrada; oSQL.ParamByName["IDUNIDADEDEMEDIDASAIDA"] = Conversao.IDUnidadeDeMedidaSaida; oSQL.ParamByName["FATOR"] = Conversao.Fator; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDConversaoUnidadeDeMedida) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "DELETE FROM CONVERSAOUNIDADEDEMEDIDA WHERE IDCONVERSAOUNIDADEDEMEDIDA = IDCONVERSAOUNIDADEDEMEDIDA"; oSQL.ParamByName["IDCONVERSAOUNIDADEDEMEDIDA"] = IDConversaoUnidadeDeMedida; return oSQL.ExecSQL() == 1; } } public static DataTable GetConversoes(string Produto) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = $@"SELECT PRODUTO.DESCRICAO AS PRODUTO, UNENTRADA.SIGLA AS UNIDADEDEMEDIDAENTRADA, UNSAIDA.SIGLA AS UNIDADEDEMEDIDASAIDA, CONVERSAOUNIDADEDEMEDIDA.FATOR, CONVERSAOUNIDADEDEMEDIDA.IDCONVERSAOUNIDADEDEMEDIDA, CONVERSAOUNIDADEDEMEDIDA.IDPRODUTO, CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDAENTRADA, CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDASAIDA FROM CONVERSAOUNIDADEDEMEDIDA INNER JOIN PRODUTO ON (CONVERSAOUNIDADEDEMEDIDA.IDPRODUTO = PRODUTO.IDPRODUTO) INNER JOIN UNIDADEDEMEDIDA UNENTRADA ON (CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDAENTRADA = UNENTRADA.IDUNIDADEDEMEDIDA) INNER JOIN UNIDADEDEMEDIDA UNSAIDA ON (CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDASAIDA = UNSAIDA.IDUNIDADEDEMEDIDA) WHERE UPPER(PRODUTO.DESCRICAO) LIKE UPPER('%{Produto}%')"; oSQL.Open(); return oSQL.dtDados; } } public static ConversaoUnidadeDeMedida GetConversao(decimal IDConversaoUnidadeDeMedida) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT * FROM CONVERSAOUNIDADEDEMEDIDA WHERE IDCONVERSAOUNIDADEDEMEDIDA = @IDCONVERSAOUNIDADEDEMEDIDA"; oSQL.ParamByName["IDCONVERSAOUNIDADEDEMEDIDA"] = IDConversaoUnidadeDeMedida; oSQL.Open(); return EntityUtil<ConversaoUnidadeDeMedida>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static bool Existe(decimal IDConversaoUnidadeDeMedida) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM CONVERSAOUNIDADEDEMEDIDA WHERE IDCONVERSAOUNIDADEDEMEDIDA = @IDCONVERSAOUNIDADEDEMEDIDA"; oSQL.ParamByName["IDCONVERSAOUNIDADEDEMEDIDA"] = IDConversaoUnidadeDeMedida; oSQL.Open(); return !oSQL.IsEmpty; } } public static List<ConversaoUnidadeDeMedida> GetConversoesPorProduto(decimal IDProduto) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT CONVERSAOUNIDADEDEMEDIDA.IDCONVERSAOUNIDADEDEMEDIDA, CONVERSAOUNIDADEDEMEDIDA.IDPRODUTO, CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDAENTRADA, CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDASAIDA, CONVERSAOUNIDADEDEMEDIDA.FATOR, UNENT.SIGLA AS UNENTRADA, UNSAI.SIGLA AS UNSAIDA FROM CONVERSAOUNIDADEDEMEDIDA INNER JOIN UNIDADEDEMEDIDA UNENT ON (CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDAENTRADA = UNENT.IDUNIDADEDEMEDIDA) INNER JOIN UNIDADEDEMEDIDA UNSAI ON (CONVERSAOUNIDADEDEMEDIDA.IDUNIDADEDEMEDIDASAIDA = UNSAI.IDUNIDADEDEMEDIDA) WHERE CONVERSAOUNIDADEDEMEDIDA.IDPRODUTO = @IDPRODUTO"; oSQL.ParamByName["IDPRODUTO"] = IDProduto; oSQL.Open(); return new DataTableParser<ConversaoUnidadeDeMedida>().ParseDataTable(oSQL.dtDados); } } } }
/* VelociWrap.cs * Author: Ben Hartman */ using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace DinoDiner.Menu { /// <summary> /// Class to represent the VelociWrap entree. /// </summary> public class VelociWrap : Entree, IMenuItem, IOrderItem, INotifyPropertyChanged { /// <summary> /// backing variables for the properties. /// </summary> private bool lettuce = true; private bool dressing = true; private bool cheese = true; /// <summary> /// Gets and sets the description. /// </summary> public override string Description { get { return this.ToString(); } } /// <summary> /// Gets any special preparation instructions. /// </summary> public override string[] Special { get { List<string> special = new List<string>(); if (!cheese) special.Add("Hold Parmesan Cheese"); if (!lettuce) special.Add("Hold Lettuce"); if (!dressing) special.Add("Hold Ceasar Dressing"); return special.ToArray(); } } /// <summary> /// Class constructor to set the price, calories, and ingredients. /// </summary> public VelociWrap() { this.Price = 6.86; this.Calories = 356; Category = "Entree"; } /// <summary> /// Method to implement no lettuce asked on meal /// </summary> public void HoldLettuce() { this.lettuce = false; NotifyOfPropertyChange("Special"); NotifyOfPropertyChange("Ingredients"); } /// <summary> /// Method to implement no dressing asked on meal /// </summary> public void HoldDressing() { this.dressing = false; NotifyOfPropertyChange("Special"); NotifyOfPropertyChange("Ingredients"); } /// <summary> /// Method to implement no cheese asked on meal /// </summary> public void HoldCheese() { this.cheese = false; NotifyOfPropertyChange("Special"); NotifyOfPropertyChange("Ingredients"); } /// <summary> /// Property to return a list of the Ingredients. /// </summary> public override List<string> Ingredients { get { List<string> Ingredients = new List<string>() { "Flour Tortilla", "Chicken Breast", "Parmesan Cheese", "Romaine Lettuce", "Ceasar Dressing",}; if(cheese == false) { Ingredients.Remove("Parmesan Cheese"); } if (lettuce == false) { Ingredients.Remove("Lettuce"); } if (dressing == false) { Ingredients.Remove("Dressing"); } return Ingredients; } } /// <summary> /// Method to override ToString() to return name of item. /// </summary> /// <returns></returns> public override string ToString() { return "Veloci-Wrap"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief 入力。 */ /** NInput */ namespace NInput { /** Input */ public class Input : Config { /** constructor */ private Input() { } } }
using System.Threading.Tasks; using Common; using Common.Log; using Flurl.Http; using Lykke.Service.SmsSender.Core.Services; using Lykke.Service.SmsSender.Core.Settings.ServiceSettings.SenderSettings; namespace Lykke.Service.SmsSender.Services.SmsSenders.Twilio { public class TwilioSmsSender : ISmsSender { private readonly string _baseUrl; private readonly ProviderSettings _settings; private readonly ILog _log; public TwilioSmsSender( string baseUrl, ProviderSettings settings, ILog log) { _baseUrl = baseUrl; _settings = settings; _log = log.CreateComponentScope(nameof(TwilioSmsSender)); } public async Task<string> SendSmsAsync(string commandId, string phone, string message, string countryCode) { try { var response = await $"{_settings.BaseUrl}/Accounts/{_settings.ApiKey}/Messages.json" .WithBasicAuth(_settings.ApiKey, _settings.ApiSecret) .PostUrlEncodedAsync(new { To = phone, From = _settings.GetFrom(countryCode), Body = message, StatusCallback = $"{_baseUrl}/callback/twilio" }).ReceiveJson<TwilioResponse>(); if (!string.IsNullOrEmpty(response.ErrorCode)) { var error = new { response.Sid, Phone = response.To.SanitizePhone(), countryCode, response.Status, response.ErrorCode, response.ErrorMessage }; if (response.AccountNotActive) _log.WriteError(nameof(SendSmsAsync), error); else _log.WriteWarning(nameof(SendSmsAsync), error, "error sending sms"); } else { return response.Sid; } } catch (FlurlHttpException ex) { var error = await ex.GetResponseJsonAsync<TwilioErrorResponse>(); _log.WriteWarning(nameof(SendSmsAsync), error, "twilio: error sending sms"); } return null; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using DataAccessLayer.basis; using Model.DataEntity; using Model.InvoiceManagement; using Model.Locale; using Model.Resource; using Model.Schema.EIVO; using Utility; namespace Model.Models.ViewModel { public static class ValidatorExtensions { public readonly static String[] __InvoiceTypeList = { /*"01", "02", "03", "04", "05", "06",*/ "07", "08" }; public static bool IsValidInvoiceType(this byte? invoiceType) { return invoiceType.HasValue ? invoiceType.Value.IsValidInvoiceType() : false; } public static bool IsValidInvoiceType(this byte invoiceType) { return __InvoiceTypeList.Contains(String.Format("{0:00}", invoiceType)); } public static bool IsValidInvoiceType(this String invoiceType, out byte data) { if (byte.TryParse(invoiceType, out data)) { return data.IsValidInvoiceType(); } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UCMAService { public class ConferenceUser { public string DisplayName { get; set; } public string UserAddress { get; set; } } }
using System.IO; using System.Web; using System.Web.Http; using log4net; using log4net.Config; namespace CloneDeploy_App { public class WebApiApplication : HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var logPath = HttpContext.Current.Server.MapPath("~") + Path.DirectorySeparatorChar + "private" + Path.DirectorySeparatorChar + "logs" + Path.DirectorySeparatorChar + "CloneDeployApplication.log"; GlobalContext.Properties["LogFile"] = logPath; XmlConfigurator.Configure(); } } }
using LuaInterface; using SLua; using System; public class Lua_RO_HttpOperationJsonState : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "RO.HttpOperationJsonState"); LuaObject.addMember(l, 0, "OK"); LuaObject.addMember(l, 1, "LackOfParams"); LuaObject.addMember(l, 2, "ErrorGetServerVersion"); LuaObject.addMember(l, 3, "ErrorGetUpdateInfo"); LuaObject.addMember(l, 4, "ErrorClientMuchNewer"); LuaDLL.lua_pop(l, 1); } }
using System; #if MONO using System.IO; #else using Delimon.Win32.IO; #endif using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace FileSearch { public interface IExtendedFileInfo { [JsonProperty] string Extension { get; } [JsonProperty] string Name { get; } [JsonIgnore] bool IsReadOnly { get; } [JsonProperty] [JsonConverter(typeof(IsoDateTimeConverter))] DateTime Modified { get; } [JsonProperty] [JsonConverter(typeof(IsoDateTimeConverter))] DateTime LastAccessed { get; } [JsonProperty] [JsonConverter(typeof(IsoDateTimeConverter))] DateTime Created { get; } [JsonProperty] long Length { get; set; } [JsonIgnore] string FullName { get; } [JsonProperty] string MD5 { get; set; } [JsonProperty] string MachineName { get; } [JsonProperty] string Directory { get; } [JsonIgnore] FileAttributes Attributes { get; set; } FileInfo GetFileInfo(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test7._6 { class iphone { public string language = "英文"; public iphone() { language = "中文"; } public iphone(string language) { this.language = language; } } class Program { static void Main(string[] args) { Console.WriteLine("创造第一部手机:"); iphone sj1 = new iphone(); Console.WriteLine("手机的默认语言为:{0}", sj1.language); Console.WriteLine("创造第二部手机:"); iphone sj2 = new iphone("阿拉伯语"); Console.WriteLine("手机的默认语言为:{0}", sj2.language); Console.ReadKey(); } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class UIMangement : MonoBehaviour { public void onButtonClicked(GameObject button) { switch (button.tag) { case "EnterBtn": SceneManager.LoadScene("Stepper"); break; case "TurnoffBtn": GameObject.Find("Base").GetComponent<CreateBase>().turnoffButton(); break; case "chbase": GameObject.Find("Base").GetComponent<CreateBase>().displaycoll(); break; case "StepperBtn": SceneManager.LoadScene("SelectMask"); break; case "BackBtn": SceneManager.LoadScene("MenuScene"); break; case "ResetBtn": string Scene = SceneManager.GetActiveScene().name; SceneManager.LoadScene(Scene); if (Scene == "SelectMask") { CreateMaskBtn.selectedButtons.Clear(); } break; default: MaskBtnCtrl buttonCtrl = button.GetComponent<MaskBtnCtrl>(); if (!CreateMaskBtn.selectedButtons.Contains(int.Parse(button.name))) { CreateMaskBtn.selectedButtons.Add(int.Parse(button.name)); buttonCtrl.setIsClicked(true); buttonCtrl.ChangeColor(); } break; } } }
using API.Models; using Nancy; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace API { public class Routes : NancyModule { private BeforePipeline bpl; public Routes() { Before += async (ctx, token) => { if (Startup.con.State != System.Data.ConnectionState.Connecting && Startup.con.State == System.Data.ConnectionState.Closed) { await Startup.ConOpen(token); return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN CONNECTION", InternalMessage = "CONNECTON IS IN PROGRESS" }); } else if (Startup.con.State == System.Data.ConnectionState.Connecting) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN CONNECTION", InternalMessage = "MYSQL CONNECTION IS IN PROGRESS" }); } else return null; }; Get("/", args => { return Request.Headers.ToDictionary(key => key, value => value); }); Get("/GetOTP", async (args) => { try { User user = await Startup.dbl.GetOTP(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); if (user == null) { user = new User { Success = "0" as string, Message = "USER NOT FOUND SUCCESSFULLY" as string, Mobile = "", Password = "" }; } return user; } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetParentsLoginTokenBase64", async (args) => { try { return await Startup.dbl.GetParentsLoginTokenBase64(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetCompany", async (args) => { try { return await Startup.dbl.GetCompany(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetCompanyImages", async (args) => { try { return await Startup.dbl.GetCompanyImages(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetAttendance", async (args) => { try { return await Startup.dbl.GetAttendance(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetMonthlyAttendances", async (args) => { try { return await Startup.dbl.GetMonthlyAttendances(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetDailyAttendance", async (args) => { try { return await Startup.dbl.GetDailyAttendance(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetTest", async (args) => { try { return await Startup.dbl.GetTest(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetMonthlyTests", async (args) => { try { return await Startup.dbl.GetMonthlyTests(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetTimetable", async (args) => { try { return await Startup.dbl.GetTimetable(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetFees", async (args) => { try { return await Startup.dbl.GetFees(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetLeave", async (args) => { try { return await Startup.dbl.GetLeave(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetPublicNotice", async (args) => { try { return await Startup.dbl.GetPublicNotice(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetNotice", async (args) => { try { return await Startup.dbl.GetNotice(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetNoticeMobilebased", async (args) => { try { return await Startup.dbl.GetNoticeMobilebased(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetChat", async (args) => { try { return await Startup.dbl.GetChat(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetPhotoGallery", async (args) => { try { return await Startup.dbl.GetPhotoGallery(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetVideoGallery", async (args) => { try { return await Startup.dbl.GetVideoGallery(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetPDFGallery", async (args) => { try { return await Startup.dbl.GetPDFGallery(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Get("/GetExam", async (args) => { try { return await Startup.dbl.GetExam(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Post("/SetLeave", async (args) => { try { return await Startup.dbl.SetLeave(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Post("/SetNotice", async (args) => { try { return await Startup.dbl.SetNotice(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Post("/SetChat", async (args) => { try { return await Startup.dbl.SetChat(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); Post("/SetLastVisit", async (args) => { try { return await Startup.dbl.SetLastVisit(new JObject { { "headers" , JsonConvert.SerializeObject(await GetRequestHeaders()) } }); } catch (Exception ex) { return Response.AsJson(new ResponseMessage { Success = "101", Message = "ERROR IN DATA", InternalMessage = ex.Message }); } }); } public Task<Dictionary<string, string>> GetRequestHeaders() { Dictionary<string, string> dic = new Dictionary<string, string>(); return Task.Run(() => { foreach (var item in Request.Headers) { List<string> lstValues = item.Value.ToList(); if (lstValues.Count == 1) dic.Add(item.Key, lstValues[0]); } return dic; }); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Logging; using Microsoft.PowerShell.EditorServices.Services.PowerShellContext; using Microsoft.PowerShell.EditorServices.Utility; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Services { /// <summary> /// Manages files that are accessed from a remote PowerShell session. /// Also manages the registration and handling of the 'psedit' function. /// </summary> internal class RemoteFileManagerService { #region Fields private ILogger logger; private string remoteFilesPath; private string processTempPath; private PowerShellContextService powerShellContext; private IEditorOperations editorOperations; private Dictionary<string, RemotePathMappings> filesPerComputer = new Dictionary<string, RemotePathMappings>(); private const string RemoteSessionOpenFile = "PSESRemoteSessionOpenFile"; private const string PSEditModule = @"<# .SYNOPSIS Opens the specified files in your editor window .DESCRIPTION Opens the specified files in your editor window .EXAMPLE PS > Open-EditorFile './foo.ps1' Opens foo.ps1 in your editor .EXAMPLE PS > gci ./myDir | Open-EditorFile Opens everything in 'myDir' in your editor .INPUTS Path an array of files you want to open in your editor #> function Open-EditorFile { param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]] $Path ) begin { $Paths = @() } process { $Paths += $Path } end { if ($Paths.Count -gt 1) { $preview = $false } else { $preview = $true } foreach ($fileName in $Paths) { Microsoft.PowerShell.Management\Get-ChildItem $fileName | Where-Object { ! $_.PSIsContainer } | Foreach-Object { $filePathName = $_.FullName # Get file contents $params = @{ Path=$filePathName; Raw=$true } if ($PSVersionTable.PSEdition -eq 'Core') { $params['AsByteStream']=$true } else { $params['Encoding']='Byte' } $contentBytes = Microsoft.PowerShell.Management\Get-Content @params # Notify client for file open. Microsoft.PowerShell.Utility\New-Event -SourceIdentifier PSESRemoteSessionOpenFile -EventArguments @($filePathName, $contentBytes, $preview) > $null } } } } <# .SYNOPSIS Creates new files and opens them in your editor window .DESCRIPTION Creates new files and opens them in your editor window .EXAMPLE PS > New-EditorFile './foo.ps1' Creates and opens a new foo.ps1 in your editor .EXAMPLE PS > Get-Process | New-EditorFile proc.txt Creates and opens a new foo.ps1 in your editor with the contents of the call to Get-Process .EXAMPLE PS > Get-Process | New-EditorFile proc.txt -Force Creates and opens a new foo.ps1 in your editor with the contents of the call to Get-Process. Overwrites the file if it already exists .INPUTS Path an array of files you want to open in your editor Value The content you want in the new files Force Overwrites a file if it exists #> function New-EditorFile { [CmdletBinding()] param ( [Parameter()] [String[]] [ValidateNotNullOrEmpty()] $Path, [Parameter(ValueFromPipeline=$true)] $Value, [Parameter()] [switch] $Force ) begin { $valueList = @() } process { $valueList += $Value } end { if ($Path) { foreach ($fileName in $Path) { if (-not (Microsoft.PowerShell.Management\Test-Path $fileName) -or $Force) { $valueList > $fileName # Get file contents $params = @{ Path=$fileName; Raw=$true } if ($PSVersionTable.PSEdition -eq 'Core') { $params['AsByteStream']=$true } else { $params['Encoding']='Byte' } $contentBytes = Microsoft.PowerShell.Management\Get-Content @params if ($Path.Count -gt 1) { $preview = $false } else { $preview = $true } # Notify client for file open. Microsoft.PowerShell.Utility\New-Event -SourceIdentifier PSESRemoteSessionOpenFile -EventArguments @($fileName, $contentBytes, $preview) > $null } else { $PSCmdlet.WriteError( ( Microsoft.PowerShell.Utility\New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList @( [System.Exception]'File already exists.' $Null [System.Management.Automation.ErrorCategory]::ResourceExists $fileName ) ) ) } } } else { $bytes = [System.Text.Encoding]::UTF8.GetBytes(($valueList | Microsoft.PowerShell.Utility\Out-String)) Microsoft.PowerShell.Utility\New-Event -SourceIdentifier PSESRemoteSessionOpenFile -EventArguments @($null, $bytes) > $null } } } Microsoft.PowerShell.Utility\Set-Alias psedit Open-EditorFile -Scope Global Microsoft.PowerShell.Core\Export-ModuleMember -Function Open-EditorFile, New-EditorFile "; // This script is templated so that the '-Forward' parameter can be added // to the script when in non-local sessions private const string CreatePSEditFunctionScript = @" param ( [string] $PSEditModule ) Microsoft.PowerShell.Utility\Register-EngineEvent -SourceIdentifier PSESRemoteSessionOpenFile -Forward -SupportEvent Microsoft.PowerShell.Core\New-Module -ScriptBlock ([Scriptblock]::Create($PSEditModule)) -Name PSEdit | Microsoft.PowerShell.Core\Import-Module -Global "; private const string RemovePSEditFunctionScript = @" Microsoft.PowerShell.Core\Get-Module PSEdit | Microsoft.PowerShell.Core\Remove-Module Microsoft.PowerShell.Utility\Unregister-Event -SourceIdentifier PSESRemoteSessionOpenFile -Force -ErrorAction Ignore "; private const string SetRemoteContentsScript = @" param( [string] $RemoteFilePath, [byte[]] $Content ) # Set file contents $params = @{ Path=$RemoteFilePath; Value=$Content; Force=$true } if ($PSVersionTable.PSEdition -eq 'Core') { $params['AsByteStream']=$true } else { $params['Encoding']='Byte' } Microsoft.PowerShell.Management\Set-Content @params 2>&1 "; #endregion #region Constructors /// <summary> /// Creates a new instance of the RemoteFileManagerService class. /// </summary> /// <param name="factory">An ILoggerFactory implementation used for writing log messages.</param> /// <param name="powerShellContext"> /// The PowerShellContext to use for file loading operations. /// </param> /// <param name="editorOperations"> /// The IEditorOperations instance to use for opening/closing files in the editor. /// </param> public RemoteFileManagerService( ILoggerFactory factory, PowerShellContextService powerShellContext, EditorOperationsService editorOperations) { Validate.IsNotNull(nameof(powerShellContext), powerShellContext); this.logger = factory.CreateLogger<RemoteFileManagerService>(); this.powerShellContext = powerShellContext; this.powerShellContext.RunspaceChanged += HandleRunspaceChangedAsync; this.editorOperations = editorOperations; this.processTempPath = Path.Combine( Path.GetTempPath(), "PSES-" + Process.GetCurrentProcess().Id); this.remoteFilesPath = Path.Combine(this.processTempPath, "RemoteFiles"); // Delete existing temporary file cache path if it already exists this.TryDeleteTemporaryPath(); // Register the psedit function in the current runspace this.RegisterPSEditFunction(this.powerShellContext.CurrentRunspace); } #endregion #region Public Methods /// <summary> /// Opens a remote file, fetching its contents if necessary. /// </summary> /// <param name="remoteFilePath"> /// The remote file path to be opened. /// </param> /// <param name="runspaceDetails"> /// The runspace from which where the remote file will be fetched. /// </param> /// <returns> /// The local file path where the remote file's contents have been stored. /// </returns> public async Task<string> FetchRemoteFileAsync( string remoteFilePath, RunspaceDetails runspaceDetails) { string localFilePath = null; if (!string.IsNullOrEmpty(remoteFilePath)) { try { RemotePathMappings pathMappings = this.GetPathMappings(runspaceDetails); localFilePath = this.GetMappedPath(remoteFilePath, runspaceDetails); if (!pathMappings.IsRemotePathOpened(remoteFilePath)) { // Does the local file already exist? if (!File.Exists(localFilePath)) { // Load the file contents from the remote machine and create the buffer PSCommand command = new PSCommand(); command.AddCommand("Microsoft.PowerShell.Management\\Get-Content"); command.AddParameter("Path", remoteFilePath); command.AddParameter("Raw"); command.AddParameter("Encoding", "Byte"); byte[] fileContent = (await this.powerShellContext.ExecuteCommandAsync<byte[]>(command, false, false)) .FirstOrDefault(); if (fileContent != null) { this.StoreRemoteFile(localFilePath, fileContent, pathMappings); } else { this.logger.LogWarning( $"Could not load contents of remote file '{remoteFilePath}'"); } } } } catch (IOException e) { this.logger.LogError( $"Caught {e.GetType().Name} while attempting to get remote file at path '{remoteFilePath}'\r\n\r\n{e.ToString()}"); } } return localFilePath; } /// <summary> /// Saves the contents of the file under the temporary local /// file cache to its corresponding remote file. /// </summary> /// <param name="localFilePath"> /// The local file whose contents will be saved. It is assumed /// that the editor has saved the contents of the local cache /// file to disk before this method is called. /// </param> /// <returns>A Task to be awaited for completion.</returns> public async Task SaveRemoteFileAsync(string localFilePath) { string remoteFilePath = this.GetMappedPath( localFilePath, this.powerShellContext.CurrentRunspace); this.logger.LogTrace( $"Saving remote file {remoteFilePath} (local path: {localFilePath})"); byte[] localFileContents = null; try { localFileContents = File.ReadAllBytes(localFilePath); } catch (IOException e) { this.logger.LogException( "Failed to read contents of local copy of remote file", e); return; } PSCommand saveCommand = new PSCommand(); saveCommand .AddScript(SetRemoteContentsScript) .AddParameter("RemoteFilePath", remoteFilePath) .AddParameter("Content", localFileContents); StringBuilder errorMessages = new StringBuilder(); await this.powerShellContext.ExecuteCommandAsync<object>( saveCommand, errorMessages, false, false); if (errorMessages.Length > 0) { this.logger.LogError($"Remote file save failed due to an error:\r\n\r\n{errorMessages}"); } } /// <summary> /// Creates a temporary file with the given name and contents /// corresponding to the specified runspace. /// </summary> /// <param name="fileName"> /// The name of the file to be created under the session path. /// </param> /// <param name="fileContents"> /// The contents of the file to be created. /// </param> /// <param name="runspaceDetails"> /// The runspace for which the temporary file relates. /// </param> /// <returns>The full temporary path of the file if successful, null otherwise.</returns> public string CreateTemporaryFile(string fileName, string fileContents, RunspaceDetails runspaceDetails) { string temporaryFilePath = Path.Combine(this.processTempPath, fileName); try { File.WriteAllText(temporaryFilePath, fileContents); RemotePathMappings pathMappings = this.GetPathMappings(runspaceDetails); pathMappings.AddOpenedLocalPath(temporaryFilePath); } catch (IOException e) { this.logger.LogError( $"Caught {e.GetType().Name} while attempting to write temporary file at path '{temporaryFilePath}'\r\n\r\n{e.ToString()}"); temporaryFilePath = null; } return temporaryFilePath; } /// <summary> /// For a remote or local cache path, get the corresponding local or /// remote file path. /// </summary> /// <param name="filePath"> /// The remote or local file path. /// </param> /// <param name="runspaceDetails"> /// The runspace from which the remote file was fetched. /// </param> /// <returns>The mapped file path.</returns> public string GetMappedPath( string filePath, RunspaceDetails runspaceDetails) { RemotePathMappings remotePathMappings = this.GetPathMappings(runspaceDetails); return remotePathMappings.GetMappedPath(filePath); } /// <summary> /// Returns true if the given file path is under the remote files /// path in the temporary folder. /// </summary> /// <param name="filePath">The local file path to check.</param> /// <returns> /// True if the file path is under the temporary remote files path. /// </returns> public bool IsUnderRemoteTempPath(string filePath) { return filePath.StartsWith( this.remoteFilesPath, System.StringComparison.CurrentCultureIgnoreCase); } #endregion #region Private Methods private string StoreRemoteFile( string remoteFilePath, byte[] fileContent, RunspaceDetails runspaceDetails) { RemotePathMappings pathMappings = this.GetPathMappings(runspaceDetails); string localFilePath = pathMappings.GetMappedPath(remoteFilePath); this.StoreRemoteFile( localFilePath, fileContent, pathMappings); return localFilePath; } private void StoreRemoteFile( string localFilePath, byte[] fileContent, RemotePathMappings pathMappings) { File.WriteAllBytes(localFilePath, fileContent); pathMappings.AddOpenedLocalPath(localFilePath); } private RemotePathMappings GetPathMappings(RunspaceDetails runspaceDetails) { RemotePathMappings remotePathMappings = null; string computerName = runspaceDetails.SessionDetails.ComputerName; if (!this.filesPerComputer.TryGetValue(computerName, out remotePathMappings)) { remotePathMappings = new RemotePathMappings(runspaceDetails, this); this.filesPerComputer.Add(computerName, remotePathMappings); } return remotePathMappings; } private async void HandleRunspaceChangedAsync(object sender, RunspaceChangedEventArgs e) { if (e.ChangeAction == RunspaceChangeAction.Enter) { this.RegisterPSEditFunction(e.NewRunspace); } else { // Close any remote files that were opened if (e.PreviousRunspace.Location == RunspaceLocation.Remote && (e.ChangeAction == RunspaceChangeAction.Shutdown || !string.Equals( e.NewRunspace.SessionDetails.ComputerName, e.PreviousRunspace.SessionDetails.ComputerName, StringComparison.CurrentCultureIgnoreCase))) { RemotePathMappings remotePathMappings; if (this.filesPerComputer.TryGetValue(e.PreviousRunspace.SessionDetails.ComputerName, out remotePathMappings)) { foreach (string remotePath in remotePathMappings.OpenedPaths) { await this.editorOperations?.CloseFileAsync(remotePath); } } } if (e.PreviousRunspace != null) { this.RemovePSEditFunction(e.PreviousRunspace); } } } private async void HandlePSEventReceivedAsync(object sender, PSEventArgs args) { if (string.Equals(RemoteSessionOpenFile, args.SourceIdentifier, StringComparison.CurrentCultureIgnoreCase)) { try { if (args.SourceArgs.Length >= 1) { string localFilePath = string.Empty; string remoteFilePath = args.SourceArgs[0] as string; // Is this a local process runspace? Treat as a local file if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Local) { localFilePath = remoteFilePath; } else { byte[] fileContent = null; if (args.SourceArgs.Length >= 2) { // Try to cast as a PSObject to get the BaseObject, if not, then try to case as a byte[] PSObject sourceObj = args.SourceArgs[1] as PSObject; if (sourceObj != null) { fileContent = sourceObj.BaseObject as byte[]; } else { fileContent = args.SourceArgs[1] as byte[]; } } // If fileContent is still null after trying to // unpack the contents, just return an empty byte // array. fileContent = fileContent ?? new byte[0]; if (remoteFilePath != null) { localFilePath = this.StoreRemoteFile( remoteFilePath, fileContent, this.powerShellContext.CurrentRunspace); } else { await this.editorOperations?.NewFileAsync(); EditorContext context = await this.editorOperations?.GetEditorContextAsync(); context?.CurrentFile.InsertText(Encoding.UTF8.GetString(fileContent, 0, fileContent.Length)); } } bool preview = true; if (args.SourceArgs.Length >= 3) { bool? previewCheck = args.SourceArgs[2] as bool?; preview = previewCheck ?? true; } // Open the file in the editor this.editorOperations?.OpenFileAsync(localFilePath, preview); } } catch (NullReferenceException e) { this.logger.LogException("Could not store null remote file content", e); } } } private void RegisterPSEditFunction(RunspaceDetails runspaceDetails) { if (runspaceDetails.Location == RunspaceLocation.Remote && runspaceDetails.Context == RunspaceContext.Original) { try { runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived += HandlePSEventReceivedAsync; PSCommand createCommand = new PSCommand(); createCommand .AddScript(CreatePSEditFunctionScript) .AddParameter("PSEditModule", PSEditModule); if (runspaceDetails.Context == RunspaceContext.DebuggedRunspace) { this.powerShellContext.ExecuteCommandAsync(createCommand).Wait(); } else { using (var powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Runspace = runspaceDetails.Runspace; powerShell.Commands = createCommand; powerShell.Invoke(); } } } catch (RemoteException e) { this.logger.LogException("Could not create psedit function.", e); } } } private void RemovePSEditFunction(RunspaceDetails runspaceDetails) { if (runspaceDetails.Location == RunspaceLocation.Remote && runspaceDetails.Context == RunspaceContext.Original) { try { if (runspaceDetails.Runspace.Events != null) { runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived -= HandlePSEventReceivedAsync; } if (runspaceDetails.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { using (var powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Runspace = runspaceDetails.Runspace; powerShell.Commands.AddScript(RemovePSEditFunctionScript); powerShell.Invoke(); } } } catch (Exception e) when (e is RemoteException || e is PSInvalidOperationException) { this.logger.LogException("Could not remove psedit function.", e); } } } private void TryDeleteTemporaryPath() { try { if (Directory.Exists(this.processTempPath)) { Directory.Delete(this.processTempPath, true); } Directory.CreateDirectory(this.processTempPath); } catch (IOException e) { this.logger.LogException( $"Could not delete temporary folder for current process: {this.processTempPath}", e); } } #endregion #region Nested Classes private class RemotePathMappings { private RunspaceDetails runspaceDetails; private RemoteFileManagerService remoteFileManager; private HashSet<string> openedPaths = new HashSet<string>(); private Dictionary<string, string> pathMappings = new Dictionary<string, string>(); public IEnumerable<string> OpenedPaths { get { return openedPaths; } } public RemotePathMappings( RunspaceDetails runspaceDetails, RemoteFileManagerService remoteFileManager) { this.runspaceDetails = runspaceDetails; this.remoteFileManager = remoteFileManager; } public void AddPathMapping(string remotePath, string localPath) { // Add mappings in both directions this.pathMappings[localPath.ToLower()] = remotePath; this.pathMappings[remotePath.ToLower()] = localPath; } public void AddOpenedLocalPath(string openedLocalPath) { this.openedPaths.Add(openedLocalPath); } public bool IsRemotePathOpened(string remotePath) { return this.openedPaths.Contains(remotePath); } public string GetMappedPath(string filePath) { string mappedPath = filePath; if (!this.pathMappings.TryGetValue(filePath.ToLower(), out mappedPath)) { // If the path isn't mapped yet, generate it if (!filePath.StartsWith(this.remoteFileManager.remoteFilesPath)) { mappedPath = this.MapRemotePathToLocal( filePath, runspaceDetails.SessionDetails.ComputerName); this.AddPathMapping(filePath, mappedPath); } } return mappedPath; } private string MapRemotePathToLocal(string remotePath, string connectionString) { // The path generated by this code will look something like // %TEMP%\PSES-[PID]\RemoteFiles\1205823508\computer-name\MyFile.ps1 // The "path hash" is just the hashed representation of the remote // file's full path (sans directory) to try and ensure some amount of // uniqueness across different files on the remote machine. We put // the "connection string" after the path slug so that it can be used // as the differentiator string in editors like VS Code when more than // one tab has the same filename. var sessionDir = Directory.CreateDirectory(this.remoteFileManager.remoteFilesPath); var pathHashDir = sessionDir.CreateSubdirectory( Path.GetDirectoryName(remotePath).GetHashCode().ToString()); var remoteFileDir = pathHashDir.CreateSubdirectory(connectionString); return Path.Combine( remoteFileDir.FullName, Path.GetFileName(remotePath)); } } #endregion } }
using FreightRateCalculator.Calculators.Interfaces; using FreightRateCalculator.Models; namespace FreightRateCalculator.Calculators { public class SeaFreight : IFreightCalculatorStrategy { public decimal Calculate(FreightData freightData) { return freightData.MaximumPayload * 0.07M; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ALM.Reclutamiento.Entidades { public class EMapeoColumna { public int IdMapeoColumnaSegmento { get; set; } public int IdSegmento { get; set; } public int IdEmpresa { get; set; } public int IdColumnaDefaultSegmento { get; set; } public int? IdColumnaSegmento { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Protocol; using UnityEngine; using WebSocketSharp; public class Network : MonoBehaviour { #region sigleton & lifecycle private static Network s_Instance = null; public static Network Instance { get { if (s_Instance == null) { GameObject go = new GameObject("_Network"); s_Instance = go.AddComponent<Network>(); DontDestroyOnLoad(go); } return s_Instance; } } #endregion private WebSocket ws; public bool IsConnect { get; private set; } private bool mRunningQueue = false; private bool isQuitting = false; Queue<string> responseQueue = new Queue<string>(); // Use this for initialization void Start() { mRunningQueue = true; } // Update is called once per frame void Update() { if (mRunningQueue && IsConnect) { StartCoroutine(ResponseQueueWorker()); } } IEnumerator ResponseQueueWorker() { while (!isQuitting) { if (responseQueue.Count > 0) { string respStr = responseQueue.Peek(); var resp = JsonConvert.DeserializeObject<Protocol.BaseResp>(respStr); switch ((Protocol.Response) resp.ResponseType) { case Response.CreateRoom: var createRoomResp = JsonConvert.DeserializeObject<Protocol.CreateRoomResp>(respStr); GameManager.Instance.CreateRoomRes(createRoomResp); break; case Protocol.Response.JoinRoom: var joinRoomResp = JsonConvert.DeserializeObject<Protocol.JoinRoomResp>(respStr); GameManager.Instance.JoinRoomRes(joinRoomResp); break; case Protocol.Response.RoomInit: var roomInitResp = JsonConvert.DeserializeObject<Protocol.RoomInitResp>(respStr); GameManager.Instance.RoomInitRes(roomInitResp); break; case Protocol.Response.CallLargeTichu: var callLargeTichuResp = JsonConvert.DeserializeObject<Protocol.CallLargeTichuResp>(respStr); GameManager.Instance.CallLargeTichuRes(callLargeTichuResp); break; case Protocol.Response.DistributeAllCard: var distirbuteAllCardResp = JsonConvert.DeserializeObject<Protocol.DistributeAllCardResp>(respStr); GameManager.Instance.DistributeAllCardRes(distirbuteAllCardResp); break; case Protocol.Response.StartGame: var startGameResp = JsonConvert.DeserializeObject<Protocol.StartGameResp>(respStr); GameManager.Instance.StartGameRes(startGameResp); break; case Protocol.Response.CallTichu: var callTichuResp = JsonConvert.DeserializeObject<Protocol.CallTichuResp>(respStr); GameManager.Instance.CallTichuRes(callTichuResp); break; default: break; } } if (responseQueue.Count > 0) { responseQueue.Dequeue(); } yield return null; } } public void Connect() { ws = new WebSocket(NetworkSettings.Instance.GetServerURL()); ws.OnOpen += NetworkOpen; ws.OnMessage += NetworkOnMessage; ws.OnError += NetworkOnError; ws.OnClose += NetworkOnClose; ws.Connect(); IsConnect = true; } public void SendMessage(object value) { ws.Send(JsonConvert.SerializeObject(value)); } private void NetworkOpen(object sender, EventArgs e) { } private void NetworkOnMessage(object sender, MessageEventArgs e) { Debug.Log(e.Data); responseQueue.Enqueue(e.Data); } private void NetworkOnError(object sender, ErrorEventArgs e) { //TODO error Debug.LogError(e.Message); } private void NetworkOnClose(object sender, CloseEventArgs e) { //TODO error Debug.LogError(e.Reason); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using RestaurantApp.Core; using RestaurantApp.Core.Interfaces; using AutoFixture; using System.Collections.Generic; using System.Linq; using RestaurantApp.Web; using System.Web.Mvc; namespace RestaurantApp.Web.Test { [TestClass] public class FoodsControllerTest { [TestMethod] public void Index_ReturnsAViewResult_WithAListOfFoodsNoPaging() { var fixture = new Fixture(); var testObject = new List<Food> { fixture.Build<Food>().With(f=>f.Type,1).Create(), fixture.Build<Food>().With(f=>f.Type,1).Create(), fixture.Build<Food>().With(f=>f.Type,2).Create(), fixture.Build<Food>().With(f=>f.Type,2).Create(), fixture.Build<Food>().With(f=>f.Type,2).Create(), fixture.Build<Food>().With(f=>f.Type,1).Create(), fixture.Build<Food>().With(f=>f.Type,1).Create() }; var repMock = new Mock<IFoodRepository>(); int pageSize = 5; int page = 0; int type = 0; repMock.Setup(m => m.GetFoods(type,page,pageSize)).Returns(testObject.AsQueryable()); var controller = new Controllers.FoodsController(repMock.Object); var result = controller.Index(type, page) as ViewResult; var model = result.Model as List<Food>; Assert.IsNotNull(result); Assert.AreEqual(5, model.Count()); } } }
using RO.Config; using System; using UnityEngine; namespace RO { public class TerrainProjector : MonoBehaviour { private Vector3 prevPosition = Vector3.get_zero(); private void Update() { Ray ray = new Ray(base.get_transform().get_position() + Vector3.get_up(), Vector3.get_down()); int mask = LayerMask.GetMask(new string[] { Layer.TERRAIN.get_Key() }); RaycastHit raycastHit; if (Physics.Raycast(ray, ref raycastHit, float.PositiveInfinity, mask)) { base.get_transform().LookAt(raycastHit.get_point() - raycastHit.get_normal()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ParticleSystem { public class AdvancedParticleOperator : ParticleUpdater { private List<Particle> currentTickParticles = new List<Particle>(); private List<ParticleAttractor> currentTickAttractors = new List<ParticleAttractor>(); private List<ParticleRepulsor> currentTickRepulsors = new List<ParticleRepulsor>(); public override IEnumerable<Particle> OperateOn(Particle p) { if (p is ParticleAttractor) { currentTickAttractors.Add(p as ParticleAttractor); } else if (p is ParticleRepulsor) { currentTickRepulsors.Add(p as ParticleRepulsor); } else { this.currentTickParticles.Add(p); } return base.OperateOn(p); } public override void TickEnded() { foreach (var attractor in this.currentTickAttractors) { foreach (var particle in this.currentTickParticles) { var currParticleToAttractorVector = attractor.Position - particle.Position; int pToAttrRow = currParticleToAttractorVector.Row; pToAttrRow = DecreaseVectorCoordToPower(attractor, pToAttrRow); int pToAttrCol = currParticleToAttractorVector.Col; pToAttrCol = DecreaseVectorCoordToPower(attractor, pToAttrCol); var currAcceleration = new MatrixCoords(pToAttrRow, pToAttrCol); particle.Accelerate(currAcceleration); } } foreach (var repulsor in this.currentTickRepulsors) { foreach (var particle in this.currentTickParticles) { if (GetDistanceBetweenPoints(repulsor, particle) <= repulsor.Range) { // Gets the vector between the particle position and the repulsors position // and accelerates the particle in that direction var currParticleToRepulsorVector = particle.Position - repulsor.Position; particle.Accelerate(currParticleToRepulsorVector); } } } this.currentTickParticles.Clear(); this.currentTickAttractors.Clear(); this.currentTickRepulsors.Clear(); base.TickEnded(); } private static int DecreaseVectorCoordToPower(ParticleAttractor attractor, int pToAttrCoord) { if (Math.Abs(pToAttrCoord) > attractor.AttractionPower) { pToAttrCoord = (pToAttrCoord / (int)Math.Abs(pToAttrCoord)) * attractor.AttractionPower; } return pToAttrCoord; } // Calculates Euclidean Distance between two points. private static int GetDistanceBetweenPoints(Particle firstParticle, Particle secondParticle) { return (int)Math.Sqrt(Math.Pow(firstParticle.Position.Row - secondParticle.Position.Row, 2) + Math.Pow(firstParticle.Position.Col - secondParticle.Position.Col, 2)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering.LWRP; public class AIHealth : CharacterHealth { private AIStateManager stateManager; public Transform inactiveEntities; public AudioSource[] hurtSounds; [Space] public Light2D flashlight; public SpriteRenderer weapon; protected override void Awake() { base.Awake(); stateManager = GetComponentInParent<AIStateManager>(); } public override void TakeDamage(int amount) { base.TakeDamage(amount); int random = UnityEngine.Random.Range(0, hurtSounds.Length); hurtSounds[random].PlayOneShot(hurtSounds[random].clip); } protected override void CharacterDeath() { if (stateManager.GetState() != AIStateManager.State.Dead) StartCoroutine(Death()); } private IEnumerator Death() { if (flashlight != null) { flashlight.enabled = false; } if (weapon != null) { weapon.enabled = false; } stateManager.SetState(AIStateManager.State.Dead); anim.SetBool("Dead", true); yield return new WaitForSeconds(10f); transform.parent.SetParent(inactiveEntities); transform.parent.gameObject.SetActive(false); } }
using Ninject; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Webcorp.lib.onedcut; using Webcorp.OneDCut.Models; namespace Webcorp.OneDCut.Controllers { public class SettingsController : Controller { IKernel kernel; public SettingsController(IKernel kernel) { this.kernel = kernel; } [HttpPost] public ActionResult Index(SettingsModel settings) { //settings.OrignalParameters= var param = kernel.Get<ISolverParameter>(); param.CrossoverProbability = settings.CrossoverProbability; param.ElitePercentage = settings.ElitePercentage; param.InitialPopulationCount = settings.InitialPopulationCount; param.MaxEvaluation = settings.MaxEvaluation; param.MutationProbability = settings.MutationProbability; param.CuttingWidth = settings.CuttingWidth; param.MiniLength = settings.MiniLength; // param.Save(); //return RedirectToAction("index","home"); return View("index",settings); } // GET: Settings public ActionResult Index() { var settings = kernel.Get<SettingsModel>(); return View(settings); } } }