text stringlengths 13 6.01M |
|---|
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ArduinoMonitor
{
public partial class Form1 : Form
{
private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
private SerialPort port;
private int baudRate;
private String serialPortName;
private String usedCpu;
private String usedRam;
public Form1()
{
InitializeComponent();
InitializeCpuCounter();
InitializeRamCounter();
String[] portsList = SerialPort.GetPortNames();
serialList.DataSource = portsList;
}
private void InitializeCpuCounter()
{
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
}
private void InitializeRamCounter()
{
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
// When Connect button is pressed...
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
serialPortName = serialList.SelectedItem.ToString();
baudRate = Convert.ToInt32(textBaud.Text);
port = new SerialPort(serialPortName);
port.BaudRate = baudRate;
port.Open();
if (port.IsOpen)
{
timer1.Enabled = true;
buttonConnect.Enabled = false;
buttonDisconnect.Enabled = true;
}
} catch(NullReferenceException exc)
{
MessageBox.Show("Select a Serial Port!", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
} catch(System.FormatException exc)
{
MessageBox.Show("Set a Baud Rate!", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
}
// When Disconnect button is pressed...
private void buttonDisconnect_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
// Close the serial port
port.Close();
buttonConnect.Enabled = true;
buttonDisconnect.Enabled = false;
}
// Update Cpu and Ram usage
private void timer1_Tick(object sender, EventArgs e)
{
//getComponent("Win32_Processor", "CurrentClockSpeed");
// Send Cpu usage over the serial line
//usedCpu = ((int)cpuCounter.NextValue()).ToString();
//port.WriteLine(usedCpu);
// Send Ram usage over the serial line
usedRam = ((int)ramCounter.NextValue()).ToString();
port.WriteLine(usedRam);
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
String[] portsList = SerialPort.GetPortNames();
serialList.DataSource = portsList;
}
static private void getComponent(String hwclass, String syntax)
{
ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
foreach (ManagementObject mj in mos.Get())
{
Console.WriteLine(Convert.ToString(mj[syntax]));
}
}
}
}
|
๏ปฟusing System.Collections;
using Facebook.Unity;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine;
public class FacebookManger : MonoBehaviour {
public Text userIDText;
private void Awake()
{
if (!FB.IsInitialized)
{
}
else
{
FB.ActivateApp();
}
}
public void LogIn()
{
FB.LogInWithReadPermissions();
}
private void OnLogin(ILoginResult result)
{
if (FB.IsLoggedIn)
{
AccessToken token = AccessToken.CurrentAccessToken;
userIDText.text = token.UserId;
}
}
public void Share()
{
/* Will pop up share */
FB.ShareLink(callback:OnShare
);
}
private void OnShare(IShareResult result)
{
if (result.Cancelled || !string.IsNullOrEmpty(result.Error))
{
Debug.Log("ShareLink error: " + result.Error);
}
else if (!string.IsNullOrEmpty(result.PostId))
{
Debug.Log(result.PostId);
}
else
Debug.Log("Share succeeded");
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NAME_UNWN.Path
{
class NormalPath
{
public Point begin;
public Point end;
public NormalPath(Point A, Point B)
{
this.begin = A;
this.end = B;
}
}
}
|
๏ปฟ// Copyright 2016, 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace NtApiDotNet.Win32
{
/// <summary>
/// Class representing a service instance.
/// </summary>
public sealed class Win32Service
{
private ServiceInformation GetServiceInformation()
{
return ServiceUtils.GetServiceInformation(MachineName, Name,
false).GetResultOrDefault(new ServiceInformation(MachineName, Name));
}
private readonly Lazy<ServiceInformation> _service_information;
/// <summary>
/// The name of the service.
/// </summary>
public string Name { get; }
/// <summary>
/// The description of the service.
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Type of service.
/// </summary>
public ServiceType ServiceType { get; }
/// <summary>
/// Image path for the service.
/// </summary>
public string ImagePath => _service_information.Value.ImagePath;
/// <summary>
/// Command line for the service.
/// </summary>
public string CommandLine => _service_information.Value.BinaryPathName;
/// <summary>
/// Service DLL if a shared process server.
/// </summary>
public string ServiceDll => _service_information.Value.ServiceDll;
/// <summary>
/// Current service status.
/// </summary>
public ServiceStatus Status { get; }
/// <summary>
/// What controls are accepted by the service.
/// </summary>
public ServiceControlsAccepted ControlsAccepted { get; }
/// <summary>
/// Whether the service can be stopped.
/// </summary>
public bool CanStop => ControlsAccepted.HasFlagSet(ServiceControlsAccepted.Stop);
/// <summary>
/// The Win32 exit code.
/// </summary>
public Win32Error Win32ExitCode { get; }
/// <summary>
/// The service specific exit code, if Win32ExitCode is Win32Error.ERROR_SERVICE_SPECIFIC_ERROR.
/// </summary>
public int ServiceSpecificExitCode { get; }
/// <summary>
/// The checkpoint while starting.
/// </summary>
public int CheckPoint { get; }
/// <summary>
/// Waiting hint time.
/// </summary>
public int WaitHint { get; }
/// <summary>
/// Service flags.
/// </summary>
public ServiceFlags ServiceFlags { get; }
/// <summary>
/// Process ID of the running service.
/// </summary>
public int ProcessId { get; }
/// <summary>
/// The security descriptor of the service.
/// </summary>
public SecurityDescriptor SecurityDescriptor => _service_information.Value.SecurityDescriptor;
/// <summary>
/// The list of triggers for the service.
/// </summary>
public IEnumerable<ServiceTriggerInformation> Triggers => _service_information.Value.Triggers;
/// <summary>
/// The service SID type.
/// </summary>
public ServiceSidType SidType => _service_information.Value.SidType;
/// <summary>
/// The service launch protected setting.
/// </summary>
public ServiceLaunchProtectedType LaunchProtected => _service_information.Value.LaunchProtected;
/// <summary>
/// The service required privileges.
/// </summary>
public IEnumerable<string> RequiredPrivileges => _service_information.Value.RequiredPrivileges;
/// <summary>
/// Service start type.
/// </summary>
public ServiceStartType StartType => _service_information.Value.StartType;
/// <summary>
/// Whether the service is a delayed auto start service.
/// </summary>
public bool DelayedAutoStart => _service_information.Value.DelayedAutoStart;
/// <summary>
/// Error control.
/// </summary>
public ServiceErrorControl ErrorControl => _service_information.Value.ErrorControl;
/// <summary>
/// Load order group.
/// </summary>
public string LoadOrderGroup => _service_information.Value.LoadOrderGroup;
/// <summary>
/// Tag ID for load order.
/// </summary>
public int TagId => _service_information.Value.TagId;
/// <summary>
/// Dependencies.
/// </summary>
public IEnumerable<string> Dependencies => _service_information.Value.Dependencies;
/// <summary>
/// The user name this service runs under.
/// </summary>
public string UserName => _service_information.Value.UserName;
/// <summary>
/// Type of service host when using Win32Share.
/// </summary>
public string ServiceHostType => _service_information.Value.ServiceHostType;
/// <summary>
/// Service main function when using Win32Share.
/// </summary>
public string ServiceMain => _service_information.Value.ServiceMain;
/// <summary>
/// Indicates if this service process is grouped with others.
/// </summary>
public bool SvcHostSplitDisabled => _service_information.Value.SvcHostSplitDisabled;
/// <summary>
/// The name of the machine this service was found on.
/// </summary>
public string MachineName { get; }
/// <summary>
/// Overridden ToString method.
/// </summary>
/// <returns>The name of the service.</returns>
public override string ToString()
{
return Name;
}
private static string GetString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
{
return string.Empty;
}
return Marshal.PtrToStringUni(ptr);
}
internal Win32Service(string name, string display_name, string machine_name, SERVICE_STATUS_PROCESS status)
{
Name = name;
DisplayName = display_name;
ServiceType = status.dwServiceType;
Status = status.dwCurrentState;
ProcessId = status.dwProcessId;
ControlsAccepted = status.dwControlsAccepted;
Win32ExitCode = status.dwWin32ExitCode;
ServiceSpecificExitCode = status.dwServiceSpecificExitCode;
CheckPoint = status.dwCheckPoint;
WaitHint = status.dwWaitHint;
ServiceFlags = status.dwServiceFlags;
MachineName = machine_name ?? string.Empty;
_service_information = new Lazy<ServiceInformation>(GetServiceInformation);
}
internal Win32Service(string machine_name, ENUM_SERVICE_STATUS_PROCESS process)
: this(GetString(process.lpServiceName), GetString(process.lpDisplayName),
machine_name, process.ServiceStatusProcess)
{
}
}
#pragma warning restore
}
|
using System;
using System.Text;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Exceptions;
using LePapeoGenNHibernate.Exceptions;
using LePapeoGenNHibernate.EN.LePapeo;
using LePapeoGenNHibernate.CAD.LePapeo;
/*PROTECTED REGION ID(usingLePapeoGenNHibernate.CEN.LePapeo_Usuario_login) ENABLED START*/
// references to other libraries
/*PROTECTED REGION END*/
namespace LePapeoGenNHibernate.CEN.LePapeo
{
public partial class UsuarioCEN
{
public string Login (int p_Usuario_OID, string p_pass)
{
/*PROTECTED REGION ID(LePapeoGenNHibernate.CEN.LePapeo_Usuario_login) ENABLED START*/
string result = null;
UsuarioEN en = _IUsuarioCAD.ReadOIDDefault (p_Usuario_OID);
if (en.Pass.Equals (Utils.Util.GetEncondeMD5 (p_pass)))
result = en.GetType ().Name;
//FALTA CREAR SESION
return result;
/*PROTECTED REGION END*/
}
}
}
|
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace xy3d.tstd.lib.textureFactory{
public class TextureFactory{
private static TextureFactory _Instance;
public static TextureFactory Instance {
get {
if (_Instance == null) {
_Instance = new TextureFactory ();
}
return _Instance;
}
}
// public delegate void getTextureCallBack<T>(T _texture);
public Dictionary<string,TextureFactoryUnitBase> dic ;
public TextureFactory(){
dic = new Dictionary<string, TextureFactoryUnitBase>();
}
public T GetTexture<T> (string _name,Action<T> _callBack,bool _addUseNum) where T:UnityEngine.Object {
TextureFactoryUnit<T> unit;
if (!dic.ContainsKey (_name)) {
unit = new TextureFactoryUnit<T> (_name);
dic.Add (_name, unit);
} else {
unit = dic [_name] as TextureFactoryUnit<T>;
}
return unit.GetTexture(_callBack,_addUseNum);
}
public void Dispose(bool _force){
List<string> delKeyList = new List<string> ();
foreach (KeyValuePair<string,TextureFactoryUnitBase> pair in dic) {
if (_force || pair.Value.useNum == 0) {
pair.Value.Dispose ();
delKeyList.Add (pair.Key);
}
}
foreach (string key in delKeyList) {
dic.Remove (key);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class AssetBundleReference : MonoBehaviour
{
public string assetBundleName;
private void OnDestroy()
{
if (!string.IsNullOrEmpty(assetBundleName))
{
if (!AssetBundleManager.UnloadAssetBundle(assetBundleName, true, this.gameObject.name))
{
//Debug.LogWarningFormat("UnloadAssetBundle: {0} delete error.", assetBundleName);
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TankBot
{
class Aim
{
TankBot tb;
int bestAim;
public Aim()
{
tb = TankBot.getInstance();
bestAim = -1;
}
/// <summary>
/// move the tank turret when there's no enemy in sight.
/// </summary>
private void noAimMoveTankTurret()
{
if (TBConst.notMoveTank)
return;
double degree_diff = tb.myTank.direction - tb.myTank.cameraDirection;
int x_move = Convert.ToInt32(degree_diff / tb.mouseHorizonRatio[SniperMode.sniper_level]);
// remove this line,
//while (Math.Abs(x_move) > 4000) x_move /= 2;
//Console.WriteLine("aiming " + et.username);
//Console.WriteLine("move cursor " + x_move + " " + y_move);
Helper.MoveCursor(x_move, 0);
Thread.Sleep(100);
}
/// <summary>
/// trying to aim the tank et
/// return true if we get to that position
/// </summary>
/// <param name="et"></param>
/// <param name="arg_x"></param>
/// <param name="arg_y"></param>
/// <param name="farAway"></param>
/// <returns></returns>
internal void aimToTankArgxArgy(Vehicle et, double arg_x, double arg_y)
{
if (et.visible_on_screen == false)
{
throw new NotVisibleOnScreenException();
}
if (!et.posScreenUpdated) return;
if (!tb.myTank.directionUpdated) return;
if (!tb.myTank.cameraDirectionUpdated) return;
// force everything to update to correct
double cameraDirectionBeforeMouseMove = tb.myTank.cameraDirection;
Point beforeMouseMove = et.posScreen;
Helper.LogDebug("aimToTank arg_x:" + arg_x + " arg_y:" + arg_y + " direction:" + tb.myTank.direction + " cameraDirection:" + tb.myTank.cameraDirection);
double degree_diff = 0;
int x_move = 0, y_move = 0;
degree_diff = TBMath.cameraDegreeToEnemy(et, tb.myTank);
// if too far away, just move horizontal.
if (et.posScreen.x > TBConst.screen_width / 2 + 400 || et.posScreen.x < TBConst.screen_width / 2 - 400)
{
x_move = Convert.ToInt32(degree_diff / tb.mouseHorizonRatio[SniperMode.sniper_level]);
}
else // the tank is almost near in horizontal view
{
//---------------------------move horizontal
degree_diff = (et.posScreen.x - TBConst.screen_width / 2);
double dis = TBMath.distance(tb.myTank.pos, et.pos) * tb.mapSacle;
degree_diff = arg_x + tb.meterPerPixel[SniperMode.sniper_level] * degree_diff / 100 * dis; // meter from center to screen;
degree_diff = degree_diff / (2 * Math.PI * dis) * 360;
x_move = Convert.ToInt32(degree_diff / tb.mouseHorizonRatio[SniperMode.sniper_level]);
//----------------------------------move vertical
double pixel_diff = 0;
if (SniperMode.sniper_level >= 6)
pixel_diff = (et.posScreen.y - TBConst.screen_height / 2); // positive then move down pixel diff on screen
else
pixel_diff = (et.posScreen.y - TBConst.screen_height / 2 + 58); // fuck this 58 mm
dis = TBMath.distance(tb.myTank.pos, et.pos) * tb.mapSacle;
double meter_diff = arg_y + tb.meterPerPixel[SniperMode.sniper_level] * pixel_diff / 100 * dis; // meter from center to screen; arg_y meter's away
degree_diff = meter_diff / (2 * Math.PI * dis) * 360;
//Logger("mouse move" + degree_diff / mouse_horizon_ratio);
y_move = Convert.ToInt32(degree_diff / tb.mouseHorizonRatio[SniperMode.sniper_level]);
//if(Const.LoggerMode)
//Trace.WriteLine("dis: " + dis + " pixel_diff: " + pixel_diff + " meter_diff: " + meter_diff + " degree_diff: " + degree_diff + " y_move: " + y_move);
}
while (Math.Abs(x_move) > 8000)
{
x_move /= 2;
}
while (Math.Abs(y_move) > 8000)
{
y_move /= 2;
}
//Console.WriteLine("aiming " + et.username);
//Console.WriteLine("move cursor " + x_move + " " + y_move);
Helper.MoveCursor(x_move, y_move);
if(y_move==0)
Thread.Sleep(50);
else
Thread.Sleep(30);
/*
et.posScreenUpdated = false;
myTank.directionUpdated = false;
myTank.cameraDirectionUpdated = false;
if (Math.Abs(x_move) + Math.Abs(y_move) > 5)
{
while (beforeMouseMove.x == et.posScreen.x && beforeMouseMove.y == et.posScreen.y && et.visible_on_screen)
;
}
* */
Helper.LogDebug("aimToTankFinish " + arg_x + " " + arg_y + " " + tb.myTank.direction + " " + tb.myTank.cameraDirection);
return;
}
double select_x = Double.NaN, select_y = double.NaN;
internal void tryingUpDownRange(Vehicle v)
{
List<Tuple<double, double>> success = new List<Tuple<double, double>>();
double argx = 0;
for (double argy = 0.5; argy <= 5; argy += 0.4)
{
aimToTankArgxArgy(v, argx, argy);
waitFocusTargetUpdate();
if (tb.focusTarget)
success.Add(new Tuple<double, double>(argx, argy));
}
select_x = select_y = 0;
foreach (Tuple<double, double> t in success)
{
select_x += t.Item1;
select_y += t.Item2;
}
if (success.Count == 0)
{
select_x = 0;
select_y = 2.0;
}
else
{
select_x /= success.Count;
select_y /= success.Count;
}
}
internal bool findBestAim(int uid)
{
Helper.LogDebug("tryAimTank" + uid);
if (tb.enemyTank[uid].username == TBConst.cheatMasterUserName)
{
Helper.LogDebug("dont aim cheat master");
return false;
}
tb.focusTargetHappen = false;
DateTime start = DateTime.Now;
while ((DateTime.Now - start).Seconds < 3)
{
Random r = new Random();
aimToTankArgxArgy(tb.enemyTank[uid], r.NextDouble() * 4 - 2, r.NextDouble() * 4);
if (tb.focusTargetHappen)
{
Helper.LogDebug("findBestAim " + uid + " return true");
return true;
}
}
Helper.LogDebug("findBestAim " + uid + " return false");
return false;
}
private string findBestAimDebugString;
internal int findBestAim()
{
List<Tuple<double, int>> dist = new List<Tuple<double, int>>();
for (int i = 0; i < 15; i++)
{
if (tb.enemyTank[i].visible_on_screen)
{
dist.Add(new Tuple<double, int>(TBMath.distance(tb.myTank.pos, tb.enemyTank[i].pos), i));
}
}
dist.Sort();
Helper.LogDebug("Try find best aim");
findBestAimDebugString = "";
for (int i = 0; i < dist.Count; i++)
{
int tid = dist[i].Item2;
findBestAimDebugString += "id: " + dist[i].Item2 + " dist: " + dist[i].Item1 + " " + tb.enemyTank[tid].tankName;
double mindis = dist[0].Item1;
// only try the one near the minimal distance one.
if (dist[i].Item1 > mindis + 1)
break;
Helper.LogDebug("choose_tank " + tid);
SniperMode.setSniperMode(6);
if (findBestAim(tid))
{
return tid;
}
}
return -1;
}
private void aimSpecificTank(Vehicle v)
{
Helper.LogInfo("aimSpecificTank");
DateTime start = DateTime.Now;
double dis = TBMath.distance(tb.myTank.pos, v.pos) * tb.mapSacle;
if (dis > 100) SniperMode.setSniperMode(8); // x8 sniper
else if (dis > 50) SniperMode.setSniperMode(7); // x4 sniper
else SniperMode.setSniperMode(6); // x2 sniper
this.tryingUpDownRange(v);
while (true)
{
tb.focusTargetHappen = false;
aimToTankArgxArgy(v, select_x, select_y);
waitFocusTargetUpdate();
if (tb.focusTargetHappen == false)
{
Helper.LogInfo("throw CannotAimException");
throw new CannotAimException();
}
Helper.LogDebug("aiming at tank " + v.tankName + " " + v.username);
}
}
private void waitFocusTargetUpdate()
{
//Helper.LogInfo("wait focus update in");
for (int i = 0; i < 5; i++)
{
tb.focusTargetUpdated = false;
while (!tb.focusTargetUpdated)
{
Thread.Sleep(1);
//Helper.LogInfo("focus updated @i " + i + " " + focusTargetUpdated);
}
}
//Helper.LogInfo("wait focus update out");
}
private bool noEnemyOnScreen()
{
for (int i = 0; i < 15; i++)
{
if (tb.enemyTank[i].visible_on_screen == true)
return false;
}
Helper.LogDebug("no enemy on screen");
return true;
}
public string debugString()
{
return "\r\n " + findBestAimDebugString;
}
internal void aim()
{
if (tb.status != Status.PLAYING)
throw new StatusChangeException();
try
{
// we are going to aim something
if (tb.focusTargetHappen)
{
tb.focusTargetHappen = false;
if (bestAim >= 0)
aimSpecificTank(tb.enemyTank[bestAim]);
}
else
{
bestAim = findBestAim();
if (noEnemyOnScreen())
{
SniperMode.setSniperMode(5);
noAimMoveTankTurret();
}
}
}
catch (NotVisibleOnScreenException)
{
Helper.LogDebug("NotVisibleOnScreenException catch");
bestAim = -1;
}
catch (CannotAimException)
{
Helper.LogDebug("CannotAimException catch");
bestAim = -1;
}
}
}
}
|
๏ปฟusing Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace Dashboard.API.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: false),
Website = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ClientServices",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ClientId = table.Column<Guid>(nullable: false),
DefaultValue = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
Key = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ClientServices", x => x.Id);
table.ForeignKey(
name: "FK_ClientServices_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserSubscriptions",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ClientServiceId = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserSubscriptions", x => x.Id);
table.ForeignKey(
name: "FK_UserSubscriptions_ClientServices_ClientServiceId",
column: x => x.ClientServiceId,
principalTable: "ClientServices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ClientServices_ClientId",
table: "ClientServices",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_UserSubscriptions_ClientServiceId",
table: "UserSubscriptions",
column: "ClientServiceId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserSubscriptions");
migrationBuilder.DropTable(
name: "ClientServices");
migrationBuilder.DropTable(
name: "Clients");
}
}
}
|
๏ปฟnamespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("TournamentScene")]
public class TournamentScene : PlayGameScene
{
public TournamentScene(IntPtr address) : this(address, "TournamentScene")
{
}
public TournamentScene(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public static TournamentScene Get()
{
return MonoClass.smethod_15<TournamentScene>(TritonHs.MainAssemblyPath, "", "TournamentScene", "Get", Array.Empty<object>());
}
public string GetScreenName()
{
return base.method_13("GetScreenName", Array.Empty<object>());
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void Unload()
{
base.method_8("Unload", Array.Empty<object>());
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
namespace ConfigData
{
public class MainConfig
{
/// <summary>
/// ๆฏๅฆไธบๅผๅ็
/// </summary>
public const bool IsDev = true;
/// <summary>
/// ้กน็ฎ็ธๅ
ณๅๆฐ
/// </summary>
public const string
ProjDevName = "CollectWuFu_Dev",
ProjLineName = "CollectWuFu",
BaseDir = "/home/project_data/" + (IsDev ? ProjDevName : ProjLineName) + "/",
AvatarDir = "avatar/",
AlbumDir= "album/",
GoodsImagesDir = "goods/",
LogoImagesDir = "logo/",
TempDir = "temp/",
CertsDir = "certs/";
/// <summary>
/// ๆฐๆฎๅบๅๆฐ
/// </summary>
public const string
MongoDBLineConn = "mongodb://47.94.208.29:27027",
MongoDBLocalConn = "mongodb://localhost:27027",
MongoDBName = IsDev ? ProjDevName : ProjLineName;
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
namespace OdmNet.Domains
{
public partial class Customers
{
public Customers()
{
Orders = new HashSet<Orders>();
}
public int Id { get; set; }
public string IpAddress { get; set; }
public string FullName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public DateTime? VisistedDate { get; set; }
public string Url { get; set; }
public string ProductViewedIds { get; set; }
public DateTime? LastVisistedDate { get; set; }
public ICollection<Orders> Orders { get; set; }
}
}
|
๏ปฟ// Copyright (c) Daniel Crenna & Contributors. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using ActiveApi.Configuration;
using ActiveRoutes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace ActiveApi
{
public static partial class Use
{
public static void UseCanonicalRoutes(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
if (context.FeatureEnabled<CanonicalRoutesOptions>(out var options))
{
await ExecuteFeature(context, options, next);
}
else
{
await next();
}
});
static async Task ExecuteFeature(HttpContext c, CanonicalRoutesOptions o, Func<Task> next)
{
if (string.Equals(c.Request.Method, HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
{
if (!CanonicalRoutesResourceFilter.TryGetCanonicalRoute(c.Request, o, out var redirectToUrl))
{
c.Response.Redirect(redirectToUrl, true);
return;
}
}
await next();
}
}
}
} |
๏ปฟusing System;
using BridgePattern.Models;
namespace BridgePattern
{
class Program
{
static void Main(string[] args)
{
var sorter = new Sorter
{
SortImple = new QuickSortImple()
};
var timeSorter = new TimeSorter
{
SortImple = new BubbleSortImple()
}
}
}
}
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour {
public float offsetZ;
[SerializeField] private GameObject cannon;
private void Start ()
{
offsetZ = cannon.transform.localScale.z * 15;
LookAtCannon();
}
private void LookAtCannon()
{
Vector3 temp = transform.position;
temp.z = cannon.transform.position.x - offsetZ;
transform.position = temp;
}
}
|
๏ปฟusing Microsoft.AspNetCore.Mvc;
using System;
using RestauranteHotel.Aplication;
using RestauranteHotel.Domain.Contracts;
namespace RestauranteHotel.Infrastructure.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductoCompuestoController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
private readonly IProductoCompuestoRepository _productoCompuestoRepository;
public ProductoCompuestoController(IUnitOfWork unitOfWork, IProductoCompuestoRepository productoCompuestoRepository)
{
_unitOfWork = unitOfWork;
_productoCompuestoRepository = productoCompuestoRepository;
/*if (!productoSimpleRepository.GetAll().Any())
{
var cuenta = new CuentaAhorro("10001", "Cuenta ejemplo", "VALLEDUPAR", "cliente@bancoacme.com");
cuentaBancariaRepository.Add(cuenta);
unitOfWork.Commit();
}*/
}
[HttpPost("salida-compuesto-simple")]
public SalidaProductoCompuestoResponse PostSalida(SalidaProductoCompuestoRequest request)
{
var service = new SalidaProductoCompuestoService(_unitOfWork, _productoCompuestoRepository);
var response = service.Salida(request);
return response;
}
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace Tivo.Has.Configuration
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
[ServiceContract]
public interface IHasConfigurationService
{
[OperationContract]
void PrepareApplication(string applicationName);
[OperationContract]
void RemoveApplication(string applicationName);
[OperationContract]
void DisableApplication(string applicationName);
// Prepare Application // prepare for upload
// Remove Appliction
// Disable Application
//[OperationContract]
//string[] GetApplicationDirectories();
//[OperationContract]
//void AddApplicationDirectory(string directory);
//[OperationContract]
//void RemoveApplicationDirectory(string directory);
//[OperationContract]
//void StopAllApplications();
//[OperationContract]
//void StopApplication(string applicationName);
//[OperationContract]
//void StopApplications(string[] applicationNames);
//[OperationContract]
//void StartApplication(string applicationName);
//[OperationContract]
//void StartApplications(string[] applicationNames);
//[OperationContract]
//string[] GetApplicationNames(string directory);
}
}
|
๏ปฟusing BookShelf.Data;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace BookShelf.Infrastructure.Repositories
{
public interface IRepository<TEntity>
{
IEnumerable<TEntity> Get();
TEntity Get(params object[] keyValues);
void Add(TEntity entity);
void Delete(TEntity entity);
void SaveChanges();
}
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _context;
private readonly DbSet<TEntity> _set;
public GenericRepository(ApplicationDbContext context)
{
_context = context;
_set = _context.Set<TEntity>();
}
public IEnumerable<TEntity> Get()
{
return _set;
}
public TEntity Get(params object[] keyValues)
{
return _set.Find(keyValues);
}
public void Add(TEntity entity)
{
_context.Entry(entity).State = EntityState.Added;
}
public void Delete(TEntity entity)
{
_context.Entry(entity).State = EntityState.Deleted;
}
public void SaveChanges()
{
_context.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFP.Persistencia.Dao;
using SFP.Persistencia.Model;
using SFP.SIT.SERV.Model.SOL;
namespace SFP.SIT.SERV.Dao.SOL
{
public class SIT_SOL_DOCDao : BaseDao
{
public SIT_SOL_DOCDao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter)
{
}
public Object dmlAgregar(SIT_SOL_DOC oDatos)
{
String sSQL = " INSERT INTO SIT_SOL_DOC( docclave, solclave) VALUES ( :P0, :P1) ";
return EjecutaDML ( sSQL, oDatos.docclave, oDatos.solclave );
}
public int dmlImportar( List<SIT_SOL_DOC> lstDatos)
{
int iTotReg = 0;
String sSQL = " INSERT INTO SIT_SOL_DOC( docclave, solclave) VALUES ( :P0, :P1) ";
foreach (SIT_SOL_DOC oDatos in lstDatos)
{
EjecutaDML ( sSQL, oDatos.docclave, oDatos.solclave );
iTotReg++;
}
return iTotReg;
}
public int dmlEditar(SIT_SOL_DOC oDatos)
{
// NO SE IMPLEMENTA PORQUE TODO ES LLAVE
throw new NotImplementedException();
}
public int dmlBorrar(SIT_SOL_DOC oDatos)
{
String sSQL = " DELETE FROM SIT_SOL_DOC WHERE docclave = :P0 AND solclave = :P1 ";
return (int) EjecutaDML ( sSQL, oDatos.docclave, oDatos.solclave );
}
public List<SIT_SOL_DOC> dmlSelectTabla( )
{
String sSQL = " SELECT * FROM SIT_SOL_DOC ";
return CrearListaMDL<SIT_SOL_DOC>(ConsultaDML(sSQL) as DataTable);
}
public List<ComboMdl> dmlSelectCombo( )
{
throw new NotImplementedException();
}
public Dictionary<int, string> dmlSelectDiccionario( )
{
throw new NotImplementedException();
}
public SIT_SOL_DOC dmlSelectID(SIT_SOL_DOC oDatos )
{
String sSQL = " SELECT * FROM SIT_SOL_DOC WHERE docclave = :P0 AND solclave = :P1 ";
return CrearListaMDL<SIT_SOL_DOC>(ConsultaDML ( sSQL, oDatos.docclave, oDatos.solclave ) as DataTable)[0];
}
public object dmlCRUD( Dictionary<string, object> dicParam )
{
int iOper = (int)dicParam[CMD_OPERACION];
if (iOper == OPE_INSERTAR)
return dmlAgregar(dicParam[CMD_ENTIDAD] as SIT_SOL_DOC );
else if (iOper == OPE_EDITAR)
return dmlEditar(dicParam[CMD_ENTIDAD] as SIT_SOL_DOC );
else if (iOper == OPE_BORRAR)
return dmlBorrar(dicParam[CMD_ENTIDAD] as SIT_SOL_DOC );
else
return 0;
}
/*INICIO*/
/*FIN*/
}
}
|
๏ปฟusing UnityEngine;
using System.Collections;
using TMPro;
// Text wave animates static text character positions
public class TextWave : UpdateBehavior
{
public TextMeshProUGUI m_textComponent;
public RectTransform m_rectTransform;
public float m_amplitude = 0.2f;
public float m_frequency = 10;
CanvasRenderer m_UIRenderer;
TMP_TextInfo m_textInfo;
Vector3[] m_meshVerts;
int loopCount = 0;
void Start()
{
m_UIRenderer = m_textComponent.canvasRenderer;
m_textInfo = m_textComponent.textInfo;
UpdateManager.Singleton.AddUpdateBehavior(this);
}
public override void UpdateScript()
{
m_textComponent.renderMode = TextRenderFlags.DontRender; // Instructing TextMesh Pro not to upload the mesh as we will be modifying it.
m_textComponent.ForceMeshUpdate(); // Generate the mesh and populate the textInfo with data we can use and manipulate.
Mesh mesh = m_textInfo.meshInfo[0].mesh;
int characterCount = m_textInfo.characterCount;
m_meshVerts = m_textInfo.meshInfo[0].vertices;
for (int i = 0; i < characterCount; i++)
{
if (!m_textInfo.characterInfo[i].isVisible)
continue;
float sinA = Mathf.Sin((loopCount + i) / m_frequency);
float diffY = (sinA * -m_amplitude) * m_amplitude;
int vertexIndex = m_textInfo.characterInfo[i].vertexIndex;
m_meshVerts[vertexIndex + 0].y += diffY;
m_meshVerts[vertexIndex + 1].y += diffY;
m_meshVerts[vertexIndex + 2].y += diffY;
m_meshVerts[vertexIndex + 3].y += diffY;
}
loopCount += 1;
m_textComponent.UpdateVertexData();
m_textComponent.renderMode = TextRenderFlags.Render;
}
}
|
๏ปฟusing phase1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace phase1.Viewmodel
{
public class ProductCarts
{
public List<product> products { get; set; }
public List<Cart> Carts { get; set; }
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeJam.Google.StoreCredit
{
public class StoreCardJamStrategy : ICodeJamStrategy
{
private static void Main(string[] args)
{
new Skeleton(new StoreCardJamStrategy(), "A-large-practice.in", "A-large-practice.out", 3).Execute().DisplayUnMatchedResult();
Console.ReadKey(true);
}
public string Solve(List<string> caseData)
{
var totalCredit = Int32.Parse(caseData[0]);
var itemCount = Int32.Parse(caseData[1]);
var itemCosts = caseData[2].Split(' ').Select(Int32.Parse).ToList();
//itemCosts.Sort();
for (int i = itemCount - 1; i >= 0; i--)
{
if (itemCosts[i] > totalCredit)
continue;
for (int j = i - 1; j >= 0; j--)
{
if (itemCosts[i] > totalCredit)
continue;
if (itemCosts[i] + itemCosts[j] == totalCredit)
{
return (j+1) + " " + (i+1);
}
}
}
return null;
}
}
}
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShortLivedObject : MonoBehaviour
{
[SerializeField]
float lifeTime = 5.0f;
Timer lifeTimer;
private void Awake()
{
lifeTimer = new Timer(lifeTime);
lifeTimer.OnComplete.AddListener(() =>
{
Destroy(gameObject);
});
lifeTimer.Start();
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PBingenering.Model
{
public class ProjectDoc
{
public string NameProject;
public string SurNameProject;
public User User;
public int PlanHourse;
public int PlanMinets;
public int SpendedHourse;
public int SpendedMinets;
public decimal PlanMoney;
public decimal SpendedMoney;
public Guid guid;
}
}
|
๏ปฟusing Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using System;
using Utils.Extensions;
using Utils.Helpers;
using Utils.Localization;
using Utils.Models;
namespace WebApplication.Dashboard.Quartz.Controllers
{
public class LocalizationController : QuartzBaseController
{
public virtual ActionResult ChangeCulture(string cultureName, string returnUrl = "")
{
if (!GlobalizationHelper.IsValidCultureCode(cultureName))
{
throw new Exception("Unknown language: " + cultureName + ". It must be a valid culture!");
}
string cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cultureName, cultureName));
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
cookieValue,
new CookieOptions
{
Expires = DateTime.UtcNow.AddYears(2),
HttpOnly = true
}
);
LocalizationIocManager.CultureName = cultureName;
if (Request.IsAjaxRequest())
{
return Json(new AjaxResponse());
}
if (!string.IsNullOrWhiteSpace(returnUrl) && UrlHelper.IsLocalUrl(Request, returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("/"); //TODO: Go to app root
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simon.Pattern.Proxy
{
public class ProxyDemo
{
public static void Run()
{
IReporter proxy = new ProxyReporter();
proxy.Add("I am Simon.");
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Rendering;
using Travel.Booking.Dto;
using Travel.Booking.Models;
namespace Travel.Booking.Services
{
public class BookingService
{
private readonly BookingRepository _repo;
public BookingService(BookingRepository repo)
{
_repo = repo;
}
public bool IsExist(string code)
{
return _repo.Get(x => x.Code == code).Any();
}
public void Add(string code, string name)
{
_repo.Add(new User
{
Code = code,
Name = name,
Id = Guid.NewGuid().ToString()
});
}
public User GetByCode(string code)
{
var user = _repo.Get(x => x.Code == code).First();
return user;
}
public User Get(string id)
{
return _repo.Get(id);
}
public void Update(UpdateDto dto)
{
var user = _repo.Get(dto.Id);
user.Act1 = dto.Act1;
user.Act2 = dto.Act2;
user.Act3 = dto.Act3;
user.ActOther = dto.ActOther;
user.Eat1 = dto.Eat1;
user.Eat2 = dto.Eat2;
user.Eat3 = dto.Eat3;
user.Eat4 = dto.Eat4;
user.Eat5 = dto.Eat5;
user.Eat6 = dto.Eat6;
user.EatOther = dto.EatOther;
user.Drink1 = dto.Drink1;
user.Drink2 = dto.Drink2;
user.Drink3 = dto.Drink3;
user.Drink4 = dto.Drink4;
user.DrinkOther = dto.DrinkOther;
user.Alco1 = dto.Alco1;
user.Alco2 = dto.Alco2;
user.Alco3 = dto.Alco3;
user.Alco4 = dto.Alco4;
user.Alco5 = dto.Alco5;
user.AlcoOther = dto.AlcoOther;
_repo.Update(user);
}
public List<User> GetAll()
{
return _repo.Get(x => true).ToList();
}
}
} |
๏ปฟnamespace ShipTester.Permutation
{
using System.Collections.Generic;
/// <summary>
/// Creates permutations of all
/// </summary>
/// <typeparam name="TValue">ShipTest permutator</typeparam>
/// <typeparam name="TResult">IEnumerable ShipTest</typeparam>
public class EnumerablePermutator<TValue, TResult> : Permutator<TValue, TResult>
{
/// <summary>
/// Gets or sets properties of the permutator
/// </summary>
public IEnumerable<TValue> Values { get; set; }
/// <summary>
/// retrieves all values of permutations
/// </summary>
/// <returns>IEnumerable array of shipTest permutations</returns>
public override IEnumerable<TValue> GetValues()
{
return this.Values;
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MGL_API.Model.Entrada.Game
{
public class EntradaObterClassificacao
{
public int CodigoGame { get; set; }
}
}
|
๏ปฟusing PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json;
namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing;
internal class AlertOutgoingMessage : JsonOutgoingMessage<JsonAlertOutgoingMessage>
{
internal AlertOutgoingMessage(string message) : base(new JsonAlertOutgoingMessage(message))
{
}
} |
using System;
namespace OnlyOrm.Exceptions
{
public class MethodNotSupportException : ApplicationException
{
public MethodNotSupportException(string oprtate) : base("ๆชๆฏๆ็ๆไฝ็ฌฆ:" + oprtate)
{
}
}
} |
๏ปฟusing System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HacktoberfestProject.Web.Data;
using HacktoberfestProject.Web.Models.DTOs;
using HacktoberfestProject.Web.Models.Entities;
using HacktoberfestProject.Web.Models.Enums;
using HacktoberfestProject.Web.Models.Helpers;
using HacktoberfestProject.Web.Tools;
namespace HacktoberfestProject.Web.Services
{
public class ProjectService : IProjectService
{
private readonly ITableContext _tableContext;
public ProjectService(ITableContext tableContext)
{
NullChecker.IsNotNull(tableContext, nameof(tableContext));
_tableContext = tableContext;
}
public async Task<ServiceResponse> AddProjectAsync(Project project)
{
var projectEntity = new ProjectEntity(project);
await _tableContext.InsertOrMergeEntityAsync(projectEntity);
//todo: add in error handling
return new ServiceResponse
{
ServiceResponseStatus = ServiceResponseStatus.Ok,
Message = $"The project {project.RepoName} was added."
};
}
public async Task<ServiceResponse<IEnumerable<Project>>> GetAllProjectsAsync()
{
var projectEntities = await _tableContext.GetEntities<ProjectEntity>("Project");
//todo: add in error handling
var response = new ServiceResponse<IEnumerable<Project>>
{
Content = projectEntities.Select(x => new Project(x)),
ServiceResponseStatus = ServiceResponseStatus.Ok,
Message = "Successful Retrieval"
};
return response;
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DB_First_SqlServer_Web_Api.Models;
namespace DB_First_SqlServer_Web_Api.Controllers
{
//1.api/[controller]
[Route("/[action]")]
[ApiController]
public class PublishersController : ControllerBase
{
private readonly BookStoreContext _context;
public PublishersController(BookStoreContext context)
{
_context = context;
}
// GET: api/Publishers
[HttpGet]
//[AcceptVerbs("GET", "HEAD")]
[ActionName("GetAllPublisher")]
public async Task<ActionResult<IEnumerable<Publisher>>> GetPublisher()
{
return await _context.Publisher.ToListAsync();
}
// GET: api/Publishers/5
//[HttpGet("{id}")]
[HttpGet]
//Added
[ActionName("PublisherById")]
public async Task<ActionResult<Publisher>> GetPublisher(long id)
{
var publisher = await _context.Publisher.FindAsync(id);
if (publisher == null)
{
return NotFound();
}
return publisher;
}
// PUT: api/Publishers/5
//[HttpPut("{id}")]
[HttpPut]
[ActionName("UpdatePublisher")]
public async Task<IActionResult> PutPublisher(long id, Publisher publisher)
{
if (id != publisher.Id)
{
return BadRequest();
}
_context.Entry(publisher).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PublisherExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Publishers
[HttpPost]
[ActionName("InsertPublisher")]
public async Task<ActionResult<Publisher>> PostPublisher(Publisher publisher)
{
_context.Publisher.Add(publisher);
await _context.SaveChangesAsync();
return CreatedAtAction("GetPublisher", new { id = publisher.Id }, publisher);
}
// DELETE: api/Publishers/5
//[HttpDelete("{id}")]
[HttpDelete]
[ActionName("DeletePublisher")]
public async Task<ActionResult<Publisher>> DeletePublisher(long id)
{
var publisher = await _context.Publisher.FindAsync(id);
if (publisher == null)
{
return NotFound();
}
_context.Publisher.Remove(publisher);
await _context.SaveChangesAsync();
return publisher;
}
private bool PublisherExists(long id)
{
return _context.Publisher.Any(e => e.Id == id);
}
}
}
|
๏ปฟusing System;
namespace RafsScientificCalculator
{
class MainClass
{
public static void Main(string[] args)
{
double distance;
double speed;
double time;
Menu();
void Menu()
{
Console.WriteLine("WELCOME TO RAFS SCIENTIFIC CALCULATOR!!");
string[] options = new string[4];
options[1] = "1.Distance";
options[2] = "2.Speed";
options[3] = "3.Time";
for (int x = 0; x < options.Length; x++)
{
Console.WriteLine(options[x]);
}
Console.WriteLine("");
Console.WriteLine("Enter in a number from 1 to 3 from the menu:");
int input= int.Parse(Console.ReadLine());
if (input == 1)
{
Distance();
}
if (input == 2)
{
Speed();
}
if (input == 3)
{
Time();
}
}
//Methods
void Time()
{
Console.WriteLine("");
Console.WriteLine("Enter in Distance in meters of the object:");
distance = double.Parse(Console.ReadLine());
Console.WriteLine("Enter in the Speed in m/s, it took to the given distance of the object:");
speed = double.Parse(Console.ReadLine());
double result = distance / speed;
Console.WriteLine("The Time in seconds of your object is :" + result + "s");
Console.WriteLine("Would you like to go back to the main menu again ? yes/no");
string whatNow = Console.ReadLine();
if (whatNow == "yes")
{
Menu();
}
if (whatNow == "no")
{
Console.WriteLine("THANK YOU FOR USING RAFS SCIENTIFIC CALCULATOR!!");
}
}
void Speed()
{
Console.WriteLine("");
Console.WriteLine("Enter in Distance in meters of the object:");
speed = double.Parse(Console.ReadLine());
Console.WriteLine("Enter in the Time in seconds it took to the given distance of the object:");
time = double.Parse(Console.ReadLine());
double result = speed / time;
Console.WriteLine("The Speed of your object is :" + result + "m/s");
Console.WriteLine("Would you like to go back to the main menu again ? yes/no");
string whatNow = Console.ReadLine();
if (whatNow == "yes")
{
Menu();
}
if (whatNow == "no")
{
Console.WriteLine("THANK YOU FOR USING RAFS SCIENTIFIC CALCULATOR!!");
}
}
void Distance()
{
Console.WriteLine("");
Console.WriteLine("Enter in the Speed in m/s, it took to the given distance of the object:");
speed = double.Parse(Console.ReadLine());
Console.WriteLine("Enter in the Time in seconds it took to the given distance of the object:");
time = double.Parse(Console.ReadLine());
double result = speed * time;
Console.WriteLine("The Distance of your object is :" + result + "m");
Console.WriteLine("Would you like to go back to the main menu again ? yes/no");
string whatNow = Console.ReadLine();
if (whatNow == "yes")
{
Menu();
}
if (whatNow == "no")
{
Console.WriteLine("THANK YOU FOR USING RAFS SCIENTIFIC CALCULATOR!!");
}
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Standard;
namespace Microsoft.Windows.Shell
{
using HANDLE_MESSAGE = KeyValuePair<WM, MessageHandler>;
internal class WindowChromeWorker : DependencyObject
{
private const SWP _SwpFlags =
SWP.NOOWNERZORDER | SWP.DRAWFRAME | SWP.NOACTIVATE | SWP.NOZORDER | SWP.NOMOVE | SWP.NOSIZE;
[SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId =
"Member")] private static readonly HT[,] _HitTestBorders =
{
{HT.TOPLEFT, HT.TOP, HT.TOPRIGHT}, {HT.LEFT, HT.CLIENT, HT.RIGHT},
{HT.BOTTOMLEFT, HT.BOTTOM, HT.BOTTOMRIGHT}
};
public static readonly DependencyProperty WindowChromeWorkerProperty =
DependencyProperty.RegisterAttached("WindowChromeWorker", typeof(WindowChromeWorker),
typeof(WindowChromeWorker), new PropertyMetadata(null, _OnChromeWorkerChanged));
private readonly List<KeyValuePair<WM, MessageHandler>> _messageTable;
private int _blackGlassFixupAttemptCount;
private WindowChrome _chromeInfo;
private bool _hasUserMovedWindow;
private IntPtr _hwnd;
private HwndSource _hwndSource;
private bool _isFixedUp;
private bool _isGlassEnabled;
private bool _isHooked;
private bool _isUserResizing;
private WindowState _lastMenuState;
private WindowState _lastRoundingState;
private Window _window;
private Point _windowPosAtStartOfUserMove;
public WindowChromeWorker()
{
_messageTable = new List<HANDLE_MESSAGE>
{
new HANDLE_MESSAGE(WM.SETTEXT, _HandleSetTextOrIcon),
new HANDLE_MESSAGE(WM.SETICON, _HandleSetTextOrIcon),
new HANDLE_MESSAGE(WM.NCACTIVATE, _HandleNCActivate),
new HANDLE_MESSAGE(WM.NCCALCSIZE, _HandleNCCalcSize),
new HANDLE_MESSAGE(WM.NCHITTEST, _HandleNCHitTest),
new HANDLE_MESSAGE(WM.NCRBUTTONUP, _HandleNCRButtonUp),
new HANDLE_MESSAGE(WM.SIZE, _HandleSize),
new HANDLE_MESSAGE(WM.WINDOWPOSCHANGED, _HandleWindowPosChanged),
new HANDLE_MESSAGE(WM.DWMCOMPOSITIONCHANGED, _HandleDwmCompositionChanged)
};
if (Utility.IsPresentationFrameworkVersionLessThan4)
{
KeyValuePair<WM, MessageHandler>[] collection =
{
new KeyValuePair<WM, MessageHandler>(WM.WININICHANGE, _HandleSettingChange),
new KeyValuePair<WM, MessageHandler>(WM.ENTERSIZEMOVE, _HandleEnterSizeMove),
new KeyValuePair<WM, MessageHandler>(WM.EXITSIZEMOVE, _HandleExitSizeMove),
new KeyValuePair<WM, MessageHandler>(WM.MOVE, _HandleMove)
};
_messageTable.AddRange(collection);
}
}
private bool _IsWindowDocked
{
get
{
if (_window.WindowState != WindowState.Normal)
return false;
var rcWindow = new RECT
{
Bottom = 100,
Right = 100
};
var rect = _GetAdjustedWindowRect(rcWindow);
var point = new Point(_window.Left, _window.Top);
point -= (Vector) DpiHelper.DevicePixelsToLogical(new Point(rect.Left, rect.Top));
return _window.RestoreBounds.Location != point;
}
}
private void _ApplyNewCustomChrome()
{
if (_hwnd != IntPtr.Zero)
if (_chromeInfo == null)
{
_RestoreStandardChromeState(false);
}
else
{
if (!_isHooked)
{
_hwndSource.AddHook(_WndProc);
_isHooked = true;
}
_FixupFrameworkIssues();
_UpdateSystemMenu(_window.WindowState);
_UpdateFrameState(true);
NativeMethods.SetWindowPos(_hwnd, IntPtr.Zero, 0, 0, 0, 0,
SWP.NOOWNERZORDER | SWP.DRAWFRAME | SWP.NOACTIVATE | SWP.NOZORDER | SWP.NOMOVE | SWP.NOSIZE);
}
}
private void _ClearRoundingRegion()
{
NativeMethods.SetWindowRgn(_hwnd, IntPtr.Zero, NativeMethods.IsWindowVisible(_hwnd));
}
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "HRGNs")]
private static void _CreateAndCombineRoundRectRgn(IntPtr hrgnSource, Rect region, double radius)
{
var zero = IntPtr.Zero;
try
{
zero = _CreateRoundRectRgn(region, radius);
if (NativeMethods.CombineRgn(hrgnSource, hrgnSource, zero, RGN.OR) == CombineRgnResult.ERROR)
throw new InvalidOperationException("Unable to combine two HRGNs.");
}
catch
{
Utility.SafeDeleteObject(ref zero);
throw;
}
}
private static IntPtr _CreateRoundRectRgn(Rect region, double radius)
{
if (DoubleUtilities.AreClose(0.0, radius))
return NativeMethods.CreateRectRgn((int) Math.Floor(region.Left), (int) Math.Floor(region.Top),
(int) Math.Ceiling(region.Right), (int) Math.Ceiling(region.Bottom));
return NativeMethods.CreateRoundRectRgn((int) Math.Floor(region.Left), (int) Math.Floor(region.Top),
(int) Math.Ceiling(region.Right) + 1, (int) Math.Ceiling(region.Bottom) + 1, (int) Math.Ceiling(radius),
(int) Math.Ceiling(radius));
}
private void _ExtendGlassFrame()
{
if (Utility.IsOSVistaOrNewer && IntPtr.Zero != _hwnd)
if (!NativeMethods.DwmIsCompositionEnabled())
{
_hwndSource.CompositionTarget.BackgroundColor = SystemColors.WindowColor;
}
else
{
_hwndSource.CompositionTarget.BackgroundColor = Colors.Transparent;
var point = DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.GlassFrameThickness.Left,
_chromeInfo.GlassFrameThickness.Top));
var point2 = DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.GlassFrameThickness.Right,
_chromeInfo.GlassFrameThickness.Bottom));
var pMarInset = new MARGINS
{
cxLeftWidth = (int) Math.Ceiling(point.X),
cxRightWidth = (int) Math.Ceiling(point2.X),
cyTopHeight = (int) Math.Ceiling(point.Y),
cyBottomHeight = (int) Math.Ceiling(point2.Y)
};
NativeMethods.DwmExtendFrameIntoClientArea(_hwnd, ref pMarInset);
}
}
private void _FixupFrameworkIssues()
{
if (Utility.IsPresentationFrameworkVersionLessThan4 && _window.Template != null)
if (VisualTreeHelper.GetChildrenCount(_window) == 0)
{
_window.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new _Action(_FixupFrameworkIssues));
}
else
{
var child = (FrameworkElement) VisualTreeHelper.GetChild(_window, 0);
var windowRect = NativeMethods.GetWindowRect(_hwnd);
var rect2 = _GetAdjustedWindowRect(windowRect);
var rect3 = DpiHelper.DeviceRectToLogical(new Rect(windowRect.Left, windowRect.Top,
windowRect.Width, windowRect.Height));
var rect4 = DpiHelper.DeviceRectToLogical(
new Rect(rect2.Left, rect2.Top, rect2.Width, rect2.Height));
var thickness = new Thickness(rect3.Left - rect4.Left, rect3.Top - rect4.Top,
rect4.Right - rect3.Right, rect4.Bottom - rect3.Bottom);
child.Margin = new Thickness(0.0, 0.0, -(thickness.Left + thickness.Right),
-(thickness.Top + thickness.Bottom));
if (_window.FlowDirection == FlowDirection.RightToLeft)
child.RenderTransform =
new MatrixTransform(1.0, 0.0, 0.0, 1.0, -(thickness.Left + thickness.Right), 0.0);
else
child.RenderTransform = null;
if (!_isFixedUp)
{
_hasUserMovedWindow = false;
_window.StateChanged += _FixupRestoreBounds;
_isFixedUp = true;
}
}
}
private void _FixupRestoreBounds(object sender, EventArgs e)
{
if ((_window.WindowState == WindowState.Maximized || _window.WindowState == WindowState.Minimized) &&
_hasUserMovedWindow)
{
_hasUserMovedWindow = false;
var windowPlacement = NativeMethods.GetWindowPlacement(_hwnd);
var rcWindow = new RECT
{
Bottom = 100,
Right = 100
};
var rect = _GetAdjustedWindowRect(rcWindow);
var point = DpiHelper.DevicePixelsToLogical(new Point(windowPlacement.rcNormalPosition.Left - rect.Left,
windowPlacement.rcNormalPosition.Top - rect.Top));
_window.Top = point.Y;
_window.Left = point.X;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void _FixupWindows7Issues()
{
if (_blackGlassFixupAttemptCount <= 5 && Utility.IsOSWindows7OrNewer &&
NativeMethods.DwmIsCompositionEnabled())
{
_blackGlassFixupAttemptCount++;
var hasValue = false;
try
{
hasValue = NativeMethods.DwmGetCompositionTimingInfo(_hwnd).HasValue;
}
catch (Exception)
{
}
if (!hasValue)
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new _Action(_FixupWindows7Issues));
else
_blackGlassFixupAttemptCount = 0;
}
}
private RECT _GetAdjustedWindowRect(RECT rcWindow)
{
var windowLongPtr = (WS) (int) NativeMethods.GetWindowLongPtr(_hwnd, GWL.STYLE);
var dwExStyle = (WS_EX) (int) NativeMethods.GetWindowLongPtr(_hwnd, GWL.EXSTYLE);
return NativeMethods.AdjustWindowRectEx(rcWindow, windowLongPtr, false, dwExStyle);
}
private WindowState _GetHwndState()
{
switch (NativeMethods.GetWindowPlacement(_hwnd).showCmd)
{
case SW.SHOWMINIMIZED:
return WindowState.Minimized;
case SW.SHOWMAXIMIZED:
return WindowState.Maximized;
}
return WindowState.Normal;
}
private Rect _GetWindowRect()
{
var windowRect = NativeMethods.GetWindowRect(_hwnd);
return new Rect(windowRect.Left, windowRect.Top, windowRect.Width, windowRect.Height);
}
private IntPtr _HandleDwmCompositionChanged(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
_UpdateFrameState(false);
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleEnterSizeMove(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
_isUserResizing = true;
if (_window.WindowState != WindowState.Maximized && !_IsWindowDocked)
_windowPosAtStartOfUserMove = new Point(_window.Left, _window.Top);
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleExitSizeMove(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
_isUserResizing = false;
if (_window.WindowState == WindowState.Maximized)
{
_window.Top = _windowPosAtStartOfUserMove.Y;
_window.Left = _windowPosAtStartOfUserMove.X;
}
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleMove(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
if (_isUserResizing)
_hasUserMovedWindow = true;
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleNCActivate(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
var ptr = NativeMethods.DefWindowProc(_hwnd, WM.NCACTIVATE, wParam, new IntPtr(-1));
handled = true;
return ptr;
}
private IntPtr _HandleNCCalcSize(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
handled = true;
return new IntPtr(0x300);
}
private IntPtr _HandleNCHitTest(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
var zero = IntPtr.Zero;
handled = false;
if (Utility.IsOSVistaOrNewer && _chromeInfo.GlassFrameThickness != new Thickness() && _isGlassEnabled)
handled = NativeMethods.DwmDefWindowProc(_hwnd, uMsg, wParam, lParam, out zero);
if (!(IntPtr.Zero == zero))
return zero;
var devicePoint = new Point(Utility.GET_X_LPARAM(lParam), Utility.GET_Y_LPARAM(lParam));
var deviceRectangle = _GetWindowRect();
var cLIENT = _HitTestNca(DpiHelper.DeviceRectToLogical(deviceRectangle),
DpiHelper.DevicePixelsToLogical(devicePoint));
if (cLIENT != HT.CLIENT)
{
var point2 = devicePoint;
point2.Offset(-deviceRectangle.X, -deviceRectangle.Y);
point2 = DpiHelper.DevicePixelsToLogical(point2);
var inputElement = _window.InputHitTest(point2);
if (inputElement != null && WindowChrome.GetIsHitTestVisibleInChrome(inputElement))
cLIENT = HT.CLIENT;
}
handled = true;
return new IntPtr((int) cLIENT);
}
private IntPtr _HandleNCRButtonUp(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
if (2 == wParam.ToInt32())
SystemCommands.ShowSystemMenuPhysicalCoordinates(_window,
new Point(Utility.GET_X_LPARAM(lParam), Utility.GET_Y_LPARAM(lParam)));
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleSetTextOrIcon(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
var flag = _ModifyStyle(WS.OVERLAPPED | WS.VISIBLE, WS.OVERLAPPED);
var ptr = NativeMethods.DefWindowProc(_hwnd, uMsg, wParam, lParam);
if (flag)
_ModifyStyle(WS.OVERLAPPED, WS.OVERLAPPED | WS.VISIBLE);
handled = true;
return ptr;
}
private IntPtr _HandleSettingChange(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
_FixupFrameworkIssues();
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleSize(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
WindowState? assumeState = null;
if (wParam.ToInt32() == 2)
assumeState = WindowState.Maximized;
_UpdateSystemMenu(assumeState);
handled = false;
return IntPtr.Zero;
}
private IntPtr _HandleWindowPosChanged(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled)
{
_UpdateSystemMenu(null);
if (!_isGlassEnabled)
{
var windowpos = (WINDOWPOS) Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
_SetRoundingRegion(windowpos);
}
handled = false;
return IntPtr.Zero;
}
private HT _HitTestNca(Rect windowPosition, Point mousePosition)
{
var num = 1;
var num2 = 1;
var flag = false;
if (mousePosition.Y >= windowPosition.Top && mousePosition.Y <
windowPosition.Top + _chromeInfo.ResizeBorderThickness.Top + _chromeInfo.CaptionHeight)
{
flag = mousePosition.Y < windowPosition.Top + _chromeInfo.ResizeBorderThickness.Top;
num = 0;
}
else if (mousePosition.Y < windowPosition.Bottom && mousePosition.Y >=
windowPosition.Bottom - (int) _chromeInfo.ResizeBorderThickness.Bottom)
{
num = 2;
}
if (mousePosition.X >= windowPosition.Left &&
mousePosition.X < windowPosition.Left + (int) _chromeInfo.ResizeBorderThickness.Left)
num2 = 0;
else if (mousePosition.X < windowPosition.Right &&
mousePosition.X >= windowPosition.Right - _chromeInfo.ResizeBorderThickness.Right)
num2 = 2;
if (num == 0 && num2 != 1 && !flag)
num = 1;
var cAPTION = _HitTestBorders[num, num2];
if (cAPTION == HT.TOP && !flag)
cAPTION = HT.CAPTION;
return cAPTION;
}
private static bool _IsUniform(CornerRadius cornerRadius)
{
if (!DoubleUtilities.AreClose(cornerRadius.BottomLeft, cornerRadius.BottomRight))
return false;
if (!DoubleUtilities.AreClose(cornerRadius.TopLeft, cornerRadius.TopRight))
return false;
if (!DoubleUtilities.AreClose(cornerRadius.BottomLeft, cornerRadius.TopRight))
return false;
return true;
}
private bool _ModifyStyle(WS removeStyle, WS addStyle)
{
var ws = (WS) NativeMethods.GetWindowLongPtr(_hwnd, GWL.STYLE).ToInt32();
var ws2 = (ws & ~removeStyle) | addStyle;
if (ws == ws2)
return false;
NativeMethods.SetWindowLongPtr(_hwnd, GWL.STYLE, new IntPtr((int) ws2));
return true;
}
private void _OnChromePropertyChangedThatRequiresRepaint(object sender, EventArgs e)
{
_UpdateFrameState(true);
}
private static void _OnChromeWorkerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = (Window) d;
((WindowChromeWorker) e.NewValue)._SetWindow(window);
}
private void _OnWindowPropertyChangedThatRequiresTemplateFixup(object sender, EventArgs e)
{
if (_chromeInfo != null && _hwnd != IntPtr.Zero)
_window.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new _Action(_FixupFrameworkIssues));
}
private void _RestoreFrameworkIssueFixups()
{
if (Utility.IsPresentationFrameworkVersionLessThan4)
{
var child = (FrameworkElement) VisualTreeHelper.GetChild(_window, 0);
child.Margin = new Thickness();
_window.StateChanged -= _FixupRestoreBounds;
_isFixedUp = false;
}
}
private void _RestoreGlassFrame()
{
if (Utility.IsOSVistaOrNewer && _hwnd != IntPtr.Zero)
{
_hwndSource.CompositionTarget.BackgroundColor = SystemColors.WindowColor;
if (NativeMethods.DwmIsCompositionEnabled())
{
var pMarInset = new MARGINS();
NativeMethods.DwmExtendFrameIntoClientArea(_hwnd, ref pMarInset);
}
}
}
private void _RestoreHrgn()
{
_ClearRoundingRegion();
NativeMethods.SetWindowPos(_hwnd, IntPtr.Zero, 0, 0, 0, 0,
SWP.NOOWNERZORDER | SWP.DRAWFRAME | SWP.NOACTIVATE | SWP.NOZORDER | SWP.NOMOVE | SWP.NOSIZE);
}
private void _RestoreStandardChromeState(bool isClosing)
{
VerifyAccess();
_UnhookCustomChrome();
if (!isClosing)
{
_RestoreFrameworkIssueFixups();
_RestoreGlassFrame();
_RestoreHrgn();
_window.InvalidateMeasure();
}
}
private void _SetRoundingRegion(WINDOWPOS? wp)
{
if (NativeMethods.GetWindowPlacement(_hwnd).showCmd == SW.SHOWMAXIMIZED)
{
int x;
int y;
if (wp.HasValue)
{
x = wp.Value.x;
y = wp.Value.y;
}
else
{
var rect = _GetWindowRect();
x = (int) rect.Left;
y = (int) rect.Top;
}
var rcWork = NativeMethods.GetMonitorInfo(NativeMethods.MonitorFromWindow(_hwnd, 2)).rcWork;
rcWork.Offset(-x, -y);
var zero = IntPtr.Zero;
try
{
zero = NativeMethods.CreateRectRgnIndirect(rcWork);
NativeMethods.SetWindowRgn(_hwnd, zero, NativeMethods.IsWindowVisible(_hwnd));
zero = IntPtr.Zero;
}
finally
{
Utility.SafeDeleteObject(ref zero);
}
}
else
{
Size size;
if (wp.HasValue && !Utility.IsFlagSet(wp.Value.flags, 1))
{
size = new Size(wp.Value.cx, wp.Value.cy);
}
else
{
if (wp.HasValue && _lastRoundingState == _window.WindowState)
return;
size = _GetWindowRect().Size;
}
_lastRoundingState = _window.WindowState;
var hrgnSource = IntPtr.Zero;
try
{
var num3 = Math.Min(size.Width, size.Height);
var radius =
Math.Min(DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.CornerRadius.TopLeft, 0.0)).X,
num3 / 2.0);
if (_IsUniform(_chromeInfo.CornerRadius))
{
hrgnSource = _CreateRoundRectRgn(new Rect(size), radius);
}
else
{
hrgnSource =
_CreateRoundRectRgn(
new Rect(0.0, 0.0, size.Width / 2.0 + radius, size.Height / 2.0 + radius), radius);
var num5 = Math.Min(
DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.CornerRadius.TopRight, 0.0)).X,
num3 / 2.0);
var region = new Rect(0.0, 0.0, size.Width / 2.0 + num5, size.Height / 2.0 + num5);
region.Offset(size.Width / 2.0 - num5, 0.0);
_CreateAndCombineRoundRectRgn(hrgnSource, region, num5);
var num6 = Math.Min(
DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.CornerRadius.BottomLeft, 0.0)).X,
num3 / 2.0);
var rect4 = new Rect(0.0, 0.0, size.Width / 2.0 + num6, size.Height / 2.0 + num6);
rect4.Offset(0.0, size.Height / 2.0 - num6);
_CreateAndCombineRoundRectRgn(hrgnSource, rect4, num6);
var num7 = Math.Min(
DpiHelper.LogicalPixelsToDevice(new Point(_chromeInfo.CornerRadius.BottomRight, 0.0)).X,
num3 / 2.0);
var rect5 = new Rect(0.0, 0.0, size.Width / 2.0 + num7, size.Height / 2.0 + num7);
rect5.Offset(size.Width / 2.0 - num7, size.Height / 2.0 - num7);
_CreateAndCombineRoundRectRgn(hrgnSource, rect5, num7);
}
NativeMethods.SetWindowRgn(_hwnd, hrgnSource, NativeMethods.IsWindowVisible(_hwnd));
hrgnSource = IntPtr.Zero;
}
finally
{
Utility.SafeDeleteObject(ref hrgnSource);
}
}
}
private void _SetWindow(Window window)
{
EventHandler handler = null;
_window = window;
_hwnd = new WindowInteropHelper(_window).Handle;
if (Utility.IsPresentationFrameworkVersionLessThan4)
{
Utility.AddDependencyPropertyChangeListener(_window, Control.TemplateProperty,
_OnWindowPropertyChangedThatRequiresTemplateFixup);
Utility.AddDependencyPropertyChangeListener(_window, FrameworkElement.FlowDirectionProperty,
_OnWindowPropertyChangedThatRequiresTemplateFixup);
}
_window.Closed += _UnsetWindow;
if (IntPtr.Zero != _hwnd)
{
_hwndSource = HwndSource.FromHwnd(_hwnd);
_window.ApplyTemplate();
if (_chromeInfo != null)
_ApplyNewCustomChrome();
}
else
{
if (handler == null)
handler = delegate
{
_hwnd = new WindowInteropHelper(_window).Handle;
_hwndSource = HwndSource.FromHwnd(_hwnd);
if (_chromeInfo != null)
_ApplyNewCustomChrome();
};
_window.SourceInitialized += handler;
}
}
private void _UnhookCustomChrome()
{
if (_isHooked)
{
_hwndSource.RemoveHook(_WndProc);
_isHooked = false;
}
}
private void _UnsetWindow(object sender, EventArgs e)
{
if (Utility.IsPresentationFrameworkVersionLessThan4)
{
Utility.RemoveDependencyPropertyChangeListener(_window, Control.TemplateProperty,
_OnWindowPropertyChangedThatRequiresTemplateFixup);
Utility.RemoveDependencyPropertyChangeListener(_window, FrameworkElement.FlowDirectionProperty,
_OnWindowPropertyChangedThatRequiresTemplateFixup);
}
if (_chromeInfo != null)
_chromeInfo.PropertyChangedThatRequiresRepaint -= _OnChromePropertyChangedThatRequiresRepaint;
_RestoreStandardChromeState(true);
}
private void _UpdateFrameState(bool force)
{
if (IntPtr.Zero != _hwnd)
{
var flag = NativeMethods.DwmIsCompositionEnabled();
if (force || flag != _isGlassEnabled)
{
_isGlassEnabled = flag && _chromeInfo.GlassFrameThickness != new Thickness();
if (!_isGlassEnabled)
{
_SetRoundingRegion(null);
}
else
{
_ClearRoundingRegion();
_ExtendGlassFrame();
_FixupWindows7Issues();
}
NativeMethods.SetWindowPos(_hwnd, IntPtr.Zero, 0, 0, 0, 0,
SWP.NOOWNERZORDER | SWP.DRAWFRAME | SWP.NOACTIVATE | SWP.NOZORDER | SWP.NOMOVE | SWP.NOSIZE);
}
}
}
private void _UpdateSystemMenu(WindowState? assumeState)
{
var nullable = assumeState;
var state = nullable.HasValue ? nullable.GetValueOrDefault() : _GetHwndState();
if (!assumeState.HasValue && _lastMenuState == state)
return;
_lastMenuState = state;
var flag = _ModifyStyle(WS.OVERLAPPED | WS.VISIBLE, WS.OVERLAPPED);
var systemMenu = NativeMethods.GetSystemMenu(_hwnd, false);
if (IntPtr.Zero != systemMenu)
{
var ws = (WS) NativeMethods.GetWindowLongPtr(_hwnd, GWL.STYLE).ToInt32();
var flag2 = Utility.IsFlagSet((int) ws, 0x20000);
var flag3 = Utility.IsFlagSet((int) ws, 0x10000);
var flag4 = Utility.IsFlagSet((int) ws, 0x40000);
switch (state)
{
case WindowState.Minimized:
NativeMethods.EnableMenuItem(systemMenu, SC.RESTORE, MF.BYCOMMAND);
NativeMethods.EnableMenuItem(systemMenu, SC.MOVE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.SIZE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MINIMIZE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MAXIMIZE,
flag3 ? MF.BYCOMMAND : MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
goto Label_01A6;
case WindowState.Maximized:
NativeMethods.EnableMenuItem(systemMenu, SC.RESTORE, MF.BYCOMMAND);
NativeMethods.EnableMenuItem(systemMenu, SC.MOVE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.SIZE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MINIMIZE,
flag2 ? MF.BYCOMMAND : MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MAXIMIZE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
goto Label_01A6;
}
NativeMethods.EnableMenuItem(systemMenu, SC.RESTORE, MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MOVE, MF.BYCOMMAND);
NativeMethods.EnableMenuItem(systemMenu, SC.SIZE,
flag4 ? MF.BYCOMMAND : MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MINIMIZE,
flag2 ? MF.BYCOMMAND : MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
NativeMethods.EnableMenuItem(systemMenu, SC.MAXIMIZE,
flag3 ? MF.BYCOMMAND : MF.BYCOMMAND | MF.DISABLED | MF.GRAYED);
}
Label_01A6:
if (flag)
_ModifyStyle(WS.OVERLAPPED, WS.OVERLAPPED | WS.VISIBLE);
}
private IntPtr _WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
var uMsg = (WM) msg;
foreach (var pair in _messageTable)
if (pair.Key == uMsg)
return pair.Value(uMsg, wParam, lParam, out handled);
return IntPtr.Zero;
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static WindowChromeWorker GetWindowChromeWorker(Window window)
{
Verify.IsNotNull(window, "window");
return (WindowChromeWorker) window.GetValue(WindowChromeWorkerProperty);
}
public void SetWindowChrome(WindowChrome newChrome)
{
VerifyAccess();
if (newChrome != _chromeInfo)
{
if (_chromeInfo != null)
_chromeInfo.PropertyChangedThatRequiresRepaint -= _OnChromePropertyChangedThatRequiresRepaint;
_chromeInfo = newChrome;
if (_chromeInfo != null)
_chromeInfo.PropertyChangedThatRequiresRepaint += _OnChromePropertyChangedThatRequiresRepaint;
_ApplyNewCustomChrome();
}
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static void SetWindowChromeWorker(Window window, WindowChromeWorker chrome)
{
Verify.IsNotNull(window, "window");
window.SetValue(WindowChromeWorkerProperty, chrome);
}
private delegate void _Action();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace ZiZhuJY.ServiceModel
{
//ISS .svc example
//<%@ServiceHost Service="YourCalculatorService"
// Factory="DevAge.ServiceModel.CertificateServiceHostFactory"
// language=c# Debug="true" %>
//
// For more informations look at:
// http://msdn2.microsoft.com/en-us/library/aa395224.aspx "Custom Service Host"
/// <summary>
/// The factory class derived from ServiceHostFactory used to create the CertificateServiceHost class.
/// Useful when hosting the service with IIS where you cannot specify what class to create but you can specify the host factory.
/// </summary>
public class CertificateServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new CertificateServiceHost(serviceType, baseAddresses);
}
}
}
|
๏ปฟ//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using DotNetNuke.ComponentModel;
#endregion
namespace DotNetNuke.Services.Log.EventLog
{
public abstract class LoggingProvider
{
#region ReturnType enum
public enum ReturnType
{
LogInfoObjects,
XML
}
#endregion
#region "Shared/Static Methods"
//return the provider
public static LoggingProvider Instance()
{
return ComponentFactory.GetComponent<LoggingProvider>();
}
#endregion
#region "Abstract Methods"
public abstract void AddLog(LogInfo logInfo);
public abstract void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner);
public abstract void AddLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress);
public abstract void ClearLog();
public abstract void DeleteLog(LogInfo logInfo);
public abstract void DeleteLogType(string logTypeKey);
public abstract void DeleteLogTypeConfigInfo(string id);
public virtual List<LogInfo> GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords)
{
return new List<LogInfo>();
}
public abstract ArrayList GetLogTypeConfigInfo();
public abstract ArrayList GetLogTypeInfo();
public abstract LogTypeConfigInfo GetLogTypeConfigInfoByID(string id);
public abstract object GetSingleLog(LogInfo logInfo, ReturnType returnType);
public abstract bool LoggingIsEnabled(string logType, int portalID);
public abstract void PurgeLogBuffer();
public abstract void SendLogNotifications();
public abstract bool SupportsEmailNotification();
public abstract bool SupportsInternalViewer();
public abstract bool SupportsSendToCoreTeam();
public abstract bool SupportsSendViaEmail();
public abstract void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner);
public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress);
#endregion
}
}
|
๏ปฟusing System;
namespace Aqueduct.SitecoreLib.DataAccess.ValueResolvers
{
public class GuidValueResolver : IValueResolver
{
public bool CanResolve(Type type)
{
return typeof (Guid) == type;
}
public object ResolveEntityPropertyValue(string rawValue, Type propertyType)
{
return new Guid(rawValue);
}
public object ResolveItemFieldValue(object rawValue)
{
return rawValue;
}
}
}
|
๏ปฟusing Ego.PDF.Data;
namespace Ego.PDF.Samples
{
public class Sample1
{
public static FPdf GetSample()
{
var pdf = new FPdf();
pdf.AddPage(PageSizeEnum.A4);
pdf.SetFont("Arial", "", 16);
pdf.Cell(40, 10, "Hello World!");
return pdf;
}
}
} |
๏ปฟusing FeedBackPlatformWeb.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FeedBackPlatformWeb.Controllers.Base
{
public abstract class BaseController: Controller
{
public UserContext UserContext
{
get
{
var userContext = this.Session[Constants.UserContext_key] as UserContext;
if (userContext == null)
userContext = new UserContext();
return userContext;
}
set
{
this.Session[Constants.UserContext_key] = value;
}
}
}
} |
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScrFruit : MonoBehaviour {
public float speed;
public float falltime;
public GameObject parent;
// Use this for initialization
void Start () {
Debug.Log ("Bonjour le fruit peut plus ou moins apapraitre");
}
// Update is called once per frame
public void Update () {
}
public void falling()
{
if (gameObject.transform.position.y != -1) {
GetComponent<Rigidbody> ().velocity = transform.up * speed;
}
}
public void timing(){
StartCoroutine (test ());
}
IEnumerator test ()
{
Debug.Log ("Timer set");
yield return new WaitForSeconds (falltime);
Debug.Log ("Timer finish");
GetComponent<Rigidbody> ().velocity = transform.up * 0;
transform.gameObject.tag = "healingFruit";
transform.gameObject.name = "Fruit juteux";
transform.parent = null;
}
}
|
๏ปฟusing log4net;
using System;
using System.Collections.Generic;
using System.Linq;
namespace UrTLibrary.Server.Logging.Events.ChatCommands
{
[ChatCommandKey("admins")]
public class AdminsCommand : ChatCommand
{
public override void Execute(GameServer server)
{
log.DebugFormat("--> Executing AdminsCommand");
try
{
IEnumerable<Client> source = server.Clients.Where(x => x.Info.Level > 1);
if (source.Count() > 0)
foreach (Client client in source)
{
GroupInfo groupInfo = server.GetGroupByLevel(client.Info.Level);
server.QueryManager.TellInfo(Slot, string.Format("{0} ^7[^3{1}^7]", client.Name, groupInfo.Name));
}
else
server.QueryManager.TellInfo(Slot, "No admin connected");
}
catch (CommandException ex)
{
server.QueryManager.TellError(Slot, ex.Message);
}
}
}
}
|
๏ปฟusing DavisVantage.WeatherReader.Extensions;
namespace DavisVantage.WeatherReader.Models.Extremes
{
public class WeatherYearExtremes
{
public override string ToString()
{
return this.PrintAllProperties();
}
}
}
|
๏ปฟusing NLog;
using NLog.Config;
using NLog.Targets;
using System;
using PhonebookImportServer.Business;
using PhonebookImportServer.Wcf;
namespace PhonebookImportServer
{
class Program
{
static void SetLogging()
{
LoggingConfiguration cfg = new LoggingConfiguration();
ColoredConsoleTarget target = new ColoredConsoleTarget();
target.Layout = "${date:format=yyyy\\.MM\\.dd HH\\:mm\\:ss} [${level:uppercase=true}] ${callsite} => ${message} <${exception:format=tostring}>";
cfg.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
cfg.AddTarget("console", target);
#region Logovรกnรญ do souboru
/*
FileTarget fileTarget = new FileTarget();
fileTarget.FileName = "${basedir}/PhonebookImportService.log";
fileTarget.Layout = "${date:format=yyyy\\.MM\\.dd HH\\:mm\\:ss} [${level:uppercase=true}] ${callsite} => ${message} <${exception:format=tostring}>";
cfg.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
cfg.AddTarget("file", fileTarget);
*/
#endregion
try
{
LogManager.Configuration = cfg;
}
catch { }
}
readonly Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
SetLogging();
new Program().Run();
}
private void Run()
{
logger.Info("Application start");
PhonebookImportServiceImpl sampleService = new PhonebookImportServiceImpl(logger);
WcfServiceHost serviceHost = new WcfServiceHost();
serviceHost.Open(sampleService);
Console.ReadKey();
serviceHost.Close();
}
}
}
|
๏ปฟusing System;
using System.Linq;
namespace SiDualMode.Base {
/// <summary>
/// Payload publisher base class.
/// </summary>
/// <typeparam name="TPayloadType">The type of the event type.</typeparam>
/// <typeparam name="TConfigType">The type of config type.</typeparam>
public abstract class StreamEventProducer<TPayloadType, TConfigType> : IObservable<StreamInputEvent<TPayloadType>>, IDisposable {
public TConfigType Configuration { get; protected set; }
private IObserver<StreamInputEvent<TPayloadType>> _observer;
//This allows us to lock certain critical sections.
//While the possibility of threading issues is low, it's still there
protected object LockObject = new object();
private bool _disposed;
protected StreamEventProducer(TConfigType configuration) {
this.Configuration = configuration;
}
protected abstract void Start();
public virtual IDisposable Subscribe(IObserver<StreamInputEvent<TPayloadType>> observer) {
CheckDisposed();
lock (LockObject) {
this._observer = observer;
}
Start();
return this;
}
/// <summary>
/// Publishes the exception.
/// </summary>
/// <param name="ex">The exception</param>
protected void PublishException(Exception ex) {
CheckDisposed();
lock (LockObject) {
if (_observer != null) {
_observer.OnError(ex);
}
}
}
/// <summary>
/// Publishes the event.
/// </summary>
/// <param name="newEvent">The new event.</param>
protected void PublishEvent(StreamInputEvent<TPayloadType> newEvent) {
CheckDisposed();
lock (LockObject) {
if (_observer != null) {
_observer.OnNext(newEvent);
}
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing) {
if (disposing) {
lock (LockObject) {
_observer.OnCompleted();
_observer = null;
}
}
}
/// <summary>
/// Checks if the class has been disposed.
/// </summary>
/// <remarks>Throws an <see cref="ObjectDisposedException"/>ObjectDisposedException</remarks>
/// if the object has been disposed.
protected void CheckDisposed() {
if (_disposed) {
throw new ObjectDisposedException("Object has been disposed");
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmangaged resources.
/// </summary>
public void Dispose() {
//Make sure Dispose is only handled once!
if (!_disposed) {
Dispose(true);
_disposed = true;
GC.SuppressFinalize(this);
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Raiwan.pages
{
/// <summary>
/// Interaction logic for message.xaml
/// </summary>
public partial class message : Window
{
MainWindow mainWindow;
DispatcherTimer stTimer;
public message()
{
InitializeComponent();
mainWindow = null;
foreach (Window window in Application.Current.Windows)
{
Type type = typeof(MainWindow);
if (window != null && window.DependencyObjectType.Name == type.Name)
{
mainWindow = (MainWindow)window;
if (mainWindow != null)
{
break;
}
}
}
mainWindow.NotConnected = true;
setTimer();
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
Application.Current.Shutdown();
}
private void retry()
{
mainWindow.CheckConnect -= value => ConnectRespond(value);
mainWindow.CheckConnect += value => ConnectRespond(value);
mainWindow.setPortsNames();
string[] ports = mainWindow.getPorts();
mainWindow.AutomateConnect(ports);
mainWindow.JsonType = "ACK1";
mainWindow.request("{\"PKT\":2,\"AYR\":\"T\"}***");
mainWindow.CanRequest = false;
}
private void setTimer()
{
stTimer = new DispatcherTimer();
stTimer.Interval = TimeSpan.FromMilliseconds(100);
stTimer.Tick += stevent;
stTimer.Start();
}
private void stevent(object sender, EventArgs e)
{
retry();
}
public void ConnectRespond(string s)
{
mainWindow.NotConnected = false;
stTimer.Stop();
mainWindow.MessageShow = false;
mainWindow.CanRequest = true;
mainWindow.CanDownload = true;
mainWindow.fileText.Clear();
this.Dispatcher.Invoke(() =>
{
this.Hide();
});
}
private void Window_Closed(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Application.Current.Shutdown();
}
}
}
|
๏ปฟusing Checkout.Payment.Identity.Data.Repositories;
using Checkout.Payment.Identity.Domain.Interfaces;
using Checkout.Payment.Identity.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Checkout.Payment.Identity.Extensions
{
public static class CustomIdentityServerBuilderExtensions
{
public static IIdentityServerBuilder AddCustomUserStore(this IIdentityServerBuilder builder)
{
builder.Services.TryAddSingleton<IUserRepository, UserRepository>();
builder.Services.TryAddSingleton<IApiKeyRepository, ApiKeyRepository>();
builder.AddProfileService<CustomProfileService>();
builder.AddResourceOwnerValidator<CustomResourceOwnerPasswordValidator>();
builder.AddCustomTokenRequestValidator<CustomResourceOwnerClientValidator>();
return builder;
}
}
}
|
๏ปฟusing Converter.UI.Framework;
namespace Converter.UI.Views
{
/// <summary>
/// Interaction logic for SummaryView.xaml
/// </summary>
public partial class SummaryView : ViewModelUserControl
{
public SummaryView()
{
InitializeComponent();
}
}
}
|
๏ปฟusing Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace FastSQL.Magento2
{
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var descriptor = container.Resolve<FromAssemblyDescriptor>();
container.Register(Component.For<Magento2RestApi>().ImplementedBy<Magento2RestApi>().LifestyleTransient());
// Processors
//container.Register(descriptor
// .BasedOn<IProcessor>()
// .WithService.Select(new Type[] { typeof(IProcessor) })
// .WithServiceSelf()
// .Configure(x => x.LifeStyle.Is(LifestyleType.Transient)));
}
}
}
|
๏ปฟ/* ๋ฆฌ์คํธ ๋ทฐ xaml - prjid, bldid, fileid, nameKr ์ถ๋ ฅ
* json ์ ๊ณต api - http://indoormap.seoul.go.kr/openapi/request.html
* sbm ์ ์ฅ ์์น C - dev - sbm ์ ๊ฐ ๊ฑด๋ฌผ ์ด๋ฆ ํด๋๊ฐ ์์ฑ๋๊ณ ์ ์ฅ๋จ
* sbmall - ํ ๊ฑด๋ฌผ ๋ด ์ ์ฒด sbm ๋ฐ์์ด
* sbm - ํด๋น ๊ฑด๋ฌผ์ ๋ํดํธ floorid ๋ฅผ ์ด์ฉํ์ฌ ํ๊ฐ์ sbm ๋ง ๋ฐ์์ด.
* refresh - ๋ด๋ถ์ง๋๊ฐ ์๋ ์ ์ฒด ๊ฑด๋ฌผ ๋ชฉ๋ก์ ๋ฆฌ์คํธ ๋ทฐ์ ์ฌ๋ ค์ค.
* refresh ๋ฅผ ๋๋ฌ ๊ฑด๋ฌผ ๋ชฉ๋ก์ ๋ฐ์ ํ, ํด๋น ๊ฑด๋ฌผ์ ํด๋ฆญํ ํ sbmall ์ด๋ sbm ๋ฒํผ์ ๋๋ฅด๋ฉด ๋จ.
* json๋ฅผ ํ์ฑํ ํ ์ด๋ ๋ก ๋ณํํ๋ get, set ์ ๊ฐ issue.cs, sbmissue.cs, sbmall.cs ์ ์ง์ ๋์ด ์์.
*
*/
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Threading;
namespace WpfApp1
{
public partial class MainWindow : Window
{
SbmWork sbmWork = new SbmWork(); // ๋ํดํธ sbm๋ง ์ฒ๋ฆฌํจ
SbmAllWork sbmAllWork = new SbmAllWork(); // ํ ๊ฑด๋ฌผ ๋ด์ ์๋ sbm ์ ์ฒด ์ฒ๋ฆฌํจ
List<UrlComponent> urlCollecter = new List<UrlComponent>(); // prjid, bldid, zoneCode, bldVer
AllDownSbm alldownSbm = AllDownSbm.GetInstance();
public MainWindow()
{
InitializeComponent();
}
private async void Refresh_Button_Click(object sender, RoutedEventArgs e)
{
string url = "http://indoormap.seoul.go.kr/app/openapi/seoulcity/svcproject/list.json";
string json = await RequestJson(url);
this.ParseJson(json, 0);
}
private async void Sbm_Button_Click(object sender, RoutedEventArgs e)
{
if (IssueListView.SelectedItems.Count != 0)
{
string prjid = urlCollecter[0].prjid;
string url = "http://indoormap.seoul.go.kr/app/openapi/seoulcity/svcmanage/getSvcBuildingInfo.json?prjId=" + prjid;
string json = await RequestJson(url);
this.ParseJson(json, 1);
}
}//sbm pars
private async void SbmAll_Button_Click(object sender, RoutedEventArgs e)
{
if (IssueListView.SelectedItems.Count != 0)
{
string prjid = urlCollecter[0].prjid;
string bldid = urlCollecter[0].bldid;
string url = "http://indoormap.seoul.go.kr/app/openapi/seoulcity/svcmanage/getSvcFloorList.json?prjId=" + prjid + "&bldId=" + bldid;
string json = await RequestJson(url);
this.ParseJson(json, 2);
}
}//sbm_all pars
private async void AllDown_Button_Click(object sender, RoutedEventArgs e)
{
foreach(Issue items in IssueListView.Items.SourceCollection)
{
urlCollecter.Clear();
UrlComponent urlComponent = new UrlComponent();
urlComponent.bldid = items.bldId;
urlComponent.prjid = items.PrjId.ToString();
urlComponent.zcode = items.code.ToString();
urlComponent.bldVer = items.bldVer.ToString();
urlCollecter.Add(urlComponent);
while (alldownSbm.checkThreadPoint()) { }
alldownSbm.upThreadPoint();
string url = "http://indoormap.seoul.go.kr/app/openapi/seoulcity/svcmanage/getSvcFloorList.json?prjId="
+ items.PrjId + "&bldId=" + items.bldId;
string json = await RequestJson(url);
this.ParseJson(json, 2);
}
List<string> list = new List<string>();
list = alldownSbm.getErrorList();
System.IO.File.WriteAllLines(@"C:\Dev\texture\ErrorSbm.txt", list);
}// all download
private async Task<string> RequestJson(String url)
{
HttpClient client = new HttpClient();
Task<string> getStringTask = client.GetStringAsync(url);
string result = await getStringTask;
return result;
}
private void ParseJson(String json, int flag)
{
int num = 0; // ๋จ์ ๋ฒํธ ๋งค๊น. ์์ ์ Issue.cs ์์ ํ ๊ฒ
if (flag == 0)
{
List<Issue> issues = new List<Issue>();
JObject obj = JObject.Parse(json);
JArray array = JArray.Parse(obj["result"].ToString());
foreach (JObject itemObj in array)
{
num++;
Issue issue = new Issue();
issue.idnum = num;
issue.bldId = itemObj["buildingInfo"]["bldId"].ToString();
issue.bldVer = itemObj["buildingInfo"]["bldVer"].ToString();
issue.PrjId = itemObj["prjId"].ToString();
issue.fileId = itemObj["file"]["fileId"].ToString();
issue.nameKr = itemObj["nameKr"].ToString();
issue.code = itemObj["zoneInfo"]["code"].ToString();
issues.Add(issue);
}
IssueListView.ItemsSource = issues;
} // ๊ฑด๋ฌผ๋ชฉ๋ก ๋ถ๋ฌ์ฌ ๋.
else if (flag == 1)
{
List<SbmIssue> sbmIssues = new List<SbmIssue>();
JObject sObj = JObject.Parse(json);
JArray sbArray = JArray.Parse(sObj["result"].ToString());
foreach (JObject itemObj in sbArray)
{
SbmIssue sbmIssue = new SbmIssue();
sbmIssue.floorId = itemObj["defaultFloorInfo"]["floorId"].ToString();
sbmIssue.sbmFile = itemObj["defaultFloorInfo"]["sbmFile"].ToString();
sbmIssue.prjCode = itemObj["projectInfo"]["code"].ToString();
sbmIssue.zcode = itemObj["zoneInfo"]["code"].ToString();
sbmIssue.bcode = itemObj["code"].ToString();
sbmIssue.bldVer = itemObj["bldVer"].ToString();
sbmIssues.Add(sbmIssue);
}
sbmWork.SbmDownload(sbmIssues);
}//sbm ๊ด๋ จ ์ ๋ณด ๋ถ๋ฌ์ฌ ๋.
else if (flag == 2)
{
List<SbmAll> sbmallCollect = new List<SbmAll>();
JObject sAllObj = JObject.Parse(json);
JArray saArray = JArray.Parse(sAllObj["floorInfoList"].ToString());
foreach (JObject itemObj in saArray)
{
SbmAll sbmall = new SbmAll();
sbmall.floorId = itemObj["floorId"].ToString();
sbmall.bcode = itemObj["buildingInfo"]["code"].ToString();
sbmall.namekr = itemObj["buildingInfo"]["nameKr"].ToString();
sbmall.sbmFile = itemObj["sbmFile"].ToString();
sbmallCollect.Add(sbmall);
}
sbmAllWork.SbmAllDownload(sbmallCollect, urlCollecter);
}//ํ ๊ฑด๋ฌผ๋ด ์ ์ฒด ์ธต sbm๊ด๋ จ ์ ๋ณด ๋ถ๋ฌ์ฌ ๋.
}
private void IssueListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (IssueListView.SelectedItems.Count != 0)
{
urlCollecter.Clear();
UrlComponent urlComponent = new UrlComponent();
var selectedItem = ((Issue)IssueListView.SelectedItem);
//!notice - ๋์ค์ ํ์ํ๋ฉด urlCollecter.cs ์ ์๋ ๋ณ์๋ฅผ ๋ฃ์๊ฒ.
string selectedFileId = selectedItem.fileId.ToString();
string selectedNameKr = selectedItem.nameKr.ToString();
urlComponent.bldid = selectedItem.bldId.ToString();
urlComponent.prjid = selectedItem.PrjId.ToString();
urlComponent.zcode = selectedItem.code.ToString();
urlComponent.bldVer = selectedItem.bldVer.ToString();
urlCollecter.Add(urlComponent);
}
}//listview eventhandler
}
}
|
๏ปฟusing UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class timer : MonoBehaviour {
private float time = 80;
public Text timerText;
// Use this for initialization
void Start () {
timerText = GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
time -= Time.deltaTime;
timerText.text = string.Format ("{0:00}:{1:00}", time/60, time % 60);
if (time < 0) {
SceneManager.LoadScene ("end");
}
}
}
|
๏ปฟusing Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Cauldron.LadyOfTheWood
{
public class NobilityOfDuskCardController : CardController
{
public NobilityOfDuskCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController)
{
this.AllowFastCoroutinesDuringPretend = false;
this.RunModifyDamageAmountSimulationForThisCard = false;
base.SetCardProperty(base.GeneratePerTargetKey("BuffUsed", base.CharacterCard), false);
}
public override void AddTriggers()
{
//Once per turn when LadyOfTheWood would deal damage you may increase that damage by 2
Func<DealDamageAction, bool> criteria = (DealDamageAction dd) => dd.DamageSource != null && dd.DamageSource.IsSameCard(base.CharacterCard) && !base.CharacterCardController.IsPropertyTrue("BuffUsed");
base.AddTrigger<DealDamageAction>(criteria, new Func<DealDamageAction, IEnumerator>(this.IncreaseDamageDecision), TriggerType.ModifyDamageAmount, TriggerTiming.Before);
}
private DealDamageAction DealDamageAction { get; set; }
private IEnumerator IncreaseFunction()
{
//Increase the damage by 2
IEnumerator coroutine = base.GameController.IncreaseDamage(this.DealDamageAction, 2, cardSource: base.GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
yield break;
}
private IEnumerator IncreaseDamageDecision(DealDamageAction dd)
{
//Offer the player a yes/no decision if they want to increase that damage by 2
//This currently doesn't have any text on the decision other than yes/no, room for improvement
this.DealDamageAction = dd;
List<YesNoCardDecision> storedResults = new List<YesNoCardDecision>();
IEnumerator coroutine = base.GameController.MakeYesNoCardDecision(this.DecisionMaker, SelectionType.IncreaseNextDamage, base.Card, storedResults: storedResults, cardSource: base.GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
if (storedResults != null)
{
YesNoCardDecision yesNo = storedResults.First();
//if player said yes, set BuffUsed to true and Increase Damage
if (yesNo.Answer.Value == true)
{
base.CharacterCardController.SetCardPropertyToTrueIfRealAction("BuffUsed");
IEnumerator coroutine2 = this.IncreaseFunction();
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine2);
}
else
{
base.GameController.ExhaustCoroutine(coroutine2);
}
}
}
yield break;
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using Athena.Data;
using Athena.Data.Books;
using Athena.Data.Borrowings;
using Athena.Data.Series;
using Athena.Data.PublishingHouses;
using Microsoft.EntityFrameworkCore;
using Athena.Data.Categories;
using Athena.Data.StoragePlaces;
using Castle.Core.Internal;
namespace Athena {
public class ApplicationDbContext : DbContext {
static ApplicationDbContext instance;
private ApplicationDbContext() { }
public static ApplicationDbContext Instance {
get {
if (instance == null) {
instance = new ApplicationDbContext();
}
return instance;
}
}
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Series> Series { get; set; }
public DbSet<PublishingHouse> PublishingHouses { get; set; }
public DbSet<StoragePlace> StoragePlaces { get; set; }
public DbSet<Borrowing> Borrowings { get; set; }
public DbSet<Category> Categories { get; set; }
public void Seed() {
if (instance.Categories.IsNullOrEmpty()) {
var categories = Enum.GetValues(typeof(CategoryName))
.Cast<CategoryName>()
.Select(a => new Category {
Name = a
}).ToList();
instance.Categories.AddRange(categories);
instance.SaveChanges();
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlite("Data Source=athena.sqlite");
// optionsBuilder.UseLazyLoadingProxies();
optionsBuilder.EnableSensitiveDataLogging();
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder) {
base.OnModelCreating(builder);
builder.Entity<Book>().Configure();
builder.Entity<Author>()
.HasKey(a => a.Id);
builder.Entity<Series>()
.HasKey(a => a.Id);
builder.Entity<PublishingHouse>()
.HasKey(a => a.Id);
builder.Entity<StoragePlace>()
.HasKey(a => a.Id);
builder.Entity<Borrowing>()
.HasKey(a => a.Id);
builder.Entity<Category>()
.HasKey(a => a.Name);
}
}
} |
๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRB.Legacy.Repository
{
public class PropertyComparer:IEqualityComparer<Property>
{
public bool Equals(Property x, Property y)
{
return string.Equals(x.prkno, y.prkno);
}
public int GetHashCode(Property obj)
{
throw new NotImplementedException();
}
}
public class LandOwnerComparer : IEqualityComparer<LandOwner>
{
public bool Equals(LandOwner x, LandOwner y)
{
return string.Equals(x.firstname, y.firstname) &&
string.Equals(x.surname, y.surname)
&& string.Equals(x.middlename, y.middlename);
}
public int GetHashCode(LandOwner obj)
{
throw new NotImplementedException();
}
}
public partial class LandOwner
{
public override string ToString()
{
string a = "";
a += this.surname+ ", ";
a += this.firstname+ " ";
a += this.middlename;
return a;
}
}
public partial class Property
{
public override string ToString()
{
return this.blockno + " "
//+ this.plotno + " "
//+ this.houseno + " "
+ this.location + " "
+ this.lga + " "
+ this.town + " ";
}
public string status
{
get
{
if (this.Transactions.Count != 0)
{
var transaction = this.Transactions.LastOrDefault();
return transaction.prkstatus;
}
else
{
return "FREE AND CLEAR";
}
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Webshop.Data;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Webshop.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductCartController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public ProductCartController(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
// GET: api/<ProductCartController>
[HttpGet]
public async Task<List<ProductCartDto>> Get()
{
var res = await _context.ProductCarts.ToListAsync();
var mappelt = _mapper.Map<List<ProductCartDto>>(res);
return mappelt;
}
// GET api/<ProductCartController>/5
[HttpGet("{id}")]
public async Task<List<ProductCartDto>> Get(int id)
{
var res = await _context.ProductCarts.Where(c => c.cartIndex == id).ToListAsync();
if (res == null) return new List<ProductCartDto>();
var mappelt = _mapper.Map<List<ProductCartDto>>(res);
return mappelt;
}
// POST api/<ProductCartController>
[HttpPost]
public async Task<ActionResult> Post([FromBody] ProductCartDto pcnew)
{
try
{
ProductCart pc = _mapper.Map<ProductCart>(pcnew);
var cartIdCheck = _context.Carts.Where(p => p.CartId == pcnew.cartIndex);
var productIdCheck = _context.Products.Where(p => p.ProductID == pcnew.productIndex);
if (cartIdCheck == null)
{
return NoContent();
}
if (productIdCheck == null)
{
return NoContent();
}
_context.ProductCarts.Add(pc);
await _context.SaveChangesAsync();
return Ok();
}
catch (Exception ex)
{
return StatusCode(418,ex.Message);
}
}
// DELETE api/<ProductCartController>/5
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
var dbProductCart = _context.ProductCarts.SingleOrDefault(p => p.ProductCartId == id);
if (dbProductCart == null)
return NotFound("Couldnt find the item");
_context.ProductCarts.Remove(dbProductCart);
await _context.SaveChangesAsync();
return Ok();
}
}
}
|
๏ปฟ/*using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
[Category("Level")]
[TestOf(typeof(Platform))]
public class TestPlatform
{
GameObject go;
GameObject terrain;
GameObject p1;
GameObject start;
GameObject p2;
GameObject end;
Platform plat;
[SetUp]
public void SetupPlatform()
{
go = new GameObject();
go.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
terrain = new GameObject();
terrain.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
start = new GameObject();
start.transform.SetPositionAndRotation(new Vector3(0, 0, 1), Quaternion.identity);
p1 = new GameObject();
p1.transform.SetPositionAndRotation(new Vector3(0, 2, 3), Quaternion.identity);
p2 = new GameObject();
p2.transform.SetPositionAndRotation(new Vector3(5, 0, 6), Quaternion.identity);
end = new GameObject();
end.transform.SetPositionAndRotation(new Vector3(0, 0, 10), Quaternion.identity);
start.transform.parent = go.transform;
p1.transform.parent = go.transform;
p2.transform.parent = go.transform;
terrain.transform.parent = go.transform;
end.transform.parent = go.transform;
plat = go.AddComponent<Platform>();
}
[TearDown]
public void TearDownPlatform()
{
GameObject.Destroy(go);
}
[Test]
public void TestInitializationID()
{
Assert.That(plat.ID, Is.EqualTo(0));
}
[Test]
public void TestInitializationIDRedLight()
{
Assert.That(plat.ID, Is.Not.EqualTo(1));
}
[Test]
public void TestInitializationSelf()
{
Assert.That(plat.Self.GetInstanceID(), Is.EqualTo(go.GetInstanceID()));
}
[Test]
public void TestInitializationSelfRedLight()
{
Assert.That(plat.Self.GetInstanceID(), Is.Not.EqualTo(go.GetInstanceID() + 1));
}
[Test]
public void TestInitializationNext()
{
Assert.That(plat.Next, Is.Null);
}
[Test]
public void TestInitializationNextRedLight()
{
plat.SetPlatform(0, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.Reposition(plat);
Assert.That(plat.Next, Is.Not.Null);
}
[Test]
public void TestInitializationSpecial()
{
Assert.That(plat.Special, Is.Null);
}
[Test]
public void TestInitializationSpecialRedLight()
{
go.AddComponent<RevertControls>();
Assert.That(plat.Special, Is.Null);
}
[Test]
public void TestInitializationForceSpecial()
{
Assert.That(plat.Special, Is.Null);
}
[Test]
public void TestInitializationForceSpecialRedLight()
{
go.AddComponent<RevertControls>();
plat.GetSpecialPlatform();
Assert.That(plat.Special, Is.Not.Null);
}
[Test]
public void TestInitializationGetSpecial()
{
Assert.That(plat.GetSpecialPlatform(), Is.Null);
}
[Test]
public void TestInitializationGetSpecialRedLight()
{
go.AddComponent<RevertControls>();
Assert.That(plat.GetSpecialPlatform(), Is.Not.Null);
}
[Test]
public void TestInitializationDifficulty()
{
Assert.That(plat.Difficulty, Is.EqualTo(0));
}
[Test]
public void TestInitializationDifficultyRedLight()
{
Assert.That(plat.Difficulty, Is.Not.EqualTo(1));
}
[Test]
public void TestInitializationLength()
{
Assert.That(plat.Length, Is.EqualTo(0).Within(0.0001));
}
[Test]
public void TestInitializationLengthRedLight()
{
Assert.That(plat.Length, Is.Not.EqualTo(1).Within(0.0001));
}
[Test]
public void TestInitializationInverseLength()
{
Assert.That(plat.InverseLength, Is.EqualTo(0).Within(0.0001));
}
[Test]
public void TestInitializationInverseLengthRedLight()
{
Assert.That(plat.InverseLength, Is.Not.EqualTo(1).Within(0.0001));
}
[Test]
public void TestInitializationCurveValidPoints()
{
Assert.That(plat.CurveValidPoints, Is.EqualTo(BezierCurve.MinValidPoints));
}
[Test]
public void TestInitializationCurveValidPointsRedLight()
{
Assert.That(plat.CurveValidPoints, Is.Not.EqualTo(-1));
}
[Test]
public void TestInitializationDistanceBetweenLanes()
{
Assert.That(plat.DistanceBetweenLanes, Is.EqualTo(Platform.DefaultLanesDistance).Within(0.0001));
}
[Test]
public void TestInitializationDistanceBetweenLanesRedLight()
{
Assert.That(plat.DistanceBetweenLanes, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestInitializationLanes()
{
Assert.That(plat.Lanes, Is.EqualTo(Platform.DefaultLanesNumber));
}
[Test]
public void TestInitializationLanesRedLight()
{
Assert.That(plat.Lanes, Is.Not.EqualTo(0));
}
[Test]
public void TestInitializationEnd()
{
Assert.That(plat.EndLocation, Is.Null);
}
[Test]
public void TestInitializationEndRedLight()
{
plat.SetPlatform(0, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.EndLocation, Is.Not.Null);
}
[Test]
public void TestInitializationStart()
{
Assert.That(plat.StartLocation, Is.Null);
}
[Test]
public void TestInitializationStartRedLight()
{
plat.SetPlatform(0, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.StartLocation, Is.Not.Null);
}
[Test]
public void TestSetId()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.ID, Is.EqualTo(2));
}
[Test]
public void TestSetIdRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.ID, Is.Not.EqualTo(0));
}
[Test]
public void TestSetStartPosition()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.StartLocation.position.x, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.EqualTo(1).Within(0.0001));
}
[Test]
public void TestSetStartPositionRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.StartLocation.position.x, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSetStartRotation()
{
start.transform.rotation = new Quaternion(0.5547f, 0.5547f, 0.5547f, 0.2773f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.StartLocation.rotation.x, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.EqualTo(0.2773).Within(0.0001));
}
[Test]
public void TestSetStartRotationRedLight()
{
start.transform.rotation = new Quaternion(0.5547f, 0.5547f, 0.5547f, 0.2773f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.StartLocation.rotation.x, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.Not.EqualTo(-1).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.Not.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.Not.EqualTo(1).Within(0.0001));
}
[Test]
public void TestSetEnd()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.EndLocation.GetInstanceID(), Is.EqualTo(end.transform.GetInstanceID()));
}
[Test]
public void TestSetEndRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.EndLocation.GetInstanceID(), Is.Not.EqualTo(end.transform.GetInstanceID() + 1));
}
[Test]
public void TestSetLength()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.Length, Is.EqualTo(9).Within(0.0001));
}
[Test]
public void TestSetLengthRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.Length, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSetInverseLength()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.InverseLength, Is.EqualTo(0.1111).Within(0.0001));
}
[Test]
public void TestSetInverseLengthRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.That(plat.InverseLength, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSetValidPoints()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Assert.That(plat.CurveValidPoints, Is.EqualTo(4));
}
[Test]
public void TestSetValidPointsRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Assert.That(plat.CurveValidPoints, Is.Not.EqualTo(2));
}
[Test]
public void TestSet2NullException()
{
Assert.Throws<System.NullReferenceException>(() => plat.SetPlatform(3));
}
[Test]
public void TestSet2NullExceptionRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
Assert.DoesNotThrow(() => plat.SetPlatform(3));
}
[Test]
public void TestSet2Id()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.ID, Is.EqualTo(3));
}
[Test]
public void TestSet2IdRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.ID, Is.Not.EqualTo(2));
}
[Test]
public void TestSet2StartPosition()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.StartLocation.position.x, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.EqualTo(1).Within(0.0001));
}
[Test]
public void TestSet2StartPositionRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.StartLocation.position.x, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSet2StartRotation()
{
start.transform.rotation = new Quaternion(0.2f, 0.2f, 0.2f, 0.1f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.StartLocation.rotation.x, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.EqualTo(0.2773).Within(0.0001));
}
[Test]
public void TestSet2StartRotationRedLight()
{
start.transform.rotation = new Quaternion(0.2f, 0.2f, 0.2f, 0.1f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.StartLocation.rotation.x, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.Not.EqualTo(-1).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.Not.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.Not.EqualTo(1).Within(0.0001));
}
[Test]
public void TestSet2End()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.EndLocation.GetInstanceID(), Is.EqualTo(end.transform.GetInstanceID()));
}
[Test]
public void TestSetEnd2RedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.EndLocation.GetInstanceID(), Is.Not.EqualTo(end.transform.GetInstanceID() + 1));
}
[Test]
public void TestSet2Length()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.Length, Is.EqualTo(9).Within(0.0001));
}
[Test]
public void TestSet2LengthRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.Length, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSet2InverseLength()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.InverseLength, Is.EqualTo(0.1111).Within(0.0001));
}
[Test]
public void TestSet2InverseLengthRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 2);
plat.SetPlatform(3);
Assert.That(plat.InverseLength, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestSet2ValidPoints()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.SetPlatform(3);
Assert.That(plat.CurveValidPoints, Is.EqualTo(4));
}
[Test]
public void TestSet2ValidPointsRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.SetPlatform(3);
Assert.That(plat.CurveValidPoints, Is.Not.EqualTo(3));
}
[Test]
public void TestNextNullWhenGoDisabled()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
go.SetActive(false);
Assert.That(plat.Next, Is.Null);
}
[Test]
public void TestNextNullWhenPlatDisabledRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
plat.enabled = false;
Assert.That(plat.Next, Is.Null);
}
[Test]
public void TestRepositionTransformStartPosition()
{
GameObject temp = new GameObject();
temp.transform.SetPositionAndRotation(new Vector3(5, 5, 5), new Quaternion(0.5547f, 0.5547f, 0.5547f, 0.2773f));
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(temp.transform);
Assert.That(plat.StartLocation.position.x, Is.EqualTo(5).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.EqualTo(5).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.EqualTo(5).Within(0.0001));
GameObject.Destroy(temp);
}
[Test]
public void TestRepositionTransformStartPositionRedLight()
{
GameObject temp = new GameObject();
temp.transform.SetPositionAndRotation(new Vector3(5, 5, 5), new Quaternion(0.5547f, 0.5547f, 0.5547f, 0.2773f));
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(temp.transform);
Assert.That(plat.StartLocation.position.x, Is.Not.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.Not.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.Not.EqualTo(1).Within(0.0001));
GameObject.Destroy(temp);
}
[Test]
public void TestRepositionTransformStartRotation()
{
GameObject temp = new GameObject();
temp.transform.SetPositionAndRotation(new Vector3(5, 5, 5), new Quaternion(0.2773f, 0.5547f, 0.5547f, 0.5547f));
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(temp.transform);
Assert.That(plat.StartLocation.rotation.x, Is.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.EqualTo(0.5547).Within(0.0001));
GameObject.Destroy(temp);
}
[Test]
public void TestRepositionTransformStartRotationRedLight()
{
GameObject temp = new GameObject();
temp.transform.SetPositionAndRotation(new Vector3(5, 5, 5), new Quaternion(0.2773f, 0.5547f, 0.5547f, 0.5547f));
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(temp.transform);
Assert.That(plat.StartLocation.rotation.x, Is.Not.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.Not.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.Not.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.Not.EqualTo(0.2773).Within(0.0001));
GameObject.Destroy(temp);
}
[Test]
public void TestRepositionPlatformStartPosition()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
Assert.That(plat.StartLocation.position.x, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.EqualTo(0).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.EqualTo(10).Within(0.0001));
}
[Test]
public void TestRepositionPlatformStartPositionRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
Assert.That(plat.StartLocation.position.x, Is.Not.EqualTo(5).Within(0.0001));
Assert.That(plat.StartLocation.position.y, Is.Not.EqualTo(5).Within(0.0001));
Assert.That(plat.StartLocation.position.z, Is.Not.EqualTo(1).Within(0.0001));
}
[Test]
public void TestRepositionPlatformStartRotation()
{
end.transform.rotation = new Quaternion(0.2773f, 0.5547f, 0.5547f, 0.5547f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
Assert.That(plat.StartLocation.rotation.x, Is.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.EqualTo(0.5547).Within(0.0001));
}
[Test]
public void TestRepositionPlatformStartRotationRedLight()
{
end.transform.rotation = new Quaternion(0.2773f, 0.5547f, 0.5547f, 0.5547f);
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
plat.Reposition(plat);
Assert.That(plat.StartLocation.rotation.x, Is.Not.EqualTo(0.5547).Within(0.0001));
Assert.That(plat.StartLocation.rotation.y, Is.Not.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.z, Is.Not.EqualTo(0.2773).Within(0.0001));
Assert.That(plat.StartLocation.rotation.w, Is.Not.EqualTo(0.2773).Within(0.0001));
}
[Test]
public void TestCurveLength()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
BezierCurve curve = new BezierCurve();
curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
Assert.That(plat.Length, Is.EqualTo(curve.Length).Within(0.0001));
}
[Test]
public void TestCurveLengthRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
BezierCurve curve = new BezierCurve();
curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
Assert.That(plat.Length, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestCalculateCurve()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
BezierCurve curve = new BezierCurve();
curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.5f);
Vector3 v2 = curve.GetPoint(0.5f);
Assert.That(v1.x, Is.EqualTo(v2.x).Within(0.0001));
Assert.That(v1.y, Is.EqualTo(v2.y).Within(0.0001));
Assert.That(v1.z, Is.EqualTo(v2.z).Within(0.0001));
}
[Test]
public void TestCalculateCurveRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
BezierCurve curve = new BezierCurve();
curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.5f);
Vector3 v2 = curve.GetPoint(0.6f);
Assert.That(v1.x, Is.Not.EqualTo(v2.x).Within(0.0001));
Assert.That(v1.y, Is.Not.EqualTo(v2.y).Within(0.0001));
Assert.That(v1.z, Is.Not.EqualTo(v2.z).Within(0.0001));
}
[Test]
public void TestCalculateCurveStart()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.0f);
Assert.That(v1.x, Is.EqualTo(0).Within(0.0001));
Assert.That(v1.y, Is.EqualTo(0).Within(0.0001));
Assert.That(v1.z, Is.EqualTo(1).Within(0.0001));
}
[Test]
public void TestCalculateCurveStartRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.0f);
Assert.That(v1.x, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(v1.y, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(v1.z, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestCalculateCurveEnd()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(1f);
Assert.That(v1.x, Is.EqualTo(0).Within(0.0001));
Assert.That(v1.y, Is.EqualTo(0).Within(0.0001));
Assert.That(v1.z, Is.EqualTo(10).Within(0.0001));
}
[Test]
public void TestCalculateCurveEndRedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(1f);
Assert.That(v1.x, Is.Not.EqualTo(10).Within(0.0001));
Assert.That(v1.y, Is.Not.EqualTo(1).Within(0.0001));
Assert.That(v1.z, Is.Not.EqualTo(0).Within(0.0001));
}
[Test]
public void TestCalculateCurveM1()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.5f);
Vector3 v2 = plat.CalculateBezierCurve(0.2f);
Assert.That(v1.magnitude, Is.GreaterThan(v2.magnitude));
}
[Test]
public void TestCalculateCurveM1RedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.5f);
Vector3 v2 = plat.CalculateBezierCurve(0.2f);
Assert.That(v1.magnitude, Is.Not.LessThan(v2.magnitude));
}
[Test]
public void TestCalculateCurveM2()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.8f);
Vector3 v2 = plat.CalculateBezierCurve(1f);
Assert.That(v1.magnitude, Is.LessThan(v2.magnitude));
}
[Test]
public void TestCalculateCurveM2RedLight()
{
plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
Vector3 v1 = plat.CalculateBezierCurve(0.8f);
Vector3 v2 = plat.CalculateBezierCurve(1f);
Assert.That(v1.magnitude, Is.Not.GreaterThan(v2.magnitude));
}
//[Test]
//public void TestCalculateCurveMoveDifference()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// BezierCurve curve = new BezierCurve();
// curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.5f);
// Vector3 v2 = curve.GetPoint(0.5f);
// Assert.That(v1.x, Is.Not.EqualTo(v2.x).Within(0.0001));
// Assert.That(v1.y, Is.Not.EqualTo(v2.y).Within(0.0001));
// Assert.That(v1.z, Is.Not.EqualTo(v2.z).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveDifferenceRedLight()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// BezierCurve curve = new BezierCurve();
// curve.Set(start.transform.position, p1.transform.position, p2.transform.position, end.transform.position, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.5f);
// Vector3 v2 = curve.GetPoint(0.5f);
// Assert.That(v1.magnitude, Is.Not.EqualTo(v2.magnitude).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveStart()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.0f);
// Assert.That(v1.x, Is.EqualTo(0).Within(0.0001));
// Assert.That(v1.y, Is.EqualTo(0).Within(0.0001));
// Assert.That(v1.z, Is.EqualTo(1).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveStartRedLight()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.0f);
// Assert.That(v1.x, Is.Not.EqualTo(10).Within(0.0001));
// Assert.That(v1.y, Is.Not.EqualTo(1).Within(0.0001));
// Assert.That(v1.z, Is.Not.EqualTo(0).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveEnd()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(1f);
// Assert.That(v1.x, Is.EqualTo(0).Within(0.0001));
// Assert.That(v1.y, Is.EqualTo(0).Within(0.0001));
// Assert.That(v1.z, Is.EqualTo(10).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveEndRedLight()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(1f);
// Assert.That(v1.x, Is.Not.EqualTo(10).Within(0.0001));
// Assert.That(v1.y, Is.Not.EqualTo(1).Within(0.0001));
// Assert.That(v1.z, Is.Not.EqualTo(0).Within(0.0001));
//}
//[Test]
//public void TestCalculateCurveMoveM1()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.5f);
// Assert.That(v1.magnitude, Is.GreaterThan(1));
//}
//[Test]
//public void TestCalculateCurveMoveM1RedLight()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.5f);
// Assert.That(v1.magnitude, Is.Not.LessThan(1));
//}
//[Test]
//public void TestCalculateCurveMoveM2()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.8f);
// Assert.That(v1.magnitude, Is.LessThan(10));
//}
//[Test]
//public void TestCalculateCurveMoveM2RedLight()
//{
// plat.SetPlatform(2, start.transform, p1.transform, p2.transform, end.transform, terrain.transform, 4);
// Vector3 v1 = plat.CalculateBezierCurveMove(0.8f);
// Assert.That(v1.magnitude, Is.Not.GreaterThan(10));
//}
}*/ |
๏ปฟusing System;
using System.Collections.Generic;
namespace Language.Analyzer
{
public class Env : IDisposable
{
private readonly List<Dictionary<string, VarInfo>> e;
private readonly List<string> scopes;
public Env(List<Dictionary<string, VarInfo>> e, List<string> scopes)
{
this.e = e;
this.scopes = scopes;
}
public void Dispose()
{
e.RemoveAt(e.Count - 1);
scopes.RemoveAt(scopes.Count - 1);
}
}
} |
๏ปฟusing Abp.Application.Services;
using Abp.Domain.Uow;
using Abp.ObjectMapping;
using Hiraya.BIR.Notices.Dto;
using Hiraya.Domain.MongoDBCollections.Entities;
using Hiraya.MongoDb;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hiraya.BIR.Notices
{
public class NoticeAppService : IApplicationService
{
private readonly HirayaMongoDbContext _mongoData;
private readonly IObjectMapper _objectMapper;
public NoticeAppService(HirayaMongoDbContext mongoData, IObjectMapper objectMapper)
{
_mongoData = mongoData;
_objectMapper = objectMapper;
}
public async Task<NoticeDto> CreateAsync(CreateNoticeDto input)
{
var entity = _objectMapper.Map<Notice>(input);
entity.Id = Guid.NewGuid().ToString();
await _mongoData.Notices.InsertOneAsync(entity);
var dto = _objectMapper.Map<NoticeDto>(entity);
return dto;
}
}
}
|
๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using RPG.Combat;
using RPG.Core;
using RPG.Movement;
using UnityEngine;
namespace RPG.Control
{
public class AIController : MonoBehaviour
{
[SerializeField]
float chaseDistance = 5f;
[SerializeField]
float suspicionTime = 3f;
[SerializeField]
PatrolPath patrolPath;
[SerializeField]
float waypointTolerance = 0.5f;
[SerializeField]
float waypointDwellTime = 2f;
private Fighter fighter;
private GameObject player;
private Health health;
private Vector3 guardPosition;
private Mover mover;
private float timeSinceLastSawPlayer = Mathf.Infinity;
private float timeSinceArriveAtWaypoint = Mathf.Infinity;
private int currentWaypointIndex = 0;
private void Start()
{
fighter = GetComponent<Fighter>();
player = GameObject.FindWithTag("Player");
health = GetComponent<Health>();
mover = GetComponent<Mover>();
guardPosition = transform.position;
}
void Update()
{
if (health.IsDead())
{
return;
}
if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
{
AttackBehavior();
}
// Suspicious Behavior
else if (timeSinceLastSawPlayer < suspicionTime)
{
// Suspicion state
SuspicionBehavior();
}
else
{
PatrolBehavior();
}
UpdateTimers();
}
private void UpdateTimers()
{
timeSinceLastSawPlayer += Time.deltaTime;
timeSinceArriveAtWaypoint += Time.deltaTime;
}
private void PatrolBehavior()
{
Vector3 nextPosition = guardPosition;
if(patrolPath)
{
if(AtWaypoint())
{
timeSinceArriveAtWaypoint = 0;
CycleWaypoint();
}
nextPosition = GetCurrentWaypoint();
}
if(timeSinceArriveAtWaypoint > waypointDwellTime)
{
mover.StartMoveAction(nextPosition);
}
}
private Vector3 GetCurrentWaypoint()
{
return patrolPath.GetWaypoint(currentWaypointIndex);
}
private void CycleWaypoint()
{
currentWaypointIndex = patrolPath.GetNextIndex(currentWaypointIndex);
}
private bool AtWaypoint()
{
float distanceToWayPoint = Vector3.Distance(transform.position, GetCurrentWaypoint());
return distanceToWayPoint < waypointTolerance;
}
private void SuspicionBehavior()
{
GetComponent<ActionScheduler>().CancelCurrentAction();
}
private void AttackBehavior()
{
timeSinceLastSawPlayer = 0;
fighter.Attack(player);
}
private bool InAttackRangeOfPlayer()
{
return Vector3.Distance(player.transform.position, transform.position) < chaseDistance;
}
// Called by Unity Editor
private void OnDrawGizmosSelected() {
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, chaseDistance);
}
}
}
|
๏ปฟ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 Shooter
{
public partial class Difficulty : Form
{
public Difficulty()
{
InitializeComponent();
}
}
}
|
๏ปฟusing Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace NetFabric.Hyperlinq.SourceGenerator
{
static class TypeSymbolExtensions
{
public static bool IsInterface(this ITypeSymbol typeSymbol)
=> typeSymbol.TypeKind == TypeKind.Interface;
public static IEnumerable<INamedTypeSymbol> GetAllInterfaces(this ITypeSymbol typeSymbol, bool includeCurrent = true)
{
if (includeCurrent && typeSymbol.IsInterface())
yield return (INamedTypeSymbol)typeSymbol;
#pragma warning disable IDE0007 // Use implicit type
ITypeSymbol? currentTypeSymbol = typeSymbol;
#pragma warning restore IDE0007 // Use implicit type
do
{
var interfaces = currentTypeSymbol.Interfaces;
for (var index = 0; index < interfaces.Length; index++)
{
var @interface = interfaces[index];
yield return @interface;
foreach (var innerInterface in @interface.GetAllInterfaces())
yield return innerInterface;
}
currentTypeSymbol = currentTypeSymbol.BaseType;
} while (currentTypeSymbol is not null && currentTypeSymbol.SpecialType != SpecialType.System_Object);
}
public static ImmutableArray<(string, string, bool)> GetGenericsMappings(this ISymbol type, Compilation compilation)
{
var mappingAttributeSymbol = compilation.GetTypeByMetadataName("NetFabric.Hyperlinq.GeneratorMappingAttribute");
var mappings = type.GetAttributes()
.Where(attribute => SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, mappingAttributeSymbol))
.Select(attribute => (
(string)attribute.ConstructorArguments[0].Value!,
(string)attribute.ConstructorArguments[1].Value!,
(bool)attribute.ConstructorArguments[2].Value!));
return ImmutableArray.CreateRange(mappings);
}
public static string ToDisplayString(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
=> type.ToDisplayString().ApplyMappings(genericsMapping, out _);
static IEnumerable<ITypeParameterSymbol> GetTypeArguments(ITypeSymbol typeSymbol)
{
if (typeSymbol is INamedTypeSymbol namedType && namedType.IsGenericType)
{
var typeArguments = namedType.TypeArguments;
for (var index = 0; index < typeArguments.Length; index++)
{
var typeArgument = typeArguments[index];
if (typeArgument is ITypeParameterSymbol typeParameter)
yield return typeParameter;
}
}
}
static IEnumerable<(string Name, ITypeParameterSymbol TypeParameter)> MapTypeParameters(IEnumerable<ITypeParameterSymbol> typeParameters, ImmutableArray<(string, string, bool)> genericsMapping)
{
var set = new HashSet<string>();
foreach (var typeParameter in typeParameters)
{
var (isMapped, mappedTo, _) = typeParameter.IsMapped(genericsMapping);
if (isMapped)
{
if (set.Add(mappedTo))
yield return (mappedTo, typeParameter);
}
else
{
var displayString = typeParameter.ToDisplayString();
if (set.Add(displayString))
{
yield return (displayString, typeParameter);
}
}
}
}
public static IEnumerable<(string Name, string Constraints)> MappedTypeArguments(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
{
var methodParameters = GetTypeArguments(type);
return MapTypeParameters(methodParameters, genericsMapping)
.Select(typeArgument => (typeArgument.Name, typeArgument.TypeParameter.AsConstraintsStrings(genericsMapping).ToCommaSeparated()));
}
static (bool, string, bool) IsMapped(this ITypeSymbol type, ImmutableArray<(string, string, bool)> genericsMapping)
{
foreach (var (from, to, isConcreteType) in genericsMapping)
{
if (type.Name == from)
return (true, to, isConcreteType);
}
return default;
}
}
}
|
๏ปฟnamespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("HistoryManager")]
public class HistoryManager : MonoBehaviour
{
public HistoryManager(IntPtr address) : this(address, "HistoryManager")
{
}
public HistoryManager(IntPtr address, string className) : base(address, className)
{
}
public void AnimateVignetteIn()
{
base.method_8("AnimateVignetteIn", Array.Empty<object>());
}
public void AnimateVignetteOut()
{
base.method_8("AnimateVignetteOut", Array.Empty<object>());
}
public void AttackHistoryCardLoadedCallback(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("AttackHistoryCardLoadedCallback", objArray1);
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void BigCardLoadedCallback(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("BigCardLoadedCallback", objArray1);
}
public void CheckForMouseOff()
{
base.method_8("CheckForMouseOff", Array.Empty<object>());
}
public void ChildLoadedCallback(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("ChildLoadedCallback", objArray1);
}
public void CreateAttackTile(Triton.Game.Mapping.Entity attacker, Triton.Game.Mapping.Entity defender, PowerTaskList taskList)
{
object[] objArray1 = new object[] { attacker, defender, taskList };
base.method_8("CreateAttackTile", objArray1);
}
public void CreateCardPlayedTile(Triton.Game.Mapping.Entity playedEntity, Triton.Game.Mapping.Entity targetedEntity)
{
object[] objArray1 = new object[] { playedEntity, targetedEntity };
base.method_8("CreateCardPlayedTile", objArray1);
}
public void CreateFatigueTile()
{
base.method_8("CreateFatigueTile", Array.Empty<object>());
}
public void CreateTriggerTile(Triton.Game.Mapping.Entity triggeredEntity)
{
object[] objArray1 = new object[] { triggeredEntity };
base.method_8("CreateTriggerTile", objArray1);
}
public void DestroyBigCard()
{
base.method_8("DestroyBigCard", Array.Empty<object>());
}
public void DestroyHistoryTilesThatFallOffTheEnd()
{
base.method_8("DestroyHistoryTilesThatFallOffTheEnd", Array.Empty<object>());
}
public void DisableHistory()
{
base.method_8("DisableHistory", Array.Empty<object>());
}
public void FadeVignetteIn()
{
base.method_8("FadeVignetteIn", Array.Empty<object>());
}
public void FadeVignetteOut()
{
base.method_8("FadeVignetteOut", Array.Empty<object>());
}
public static HistoryManager Get()
{
return MonoClass.smethod_15<HistoryManager>(TritonHs.MainAssemblyPath, "", "HistoryManager", "Get", Array.Empty<object>());
}
public List<Vector3> GetBigCardPath()
{
Class246<Vector3> class2 = base.method_14<Class246<Vector3>>("GetBigCardPath", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public Vector3 GetBigCardPosition()
{
return base.method_11<Vector3>("GetBigCardPosition", Array.Empty<object>());
}
public HistoryCard GetCurrentBigCard()
{
return base.method_14<HistoryCard>("GetCurrentBigCard", Array.Empty<object>());
}
public HistoryEntry GetCurrentHistoryEntry()
{
return base.method_14<HistoryEntry>("GetCurrentHistoryEntry", Array.Empty<object>());
}
public int GetIndexForTile(HistoryCard tile)
{
object[] objArray1 = new object[] { tile };
return base.method_11<int>("GetIndexForTile", objArray1);
}
public int GetNumHistoryTiles()
{
return base.method_11<int>("GetNumHistoryTiles", Array.Empty<object>());
}
public Vector3 GetTopTilePosition()
{
return base.method_11<Vector3>("GetTopTilePosition", Array.Empty<object>());
}
public void HandleClickOnBigCard(HistoryCard card)
{
object[] objArray1 = new object[] { card };
base.method_8("HandleClickOnBigCard", objArray1);
}
public bool HasBigCard()
{
return base.method_11<bool>("HasBigCard", Array.Empty<object>());
}
public bool IsDeadInLaterHistoryEntry(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
return base.method_11<bool>("IsDeadInLaterHistoryEntry", objArray1);
}
public bool IsEntityTheAffectedCard(Triton.Game.Mapping.Entity entity, int index)
{
object[] objArray1 = new object[] { entity, index };
return base.method_11<bool>("IsEntityTheAffectedCard", objArray1);
}
public bool IsEntityTheLastAttacker(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
return base.method_11<bool>("IsEntityTheLastAttacker", objArray1);
}
public bool IsEntityTheLastCardPlayed(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
return base.method_11<bool>("IsEntityTheLastCardPlayed", objArray1);
}
public bool IsEntityTheLastCardTargeted(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
return base.method_11<bool>("IsEntityTheLastCardTargeted", objArray1);
}
public bool IsEntityTheLastDefender(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
return base.method_11<bool>("IsEntityTheLastDefender", objArray1);
}
public void LoadNextHistoryEntry()
{
base.method_8("LoadNextHistoryEntry", Array.Empty<object>());
}
public void MarkCurrentHistoryEntryAsCompleted()
{
base.method_8("MarkCurrentHistoryEntryAsCompleted", Array.Empty<object>());
}
public void NotifyAboutAdditionalTarget(int entityID)
{
object[] objArray1 = new object[] { entityID };
base.method_8("NotifyAboutAdditionalTarget", objArray1);
}
public void NotifyAboutArmorChanged(Triton.Game.Mapping.Entity entity, int newArmor)
{
object[] objArray1 = new object[] { entity, newArmor };
base.method_8("NotifyAboutArmorChanged", objArray1);
}
public void NotifyAboutCardDeath(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
base.method_8("NotifyAboutCardDeath", objArray1);
}
public void NotifyAboutDamageChanged(Triton.Game.Mapping.Entity entity, int damage)
{
object[] objArray1 = new object[] { entity, damage };
base.method_8("NotifyAboutDamageChanged", objArray1);
}
public void NotifyAboutPreDamage(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
base.method_8("NotifyAboutPreDamage", objArray1);
}
public void NotifyOfInput(float zPosition)
{
object[] objArray1 = new object[] { zPosition };
base.method_8("NotifyOfInput", objArray1);
}
public void NotifyOfMouseOff()
{
base.method_8("NotifyOfMouseOff", Array.Empty<object>());
}
public void NotifyOfSecretSpellFinished()
{
base.method_8("NotifyOfSecretSpellFinished", Array.Empty<object>());
}
public void OnDesatInFinished()
{
base.method_8("OnDesatInFinished", Array.Empty<object>());
}
public void OnDesatOutFinished()
{
base.method_8("OnDesatOutFinished", Array.Empty<object>());
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void OnFullScreenEffectOutFinished()
{
base.method_8("OnFullScreenEffectOutFinished", Array.Empty<object>());
}
public void OnHistoryTileComplete()
{
base.method_8("OnHistoryTileComplete", Array.Empty<object>());
}
public void OnUpdateDesatVal(float val)
{
object[] objArray1 = new object[] { val };
base.method_8("OnUpdateDesatVal", objArray1);
}
public void OnUpdateVignetteVal(float val)
{
object[] objArray1 = new object[] { val };
base.method_8("OnUpdateVignetteVal", objArray1);
}
public void OnVignetteInFinished()
{
base.method_8("OnVignetteInFinished", Array.Empty<object>());
}
public void OnVignetteOutFinished()
{
base.method_8("OnVignetteOutFinished", Array.Empty<object>());
}
public void SetAsideTileAndTryToUpdate(HistoryCard tile)
{
object[] objArray1 = new object[] { tile };
base.method_8("SetAsideTileAndTryToUpdate", objArray1);
}
public void SetBigCard(HistoryCard newCard, bool delayTimer)
{
object[] objArray1 = new object[] { newCard, delayTimer };
base.method_8("SetBigCard", objArray1);
}
public void SetBigTileSize(float size)
{
object[] objArray1 = new object[] { size };
base.method_8("SetBigTileSize", objArray1);
}
public void Start()
{
base.method_8("Start", Array.Empty<object>());
}
public void StartBigCardTimer()
{
base.method_8("StartBigCardTimer", Array.Empty<object>());
}
public void StopTimerAndKillBigCardNow()
{
base.method_8("StopTimerAndKillBigCardNow", Array.Empty<object>());
}
public void TileHistoryCardLoadedCallback(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("TileHistoryCardLoadedCallback", objArray1);
}
public void UpdateLayout()
{
base.method_8("UpdateLayout", Array.Empty<object>());
}
public bool UserIsMousedOverAHistoryTile()
{
return base.method_11<bool>("UserIsMousedOverAHistoryTile", Array.Empty<object>());
}
public static float BATTLEFIELD_CARD_DISPLAY_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "HistoryManager", "BATTLEFIELD_CARD_DISPLAY_TIME");
}
}
public List<Vector3> bigCardPath
{
get
{
Class246<Vector3> class2 = base.method_3<Class246<Vector3>>("bigCardPath");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public HistoryCard currentBigCard
{
get
{
return base.method_3<HistoryCard>("currentBigCard");
}
}
public HistoryCard currentlyMousedOverTile
{
get
{
return base.method_3<HistoryCard>("currentlyMousedOverTile");
}
}
public Texture fatigueTexture
{
get
{
return base.method_3<Texture>("fatigueTexture");
}
}
public static float HERO_POWER_DISPLAY_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "HistoryManager", "HERO_POWER_DISPLAY_TIME");
}
}
public bool historyDisabled
{
get
{
return base.method_2<bool>("historyDisabled");
}
}
public bool m_animatingDesat
{
get
{
return base.method_2<bool>("m_animatingDesat");
}
}
public bool m_animatingVignette
{
get
{
return base.method_2<bool>("m_animatingVignette");
}
}
public List<HistoryCard> m_historyTiles
{
get
{
Class267<HistoryCard> class2 = base.method_3<Class267<HistoryCard>>("m_historyTiles");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public Texture m_hunterSecretTexture
{
get
{
return base.method_3<Texture>("m_hunterSecretTexture");
}
}
public Texture m_mageSecretTexture
{
get
{
return base.method_3<Texture>("m_mageSecretTexture");
}
}
public Texture m_paladinSecretTexture
{
get
{
return base.method_3<Texture>("m_paladinSecretTexture");
}
}
public List<HistoryEntry> m_queuedEntries
{
get
{
Class267<HistoryEntry> class2 = base.method_3<Class267<HistoryEntry>>("m_queuedEntries");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public SoundDucker m_SoundDucker
{
get
{
return base.method_3<SoundDucker>("m_SoundDucker");
}
}
public static float SECRET_CARD_DISPLAY_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "HistoryManager", "SECRET_CARD_DISPLAY_TIME");
}
}
public float sizeOfBigTile
{
get
{
return base.method_2<float>("sizeOfBigTile");
}
}
public float SPACE_BETWEEN_TILES
{
get
{
return base.method_2<float>("SPACE_BETWEEN_TILES");
}
}
public static float SPELL_CARD_DISPLAY_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "HistoryManager", "SPELL_CARD_DISPLAY_TIME");
}
}
[Attribute38("HistoryManager.BigCardEntry")]
public class BigCardEntry : MonoClass
{
public BigCardEntry(IntPtr address) : this(address, "BigCardEntry")
{
}
public BigCardEntry(IntPtr address, string className) : base(address, className)
{
}
public HistoryInfo cardInfo
{
get
{
return base.method_3<HistoryInfo>("cardInfo");
}
}
public bool waitForSecretSpell
{
get
{
return base.method_2<bool>("waitForSecretSpell");
}
}
public bool wasCountered
{
get
{
return base.method_2<bool>("wasCountered");
}
}
}
[Attribute38("HistoryManager.HistoryCallbackData")]
public class HistoryCallbackData : MonoClass
{
public HistoryCallbackData(IntPtr address) : this(address, "HistoryCallbackData")
{
}
public HistoryCallbackData(IntPtr address, string className) : base(address, className)
{
}
public HistoryCard parentCard
{
get
{
return base.method_3<HistoryCard>("parentCard");
}
}
public HistoryInfo sourceCard
{
get
{
return base.method_3<HistoryInfo>("sourceCard");
}
}
}
[Attribute38("HistoryManager.HistoryEntry")]
public class HistoryEntry : MonoClass
{
public HistoryEntry(IntPtr address) : this(address, "HistoryEntry")
{
}
public HistoryEntry(IntPtr address, string className) : base(address, className)
{
}
public bool CanDuplicateAllEntities()
{
return base.method_11<bool>("CanDuplicateAllEntities", Array.Empty<object>());
}
public void DuplicateAllEntities()
{
base.method_8("DuplicateAllEntities", Array.Empty<object>());
}
public HistoryInfo GetSourceInfo()
{
return base.method_14<HistoryInfo>("GetSourceInfo", Array.Empty<object>());
}
public HistoryInfo GetTargetInfo()
{
return base.method_14<HistoryInfo>("GetTargetInfo", Array.Empty<object>());
}
public void SetAttacker(Triton.Game.Mapping.Entity attacker)
{
object[] objArray1 = new object[] { attacker };
base.method_8("SetAttacker", objArray1);
}
public void SetCardPlayed(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
base.method_8("SetCardPlayed", objArray1);
}
public void SetCardTargeted(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
base.method_8("SetCardTargeted", objArray1);
}
public void SetCardTriggered(Triton.Game.Mapping.Entity entity)
{
object[] objArray1 = new object[] { entity };
base.method_8("SetCardTriggered", objArray1);
}
public void SetDefender(Triton.Game.Mapping.Entity defender)
{
object[] objArray1 = new object[] { defender };
base.method_8("SetDefender", objArray1);
}
public void SetFatigue()
{
base.method_8("SetFatigue", Array.Empty<object>());
}
public bool ShouldDuplicateEntity(HistoryInfo info)
{
object[] objArray1 = new object[] { info };
return base.method_11<bool>("ShouldDuplicateEntity", objArray1);
}
public List<HistoryInfo> m_affectedCards
{
get
{
Class267<HistoryInfo> class2 = base.method_3<Class267<HistoryInfo>>("m_affectedCards");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public bool m_complete
{
get
{
return base.method_2<bool>("m_complete");
}
}
public HistoryInfo m_fatigueInfo
{
get
{
return base.method_3<HistoryInfo>("m_fatigueInfo");
}
}
public HistoryInfo m_lastAttacker
{
get
{
return base.method_3<HistoryInfo>("m_lastAttacker");
}
}
public HistoryInfo m_lastCardPlayed
{
get
{
return base.method_3<HistoryInfo>("m_lastCardPlayed");
}
}
public HistoryInfo m_lastCardTargeted
{
get
{
return base.method_3<HistoryInfo>("m_lastCardTargeted");
}
}
public HistoryInfo m_lastCardTriggered
{
get
{
return base.method_3<HistoryInfo>("m_lastCardTriggered");
}
}
public HistoryInfo m_lastDefender
{
get
{
return base.method_3<HistoryInfo>("m_lastDefender");
}
}
}
}
}
|
๏ปฟusing IntegradorZeusPDV.DB;
using IntegradorZeusPDV.DB.DB.Controller;
using IntegradorZeusPDV.MODEL.ClassesPDV;
namespace IntegradorZeusPDV.CONTROLLER.Funcoes
{
public class FuncoesMovimentoFiscal
{
public static MovimentoFiscal GetMovimentoFiscalPorVenda(decimal IDVenda)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM MOVIMENTOFISCAL WHERE IDVENDA = @IDVENDA";
oSQL.ParamByName["IDVENDA"] = IDVenda;
oSQL.Open();
return EntityUtil<MovimentoFiscal>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json;
using System.Collections.Generic;
using W3ChampionsStatisticService.Cache;
using W3ChampionsStatisticService.PlayerProfiles.War3InfoPlayerAkas;
using W3ChampionsStatisticService.PersonalSettings;
namespace W3ChampionsStatisticService.Services
{
public class PlayerAkaProvider
{
private static CachedData<List<PlayerAka>> PlayersAkaCache = new CachedData<List<PlayerAka>>(() => FetchAkasSync(), TimeSpan.FromMinutes(60));
public static List<PlayerAka> FetchAkasSync()
{
try
{
return FetchAkas().GetAwaiter().GetResult();
}
catch
{
return new List<PlayerAka>();
}
}
public static async Task<List<PlayerAka>> FetchAkas() // list of all Akas requested from W3info
{
var war3infoApiKey = Environment.GetEnvironmentVariable("WAR3_INFO_API_KEY"); // Change this to secret for dev
var war3infoApiUrl = "https://warcraft3.info/api/v1/aka/battle_net";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("client-id", war3infoApiKey);
var response = await httpClient.GetAsync(war3infoApiUrl);
string data = await response.Content.ReadAsStringAsync();
var stringData = JsonSerializer.Deserialize<List<PlayerAka>>(data);
return stringData;
}
public Player GetPlayerAkaData(string battleTag) // string should be received all lower-case.
{
var akas = PlayersAkaCache.GetCachedData();
var aka = akas.Find(x => x.aka == battleTag);
if (aka != null) {
return aka.player;
}
return new Player(); // returns an default values if they are not in the database
}
public Player GetAkaDataByPreferences(string battletag, PersonalSetting settings)
{
var playerAkaData = GetPlayerAkaData(battletag.ToLower());
if (settings != null && settings.AliasSettings != null) // Strip the data if the player doesn't want it shown.
{
var modifiedAka = new Player();
if (settings.AliasSettings.showAka) {
modifiedAka.name = playerAkaData.name;
modifiedAka.main_race = playerAkaData.main_race;
modifiedAka.country = playerAkaData.country;
}
if (settings.AliasSettings.showW3info)
{
modifiedAka.id = playerAkaData.id;
}
if (settings.AliasSettings.showLiquipedia)
{
modifiedAka.liquipedia = playerAkaData.liquipedia;
}
return modifiedAka;
}
return playerAkaData;
}
}
} |
๏ปฟusing Npgsql;
using Projeto.Controller;
using Projeto.Model;
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 Projeto
{
public partial class FormManutencaoPessoa : Form
{
internal NpgsqlConnection conexao = null;
public FormManutencaoPessoa(NpgsqlConnection conexao)
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
this.conexao = conexao;
}
private void FormManutencaoPessoa_Load(object sender, EventArgs e)
{
int sequencia = GetSequencia();
textBox1.Text = sequencia.ToString();
}
private int GetSequencia()
{
return ControllerPessoa.getSequenciaPessoa(conexao);
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
int codigo = int.Parse(textBox1.Text);
String nome = textBox2.Text;
int codigo_universitario = int.Parse(textBox3.Text);
ModelPessoa pessoa = new ModelPessoa();
pessoa.codigo = codigo;
pessoa.nome = nome;
pessoa.codigo_universitario = codigo_universitario;
bool incluiu = ControllerPessoa.setInclui(conexao, pessoa);
if (incluiu)
{
MessageBox.Show("Pessoa Incluida com Sucesso");
this.Close();
}
else
{
MessageBox.Show("Erro ao Incluir Pessoa");
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace RTServer
{
public class Commander
{
//Object made over the network
NetworkObject NetList = new NetworkObject();
public static RoomList rooms = new RoomList();
//Rooms
//public static Dictionary<String, List<Socket>> rooms = new Dictionary<String, List<Socket>>();
//-------------------------------//
//----Object related commands----//
//-------------------------------//
//This is used to determain the and start the tracking of new network objects
public void Instantiate(string objectName, float x, float y, float z, float rx, float ry, float rz, float rw, Socket soc){
int clientId = MainClass.GetClientId (soc); //get the id for the person who sent it
string room = MainClass.GetPlayerRoom (soc); //get the room name of the sender
int newActorId = Commander.rooms.GetRoomId(room) + NetList.AssignActorId(); //new id for the object
Vector3 position = new Vector3(x, y, z);
Quaternion rotation = new Quaternion (rx, ry, rz, rw);
NetList.add (newActorId, soc, room, clientId, objectName, position, rotation); //add the object to the the network object list
if (clientId != -1) {
string sendMsg = "/Instantiate " + objectName + " " + x + " " + y + " " + z + " " + rx + " " + ry + " " + rz + " " + rw + " " + newActorId + " " + clientId; //the string to send
MsgInRoom (room, sendMsg, null); //send the message to everyone in the room
Debug.Log ("Netowrk object created...");
Debug.Log ("Network objects in list: " + NetList.Length);
}
}
//This is used to update the stored netowrking objects data and send the update to all the cleints in the room.
public void UpdatePosition(int actorId, float x, float y, float z, float rx, float ry, float rz, float rw, Socket soc){
int id = System.Convert.ToInt32 (actorId); //this id is for the object
Vector3 position = new Vector3(x, y, z);
Quaternion rotation = new Quaternion(rx, ry, rz, rw);
NetList.SetPosition (id, position); //change the saved data for the network object
NetList.SetRotation(id, rotation);
string sendMsg = "/UpdatePosition " + id + " " + x + " " + y + " " + z + " " + rz + " " + ry + " " + rz + " " + rw; //the string to send
string room = MainClass.GetPlayerRoom (soc);//get the room name of the sender
MsgInRoom (room, sendMsg, soc);//send the message to everyone in the room
}
//this retrieves the userid for
public void GetUserId (Socket soc){
int id = MainClass.GetClientId(soc); //get the id of the client that is wanting its id
if (id != -1) {
string sendMsg = "/SetUserId " + id;//string to send
MsgToClient (sendMsg, soc);//send the string back to the client
Debug.Log ("Joined client has been given its id");
} else {
Debug.Log ("User does not exist!");
}
}
public void RemoveNetObject(string actorId, Socket soc){
int id = System.Convert.ToInt32 (actorId);
NetList.remove (id);
}
//-------------------------------//
//-----Room related commands-----//
//-------------------------------//
public void CreateRoom(string roomName, Socket makerSocket, int maxUsers)
{
if (!rooms.RoomExist(roomName))
{
rooms.Add (makerSocket, roomName, maxUsers);
MainClass.ChangeUserRoom(makerSocket, roomName);
string msg = "/JoinRoom " + roomName + " true";
MsgToClient (msg, makerSocket);
Debug.Log("Room Created: " + roomName);
}
}
public void JoinRoom(string roomName, int maxUsers, Socket joinerSocket)
{
if (MainClass.GetPlayerRoom(joinerSocket) == "")
{
if (rooms.RoomExist(roomName))
{
if (!rooms.isFull (roomName))
{
if (!rooms.ContainsUser(roomName, joinerSocket)) {
rooms.AddUserToRoom (roomName, joinerSocket);
MainClass.ChangeUserRoom (joinerSocket, roomName);
string msg = "/JoinRoom " + roomName + " false";
string msg2 = "/NewUser " + rooms.UserCount (roomName);
MsgToClient (msg, joinerSocket);
MsgInRoom (roomName, msg2, joinerSocket);
SendRoomObjects (roomName, joinerSocket);
Debug.Log ("User joined " + roomName + ". Users in room: " + rooms.UserCount (roomName));
} else {
return;
}
}
else
{
return;
}
}
else
{
int max = System.Convert.ToInt32(maxUsers);
CreateRoom(roomName, joinerSocket, max);
}
}
else
{
this.LeaveRoom(MainClass.GetPlayerRoom(joinerSocket), joinerSocket);
JoinRoom(roomName, maxUsers, joinerSocket);
}
}
public void SendRoomObjects(string roomName, Socket joinerSocket)
{
List<NetworkObjectsList> temp = NetList.GetItemsInRoom (roomName);
if (temp != null) {
for (int i = 0; i < temp.Count; i++) {
string sendMsg = "/Instantiate " + temp [i].objectName + " " + temp [i].Position.x + " " + temp [i].Position.y + " " + temp [i].Position.z + " " + temp[i].Rotation.x + " " + temp[i].Rotation.y + " " + temp[i].Rotation.z + " " + temp[i].Rotation.w + " " + temp [i].actorId + " " + temp[i].clientId;
MsgToClient (sendMsg, joinerSocket);
}
}
}
public void SendBufferedRPC(string RoomName, Socket joinerSocket){
List<string> temp = rooms.GetBufferedRPC (RoomName);
if (temp != null) {
for (int i = 0; i < temp.Count; i++) {
string sendMsg = temp[i];
MsgToClient (sendMsg, joinerSocket);
}
}
}
public void LeaveRoom(string roomName, Socket leaverSocket)
{
if (rooms.RoomExist(roomName))
{
if (rooms.ContainsUser(roomName, leaverSocket))
{
rooms.Remove(roomName, leaverSocket);
MainClass.ChangeUserRoom(leaverSocket, "");
}
else
{
return;
}
if (rooms.UserCount(roomName) != 0)
{
Debug.Log("User left " + roomName + ". Users in room: " + rooms.UserCount(roomName));
}
else
{
DeleteRoom(roomName);
}
}
}
//this is used to remove anything about a room
public void DeleteRoom(string roomName)
{
//make sure the room does exsist if not then log it
if (rooms.RoomExist (roomName)) {
//delete the room and delete any network items that deal with the room
rooms.Remove (roomName);
NetList.DeleteRoomItems (roomName);
Debug.Log ("Room " + roomName + " has been deleted");
} else {
Debug.Log ("User was not in room but tried to send a message!");
}
}
//----------------------------------//
//----Messaging related commands----//
//----------------------------------//
public void RPC(string functionName, string target, string pars, Socket senderSocket){
object[] startParams = pars.Split (',');
string roomName = MainClass.GetPlayerRoom (senderSocket);
string msg = "/RPC " + functionName + " " + pars;
if (target == "All") {
ServerRPC (functionName, startParams);
MsgInRoom (roomName, msg, null);
} else if (target == "Others") {
ServerRPC (functionName, startParams);
MsgInRoom (roomName, msg, senderSocket);
} else if (target == "MasterClient") {
Socket sendTo = rooms.GetRoomMaster(roomName);
if(sendTo != null){
MsgToClient (msg, sendTo);
}
} else if (target == "Server") {
ServerRPC (functionName, startParams);
} else if (target == "AllBuffered") {
ServerRPC (functionName, startParams);
MsgInRoom (roomName, msg, null);
rooms.AddBufferedRPC (roomName, msg);
} else if (target == "OthersBuffered") {
ServerRPC (functionName, startParams);
MsgInRoom (roomName, msg, senderSocket);
rooms.AddBufferedRPC (roomName, msg);
} else {
Debug.LogError ("RPC target was not a valid type! RPC will not be ran!");
}
}
public void ServerRPC(string function, params object[] startParams){
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
if(a.FullName != "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"){
foreach (Type t in a.GetTypes()) {
if (Attribute.GetCustomAttribute (t, typeof(RTRPC)) != null) {
object instance = Activator.CreateInstance (t);
MethodBase method = t.GetMethod (function);
if (method != null) {
ParameterInfo[] paramaters = method.GetParameters();
object[] invokeParams = RTConverter.ConvertParams(startParams, paramaters);
if(invokeParams != null){
method.Invoke(instance, invokeParams);
}
}
}
}
}
}
Console.WriteLine ("Function (" + function + ") is not in an rpc class or does not exist!");
}
//Send message to everyone in the room
public void MsgInRoom(string roomName, String msg, Socket soc)
{
List<Socket> roomList = rooms.GetRoomUsers(roomName); //create a local instance of the sockets in the room
byte[] data = Encoding.ASCII.GetBytes(msg);
//Go through the data and send the messages to each client in the room
for (int i = 0; i < roomList.Count; i++)
{
if (roomList [i] != soc || soc == null) {
roomList [i].BeginSend (data, 0, data.Length, SocketFlags.None, new AsyncCallback (SendCallBack), roomList [i]);
}
}
}
//Send message to just a spacific client
public void MsgToClient(string msg, Socket soc)
{
byte[] data = Encoding.ASCII.GetBytes(msg);
soc.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), soc);
}
//this is the actual sending function
private static void SendCallBack(IAsyncResult AR)
{
//get the socket
Socket socket = (Socket)AR.AsyncState;
//attempt to send the message unless there is an issue then log the reason
try
{
socket.EndSend(AR);
}
catch (ArgumentException e)
{
Debug.Log(e);
}
}
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
namespace RestApiEcom.Models
{
public partial class TComVille
{
public int Id { get; set; }
public string Libelle { get; set; }
public bool? IsDelete { get; set; }
}
}
|
๏ปฟusing System;
namespace ShopsRUs.Domain.Entity
{
public class Customer
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public decimal TotalAMountSpent { get; set; }
public User User { get; set; }
public long UserId { get; set; }
public DateTime LastVisited { get; set; }
}
}
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StartMenuButton : MonoBehaviour {
public Sprite inactiveImage;
public Sprite activeImage;
protected Image buttonImage;
public void Start() {
buttonImage = GetComponent<Image>();
}
public void MouseOn() {
buttonImage.sprite = activeImage;
}
public void MouseOut() {
buttonImage.sprite = inactiveImage;
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SynchWebService.Entity
{
public class Fk_District_Entity : AppHdr
{
/// <summary>
/// ๆ้ ๅฝๆฐ,ไธ็ๆไธป้ฎ
/// </summary>
public Fk_District_Entity()
: this(false)
{
}
/// <summary>
/// ๆ้ ๅฝๆฐ
/// </summary>
/// <param name="isCreateKeyField">ๆฏๅฆ่ฆๅๅปบไธป้ฎ</param>
public Fk_District_Entity(bool isCreateKeyField = false)
{
}
public string districtId { get; set; }
public string parkName { get; set; }
public string seatTotalNum { get; set; }
public string seatLeftNum { get; set; }
}
} |
๏ปฟusing System;
using System.Text;
namespace MvcMonitor.Models.Factories
{
public class ElmahErrorDtoFactory : IElmahErrorDtoFactory
{
private readonly IElmahErrorDetailDtoFactory _elmahErrorDetailDtoFactory;
public ElmahErrorDtoFactory() : this(new ElmahErrorDetailDtoFactory())
{
}
public ElmahErrorDtoFactory(IElmahErrorDetailDtoFactory elmahErrorDetailDtoFactory)
{
_elmahErrorDetailDtoFactory = elmahErrorDetailDtoFactory;
}
public ElmahErrorRequest Create(string errorId, string sourceApplicationId, string infoUrl, string errorDetails)
{
var errorDetailModel = _elmahErrorDetailDtoFactory.Create(FromBase64(errorDetails));
return new ElmahErrorRequest(errorId, sourceApplicationId, infoUrl, errorDetailModel);
}
private static string FromBase64(string errorDetails)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(errorDetails));
}
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlooringMastery.Models;
using FlooringMastery.Models.Interfaces;
using System.IO;
namespace FlooringMastery.Data
{
public class ProductRepository : IProductRepository
{
private string path = @"C:\Users\John\Desktop\SoftwareGuild\C#\Badge 2\Milestone 2\Flooring Mastery\products.txt";
public List<Product> LoadProductType()
{
List<Product> Products = new List<Product>();
if (File.Exists(path))
{
var reader = File.ReadAllLines(path);
for (int i = 1; i < reader.Length; i++)
{
var columns = reader[i].Split(',');
var product = new Product();
product.ProductType = (columns[0]);
product.CostPerSquareFoot = decimal.Parse(columns[1]);
product.LaborCostPerSquareFoot = decimal.Parse(columns[2]);
Products.Add(product);
}
}
else
{
Console.Write("Product file not found.");
Console.ReadKey();
}
return Products;
}
}
}
|
๏ปฟusing System.Collections.Generic;
using System;
using LogicBuilder.Attributes;
using System.Linq;
namespace Enrollment.Parameters.Expressions
{
public class MemberInitOperatorParameters : IExpressionParameter
{
public MemberInitOperatorParameters()
{
}
public MemberInitOperatorParameters
(
[Comments("List of member bindings")]
IList<MemberBindingItem> memberBindings,
[Comments("The Select New type leave as null (uncheck) for anonymous types. Click the function button and use the configured GetType function. Use the Assembly qualified type name for the type argument.")]
Type newType = null
)
{
MemberBindings = memberBindings.ToDictionary(m => m.Property, m => m.Selector);
NewType = newType;
}
public IDictionary<string, IExpressionParameter> MemberBindings { get; set; }
public Type NewType { get; set; }
}
} |
๏ปฟusing System;
namespace SGDE.Domain.ViewModels
{
public class WorkClosePageViewModel
{
public string openDate { get; set; }
public string closeDate { get; set; }
public string workName { get; set; }
public string workAddress { get; set; }
public int workId { get; set; }
public string clientName { get; set; }
public int clientId { get; set; }
public string workBudgetsName { get; set; }
public string workBudgetsSumFormat { get; set; }
public double workBudgetsSum { get; set; }
public double invoicesSum { get; set; }
public double? invoiceTotalPaymentSum { get; set; }
public double workCostsSum { get; set; }
public double authorizeCancelWorkersCostsSum { get; set; }
public double authorizeCancelWorkersCostsSalesSum { get; set; }
public double indirectCostsSum { get; set; }
public double total
{
get
{
return Math.Round(invoicesSum - workCostsSum - authorizeCancelWorkersCostsSum - indirectCostsSum, 2);
}
}
}
}
|
๏ปฟusing Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OscGuiControl.Controls
{
/// <summary>
/// Interaction logic for Label.xaml
/// </summary>
public partial class Label : System.Windows.Controls.Label, OscTree.IOscObject, IJsonInterface, IPropertyInterface, IContextMenu
{
static private PropertyCollection properties = null;
public PropertyCollection Properties { get => properties; }
private OscTree.Object oscObject;
public OscTree.Object OscObject => oscObject;
static private int id = 1;
private bool changed = false;
public void Taint()
{
changed = true;
}
private ContextMenu menu = new ContextMenu();
public ContextMenu Menu => menu;
static Label()
{
properties = new PropertyCollection();
properties.Add("ObjName", "Name");
properties.Add("Content", "Text");
properties.Add("FontSize");
properties.Add("Color", "Color", "Appearance");
properties.Add("BackgroundColor", "Background", "Appearance");
properties.Add("HorizontalContentAlignment", "Alignment");
properties.Add("FontWeight");
properties.Add("FontStyle");
properties.Add("Visible", "Visible", "Appearance");
}
public Label()
{
InitializeComponent();
this.Style = FindResource("LabelStyle") as Style;
oscObject = new OscTree.Object(new OscTree.Address("Label" + id++),typeof(int));
oscObject.Endpoints.Add(new OscTree.Endpoint("Text", (args) =>
{
Content = OscParser.ToString(args);
}, typeof(string)));
oscObject.Endpoints.Add(new OscTree.Endpoint("FontSize", (args) =>
{
FontSize = OscParser.ToInt(args);
}, typeof(int)));
oscObject.Endpoints.Add(new OscTree.Endpoint("Visible", (args) =>
{
Visibility = OscParser.ToBool(args) ? Visibility.Visible : Visibility.Hidden;
}, typeof(bool)));
oscObject.Endpoints.Add(new OscTree.Endpoint("TextColor", (args) =>
{
Color = OscParser.ToColor(args);
}));
oscObject.Endpoints.Add(new OscTree.Endpoint("BackgroundColor", (args) =>
{
BackgroundColor = OscParser.ToColor(args);
}));
foreach (var endpoint in oscObject.Endpoints.List)
{
var item = new MenuItem();
item.Header = "Route to " + endpoint.Key;
item.Click += (sender, e) =>
{
var route = oscObject.GetRouteString(OscTree.Route.RouteType.ID) + "/" + endpoint.Key;
System.Windows.Clipboard.SetText(route);
};
menu.Items.Add(item);
}
}
public new double FontSize
{
get { return base.FontSize; }
set
{
if (value > 0)
{
base.FontSize = value;
}
}
}
public string ObjName
{
get => OscObject.Address.Name;
set
{
OscObject.Address.Name = value;
}
}
public new string Name => ObjName;
public string ID
{
get => OscObject.Address.ID;
}
public Color Color
{
get => (Foreground as SolidColorBrush).Color;
set
{
Foreground = new SolidColorBrush(value);
}
}
public Color BackgroundColor
{
get => (Background as SolidColorBrush).Color;
set
{
Background = new SolidColorBrush(value);
}
}
public new bool IsEnabled
{
get => base.IsEnabled;
set
{
var brush = Foreground;
base.IsEnabled = value;
Foreground = brush;
}
}
public JObject ToJSON()
{
OscJsonObject result = new OscJsonObject("Label", ID, Name);
result.Content = Content;
result.Color = Color;
result.Background = BackgroundColor;
result.FontSize = FontSize;
result.FontWeight = FontWeight;
result.FontStyle = FontStyle;
result.HAlign = HorizontalContentAlignment;
result.Visible = Visibility == Visibility.Visible ? true : false;
changed = false;
return result.Get();
}
public bool LoadJSON(JObject obj)
{
OscJsonObject json = new OscJsonObject(obj);
OscObject.Address.ID = json.UID;
ObjName = json.Name;
Content = json.Content;
Color = json.Color;
BackgroundColor = json.Background;
FontSize = json.FontSize;
FontWeight = json.FontWeight;
FontStyle = json.FontStyle;
HorizontalContentAlignment = json.HAlign;
Visibility = json.Visible ? Visibility.Visible : Visibility.Hidden;
changed = false;
return true;
}
public bool HasChanged()
{
return changed;
}
}
}
|
๏ปฟ//ใใใใ๏ฝ๏ผ
//2014/11/03 ๅๅฒ
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace CREA2014
{
#region ใใผใฟ
//่ฉฆ้จ็จ๏ผ
public class Chat : SHAREDDATA
{
public Chat() : base(0) { }
public void LoadVersion0(string _name, string _message, Ecdsa256PubKey _pubKey)
{
this.Version = 0;
this.Name = _name;
this.Message = _message;
this.PubKey = _pubKey;
this.Id = Guid.NewGuid();
}
public string Name { get; private set; }
public string Message { get; private set; }
public Guid Id { get; private set; }
public Ecdsa256PubKey PubKey { get; private set; }
public Ecdsa256Signature signature { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => this.Name, (o) => this.Name = (string)o),
new MainDataInfomation(typeof(string), () => this.Message, (o) => this.Message = (string)o),
new MainDataInfomation(typeof(byte[]), 16, () => this.Id.ToByteArray(), (o) => this.Id = new Guid((byte[])o)),
new MainDataInfomation(typeof(Ecdsa256PubKey), null, () => this.PubKey, (o) => this.PubKey = (Ecdsa256PubKey)o),
new MainDataInfomation(typeof(Ecdsa256Signature), null, () => this.signature, (o) => this.signature = (Ecdsa256Signature)o),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked { get { return true; } }
public string Trip
{
get
{
if (Version != 0)
throw new NotSupportedException();
return PubKey.pubKey.ComputeTrip();
}
}
public string NameWithTrip { get { return Name + Trip; } }
public Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfoToSign
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => this.Name, (o) => this.Name = (string)o),
new MainDataInfomation(typeof(string), () => this.Message, (o) => this.Message = (string)o),
new MainDataInfomation(typeof(byte[]), 16, () => this.Id.ToByteArray(), (o) => this.Id = new Guid((byte[])o))
};
else
throw new NotSupportedException();
}
}
public void Sign(Ecdsa256PrivKey privKey)
{
signature = privKey.Sign(ToBinary(StreamInfoToSign)) as Ecdsa256Signature;
}
public bool Verify()
{
return PubKey.Verify(ToBinary(StreamInfoToSign), signature.signature);
}
}
public class ChatCollection : SHAREDDATA
{
public ChatCollection()
: base(null)
{
chats = new List<Chat>();
chatsCache = new CachedData<Chat[]>(() =>
{
lock (chatsLock)
return chats.ToArray();
});
}
private readonly object chatsLock = new object();
private List<Chat> chats;
private readonly CachedData<Chat[]> chatsCache;
public Chat[] Chats { get { return chatsCache.Data; } }
public event EventHandler<Chat> ChatAdded = delegate { };
public event EventHandler<Chat> ChatRemoved = delegate { };
public bool Contains(Guid id)
{
lock (chatsLock)
return chats.FirstOrDefault((elem) => elem.Id.Equals(id)) != null;
}
public bool AddChat(Chat chat)
{
lock (chatsLock)
{
if (chats.Contains(chat))
return false;
this.ExecuteBeforeEvent(() =>
{
chats.Add(chat);
chatsCache.IsModified = true;
}, chat, ChatAdded);
return true;
}
}
public bool RemoveChat(Chat chat)
{
lock (chatsLock)
{
if (!chats.Contains(chat))
return false;
this.ExecuteBeforeEvent(() =>
{
chats.Remove(chat);
chatsCache.IsModified = true;
}, chat, ChatRemoved);
return true;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get { throw new NotImplementedException(); }
}
}
#region ่ฆ็ด้ขๆฐ
public abstract class HASHBASE : SHAREDDATA, IComparable<HASHBASE>, IEquatable<HASHBASE>, IComparable
{
public HASHBASE()
{
if (SizeBit % 8 != 0)
throw new InvalidDataException("invalid_size_bit");
FromHash(new byte[SizeByte]);
}
public HASHBASE(string stringHash)
{
if (SizeBit % 8 != 0)
throw new InvalidDataException("invalid_size_bit");
FromHash(stringHash.FromHexstringToBytes());
if (hash.Length != SizeByte)
throw new InvalidOperationException("invalid_length_hash");
}
public HASHBASE(byte[] data)
{
if (SizeBit % 8 != 0)
throw new InvalidDataException("invalid_size_bit");
hash = ComputeHash(data);
if (hash.Length != SizeByte)
throw new InvalidOperationException("invalid_length_hash");
}
public byte[] hash { get; private set; }
public abstract int SizeBit { get; }
protected abstract byte[] ComputeHash(byte[] data);
public int SizeByte { get { return SizeBit / 8; } }
public T XOR<T>(T other) where T : HASHBASE
{
byte[] xorBytes = new byte[SizeByte];
for (int i = 0; i < SizeByte; i++)
xorBytes[i] = (byte)(hash[i] ^ other.hash[i]);
return HASHBASE.FromHash<T>(xorBytes);
}
public void FromHash(byte[] _hash)
{
if (_hash.Length != SizeByte)
throw new InvalidOperationException("invalid_length_hash");
hash = _hash;
}
public static T FromHash<T>(byte[] hash) where T : HASHBASE
{
T t = Activator.CreateInstance(typeof(T)) as T;
t.FromHash(hash);
return t;
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(byte[]), SizeByte, () => hash, (o) => hash = (byte[])o),
};
}
}
public override bool Equals(object obj) { return (obj as HASHBASE).Pipe((o) => o != null && Equals(o)); }
public bool Equals(HASHBASE other) { return hash.BytesEquals(other.hash); }
public int CompareTo(object obj) { return hash.BytesCompareTo((obj as HASHBASE).hash); }
public int CompareTo(HASHBASE other) { return hash.BytesCompareTo(other.hash); }
public override int GetHashCode()
{
//ๆๅท้่ฒจใซใใใใใใทใฅๅคใฏๅ
้ ญใซ0ใไธฆใถใใจใใใใฎใง
//ใใใใฎไธฆใณใใฐใใฐใใซใใฆใใ่จ็ฎใใใใจใซใใ
//ใใฎๅฎ่ฃ
ใงใ0ใฎๆฐใฏๅคใใใชใใฎใงๅคใๅใใฎใใใใใชใ
//ๅ
้ ญใฎ0ใๅใ้คใใใใฎใใ่จ็ฎใใในใใชใฎใใใใใชใ
//2014/04/06 ๅธธใซๅไธใฎไธฆใณใงใชใใใฐๅคใๆฏๅๅคใใฃใฆใใพใ
byte[] randomBytes = hash.ArrayRandomCache();
byte[] intByte = new byte[4];
CirculatedInteger c = new CirculatedInteger(0, intByte.Length);
for (int i = 0; i < randomBytes.Length; i++, c.Next())
intByte[c.value] = intByte[c.value] ^= randomBytes[i];
int h = 0;
for (int i = 0; i < 4; i++)
h |= intByte[i] << (i * 8);
return h;
}
public override string ToString() { return hash.ToHexstring(); }
}
public class Sha256Hash : HASHBASE
{
public Sha256Hash() : base() { }
public Sha256Hash(string stringHash) : base(stringHash) { }
public Sha256Hash(byte[] data) : base(data) { }
public override int SizeBit { get { return 256; } }
protected override byte[] ComputeHash(byte[] data) { return data.ComputeSha256(); }
}
public class Sha256Sha256Hash : HASHBASE
{
public Sha256Sha256Hash() : base() { }
public Sha256Sha256Hash(string stringHash) : base(stringHash) { }
public Sha256Sha256Hash(byte[] data) : base(data) { }
public override int SizeBit { get { return 256; } }
protected override byte[] ComputeHash(byte[] data) { return data.ComputeSha256().ComputeSha256(); }
}
public class Sha256Ripemd160Hash : HASHBASE
{
public Sha256Ripemd160Hash() : base() { }
public Sha256Ripemd160Hash(string stringHash) : base(stringHash) { }
public Sha256Ripemd160Hash(byte[] data) : base(data) { }
public override int SizeBit { get { return 160; } }
protected override byte[] ComputeHash(byte[] data) { return data.ComputeSha256().ComputeRipemd160(); }
}
public class X14Hash : HASHBASE
{
public X14Hash() : base() { }
public X14Hash(string stringHash) : base(stringHash) { }
public X14Hash(byte[] data) : base(data) { }
public override int SizeBit { get { return 256; } }
protected override byte[] ComputeHash(byte[] data)
{
return data.ComputeBlake512().ComputeBmw512().ComputeGroestl512().ComputeSkein512().ComputeJh512().ComputeKeccak512().ComputeLuffa512().ComputeCubehash512().ComputeShavite512().ComputeSimd512().ComputeEcho512().ComputeFugue512().ComputeHamsi512().ComputeShabal512().Decompose(0, SizeByte);
}
}
public class X15Hash : HASHBASE
{
public X15Hash() : base() { }
public X15Hash(string stringHash) : base(stringHash) { }
public X15Hash(byte[] data) : base(data) { }
public string tripKey { get; private set; }
public string trip { get; private set; }
public override int SizeBit { get { return 256; } }
protected override byte[] ComputeHash(byte[] data)
{
tripKey = Convert.ToBase64String(data.ComputeSha1());
byte[] sha1base64shiftjissha1 = Encoding.GetEncoding("Shift-JIS").GetBytes(tripKey).ComputeSha1();
tripKey += "#";
trip = "โ" + Convert.ToBase64String(sha1base64shiftjissha1).Substring(0, 12).Replace('+', '.');
byte[] blake512 = data.ComputeBlake512();
byte[] bmw512 = data.ComputeBmw512();
byte[] groestl512 = data.ComputeGroestl512();
byte[] skein512 = data.ComputeSkein512();
byte[] jh512 = data.ComputeJh512();
byte[] keccak512 = data.ComputeKeccak512();
byte[] luffa512 = data.ComputeLuffa512();
byte[] cubehash512 = sha1base64shiftjissha1.Combine(blake512).ComputeCubehash512();
byte[] shavite512 = bmw512.Combine(groestl512).ComputeShavite512();
byte[] simd512 = skein512.Combine(jh512).ComputeSimd512();
byte[] echo512 = keccak512.Combine(luffa512).ComputeEcho512();
byte[] fugue512 = cubehash512.Combine(shavite512).ComputeFugue512();
byte[] hamsi512 = simd512.Combine(echo512).ComputeHamsi512();
byte[] shabal512 = fugue512.Combine(hamsi512).ComputeShabal512();
return shavite512.Decompose(0, SizeByte);
}
}
public class Creahash : HASHBASE
{
public Creahash() : base() { }
public Creahash(string stringHash) : base(stringHash) { }
public Creahash(byte[] data) : base(data) { }
public string tripKey { get; private set; }
public string trip { get; private set; }
public override int SizeBit { get { return 256; } }
protected override byte[] ComputeHash(byte[] data)
{
tripKey = Convert.ToBase64String(data.ComputeSha1());
byte[] sha1base64shiftjissha1 = Encoding.GetEncoding("Shift-JIS").GetBytes(tripKey).ComputeSha1();
tripKey += "#";
trip = "โ" + Convert.ToBase64String(sha1base64shiftjissha1).Substring(0, 12).Replace('+', '.');
byte[] blake512 = data.ComputeBlake512();
byte[] bmw512 = data.ComputeBmw512();
byte[] groestl512 = data.ComputeGroestl512();
byte[] skein512 = data.ComputeSkein512();
byte[] jh512 = data.ComputeJh512();
byte[] keccak512 = data.ComputeKeccak512();
byte[] luffa512 = data.ComputeLuffa512();
byte[] cubehash512 = data.ComputeCubehash512();
byte[] shavite512 = data.ComputeShavite512();
byte[] simd512 = data.ComputeSimd512();
byte[] echo512 = data.ComputeEcho512();
byte[] fugue512 = data.ComputeFugue512();
byte[] hamsi512 = data.ComputeHamsi512();
byte[] shabal512 = data.ComputeShabal512();
byte[] hash = new byte[32];
Array.Copy(sha1base64shiftjissha1, hash, 20);
foreach (var item in new byte[][] { blake512, bmw512, groestl512, skein512, jh512, keccak512, luffa512
, cubehash512, shavite512, simd512, echo512, fugue512, hamsi512, shabal512 })
{
for (int i = 0; i < 32; i++)
hash[i] ^= item[i];
}
return hash;
}
}
#endregion
#region ้ปๅญ็ฝฒๅ
public abstract class DSAPUBKEYBASE : SHAREDDATA
{
public DSAPUBKEYBASE() : base(null) { }
public DSAPUBKEYBASE(byte[] _pubKey)
: base(null)
{
if (_pubKey.Length != SizeByte)
throw new InvalidOperationException("invalid_length_pub_key");
pubKey = _pubKey;
}
public byte[] pubKey { get; private set; }
public abstract int SizeByte { get; }
public abstract bool Verify(byte[] data, byte[] signature);
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(byte[]), SizeByte, () => pubKey, (o) => pubKey = (byte[])o),
};
}
}
}
//<ๆชไฟฎๆญฃ>Signใฎๆปใๅคใใธใงใใชใใฏใซ
public abstract class DSAPRIVKEYBASE : SHAREDDATA
{
public DSAPRIVKEYBASE() : base(null) { }
public DSAPRIVKEYBASE(byte[] _privKey)
: base(null)
{
if (_privKey.Length != SizeByte)
throw new InvalidOperationException("invalid_length_priv_key");
privKey = _privKey;
}
public byte[] privKey { get; private set; }
public abstract int SizeByte { get; }
public abstract DSASIGNATUREBASE Sign(byte[] data);
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(byte[]), SizeByte, () => privKey, (o) => privKey = (byte[])o),
};
}
}
}
public abstract class DSAKEYPAIRBASE<DsaPubKeyType, DsaPrivKeyType> : SHAREDDATA
where DsaPubKeyType : DSAPUBKEYBASE
where DsaPrivKeyType : DSAPRIVKEYBASE
{
public DSAKEYPAIRBASE() : base(null) { }
public DsaPubKeyType pubKey { get; protected set; }
public DsaPrivKeyType privKey { get; protected set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(DsaPubKeyType), null, () => pubKey, (o) => pubKey = (DsaPubKeyType)o),
new MainDataInfomation(typeof(DsaPrivKeyType), null, () => privKey, (o) => privKey = (DsaPrivKeyType)o),
};
}
}
}
public abstract class DSASIGNATUREBASE : SHAREDDATA
{
public DSASIGNATUREBASE() : base(null) { }
public DSASIGNATUREBASE(byte[] _signature)
: base(null)
{
if (_signature.Length != SizeByte)
throw new InvalidOperationException("invalid_length_signature");
signature = _signature;
}
public byte[] signature { get; private set; }
public abstract int SizeByte { get; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(byte[]), SizeByte, () => signature, (o) => signature = (byte[])o),
};
}
}
}
public class Ecdsa256PubKey : DSAPUBKEYBASE
{
public Ecdsa256PubKey() : base() { }
public Ecdsa256PubKey(byte[] _pubKey) : base(_pubKey) { }
public override int SizeByte { get { return 72; } }
public override bool Verify(byte[] data, byte[] signature)
{
try
{
return data.VerifyEcdsa(signature, pubKey);
}
catch (Exception) { }
return false;
}
}
public class Ecdsa256PrivKey : DSAPRIVKEYBASE
{
public Ecdsa256PrivKey() : base() { }
public Ecdsa256PrivKey(byte[] _privKey) : base(_privKey) { }
public override int SizeByte { get { return 104; } }
public override DSASIGNATUREBASE Sign(byte[] data) { return new Ecdsa256Signature(data.SignEcdsaSha256(privKey)); }
}
public class Ecdsa256KeyPair : DSAKEYPAIRBASE<Ecdsa256PubKey, Ecdsa256PrivKey>
{
public Ecdsa256KeyPair() : this(false) { }
public Ecdsa256KeyPair(bool isCreate)
{
if (isCreate)
{
CngKey ck = CngKey.Create(CngAlgorithm.ECDsaP256, null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport });
pubKey = new Ecdsa256PubKey(ck.Export(CngKeyBlobFormat.EccPublicBlob));
privKey = new Ecdsa256PrivKey(ck.Export(CngKeyBlobFormat.EccPrivateBlob));
}
}
}
public class Ecdsa256Signature : DSASIGNATUREBASE
{
public Ecdsa256Signature() : base() { }
public Ecdsa256Signature(byte[] _signature) : base(_signature) { }
public override int SizeByte { get { return 64; } }
}
public static class Secp256k1Utility
{
public static Secp256k1PubKey<HashType> Recover<HashType>(byte[] data, byte[] signature) where HashType : HASHBASE
{
var r = new byte[32];
var s = new byte[32];
Buffer.BlockCopy(signature, 1, r, 0, 32);
Buffer.BlockCopy(signature, 33, s, 0, 32);
var recId = signature[0] - 27;
ECDsaSigner signer = new ECDsaSigner();
byte[] hash = (Activator.CreateInstance(typeof(HashType), data) as HashType).hash;
ECPoint publicKey = signer.RecoverFromSignature(hash, r.ToBigIntegerUnsigned(true), s.ToBigIntegerUnsigned(true), recId);
return new Secp256k1PubKey<HashType>(publicKey.EncodePoint(false));
}
public static bool RecoverAndVerify<HashType>(byte[] data, byte[] signature) where HashType : HASHBASE
{
var r = new byte[32];
var s = new byte[32];
Buffer.BlockCopy(signature, 1, r, 0, 32);
Buffer.BlockCopy(signature, 33, s, 0, 32);
var recId = signature[0] - 27;
ECDsaSigner signer = new ECDsaSigner();
byte[] hash = (Activator.CreateInstance(typeof(HashType), data) as HashType).hash;
ECPoint publicKey = signer.RecoverFromSignature(hash, r.ToBigIntegerUnsigned(true), s.ToBigIntegerUnsigned(true), recId);
return signer.VerifySignature(publicKey, hash, r.ToBigIntegerUnsigned(true), s.ToBigIntegerUnsigned(true));
}
}
public class Secp256k1PubKey<HashType> : DSAPUBKEYBASE where HashType : HASHBASE
{
public Secp256k1PubKey() : base() { }
public Secp256k1PubKey(byte[] _pubKey) : base(_pubKey) { }
public override int SizeByte { get { return 65; } }
public override bool Verify(byte[] data, byte[] signature)
{
var r = new byte[32];
var s = new byte[32];
Buffer.BlockCopy(signature, 1, r, 0, 32);
Buffer.BlockCopy(signature, 33, s, 0, 32);
var recId = signature[0] - 27;
ECDsaSigner signer = new ECDsaSigner();
byte[] hash = (Activator.CreateInstance(typeof(HashType), data) as HashType).hash;
ECPoint publicKey = ECPoint.DecodePoint(pubKey);
return signer.VerifySignature(publicKey, hash, r.ToBigIntegerUnsigned(true), s.ToBigIntegerUnsigned(true));
}
}
public class Secp256k1PrivKey<HashType> : DSAPRIVKEYBASE where HashType : HASHBASE
{
public Secp256k1PrivKey() : base() { }
public Secp256k1PrivKey(byte[] _pribKey) : base(_pribKey) { }
public override int SizeByte { get { return 32; } }
public override DSASIGNATUREBASE Sign(byte[] data)
{
ECDsaSigner signer = new ECDsaSigner();
byte[] hash = (Activator.CreateInstance(typeof(HashType), data) as HashType).hash;
BigInteger privateKey = privKey.ToBigIntegerUnsigned(true);
BigInteger[] signature = signer.GenerateSignature(privateKey, hash);
int? recId = null;
ECPoint publicKey = Secp256k1.G.Multiply(privateKey);
for (var i = 0; i < 4 && recId == null; i++)
{
ECPoint Q = signer.RecoverFromSignature(hash, signature[0], signature[1], i);
if (Q.X == publicKey.X && Q.Y == publicKey.Y)
recId = i;
}
if (recId == null)
throw new Exception("Did not find proper recid");
byte[] sig = new byte[65];
sig[0] = (byte)(27 + recId);
byte[] rByteArray = signature[0].ToByteArrayUnsigned(true);
byte[] sByteArray = signature[1].ToByteArrayUnsigned(true);
Buffer.BlockCopy(rByteArray, 0, sig, 1 + (32 - rByteArray.Length), rByteArray.Length);
Buffer.BlockCopy(sByteArray, 0, sig, 33 + (32 - sByteArray.Length), sByteArray.Length);
return new Secp256k1Signature(sig);
}
}
public class Secp256k1KeyPair<HashType> : DSAKEYPAIRBASE<Secp256k1PubKey<HashType>, Secp256k1PrivKey<HashType>> where HashType : HASHBASE
{
public Secp256k1KeyPair() : this(false) { }
public Secp256k1KeyPair(bool isCreate)
{
if (isCreate)
{
byte[] privKeyBytes = new byte[32];
using (RNGCryptoServiceProvider rngcsp = new RNGCryptoServiceProvider())
rngcsp.GetBytes(privKeyBytes);
BigInteger privateKey = privKeyBytes.ToBigIntegerUnsigned(true);
ECPoint publicKey = Secp256k1.G.Multiply(privateKey);
pubKey = new Secp256k1PubKey<HashType>(publicKey.EncodePoint(false));
privKey = new Secp256k1PrivKey<HashType>(privKeyBytes);
}
}
}
public class Secp256k1Signature : DSASIGNATUREBASE
{
public Secp256k1Signature() : base() { }
public Secp256k1Signature(byte[] _signature) : base(_signature) { }
public override int SizeByte { get { return 65; } }
}
#endregion
#region ๅฃๅบง
public interface IAccount
{
string iName { get; }
string iDescription { get; }
string iAddress { get; }
CurrencyUnit iUsableAmount { get; }
CurrencyUnit iUnusableAmount { get; }
CurrencyUnit iUnconfirmedAmount { get; }
CurrencyUnit iUsableAmountWithUnconfirmed { get; }
CurrencyUnit iUnusableAmountWithUnconfirmed { get; }
event EventHandler iAccountChanged;
}
public interface IAccountHolder
{
IAccount[] iAccounts { get; }
event EventHandler<IAccount> iAccountAdded;
event EventHandler<IAccount> iAccountRemoved;
event EventHandler iAccountHolderChanged;
void iAddAccount(IAccount iAccount);
void iRemoveAccount(IAccount iAccount);
}
public interface IAnonymousAccountHolder : IAccountHolder { }
public interface IPseudonymousAccountHolder : IAccountHolder
{
DSAPRIVKEYBASE iPrivKey { get; }
DSAPUBKEYBASE iPubKey { get; }
string iName { get; }
string iSign { get; }
}
public interface IAccountHolders
{
IAnonymousAccountHolder iAnonymousAccountHolder { get; }
IPseudonymousAccountHolder[] iPseudonymousAccountHolders { get; }
event EventHandler<IAccountHolder> iAccountHolderAdded;
event EventHandler<IAccountHolder> iAccountHolderRemoved;
void iAddAccountHolder(IPseudonymousAccountHolder iPseudonymousAccountHolder);
void iDeleteAccountHolder(IPseudonymousAccountHolder iPseudonymousAccountHolder);
}
public interface IAccountHoldersFactory
{
IAccount CreateAccount(string name, string description);
IPseudonymousAccountHolder CreatePseudonymousAccountHolder(string name);
}
public class Account : SHAREDDATA, IAccount
{
public Account() : base(0) { accountStatus = new AccountStatus(); }
public void LoadVersion0(string _name, string _description)
{
Version = 0;
LoadCommon(_name, _description);
ecdsa256KeyPair = new Ecdsa256KeyPair(true);
}
public void LoadVersion1(string _name, string _description)
{
Version = 1;
LoadCommon(_name, _description);
secp256k1KeyPair = new Secp256k1KeyPair<Sha256Hash>(true);
}
private void LoadCommon(string _name, string _description)
{
name = _name;
description = _description;
}
public AccountStatus accountStatus { get; private set; }
private string name;
private string description;
private Ecdsa256KeyPair ecdsa256KeyPair;
private Secp256k1KeyPair<Sha256Hash> secp256k1KeyPair;
public string Name
{
get { return name; }
set
{
if (name != value)
this.ExecuteBeforeEvent(() => name = value, AccountChanged);
}
}
public string Description
{
get { return description; }
set
{
if (description != value)
this.ExecuteBeforeEvent(() => description = value, AccountChanged);
}
}
public Ecdsa256KeyPair Ecdsa256KeyPair
{
get
{
if (Version != 0)
throw new NotSupportedException();
return ecdsa256KeyPair;
}
}
public Secp256k1KeyPair<Sha256Hash> Secp256k1KeyPair
{
get
{
if (Version != 1)
throw new NotSupportedException();
return secp256k1KeyPair;
}
}
public DSAPUBKEYBASE pubKey
{
get
{
if (Version == 0)
return ecdsa256KeyPair.pubKey;
else if (Version == 1)
return secp256k1KeyPair.pubKey;
else
throw new NotSupportedException();
}
}
public DSAPRIVKEYBASE privKey
{
get
{
if (Version == 0)
return ecdsa256KeyPair.privKey;
else if (Version == 1)
return ecdsa256KeyPair.privKey;
else
throw new NotSupportedException();
}
}
public AccountAddress Address
{
get
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return new AccountAddress(pubKey.pubKey);
}
}
public string AddressBase58
{
get
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return Address.Base58;
}
}
public class AccountAddress
{
public AccountAddress(byte[] _publicKey) { hash = new Sha256Ripemd160Hash(_publicKey); }
public AccountAddress(Sha256Ripemd160Hash _hash) { hash = _hash; }
public AccountAddress(string _base58) { base58 = _base58; }
private Sha256Ripemd160Hash hash;
public Sha256Ripemd160Hash Hash
{
get
{
if (hash != null)
return hash;
else
{
byte[] mergedMergedBytes = Base58Encoding.Decode(base58);
byte[] mergedBytes = new byte[mergedMergedBytes.Length - 4];
Array.Copy(mergedMergedBytes, 0, mergedBytes, 0, mergedBytes.Length);
byte[] checkBytes = new byte[4];
Array.Copy(mergedMergedBytes, mergedBytes.Length, checkBytes, 0, 4);
int check1 = BitConverter.ToInt32(checkBytes, 0);
int check2 = BitConverter.ToInt32(mergedBytes.ComputeSha256().ComputeSha256(), 0);
if (check1 != check2)
throw new InvalidDataException("base58_check");
byte[] identifierBytes = new byte[3];
Array.Copy(mergedBytes, 0, identifierBytes, 0, identifierBytes.Length);
byte[] hashBytes = new byte[mergedBytes.Length - identifierBytes.Length];
Array.Copy(mergedBytes, identifierBytes.Length, hashBytes, 0, hashBytes.Length);
//base58่กจ็พใฎๅ
้ ญใCREAใซใชใใใใชใใคใ้
ๅใไฝฟใฃใฆใใ
byte[] correctIdentifierBytes = new byte[] { 84, 122, 143 };
if (!identifierBytes.BytesEquals(correctIdentifierBytes))
throw new InvalidDataException("base58_identifier");
return hash = HASHBASE.FromHash<Sha256Ripemd160Hash>(hashBytes);
}
}
set
{
hash = value;
base58 = null;
}
}
private string base58;
public string Base58
{
get
{
if (base58 != null)
return base58;
else
{
//base58่กจ็พใฎๅ
้ ญใCREAใซใชใใใใชใใคใ้
ๅใไฝฟใฃใฆใใ
byte[] identifierBytes = new byte[] { 84, 122, 143 };
byte[] hashBytes = hash.hash;
byte[] mergedBytes = new byte[identifierBytes.Length + hashBytes.Length];
Array.Copy(identifierBytes, 0, mergedBytes, 0, identifierBytes.Length);
Array.Copy(hashBytes, 0, mergedBytes, identifierBytes.Length, hashBytes.Length);
//ๅ
้ ญ4ใใคใใใไฝฟ็จใใชใ
byte[] checkBytes = mergedBytes.ComputeSha256().ComputeSha256();
byte[] mergedMergedBytes = new byte[mergedBytes.Length + 4];
Array.Copy(mergedBytes, 0, mergedMergedBytes, 0, mergedBytes.Length);
Array.Copy(checkBytes, 0, mergedMergedBytes, mergedBytes.Length, 4);
return base58 = Base58Encoding.Encode(mergedMergedBytes);
}
}
set
{
base58 = value;
hash = null;
}
}
public bool IsValid
{
get
{
if (hash != null)
return true;
else
{
try
{
Sha256Ripemd160Hash test = Hash;
return true;
}
catch (Exception)
{
return false;
}
}
}
}
public override string ToString() { return Base58; }
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => name, (o) => name = (string)o),
new MainDataInfomation(typeof(string), () => description, (o) => description = (string)o),
new MainDataInfomation(typeof(Ecdsa256KeyPair), null, () => ecdsa256KeyPair, (o) => ecdsa256KeyPair = (Ecdsa256KeyPair)o),
};
else if (Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => name, (o) => name = (string)o),
new MainDataInfomation(typeof(string), () => description, (o) => description = (string)o),
new MainDataInfomation(typeof(Secp256k1KeyPair<Sha256Hash>), null, () => secp256k1KeyPair, (o) => secp256k1KeyPair = (Secp256k1KeyPair<Sha256Hash>)o),
};
else
throw new NotSupportedException("account_main_data_info");
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked
{
get
{
if (Version == 0 || Version == 1)
return true;
else
throw new NotSupportedException("account_check");
}
}
public event EventHandler AccountChanged = delegate { };
public override string ToString() { return string.Join(":", Name, AddressBase58); }
public string iName { get { return Name; } }
public string iDescription { get { return Description; } }
public string iAddress { get { return AddressBase58; } }
public CurrencyUnit iUsableAmount { get { return accountStatus.usableAmount; } }
public CurrencyUnit iUnusableAmount { get { return accountStatus.unusableAmount; } }
public CurrencyUnit iUnconfirmedAmount { get { return accountStatus.unconfirmedAmount; } }
public CurrencyUnit iUsableAmountWithUnconfirmed { get { return accountStatus.usableAmountWithUnconfirmed; } }
public CurrencyUnit iUnusableAmountWithUnconfirmed { get { return accountStatus.unusableAmountWithUnconfirmed; } }
public event EventHandler iAccountChanged
{
add { AccountChanged += value; }
remove { AccountChanged -= value; }
}
}
public abstract class AccountHolder : SHAREDDATA, IAccountHolder
{
public AccountHolder()
: base(0)
{
accounts = new List<Account>();
accountsCache = new CachedData<Account[]>(() =>
{
lock (accountsLock)
return accounts.ToArray();
});
}
public virtual void LoadVersion0() { Version = 0; }
public virtual void LoadVersion1() { Version = 1; }
private readonly object accountsLock = new object();
private List<Account> accounts;
private readonly CachedData<Account[]> accountsCache;
public Account[] Accounts { get { return accountsCache.Data; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Account[]), 0, null, () => accountsCache.Data, (o) =>
{
accounts = ((Account[])o).ToList();
foreach (var account in accounts)
if (account.Version != 0)
throw new NotSupportedException();
}),
};
else if (Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Account[]), 1, null, () => accountsCache.Data, (o) =>
{
accounts = ((Account[])o).ToList();
foreach (var account in accounts)
if (account.Version != 1)
throw new NotSupportedException();
}),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked
{
get
{
if (Version == 0 || Version == 1)
return true;
else
throw new NotSupportedException();
}
}
public event EventHandler<Account> AccountAdded = delegate { };
protected EventHandler<Account> PAccountAdded { get { return AccountAdded; } }
public event EventHandler<Account> AccountRemoved = delegate { };
protected EventHandler<Account> PAccountRemoved { get { return AccountRemoved; } }
public event EventHandler AccountHolderChanged = delegate { };
protected EventHandler PAccountHolderChanged { get { return AccountHolderChanged; } }
public void AddAccount(Account account)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
if (account.Version != Version)
throw new ArgumentException();
lock (accountsLock)
{
if (accounts.Contains(account))
throw new InvalidOperationException("exist_account");
this.ExecuteBeforeEvent(() =>
{
accounts.Add(account);
accountsCache.IsModified = true;
}, account, AccountAdded);
}
}
public void RemoveAccount(Account account)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
if (account.Version != Version)
throw new ArgumentException();
lock (accountsLock)
{
if (!accounts.Contains(account))
throw new InvalidOperationException("not_exist_account");
this.ExecuteBeforeEvent(() =>
{
accounts.Remove(account);
accountsCache.IsModified = true;
}, account, AccountRemoved);
}
}
public IAccount[] iAccounts { get { return Accounts; } }
private Dictionary<EventHandler<IAccount>, EventHandler<Account>> iAccountAddedDict = new Dictionary<EventHandler<IAccount>, EventHandler<Account>>();
public event EventHandler<IAccount> iAccountAdded
{
add
{
EventHandler<Account> eh = (sender, e) => value(sender, e);
iAccountAddedDict.Add(value, eh);
AccountAdded += eh;
}
remove
{
EventHandler<Account> eh = iAccountAddedDict[value];
iAccountAddedDict.Remove(value);
AccountAdded -= eh;
}
}
private Dictionary<EventHandler<IAccount>, EventHandler<Account>> iAccountRemovedDict = new Dictionary<EventHandler<IAccount>, EventHandler<Account>>();
public event EventHandler<IAccount> iAccountRemoved
{
add
{
EventHandler<Account> eh = (sender, e) => value(sender, e);
iAccountRemovedDict.Add(value, eh);
AccountRemoved += eh;
}
remove
{
EventHandler<Account> eh = iAccountRemovedDict[value];
iAccountRemovedDict.Remove(value);
AccountRemoved -= eh;
}
}
public event EventHandler iAccountHolderChanged
{
add { AccountHolderChanged += value; }
remove { AccountHolderChanged -= value; }
}
public void iAddAccount(IAccount iAccount)
{
if (!(iAccount is Account))
throw new ArgumentException("type_mismatch");
AddAccount(iAccount as Account);
}
public void iRemoveAccount(IAccount iAccount)
{
if (!(iAccount is Account))
throw new ArgumentException("type_mismatch");
RemoveAccount(iAccount as Account);
}
}
public class AnonymousAccountHolder : AccountHolder, IAnonymousAccountHolder { }
public class PseudonymousAccountHolder : AccountHolder, IPseudonymousAccountHolder
{
public override void LoadVersion0() { throw new NotSupportedException(); }
public virtual void LoadVersion0(string _name)
{
base.LoadVersion0();
LoadCommon(_name);
ecdsa256KeyPair = new Ecdsa256KeyPair(true);
}
public override void LoadVersion1() { throw new NotSupportedException(); }
public virtual void LoadVersion1(string _name)
{
base.LoadVersion1();
LoadCommon(_name);
secp256k1KeyPair = new Secp256k1KeyPair<Sha256Hash>(true);
}
private void LoadCommon(string _name) { name = _name; }
private string name;
private Ecdsa256KeyPair ecdsa256KeyPair;
private Secp256k1KeyPair<Sha256Hash> secp256k1KeyPair;
public string Name
{
get { return name; }
set
{
if (name != value)
this.ExecuteBeforeEvent(() => name = value, PAccountHolderChanged);
}
}
public Ecdsa256KeyPair Ecdsa256KeyPair
{
get
{
if (Version != 0)
throw new NotSupportedException();
return ecdsa256KeyPair;
}
}
public Secp256k1KeyPair<Sha256Hash> Secp256k1KeyPair
{
get
{
if (Version != 1)
throw new NotSupportedException();
return secp256k1KeyPair;
}
}
public DSAPUBKEYBASE pubKey
{
get
{
if (Version == 0)
return ecdsa256KeyPair.pubKey;
else if (Version == 1)
return secp256k1KeyPair.pubKey;
else
throw new NotSupportedException();
}
}
public DSAPRIVKEYBASE privKey
{
get
{
if (Version == 0)
return ecdsa256KeyPair.privKey;
else if (Version == 1)
return secp256k1KeyPair.privKey;
else
throw new NotSupportedException();
}
}
public string Trip
{
get
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return pubKey.pubKey.ComputeTrip();
}
}
public string Sign { get { return name + Trip; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => name, (o) => name = (string)o),
new MainDataInfomation(typeof(Ecdsa256KeyPair), null, () => ecdsa256KeyPair, (o) => ecdsa256KeyPair = (Ecdsa256KeyPair)o),
});
else if (Version == 1)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => name, (o) => name = (string)o),
new MainDataInfomation(typeof(Secp256k1KeyPair<Sha256Hash>), null, () => secp256k1KeyPair, (o) => secp256k1KeyPair = (Secp256k1KeyPair<Sha256Hash>)o),
});
else
throw new NotSupportedException("pah_main_data_info");
}
}
public override string ToString() { return Sign; }
public DSAPUBKEYBASE iPubKey { get { return pubKey; } }
public DSAPRIVKEYBASE iPrivKey { get { return privKey; } }
public string iName { get { return Name; } }
public string iSign { get { return Sign; } }
}
public class AccountHolders : SHAREDDATA, IAccountHolders
{
public AccountHolders()
: base(0)
{
anonymousAccountHolder = new AnonymousAccountHolder();
pseudonymousAccountHolders = new List<PseudonymousAccountHolder>();
pseudonymousAccountHoldersCache = new CachedData<PseudonymousAccountHolder[]>(() =>
{
lock (pahsLock)
return pseudonymousAccountHolders.ToArray();
});
candidateAccountHolders = new List<PseudonymousAccountHolder>();
}
public virtual void LoadVersion0()
{
Version = 0;
anonymousAccountHolder.LoadVersion0();
}
public virtual void LoadVersion1()
{
Version = 1;
anonymousAccountHolder.LoadVersion1();
}
public AnonymousAccountHolder anonymousAccountHolder { get; private set; }
private readonly object pahsLock = new object();
private List<PseudonymousAccountHolder> pseudonymousAccountHolders;
private readonly CachedData<PseudonymousAccountHolder[]> pseudonymousAccountHoldersCache;
public PseudonymousAccountHolder[] PseudonymousAccountHolders { get { return pseudonymousAccountHoldersCache.Data; } }
public IEnumerable<AccountHolder> AllAccountHolders
{
get
{
yield return anonymousAccountHolder;
foreach (var pseudonymousAccountHolder in PseudonymousAccountHolders)
yield return pseudonymousAccountHolder;
}
}
private readonly object cahsLock = new object();
private List<PseudonymousAccountHolder> candidateAccountHolders;
public PseudonymousAccountHolder[] CandidateAccountHolders
{
get { return candidateAccountHolders.ToArray(); }
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (mswr) => new MainDataInfomation[]{
new MainDataInfomation(typeof(AnonymousAccountHolder), 0, () => anonymousAccountHolder, (o) =>
{
anonymousAccountHolder = (AnonymousAccountHolder)o;
if (anonymousAccountHolder.Version != 0)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(PseudonymousAccountHolder[]), 0, null, () => pseudonymousAccountHoldersCache.Data, (o) =>
{
pseudonymousAccountHolders = ((PseudonymousAccountHolder[])o).ToList();
foreach (var pseudonymousAccountHolder in pseudonymousAccountHolders)
if (pseudonymousAccountHolder.Version != 0)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(PseudonymousAccountHolder[]), 0, null, () => candidateAccountHolders.ToArray(), (o) =>
{
candidateAccountHolders = ((PseudonymousAccountHolder[])o).ToList();
foreach (var candidateAccountHolder in candidateAccountHolders)
if (candidateAccountHolder.Version != 0)
throw new NotSupportedException();
}),
};
else if (Version == 1)
return (mswr) => new MainDataInfomation[]{
new MainDataInfomation(typeof(AnonymousAccountHolder), 1, () => anonymousAccountHolder, (o) =>
{
anonymousAccountHolder = (AnonymousAccountHolder)o;
foreach (var pseudonymousAccountHolder in pseudonymousAccountHolders)
if (pseudonymousAccountHolder.Version != 1)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(PseudonymousAccountHolder[]), 1, null, () => pseudonymousAccountHoldersCache.Data, (o) =>
{
pseudonymousAccountHolders = ((PseudonymousAccountHolder[])o).ToList();
foreach (var pseudonymousAccountHolder in pseudonymousAccountHolders)
if (pseudonymousAccountHolder.Version != 1)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(PseudonymousAccountHolder[]), 1, null, () => candidateAccountHolders.ToArray(), (o) =>
{
candidateAccountHolders = ((PseudonymousAccountHolder[])o).ToList();
foreach (var candidateAccountHolder in candidateAccountHolders)
if (candidateAccountHolder.Version != 1)
throw new NotSupportedException();
}),
};
else
throw new NotSupportedException("account_holder_database_main_data_info");
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked
{
get
{
if (Version == 0 || Version == 1)
return true;
else
throw new NotSupportedException("account_holder_database_check");
}
}
public event EventHandler<AccountHolder> AccountHolderAdded = delegate { };
public event EventHandler<AccountHolder> AccountHolderRemoved = delegate { };
public void AddAccountHolder(PseudonymousAccountHolder ah)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
if (ah.Version != Version)
throw new ArgumentException();
lock (pahsLock)
{
if (pseudonymousAccountHolders.Contains(ah))
throw new InvalidOperationException("exist_account_holder");
if (!pseudonymousAccountHolders.Where((e) => e.Name == ah.Name).FirstOrDefault().IsNotNull().RaiseError(this.GetType(), "exist_same_name_account_holder", 5))
this.ExecuteBeforeEvent(() =>
{
pseudonymousAccountHolders.Add(ah);
pseudonymousAccountHoldersCache.IsModified = true;
}, ah, AccountHolderAdded);
}
}
public void DeleteAccountHolder(PseudonymousAccountHolder ah)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
if (ah.Version != Version)
throw new ArgumentException();
lock (pahsLock)
{
if (!pseudonymousAccountHolders.Contains(ah))
throw new InvalidOperationException("not_exist_account_holder");
this.ExecuteBeforeEvent(() =>
{
pseudonymousAccountHolders.Remove(ah);
pseudonymousAccountHoldersCache.IsModified = true;
}, ah, AccountHolderRemoved);
}
}
public void AddCandidateAccountHolder(PseudonymousAccountHolder ah)
{
lock (cahsLock)
{
if (candidateAccountHolders.Contains(ah))
throw new InvalidOperationException("exist_candidate_account_holder");
candidateAccountHolders.Add(ah);
}
}
public void DeleteCandidateAccountHolder(PseudonymousAccountHolder ah)
{
lock (cahsLock)
{
if (!candidateAccountHolders.Contains(ah))
throw new InvalidOperationException("not_exist_candidate_account_holder");
candidateAccountHolders.Remove(ah);
}
}
public void ClearCandidateAccountHolders()
{
lock (cahsLock)
candidateAccountHolders.Clear();
}
public IAnonymousAccountHolder iAnonymousAccountHolder { get { return anonymousAccountHolder; } }
public IPseudonymousAccountHolder[] iPseudonymousAccountHolders { get { return PseudonymousAccountHolders; } }
private Dictionary<EventHandler<IAccountHolder>, EventHandler<AccountHolder>> iAccountHolderAddedDict = new Dictionary<EventHandler<IAccountHolder>, EventHandler<AccountHolder>>();
public event EventHandler<IAccountHolder> iAccountHolderAdded
{
add
{
EventHandler<AccountHolder> eh = (sender, e) => value(sender, e);
iAccountHolderAddedDict.Add(value, eh);
AccountHolderAdded += eh;
}
remove
{
EventHandler<AccountHolder> eh = iAccountHolderAddedDict[value];
iAccountHolderAddedDict.Remove(value);
AccountHolderAdded -= eh;
}
}
private Dictionary<EventHandler<IAccountHolder>, EventHandler<AccountHolder>> iAccountHolderRemovedDict = new Dictionary<EventHandler<IAccountHolder>, EventHandler<AccountHolder>>();
public event EventHandler<IAccountHolder> iAccountHolderRemoved
{
add
{
EventHandler<AccountHolder> eh = (sender, e) => value(sender, e);
iAccountHolderRemovedDict.Add(value, eh);
AccountHolderRemoved += eh;
}
remove
{
EventHandler<AccountHolder> eh = iAccountHolderRemovedDict[value];
iAccountHolderRemovedDict.Remove(value);
AccountHolderAdded -= eh;
}
}
public void iAddAccountHolder(IPseudonymousAccountHolder iPseudonymousAccountHolder)
{
if (!(iPseudonymousAccountHolder is PseudonymousAccountHolder))
throw new ArgumentException("type_mismatch");
AddAccountHolder(iPseudonymousAccountHolder as PseudonymousAccountHolder);
}
public void iDeleteAccountHolder(IPseudonymousAccountHolder iPseudonymousAccountHolder)
{
if (!(iPseudonymousAccountHolder is PseudonymousAccountHolder))
throw new ArgumentException("type_mismatch");
DeleteAccountHolder(iPseudonymousAccountHolder as PseudonymousAccountHolder);
}
}
public class AccountHoldersFactory : IAccountHoldersFactory
{
public IAccount CreateAccount(string name, string description)
{
return new Account().Pipe((account) => account.LoadVersion0(name, description));
}
public IPseudonymousAccountHolder CreatePseudonymousAccountHolder(string name)
{
return new PseudonymousAccountHolder().Pipe((pseudonymousAccountHolder) => pseudonymousAccountHolder.LoadVersion0(name));
}
}
#endregion
public class MerkleTree<U> where U : HASHBASE
{
public MerkleTree(U[] _hashes)
{
hashes = new List<U>();
tree = new U[1][];
tree[0] = new U[0];
Add(_hashes);
}
public List<U> hashes { get; private set; }
public U[][] tree { get; private set; }
public U Root
{
get
{
if (hashes.Count == 0)
throw new InvalidOperationException("Merkle_tree_empty");
return tree[tree.Length - 1][0];
}
}
public void Add(U[] hs)
{
int start = hashes.Count;
hashes.AddRange(hs);
int end = hashes.Count;
if (tree[0].Length < hashes.Count)
{
int newLength = tree[0].Length;
int newHeight = tree.Length;
while (newLength < hashes.Count)
if (newLength == 0)
newLength++;
else
{
newLength *= 2;
newHeight++;
}
U[][] newTree = new U[newHeight][];
for (int i = 0; i < newTree.Length; i++, newLength /= 2)
newTree[i] = new U[newLength];
for (int i = 0; i < tree.Length; i++)
for (int j = 0; j < tree[i].Length; j++)
newTree[i][j] = tree[i][j];
tree = newTree;
end = tree[0].Length;
}
for (int j = start; j < end; j++)
if (j < hashes.Count)
tree[0][j] = hashes[j];
else
tree[0][j] = hashes[hashes.Count - 1];
start /= 2;
end /= 2;
for (int i = 1; i < tree.Length; i++)
{
for (int j = start; j < end; j++)
tree[i][j] = Activator.CreateInstance(typeof(U), (tree[i - 1][j * 2] as HASHBASE).hash.Combine((tree[i - 1][j * 2 + 1] as HASHBASE).hash)) as U;
start /= 2;
end /= 2;
}
}
public MerkleProof<U> GetProof(U target)
{
int? index = null;
for (int i = 0; i < tree[0].Length; i++)
if (tree[0][i].Equals(target))
{
index = i;
break;
}
if (index == null)
throw new InvalidOperationException("merkle_tree_target");
int index2 = index.Value;
U[] proof = new U[tree.Length];
for (int i = 0; i < proof.Length - 1; i++, index /= 2)
proof[i] = index % 2 == 0 ? tree[i][index.Value + 1] : tree[i][index.Value - 1];
proof[proof.Length - 1] = tree[proof.Length - 1][0];
return new MerkleProof<U>(index2, proof);
}
public static bool Verify(U target, MerkleProof<U> proof)
{
U cal = Activator.CreateInstance(typeof(U)) as U;
cal.FromHash(target.hash);
int index = proof.index;
for (int i = 0; i < proof.proof.Length - 1; i++, index /= 2)
cal = Activator.CreateInstance(typeof(U), index % 2 == 0 ? cal.hash.Combine(proof.proof[i].hash) : proof.proof[i].hash.Combine(cal.hash)) as U;
return cal.Equals(proof.proof[proof.proof.Length - 1]);
}
}
public class MerkleProof<U> : SHAREDDATA where U : HASHBASE
{
public MerkleProof() { }
public MerkleProof(int _index, U[] _proof) { index = _index; proof = _proof; }
public int index { get; private set; }
public U[] proof { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(int), () => index, (o) => index = (int)o),
new MainDataInfomation(typeof(U[]), null, null, () => proof, (o) => proof = (U[])o),
};
}
}
}
public class CurrencyUnit
{
protected CurrencyUnit() { }
public CurrencyUnit(long _rawAmount) { rawAmount = _rawAmount; }
public static CurrencyUnit Zero = new CurrencyUnit(0);
public long rawAmount { get; protected set; }
public virtual decimal Amount { get { throw new NotImplementedException("currency_unit_amount"); } }
public virtual Creacoin AmountInCreacoin { get { return new Creacoin(rawAmount); } }
public virtual Yumina AmountInYumina { get { return new Yumina(rawAmount); } }
}
public class Creacoin : CurrencyUnit
{
public Creacoin(long _rawAmount) : base(_rawAmount) { }
public Creacoin(decimal _amountInCreacoin)
{
if (_amountInCreacoin < 0.0m)
throw new ArgumentException("creacoin_out_of_range");
decimal amountInMinimumUnit = _amountInCreacoin * CreacoinInMinimumUnit;
if (amountInMinimumUnit != Math.Floor(amountInMinimumUnit))
throw new InvalidDataException("creacoin_precision");
rawAmount = (long)amountInMinimumUnit;
}
public static string Name = "CREA";
public static decimal CreacoinInMinimumUnit = 100000000.0m;
public override decimal Amount { get { return rawAmount / CreacoinInMinimumUnit; } }
public override Creacoin AmountInCreacoin { get { return this; } }
}
public class Yumina : CurrencyUnit
{
public Yumina(long _rawAmount) : base(_rawAmount) { }
public Yumina(decimal _amountInYumina)
{
if (_amountInYumina < 0.0m)
throw new ArgumentException("yumina_out_of_range");
decimal amountInMinimumUnit = _amountInYumina * YuminaInMinimumUnit;
if (amountInMinimumUnit != Math.Floor(amountInMinimumUnit))
throw new InvalidDataException("yumina_precision");
rawAmount = (long)amountInMinimumUnit;
}
public static string Name = "Yumina";
public static decimal YuminaInMinimumUnit = 1000000.0m;
public override decimal Amount { get { return rawAmount / YuminaInMinimumUnit; } }
public override Yumina AmountInYumina { get { return this; } }
}
public class Difficulty<BlockidHashType> where BlockidHashType : HASHBASE
{
public Difficulty(byte[] _compactTarget)
{
if (_compactTarget.Length != 4)
throw new ArgumentException("ill-formed_compact_target");
compactTarget = _compactTarget;
}
public Difficulty(BlockidHashType _target)
{
if (_target.SizeByte > 254)
throw new ArgumentException("too_long_target");
target = _target;
}
private byte[] compactTarget;
public byte[] CompactTarget
{
get
{
if (compactTarget == null)
{
byte[] bytes = target.hash;
int numOfHead0 = 0;
for (int i = 0; i < bytes.Length && bytes[i] == 0; i++)
numOfHead0++;
if (numOfHead0 != 0)
bytes = bytes.Decompose(numOfHead0);
if (bytes.Length == 0)
return new byte[] { 0, 0, 0, 0 };
if (bytes[0] > 127)
bytes = new byte[] { 0 }.Combine(bytes);
bytes = new byte[] { (byte)bytes.Length }.Combine(bytes);
if (bytes.Length == 2)
bytes = bytes.Combine(new byte[] { 0, 0 });
else if (bytes.Length == 3)
bytes = bytes.Combine(new byte[] { 0 });
else if (bytes.Length > 4)
bytes = bytes.Decompose(0, 4);
compactTarget = bytes;
}
return compactTarget;
}
}
private BlockidHashType target;
public BlockidHashType Target
{
get
{
if (target == null)
{
byte[] bytes;
if (compactTarget[0] > 2)
bytes = new byte[] { compactTarget[1], compactTarget[2], compactTarget[3] };
else if (compactTarget[0] == 2)
bytes = new byte[] { compactTarget[1], compactTarget[2] };
else if (compactTarget[0] == 1)
bytes = new byte[] { compactTarget[1] };
else
return target = Activator.CreateInstance(typeof(BlockidHashType)) as BlockidHashType;
int numOfTail0 = compactTarget[0] - 3;
if (numOfTail0 > 0)
bytes = bytes.Combine(new byte[numOfTail0]);
BlockidHashType newTarget = Activator.CreateInstance(typeof(BlockidHashType)) as BlockidHashType;
int numOfHead0 = newTarget.SizeByte - bytes.Length;
if (numOfHead0 > 0)
bytes = new byte[numOfHead0].Combine(bytes);
newTarget.FromHash(bytes);
target = newTarget;
}
return target;
}
}
public double Diff { get { return BDiff; } }
private double? pDifficulty;
public double PDiff
{
get
{
if (pDifficulty == null)
{
BlockidHashType tag = Target;
byte[] difficulty1TargetBytes = new byte[tag.SizeByte];
for (int i = 4; i < difficulty1TargetBytes.Length; i++)
difficulty1TargetBytes[i] = 255;
pDifficulty = CalculateDifficulty(difficulty1TargetBytes, tag.hash);
}
return pDifficulty.Value;
}
}
private double? bDifficulty;
public double BDiff
{
get
{
if (bDifficulty == null)
{
BlockidHashType tag = Target;
byte[] difficulty1TargetBytes = new byte[tag.SizeByte];
if (difficulty1TargetBytes.Length > 4)
difficulty1TargetBytes[4] = 255;
if (difficulty1TargetBytes.Length > 5)
difficulty1TargetBytes[5] = 255;
bDifficulty = CalculateDifficulty(difficulty1TargetBytes, tag.hash);
}
return bDifficulty.Value;
}
}
private double? averageHash;
public double AverageHash
{
get
{
if (averageHash == null)
{
BlockidHashType tag = Target;
byte[] maxBytes = Enumerable.Repeat((byte)255, tag.SizeByte).ToArray();
BigInteger maxBigInt = new BigInteger(maxBytes.Reverse().ToArray().Combine(new byte[] { 0 }));
BigInteger targetBigInt = new BigInteger(tag.hash.Reverse().ToArray().Combine(new byte[] { 0 }));
BigInteger averageHashBigInt100000000 = (maxBigInt * 100000000) / targetBigInt;
averageHash = (double)averageHashBigInt100000000 / 100000000.0;
}
return averageHash.Value;
}
}
public double GetAverageHashrate(double averageInterval) { return AverageHash / averageInterval; }
public double GetAverageTime(double averageHashrate) { return AverageHash / averageHashrate; }
private double CalculateDifficulty(byte[] difficulty1TargetBytes, byte[] targetBytes)
{
BigInteger difficulty1TargetBigInt = new BigInteger(difficulty1TargetBytes.Reverse().ToArray().Combine(new byte[] { 0 }));
BigInteger targetBigInt = new BigInteger(targetBytes.Reverse().ToArray().Combine(new byte[] { 0 }));
BigInteger difficultyBigInt100000000 = (difficulty1TargetBigInt * 100000000) / targetBigInt;
return (double)difficultyBigInt100000000 / 100000000.0;
}
}
#region ๅๅผ
//<ๆชๅฎ่ฃ
>Load้จๅใฎๆฝ่ฑกๅ
//2014/12/02 ่ฉฆ้จๆธ
public class TransactionInput : SHAREDDATA
{
public TransactionInput() : base(0) { }
public void LoadVersion0(long _prevTxBlockIndex, int _prevTxIndex, int _prevTxOutputIndex, Ecdsa256PubKey _senderPubKey)
{
Version = 0;
LoadCommon(_prevTxBlockIndex, _prevTxIndex, _prevTxOutputIndex);
ecdsa256PubKey = _senderPubKey;
}
public void LoadVersion1(long _prevTxBlockIndex, int _prevTxIndex, int _prevTxOutputIndex)
{
Version = 1;
LoadCommon(_prevTxBlockIndex, _prevTxIndex, _prevTxOutputIndex);
}
private void LoadCommon(long _prevTxBlockIndex, int _prevTxIndex, int _prevTxOutputIndex)
{
prevTxBlockIndex = _prevTxBlockIndex;
prevTxIndex = _prevTxIndex;
prevTxOutputIndex = _prevTxOutputIndex;
}
private long prevTxBlockIndex;
private int prevTxIndex;
private int prevTxOutputIndex;
private Ecdsa256Signature ecdsa256Signature;
private Secp256k1Signature secp256k1Signature;
private Ecdsa256PubKey ecdsa256PubKey;
public long PrevTxBlockIndex { get { return prevTxBlockIndex; } }
public int PrevTxIndex { get { return prevTxIndex; } }
public int PrevTxOutputIndex { get { return prevTxOutputIndex; } }
public Ecdsa256Signature Ecdsa256Signature
{
get
{
if (Version != 0)
throw new NotSupportedException();
return ecdsa256Signature;
}
}
public Secp256k1Signature Secp256k1Signature
{
get
{
if (Version != 1)
throw new NotSupportedException();
return secp256k1Signature;
}
}
public Ecdsa256PubKey Ecdsa256PubKey
{
get
{
if (Version != 0)
throw new NotSupportedException();
return ecdsa256PubKey;
}
}
public DSASIGNATUREBASE SenderSignature
{
get
{
if (Version == 0)
return ecdsa256Signature;
else if (Version == 1)
return secp256k1Signature;
else
throw new NotSupportedException();
}
}
public DSAPUBKEYBASE SenderPubKey
{
get
{
if (Version == 0)
return ecdsa256PubKey;
//Secp256k1ใฎๅ ดๅใ็ฝฒๅใ ใใงใฏใชใ็ฝฒๅๅฏพ่ฑกใฎใใผใฟใใชใใใฐๅ
ฌ้้ตใๅพฉๅ
ใงใใชใ
else if (Version == 1)
throw new InvalidOperationException();
else
throw new NotSupportedException();
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => prevTxBlockIndex, (o) => prevTxBlockIndex = (long)o),
new MainDataInfomation(typeof(int), () => prevTxIndex, (o) => prevTxIndex = (int)o),
new MainDataInfomation(typeof(int), () => prevTxOutputIndex, (o) => prevTxOutputIndex = (int)o),
new MainDataInfomation(typeof(Ecdsa256Signature), null, () => ecdsa256Signature, (o) => ecdsa256Signature = (Ecdsa256Signature)o),
new MainDataInfomation(typeof(Ecdsa256PubKey), null, () => ecdsa256PubKey, (o) => ecdsa256PubKey = (Ecdsa256PubKey)o),
};
else if (Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => prevTxBlockIndex, (o) => prevTxBlockIndex = (long)o),
new MainDataInfomation(typeof(int), () => prevTxIndex, (o) => prevTxIndex = (int)o),
new MainDataInfomation(typeof(int), () => prevTxOutputIndex, (o) => prevTxOutputIndex = (int)o),
new MainDataInfomation(typeof(Secp256k1Signature), null, () => secp256k1Signature, (o) => secp256k1Signature = (Secp256k1Signature)o),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsVersionSaved { get { return false; } }
public Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfoToSign
{
get
{
if (Version == 0 || Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => prevTxBlockIndex, (o) => { throw new NotSupportedException(); }),
new MainDataInfomation(typeof(int), () => prevTxIndex, (o) => { throw new NotSupportedException(); }),
new MainDataInfomation(typeof(int), () => prevTxOutputIndex, (o) => { throw new NotSupportedException(); }),
};
else
throw new NotSupportedException();
}
}
public void SetSenderSig(DSASIGNATUREBASE signature)
{
if (Version == 0)
{
if (!(signature is Ecdsa256Signature))
throw new ArgumentException();
ecdsa256Signature = signature as Ecdsa256Signature;
}
else if (Version == 1)
{
if (!(signature is Secp256k1Signature))
throw new ArgumentException();
secp256k1Signature = signature as Secp256k1Signature;
}
else
throw new NotSupportedException();
}
}
//2014/12/02 ่ฉฆ้จๆธ
public class TransactionOutput : SHAREDDATA
{
public TransactionOutput() : base(0) { }
public void LoadVersion0(Sha256Ripemd160Hash _receiverPubKeyHash, CurrencyUnit _amount)
{
Version = 0;
receiverPubKeyHash = _receiverPubKeyHash;
amount = _amount;
}
private Sha256Ripemd160Hash receiverPubKeyHash;
private CurrencyUnit amount;
public Sha256Ripemd160Hash Address { get { return receiverPubKeyHash; } }
public CurrencyUnit Amount { get { return amount; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Sha256Ripemd160Hash), null, () => receiverPubKeyHash, (o) => receiverPubKeyHash = (Sha256Ripemd160Hash)o),
new MainDataInfomation(typeof(long), () => amount.rawAmount, (o) => amount = new CurrencyUnit((long)o)),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsVersionSaved { get { return false; } }
public Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfoToSign
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Sha256Ripemd160Hash), null, () => receiverPubKeyHash, (o) => { throw new NotSupportedException(); }),
new MainDataInfomation(typeof(long), () => amount.rawAmount, (o) => { throw new NotSupportedException(); }),
};
else
throw new NotSupportedException();
}
}
public Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfoToSignPrev
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Sha256Ripemd160Hash), null, () => receiverPubKeyHash, (o) => { throw new NotSupportedException(); }),
};
else
throw new NotSupportedException();
}
}
}
//2014/12/02 ่ฉฆ้จๆธ
//<ๆชๅฎ่ฃ
>ๅๅบฆ่กใๅฟ
่ฆใฎใชใๆค่จผใฏ่กใใชใ
public abstract class Transaction : SHAREDDATA
{
public Transaction() : base(0) { idCache = new CachedData<Sha256Sha256Hash>(() => new Sha256Sha256Hash(ToBinary())); }
public virtual void LoadVersion0(TransactionOutput[] _txOutputs)
{
foreach (var txOutput in _txOutputs)
if (txOutput.Version != 0)
throw new ArgumentException();
Version = 0;
LoadCommon(_txOutputs);
}
public virtual void LoadVersion1(TransactionOutput[] _txOutputs)
{
foreach (var txOutput in _txOutputs)
if (txOutput.Version != 0)
throw new ArgumentException();
Version = 1;
LoadCommon(_txOutputs);
}
private void LoadCommon(TransactionOutput[] _txOutputs)
{
if (_txOutputs.Length == 0)
throw new ArgumentException();
txOutputs = _txOutputs;
}
private static readonly CurrencyUnit dustTxoutput = new Yumina(0.1m);
private static readonly int maxTxInputs = 100;
private static readonly int maxTxOutputs = 10;
private TransactionOutput[] _txOutputs;
private TransactionOutput[] txOutputs
{
get { return _txOutputs; }
set
{
if (value != _txOutputs)
{
_txOutputs = value;
idCache.IsModified = true;
}
}
}
public virtual TransactionInput[] TxInputs { get { return new TransactionInput[] { }; } }
public virtual TransactionOutput[] TxOutputs { get { return txOutputs; } }
protected readonly CachedData<Sha256Sha256Hash> idCache;
public virtual Sha256Sha256Hash Id { get { return idCache.Data; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0 || Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(TransactionOutput[]), 0, null, () => txOutputs, (o) => txOutputs = (TransactionOutput[])o),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked
{
get
{
if (Version == 0 || Version == 1)
return true;
else
throw new NotSupportedException();
}
}
public virtual bool Verify()
{
if (Version == 0 || Version == 1)
return VerifyNotExistDustTxOutput() && VerifyNumberOfTxInputs() && VerifyNumberOfTxOutputs();
else
throw new NotSupportedException();
}
public bool VerifyNotExistDustTxOutput()
{
if (Version == 0 || Version == 1)
return txOutputs.All((elem) => elem.Amount.rawAmount >= dustTxoutput.rawAmount);
else
throw new NotSupportedException();
}
public bool VerifyNumberOfTxInputs()
{
if (Version == 0 || Version == 1)
return TxInputs.Length <= maxTxInputs;
else
throw new NotSupportedException();
}
public bool VerifyNumberOfTxOutputs()
{
if (Version == 0 || Version == 1)
return TxOutputs.Length <= maxTxOutputs;
else
throw new NotSupportedException();
}
}
//2014/12/02 ่ฉฆ้จๆธ
public class CoinbaseTransaction : Transaction
{
public override void LoadVersion1(TransactionOutput[] _txOutputs) { throw new NotSupportedException(); }
private const string guidString = "784aee51e677e6469ca2ae0d6c72d60e";
private Guid guid;
public override Guid Guid
{
get
{
if (guid == Guid.Empty)
guid = new Guid(guidString);
return guid;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return base.StreamInfo;
else
throw new NotSupportedException();
}
}
}
//2014/12/02 ่ฉฆ้จๆธ
//<ๆชๅฎ่ฃ
>ๅๅบฆ่กใๅฟ
่ฆใฎใชใๆค่จผใฏ่กใใชใ
public class TransferTransaction : Transaction
{
public override void LoadVersion0(TransactionOutput[] _txOutputs) { throw new NotSupportedException(); }
public virtual void LoadVersion0(TransactionInput[] _txInputs, TransactionOutput[] _txOutputs)
{
foreach (var txInput in _txInputs)
if (txInput.Version != 0)
throw new ArgumentException();
base.LoadVersion0(_txOutputs);
LoadCommon(_txInputs);
}
public override void LoadVersion1(TransactionOutput[] _txOutputs) { throw new NotSupportedException(); }
public virtual void LoadVersion1(TransactionInput[] _txInputs, TransactionOutput[] _txOutputs)
{
foreach (var txInput in _txInputs)
if (txInput.Version != 1)
throw new ArgumentException();
base.LoadVersion1(_txOutputs);
LoadCommon(_txInputs);
}
private void LoadCommon(TransactionInput[] _txInputs)
{
if (_txInputs.Length == 0)
throw new ArgumentException();
txInputs = _txInputs;
}
private TransactionInput[] _txInputs;
public TransactionInput[] txInputs
{
get { return _txInputs; }
private set
{
if (value != _txInputs)
{
_txInputs = value;
idCache.IsModified = true;
}
}
}
public override TransactionInput[] TxInputs { get { return txInputs; } }
private const string guidString = "5c5493dff997774db351ae5018844b23";
private Guid guid;
public override Guid Guid
{
get
{
if (guid == Guid.Empty)
guid = new Guid(guidString);
return guid;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(TransactionInput[]), 0, null, () => txInputs, (o) => txInputs = (TransactionInput[])o),
});
else if (Version == 1)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(TransactionInput[]), 1, null, () => txInputs, (o) => txInputs = (TransactionInput[])o),
});
else
throw new NotSupportedException();
}
}
private Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfoToSign(TransactionOutput[] prevTxOutputs) { return (msrw) => StreamInfoToSignInner(prevTxOutputs); }
private IEnumerable<MainDataInfomation> StreamInfoToSignInner(TransactionOutput[] prevTxOutputs)
{
if (Version == 0 || Version == 1)
{
for (int i = 0; i < txInputs.Length; i++)
{
foreach (var mdi in txInputs[i].StreamInfoToSign(null))
yield return mdi;
foreach (var mdi in prevTxOutputs[i].StreamInfoToSignPrev(null))
yield return mdi;
}
for (int i = 0; i < TxOutputs.Length; i++)
foreach (var mdi in TxOutputs[i].StreamInfoToSign(null))
yield return mdi;
}
else
throw new NotSupportedException();
}
public byte[] GetBytesToSign(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
return ToBinaryMainData(StreamInfoToSign(prevTxOutputs));
}
public void Sign(TransactionOutput[] prevTxOutputs, DSAPRIVKEYBASE[] privKeys)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
if (privKeys.Length != txInputs.Length)
throw new ArgumentException();
byte[] bytesToSign = GetBytesToSign(prevTxOutputs);
for (int i = 0; i < txInputs.Length; i++)
txInputs[i].SetSenderSig(privKeys[i].Sign(bytesToSign));
//ๅๅผๅ
ฅๅใฎๅ
ๅฎนใๅคๆดใใใ
idCache.IsModified = true;
}
public override bool Verify() { throw new NotSupportedException(); }
public virtual bool Verify(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
if (Version == 0 || Version == 1)
return base.Verify() && VerifySignature(prevTxOutputs) && VerifyPubKey(prevTxOutputs) && VerifyAmount(prevTxOutputs);
else
throw new NotSupportedException();
}
public bool VerifySignature(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
byte[] bytesToSign = GetBytesToSign(prevTxOutputs);
if (Version == 0)
{
for (int i = 0; i < txInputs.Length; i++)
if (!txInputs[i].Ecdsa256PubKey.Verify(bytesToSign, txInputs[i].SenderSignature.signature))
return false;
}
else if (Version == 1)
{
//<ๆชๆน่ฏ>ไบใๅ
ฌ้้ตใๅพฉๅ
ใใฆใใ๏ผ
for (int i = 0; i < txInputs.Length; i++)
//if (!Secp256k1Utility.Recover<Sha256Hash>(bytesToSign, txInputs[i].SenderSignature.signature).Verify(bytesToSign, txInputs[i].SenderSignature.signature))
if (!Secp256k1Utility.RecoverAndVerify<Sha256Hash>(bytesToSign, txInputs[i].SenderSignature.signature))
return false;
}
else
throw new NotSupportedException();
return true;
}
public bool VerifyPubKey(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
if (Version == 0)
{
for (int i = 0; i < txInputs.Length; i++)
if (!new Sha256Ripemd160Hash(txInputs[i].Ecdsa256PubKey.pubKey).Equals(prevTxOutputs[i].Address))
return false;
}
else if (Version == 1)
{
byte[] bytesToSign = GetBytesToSign(prevTxOutputs);
//<ๆชๆน่ฏ>ไบใๅ
ฌ้้ตใๅพฉๅ
ใใฆใใ๏ผ
for (int i = 0; i < txInputs.Length; i++)
if (!new Sha256Ripemd160Hash(Secp256k1Utility.Recover<Sha256Hash>(bytesToSign, txInputs[i].Secp256k1Signature.signature).pubKey).Equals(prevTxOutputs[i].Address))
return false;
}
else
throw new NotSupportedException();
return true;
}
public bool VerifyAmount(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
return GetFee(prevTxOutputs).rawAmount >= 0;
}
public CurrencyUnit GetFee(TransactionOutput[] prevTxOutputs)
{
if (prevTxOutputs.Length != txInputs.Length)
throw new ArgumentException();
long totalPrevOutputs = 0;
for (int i = 0; i < prevTxOutputs.Length; i++)
totalPrevOutputs += prevTxOutputs[i].Amount.rawAmount;
long totalOutpus = 0;
for (int i = 0; i < TxOutputs.Length; i++)
totalOutpus += TxOutputs[i].Amount.rawAmount;
return new CurrencyUnit(totalPrevOutputs - totalOutpus);
}
}
#endregion
#region ใใญใใฏ
public abstract class Block : SHAREDDATA
{
public Block(int? _version) : base(_version) { idCache = new CachedData<Creahash>(IdGenerator); }
protected CachedData<Creahash> idCache;
protected virtual Func<Creahash> IdGenerator { get { return () => new Creahash(ToBinary()); } }
public virtual Creahash Id { get { return idCache.Data; } }
public abstract long Index { get; }
public abstract Creahash PrevId { get; }
public abstract Difficulty<Creahash> Difficulty { get; }
public abstract Transaction[] Transactions { get; }
public virtual bool Verify() { return true; }
}
//2014/12/02 ่ฉฆ้จๆธ
public class GenesisBlock : Block
{
public GenesisBlock() : base(null) { }
public readonly string genesisWord = "Bitstamp 2014/05/25 BTC/USD High 586.34 BTC to the moooooooon!!";
public override long Index { get { return 0; } }
public override Creahash PrevId { get { return null; } }
public override Difficulty<Creahash> Difficulty { get { return 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 })); } }
public override Transaction[] Transactions { get { return new Transaction[] { }; } }
private const string guidString = "86080fc3b48032489cf8c19e275fc185";
private Guid guid;
public override Guid Guid
{
get
{
if (guid == Guid.Empty)
guid = new Guid(guidString);
return guid;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(string), () => genesisWord, (o) =>
{
if((string)o != genesisWord)
throw new NotSupportedException("genesis_word_mismatch");;
}),
};
}
}
}
//2014/12/02 ่ฉฆ้จๆธ
public class BlockHeader : SHAREDDATA
{
public BlockHeader() : base(0) { }
public void LoadVersion0(long _index, Creahash _prevBlockHash, DateTime _timestamp, Difficulty<Creahash> _difficulty, byte[] _nonce)
{
if (_index < 1)
throw new ArgumentOutOfRangeException("block_header_index_out");
if (_nonce.Length != nonceLength)
throw new ArgumentOutOfRangeException("block_header_nonce_out");
index = _index;
prevBlockHash = _prevBlockHash;
timestamp = _timestamp;
difficulty = _difficulty;
nonce = _nonce;
}
private static readonly int nonceLength = 10;
public long index { get; private set; }
public Creahash prevBlockHash { get; private set; }
public Sha256Sha256Hash merkleRootHash { get; private set; }
public DateTime timestamp { get; private set; }
public Difficulty<Creahash> difficulty { get; private set; }
public byte[] nonce { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => index, (o) => index = (long)o),
new MainDataInfomation(typeof(Creahash), null, () => prevBlockHash, (o) => prevBlockHash = (Creahash)o),
new MainDataInfomation(typeof(Sha256Sha256Hash), null, () => merkleRootHash, (o) => merkleRootHash = (Sha256Sha256Hash)o),
new MainDataInfomation(typeof(DateTime), () => timestamp, (o) => timestamp = (DateTime)o),
new MainDataInfomation(typeof(byte[]), 4, () => difficulty.CompactTarget, (o) => difficulty = new Difficulty<Creahash>((byte[])o)),
new MainDataInfomation(typeof(byte[]), nonceLength, () => nonce, (o) => nonce = (byte[])o),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsVersionSaved { get { return false; } }
public void UpdateMerkleRootHash(Sha256Sha256Hash newMerkleRootHash) { merkleRootHash = newMerkleRootHash; }
public void UpdateTimestamp(DateTime newTimestamp) { timestamp = newTimestamp; }
public void UpdateNonce(byte[] newNonce)
{
if (newNonce.Length != nonceLength)
throw new ArgumentOutOfRangeException("block_header_nonce_out");
nonce = newNonce;
}
}
//2014/12/03 ่ฉฆ้จๆธ
//<ๆชๅฎ่ฃ
>ๅๅบฆ่กใๅฟ
่ฆใฎใชใๆค่จผใฏ่กใใชใ
public abstract class TransactionalBlock : Block
{
static TransactionalBlock()
{
rewards = new CurrencyUnit[numberOfCycles];
rewards[0] = initialReward;
for (int i = 1; i < numberOfCycles; i++)
rewards[i] = new Creacoin(rewards[i - 1].Amount * rewardReductionRate);
}
public TransactionalBlock()
: base(0)
{
transactionsCache = new CachedData<Transaction[]>(TransactionsGenerator);
merkleTreeCache = new CachedData<MerkleTree<Sha256Sha256Hash>>(() => new MerkleTree<Sha256Sha256Hash>(Transactions.Select((e) => e.Id).ToArray()));
}
public virtual void LoadVersion0(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, TransferTransaction[] _transferTxs)
{
if (_header.Version != 0)
throw new ArgumentException();
if (_coinbaseTxToMiner.Version != 0)
throw new ArgumentException();
foreach (var transferTx in _transferTxs)
if (transferTx.Version != 0)
throw new ArgumentException();
Version = 0;
LoadCommon(_header, _coinbaseTxToMiner, _transferTxs);
}
public virtual void LoadVersion1(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, TransferTransaction[] _transferTxs)
{
if (_header.Version != 0)
throw new ArgumentException();
if (_coinbaseTxToMiner.Version != 0)
throw new ArgumentException();
foreach (var transferTx in _transferTxs)
if (transferTx.Version != 1)
throw new ArgumentException();
Version = 1;
LoadCommon(_header, _coinbaseTxToMiner, _transferTxs);
}
private void LoadCommon(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, TransferTransaction[] _transferTxs)
{
header = _header;
coinbaseTxToMiner = _coinbaseTxToMiner;
transferTxs = _transferTxs;
}
public static readonly int maxTxs = 100;
#if TEST
private static readonly long blockGenerationInterval = 1; //[sec]
#else
private static readonly long blockGenerationInterval = 60; //[sec]
#endif
private static readonly long cycle = 60 * 60 * 24 * 365; //[sec]=1[year]
private static readonly int numberOfCycles = 8;
private static readonly long rewardlessStart = cycle * numberOfCycles; //[sec]=8[year]
private static readonly decimal rewardReductionRate = 0.8m;
private static readonly CurrencyUnit initialReward = new Creacoin(1.0m); //[CREA/sec]
private static readonly CurrencyUnit[] rewards; //[CREA/sec]
private static readonly decimal foundationShare = 0.1m;
private static readonly long foundationInterval = 60 * 60 * 24 / blockGenerationInterval; //[block]
private static readonly long numberOfTimestamps = 11;
private static readonly long targetTimespan = blockGenerationInterval * 1; //[sec]=60[sec]
private static readonly long retargetInterval = targetTimespan / blockGenerationInterval; //[block]=1[block]
private static readonly Difficulty<Creahash> minDifficulty = 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 }));
#if TEST
public static readonly Sha256Ripemd160Hash foundationPubKeyHash = new Sha256Ripemd160Hash(new byte[] { 69, 67, 83, 49, 32, 0, 0, 0, 16, 31, 116, 194, 127, 71, 154, 183, 50, 198, 23, 17, 129, 220, 25, 98, 4, 30, 93, 45, 53, 252, 176, 145, 108, 20, 226, 233, 36, 7, 35, 198, 98, 239, 109, 66, 206, 41, 162, 179, 255, 189, 126, 72, 97, 140, 165, 139, 118, 107, 137, 103, 76, 238, 125, 62, 163, 205, 108, 62, 189, 240, 124, 71 });
#else
public static readonly Sha256Ripemd160Hash foundationPubKeyHash = null;
#endif
private BlockHeader _header;
public BlockHeader header
{
get { return _header; }
private set
{
if (value != _header)
{
_header = value;
idCache.IsModified = true;
}
}
}
private CoinbaseTransaction _coinbaseTxToMiner;
public CoinbaseTransaction coinbaseTxToMiner
{
get { return _coinbaseTxToMiner; }
private set
{
if (value != _coinbaseTxToMiner)
{
_coinbaseTxToMiner = value;
idCache.IsModified = true;
transactionsCache.IsModified = true;
merkleTreeCache.IsModified = true;
}
}
}
private TransferTransaction[] _transferTxs;
public TransferTransaction[] transferTxs
{
get { return _transferTxs; }
private set
{
if (value != _transferTxs)
{
_transferTxs = value;
idCache.IsModified = true;
transactionsCache.IsModified = true;
merkleTreeCache.IsModified = true;
}
}
}
public override long Index { get { return header.index; } }
public override Creahash PrevId { get { return header.prevBlockHash; } }
public override Difficulty<Creahash> Difficulty { get { return header.difficulty; } }
protected override Func<Creahash> IdGenerator { get { return () => new Creahash(header.ToBinary()); } }
protected CachedData<Transaction[]> transactionsCache;
protected virtual Func<Transaction[]> TransactionsGenerator
{
get
{
return () =>
{
Transaction[] transactions = new Transaction[transferTxs.Length + 1];
transactions[0] = coinbaseTxToMiner;
for (int i = 0; i < transferTxs.Length; i++)
transactions[i + 1] = transferTxs[i];
return transactions;
};
}
}
public override Transaction[] Transactions { get { return transactionsCache.Data; } }
protected CachedData<MerkleTree<Sha256Sha256Hash>> merkleTreeCache;
public MerkleTree<Sha256Sha256Hash> MerkleTree { get { return merkleTreeCache.Data; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(BlockHeader), 0, () => header, (o) => header = (BlockHeader)o),
new MainDataInfomation(typeof(CoinbaseTransaction), 0, () => coinbaseTxToMiner, (o) =>
{
coinbaseTxToMiner = (CoinbaseTransaction)o;
if (coinbaseTxToMiner.Version != 0)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(TransferTransaction[]), 0, null, () => transferTxs, (o) =>
{
transferTxs = (TransferTransaction[])o;
foreach (var transaferTx in transferTxs)
if (transaferTx.Version != 0)
throw new NotSupportedException();
}),
};
else if (Version == 1)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(BlockHeader), 0, () => header, (o) => header = (BlockHeader)o),
new MainDataInfomation(typeof(CoinbaseTransaction), 0, () => coinbaseTxToMiner, (o) =>
{
coinbaseTxToMiner = (CoinbaseTransaction)o;
if (coinbaseTxToMiner.Version != 0)
throw new NotSupportedException();
}),
new MainDataInfomation(typeof(TransferTransaction[]), 1, null, () => transferTxs, (o) =>
{
transferTxs = (TransferTransaction[])o;
foreach (var transaferTx in transferTxs)
if (transaferTx.Version != 1)
throw new NotSupportedException();
}),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked
{
get
{
if (Version == 0 || Version == 1)
return true;
else
throw new NotSupportedException();
}
}
public void UpdateMerkleRootHash()
{
header.UpdateMerkleRootHash(MerkleTree.Root);
idCache.IsModified = true;
}
public void UpdateTimestamp(DateTime newTimestamp)
{
header.UpdateTimestamp(newTimestamp);
idCache.IsModified = true;
}
public void UpdateNonce(byte[] newNonce)
{
header.UpdateNonce(newNonce);
idCache.IsModified = true;
}
public override bool Verify() { throw new NotSupportedException(); }
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public virtual bool Verify(TransactionOutput[][] prevTxOutputss, Func<long, TransactionalBlock> indexToTxBlock)
{
if (prevTxOutputss.Length != Transactions.Length)
throw new ArgumentException("txs_and_prev_outputs");
//if (prevTxOutputss.Length != transferTxs.Length)
// throw new ArgumentException("transfet_txs_and_prev_outputs");
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return VerifyBlockType() && VerifyMerkleRootHash() && VerifyId() && VerifyNumberOfTxs() && VerifyTransferTransaction(prevTxOutputss) && VerifyRewardAndTxFee(prevTxOutputss) & VerifyTimestamp(indexToTxBlock) && VerifyDifficulty(indexToTxBlock);
}
public bool VerifyBlockType()
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return this.GetType() == GetBlockType(header.index, Version);
}
public bool VerifyMerkleRootHash()
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return header.merkleRootHash.Equals(MerkleTree.Root);
}
public bool VerifyId()
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return Id.CompareTo(header.difficulty.Target) <= 0;
}
public bool VerifyNumberOfTxs()
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return Transactions.Length <= maxTxs;
}
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public bool VerifyTransferTransaction(TransactionOutput[][] prevTxOutputss)
{
if (prevTxOutputss.Length != Transactions.Length)
throw new ArgumentException("txs_and_prev_outputs");
if (Version != 0 && Version != 1)
throw new NotSupportedException();
for (int i = 0; i < Transactions.Length; i++)
if (Transactions[i] is TransferTransaction && !(Transactions[i] as TransferTransaction).Verify(prevTxOutputss[i]))
return false;
return true;
//if (prevTxOutputss.Length != transferTxs.Length)
// throw new ArgumentException("transfet_txs_and_prev_outputs");
//if (Version != 0 && Version != 1)
// throw new NotSupportedException();
//for (int i = 0; i < transferTxs.Length; i++)
// if (!transferTxs[i].Verify(prevTxOutputss[i]))
// return false;
//return true;
}
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public virtual bool VerifyRewardAndTxFee(TransactionOutput[][] prevTxOutputss)
{
if (prevTxOutputss.Length != Transactions.Length)
throw new ArgumentException("txs_and_prev_outputs");
//if (prevTxOutputss.Length != transferTxs.Length)
// throw new ArgumentException("transfet_txs_and_prev_outputs");
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return GetActualRewardToMinerAndTxFee().rawAmount == GetValidRewardToMinerAndTxFee(prevTxOutputss).rawAmount;
}
public bool VerifyTimestamp(Func<long, TransactionalBlock> indexToTxBlock)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
List<DateTime> timestamps = new List<DateTime>();
for (long i = 1; i < numberOfTimestamps + 1 && header.index - i > 0; i++)
timestamps.Add(indexToTxBlock(header.index - i).header.timestamp);
timestamps.Sort();
if (timestamps.Count == 0)
return true;
return (timestamps.Count / 2).Pipe((index) => header.timestamp > (timestamps.Count % 2 == 0 ? timestamps[index - 1] + new TimeSpan((timestamps[index] - timestamps[index - 1]).Ticks / 2) : timestamps[index]));
}
public bool VerifyDifficulty(Func<long, TransactionalBlock> indexToTxBlock)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return header.difficulty.Diff == GetWorkRequired(header.index, indexToTxBlock, 0).Diff;
}
public CurrencyUnit GetValidRewardToMiner() { return GetRewardToMiner(header.index, Version); }
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public CurrencyUnit GetValidTxFee(TransactionOutput[][] prevTxOutputss)
{
if (prevTxOutputss.Length != Transactions.Length)
throw new ArgumentException("txs_and_prev_outputs");
long rawTxFee = 0;
for (int i = 0; i < Transactions.Length; i++)
if (Transactions[i] is TransferTransaction)
rawTxFee += (Transactions[i] as TransferTransaction).GetFee(prevTxOutputss[i]).rawAmount;
return new CurrencyUnit(rawTxFee);
//if (prevTxOutputss.Length != transferTxs.Length)
// throw new ArgumentException("transfet_txs_and_prev_outputs");
//long rawTxFee = 0;
//for (int i = 0; i < transferTxs.Length; i++)
// rawTxFee += transferTxs[i].GetFee(prevTxOutputss[i]).rawAmount;
//return new CurrencyUnit(rawTxFee);
}
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public CurrencyUnit GetValidRewardToMinerAndTxFee(TransactionOutput[][] prevTxOutputss)
{
if (prevTxOutputss.Length != Transactions.Length)
throw new ArgumentException("txs_and_prev_outputs");
//if (prevTxOutputss.Length != transferTxs.Length)
// throw new ArgumentException("transfet_txs_and_prev_outputs");
return new CurrencyUnit(GetValidRewardToMiner().rawAmount + GetValidTxFee(prevTxOutputss).rawAmount);
}
public CurrencyUnit GetActualRewardToMinerAndTxFee()
{
long rawTxFee = 0;
for (int i = 0; i < coinbaseTxToMiner.TxOutputs.Length; i++)
rawTxFee += coinbaseTxToMiner.TxOutputs[i].Amount.rawAmount;
return new CurrencyUnit(rawTxFee);
}
public static Type GetBlockType(long index, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
return index % foundationInterval == 0 ? typeof(FoundationalBlock) : typeof(NormalBlock);
else
throw new NotSupportedException("tx_block_not_supported");
}
public static CurrencyUnit GetRewardToAll(long index, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
{
long sec = index * blockGenerationInterval;
for (int i = 0; i < numberOfCycles; i++)
if (sec < cycle * (i + 1))
return new Creacoin(rewards[i].rawAmount * (long)blockGenerationInterval);
return new Creacoin(0.0m);
}
else
throw new NotSupportedException("tx_block_not_supported");
}
public static CurrencyUnit GetRewardToMiner(long index, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
return new Creacoin(GetRewardToAll(index, version).AmountInCreacoin.Amount * (1.0m - foundationShare));
else
throw new NotSupportedException("tx_block_not_supported");
}
public static CurrencyUnit GetRewardToFoundation(long index, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
return new Creacoin(GetRewardToAll(index, version).AmountInCreacoin.Amount * foundationShare);
else
throw new NotSupportedException("tx_block_not_supported");
}
public static CurrencyUnit GetRewardToFoundationInterval(long index, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (GetBlockType(index, version) != typeof(FoundationalBlock))
throw new ArgumentException("index_invalid");
if (version == 0 || version == 1)
return new Creacoin(GetRewardToFoundation(index, version).AmountInCreacoin.Amount * foundationInterval);
else
throw new NotSupportedException("tx_block_not_supported");
}
public static Difficulty<Creahash> GetWorkRequired(long index, Func<long, TransactionalBlock> indexToTxBlock, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
{
if (index == 1)
return minDifficulty;
long lastIndex = index - 1;
//ๅธธใซfalseใซใชใ็ญ
if (index % retargetInterval != 0)
return indexToTxBlock(lastIndex).header.difficulty;
else
{
//ๅธธใซ1ใซใชใ็ญ
long blocksToGoBack = index != retargetInterval ? retargetInterval : retargetInterval - 1;
//ใใญใใฏ2ใฎใจใ1ใใใญใใฏ3ใฎใจใ1ใใใญใใฏ4ใฎใจใ2ใใปใปใป
long firstIndex = lastIndex - blocksToGoBack > 0 ? lastIndex - blocksToGoBack : 1;
TimeSpan actualTimespan = indexToTxBlock(lastIndex).header.timestamp - indexToTxBlock(firstIndex).header.timestamp;
//ๆๅฐใง75%
if (actualTimespan.TotalSeconds < targetTimespan - (targetTimespan / 4.0))
actualTimespan = TimeSpan.FromSeconds(targetTimespan - (targetTimespan / 4.0));
//ๆๅคงใง150%
else if (actualTimespan.TotalSeconds > targetTimespan + (targetTimespan / 2.0))
actualTimespan = TimeSpan.FromSeconds(targetTimespan + (targetTimespan / 2.0));
//ๆๅฐใง0.75ใๆๅคงใง1.5
double ratio = (double)actualTimespan.TotalSeconds / (double)targetTimespan;
byte[] prevTargetBytes = indexToTxBlock(lastIndex).header.difficulty.Target.hash;
int? pos = null;
for (int i = 0; i < prevTargetBytes.Length && pos == null; i++)
if (prevTargetBytes[i] != 0)
pos = i;
double prevtarget2BytesDouble;
if (pos != prevTargetBytes.Length - 1)
prevtarget2BytesDouble = prevTargetBytes[pos.Value] * 256 + prevTargetBytes[pos.Value + 1];
else
prevtarget2BytesDouble = prevTargetBytes[pos.Value];
prevtarget2BytesDouble *= ratio;
List<byte> target3Bytes = new List<byte>();
while (prevtarget2BytesDouble > 255)
{
target3Bytes.Add((byte)(prevtarget2BytesDouble % 256));
prevtarget2BytesDouble /= 256;
}
target3Bytes.Add((byte)prevtarget2BytesDouble);
Creahash hash = new Creahash();
byte[] targetBytes = new byte[hash.SizeByte];
if (pos != prevTargetBytes.Length - 1)
{
if (target3Bytes.Count == 3)
if (pos == 0)
{
targetBytes[pos.Value] = 255;
targetBytes[pos.Value + 1] = target3Bytes[0];
}
else
{
targetBytes[pos.Value - 1] = target3Bytes[2];
targetBytes[pos.Value] = target3Bytes[1];
targetBytes[pos.Value + 1] = target3Bytes[0];
}
else
{
targetBytes[pos.Value] = target3Bytes[1];
targetBytes[pos.Value + 1] = target3Bytes[0];
}
}
else
{
if (target3Bytes.Count == 2)
{
targetBytes[pos.Value - 1] = target3Bytes[1];
targetBytes[pos.Value] = target3Bytes[0];
}
else
targetBytes[pos.Value] = target3Bytes[0];
}
hash.FromHash(targetBytes);
Difficulty<Creahash> difficulty = new Difficulty<Creahash>(hash);
return (difficulty.Diff < minDifficulty.Diff ? minDifficulty : difficulty).Pipe((dif) => dif.RaiseNotification("difficulty", 3, difficulty.Diff.ToString()));
}
}
else
throw new NotSupportedException("tx_block_not_supported");
}
public static BlockHeader GetBlockHeaderTemplate(long index, Func<long, TransactionalBlock> indexToTxBlock, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
return new BlockHeader().Pipe((bh) => bh.LoadVersion0(index, index - 1 == 0 ? new GenesisBlock().Id : indexToTxBlock(index - 1).Id, DateTime.Now, GetWorkRequired(index, indexToTxBlock, version), new byte[10]));
else
throw new NotSupportedException("tx_block_not_supported");
}
public static TransactionalBlock GetBlockTemplate(long index, CoinbaseTransaction coinbaseTxToMiner, TransferTransaction[] transferTxs, Func<long, TransactionalBlock> indexToTxBlock, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0)
{
BlockHeader header = GetBlockHeaderTemplate(index, indexToTxBlock, version);
TransactionalBlock txBlock;
if (GetBlockType(index, version) == typeof(NormalBlock))
txBlock = new NormalBlock().Pipe((normalBlock) => normalBlock.LoadVersion0(header, coinbaseTxToMiner, transferTxs));
else
{
TransactionOutput coinbaseTxOutToFoundation = new TransactionOutput();
coinbaseTxOutToFoundation.LoadVersion0(foundationPubKeyHash, GetRewardToFoundationInterval(index, version));
CoinbaseTransaction coinbaseTxToFoundation = new CoinbaseTransaction();
coinbaseTxToFoundation.LoadVersion0(new TransactionOutput[] { coinbaseTxOutToFoundation });
txBlock = new FoundationalBlock().Pipe((foundationalBlock) => foundationalBlock.LoadVersion0(header, coinbaseTxToMiner, coinbaseTxToFoundation, transferTxs));
}
txBlock.UpdateMerkleRootHash();
return txBlock;
}
else if (version == 1)
{
BlockHeader header = GetBlockHeaderTemplate(index, indexToTxBlock, version);
TransactionalBlock txBlock;
if (GetBlockType(index, version) == typeof(NormalBlock))
txBlock = new NormalBlock().Pipe((normalBlock) => normalBlock.LoadVersion1(header, coinbaseTxToMiner, transferTxs));
else
{
TransactionOutput coinbaseTxOutToFoundation = new TransactionOutput();
coinbaseTxOutToFoundation.LoadVersion0(foundationPubKeyHash, GetRewardToFoundationInterval(index, version));
CoinbaseTransaction coinbaseTxToFoundation = new CoinbaseTransaction();
coinbaseTxToFoundation.LoadVersion0(new TransactionOutput[] { coinbaseTxOutToFoundation });
txBlock = new FoundationalBlock().Pipe((foundationalBlock) => foundationalBlock.LoadVersion1(header, coinbaseTxToMiner, coinbaseTxToFoundation, transferTxs));
}
txBlock.UpdateMerkleRootHash();
return txBlock;
}
else
throw new NotSupportedException("tx_block_not_supported");
}
public static TransactionalBlock GetBlockTemplate(long index, Sha256Ripemd160Hash minerPubKeyHash, TransferTransaction[] transferTxs, TransactionOutput[][] prevTxOutss, Func<long, TransactionalBlock> indexToTxBlock, int version)
{
if (index < 1)
throw new ArgumentOutOfRangeException("index_out");
if (version == 0 || version == 1)
{
long rawFee = 0;
foreach (var prevTxOuts in prevTxOutss)
foreach (var prevTxOut in prevTxOuts)
rawFee += prevTxOut.Amount.rawAmount;
foreach (var transferTx in transferTxs)
foreach (var txOut in transferTx.TxOutputs)
rawFee -= txOut.Amount.rawAmount;
TransactionOutput coinbaseTxOutToMiner = new TransactionOutput();
coinbaseTxOutToMiner.LoadVersion0(minerPubKeyHash, new CurrencyUnit(GetRewardToMiner(index, version).rawAmount + rawFee));
CoinbaseTransaction coinbaseTxToMiner = new CoinbaseTransaction();
coinbaseTxToMiner.LoadVersion0(new TransactionOutput[] { coinbaseTxOutToMiner });
return GetBlockTemplate(index, coinbaseTxToMiner, transferTxs, indexToTxBlock, version);
}
else
throw new NotSupportedException("tx_block_not_supported");
}
}
//2014/12/03 ่ฉฆ้จๆธ
public class NormalBlock : TransactionalBlock
{
private const string guidString = "6bf78c27e25fe843bf354952848edd52";
private Guid guid;
public override Guid Guid
{
get
{
if (guid == Guid.Empty)
guid = new Guid(guidString);
return guid;
}
}
}
//2014/12/03 ่ฉฆ้จๆธ
//<ๆชๅฎ่ฃ
>ๅๅบฆ่กใๅฟ
่ฆใฎใชใๆค่จผใฏ่กใใชใ
public class FoundationalBlock : TransactionalBlock
{
public override void LoadVersion0(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, TransferTransaction[] _transferTxs) { throw new NotSupportedException(); }
public virtual void LoadVersion0(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, CoinbaseTransaction _coinbaseTxToFoundation, TransferTransaction[] _transferTxs)
{
if (_coinbaseTxToFoundation.Version != 0)
throw new ArgumentException();
base.LoadVersion0(_header, _coinbaseTxToMiner, _transferTxs);
LoadCommon(_coinbaseTxToFoundation);
}
public override void LoadVersion1(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, TransferTransaction[] _transferTxs) { throw new NotSupportedException(); }
public virtual void LoadVersion1(BlockHeader _header, CoinbaseTransaction _coinbaseTxToMiner, CoinbaseTransaction _coinbaseTxToFoundation, TransferTransaction[] _transferTxs)
{
if (_coinbaseTxToFoundation.Version != 0)
throw new ArgumentException();
base.LoadVersion1(_header, _coinbaseTxToMiner, _transferTxs);
LoadCommon(_coinbaseTxToFoundation);
}
private void LoadCommon(CoinbaseTransaction _coinbaseTxToFoundation) { coinbaseTxToFoundation = _coinbaseTxToFoundation; }
private CoinbaseTransaction _coinbaseTxToFoundation;
public CoinbaseTransaction coinbaseTxToFoundation
{
get { return _coinbaseTxToFoundation; }
private set
{
if (value != _coinbaseTxToFoundation)
{
_coinbaseTxToFoundation = value;
idCache.IsModified = true;
transactionsCache.IsModified = true;
merkleTreeCache.IsModified = true;
}
}
}
protected override Func<Transaction[]> TransactionsGenerator
{
get
{
return () =>
{
Transaction[] transactions = new Transaction[transferTxs.Length + 2];
transactions[0] = coinbaseTxToMiner;
transactions[1] = coinbaseTxToFoundation;
for (int i = 0; i < transferTxs.Length; i++)
transactions[i + 2] = transferTxs[i];
return transactions;
};
}
}
private const string guidString = "1a3fbbf05e672d41ba52ace089710fc1";
private Guid guid;
public override Guid Guid
{
get
{
if (guid == Guid.Empty)
guid = new Guid(guidString);
return guid;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(CoinbaseTransaction), 0, () => coinbaseTxToFoundation, (o) =>
{
coinbaseTxToFoundation = (CoinbaseTransaction)o;
if (coinbaseTxToFoundation.Version != 0)
throw new NotSupportedException();
}),
});
else if (Version == 1)
return (msrw) => base.StreamInfo(msrw).Concat(new MainDataInfomation[]{
new MainDataInfomation(typeof(CoinbaseTransaction), 0, () => coinbaseTxToFoundation, (o) =>
{
coinbaseTxToFoundation = (CoinbaseTransaction)o;
if (coinbaseTxToFoundation.Version != 0)
throw new NotSupportedException();
}),
});
else
throw new NotSupportedException();
}
}
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public override bool Verify(TransactionOutput[][] prevTxOutputss, Func<long, TransactionalBlock> indexToTxBlock)
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return base.Verify(prevTxOutputss, indexToTxBlock) && VerifyCoinbaseTxToFoundationPubKey();
}
public bool VerifyCoinbaseTxToFoundationPubKey()
{
if (Version != 0 && Version != 1)
throw new NotSupportedException();
return coinbaseTxToFoundation.TxOutputs.All((e) => e.Address.Equals(foundationPubKeyHash));
}
//2014/12/03
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public override bool VerifyRewardAndTxFee(TransactionOutput[][] prevTxOutputss)
{
if (!base.VerifyRewardAndTxFee(prevTxOutputss))
return false;
return GetActualRewardToFoundation().rawAmount == GetValidRewardToFoundation().rawAmount;
}
public CurrencyUnit GetValidRewardToFoundation() { return GetRewardToFoundationInterval(header.index, Version); }
public CurrencyUnit GetActualRewardToFoundation()
{
long rawTxFee = 0;
for (int i = 0; i < coinbaseTxToFoundation.TxOutputs.Length; i++)
rawTxFee += coinbaseTxToFoundation.TxOutputs[i].Amount.rawAmount;
return new CurrencyUnit(rawTxFee);
}
}
#endregion
public class TransactionCollection : SHAREDDATA
{
public TransactionCollection()
: base(null)
{
transactions = new List<Transaction>();
transactionsCache = new CachedData<Transaction[]>(() =>
{
lock (transactionsLock)
return transactions.ToArray();
});
}
private readonly object transactionsLock = new object();
private List<Transaction> transactions;
private readonly CachedData<Transaction[]> transactionsCache;
public Transaction[] Transactions { get { return transactionsCache.Data; } }
public event EventHandler<Transaction> TransactionAdded = delegate { };
public event EventHandler<Transaction> TransactionRemoved = delegate { };
public bool Contains(Sha256Sha256Hash id)
{
lock (transactionsLock)
return transactions.FirstOrDefault((elem) => elem.Id.Equals(id)) != null;
}
public bool AddTransaction(Transaction transaction)
{
lock (transactionsLock)
{
if (transactions.Contains(transaction))
return false;
this.ExecuteBeforeEvent(() =>
{
transactions.Add(transaction);
transactionsCache.IsModified = true;
}, transaction, TransactionAdded);
return true;
}
}
public bool RemoveTransaction(Transaction transaction)
{
lock (transactionsLock)
{
if (!transactions.Contains(transaction))
return false;
this.ExecuteBeforeEvent(() =>
{
transactions.Remove(transaction);
transactionsCache.IsModified = true;
}, transaction, TransactionRemoved);
return true;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get { throw new NotImplementedException(); }
}
}
public class BlockCollection : SHAREDDATA
{
public BlockCollection()
: base(null)
{
blocks = new List<Block>();
blocksCache = new CachedData<Block[]>(() =>
{
lock (blocksLock)
return blocks.ToArray();
});
}
private readonly object blocksLock = new object();
private List<Block> blocks;
private readonly CachedData<Block[]> blocksCache;
public Block[] Blocks { get { return blocksCache.Data; } }
public event EventHandler<Block> BlockAdded = delegate { };
public event EventHandler<Block> BlockRemoved = delegate { };
public bool Contains(Creahash id)
{
lock (blocksLock)
return blocks.FirstOrDefault((elem) => elem.Id.Equals(id)) != null;
}
public bool AddBlock(Block block)
{
lock (blocksLock)
{
if (blocks.Contains(block))
return false;
this.ExecuteBeforeEvent(() =>
{
blocks.Add(block);
blocksCache.IsModified = true;
}, block, BlockAdded);
return true;
}
}
public bool RemoveBlock(Block block)
{
lock (blocksLock)
{
if (!blocks.Contains(block))
return false;
this.ExecuteBeforeEvent(() =>
{
blocks.Remove(block);
blocksCache.IsModified = true;
}, block, BlockRemoved);
return true;
}
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get { throw new NotImplementedException(); }
}
}
#region ใใญใใฏ้
public class BlockChainAccesser
{
public BlockChainAccesser(BlockChain _blockchain, object _accessObj, Func<object, bool> _checker)
{
blockchain = _blockchain;
accessObj = _accessObj;
checker = _checker;
}
private BlockChain blockchain;
private object accessObj;
private Func<object, bool> checker;
}
//ๆช่ฉฆ้จ้
็ฎ
//ใปใใญใใฏ้ใฎExit/ๅๆๆดๆฐใชใฉ
//ใปๅๅผๅฑฅๆญด้ข้ฃ
//2014/12/05 ๅๅฒใ็บ็ใใชใๅ ดๅ ่ฉฆ้จๆธ
//2014/12/14 ๅๅฒใ็บ็ใใๅ ดๅ ่ฉฆ้จๆธ
public class BlockChain
{
public BlockChain(BlockchainAccessDB _bcadb, BlockManagerDB _bmdb, BlockDB _bdb, BlockFilePointersDB _bfpdb, UtxoFileAccessDB _ufadb, UtxoFilePointersDB _ufpdb, UtxoFilePointersTempDB _ufptempdb, UtxoDB _udb, long _maxBlockIndexMargin = 100, long _mainBlockFinalization = 300, int _mainBlocksRetain = 1000, int _oldBlocksRetain = 1000)
{
bcadb = _bcadb;
bmdb = _bmdb;
bdb = _bdb;
bfpdb = _bfpdb;
ufadb = _ufadb;
ufpdb = _ufpdb;
ufptempdb = _ufptempdb;
udb = _udb;
maxBlockIndexMargin = _maxBlockIndexMargin;
mainBlockFinalization = _mainBlockFinalization;
capacity = (maxBlockIndexMargin + mainBlockFinalization) * 2;
mainBlocksRetain = _mainBlocksRetain;
oldBlocksRetain = _oldBlocksRetain;
blockManager = new BlockManager(bmdb, bdb, bfpdb, mainBlocksRetain, oldBlocksRetain, mainBlockFinalization);
utxoManager = new UtxoManager(ufadb, ufpdb, ufptempdb, udb);
pendingBlocks = new Dictionary<Creahash, Block>[capacity];
rejectedBlocks = new Dictionary<Creahash, Block>[capacity];
blocksCurrent = new CirculatedInteger((int)capacity);
registeredAddresses = new Dictionary<AddressEvent, List<Utxo>>();
are = new AutoResetEvent(true);
}
private static readonly long unusableConformation = 6;
private long maxBlockIndexMargin = 100;
private long mainBlockFinalization = 300;
private long capacity;
private int mainBlocksRetain = 1000;
private int oldBlocksRetain = 1000;
private readonly BlockchainAccessDB bcadb;
private readonly BlockManagerDB bmdb;
private readonly BlockDB bdb;
private readonly BlockFilePointersDB bfpdb;
private readonly UtxoFileAccessDB ufadb;
private readonly UtxoFilePointersDB ufpdb;
private readonly UtxoFilePointersTempDB ufptempdb;
private readonly UtxoDB udb;
private readonly BlockManager blockManager;
private readonly UtxoManager utxoManager;
public readonly Dictionary<Creahash, Block>[] pendingBlocks;
public readonly Dictionary<Creahash, Block>[] rejectedBlocks;
public readonly CirculatedInteger blocksCurrent;
public readonly Dictionary<AddressEvent, List<Utxo>> registeredAddresses;
private TransactionHistories ths;
public bool isExited { get; private set; }
public event EventHandler BalanceUpdated = delegate { };
public event EventHandler<List<Block>> Updated = delegate { };
private readonly AutoResetEvent are;
private readonly object lockObj = new object();
public long headBlockIndex { get { return blockManager.headBlockIndex; } }
public long finalizedBlockIndex { get { return blockManager.finalizedBlockIndex; } }
public List<Utxo> GetAllUtxos(Sha256Ripemd160Hash address)
{
return utxoManager.GetAllUtxos(address);
}
public Utxo FindUtxo(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
return utxoManager.FindUtxo(address, blockIndex, txIndex, txOutIndex);
}
public Block GetHeadBlock()
{
return blockManager.GetHeadBlock();
}
public Block GetMainBlock(long blockIndex)
{
return blockManager.GetMainBlock(blockIndex);
}
public enum UpdateChainReturnType { updated, invariable, pending, rejected, updatedAndRejected }
public class UpdateChainInnerReturn
{
public UpdateChainInnerReturn(UpdateChainReturnType _type)
{
if (_type == UpdateChainReturnType.rejected || _type == UpdateChainReturnType.pending)
throw new ArgumentException();
type = _type;
}
public UpdateChainInnerReturn(UpdateChainReturnType _type, int _position)
{
if (_type != UpdateChainReturnType.pending)
throw new ArgumentException();
type = _type;
position = _position;
}
public UpdateChainInnerReturn(UpdateChainReturnType _type, int _position, List<Block> _rejectedBlocks)
{
if (_type != UpdateChainReturnType.rejected && _type != UpdateChainReturnType.updatedAndRejected)
throw new ArgumentException();
type = _type;
position = _position;
rejectedBlocks = _rejectedBlocks;
}
public UpdateChainReturnType type { get; set; }
public int position { get; set; }
public List<Block> rejectedBlocks { get; set; }
}
public class BlockNode
{
public BlockNode(Block _block, double _cumulativeDiff, CirculatedInteger _ci)
{
block = _block;
cumulativeDiff = _cumulativeDiff;
ci = _ci;
}
public Block block { get; set; }
public double cumulativeDiff { get; set; }
public CirculatedInteger ci { get; set; }
}
//<ๆชๆน่ฏ>ๆฌๅฝใฏใณใณในใใฉใฏใฟใงๅฆ็ใในใใงใฏใใใใในใใณใผใใๆธใๆใใชใใใฐใชใใชใใชใใฎใงๆซๅฎ็ใซๅฅใกใฝใใใซ
public void LoadTransactionHistories(TransactionHistories transactionHistories)
{
ths = transactionHistories;
}
private Tuple<CurrencyUnit, CurrencyUnit> CalculateBalance(List<Utxo> utxosList)
{
long usableRawAmount = 0;
long unusableRawAmount = 0;
foreach (var utxo in utxosList)
if (utxo.blockIndex + unusableConformation > headBlockIndex)
unusableRawAmount += utxo.amount.rawAmount;
else
usableRawAmount += utxo.amount.rawAmount;
return new Tuple<CurrencyUnit, CurrencyUnit>(new CurrencyUnit(usableRawAmount), new CurrencyUnit(unusableRawAmount));
}
public void AddAddressEvent(AddressEvent addressEvent)
{
if (registeredAddresses.Keys.FirstOrDefault((elem) => elem.address.Equals(addressEvent.address)) != null)
throw new InvalidOperationException("already_added");
List<Utxo> utxos = utxoManager.GetAllUtxosLatestFirst(addressEvent.address);
registeredAddresses.Add(addressEvent, utxos);
Tuple<CurrencyUnit, CurrencyUnit> balance = CalculateBalance(utxos);
addressEvent.RaiseBalanceUpdated(balance);
addressEvent.RaiseUsableBalanceUpdated(balance.Item1);
addressEvent.RaiseUnusableBalanceUpdated(balance.Item2);
}
public AddressEvent RemoveAddressEvent(Sha256Ripemd160Hash address)
{
AddressEvent addressEvent = registeredAddresses.Keys.FirstOrDefault((elem) => elem.address.Equals(address));
if (addressEvent == null)
throw new ArgumentException("not_added");
registeredAddresses.Remove(addressEvent);
return addressEvent;
}
public void Exit()
{
if (isExited)
throw new InvalidOperationException("blockchain_alredy_exited");
if (are.WaitOne(30000))
isExited = true;
else
throw new InvalidOperationException("fatal:blkchain_freeze");
}
public UpdateChainReturnType UpdateChain(Block block)
{
if (isExited)
throw new InvalidOperationException("blockchain_already_exited");
lock (lockObj)
{
//ๆๅพใซ็ขบๅฎใใใใใญใใฏใฎใใญใใฏ็ชๅทใๆๅฐใใญใใฏ็ชๅทใงใใ
long minBlockIndex = blockManager.finalizedBlockIndex;
//ๅ
้ ญใใญใใฏใฎใใญใใฏ็ชๅทใซไฝ่ฃใๅ ใใใใฎใๆๅคงใใญใใฏ็ชๅทใงใใ
long maxBlockIndex = blockManager.headBlockIndex + maxBlockIndexMargin;
//ๆๅฐใใญใใฏ็ชๅทไปฅไธใฎใใญใใฏ็ชๅทใๆใใใใญใใฏใฏ่ชใใใใชใ
if (block.Index <= minBlockIndex)
throw new InvalidOperationException();
//็พๅจใฎใใญใใฏใฎใใญใใฏ็ชๅทใใๅคงใ้ใใใใญใใฏ็ชๅท๏ผๆๅคงใใญใใฏ็ชๅทใ่ถ
ใใใใญใใฏ็ชๅท๏ผใๆใใใใญใใฏใฏ่ชใใใใชใ
if (block.Index > maxBlockIndex)
throw new InvalidOperationException();
int position = blocksCurrent.GetForward((int)(block.Index - blockManager.headBlockIndex));
//ๆขใซ้ปๅดใใใฆใใใใญใใฏใฎๅ ดๅใฏไฝใๅคใใใชใ
if (rejectedBlocks[position] != null && rejectedBlocks[position].Keys.Contains(block.Id))
return UpdateChainReturnType.invariable;
//ๆขใซใใญใใฏ้ใฎไธ้จใงใใๅ ดๅใฏไฝใๅคใใใชใ
Block mainBlock = block.Index > blockManager.headBlockIndex ? null : blockManager.GetMainBlock(block.Index);
if (mainBlock != null && mainBlock.Id.Equals(block.Id))
return UpdateChainReturnType.invariable;
Node<BlockNode> root = new Node<BlockNode>(new BlockNode(block, block.Difficulty.Diff, new CirculatedInteger(position, (int)capacity)), null);
Queue<Node<BlockNode>> queue = new Queue<Node<BlockNode>>();
queue.Enqueue(root);
while (queue.Count > 0)
{
Node<BlockNode> current = queue.Dequeue();
int nextIndex = current.value.ci.GetForward(1);
if (pendingBlocks[nextIndex] == null)
continue;
foreach (var nextBlock in pendingBlocks[nextIndex].Values.Where((elem) => elem.PrevId.Equals(current.value.block.Id)))
{
Node<BlockNode> child = new Node<BlockNode>(new BlockNode(nextBlock, current.value.cumulativeDiff + nextBlock.Difficulty.Diff, new CirculatedInteger(nextIndex, (int)capacity)), current);
current.children.Add(child);
queue.Enqueue(child);
}
}
UpdateChainReturnType type = UpdateChainReturnType.rejected;
double actualCumulativeDiff = 0.0;
while (true)
{
queue.Enqueue(root);
Node<BlockNode> maxCumulativeDiffNode = new Node<BlockNode>(new BlockNode(null, 0.0, null), null);
while (queue.Count > 0)
{
Node<BlockNode> current = queue.Dequeue();
if (current.children.Count == 0 && current.value.cumulativeDiff > maxCumulativeDiffNode.value.cumulativeDiff)
maxCumulativeDiffNode = current;
else
foreach (var child in current.children)
queue.Enqueue(child);
}
if (maxCumulativeDiffNode.value.cumulativeDiff <= actualCumulativeDiff)
return type;
//ใใญใใฏไปฅๅพใฎใใญใใฏใๆ ผ็ดใใ
//ใใญใใฏใๅๅฒใใญใใฏ้ใฎใใญใใฏใฎไธ้จใงใใๅ ดๅใฏใใใญใใฏใฎ็ดๅใฎใใญใใฏใใใใญใใฏ้ใใๅๅฒใใใพใงใฎใใญใใฏใๆ ผ็ดใใ
List<Block> blocksList = new List<Block>();
//ใใญใใฏไปฅๅพใฎใใญใใฏใฎ่ขซๅ็
งๅๅผๅบๅใๆ ผ็ดใใ
//ใใญใใฏใๅๅฒใใญใใฏ้ใฎใใญใใฏใฎไธ้จใงใใๅ ดๅใฏใใใญใใฏใฎ็ดๅใฎใใญใใฏใใใใญใใฏ้ใใๅๅฒใใใพใงใฎใใญใใฏใฎ่ขซๅ็
งๅๅผๅบๅใๆ ผ็ดใใ
List<TransactionOutput[][]> prevTxOutputssList = new List<TransactionOutput[][]>();
//ใใญใใฏใๅๅฒใใญใใฏ้ใฎใใญใใฏใฎไธ้จใงใใๅ ดๅใฏใๅ
้ ญใใญใใฏใใๅๅฒใๅงใพใฃใฆใใใใญใใฏใจๅไธใฎใใญใใฏ็ชๅทใฎใใญใใฏใพใงใๆ ผ็ดใใ
List<Block> mainBlocksList = new List<Block>();
//ใใญใใฏใๅๅฒใใญใใฏ้ใฎใใญใใฏใฎไธ้จใงใใๅ ดๅใฏใๅ
้ ญใใญใใฏใใๅๅฒใๅงใพใฃใฆใใใใญใใฏใจๅไธใฎใใญใใฏ็ชๅทใฎใใญใใฏใพใงใฎ่ขซๅ็
งๅๅผๅบๅใๆ ผ็ดใใ
List<TransactionOutput[][]> mainPrevTxOutputssList = new List<TransactionOutput[][]>();
Node<BlockNode> temp = maxCumulativeDiffNode;
while (temp != null)
{
blocksList.Insert(0, temp.value.block);
temp = temp.parent;
}
UpdateChainInnerReturn ret = UpdateChainInner(block, blocksList, prevTxOutputssList, mainBlocksList, mainPrevTxOutputssList, minBlockIndex, position, maxCumulativeDiffNode.value.cumulativeDiff);
if (ret.type == UpdateChainReturnType.updated)
return UpdateChainReturnType.updated;
else if (ret.type == UpdateChainReturnType.pending)
{
if (pendingBlocks[ret.position] == null)
{
pendingBlocks[ret.position] = new Dictionary<Creahash, Block>();
pendingBlocks[ret.position].Add(block.Id, block);
}
else if (!pendingBlocks[ret.position].Keys.Contains(block.Id))
pendingBlocks[ret.position].Add(block.Id, block);
return UpdateChainReturnType.pending;
}
else if (ret.type == UpdateChainReturnType.rejected || ret.type == UpdateChainReturnType.updatedAndRejected)
{
Block rejectedRootBlock = ret.rejectedBlocks[0];
queue.Enqueue(root);
Node<BlockNode> rejectedRootNode = null;
while (queue.Count > 0)
{
Node<BlockNode> current = queue.Dequeue();
if (current.value.block == rejectedRootBlock)
{
rejectedRootNode = current;
break;
}
foreach (var child in current.children)
queue.Enqueue(child);
}
queue = new Queue<Node<BlockNode>>();
queue.Enqueue(rejectedRootNode);
CirculatedInteger ci = new CirculatedInteger(ret.position, (int)capacity);
while (queue.Count > 0)
{
Node<BlockNode> current = queue.Dequeue();
int rejectedPosition = ci.GetForward((int)(current.value.block.Index - rejectedRootBlock.Index));
if (pendingBlocks[rejectedPosition] != null && pendingBlocks[rejectedPosition].Keys.Contains(current.value.block.Id))
pendingBlocks[rejectedPosition].Remove(current.value.block.Id);
if (rejectedBlocks[rejectedPosition] == null)
rejectedBlocks[rejectedPosition] = new Dictionary<Creahash, Block>();
rejectedBlocks[rejectedPosition].Add(current.value.block.Id, current.value.block);
foreach (var child in current.children)
queue.Enqueue(child);
}
if (rejectedRootNode.parent == null)
return ret.type;
rejectedRootNode.parent.children.Remove(rejectedRootNode);
type = ret.type;
actualCumulativeDiff = rejectedRootNode.parent.value.cumulativeDiff;
}
}
}
}
private double VerifyBlockChain(List<Block> blocksList, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos, List<TransactionOutput[][]> prevTxOutputssList)
{
Func<long, TransactionalBlock> _bindexToTxBlock = (bindex) =>
{
if (bindex < blocksList[0].Index)
return blockManager.GetMainBlock(bindex) as TransactionalBlock;
else if (bindex < blocksList[0].Index + blocksList.Count)
return blocksList[(int)(bindex - blocksList[0].Index)] as TransactionalBlock;
else
return null;
};
double cumulativeDiff = 0.0;
udb.Open();
for (int i = 0; i < blocksList.Count; i++)
{
//ใใญใใฏใฎ่ขซๅ็
งๅๅผๅบๅใๅๅพใใ
TransactionOutput[][] prevTxOutputss = GetPrevTxOutputss(blocksList[i], _bindexToTxBlock);
if (prevTxOutputss == null)
{
udb.Close();
return cumulativeDiff;
}
//ใใญใใฏ่ชไฝใฎๆค่จผใๅฎ่กใใ
//็กๅนใใญใใฏใงใใๅ ดๅใฏ้ปๅดใใญใใฏใจใใ
if (blocksList[i] is GenesisBlock)
{
if (!(blocksList[i] as GenesisBlock).Verify())
{
udb.Close();
return cumulativeDiff;
}
}
else if (blocksList[i] is TransactionalBlock)
{
if (!(blocksList[i] as TransactionalBlock).Verify(prevTxOutputss, _bindexToTxBlock))
{
udb.Close();
return cumulativeDiff;
}
}
else
throw new NotSupportedException();
//ใใญใใฏ้ใฎ็ถๆ
๏ผ๏ผๆชไฝฟ็จใฎๅๅผๅบๅใฎๅญๅฆ๏ผใจ็็พใใชใใๆค่จผใใ
//็็พใใใๅ ดๅใฏ็กๅนใใญใใฏใจใชใใ้ปๅดใใญใใฏใจใใ
if (!VerifyUtxo(blocksList[i], prevTxOutputss, addedUtxos, removedUtxos))
{
udb.Close();
return cumulativeDiff;
}
prevTxOutputssList.Add(prevTxOutputss);
RetrieveTransactionTransitionForward(blocksList[i], prevTxOutputss, addedUtxos, removedUtxos);
cumulativeDiff += blocksList[i].Difficulty.Diff;
}
udb.Close();
return cumulativeDiff;
}
private UpdateChainInnerReturn UpdateChainInner(Block block, List<Block> blocksList, List<TransactionOutput[][]> prevTxOutputssList, List<Block> mainBlocksList, List<TransactionOutput[][]> mainPrevTxOutputssList, long minBlockIndex, int position, double cumulativeDiff)
{
//ใใญใใฏใ่ตทๆบใใญใใฏใงใใๅ ดๅใจๅ
้ ญใใญใใฏใฎ็ดๅพใฎใใญใใฏใงใใๅ ดๅ
if (block.Index == blockManager.headBlockIndex + 1 && (blockManager.headBlockIndex == -1 || block.PrevId.Equals(blockManager.GetHeadBlock().Id)))
{
VerifyBlockChain(blocksList, new Dictionary<Sha256Ripemd160Hash, List<Utxo>>(), new Dictionary<Sha256Ripemd160Hash, List<Utxo>>(), prevTxOutputssList);
UpdateBlockChainDB(blocksList, prevTxOutputssList, mainBlocksList, mainPrevTxOutputssList);
}
else
{
double mainCumulativeDiff = 0.0;
for (long i = block.Index; i <= blockManager.headBlockIndex; i++)
{
Block nextBlock = blockManager.GetMainBlock(i);
mainCumulativeDiff += nextBlock.Difficulty.Diff;
mainBlocksList.Add(nextBlock);
}
Block prevBlockBrunch = block;
Block prevBlockMain = block.Index > blockManager.headBlockIndex ? null : blockManager.GetMainBlock(block.Index);
CirculatedInteger ci = new CirculatedInteger(position, (int)capacity);
while (true)
{
if (prevBlockBrunch.Index == 0)
break;
if (prevBlockMain != null && prevBlockMain.PrevId.Equals(prevBlockBrunch.PrevId))
break;
long prevIndex = prevBlockBrunch.Index - 1;
if (prevIndex <= minBlockIndex)
return new UpdateChainInnerReturn(UpdateChainReturnType.rejected, ci.value, blocksList);
ci.Previous();
if (pendingBlocks[ci.value] == null || !pendingBlocks[ci.value].Keys.Contains(prevBlockBrunch.PrevId))
if (rejectedBlocks[ci.value] != null && rejectedBlocks[ci.value].Keys.Contains(prevBlockBrunch.PrevId))
return new UpdateChainInnerReturn(UpdateChainReturnType.rejected, ci.GetForward(1), blocksList);
else
return new UpdateChainInnerReturn(UpdateChainReturnType.pending, position);
prevBlockBrunch = pendingBlocks[ci.value][prevBlockBrunch.PrevId];
prevBlockMain = prevIndex > blockManager.headBlockIndex ? null : blockManager.GetMainBlock(prevIndex);
blocksList.Insert(0, prevBlockBrunch);
if (prevBlockMain != null)
mainBlocksList.Insert(0, prevBlockMain);
cumulativeDiff += prevBlockBrunch.Difficulty.Diff;
if (prevBlockMain != null)
mainCumulativeDiff += prevBlockMain.Difficulty.Diff;
}
if (cumulativeDiff <= mainCumulativeDiff)
return new UpdateChainInnerReturn(UpdateChainReturnType.pending, position);
Func<long, TransactionalBlock> _bindexToTxBlock = (bindex) =>
{
if (bindex <= blockManager.headBlockIndex)
return blockManager.GetMainBlock(bindex) as TransactionalBlock;
else
return null;
};
Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
for (int i = mainBlocksList.Count - 1; i >= 0; i--)
{
TransactionOutput[][] prevTxOutputss = GetPrevTxOutputss(mainBlocksList[i], _bindexToTxBlock);
if (prevTxOutputss == null)
throw new InvalidOperationException("blockchain_fork_main_backward");
mainPrevTxOutputssList.Insert(0, prevTxOutputss);
RetrieveTransactionTransitionBackward(mainBlocksList[i], prevTxOutputss, addedUtxos, removedUtxos);
}
cumulativeDiff = VerifyBlockChain(blocksList, addedUtxos, removedUtxos, prevTxOutputssList);
if (cumulativeDiff > mainCumulativeDiff)
UpdateBlockChainDB(blocksList, prevTxOutputssList, mainBlocksList, mainPrevTxOutputssList);
}
if (blocksList.Count != prevTxOutputssList.Count)
{
List<Block> rejecteds = new List<Block>();
for (int i = prevTxOutputssList.Count; i < blocksList.Count; i++)
rejecteds.Add(blocksList[i]);
List<Block> notRejecteds = new List<Block>();
for (int i = 0; i < prevTxOutputssList.Count; i++)
notRejecteds.Add(blocksList[i]);
Updated(this, notRejecteds);
return new UpdateChainInnerReturn(UpdateChainReturnType.updatedAndRejected, blocksCurrent.GetForward((int)(blocksList[prevTxOutputssList.Count].Index - blockManager.headBlockIndex)), rejecteds);
}
Updated(this, blocksList);
return new UpdateChainInnerReturn(UpdateChainReturnType.updated);
}
private void UpdateBlockChainDB(List<Block> blocksList, List<TransactionOutput[][]> prevTxOutputssList, List<Block> mainBlocksList, List<TransactionOutput[][]> mainPrevTxOutputssList)
{
long beforeIndex = headBlockIndex;
udb.Open();
are.Reset();
bcadb.Create();
List<AddressEvent> updatedAddressesList = new List<AddressEvent>();
List<AddressEvent> notupdatedAddressesList = new List<AddressEvent>(registeredAddresses.Keys);
Func<TransactionOutput, bool> _FindUpdatedAddressEvent = (txOut) =>
{
AddressEvent updatedAddressEvent = null;
foreach (var addressEvent in notupdatedAddressesList)
if (txOut.Address.Equals(addressEvent.address))
{
updatedAddressEvent = addressEvent;
break;
}
if (updatedAddressEvent != null)
{
updatedAddressesList.Add(updatedAddressEvent);
notupdatedAddressesList.Remove(updatedAddressEvent);
return true;
}
foreach (var addressEvent in updatedAddressesList)
if (txOut.Address.Equals(addressEvent.address))
return true;
return false;
};
Func<Transaction, List<TransactionOutput>, List<TransactionOutput>, TransactionHistoryType> _GetType = (transaction, receiversList, sendersList) =>
{
TransactionHistoryType type = TransactionHistoryType.mined;
if (!(transaction is CoinbaseTransaction))
{
if (receiversList.Count < transaction.TxOutputs.Length)
type = TransactionHistoryType.sent;
else if (sendersList.Count < transaction.TxInputs.Length)
type = TransactionHistoryType.received;
else
type = TransactionHistoryType.transfered;
}
return type;
};
Func<Block, Transaction, TransactionHistory, DateTime> _GetDatetime = (block, transaction, th) =>
{
DateTime datetime = DateTime.MinValue;
if (th != null)
datetime = th.datetime;
else if (transaction is CoinbaseTransaction)
datetime = (block as TransactionalBlock).header.timestamp;
return datetime;
};
List<TransactionOutput> senders = new List<TransactionOutput>();
List<TransactionOutput> receivers = new List<TransactionOutput>();
for (int i = mainBlocksList.Count - 1; i >= 0; i--)
{
for (int j = 0; j < mainBlocksList[i].Transactions.Length; j++)
{
senders.Clear();
receivers.Clear();
long sentAmount = 0;
long receivedAmount = 0;
for (int k = 0; k < mainBlocksList[i].Transactions[j].TxInputs.Length; k++)
if (_FindUpdatedAddressEvent(mainPrevTxOutputssList[i][j][k]))
{
sentAmount += mainPrevTxOutputssList[i][j][k].Amount.rawAmount;
senders.Add(mainPrevTxOutputssList[i][j][k]);
}
for (int k = 0; k < mainBlocksList[i].Transactions[j].TxOutputs.Length; k++)
if (_FindUpdatedAddressEvent(mainBlocksList[i].Transactions[j].TxOutputs[k]))
{
receivedAmount += mainBlocksList[i].Transactions[j].TxOutputs[k].Amount.rawAmount;
receivers.Add(mainBlocksList[i].Transactions[j].TxOutputs[k]);
}
if (senders.Count > 0 || receivers.Count > 0)
{
TransactionHistory th = ths.ContainsConformedTransactionHistory(mainBlocksList[i].Transactions[j].Id);
if (th != null)
ths.RemoveConfirmedTransactionHistory(mainBlocksList[i].Transactions[j].Id);
th = new TransactionHistory(true, false, _GetType(mainBlocksList[i].Transactions[j], receivers, senders), _GetDatetime(mainBlocksList[i], mainBlocksList[i].Transactions[j], th), 0, mainBlocksList[i].Transactions[j].Id, senders.ToArray(), receivers.ToArray(), mainBlocksList[i].Transactions[j], mainPrevTxOutputssList[i][j], new CurrencyUnit(sentAmount), new CurrencyUnit(receivedAmount - sentAmount));
ths.AddTransactionHistory(th);
}
}
blockManager.DeleteMainBlock(mainBlocksList[i].Index);
utxoManager.RevertBlock(mainBlocksList[i], mainPrevTxOutputssList[i]);
if (pendingBlocks[blocksCurrent.value] == null)
pendingBlocks[blocksCurrent.value] = new Dictionary<Creahash, Block>();
pendingBlocks[blocksCurrent.value].Add(mainBlocksList[i].Id, mainBlocksList[i]);
blocksCurrent.Previous();
}
for (int i = 0; i < prevTxOutputssList.Count; i++)
{
for (int j = 0; j < blocksList[i].Transactions.Length; j++)
{
senders.Clear();
receivers.Clear();
long sentAmount = 0;
long receivedAmount = 0;
for (int k = 0; k < blocksList[i].Transactions[j].TxInputs.Length; k++)
if (_FindUpdatedAddressEvent(prevTxOutputssList[i][j][k]))
{
sentAmount += prevTxOutputssList[i][j][k].Amount.rawAmount;
senders.Add(prevTxOutputssList[i][j][k]);
}
for (int k = 0; k < blocksList[i].Transactions[j].TxOutputs.Length; k++)
if (_FindUpdatedAddressEvent(blocksList[i].Transactions[j].TxOutputs[k]))
{
receivedAmount += blocksList[i].Transactions[j].TxOutputs[k].Amount.rawAmount;
receivers.Add(blocksList[i].Transactions[j].TxOutputs[k]);
}
if (senders.Count > 0 || receivers.Count > 0)
{
TransactionHistory th = ths.ContainsUnconformedTransactionHistory(blocksList[i].Transactions[j].Id);
if (th != null)
ths.RemoveUnconfirmedTransactionHistory(blocksList[i].Transactions[j].Id);
th = new TransactionHistory(true, true, _GetType(blocksList[i].Transactions[j], receivers, senders), _GetDatetime(blocksList[i], blocksList[i].Transactions[j], th), blocksList[i].Index, blocksList[i].Transactions[j].Id, senders.ToArray(), receivers.ToArray(), blocksList[i].Transactions[j], prevTxOutputssList[i][j], new CurrencyUnit(sentAmount), new CurrencyUnit(receivedAmount - sentAmount));
ths.AddTransactionHistory(th);
}
}
blockManager.AddMainBlock(blocksList[i]);
utxoManager.ApplyBlock(blocksList[i], prevTxOutputssList[i]);
blocksCurrent.Next();
if (pendingBlocks[blocksCurrent.value] != null && pendingBlocks[blocksCurrent.value].Keys.Contains(blocksList[i].Id))
pendingBlocks[blocksCurrent.value].Remove(blocksList[i].Id);
int nextMaxPosition = blocksCurrent.GetForward((int)maxBlockIndexMargin);
rejectedBlocks[nextMaxPosition] = null;
pendingBlocks[nextMaxPosition] = null;
}
utxoManager.SaveUFPTemp();
bcadb.Delete();
are.Set();
long minIndex = Math.Min(beforeIndex, headBlockIndex);
foreach (var addressEvent in updatedAddressesList)
{
List<Utxo> utxos = utxoManager.GetAllUtxosLatestFirst(addressEvent.address);
registeredAddresses[addressEvent] = utxos;
Tuple<CurrencyUnit, CurrencyUnit> balance = CalculateBalance(utxos);
addressEvent.RaiseBalanceUpdated(balance);
addressEvent.RaiseUsableBalanceUpdated(balance.Item1);
addressEvent.RaiseUnusableBalanceUpdated(balance.Item2);
}
bool flag = false;
foreach (var addressEvent in notupdatedAddressesList)
{
List<Utxo> utxos = registeredAddresses[addressEvent];
if (utxos.Count > 0 && utxos[0].blockIndex + unusableConformation > minIndex)
{
Tuple<CurrencyUnit, CurrencyUnit> balance = CalculateBalance(utxos);
addressEvent.RaiseBalanceUpdated(balance);
addressEvent.RaiseUsableBalanceUpdated(balance.Item1);
addressEvent.RaiseUnusableBalanceUpdated(balance.Item2);
flag = true;
}
}
udb.Close();
if (updatedAddressesList.Count > 0 || flag)
BalanceUpdated(this, EventArgs.Empty);
}
private void RetrieveTransactionTransitionForward(Block block, TransactionOutput[][] prevTxOutss, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
for (int i = 0; i < block.Transactions.Length; i++)
{
for (int j = 0; j < block.Transactions[i].TxInputs.Length; j++)
AddedRemoveAndRemovedAdd(prevTxOutss[i][j].Address, block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex, prevTxOutss[i][j].Amount, addedUtxos, removedUtxos);
for (int j = 0; j < block.Transactions[i].TxOutputs.Length; j++)
RemovedRemoveAndAddedAdd(block.Transactions[i].TxOutputs[j].Address, block.Index, i, j, block.Transactions[i].TxOutputs[j].Amount, addedUtxos, removedUtxos);
}
}
private void RetrieveTransactionTransitionBackward(Block block, TransactionOutput[][] prevTxOutss, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
for (int i = 0; i < block.Transactions.Length; i++)
{
for (int j = 0; j < block.Transactions[i].TxInputs.Length; j++)
RemovedRemoveAndAddedAdd(prevTxOutss[i][j].Address, block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex, prevTxOutss[i][j].Amount, addedUtxos, removedUtxos);
for (int j = 0; j < block.Transactions[i].TxOutputs.Length; j++)
AddedRemoveAndRemovedAdd(block.Transactions[i].TxOutputs[j].Address, block.Index, i, j, block.Transactions[i].TxOutputs[j].Amount, addedUtxos, removedUtxos);
}
}
//ๅพ้ใใๅ ดๅใฎๅๅผๅ
ฅๅ๏ผ่ขซๅ็
งๅๅผๅบๅ๏ผใฏๅ้ค้ๅใใๅ้ค or ่ฟฝๅ ้ๅใซ่ฟฝๅ
//ๅ้ฒใใๅ ดๅใฎๅๅผๅบๅใฏๅ้ค้ๅใใๅ้ค or ่ฟฝๅ ้ๅใซ่ฟฝๅ
private void RemovedRemoveAndAddedAdd(Sha256Ripemd160Hash address, long bindex, int txindex, int txoutindex, CurrencyUnit amount, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
if (removedUtxos.Keys.Contains(address))
{
Utxo utxo = removedUtxos[address].Where((elem) => elem.IsMatch(bindex, txindex, txoutindex)).FirstOrDefault();
if (utxo != null)
{
removedUtxos[address].Remove(utxo);
return;
}
}
List<Utxo> utxos = null;
if (addedUtxos.Keys.Contains(address))
utxos = addedUtxos[address];
else
addedUtxos.Add(address, utxos = new List<Utxo>());
utxos.Add(new Utxo(bindex, txindex, txoutindex, amount));
}
//ๅพ้ใใๅ ดๅใฎๅๅผๅบๅใฏ่ฟฝๅ ้ๅใใๅ้ค or ๅ้ค้ๅใซ่ฟฝๅ
//ๅ้ฒใใๅ ดๅใฎๅๅผๅ
ฅๅ๏ผ่ขซๅ็
งๅๅผๅบๅ๏ผใฏ่ฟฝๅ ้ๅใใๅ้ค or ๅ้ค้ๅใซ่ฟฝๅ
private void AddedRemoveAndRemovedAdd(Sha256Ripemd160Hash address, long bindex, int txindex, int txoutindex, CurrencyUnit amount, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
if (addedUtxos.Keys.Contains(address))
{
Utxo utxo = addedUtxos[address].Where((elem) => elem.IsMatch(bindex, txindex, txoutindex)).FirstOrDefault();
if (utxo != null)
{
addedUtxos[address].Remove(utxo);
return;
}
}
List<Utxo> utxos = null;
if (removedUtxos.Keys.Contains(address))
utxos = removedUtxos[address];
else
removedUtxos.Add(address, utxos = new List<Utxo>());
utxos.Add(new Utxo(bindex, txindex, txoutindex, amount));
}
private TransactionOutput[][] GetPrevTxOutputss(Block block, Func<long, TransactionalBlock> _bindexToBlock)
{
TransactionOutput[][] prevTxOutputss = new TransactionOutput[block.Transactions.Length][];
for (int i = 0; i < block.Transactions.Length; i++)
{
prevTxOutputss[i] = new TransactionOutput[block.Transactions[i].TxInputs.Length];
for (int j = 0; j < block.Transactions[i].TxInputs.Length; j++)
{
Block prevBlock = _bindexToBlock(block.Transactions[i].TxInputs[j].PrevTxBlockIndex);
if (prevBlock == null)
return null;
if (block.Transactions[i].TxInputs[j].PrevTxIndex >= prevBlock.Transactions.Length)
return null;
Transaction prevTx = prevBlock.Transactions[block.Transactions[i].TxInputs[j].PrevTxIndex];
if (block.Transactions[i].TxInputs[j].PrevTxOutputIndex >= prevTx.TxOutputs.Length)
return null;
prevTxOutputss[i][j] = prevTx.TxOutputs[block.Transactions[i].TxInputs[j].PrevTxOutputIndex];
}
}
return prevTxOutputss;
}
private bool VerifyUtxo(Block block, TransactionOutput[][] prevTxOutss, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos2 = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
for (int i = 0; i < block.Transactions.Length; i++)
for (int j = 0; j < block.Transactions[i].TxInputs.Length; j++)
{
if (removedUtxos2.Keys.Contains(prevTxOutss[i][j].Address) && removedUtxos2[prevTxOutss[i][j].Address].Where((elem) => elem.IsMatch(block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex)).FirstOrDefault() != null)
return false;
if (removedUtxos.Keys.Contains(prevTxOutss[i][j].Address) && removedUtxos[prevTxOutss[i][j].Address].Where((elem) => elem.IsMatch(block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex)).FirstOrDefault() != null)
return false;
List<Utxo> utxos;
if (!removedUtxos2.Keys.Contains(prevTxOutss[i][j].Address))
removedUtxos2.Add(prevTxOutss[i][j].Address, utxos = new List<Utxo>());
else
utxos = removedUtxos2[prevTxOutss[i][j].Address];
utxos.Add(new Utxo(block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex, prevTxOutss[i][j].Amount));
if (addedUtxos.Keys.Contains(prevTxOutss[i][j].Address) && addedUtxos[prevTxOutss[i][j].Address].Where((elem) => elem.IsMatch(block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex)).FirstOrDefault() != null)
continue;
if (utxoManager.FindUtxo(prevTxOutss[i][j].Address, block.Transactions[i].TxInputs[j].PrevTxBlockIndex, block.Transactions[i].TxInputs[j].PrevTxIndex, block.Transactions[i].TxInputs[j].PrevTxOutputIndex) == null)
return false;
}
return true;
}
}
//2014/12/04 ่ฉฆ้จๆธ
public class BlockManager
{
public BlockManager(BlockManagerDB _bmdb, BlockDB _bdb, BlockFilePointersDB _bfpdb, int _mainBlocksRetain, int _oldBlocksRetain, long _mainBlockFinalization)
{
if (_mainBlocksRetain < _mainBlockFinalization)
throw new InvalidOperationException();
bmdb = _bmdb;
bdb = _bdb;
bfpdb = _bfpdb;
mainBlocksRetain = _mainBlocksRetain;
oldBlocksRetain = _oldBlocksRetain;
mainBlockFinalization = _mainBlockFinalization;
bmd = bmdb.GetData().Pipe((bmdBytes) => bmdBytes.Length != 0 ? SHAREDDATA.FromBinary<BlockManagerData>(bmdBytes) : new BlockManagerData());
mainBlocks = new Block[mainBlocksRetain];
sideBlocks = new List<Block>[mainBlocksRetain];
mainBlocksCurrent = new CirculatedInteger(mainBlocksRetain);
oldBlocks = new Dictionary<long, Block>();
}
private static readonly long blockFileCapacity = 100000;
public readonly int mainBlocksRetain;
public readonly int oldBlocksRetain;
public readonly long mainBlockFinalization;
private readonly BlockManagerDB bmdb;
private readonly BlockDB bdb;
private readonly BlockFilePointersDB bfpdb;
private readonly BlockManagerData bmd;
public readonly Block[] mainBlocks;
//<ๆชๆน่ฏ>ใฉใใซไฟๅญใใใใไฟๆใใฆใใใชใใจๆๅณใใชใ
public readonly List<Block>[] sideBlocks;
public readonly CirculatedInteger mainBlocksCurrent;
public readonly Dictionary<long, Block> oldBlocks;
public long headBlockIndex { get { return bmd.headBlockIndex; } }
public long finalizedBlockIndex { get { return bmd.finalizedBlockIndex; } }
public void DeleteMainBlock(long blockIndex)
{
if (blockIndex != bmd.headBlockIndex)
throw new InvalidOperationException();
if (blockIndex <= bmd.finalizedBlockIndex)
throw new InvalidOperationException();
if (blockIndex < 0)
throw new InvalidOperationException();
if (sideBlocks[mainBlocksCurrent.value] == null)
sideBlocks[mainBlocksCurrent.value] = new List<Block>();
if (sideBlocks[mainBlocksCurrent.value].Where((elem) => elem.Id.Equals(mainBlocks[mainBlocksCurrent.value].Id)).FirstOrDefault() == null)
sideBlocks[mainBlocksCurrent.value].Add(mainBlocks[mainBlocksCurrent.value]);
mainBlocks[mainBlocksCurrent.value] = null;
mainBlocksCurrent.Previous();
bmd.headBlockIndex = blockIndex - 1;
bmdb.UpdateData(bmd.ToBinary());
}
public void DeleteMainBlocks(long blockIndex)
{
}
//<ๆชๆน่ฏ>sideBlocksใไฝฟใใใใซ
public void AddMainBlock(Block block)
{
if (block.Index != bmd.headBlockIndex + 1)
throw new InvalidOperationException();
mainBlocksCurrent.Next();
mainBlocks[mainBlocksCurrent.value] = block;
sideBlocks[mainBlocksCurrent.value] = new List<Block>();
bmd.headBlockIndex = block.Index;
bmd.finalizedBlockIndex = bmd.headBlockIndex < mainBlockFinalization ? 0 : bmd.headBlockIndex - mainBlockFinalization;
bfpdb.UpdateBlockFilePointerData(block.Index, bdb.AddBlockData(block.Index / blockFileCapacity, SHAREDDATA.ToBinary<Block>(block)));
bmdb.UpdateData(bmd.ToBinary());
}
public void AddMainBlocks(Block[] blocks)
{
}
public Block GetHeadBlock() { return GetMainBlock(bmd.headBlockIndex); }
public Block GetMainBlock(long blockIndex)
{
if (blockIndex > bmd.headBlockIndex)
throw new InvalidOperationException();
if (blockIndex < 0)
throw new InvalidOperationException();
if (blockIndex > bmd.headBlockIndex - mainBlocksRetain)
{
int index = mainBlocksCurrent.GetBackward((int)(bmd.headBlockIndex - blockIndex));
if (mainBlocks[index] == null)
mainBlocks[index] = SHAREDDATA.FromBinary<Block>(bdb.GetBlockData(blockIndex / blockFileCapacity, bfpdb.GetBlockFilePointerData(blockIndex)));
if (mainBlocks[index].Index != blockIndex)
throw new InvalidOperationException();
return mainBlocks[index];
}
if (oldBlocks.Keys.Contains(blockIndex))
return oldBlocks[blockIndex];
Block block = SHAREDDATA.FromBinary<Block>(bdb.GetBlockData(blockIndex / blockFileCapacity, bfpdb.GetBlockFilePointerData(blockIndex)));
if (block.Index != blockIndex)
throw new InvalidOperationException();
oldBlocks.Add(blockIndex, block);
while (oldBlocks.Count > oldBlocksRetain)
oldBlocks.Remove(oldBlocks.First().Key);
return block;
}
//<ๆชๆน่ฏ>ไธๆฌๅๅพ
//2014/12/01 ่ฉฆ้จ้คๅคใไธๆฌๅๅพใๅฎ่ฃ
ใใใ่ฉฆ้จใใ
public Block[] GetMainBlocks(long[] blockIndexes)
{
Block[] blocks = new Block[blockIndexes.Length];
for (int i = 0; i < blocks.Length; i++)
blocks[i] = GetMainBlock(blockIndexes[i]);
return blocks;
}
//<ๆชๆน่ฏ>ไธๆฌๅๅพ
//2014/12/01 ่ฉฆ้จ้คๅคใไธๆฌๅๅพใๅฎ่ฃ
ใใใ่ฉฆ้จใใ
public Block[] GetMainBlocks(long blockIndexFrom, long blockIndexThrough)
{
if (blockIndexFrom > blockIndexThrough)
throw new InvalidOperationException();
Block[] blocks = new Block[blockIndexThrough - blockIndexFrom + 1];
for (int i = 0; i < blocks.Length; i++)
blocks[i] = GetMainBlock(blockIndexFrom + i);
return blocks;
}
}
public class BlockManagerData : SHAREDDATA
{
public BlockManagerData()
: base(0)
{
headBlockIndex = -1;
finalizedBlockIndex = -1;
}
public long headBlockIndex { get; set; }
public long finalizedBlockIndex { get; set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => headBlockIndex, (o) => headBlockIndex = (long)o),
new MainDataInfomation(typeof(long), () => finalizedBlockIndex, (o) => finalizedBlockIndex = (long)o),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
}
//2014/12/04 ่ฉฆ้จๆธ
public class UtxoManager
{
public UtxoManager(UtxoFileAccessDB _ufadb, UtxoFilePointersDB _ufpdb, UtxoFilePointersTempDB _ufptempdb, UtxoDB _udb)
{
ufadb = _ufadb;
ufpdb = _ufpdb;
ufptempdb = _ufptempdb;
udb = _udb;
ufp = ufpdb.GetData().Pipe((bytes) => bytes.Length == 0 ? new UtxoFilePointers() : SHAREDDATA.FromBinary<UtxoFilePointers>(bytes));
ufptemp = ufptempdb.GetData().Pipe((bytes) => bytes.Length == 0 ? new UtxoFilePointers() : SHAREDDATA.FromBinary<UtxoFilePointers>(bytes));
foreach (var ufpitem in ufptemp.GetAll())
ufp.AddOrUpdate(ufpitem.Key, ufpitem.Value);
ufadb.Create();
ufpdb.UpdateData(ufp.ToBinary());
ufptempdb.Delete();
ufadb.Delete();
ufptemp = new UtxoFilePointers();
}
private static readonly int FirstUtxoFileItemSize = 16;
private readonly UtxoFileAccessDB ufadb;
private readonly UtxoFilePointersDB ufpdb;
private readonly UtxoFilePointersTempDB ufptempdb;
private readonly UtxoDB udb;
private readonly UtxoFilePointers ufp;
private readonly UtxoFilePointers ufptemp;
public void AddUtxo(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex, CurrencyUnit amount)
{
bool isExistedInTemp = false;
long? position = ufptemp.Get(address);
if (position.HasValue)
isExistedInTemp = true;
else
position = ufp.Get(address);
bool isProcessed = false;
bool isFirst = true;
long? firstPosition = null;
int? firstSize = null;
UtxoFileItem ufi = null;
while (true)
{
if (!position.HasValue)
ufi = new UtxoFileItem(FirstUtxoFileItemSize);
else if (position == -1)
ufi = new UtxoFileItem(firstSize.Value * 2);
else
ufi = SHAREDDATA.FromBinary<UtxoFileItem>(udb.GetUtxoData(position.Value));
if (isFirst)
{
firstPosition = position;
firstSize = ufi.Size;
isFirst = false;
}
for (int i = 0; i < ufi.Size; i++)
if (ufi.utxos[i].IsEmpty)
{
ufi.utxos[i].Reset(blockIndex, txIndex, txOutIndex, amount);
if (!position.HasValue)
ufptemp.Add(address, udb.AddUtxoData(ufi.ToBinary()));
else if (position == -1)
{
ufi.Update(firstPosition.Value);
if (isExistedInTemp)
ufptemp.Update(address, udb.AddUtxoData(ufi.ToBinary()));
else
ufptemp.Add(address, udb.AddUtxoData(ufi.ToBinary()));
}
else
udb.UpdateUtxoData(position.Value, ufi.ToBinary());
isProcessed = true;
break;
}
if (isProcessed)
break;
position = ufi.nextPosition;
}
}
public void RemoveUtxo(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
long? position = ufptemp.Get(address);
if (!position.HasValue)
position = ufp.Get(address);
if (!position.HasValue)
throw new InvalidOperationException("utxo_address_not_exist");
bool isProcessed = false;
while (position.Value != -1)
{
UtxoFileItem ufi = SHAREDDATA.FromBinary<UtxoFileItem>(udb.GetUtxoData(position.Value));
for (int i = 0; i < ufi.Size; i++)
if (ufi.utxos[i].IsMatch(blockIndex, txIndex, txOutIndex))
{
ufi.utxos[i].Empty();
udb.UpdateUtxoData(position.Value, ufi.ToBinary());
isProcessed = true;
break;
}
if (isProcessed)
break;
position = ufi.nextPosition;
}
if (!isProcessed)
throw new InvalidOperationException("utxo_not_exist");
}
public void SaveUFPTemp()
{
ufptempdb.UpdateData(ufptemp.ToBinary());
}
public Utxo FindUtxo(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
long? position = ufptemp.Get(address);
if (!position.HasValue)
position = ufp.Get(address);
if (!position.HasValue)
return null;
while (position.Value != -1)
{
UtxoFileItem ufi = SHAREDDATA.FromBinary<UtxoFileItem>(udb.GetUtxoData(position.Value));
for (int i = 0; i < ufi.Size; i++)
if (ufi.utxos[i].IsMatch(blockIndex, txIndex, txOutIndex))
return ufi.utxos[i];
position = ufi.nextPosition;
}
return null;
}
public List<Utxo> GetAllUtxos(Sha256Ripemd160Hash address)
{
List<Utxo> utxos = new List<Utxo>();
long? position = ufptemp.Get(address);
if (!position.HasValue)
position = ufp.Get(address);
if (position.HasValue)
while (position.Value != -1)
{
UtxoFileItem ufi = SHAREDDATA.FromBinary<UtxoFileItem>(udb.GetUtxoData(position.Value));
for (int i = 0; i < ufi.Size; i++)
if (!ufi.utxos[i].IsEmpty)
utxos.Add(ufi.utxos[i]);
position = ufi.nextPosition;
}
return utxos;
}
public List<Utxo> GetAllUtxosLatestFirst(Sha256Ripemd160Hash address)
{
Utxo latestUtxo = null;
List<Utxo> utxos = new List<Utxo>();
long? position = ufptemp.Get(address);
if (!position.HasValue)
position = ufp.Get(address);
if (position.HasValue)
while (position.Value != -1)
{
UtxoFileItem ufi = SHAREDDATA.FromBinary<UtxoFileItem>(udb.GetUtxoData(position.Value));
for (int i = 0; i < ufi.Size; i++)
if (!ufi.utxos[i].IsEmpty)
if (latestUtxo == null)
latestUtxo = ufi.utxos[i];
else if (ufi.utxos[i].blockIndex > latestUtxo.blockIndex)
{
utxos.Add(latestUtxo);
latestUtxo = ufi.utxos[i];
}
else
utxos.Add(ufi.utxos[i]);
position = ufi.nextPosition;
}
if (latestUtxo != null)
utxos.Insert(0, latestUtxo);
return utxos;
}
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public void ApplyBlock(Block block, TransactionOutput[][] prevTxOutss)
{
if (block.Transactions.Length != prevTxOutss.Length)
throw new InvalidOperationException("apply_blk_num_of_txs_mismatch");
block.Transactions.ForEach((i, tx) =>
{
if (tx.TxInputs.Length != prevTxOutss[i].Length)
throw new InvalidOperationException("apply_blk_num_of_txin_and_txout_mismatch");
tx.TxInputs.ForEach((j, txIn) => RemoveUtxo(prevTxOutss[i][j].Address, txIn.PrevTxBlockIndex, txIn.PrevTxIndex, txIn.PrevTxOutputIndex));
tx.TxOutputs.ForEach((j, txOut) => AddUtxo(txOut.Address, block.Index, i, j, txOut.Amount));
});
}
//prevTxOutssใฏๅ
จใฆใฎๅๅผใซๅฏพใใใใฎใๅซใใงใใชใใใฐใชใใชใใใจใซๆณจๆ
//่ฒจๅนฃ็งปๅๅๅผใฎใฟใชใใ่ฒจๅนฃ็ๆๅๅผใซๅฏพใใใใฎ๏ผ่ฒจๅนฃ็ๆๅๅผใฎๅ ดๅๅๅผๅ
ฅๅใฏ0ๅใงใใใใ็ฉบใซใชใ็ญ๏ผใๅซใใงใใชใใใฐใชใใชใ
public void RevertBlock(Block block, TransactionOutput[][] prevTxOutss)
{
if (block.Transactions.Length != prevTxOutss.Length)
throw new InvalidOperationException("revert_blk_num_of_txs_mismatch");
block.Transactions.ForEach((i, tx) =>
{
if (tx.TxInputs.Length != prevTxOutss[i].Length)
throw new InvalidOperationException("revert_blk_num_of_txin_and_txout_mismatch");
tx.TxInputs.ForEach((j, txIn) => AddUtxo(prevTxOutss[i][j].Address, txIn.PrevTxBlockIndex, txIn.PrevTxIndex, txIn.PrevTxOutputIndex, prevTxOutss[i][j].Amount));
tx.TxOutputs.ForEach((j, txOut) => RemoveUtxo(txOut.Address, block.Index, i, j));
});
}
}
//2014/11/27 ่ฉฆ้จๆธ
public class UtxoFilePointers : SHAREDDATA
{
public UtxoFilePointers() : base(null) { addressFilePointers = new Dictionary<Sha256Ripemd160Hash, long>(); }
private Dictionary<Sha256Ripemd160Hash, long> addressFilePointers;
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo { get { return (msrw) => StreamInfoInner(msrw); } }
private IEnumerable<MainDataInfomation> StreamInfoInner(ReaderWriter msrw)
{
Sha256Ripemd160Hash[] addresses = addressFilePointers.Keys.ToArray();
long[] positions = addressFilePointers.Values.ToArray();
yield return new MainDataInfomation(typeof(Sha256Ripemd160Hash[]), null, null, () => addresses, (o) => addresses = (Sha256Ripemd160Hash[])o);
yield return new MainDataInfomation(typeof(long[]), null, () => positions, (o) =>
{
positions = (long[])o;
if (addresses.Length != positions.Length)
throw new InvalidOperationException();
addressFilePointers = new Dictionary<Sha256Ripemd160Hash, long>();
for (int i = 0; i < addresses.Length; i++)
addressFilePointers.Add(addresses[i], positions[i]);
});
}
public void Add(Sha256Ripemd160Hash address, long position)
{
if (addressFilePointers.Keys.Contains(address))
throw new InvalidOperationException();
addressFilePointers.Add(address, position);
}
public void Remove(Sha256Ripemd160Hash address)
{
if (!addressFilePointers.Keys.Contains(address))
throw new InvalidOperationException();
addressFilePointers.Remove(address);
}
public void Update(Sha256Ripemd160Hash address, long positionNew)
{
if (!addressFilePointers.Keys.Contains(address))
throw new InvalidOperationException();
addressFilePointers[address] = positionNew;
}
public void AddOrUpdate(Sha256Ripemd160Hash address, long position)
{
if (addressFilePointers.Keys.Contains(address))
addressFilePointers[address] = position;
else
addressFilePointers.Add(address, position);
}
public long? Get(Sha256Ripemd160Hash address)
{
return addressFilePointers.Keys.Contains(address) ? (long?)addressFilePointers[address] : null;
}
public Dictionary<Sha256Ripemd160Hash, long> GetAll() { return addressFilePointers; }
}
public class Utxo : SHAREDDATA
{
public Utxo() : base(null) { amount = new CurrencyUnit(0); }
public Utxo(long _blockIndex, int _txIndex, int _txOutIndex, CurrencyUnit _amount)
: base(null)
{
blockIndex = _blockIndex;
txIndex = _txIndex;
txOutIndex = _txOutIndex;
amount = _amount;
}
public long blockIndex { get; private set; }
public int txIndex { get; private set; }
public int txOutIndex { get; private set; }
public CurrencyUnit amount { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => blockIndex, (o) => blockIndex = (long)o),
new MainDataInfomation(typeof(int), () => txIndex, (o) => txIndex = (int)o),
new MainDataInfomation(typeof(int), () => txOutIndex, (o) => txOutIndex = (int)o),
new MainDataInfomation(typeof(long), () => amount.rawAmount, (o) => amount = new CurrencyUnit((long)o)),
};
}
}
public bool IsEmpty { get { return blockIndex == 0; } }
public void Empty()
{
blockIndex = 0;
txIndex = 0;
txOutIndex = 0;
amount = CurrencyUnit.Zero;
}
public void Reset(long _blockIndex, int _txIndex, int _txOutIndex, CurrencyUnit _amount)
{
blockIndex = _blockIndex;
txIndex = _txIndex;
txOutIndex = _txOutIndex;
amount = _amount;
}
public bool IsMatch(long _blockIndex, int _txIndex, int _txOutIndex)
{
return blockIndex == _blockIndex && txIndex == _txIndex && txOutIndex == _txOutIndex;
}
public bool IsMatch(long _blockIndex, int _txIndex, int _txOutIndex, CurrencyUnit _amount)
{
return blockIndex == _blockIndex && txIndex == _txIndex && txOutIndex == _txOutIndex && amount.Amount == _amount.Amount;
}
}
//2014/11/26 ่ฉฆ้จๆธ
public class UtxoFileItem : SHAREDDATA
{
public UtxoFileItem() : base(null) { }
public UtxoFileItem(int _size)
: base(null)
{
utxos = new Utxo[_size];
for (int i = 0; i < utxos.Length; i++)
utxos[i] = new Utxo();
nextPosition = -1;
}
public Utxo[] utxos { get; private set; }
public long nextPosition { get; private set; }
public int Size { get { return utxos.Length; } }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(Utxo[]), null, null, () => utxos, (o) => utxos = (Utxo[])o),
new MainDataInfomation(typeof(long), () => nextPosition, (o) => nextPosition = (long)o),
};
}
}
public void Update(long nextPositionNew) { nextPosition = nextPositionNew; }
}
#endregion
public enum TransactionHistoryType { mined, transfered, sent, received }
public class TransactionHistory : SHAREDDATA
{
public TransactionHistory() : base(0) { }
public TransactionHistory(bool _isValid, bool _isConfirmed, TransactionHistoryType _type, DateTime _datetime, long _blockIndex, Sha256Sha256Hash _id, TransactionOutput[] _senders, TransactionOutput[] _receivers, Transaction _transaction, TransactionOutput[] _prevTxOuts, CurrencyUnit _amountDependent, CurrencyUnit _amount)
: base(0)
{
isValid = _isValid;
isConfirmed = _isConfirmed;
type = _type;
datetime = _datetime;
blockIndex = _blockIndex;
id = _id;
senders = _senders;
receivers = _receivers;
transaction = _transaction;
prevTxOuts = _prevTxOuts;
amountDependent = _amountDependent;
amount = _amount;
}
public bool isValid { get; private set; }
public bool isConfirmed { get; private set; }
public TransactionHistoryType type { get; private set; }
public DateTime datetime { get; private set; }
public long blockIndex { get; private set; }
public Sha256Sha256Hash id { get; private set; }
public TransactionOutput[] senders { get; private set; }
public TransactionOutput[] receivers { get; private set; }
public Transaction transaction { get; private set; }
public TransactionOutput[] prevTxOuts { get; private set; }
public CurrencyUnit amountDependent { get; private set; }
public CurrencyUnit amount { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(bool), () => isValid, (o) => isValid = (bool)o),
new MainDataInfomation(typeof(bool), () => isConfirmed, (o) => isConfirmed = (bool)o),
new MainDataInfomation(typeof(int), () => (int)type, (o) => type = (TransactionHistoryType)o),
new MainDataInfomation(typeof(DateTime), () => datetime, (o) => datetime = (DateTime)o),
new MainDataInfomation(typeof(long), () => blockIndex, (o) => blockIndex = (long)o),
new MainDataInfomation(typeof(Sha256Sha256Hash), null, () => id, (o) => id = (Sha256Sha256Hash)o),
new MainDataInfomation(typeof(TransactionOutput[]), 0, null, () => senders, (o) => senders = (TransactionOutput[])o),
new MainDataInfomation(typeof(TransactionOutput[]), 0, null, () => receivers, (o) => receivers = (TransactionOutput[])o),
new MainDataInfomation(typeof(Transaction), 0, () => transaction, (o) => transaction = (Transaction)o),
new MainDataInfomation(typeof(TransactionOutput[]), 0, null, () => prevTxOuts, (o) => prevTxOuts = (TransactionOutput[])o),
new MainDataInfomation(typeof(long), () => amountDependent.rawAmount, (o) => amountDependent = new CurrencyUnit((long)o)),
new MainDataInfomation(typeof(long), () => amount.rawAmount, (o) => amount = new CurrencyUnit((long)o)),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked { get { return false; } }
}
public class TransactionHistories : SHAREDDATA
{
public TransactionHistories()
: base(0)
{
invalidTransactionHistories = new List<TransactionHistory>();
unconfirmedTransactionHistories = new List<TransactionHistory>();
confirmedTransactionHistories = new List<TransactionHistory>();
}
public List<TransactionHistory> invalidTransactionHistories { get; private set; }
public List<TransactionHistory> unconfirmedTransactionHistories { get; private set; }
public List<TransactionHistory> confirmedTransactionHistories { get; private set; }
public event EventHandler<TransactionHistory> InvalidTransactionAdded = delegate { };
public event EventHandler<TransactionHistory> InvalidTransactionRemoved = delegate { };
public event EventHandler<TransactionHistory> UnconfirmedTransactionAdded = delegate { };
public event EventHandler<TransactionHistory> UnconfirmedTransactionRemoved = delegate { };
public event EventHandler<TransactionHistory> ConfirmedTransactionAdded = delegate { };
public event EventHandler<TransactionHistory> ConfirmedTransactionRemoved = delegate { };
public void AddTransactionHistory(TransactionHistory th)
{
if (!th.isValid)
{
invalidTransactionHistories.Insert(0, th);
InvalidTransactionAdded(this, th);
}
else if (!th.isConfirmed)
{
unconfirmedTransactionHistories.Insert(0, th);
UnconfirmedTransactionAdded(this, th);
}
else
{
confirmedTransactionHistories.Insert(0, th);
ConfirmedTransactionAdded(this, th);
}
}
public void RemoveInvalidTransactionHistory(Sha256Sha256Hash id)
{
TransactionHistory th = invalidTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
if (th != null)
{
invalidTransactionHistories.Remove(th);
InvalidTransactionRemoved(this, th);
}
}
public void RemoveUnconfirmedTransactionHistory(Sha256Sha256Hash id)
{
TransactionHistory th = unconfirmedTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
if (th != null)
{
unconfirmedTransactionHistories.Remove(th);
UnconfirmedTransactionRemoved(this, th);
}
}
public void RemoveConfirmedTransactionHistory(Sha256Sha256Hash id)
{
TransactionHistory th = confirmedTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
if (th != null)
{
confirmedTransactionHistories.Remove(th);
ConfirmedTransactionRemoved(this, th);
}
}
public TransactionHistory ContainsInvalidTransactionHistory(Sha256Sha256Hash id)
{
return invalidTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
}
public TransactionHistory ContainsUnconformedTransactionHistory(Sha256Sha256Hash id)
{
return unconfirmedTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
}
public TransactionHistory ContainsConformedTransactionHistory(Sha256Sha256Hash id)
{
return confirmedTransactionHistories.FirstOrDefault((elem) => elem.id.Equals(id));
}
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
if (Version == 0)
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(TransactionHistory[]), 0, null, () => invalidTransactionHistories.ToArray(), (o) => invalidTransactionHistories = new List<TransactionHistory>((TransactionHistory[])o)),
new MainDataInfomation(typeof(TransactionHistory[]), 0, null, () => unconfirmedTransactionHistories.ToArray(), (o) => unconfirmedTransactionHistories = new List<TransactionHistory>((TransactionHistory[])o)),
new MainDataInfomation(typeof(TransactionHistory[]), 0, null, () => confirmedTransactionHistories.ToArray(), (o) => confirmedTransactionHistories = new List<TransactionHistory>((TransactionHistory[])o)),
};
else
throw new NotSupportedException();
}
}
public override bool IsVersioned { get { return true; } }
public override bool IsCorruptionChecked { get { return true; } }
}
public class Mining
{
public Mining()
{
are = new AutoResetEvent(false);
this.StartTask("mining", "mining", () =>
{
byte[] bytes = new byte[10];
int counter = 0;
DateTime datetime1 = DateTime.Now;
DateTime datetime2 = DateTime.Now;
while (true)
{
TransactionalBlock txBlockCopy = txBlock;
while (!isStarted || txBlockCopy == null)
{
are.WaitOne(30000);
txBlockCopy = txBlock;
are.Reset();
}
txBlockCopy.UpdateTimestamp(datetime1 = DateTime.Now);
txBlockCopy.UpdateNonce(bytes);
if (datetime1.Second != datetime2.Second)
{
this.RaiseNotification("hash_rate", 5, counter.ToString());
datetime2 = datetime1;
counter = 0;
}
else
counter++;
if (txBlockCopy.Id.CompareTo(txBlockCopy.header.difficulty.Target) < 0)
{
this.RaiseNotification("found_block", 5);
txBlock = null;
FoundNonce(this, txBlockCopy);
}
if (bytes[0] != 255)
bytes[0]++;
else if (bytes[1] != 255)
{
bytes[1]++;
bytes[0] = 0;
}
else if (bytes[2] != 255)
{
bytes[2]++;
bytes[0] = bytes[1] = 0;
}
else if (bytes[3] != 255)
{
bytes[3]++;
bytes[0] = bytes[1] = bytes[2] = 0;
}
else
bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
}
});
}
private TransactionalBlock txBlock;
private AutoResetEvent are;
public bool isStarted { get; private set; }
public event EventHandler<TransactionalBlock> FoundNonce = delegate { };
public void Start()
{
if (isStarted)
throw new InvalidOperationException("already_started");
isStarted = true;
}
public void End()
{
if (!isStarted)
throw new InvalidOperationException("not_yet_started");
isStarted = false;
}
public void NewMiningBlock(TransactionalBlock newTxBlock)
{
txBlock = newTxBlock;
are.Set();
}
}
#endregion
#region ใใผใฟใใผใน
public abstract class DATABASEBASE
{
public DATABASEBASE(string _pathBase)
{
pathBase = _pathBase;
if (!Directory.Exists(pathBase))
Directory.CreateDirectory(pathBase);
}
public readonly string pathBase;
protected abstract string filenameBase { get; }
protected abstract int version { get; }
}
public abstract class SimpleDatabase : DATABASEBASE
{
public SimpleDatabase(string _pathBase) : base(_pathBase) { }
public virtual byte[] GetData()
{
using (FileStream fs = new FileStream(GetPath(), FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
return data;
}
}
public virtual void UpdateData(byte[] data)
{
using (FileStream fs = new FileStream(GetPath(), FileMode.Create, FileAccess.Write))
fs.Write(data, 0, data.Length);
}
public string GetPath() { return Path.Combine(pathBase, filenameBase); }
}
public class FirstNodeInfosDatabase : SimpleDatabase
{
public FirstNodeInfosDatabase(string _pathBase) : base(_pathBase) { }
protected override string filenameBase { get { return "nodes" + version.ToString() + ".txt"; } }
protected override int version { get { return 0; } }
public string[] GetFirstNodeInfosData() { return Encoding.UTF8.GetString(GetData()).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); }
public void UpdateFirstNodeInfosData(string[] nodes) { UpdateData(Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, nodes))); }
}
public class AccountHoldersDatabase : SimpleDatabase
{
public AccountHoldersDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "acc_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "acc"; } }
#endif
}
public class TransactionHistoriesDatabase : SimpleDatabase
{
public TransactionHistoriesDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "th_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "th"; } }
#endif
}
public class BlockchainAccessDB : DATABASEBASE
{
public BlockchainAccessDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blkchain_access_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxos" + version.ToString(); } }
#endif
public void Create()
{
try
{
string path = GetPath();
if (File.Exists(path))
throw new InvalidOperationException("blkchain_access_file_exist");
File.WriteAllText(path, string.Empty);
}
catch (Exception ex)
{
throw new ApplicationException("fatal:blkchain_access", ex);
}
}
public void Delete()
{
try
{
string path = GetPath();
if (!File.Exists(path))
throw new InvalidOperationException("blkchain_access_file_not_exist");
File.Delete(path);
}
catch (Exception ex)
{
throw new ApplicationException("fatal:blkchain_access", ex);
}
}
public string GetPath() { return System.IO.Path.Combine(pathBase, filenameBase); }
}
public class BlockManagerDB : SimpleDatabase
{
public BlockManagerDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blk_mng_test_" + version.ToString(); } }
#else
protected override string filenameBase { get { return "blk_mng_" + version.ToString(); } }
#endif
}
//2014/12/01 ่ฉฆ้จๆธ
public class BlockDB : DATABASEBASE
{
public BlockDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blks_test" + version.ToString() + "_"; } }
#else
protected override string filenameBase { get { return "blks" + version.ToString() + "_"; } }
#endif
public byte[] GetBlockData(long blockFileIndex, long position)
{
using (FileStream fs = new FileStream(GetPath(blockFileIndex), FileMode.OpenOrCreate, FileAccess.Read))
return GetBlockData(fs, position);
}
public byte[][] GetBlockDatas(long blockFileIndex, long[] positions)
{
byte[][] blockDatas = new byte[positions.Length][];
using (FileStream fs = new FileStream(GetPath(blockFileIndex), FileMode.OpenOrCreate, FileAccess.Read))
for (int i = 0; i < positions.Length; i++)
blockDatas[i] = GetBlockData(fs, positions[i]);
return blockDatas;
}
public long AddBlockData(long blockFileIndex, byte[] blockData)
{
using (FileStream fs = new FileStream(GetPath(blockFileIndex), FileMode.Append, FileAccess.Write))
return AddBlockData(fs, blockFileIndex, blockData);
}
public long[] AddBlockDatas(long blockFileIndex, byte[][] blockDatas)
{
long[] positions = new long[blockDatas.Length];
using (FileStream fs = new FileStream(GetPath(blockFileIndex), FileMode.Append, FileAccess.Write))
for (int i = 0; i < blockDatas.Length; i++)
positions[i] = AddBlockData(fs, blockFileIndex, blockDatas[i]);
return positions;
}
private byte[] GetBlockData(FileStream fs, long position)
{
if (position >= fs.Length)
return new byte[] { };
fs.Seek(position, SeekOrigin.Begin);
byte[] lengthBytes = new byte[4];
fs.Read(lengthBytes, 0, 4);
int length = BitConverter.ToInt32(lengthBytes, 0);
byte[] data = new byte[length];
fs.Read(data, 0, length);
return data;
}
private long AddBlockData(FileStream fs, long blockFileIndex, byte[] blockData)
{
long position = fs.Position;
fs.Write(BitConverter.GetBytes(blockData.Length), 0, 4);
fs.Write(blockData, 0, blockData.Length);
return position;
}
public string GetPath(long blockFileIndex) { return System.IO.Path.Combine(pathBase, filenameBase + blockFileIndex.ToString()); }
}
//2014/12/01 ่ฉฆ้จๆธ
public class BlockFilePointersDB : DATABASEBASE
{
public BlockFilePointersDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blks_index_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "blks_index_test" + version.ToString(); } }
#endif
public long GetBlockFilePointerData(long blockIndex)
{
using (FileStream fs = new FileStream(GetPath(), FileMode.OpenOrCreate, FileAccess.Read))
{
if (fs.Length % 8 != 0)
throw new InvalidOperationException("fatal:bfpdb");
long position = blockIndex * 8;
if (position >= fs.Length)
return -1;
fs.Seek(position, SeekOrigin.Begin);
byte[] blockPointerData = new byte[8];
fs.Read(blockPointerData, 0, 8);
return BitConverter.ToInt64(blockPointerData, 0);
}
}
public void UpdateBlockFilePointerData(long blockIndex, long blockFilePointerData)
{
using (FileStream fs = new FileStream(GetPath(), FileMode.OpenOrCreate, FileAccess.Write))
{
if (fs.Length % 8 != 0)
throw new InvalidOperationException("fatal:bfpdb");
long position = blockIndex * 8;
if (position >= fs.Length)
{
fs.Seek(fs.Length, SeekOrigin.Begin);
while (position > fs.Length)
fs.Write(BitConverter.GetBytes((long)-1), 0, 8);
fs.Write(BitConverter.GetBytes(blockFilePointerData), 0, 8);
}
else
{
fs.Seek(position, SeekOrigin.Begin);
fs.Write(BitConverter.GetBytes(blockFilePointerData), 0, 8);
}
}
}
public string GetPath() { return System.IO.Path.Combine(pathBase, filenameBase); }
}
public class UtxoFileAccessDB : DATABASEBASE
{
public UtxoFileAccessDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "utxos_access_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxos" + version.ToString(); } }
#endif
public void Create()
{
try
{
string path = GetPath();
if (File.Exists(path))
throw new InvalidOperationException("utxos_access_file_exist");
File.WriteAllText(path, string.Empty);
}
catch (Exception ex)
{
throw new ApplicationException("fatal:utxos_access", ex);
}
}
public void Delete()
{
try
{
string path = GetPath();
if (!File.Exists(path))
throw new InvalidOperationException("utxo_access_file_not_exist");
File.Delete(path);
}
catch (Exception ex)
{
throw new ApplicationException("fatal:utxos_access", ex);
}
}
public string GetPath() { return System.IO.Path.Combine(pathBase, filenameBase); }
}
public class UtxoFilePointersDB : SimpleDatabase
{
public UtxoFilePointersDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "utxos_index_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxos_index" + version.ToString(); } }
#endif
}
public class UtxoFilePointersTempDB : SimpleDatabase
{
public UtxoFilePointersTempDB(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "utxos_index_temp_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxos_index_tamp" + version.ToString(); } }
#endif
public void Delete()
{
string path = GetPath();
if (File.Exists(path))
File.Delete(path);
}
}
//2014/11/26 ่ฉฆ้จๆธ
public class UtxoDB : DATABASEBASE
{
public UtxoDB(string _pathBase) : base(_pathBase) { }
private FileStream fs;
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "utxos_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxos" + version.ToString(); } }
#endif
public void Open()
{
if (fs != null)
throw new InvalidOperationException("utxodb_open_twice");
fs = new FileStream(GetPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
public void Close()
{
if (fs == null)
throw new InvalidOperationException("utxodb_close_twice_or_first");
fs.Close();
fs = null;
}
public void Flush()
{
if (fs == null)
throw new InvalidOperationException("utxodb_not_opened");
fs.Flush();
}
public byte[] GetUtxoData(long position)
{
if (fs == null)
throw new InvalidOperationException("utxodb_not_opened");
if (position >= fs.Length)
return new byte[] { };
fs.Seek(position, SeekOrigin.Begin);
byte[] lengthBytes = new byte[4];
fs.Read(lengthBytes, 0, 4);
int length = BitConverter.ToInt32(lengthBytes, 0);
byte[] data = new byte[length];
fs.Read(data, 0, length);
return data;
}
public long AddUtxoData(byte[] utxoData)
{
if (fs == null)
throw new InvalidOperationException("utxodb_not_opened");
long position = fs.Length;
fs.Seek(fs.Length, SeekOrigin.Begin);
fs.Write(BitConverter.GetBytes(utxoData.Length), 0, 4);
fs.Write(utxoData, 0, utxoData.Length);
return position;
}
public void UpdateUtxoData(long position, byte[] utxoData)
{
if (fs == null)
throw new InvalidOperationException("utxodb_not_opened");
fs.Seek(position, SeekOrigin.Begin);
byte[] lengthBytes = new byte[4];
fs.Read(lengthBytes, 0, 4);
int length = BitConverter.ToInt32(lengthBytes, 0);
if (utxoData.Length != length)
throw new InvalidOperationException();
fs.Write(utxoData, 0, utxoData.Length);
}
public string GetPath() { return System.IO.Path.Combine(pathBase, filenameBase); }
}
#endregion
}
namespace old
{
using CREA2014;
//2014/08/18
//ไฝใจใใใฆใใผใฟๆไฝ้จๅใๅ้ขใงใใชใใ๏ผ
//ใใผใฟๆไฝใฎๆฑ็จ็ใชไป็ตใฟใฏไฝใใชใใ๏ผ
public class BlockChain : SHAREDDATA
{
public BlockChain() : base(null) { }
public BlockChain(BlockChainDatabase _bcDatabase, BlockNodesGroupDatabase _bngDatabase, BlockGroupDatabase _bgDatabase, UtxoDatabase _utxoDatabase, AddressEventDatabase _addressEventDatabase)
{
bcDatabase = _bcDatabase;
bngDatabase = _bngDatabase;
bgDatabase = _bgDatabase;
utxoDatabase = _utxoDatabase;
addressEventDatabase = _addressEventDatabase;
}
public void Initialize()
{
byte[] bcDataBytes = bcDatabase.GetData();
if (bcDataBytes.Length != 0)
FromBinary(bcDataBytes);
blockGroups = new SortedDictionary<long, List<TransactionalBlock>>();
mainBlocks = new SortedDictionary<long, TransactionalBlock>();
isVerifieds = new Dictionary<Creahash, bool>();
numOfMainBlocksWhenSaveNext = numOfMainBlocksWhenSave;
currentBngIndex = head / blockNodesGroupDiv;
currentBng = new BlockNodesGroup(blockNodesGroupDiv);
if (head == 0)
currentBng.AddBlockNodes(new BlockNodes());
else
{
byte[] currentBngBytes = bngDatabase.GetBlockNodesGroupData(currentBngIndex);
if (currentBngBytes.Length != 0)
currentBng.FromBinary(currentBngBytes);
}
Dictionary<Sha256Ripemd160Hash, List<Utxo>> utxosDict = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
byte[] utxosBytes = utxoDatabase.GetData();
if (utxosBytes.Length != 0)
{
int addressLength = new Sha256Ripemd160Hash().SizeByte;
int utxoLength = new Utxo().ToBinary().Length;
int pointer = 0;
int length1 = BitConverter.ToInt32(utxosBytes, pointer);
pointer += 4;
for (int i = 0; i < length1; i++)
{
byte[] addressBytes = new byte[addressLength];
Array.Copy(utxosBytes, pointer, addressBytes, 0, addressLength);
pointer += addressLength;
Sha256Ripemd160Hash address = new Sha256Ripemd160Hash();
address.FromHash(addressBytes);
int length2 = BitConverter.ToInt32(utxosBytes, pointer);
pointer += 4;
List<Utxo> list = new List<Utxo>();
for (int j = 0; j < length2; j++)
{
byte[] utxoBytes = new byte[utxoLength];
Array.Copy(utxosBytes, pointer, utxoBytes, 0, utxoLength);
pointer += utxoLength;
list.Add(SHAREDDATA.FromBinary<Utxo>(utxoBytes));
}
utxosDict.Add(address, list);
}
}
utxos = new Utxos(utxosDict);
addedUtxosInMemory = new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>();
removedUtxosInMemory = new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>();
Dictionary<Sha256Ripemd160Hash, List<AddressEventData>> addressEventDataDict = new Dictionary<Sha256Ripemd160Hash, List<AddressEventData>>();
byte[] addressEventDatasBytes = addressEventDatabase.GetData();
if (addressEventDatasBytes.Length != 0)
{
int addressLength = new Sha256Ripemd160Hash().SizeByte;
int addressEventDataLength = new AddressEventData().ToBinary().Length;
int pointer = 0;
int length1 = BitConverter.ToInt32(addressEventDatasBytes, pointer);
pointer += 4;
for (int i = 0; i < length1; i++)
{
byte[] addressBytes = new byte[addressLength];
Array.Copy(addressEventDatasBytes, pointer, addressBytes, 0, addressLength);
pointer += addressLength;
Sha256Ripemd160Hash address = new Sha256Ripemd160Hash();
address.FromHash(addressBytes);
int length2 = BitConverter.ToInt32(addressEventDatasBytes, pointer);
pointer += 4;
List<AddressEventData> list = new List<AddressEventData>();
for (int j = 0; j < length2; j++)
{
byte[] addressEventDataBytes = new byte[addressEventDataLength];
Array.Copy(addressEventDatasBytes, pointer, addressEventDataBytes, 0, addressEventDataLength);
pointer += addressEventDataLength;
list.Add(SHAREDDATA.FromBinary<AddressEventData>(addressEventDataBytes));
}
addressEventDataDict.Add(address, list);
}
}
addressEventDatas = new AddressEventDatas(addressEventDataDict);
addressEvents = new Dictionary<AddressEvent, Tuple<CurrencyUnit, CurrencyUnit>>();
Initialized += (sender, e) =>
{
for (long i = utxoDividedHead == 0 ? 1 : utxoDividedHead * utxosInMemoryDiv; i < head + 1; i++)
GoForwardUtxosCurrent(GetMainBlock(i));
};
isInitialized = true;
Initialized(this, EventArgs.Empty);
}
private static readonly long blockGroupDiv = 100000;
private static readonly long blockNodesGroupDiv = 10000;
//Utxoใฏ100ใใญใใฏๆฏใซ่จ้ฒใใ
private static readonly long utxosInMemoryDiv = 100;
//ๅๆๅใใใฆใใชใๅ ดๅใซใใใฆๅๆๅไปฅๅคใฎใใจใๅฎ่กใใใใจใใใจไพๅคใ็บ็ใใ
private bool isInitialized = false;
public event EventHandler Initialized = delegate { };
public event EventHandler BalanceUpdated = delegate { };
//ๆชไฟๅญใฎใใญใใฏใฎ้ใพใ
//ไฟๅญใใใๅ้คใใชใใใฐใชใใชใ
//้ต๏ผbIndex๏ผใใญใใฏใฎ้ซใ๏ผ
private SortedDictionary<long, List<TransactionalBlock>> blockGroups;
//ๆชไฟๅญใฎไธปใใญใใฏใฎ้ใพใ
//ไฟๅญใใใๅ้คใใชใใใฐใชใใชใ
//้ต๏ผbIndex๏ผใใญใใฏใฎ้ซใ๏ผ
private SortedDictionary<long, TransactionalBlock> mainBlocks;
//ๆค่จผใใใ็ตๆใๆ ผ็ดใใ
//<ๆชๅฎ่ฃ
>ไฟๅญใใใ๏ผๆใใฏใๅ็
งใใใๅฏ่ฝๆงใไฝใใชใฃใใ๏ผๅ้คใใชใใใฐใชใใชใ
private Dictionary<Creahash, bool> isVerifieds;
private long cacheBgIndex;
//bgPosition1๏ผใใญใใฏ็พคใฎใใกใคใซไธใฎไฝ็ฝฎ๏ผ
//bgPosition2๏ผใใญใใฏ็พคใฎไฝ็ช็ฎใฎใใญใใฏใ๏ผ
private long cacheBgPosition1;
//ๆง่ฝๅไธใฎใใใฎใใญใใฏ็พคใฎไธๆ็ใชไฟๆ
//ๅฟ
่ฆใชใใฎใ ใ้็ดๅๅใใ
private byte[][] cacheBgBytes;
private TransactionalBlock[] cacheBg;
//ๆดๆฐใใใไธปใใญใใฏใใใไปฅไธๆบใพใใจ1ๅบฆไฟๅญใ่ฉฆ่กใใใ
private int numOfMainBlocksWhenSaveNext;
//bngIndex๏ผใใญใใฏ็ฏ็พคใฎ็ชๅท๏ผ = bIndex / blockNodesGroupDiv
//ไฟๅญใใใฆใใใใญใใฏ็ฏ็พคใฎไธญใงๆๆฐใฎใใฎ
private long currentBngIndex;
private BlockNodesGroup currentBng;
//ๆง่ฝๅไธใฎใใใฎใใญใใฏ็ฏ็พคใฎไธๆ็ใชไฟๆ
private long cacheBngIndex;
private BlockNodesGroup cacheBng;
private Utxos utxos;
private List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>> addedUtxosInMemory;
private List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>> removedUtxosInMemory;
private Dictionary<Sha256Ripemd160Hash, List<Utxo>> currentAddedUtxos;
private Dictionary<Sha256Ripemd160Hash, List<Utxo>> currentRemovedUtxos;
private AddressEventDatas addressEventDatas;
private Dictionary<AddressEvent, Tuple<CurrencyUnit, CurrencyUnit>> addressEvents;
private BlockChainDatabase bcDatabase;
private BlockNodesGroupDatabase bngDatabase;
private BlockGroupDatabase bgDatabase;
private UtxoDatabase utxoDatabase;
private AddressEventDatabase addressEventDatabase;
private GenesisBlock genesisBlock = new GenesisBlock();
//2014/07/08
//่จฑๅฎนใใใใใญใใฏ้ๅๅฒใฏๆๅคงใงใ200ใใญใใฏ๏ผใใใใ้ทใๅๅฒใฏๆๅฆใใใ๏ผ
//ไฝใใใใญใใฏ้ๅๅฒใซใใฃใฆใใญใใฏ้ใฎๅ
้ ญใฎใใญใใฏ็ชๅทใๅพ้ใใๅ ดๅใซใใใฆใ
//ๆดใซใใญใใฏ้ๅๅฒใซใใฃใฆใใญใใฏ้ใฎๅ
้ ญใฎใใญใใฏ็ชๅทใๅพ้ใใใใจใใ
//็พๅฎ็ใซใฏๅ
ใ่ตทใใใชใใ ใใใใ็่ซ็ใซใฏใใๅพใ
//ๅค้ใใใใๆฐใ้ใใใใญใใฏใฏ็กๆกไปถใซๆๅฆ
public static readonly long rejectedBIndexDif = 100;
//็พๅจใฎไธปใใญใใฏ้ใจๅๅฒใใญใใฏ้ใฎๅ
้ ญใฎๅ
ใไฝใใๅใฎใใฎใใ
//ๆดใซใใใใๅใซๅๅฒ็นใใใๅ ดๅใซใฏใใใจใๅๅฒใใญใใฏ้ใฎๆนใ้ฃๆๅบฆ็ใซ้ทใใฆใ
//ไธปใใญใใฏ้ใๅใๆฟใใใใจใฏใชใ
public static readonly int maxBrunchDeep = 100;
//ๆดๆฐใใใไธปใใญใใฏใใใไปฅไธๆบใพใใจ1ๅบฆไฟๅญใ่ฉฆ่กใใใ
public static readonly int numOfMainBlocksWhenSave = 200;
//ๆดๆฐใใใไธปใใญใใฏใโใฎๆฐไปฅไธๆบใพใฃใฆใใ็ถๆ
ใงๆดใซใใไปฅไธๅขใใใจ1ๅบฆไฟๅญใ่ฉฆ่กใใใ
public static readonly int numOfMainBlocksWhenSaveDifference = 50;
//ๆดๆฐใใใไธปใใญใใฏใใใไปฅไธๆบใพใฃใฆใใใใญใใฏ็พคไปฅๅใฎใใญใใฏ็พคใฏไฟๅญใๅฎ่กใใใ
public static readonly int numOfNewMainBlocksInGroupWhenSave = 150;
//ๆๅคงใงใใใไปฅไธใฎใใญใใฏใใ1ใคใฎใใญใใฏ็พคใซใฏไฟๅญใใใชใ
public static readonly int blockGroupCapacity = 100;
//ไฟๅญใๅฎ่กใใใใจใ็พๅจใฎไธปใใญใใฏ้ใฎๅ
้ ญใใญใใฏใฎใใญใใฏ็ชๅทใใ้ขใใฆใใใใญใใฏใฏ็ ดๆฃใใใ
public static readonly long discardOldBlock = 200;
public static readonly int maxUtxosGroup = 2;
public static readonly long unusableConformation = 6;
public enum TransactionType { normal, foundational }
public long head { get; private set; }
//1ใใใ0ใฏไฝใไฟๅญใใใฆใใชใ็ถๆ
ใ่กจใ
public long utxoDividedHead { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => head, (o) => head = (long)o),
new MainDataInfomation(typeof(long), () => utxoDividedHead, (o) => utxoDividedHead = (long)o),
};
}
}
private TransactionalBlock GetSavedOrCachedBlock(long bgIndex, long bgPosition1, long bgPosition2)
{
Func<TransactionalBlock> _GetBlockFromCache = () =>
{
byte[] txBlockTypeBytes = new byte[4];
byte[] txBlockBytes = new byte[cacheBgBytes[bgPosition2].Length - 4];
Array.Copy(cacheBgBytes[bgPosition2], 0, txBlockTypeBytes, 0, txBlockTypeBytes.Length);
Array.Copy(cacheBgBytes[bgPosition2], 4, txBlockBytes, 0, txBlockBytes.Length);
TransactionType txType = (TransactionType)BitConverter.ToInt32(txBlockTypeBytes, 0);
TransactionalBlock txBlock;
if (txType == TransactionType.normal)
txBlock = new NormalBlock();
else if (txType == TransactionType.foundational)
txBlock = new FoundationalBlock();
else
throw new NotSupportedException("not_supported_tx_block_type");
txBlock.FromBinary(txBlockBytes);
return cacheBg[bgPosition2] = txBlock;
};
if (cacheBgIndex == bgIndex && cacheBgPosition1 == bgPosition1 && cacheBgBytes != null)
if (cacheBg != null && cacheBg[bgPosition2] != null)
return cacheBg[bgPosition2];
else
return _GetBlockFromCache();
else
{
using (MemoryStream ms = new MemoryStream(bgDatabase.GetBlockGroupData(bgIndex, (long)bgPosition1)))
{
byte[] bgLengthBytes = new byte[4];
ms.Read(bgLengthBytes, 0, 4);
int bgLength = BitConverter.ToInt32(bgLengthBytes, 0);
byte[][] bgDatasBytes = new byte[bgLength][];
for (int i = 0; i < bgLength; i++)
{
byte[] bLengthBytes = new byte[4];
ms.Read(bLengthBytes, 0, 4);
int bLength = BitConverter.ToInt32(bLengthBytes, 0);
bgDatasBytes[i] = new byte[bLength];
ms.Read(bgDatasBytes[i], 0, bLength);
}
cacheBgBytes = bgDatasBytes;
cacheBg = new TransactionalBlock[cacheBgBytes.Length];
cacheBgIndex = bgIndex;
cacheBgPosition1 = bgPosition1;
}
return _GetBlockFromCache();
}
}
private long SaveBlockGroup(long bgIndex, byte[][] bgDataBytes)
{
using (MemoryStream ms = new MemoryStream())
{
byte[] bgLengthBytes = BitConverter.GetBytes(bgDataBytes.Length);
ms.Write(bgLengthBytes, 0, 4);
for (int i = 0; i < bgDataBytes.Length; i++)
{
byte[] bLengthBytes = BitConverter.GetBytes(bgDataBytes[i].Length);
ms.Write(bLengthBytes, 0, 4);
ms.Write(bgDataBytes[i], 0, bgDataBytes[i].Length);
}
return bgDatabase.AddBlockGroupData(ms.ToArray(), bgIndex);
}
}
private void LoadCacheBng(long bngIndex)
{
cacheBngIndex = bngIndex;
cacheBng = new BlockNodesGroup(blockGroupDiv);
byte[] cacheBngBytes = bngDatabase.GetBlockNodesGroupData(bngIndex);
if (cacheBngBytes.Length != 0)
cacheBng.FromBinary(cacheBngBytes);
}
private TransactionalBlock[] GetBlocksAtBIndex(long bIndex)
{
List<TransactionalBlock> blocks = new List<TransactionalBlock>();
if (blockGroups.ContainsKey(bIndex))
foreach (var block in blockGroups[bIndex])
blocks.Add(block);
long bgIndex = bIndex / blockGroupDiv;
long bngIndex = bIndex / blockNodesGroupDiv;
long bngPosition = bIndex % blockNodesGroupDiv;
if (currentBngIndex == bngIndex)
{
//<ๆชๆน่ฏ>position1ใๅไธใฎใใญใใฏๅๅพใ็บใใ๏ผ้ฃ็ถใใใ๏ผ
if (currentBng.nodess[bngPosition] != null)
foreach (var blockNode in currentBng.nodess[bngPosition].nodes)
blocks.Add(GetSavedOrCachedBlock(bgIndex, blockNode.position1, blockNode.position2));
}
else
{
if (cacheBngIndex != bngIndex || cacheBng == null)
LoadCacheBng(bngIndex);
//<ๆชๆน่ฏ>position1ใๅไธใฎใใญใใฏๅๅพใ็บใใ๏ผ้ฃ็ถใใใ๏ผ
if (cacheBng.nodess[bngPosition] != null)
foreach (var blockNode in cacheBng.nodess[bngPosition].nodes)
blocks.Add(GetSavedOrCachedBlock(bgIndex, blockNode.position1, blockNode.position2));
}
return blocks.ToArray();
}
private TransactionalBlock GetMainBlockAtBIndex(long bIndex)
{
if (mainBlocks.ContainsKey(bIndex))
return mainBlocks[bIndex];
long bgIndex = bIndex / blockGroupDiv;
long bngIndex = bIndex / blockNodesGroupDiv;
long bngPosition = bIndex % blockNodesGroupDiv;
if (currentBngIndex == bngIndex)
{
if (currentBng.nodess[bngPosition] != null)
foreach (var blockNode in currentBng.nodess[bngPosition].nodes)
if (blockNode.isMain)
return GetSavedOrCachedBlock(bgIndex, blockNode.position1, blockNode.position2);
}
else
{
if (cacheBngIndex != bngIndex || cacheBng == null)
LoadCacheBng(bngIndex);
if (cacheBng.nodess[bngPosition] != null)
foreach (var blockNode in cacheBng.nodess[bngPosition].nodes)
if (blockNode.isMain)
return GetSavedOrCachedBlock(bgIndex, blockNode.position1, blockNode.position2);
}
return null;
}
public TransactionalBlock[] GetHeadBlocks()
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
if (head == 0)
throw new ArgumentOutOfRangeException("blk_genesis_bindex");
return GetBlocksAtBIndex(head);
}
public TransactionalBlock GetHeadMainBlock()
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
if (head == 0)
throw new ArgumentOutOfRangeException("blk_genesis_bindex");
return GetMainBlockAtBIndex(head);
}
public TransactionalBlock[] GetBlocks(long bIndex)
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
if (bIndex == 0)
throw new ArgumentOutOfRangeException("blk_genesis_bindex");
return GetBlocksAtBIndex(bIndex);
}
public TransactionalBlock GetMainBlock(long bIndex)
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
if (bIndex == 0)
throw new ArgumentOutOfRangeException("blk_genesis_bindex");
if (bIndex > head)
throw new ArgumentException("blk_bindex");
return GetMainBlockAtBIndex(bIndex);
}
public void AddBlock(TransactionalBlock txBlock)
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
if (txBlock.header.index < head - rejectedBIndexDif)
{
this.RaiseError("blk_too_old", 3);
return;
}
if (txBlock.header.index > head + rejectedBIndexDif)
{
this.RaiseError("blk_too_new", 3);
return;
}
foreach (var block in GetBlocks(txBlock.header.index))
if (block.Id.Equals(txBlock.Id))
{
this.RaiseWarning("blk_already_existed", 3);
return;
}
if (txBlock.header.index == 1 && !genesisBlock.Id.Equals(txBlock.header.prevBlockHash))
{
this.RaiseError("blk_mismatch_genesis_block_hash", 3);
return;
}
List<TransactionalBlock> list;
if (blockGroups.ContainsKey(txBlock.header.index))
list = blockGroups[txBlock.header.index];
else
blockGroups.Add(txBlock.header.index, list = new List<TransactionalBlock>());
list.Add(txBlock);
//<ๆชๆน่ฏ>่ฅๅนฒ็ก้งใใใ
TransactionalBlock target = txBlock;
TransactionalBlock main = null;
while (true)
{
//<ๆชๆน่ฏ>้ฃ็ถใใ็ชๅทใฎใใญใใฏใไธๆฐใซๅๅพใใ
TransactionalBlock next = GetBlocks(target.header.index + 1).Where((e) => e.header.prevBlockHash.Equals(target.Id)).FirstOrDefault();
if (next != null)
target = next;
else
break;
}
double branchCumulativeDifficulty = 0.0;
double mainCumulativeDifficulty = 0.0;
Stack<TransactionalBlock> stack = new Stack<TransactionalBlock>();
Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedBranchUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedBranchUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
if (target.header.index > head)
{
while (target.header.index > head)
{
branchCumulativeDifficulty += target.header.difficulty.Diff;
stack.Push(target);
if (target.header.index == 1)
break;
//<ๆชๆน่ฏ>้ฃ็ถใใ็ชๅทใฎใใญใใฏใไธๆฐใซๅๅพใใ
TransactionalBlock prev = GetBlocks(target.header.index - 1).Where((e) => e.Id.Equals(target.header.prevBlockHash)).FirstOrDefault();
if (prev == null)
{
this.RaiseWarning("blk_not_connected", 3);
return;
}
else
target = prev;
}
if (head == 0 || target.Id.Equals((main = GetHeadMainBlock()).Id))
{
Dictionary<AddressEvent, bool> balanceUpdatedFlag1 = new Dictionary<AddressEvent, bool>();
Dictionary<AddressEvent, long?> balanceUpdatedBefore = new Dictionary<AddressEvent, long?>();
UpdateBalanceBefore(balanceUpdatedFlag1, balanceUpdatedBefore);
foreach (var newBlock in stack)
{
bool isValid;
if (isVerifieds.ContainsKey(newBlock.Id)) //ๅธธใซๅฝใ่ฟใใฏใ
isValid = isVerifieds[newBlock.Id];
else
isVerifieds.Add(newBlock.Id, isValid = VerifyBlock(newBlock, addedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentAddedUtxos }), removedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentRemovedUtxos })));
if (!isValid)
break;
head++;
if (mainBlocks.ContainsKey(head)) //ๅธธใซๅฝใ่ฟใใฏใ
mainBlocks[head] = newBlock;
else
mainBlocks.Add(head, newBlock);
GoForwardUtxosCurrent(newBlock);
GoForwardAddressEventdata(newBlock);
}
main = null;
UpdateBalanceAfter(balanceUpdatedFlag1, balanceUpdatedBefore);
}
}
else
{
main = GetHeadMainBlock();
if (target.header.index < head)
while (target.header.index < main.header.index)
{
mainCumulativeDifficulty += main.header.difficulty.Diff;
//<ๆชๆน่ฏ>้ฃ็ถใใ็ชๅทใฎใใญใใฏใไธๆฐใซๅๅพใใ
TransactionalBlock prev = GetMainBlock(main.header.index - 1);
if (prev == null)
{
this.RaiseError("blk_main_not_connected", 3);
return;
}
else
{
GoBackwardUtxosInMemory(main, addedBranchUtxos, removedBranchUtxos);
main = prev;
}
}
}
if (main != null)
{
//ใใฎๆ็นใงtargetใจmainใฏๅใ้ซใใฎ็ฐใชใใใญใใฏใๅ็
งใใฆใใใฏใ
for (int i = 0; !target.Id.Equals(main.Id); i++)
{
if (i >= maxBrunchDeep)
{
this.RaiseWarning("blk_too_deep", 3);
return;
}
branchCumulativeDifficulty += target.header.difficulty.Diff;
mainCumulativeDifficulty += main.header.difficulty.Diff;
stack.Push(target);
if (target.header.index == 1)
break;
//<ๆชๆน่ฏ>้ฃ็ถใใ็ชๅทใฎใใญใใฏใไธๆฐใซๅๅพใใ
TransactionalBlock prev = GetBlocks(target.header.index - 1).Where((e) => e.Id.Equals(target.header.prevBlockHash)).FirstOrDefault();
if (prev == null)
{
this.RaiseWarning("blk_not_connected", 3);
return;
}
else
target = prev;
//<ๆชๆน่ฏ>้ฃ็ถใใ็ชๅทใฎใใญใใฏใไธๆฐใซๅๅพใใ
prev = GetMainBlock(main.header.index - 1);
if (prev == null)
{
this.RaiseError("blk_main_not_connected", 3);
return;
}
else
{
GoBackwardUtxosInMemory(main, addedBranchUtxos, removedBranchUtxos);
main = prev;
}
}
if (branchCumulativeDifficulty > mainCumulativeDifficulty)
{
double cumulativeDifficulty = 0.0;
TransactionalBlock validHead = null;
foreach (var newBlock in stack)
{
bool isValid;
if (isVerifieds.ContainsKey(newBlock.Id))
isValid = isVerifieds[newBlock.Id];
else
isVerifieds.Add(newBlock.Id, isValid = VerifyBlock(newBlock, addedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentAddedUtxos, addedBranchUtxos }), removedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentRemovedUtxos, removedBranchUtxos })));
if (!isValid)
break;
cumulativeDifficulty += newBlock.header.difficulty.Diff;
validHead = newBlock;
GoForwardUtxosInMemory(newBlock, addedBranchUtxos, removedBranchUtxos);
}
if (cumulativeDifficulty > mainCumulativeDifficulty)
{
Dictionary<AddressEvent, bool> balanceUpdatedFlag1 = new Dictionary<AddressEvent, bool>();
Dictionary<AddressEvent, long?> balanceUpdatedBefore = new Dictionary<AddressEvent, long?>();
UpdateBalanceBefore(balanceUpdatedFlag1, balanceUpdatedBefore);
TransactionalBlock fork = GetHeadMainBlock();
while (!fork.Id.Equals(main.Id))
{
GoBackwardUtxosCurrent(fork);
GoBackwardAddressEventData(fork);
fork = GetMainBlock(fork.header.index - 1);
}
foreach (var newBlock in stack)
{
if (mainBlocks.ContainsKey(newBlock.header.index))
mainBlocks[newBlock.header.index] = newBlock;
else
mainBlocks.Add(newBlock.header.index, newBlock);
GoForwardUtxosCurrent(newBlock);
GoForwardAddressEventdata(newBlock);
if (newBlock == validHead)
break;
}
for (long i = validHead.header.index + 1; i < head + 1; i++)
if (mainBlocks.ContainsKey(i))
mainBlocks.Remove(i);
head = validHead.header.index;
UpdateBalanceAfter(balanceUpdatedFlag1, balanceUpdatedBefore);
}
}
}
if (mainBlocks.Count > numOfMainBlocksWhenSaveNext)
{
SortedDictionary<long, List<TransactionalBlock>> tobeSavedBlockss = GetToBeSavedBlockss();
long? last = null;
foreach (var tobeSavedBlocks in tobeSavedBlockss)
if (tobeSavedBlocks.Value.Count >= numOfNewMainBlocksInGroupWhenSave)
last = tobeSavedBlocks.Value[blockGroupCapacity - 1].header.index;
if (last == null)
{
numOfMainBlocksWhenSaveNext += numOfMainBlocksWhenSaveDifference;
return;
}
SaveBgAndBng(tobeSavedBlockss, last.Value);
foreach (var mainBlock in mainBlocks)
if (mainBlock.Key <= last.Value && blockGroups.ContainsKey(mainBlock.Key) && blockGroups[mainBlock.Key].Contains(mainBlock.Value))
blockGroups[mainBlock.Key].Remove(mainBlock.Value);
SortedDictionary<long, List<TransactionalBlock>> newBlockGroups = new SortedDictionary<long, List<TransactionalBlock>>();
foreach (var blockGroup in blockGroups)
if (blockGroup.Key >= head - discardOldBlock)
newBlockGroups.Add(blockGroup.Key, blockGroup.Value);
blockGroups = newBlockGroups;
SortedDictionary<long, TransactionalBlock> newMainBlocks = new SortedDictionary<long, TransactionalBlock>();
foreach (var mainBlock in mainBlocks)
if (mainBlock.Key > last.Value)
newMainBlocks.Add(mainBlock.Key, mainBlock.Value);
mainBlocks = newMainBlocks;
numOfMainBlocksWhenSaveNext = numOfMainBlocksWhenSave;
}
}
private void GoForwardAddressEventdata(TransactionalBlock txBlock)
{
foreach (var txi in txBlock.Transactions.Select((tx, i) => new { tx, i }))
{
for (int i = 0; i < txi.tx.TxInputs.Length; i++)
addressEventDatas.Remove(new Sha256Ripemd160Hash(txi.tx.TxInputs[i].SenderPubKey.pubKey), txi.tx.TxInputs[i].PrevTxBlockIndex, txi.tx.TxInputs[i].PrevTxIndex, txi.tx.TxInputs[i].PrevTxOutputIndex);
for (int i = 0; i < txi.tx.TxOutputs.Length; i++)
addressEventDatas.Add(txi.tx.TxOutputs[i].Address, new AddressEventData(txBlock.header.index, txi.i, i, txi.tx.TxOutputs[i].Amount));
}
}
private void GoBackwardAddressEventData(TransactionalBlock txBlock)
{
foreach (var txi in txBlock.Transactions.Select((tx, i) => new { tx, i }))
{
for (int i = 0; i < txi.tx.TxInputs.Length; i++)
addressEventDatas.Add(new Sha256Ripemd160Hash(txi.tx.TxInputs[i].SenderPubKey.pubKey), new AddressEventData(txi.tx.TxInputs[i].PrevTxBlockIndex, txi.tx.TxInputs[i].PrevTxIndex, txi.tx.TxInputs[i].PrevTxOutputIndex, GetMainBlock(txi.tx.TxInputs[i].PrevTxBlockIndex).Transactions[txi.tx.TxInputs[i].PrevTxIndex].TxOutputs[txi.tx.TxInputs[i].PrevTxOutputIndex].Amount));
for (int i = 0; i < txi.tx.TxOutputs.Length; i++)
addressEventDatas.Remove(txi.tx.TxOutputs[i].Address, txBlock.header.index, txi.i, i);
}
}
public void AddAddressEvent(AddressEvent addressEvent)
{
if (addressEvents.ContainsKey(addressEvent))
throw new ArgumentException("already_added");
List<AddressEventData> listAddressEventData = null;
if (addressEventDatas.ContainsAddress(addressEvent.address))
listAddressEventData = addressEventDatas.GetAddressEventDatas(addressEvent.address);
else
{
List<Utxo> listUtxo = utxos.ContainsAddress(addressEvent.address) ? utxos.GetAddressUtxos(addressEvent.address) : new List<Utxo>() { };
foreach (var added in addedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentAddedUtxos }))
if (added != null && added.ContainsKey(addressEvent.address))
foreach (var utxo in added[addressEvent.address])
listUtxo.Add(utxo);
foreach (var removed in removedUtxosInMemory.Concat(new List<Dictionary<Sha256Ripemd160Hash, List<Utxo>>>() { currentRemovedUtxos }))
if (removed != null && removed.ContainsKey(addressEvent.address))
foreach (var utxo in removed[addressEvent.address])
{
Utxo removedUtxo = listUtxo.FirstOrDefault((elem) => elem.blockIndex == utxo.blockIndex && elem.txIndex == utxo.txIndex && elem.txOutIndex == utxo.txOutIndex);
if (removedUtxo == null)
throw new InvalidOperationException("not_found");
listUtxo.Remove(removedUtxo);
}
listAddressEventData = new List<AddressEventData>();
foreach (var utxo in listUtxo)
listAddressEventData.Add(new AddressEventData(utxo.blockIndex, utxo.txIndex, utxo.txOutIndex, GetMainBlock(utxo.blockIndex).Transactions[utxo.txIndex].TxOutputs[utxo.txOutIndex].Amount));
addressEventDatas.Add(addressEvent.address, listAddressEventData);
}
Tuple<CurrencyUnit, CurrencyUnit> balance = CalculateBalance(listAddressEventData);
addressEvents.Add(addressEvent, balance);
addressEvent.RaiseBalanceUpdated(balance);
addressEvent.RaiseUsableBalanceUpdated(balance.Item1);
addressEvent.RaiseUnusableBalanceUpdated(balance.Item2);
}
public AddressEvent RemoveAddressEvent(Sha256Ripemd160Hash address)
{
AddressEvent addressEvent;
if ((addressEvent = addressEvents.Keys.FirstOrDefault((elem) => elem.address.Equals(address))) == null)
throw new ArgumentException("not_added");
if (addressEventDatas.ContainsAddress(address))
addressEventDatas.Remove(address);
addressEvents.Remove(addressEvent);
return addressEvent;
}
private Tuple<CurrencyUnit, CurrencyUnit> CalculateBalance(List<AddressEventData> listAddressEventData)
{
CurrencyUnit usable = new CurrencyUnit(0);
CurrencyUnit unusable = new CurrencyUnit(0);
foreach (var addressEventData in listAddressEventData)
if (addressEventData.blockIndex + unusableConformation > head)
unusable = new CurrencyUnit(unusable.rawAmount + addressEventData.amount.rawAmount);
else
usable = new CurrencyUnit(usable.rawAmount + addressEventData.amount.rawAmount);
return new Tuple<CurrencyUnit, CurrencyUnit>(usable, unusable);
}
private void UpdateBalanceBefore(Dictionary<AddressEvent, bool> balanceUpdatedFlag1, Dictionary<AddressEvent, long?> balanceUpdatedBefore)
{
foreach (var addressEvent in addressEvents)
{
AddressEventData addressEventData = addressEventDatas.GetAddressEventDatas(addressEvent.Key.address).LastOrDefault();
balanceUpdatedFlag1.Add(addressEvent.Key, addressEventData != null && addressEventData.blockIndex + unusableConformation > head);
balanceUpdatedBefore.Add(addressEvent.Key, addressEventData == null ? null : (long?)addressEventData.blockIndex);
}
}
private void UpdateBalanceAfter(Dictionary<AddressEvent, bool> balanceUpdatedFlag1, Dictionary<AddressEvent, long?> balanceUpdatedBefore)
{
bool flag = false;
List<AddressEvent> addressEventsCopy = new List<AddressEvent>(addressEvents.Keys);
foreach (var addressEvent in addressEventsCopy)
{
List<AddressEventData> listAddressEventData = addressEventDatas.GetAddressEventDatas(addressEvent.address);
AddressEventData addressEventData = listAddressEventData.LastOrDefault();
if (balanceUpdatedFlag1[addressEvent] || balanceUpdatedBefore[addressEvent] != (addressEventData == null ? null : (long?)addressEventData.blockIndex) || (addressEventData != null && addressEventData.blockIndex + unusableConformation > head))
{
Tuple<CurrencyUnit, CurrencyUnit> balanceBefore = addressEvents[addressEvent];
Tuple<CurrencyUnit, CurrencyUnit> balanceAfter = CalculateBalance(listAddressEventData);
bool flag1 = balanceBefore.Item1.rawAmount != balanceAfter.Item1.rawAmount;
bool flag2 = balanceBefore.Item2.rawAmount != balanceAfter.Item2.rawAmount;
flag |= flag1;
flag |= flag2;
if (flag1 || flag2)
addressEvent.RaiseBalanceUpdated(balanceAfter);
if (flag1)
addressEvent.RaiseUsableBalanceUpdated(balanceAfter.Item1);
if (flag2)
addressEvent.RaiseUnusableBalanceUpdated(balanceAfter.Item2);
if (flag1 || flag2)
addressEvents[addressEvent] = balanceAfter;
}
}
if (flag)
BalanceUpdated(this, EventArgs.Empty);
}
private void GoForwardUtxosCurrent(TransactionalBlock txBlock)
{
if (txBlock.header.index == 1 || txBlock.header.index % utxosInMemoryDiv == 0)
{
if (currentAddedUtxos != null)
{
addedUtxosInMemory.Add(currentAddedUtxos);
removedUtxosInMemory.Add(currentRemovedUtxos);
}
currentAddedUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
currentRemovedUtxos = new Dictionary<Sha256Ripemd160Hash, List<Utxo>>();
}
GoForwardUtxosInMemory(txBlock, currentAddedUtxos, currentRemovedUtxos);
}
private void GoBackwardUtxosCurrent(TransactionalBlock txBlock)
{
GoBackwardUtxosInMemory(txBlock, currentAddedUtxos, currentRemovedUtxos);
if (txBlock.header.index == 1 || txBlock.header.index % utxosInMemoryDiv == 0)
{
foreach (var currentAddedUtxo in currentAddedUtxos)
if (currentAddedUtxo.Value.Count != 0)
throw new InvalidOperationException("current_added_utxos_not_empty");
foreach (var currentRemovedUtxo in currentRemovedUtxos)
if (currentRemovedUtxo.Value.Count != 0)
throw new InvalidOperationException("current_removed__utxos_not_empty");
if (txBlock.header.index == 1)
{
currentAddedUtxos = null;
currentRemovedUtxos = null;
}
else
{
if (addedUtxosInMemory.Count > 0)
{
currentAddedUtxos = addedUtxosInMemory[addedUtxosInMemory.Count - 1];
currentRemovedUtxos = removedUtxosInMemory[removedUtxosInMemory.Count - 1];
addedUtxosInMemory.RemoveAt(addedUtxosInMemory.Count - 1);
removedUtxosInMemory.RemoveAt(removedUtxosInMemory.Count - 1);
}
else
//2014/07/20 ๆขใซไฟๅญใใใฆใใUTXOใฏๆปใใชใใใฎใจใใ
throw new InvalidOperationException("disallowed_go_backward_further");
}
}
}
private void UpdateUtxosTemp(Dictionary<Sha256Ripemd160Hash, List<Utxo>> utxos1, Dictionary<Sha256Ripemd160Hash, List<Utxo>> utxos2, Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutputIndex)
{
if (utxos1.ContainsKey(address))
{
List<Utxo> list = utxos1[address];
Utxo utxo = list.Where((elem) => elem.blockIndex == blockIndex && elem.txIndex == txIndex && elem.txOutIndex == txOutputIndex).FirstOrDefault();
if (utxo != null)
{
list.Remove(utxo);
return;
}
}
if (utxos2.ContainsKey(address))
utxos2[address].Add(new Utxo(blockIndex, txIndex, txOutputIndex));
else
utxos2.Add(address, new List<Utxo>() { new Utxo(blockIndex, txIndex, txOutputIndex) });
}
private void GoForwardUtxosInMemory(TransactionalBlock txBlock, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
foreach (var txi in txBlock.Transactions.Select((tx, i) => new { tx, i }))
{
for (int i = 0; i < txi.tx.TxInputs.Length; i++)
UpdateUtxosTemp(addedUtxos, removedUtxos, new Sha256Ripemd160Hash(txi.tx.TxInputs[i].SenderPubKey.pubKey), txi.tx.TxInputs[i].PrevTxBlockIndex, txi.tx.TxInputs[i].PrevTxIndex, txi.tx.TxInputs[i].PrevTxOutputIndex);
for (int i = 0; i < txi.tx.TxOutputs.Length; i++)
UpdateUtxosTemp(removedUtxos, addedUtxos, txi.tx.TxOutputs[i].Address, txBlock.header.index, txi.i, i);
}
}
private void GoBackwardUtxosInMemory(TransactionalBlock txBlock, Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
foreach (var txi in txBlock.Transactions.Select((tx, i) => new { tx, i }))
{
for (int i = 0; i < txi.tx.TxInputs.Length; i++)
UpdateUtxosTemp(removedUtxos, addedUtxos, new Sha256Ripemd160Hash(txi.tx.TxInputs[i].SenderPubKey.pubKey), txi.tx.TxInputs[i].PrevTxBlockIndex, txi.tx.TxInputs[i].PrevTxIndex, txi.tx.TxInputs[i].PrevTxOutputIndex);
for (int i = 0; i < txi.tx.TxOutputs.Length; i++)
UpdateUtxosTemp(addedUtxos, removedUtxos, txi.tx.TxOutputs[i].Address, txBlock.header.index, txi.i, i);
}
}
//็ตไบๆใซใใๅผใฐใชใ
public void SaveWhenExit()
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
SaveBgAndBng(GetToBeSavedBlockss(), long.MaxValue);
while (addedUtxosInMemory.Count > maxUtxosGroup)
{
utxos.Update(addedUtxosInMemory[0], removedUtxosInMemory[0]);
utxoDividedHead++;
addedUtxosInMemory.RemoveAt(0);
removedUtxosInMemory.RemoveAt(0);
}
using (MemoryStream ms = new MemoryStream())
{
ms.Write(BitConverter.GetBytes(addressEventDatas.addressEventDatas.Count), 0, 4);
int addressEventDataLength = new AddressEventData().ToBinary().Length;
foreach (var addressEventDatasDict in addressEventDatas.addressEventDatas)
{
ms.Write(addressEventDatasDict.Key.hash, 0, addressEventDatasDict.Key.SizeByte);
ms.Write(BitConverter.GetBytes(addressEventDatasDict.Value.Count), 0, 4);
foreach (var addressEventData in addressEventDatasDict.Value)
ms.Write(addressEventData.ToBinary(), 0, addressEventDataLength);
}
addressEventDatabase.UpdateData(ms.ToArray());
}
using (MemoryStream ms = new MemoryStream())
{
ms.Write(BitConverter.GetBytes(utxos.utxos.Count), 0, 4);
int utxoLength = new Utxo().ToBinary().Length;
foreach (var utxosDict in utxos.utxos)
{
ms.Write(utxosDict.Key.hash, 0, utxosDict.Key.SizeByte);
ms.Write(BitConverter.GetBytes(utxosDict.Value.Count), 0, 4);
foreach (var utxo in utxosDict.Value)
ms.Write(utxo.ToBinary(), 0, utxoLength);
}
utxoDatabase.UpdateData(ms.ToArray());
}
bcDatabase.UpdateData(ToBinary());
}
private SortedDictionary<long, List<TransactionalBlock>> GetToBeSavedBlockss()
{
SortedDictionary<long, List<TransactionalBlock>> tobeSavedBlockss = new SortedDictionary<long, List<TransactionalBlock>>();
foreach (var mainBlock in mainBlocks)
{
if (blockGroups.ContainsKey(mainBlock.Key) && blockGroups[mainBlock.Key].Contains(mainBlock.Value))
{
long bgIndex = mainBlock.Value.header.index / blockGroupDiv;
if (tobeSavedBlockss.ContainsKey(bgIndex))
tobeSavedBlockss[bgIndex].Add(mainBlock.Value);
else
tobeSavedBlockss.Add(bgIndex, new List<TransactionalBlock>() { mainBlock.Value });
}
}
return tobeSavedBlockss;
}
private void SaveBgAndBng(SortedDictionary<long, List<TransactionalBlock>> tobeSavedBlockss, long last)
{
SortedDictionary<long, BlockNode> newBlockNodes = new SortedDictionary<long, BlockNode>();
long lastBgIndex = last / blockGroupDiv;
foreach (var tobeSavedBlocks in tobeSavedBlockss)
{
if (tobeSavedBlocks.Key > lastBgIndex)
break;
List<byte[]> bgDatas = new List<byte[]>();
foreach (var tobeSavedBlock in tobeSavedBlocks.Value)
{
if (tobeSavedBlock.header.index > last)
break;
bgDatas.Add(BitConverter.GetBytes((int)(tobeSavedBlock is NormalBlock ? TransactionType.normal : TransactionType.foundational)).Combine(tobeSavedBlock.ToBinary()));
}
long bgPosition1 = SaveBlockGroup(tobeSavedBlocks.Key, bgDatas.ToArray());
long bgPosition2 = 0;
foreach (var tobeSavedBlock in tobeSavedBlocks.Value)
{
if (tobeSavedBlock.header.index > last)
break;
newBlockNodes.Add(tobeSavedBlock.header.index, new BlockNode(0, 0, bgPosition1, bgPosition2++, true));
}
}
foreach (var mainBlock in mainBlocks)
{
if (mainBlock.Value.header.index > last)
break;
long bgIndex = mainBlock.Value.header.index / blockGroupDiv;
long bngIndex = mainBlock.Value.header.index / blockNodesGroupDiv;
long bngPosition = mainBlock.Value.header.index % blockNodesGroupDiv;
if (currentBngIndex != bngIndex)
{
bngDatabase.UpdateBlockNodesGroupData(currentBng.ToBinary(), bngIndex);
currentBngIndex = bngIndex;
currentBng = new BlockNodesGroup(blockGroupDiv);
byte[] currentBngBytes = bngDatabase.GetBlockNodesGroupData(bngIndex);
if (currentBngBytes.Length != 0)
currentBng.FromBinary(currentBngBytes);
}
if (blockGroups.ContainsKey(mainBlock.Key) && blockGroups[mainBlock.Key].Contains(mainBlock.Value))
{
if (currentBng.nodess[bngPosition] == null)
{
if (currentBng.position != bngPosition)
throw new InvalidOleVariantTypeException("bng_position_mismatch");
currentBng.AddBlockNodes(new BlockNodes(new BlockNode[] { newBlockNodes[mainBlock.Key] }));
}
else
currentBng.nodess[bngPosition].AddBlockNode(newBlockNodes[mainBlock.Key]);
}
else
{
if (currentBng.nodess[bngPosition] == null)
throw new InvalidOperationException("bng_null");
bool flag = false;
foreach (var blockNode in currentBng.nodess[bngPosition].nodes)
{
TransactionalBlock block = GetSavedOrCachedBlock(bgIndex, blockNode.position1, blockNode.position2);
if (block.Id.Equals(mainBlock.Value.Id))
blockNode.isMain = flag = true;
else
blockNode.isMain = false;
}
if (!flag)
throw new InvalidOperationException("block_not_found");
}
}
bngDatabase.UpdateBlockNodesGroupData(currentBng.ToBinary(), currentBngIndex);
}
public bool VerifyBlock(TransactionalBlock txBlock, IEnumerable<Dictionary<Sha256Ripemd160Hash, List<Utxo>>> addeds, IEnumerable<Dictionary<Sha256Ripemd160Hash, List<Utxo>>> removeds)
{
if (!isInitialized)
throw new InvalidOperationException("not_initialized");
TransactionOutput[][] prevTxOutputs = new TransactionOutput[txBlock.transferTxs.Length][];
foreach (var transrferTx in txBlock.transferTxs.Select((v, i) => new { v, i }))
{
prevTxOutputs[transrferTx.i] = new TransactionOutput[transrferTx.v.txInputs.Length];
foreach (var txInput in transrferTx.v.txInputs.Select((v, i) => new { v, i }))
{
Sha256Ripemd160Hash address = new Sha256Ripemd160Hash(txInput.v.SenderPubKey.pubKey);
if (utxos.Contains(address, txInput.v.PrevTxBlockIndex, txInput.v.PrevTxIndex, txInput.v.PrevTxOutputIndex))
{
foreach (var removed in removeds)
if (removed.ContainsKey(address))
foreach (var removedUtxo in removed[address])
if (removedUtxo.blockIndex == txInput.v.PrevTxBlockIndex && removedUtxo.txIndex == txInput.v.PrevTxIndex && removedUtxo.txOutIndex == txInput.v.PrevTxOutputIndex)
return false;
prevTxOutputs[transrferTx.i][txInput.i] = GetMainBlock(txInput.v.PrevTxBlockIndex).Transactions[txInput.v.PrevTxIndex].TxOutputs[txInput.v.PrevTxOutputIndex];
}
else
{
foreach (var added in addeds)
if (added != null && added.ContainsKey(address))
foreach (var addedUtxo in added[address])
if (addedUtxo.blockIndex == txInput.v.PrevTxBlockIndex && addedUtxo.txIndex == txInput.v.PrevTxIndex && addedUtxo.txOutIndex == txInput.v.PrevTxOutputIndex)
prevTxOutputs[transrferTx.i][txInput.i] = GetMainBlock(txInput.v.PrevTxBlockIndex).Transactions[txInput.v.PrevTxIndex].TxOutputs[txInput.v.PrevTxOutputIndex];
if (prevTxOutputs[transrferTx.i][txInput.i] == null)
return false;
foreach (var removed in removeds)
if (removed != null && removed.ContainsKey(address))
foreach (var removedUtxo in removed[address])
if (removedUtxo.blockIndex == txInput.v.PrevTxBlockIndex && removedUtxo.txIndex == txInput.v.PrevTxIndex && removedUtxo.txOutIndex == txInput.v.PrevTxOutputIndex)
return false;
}
}
}
txBlock.Verify(prevTxOutputs, (index) => GetMainBlock(index));
return true;
}
}
public class AddressEventData : SHAREDDATA
{
public AddressEventData() { amount = CurrencyUnit.Zero; }
public AddressEventData(long _blockIndex, int _txIndex, int _txOutIndex, CurrencyUnit _amount)
{
blockIndex = _blockIndex;
txIndex = _txIndex;
txOutIndex = _txOutIndex;
amount = _amount;
}
public long blockIndex { get; private set; }
public int txIndex { get; private set; }
public int txOutIndex { get; private set; }
public CurrencyUnit amount { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => blockIndex, (o) => blockIndex = (long)o),
new MainDataInfomation(typeof(int), () => txIndex, (o) => txIndex = (int)o),
new MainDataInfomation(typeof(int), () => txOutIndex, (o) => txOutIndex = (int)o),
new MainDataInfomation(typeof(long), () => amount.rawAmount, (o) => amount = new CurrencyUnit((long)o)),
};
}
}
}
public class AddressEventDatas
{
public AddressEventDatas() { }
public AddressEventDatas(Dictionary<Sha256Ripemd160Hash, List<AddressEventData>> _addressEventData) { addressEventDatas = _addressEventData; }
public Dictionary<Sha256Ripemd160Hash, List<AddressEventData>> addressEventDatas { get; private set; }
public void Add(Sha256Ripemd160Hash address, AddressEventData addressEventData)
{
List<AddressEventData> list = null;
if (addressEventDatas.Keys.Contains(address))
list = addressEventDatas[address];
else
addressEventDatas.Add(address, list = new List<AddressEventData>());
if (list.FirstOrDefault((elem) => elem.blockIndex == addressEventData.blockIndex && elem.txIndex == addressEventData.txIndex && elem.txOutIndex == addressEventData.txOutIndex) != null)
throw new InvalidOperationException("already_existed");
list.Add(addressEventData);
}
public void Add(Sha256Ripemd160Hash address, List<AddressEventData> list)
{
if (addressEventDatas.Keys.Contains(address))
throw new InvalidOperationException("already_existed");
addressEventDatas.Add(address, list);
}
public void Remove(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
if (!addressEventDatas.Keys.Contains(address))
throw new InvalidOperationException("not_existed");
List<AddressEventData> list = addressEventDatas[address];
AddressEventData utxo = null;
if ((utxo = list.FirstOrDefault((elem) => elem.blockIndex == blockIndex && elem.txIndex == txIndex && elem.txOutIndex == txOutIndex)) == null)
throw new InvalidOperationException("not_existed");
list.Remove(utxo);
if (list.Count == 0)
addressEventDatas.Remove(address);
}
public void Remove(Sha256Ripemd160Hash address)
{
if (!addressEventDatas.Keys.Contains(address))
throw new InvalidOperationException("not_existed");
addressEventDatas.Remove(address);
}
public void Update(Dictionary<Sha256Ripemd160Hash, List<AddressEventData>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<AddressEventData>> removedUtxos)
{
foreach (var addedUtxos2 in addedUtxos)
foreach (var addedUtxo in addedUtxos2.Value)
Add(addedUtxos2.Key, addedUtxo);
foreach (var removedUtxos2 in removedUtxos)
foreach (var removedUtxo in removedUtxos2.Value)
Remove(removedUtxos2.Key, removedUtxo.blockIndex, removedUtxo.txIndex, removedUtxo.txOutIndex);
}
public bool Contains(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
if (!addressEventDatas.Keys.Contains(address))
return false;
List<AddressEventData> list = addressEventDatas[address];
return list.FirstOrDefault((elem) => elem.blockIndex == blockIndex && elem.txIndex == txIndex && elem.txOutIndex == txOutIndex) != null;
}
public bool ContainsAddress(Sha256Ripemd160Hash address) { return addressEventDatas.Keys.Contains(address); }
public List<AddressEventData> GetAddressEventDatas(Sha256Ripemd160Hash address)
{
if (!addressEventDatas.Keys.Contains(address))
throw new InvalidOperationException("not_existed");
return addressEventDatas[address];
}
}
public class Utxo : SHAREDDATA
{
public Utxo() { }
public Utxo(long _blockIndex, int _txIndex, int _txOutIndex)
{
blockIndex = _blockIndex;
txIndex = _txIndex;
txOutIndex = _txOutIndex;
}
public long blockIndex { get; private set; }
public int txIndex { get; private set; }
public int txOutIndex { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(long), () => blockIndex, (o) => blockIndex = (long)o),
new MainDataInfomation(typeof(int), () => txIndex, (o) => txIndex = (int)o),
new MainDataInfomation(typeof(int), () => txOutIndex, (o) => txOutIndex = (int)o),
};
}
}
}
public class Utxos
{
public Utxos() { }
public Utxos(Dictionary<Sha256Ripemd160Hash, List<Utxo>> _utxos) { utxos = _utxos; }
public Dictionary<Sha256Ripemd160Hash, List<Utxo>> utxos { get; private set; }
public void Add(Sha256Ripemd160Hash address, Utxo utxo)
{
List<Utxo> list = null;
if (utxos.Keys.Contains(address))
list = utxos[address];
else
utxos.Add(address, list = new List<Utxo>());
if (list.FirstOrDefault((elem) => elem.blockIndex == utxo.blockIndex && elem.txIndex == utxo.txIndex && elem.txOutIndex == utxo.txOutIndex) != null)
throw new InvalidOperationException("already_existed");
list.Add(utxo);
}
public void Remove(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
if (!utxos.Keys.Contains(address))
throw new InvalidOperationException("not_existed");
List<Utxo> list = utxos[address];
Utxo utxo = null;
if ((utxo = list.FirstOrDefault((elem) => elem.blockIndex == blockIndex && elem.txIndex == txIndex && elem.txOutIndex == txOutIndex)) == null)
throw new InvalidOperationException("not_existed");
list.Remove(utxo);
if (list.Count == 0)
utxos.Remove(address);
}
public void Update(Dictionary<Sha256Ripemd160Hash, List<Utxo>> addedUtxos, Dictionary<Sha256Ripemd160Hash, List<Utxo>> removedUtxos)
{
foreach (var addedUtxos2 in addedUtxos)
foreach (var addedUtxo in addedUtxos2.Value)
Add(addedUtxos2.Key, addedUtxo);
foreach (var removedUtxos2 in removedUtxos)
foreach (var removedUtxo in removedUtxos2.Value)
Remove(removedUtxos2.Key, removedUtxo.blockIndex, removedUtxo.txIndex, removedUtxo.txOutIndex);
}
public bool Contains(Sha256Ripemd160Hash address, long blockIndex, int txIndex, int txOutIndex)
{
if (!utxos.Keys.Contains(address))
return false;
List<Utxo> list = utxos[address];
return list.FirstOrDefault((elem) => elem.blockIndex == blockIndex && elem.txIndex == txIndex && elem.txOutIndex == txOutIndex) != null;
}
public bool ContainsAddress(Sha256Ripemd160Hash address) { return utxos.Keys.Contains(address); }
public List<Utxo> GetAddressUtxos(Sha256Ripemd160Hash address)
{
if (!utxos.Keys.Contains(address))
throw new InvalidOperationException("not_existed");
return utxos[address];
}
}
public class BlockNode : SHAREDDATA
{
public BlockNode() : this(0, 0, 0, 0, false) { }
public BlockNode(long _parentPosition1, long _parentPosition2, long _position1, long _position2, bool _isMain)
{
parentPosition1 = _parentPosition1;
parentPosition2 = _parentPosition2;
position1 = _position1;
position2 = _position2;
isMain = _isMain;
childrenPositions1 = new long[] { };
childrenPositions2 = new long[] { };
}
public long[] childrenPositions1 { get; private set; }
public long[] childrenPositions2 { get; private set; }
public long parentPosition1 { get; private set; }
public long parentPosition2 { get; private set; }
public long position1 { get; private set; }
public long position2 { get; private set; }
public bool isMain { get; set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo { get { return (msrw) => StreamInfoInner(msrw); } }
private IEnumerable<MainDataInfomation> StreamInfoInner(ReaderWriter msrw)
{
yield return new MainDataInfomation(typeof(long[]), null, () => childrenPositions1, (o) => childrenPositions1 = (long[])o);
yield return new MainDataInfomation(typeof(long[]), null, () => childrenPositions2, (o) => childrenPositions2 = (long[])o);
if (childrenPositions1.Length != childrenPositions2.Length)
throw new InvalidDataException("blknd_children_positions");
yield return new MainDataInfomation(typeof(long), () => parentPosition1, (o) => parentPosition1 = (long)o);
yield return new MainDataInfomation(typeof(long), () => parentPosition2, (o) => parentPosition2 = (long)o);
yield return new MainDataInfomation(typeof(long), () => position1, (o) => position1 = (long)o);
yield return new MainDataInfomation(typeof(long), () => position2, (o) => position2 = (long)o);
yield return new MainDataInfomation(typeof(bool), () => isMain, (o) => isMain = (bool)o);
}
public void AddChildPositions(long childPosition1, long childPosition2)
{
long[] newChildrenPositions1 = new long[childrenPositions1.Length + 1];
long[] newChildrenPositions2 = new long[childrenPositions2.Length + 1];
Array.Copy(childrenPositions1, 0, newChildrenPositions1, 0, childrenPositions1.Length);
Array.Copy(childrenPositions2, 0, newChildrenPositions2, 0, childrenPositions2.Length);
newChildrenPositions1[newChildrenPositions1.Length - 1] = childPosition1;
newChildrenPositions2[newChildrenPositions2.Length - 1] = childPosition2;
childrenPositions1 = newChildrenPositions1;
childrenPositions2 = newChildrenPositions2;
}
}
public class BlockNodes : SHAREDDATA
{
public BlockNodes() : this(new BlockNode[] { }) { }
public BlockNodes(BlockNode[] _nodes) { nodes = _nodes; }
public BlockNode[] nodes { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(BlockNode[]), null, null, () => nodes, (o) => nodes = (BlockNode[])o),
};
}
}
public void AddBlockNode(BlockNode blockNode)
{
BlockNode[] newNodes = new BlockNode[nodes.Length + 1];
Array.Copy(nodes, 0, newNodes, 0, nodes.Length);
newNodes[newNodes.Length - 1] = blockNode;
}
}
public class BlockNodesGroup : SHAREDDATA
{
public BlockNodesGroup() : base(null) { }
public BlockNodesGroup(long _div) : this(new BlockNodes[] { }, _div) { }
public BlockNodesGroup(BlockNodes[] _nodess, long _div)
{
if (_nodess.Length > (int)_div)
throw new ArgumentException("blknds_group_too_many_nodes");
div = _div;
nodess = new BlockNodes[div];
position = _nodess.Length;
Array.Copy(_nodess, 0, nodess, 0, _nodess.Length);
}
public readonly long div;
public BlockNodes[] nodess { get; private set; }
public long position { get; private set; }
protected override Func<ReaderWriter, IEnumerable<MainDataInfomation>> StreamInfo
{
get
{
return (msrw) => new MainDataInfomation[]{
new MainDataInfomation(typeof(BlockNodes[]), null, null, () =>
{
BlockNodes[] saveBlockNodess = new BlockNodes[position];
Array.Copy(nodess, 0, saveBlockNodess, 0, (int)position);
return saveBlockNodess;
}, (o) =>
{
BlockNodes[] loadBlockNodess = (BlockNodes[])o;
if (loadBlockNodess.Length > (int)div)
throw new ArgumentException("blknds_group_too_many_nodes");
position = loadBlockNodess.Length;
Array.Copy(loadBlockNodess, 0, nodess, 0, loadBlockNodess.Length);
}),
};
}
}
public void AddBlockNodes(BlockNodes blockNodes)
{
if (position >= div)
throw new InvalidOperationException("blknds_group_full");
nodess[position] = blockNodes;
position++;
}
}
public class BlockChainDatabase : SimpleDatabase
{
public BlockChainDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blkchn_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "blkchn"; } }
#endif
}
public class AddressEventDatabase : SimpleDatabase
{
public AddressEventDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "address_event_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "address_event"; } }
#endif
}
public class UtxoDatabase : SimpleDatabase
{
public UtxoDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "utxo_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "utxo"; } }
#endif
}
public class BlockNodesGroupDatabase : DATABASEBASE
{
public BlockNodesGroupDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blkng_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "blkng"; } }
#endif
public byte[] GetBlockNodesGroupData(long bngIndex)
{
using (FileStream fs = new FileStream(GetPath(bngIndex), FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
return data;
}
}
public void UpdateBlockNodesGroupData(byte[] data, long bngIndex)
{
using (FileStream fs = new FileStream(GetPath(bngIndex), FileMode.Create, FileAccess.Write))
fs.Write(data, 0, data.Length);
}
private string GetPath(long bngIndex) { return Path.Combine(pathBase, filenameBase + bngIndex.ToString()); }
}
public class BlockGroupDatabase : DATABASEBASE
{
public BlockGroupDatabase(string _pathBase) : base(_pathBase) { }
protected override int version { get { return 0; } }
#if TEST
protected override string filenameBase { get { return "blkg_test" + version.ToString(); } }
#else
protected override string filenameBase { get { return "blkg"; } }
#endif
public byte[] GetBlockGroupData(long bgIndex, long position)
{
using (FileStream fs = new FileStream(GetPath(bgIndex), FileMode.OpenOrCreate, FileAccess.Read))
{
if (position >= fs.Length)
return new byte[] { };
fs.Seek(position, SeekOrigin.Begin);
byte[] lengthBytes = new byte[4];
fs.Read(lengthBytes, 0, 4);
int length = BitConverter.ToInt32(lengthBytes, 0);
byte[] data = new byte[length];
fs.Read(data, 0, length);
return data;
}
}
public long AddBlockGroupData(byte[] data, long bgIndex)
{
using (FileStream fs = new FileStream(GetPath(bgIndex), FileMode.Append, FileAccess.Write))
{
long position = fs.Position;
fs.Write(BitConverter.GetBytes(data.Length), 0, 4);
fs.Write(data, 0, data.Length);
return position;
}
}
private string GetPath(long bgIndex)
{
return Path.Combine(pathBase, filenameBase + bgIndex.ToString());
}
}
} |
๏ปฟusing System;
using ViewModel = IMDB.Api.Models.ViewModel;
using ResponseDto = IMDB.Api.Models.ResponseDto;
namespace IMDB.Api.Services.Interfaces
{
public interface ITokenService : IService
{
string HashPassword(ViewModel.AuthUser user, string password);
bool VerifyPassword(ViewModel.AuthUser viewModelUser, Entities.User entityUser);
string CreateAccessToken(Entities.User user);
string CreateRefreshToken(Entities.User user);
}
}
|
๏ปฟ// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Judgements;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mania.UI
{
public class ManiaHitRenderer : HitRenderer<ManiaHitObject, ManiaJudgement>
{
private readonly int columns;
public ManiaHitRenderer(WorkingBeatmap beatmap, int columns = 5)
: base(beatmap)
{
this.columns = columns;
}
public override ScoreProcessor CreateScoreProcessor() => new ManiaScoreProcessor(this);
protected override BeatmapConverter<ManiaHitObject> CreateBeatmapConverter() => new ManiaBeatmapConverter();
protected override Playfield<ManiaHitObject, ManiaJudgement> CreatePlayfield() => new ManiaPlayfield(columns);
protected override DrawableHitObject<ManiaHitObject, ManiaJudgement> GetVisualRepresentation(ManiaHitObject h) => null;
}
}
|
using Foundation;
using System;
using UIKit;
namespace ratings.iOS
{
public partial class CustomCell : UITableViewCell
{
public CustomCell(IntPtr handle) : base(handle){
}
public void UpdateCell(string name, string game, UIImage image)
{
NameLabel.Text = name;
GameLabel.Text = game;
RatingImageView.Image = image;
}
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Testownik.Model
{
public class ArchStat : Entity
{
[ForeignKey("RefTest")]
public virtual Test Test { get; set; }
public int RefTest { get; set; }
public int CorrectAns { get; set; }
public int BadAns { get; set; }
public int KnownQuestions { get; set; }
}
}
|
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
// ****************************************************************
//2012ๅนด1ๆ16ๆฅ๏ผ้ท็พคไฟฎๆน
// ****************************************************************
namespace NUnit.CommandRunner.ArxNet.Tests
{
using System;
using System.IO;
using System.Reflection;
using NUnit.Core;
using NUnit.Framework;
using NUnit.CommandRunner.ArxNet;
[TestFixture]
public class CommandLineTests
{
[Test]
public void NoParametersCount()
{
CommandOptionsArxNet options = new CommandOptionsArxNet();
Assert.IsTrue(options.NoArgs);
}
[Test]
public void AllowForwardSlashDefaultsCorrectly()
{
CommandOptionsArxNet options = new CommandOptionsArxNet();
Assert.AreEqual( Path.DirectorySeparatorChar != '/', options.AllowForwardSlash );
}
[TestCase( "nologo", "nologo")]
[TestCase( "help", "help" )]
[TestCase( "help", "?" )]
[TestCase( "wait", "wait" )]
[TestCase( "xmlConsole", "xmlConsole")]
[TestCase( "labels", "labels")]
[TestCase( "noshadow", "noshadow" )]
public void BooleanOptionAreRecognized( string fieldName, string option )
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField( fieldName );
Assert.IsNotNull( field, "Field '{0}' not found", fieldName );
Assert.AreEqual( typeof(bool), field.FieldType, "Field '{0}' is wrong type", fieldName );
CommandOptionsArxNet options = new CommandOptionsArxNet( "-" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize -" + option );
options = new CommandOptionsArxNet( "--" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize --" + option );
options = new CommandOptionsArxNet( false, "/" + option );
Assert.AreEqual( false, (bool)field.GetValue( options ), "Incorrectly recognized /" + option );
options = new CommandOptionsArxNet( true, "/" + option );
Assert.AreEqual( true, (bool)field.GetValue( options ), "Didn't recognize /" + option );
}
[Test]
public void NothreadOptionIsTrue()
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField("nothread");
Assert.IsNotNull(field, "Field 'nothread' not found");
Assert.AreEqual(typeof(bool), field.FieldType, "Field 'nothread' is wrong type");
CommandOptionsArxNet options = new CommandOptionsArxNet("-nothread");
Assert.AreEqual(true, (bool)field.GetValue(options), "Field 'nothread' is not true");
options = new CommandOptionsArxNet("--nothread");
Assert.AreEqual(true, (bool)field.GetValue(options), "Field 'nothread' is not true");
options = new CommandOptionsArxNet(false, "/nothread");
Assert.AreEqual(true, (bool)field.GetValue(options), "Field 'nothread' is not true");
options = new CommandOptionsArxNet(true, "/nothread");
Assert.AreEqual(true, (bool)field.GetValue(options), "Field 'nothread' is not true");
options = new CommandOptionsArxNet();
Assert.AreEqual(true, (bool)field.GetValue(options), "Field 'nothread' is not true");
}
[TestCase( "fixture", "fixture" )]
[TestCase( "config", "config")]
[TestCase( "result", "result")]
[TestCase( "result", "xml" )]
[TestCase( "output", "output" )]
[TestCase( "output", "out" )]
[TestCase( "err", "err" )]
[TestCase( "include", "include" )]
[TestCase( "exclude", "exclude" )]
[TestCase("run", "run")]
[TestCase("runlist", "runlist")]
public void StringOptionsAreRecognized( string fieldName, string option )
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField( fieldName );
Assert.IsNotNull( field, "Field {0} not found", fieldName );
Assert.AreEqual( typeof(string), field.FieldType );
CommandOptionsArxNet options = new CommandOptionsArxNet( "-" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize -" + option );
options = new CommandOptionsArxNet( "--" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize --" + option );
options = new CommandOptionsArxNet( false, "/" + option + ":text" );
Assert.AreEqual( null, (string)field.GetValue( options ), "Incorrectly recognized /" + option );
options = new CommandOptionsArxNet( true, "/" + option + ":text" );
Assert.AreEqual( "text", (string)field.GetValue( options ), "Didn't recognize /" + option );
}
[TestCase("domain")]
[TestCase("trace")]
public void EnumOptionsAreRecognized( string fieldName )
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField( fieldName );
Assert.IsNotNull( field, "Field {0} not found", fieldName );
Assert.IsTrue( field.FieldType.IsEnum, "Field {0} is not an enum", fieldName );
}
[Test]
public void AssemblyName()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "nunit.tests.dll" );
Assert.AreEqual( "nunit.tests.dll", options.Parameters[0] );
}
[Test]
public void FixtureNamePlusAssemblyIsValid()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" );
Assert.AreEqual("nunit.tests.dll", options.Parameters[0]);
Assert.AreEqual("NUnit.Tests.AllTests", options.fixture);
Assert.IsTrue(options.Validate());
}
[Test]
public void AssemblyAloneIsValid()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "nunit.tests.dll" );
Assert.IsTrue(options.Validate(), "command line should be valid");
}
[Test]
public void InvalidOption()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "-asembly:nunit.tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void NoFixtureNameProvided()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "-fixture:", "nunit.tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void InvalidCommandLineParms()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "-garbage:TestFixture", "-assembly:Tests.dll" );
Assert.IsFalse(options.Validate());
}
[Test]
public void XmlParameter()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "tests.dll", "-xml:results.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.AreEqual("results.xml", options.result);
}
[Test]
public void XmlParameterWithFullPath()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "tests.dll", "-xml:C:/nunit/tests/bin/Debug/console-test.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.result);
}
[Test]
public void XmlParameterWithFullPathUsingEqualSign()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "tests.dll", "-xml=C:/nunit/tests/bin/Debug/console-test.xml" );
Assert.IsTrue(options.ParameterCount == 1, "assembly should be set");
Assert.AreEqual("tests.dll", options.Parameters[0]);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.result);
}
[Test]
public void FileNameWithoutXmlParameterLooksLikeParameter()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "tests.dll", "result.xml" );
Assert.IsTrue(options.Validate());
Assert.AreEqual(2, options.Parameters.Count);
}
[Test]
public void XmlParameterWithoutFileNameIsInvalid()
{
CommandOptionsArxNet options = new CommandOptionsArxNet( "tests.dll", "-xml:" );
Assert.IsFalse(options.Validate());
}
[Test]
public void HelpTextUsesCorrectDelimiterForPlatform()
{
string helpText = new CommandOptionsArxNet().GetHelpText();
char delim = System.IO.Path.DirectorySeparatorChar == '/' ? '-' : '/';
string expected = string.Format( "{0}output=", delim );
StringAssert.Contains( expected, helpText );
expected = string.Format( "{0}out=", delim );
StringAssert.Contains( expected, helpText );
}
[TestCase("None")]
[TestCase("Single")]
[TestCase("Multiple")]
public void DomainOptionIsNone(string optionValue)
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField("domain");
CommandOptionsArxNet options = new CommandOptionsArxNet("-domain=" + optionValue);
Assert.AreEqual(DomainUsage.None, (DomainUsage)field.GetValue(options), "Field 'domain' is not 'None'");
options = new CommandOptionsArxNet("--domain=" + optionValue);
Assert.AreEqual(DomainUsage.None, (DomainUsage)field.GetValue(options), "Field 'domain' is not 'None'");
options = new CommandOptionsArxNet(false, "/domain=" + optionValue);
Assert.AreEqual(DomainUsage.None, (DomainUsage)field.GetValue(options), "Field 'domain' is not 'None'");
options = new CommandOptionsArxNet(true, "/domain=" + optionValue);
Assert.AreEqual(DomainUsage.None, (DomainUsage)field.GetValue(options), "Field 'domain' is not 'None'");
options = new CommandOptionsArxNet();
Assert.AreEqual(DomainUsage.None, (DomainUsage)field.GetValue(options), "Field 'domain' is not 'None'");
}
#if CLR_2_0 || CLR_4_0
[TestCase("Single")]
[TestCase("Separate")]
[TestCase("Multiple")]
public void ProcessOptionIsSingle(string optionValue)
{
FieldInfo field = typeof(CommandOptionsArxNet).GetField("process");
CommandOptionsArxNet options = new CommandOptionsArxNet("-process=" + optionValue);
Assert.AreEqual(ProcessModel.Single, (ProcessModel)field.GetValue(options), "Field 'process' is not 'None'");
options = new CommandOptionsArxNet("--process=" + optionValue);
Assert.AreEqual(ProcessModel.Single, (ProcessModel)field.GetValue(options), "Field 'process' is not 'None'");
options = new CommandOptionsArxNet(false, "/process=" + optionValue);
Assert.AreEqual(ProcessModel.Single, (ProcessModel)field.GetValue(options), "Field 'domain' is not 'None'");
options = new CommandOptionsArxNet(true, "/process=" + optionValue);
Assert.AreEqual(ProcessModel.Single, (ProcessModel)field.GetValue(options), "Field 'process' is not 'None'");
options = new CommandOptionsArxNet();
Assert.AreEqual(ProcessModel.Single, (ProcessModel)field.GetValue(options), "Field 'process' is not 'None'");
}
#endif
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace exo_pendu
{
class Program
{
static void dessin(int pouet)
{
switch (pouet)
{
case 0:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- | -");
Console.WriteLine(" |");
Console.WriteLine(" / \\");
Console.WriteLine("Ne scie pas la branche sur laquelle tu es assis, ร moins qu'on ne veuille t'y pendre.");
Console.WriteLine("La prochaine fois scie la branche car aujourd'hui tu es pendu!!");
break;
case 1:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- | -");
Console.WriteLine(" |");
Console.WriteLine(" / \\");
break;
case 2:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- | -");
Console.WriteLine(" |");
Console.WriteLine(" /");
break;
case 3:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- | -");
Console.WriteLine(" |");
break;
case 4:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- | -");
break;
case 5:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine("- |");
break;
case 6:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
Console.WriteLine(" |");
break;
case 7:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
Console.WriteLine(" O");
break;
case 8:
Console.WriteLine("__");
Console.WriteLine(" |");
Console.WriteLine(" |");
break;
case 9:
Console.WriteLine("__");
Console.WriteLine(" |");
break;
case 10:
Console.WriteLine("__");
break;
case 11:
Console.WriteLine("_ ");
break;
}
}
static void Main(string[] args)
{
string joueur1;
string joueur2;
string LettreSaisie;
string MotATrouver;
int NombreDeVieRestante = 11;
bool validationjoueur1 = false;
bool validationjoueur2 = false;
bool validationmotsecret = false;
bool validationlettre = false;
do
{
Console.WriteLine("Nom du joueur 1");
joueur1 = Console.ReadLine();
string lettresok = @"^[a-z]{2,50}$";
if (Regex.IsMatch(joueur1, @lettresok))
{
validationjoueur1 = true;
}
else
Console.WriteLine("Saisissez un nom valide (a-Z)");
}
while (validationjoueur1 == false);
do
{
Console.WriteLine("Nom du joueur 2");
joueur2 = Console.ReadLine();
string lettresok = @"^[a-z]{2,50}$";
if (Regex.IsMatch(joueur2, @lettresok))
{
validationjoueur2 = true;
}
else
Console.WriteLine("Saisissez un nom valide (a-Z)");
}
while (validationjoueur2 == false);
do
{
Console.WriteLine(joueur1 + " Saisissez un mot de dix lettres ou moins");
MotATrouver = Console.ReadLine();
string lettresok = @"^[a-z]{1,10}$";
if (Regex.IsMatch(MotATrouver, @lettresok))
{
validationmotsecret = true;
Console.Clear();
}
else
Console.WriteLine("Saisissez un mot valide (a-Z) et de moins de dix lettres");
}
while (validationmotsecret == false);
string[] Mot = new string[MotATrouver.Length];
string[] ARemplir = new string[MotATrouver.Length];
int j = 0;
int erreur = 1;
string listelettreerreur = "";
bool gagne = false;
for (int k = 0; k < MotATrouver.Length; k++)
{
Mot[k] = MotATrouver.Substring(k, 1);
ARemplir[k] = "_";
}
while (erreur < 12 && !gagne)
{
validationlettre = false;
do
{
Console.WriteLine(joueur2 + " Saisissez une lettre");
LettreSaisie = Console.ReadLine();
string lettresok = "^[a-z]$";
if (Regex.IsMatch(LettreSaisie, @lettresok) && LettreSaisie.Length == 1)
{
validationlettre = true;
}
else
Console.WriteLine("Saisissez une lettre valide (a-Z)");
}
while (validationlettre == false);
bool perdunevie = true;
j = 0;
while (j < MotATrouver.Length)
{
if (LettreSaisie == Mot[j])
{
ARemplir[j] = Mot[j];
perdunevie = false;
}
j++;
}
Console.Clear();
if (perdunevie == true)
{
listelettreerreur += LettreSaisie;
Console.WriteLine(LettreSaisie + " ne se trouve pas dans le mot a trouver");
erreur++;
NombreDeVieRestante--;
dessin(NombreDeVieRestante);
}
Console.WriteLine("prรฉcรฉdent รฉchec " + listelettreerreur);
Console.WriteLine("Nombre de vie restante " + NombreDeVieRestante);
gagne = true;
for (int i = 0; i < ARemplir.Length; i++)
{
if (ARemplir[i] == "_")
{
gagne = false;
}
Console.Write(ARemplir[i]);
}
Console.WriteLine();
}
if (gagne)
Console.WriteLine("You WIN");
else
Console.WriteLine("NOOB , you LOOSE");
Console.ReadLine();
}
}
}
|
๏ปฟ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;
using System.IO;
using System.Drawing.Printing;
namespace YourProject_winForms
{
public partial class ReceiptView : Form
{
#region MyLogger
// declaration of logger
private static readonly log4net.ILog myLog4N = log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
#region Variables
PictureBox pbReceiptImage;
private string imgPath;
#endregion
public ReceiptView(string path)
{
InitializeComponent();
imgPath = path;
}
private void ReceiptView_Load(object sender, EventArgs e)
{
AdjustImageAddScroll();
}
private void AdjustImageAddScroll()
{
pbReceiptImage = new PictureBox();
pbReceiptImage.SizeMode = PictureBoxSizeMode.AutoSize;
pbReceiptImage.ImageLocation = imgPath;
flowLayoutPanel1.AutoScroll = true;
flowLayoutPanel1.Controls.Add(pbReceiptImage);
}
private void ReceiptView_Paint(object sender, PaintEventArgs e)
{
// read the new Property settings of the ColorTheme
this.BackColor = Properties.Settings.Default.ColorTheme;
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintFile();
}
#region Print File
/// <summary>
/// Prints Current Receipt Image.
/// </summary>
private void PrintFile()
{
try
{
//instantiate print dialog
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
doc.PrintPage += DOC_PrintPage;
pd.Document = doc;
if (pd.ShowDialog() == DialogResult.OK)
{
doc.Print();
}
}
catch (IOException IOE)
{
// display export data error.
MessageBox.Show("ERROR Printing File." + IOE.Message);
myLog4N.Debug("ERROR Printing File. " + IOE.StackTrace);
}
}
private void DOC_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(pbReceiptImage.Width, pbReceiptImage.Height);
pbReceiptImage.DrawToBitmap(bm, new Rectangle(0, 0, pbReceiptImage.Width, pbReceiptImage.Height));
e.Graphics.DrawImage(bm, 0, 0);
bm.Dispose();
}
#endregion
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleSecurity.Entities;
using SimpleSecurity.Repositories;
using WebMatrix.WebData;
namespace SimpleSecurity
{
public static class WebSecurity
{
public static UserProfile GetUser(string username)
{
UnitOfWork uow = new UnitOfWork();
return uow.UserProfileRepository.Get(u => u.UserName == username).SingleOrDefault();
}
public static UserProfile GetCurrentUser()
{
return GetUser(CurrentUserName);
}
public static void CreateUser(UserProfile user)
{
UserProfile dbUser = GetUser(user.UserName);
if (dbUser != null)
throw new Exception("User with that username already exists.");
UnitOfWork uow = new UnitOfWork();
uow.UserProfileRepository.Insert(user);
uow.Save();
}
public static void UpdateUserProfile(UserProfile user)
{
UnitOfWork uow = new UnitOfWork();
UserProfile dbUser = uow.UserProfileRepository.Get(u => u.UserName == user.UserName).SingleOrDefault();
if (dbUser == null)
throw new Exception("User with that username does not exists.");
dbUser.SurName = user.SurName;
dbUser.MiddleName = user.MiddleName;
dbUser.FirstName = user.FirstName;
dbUser.ContactAddress = user.ContactAddress;
uow.UserProfileRepository.Update(dbUser);
uow.Save();
}
public static void Register()
{
Database.SetInitializer<SecurityContext>(new InitSecurityDb());
SecurityContext context = new SecurityContext();
context.Database.Initialize(true);
if (!WebMatrix.WebData.WebSecurity.Initialized)
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
}
public static bool Login(string userName, string password, bool persistCookie = false)
{
return WebMatrix.WebData.WebSecurity.Login(userName, password, persistCookie);
}
public static bool ChangePassword(string userName, string oldPassword, string newPassword)
{
return WebMatrix.WebData.WebSecurity.ChangePassword(userName, oldPassword, newPassword);
}
public static bool ConfirmAccount(string accountConfirmationToken)
{
return WebMatrix.WebData.WebSecurity.ConfirmAccount(accountConfirmationToken);
}
public static void CreateAccount(string userName, string password, bool requireConfirmationToken = false)
{
WebMatrix.WebData.WebSecurity.CreateAccount(userName, password, requireConfirmationToken);
}
public static string CreateUserAndAccount(string userName, string password, string email, bool requireConfirmationToken = false)
{
return WebMatrix.WebData.WebSecurity.CreateUserAndAccount(userName, password, new { Email = email }, requireConfirmationToken);
}
public static int GetUserId(string userName)
{
return WebMatrix.WebData.WebSecurity.GetUserId(userName);
}
public static void Logout()
{
WebMatrix.WebData.WebSecurity.Logout();
}
public static bool IsAuthenticated { get { return WebMatrix.WebData.WebSecurity.IsAuthenticated; } }
public static string CurrentUserName { get { return WebMatrix.WebData.WebSecurity.CurrentUserName; } }
}
}
|
๏ปฟusing System.Collections.Generic;
namespace RiverCrossPuzzle
{
public class Game
{
private List<Occupant> _occupants = new List<Occupant>();
private List<Shoreline> _shoreLines = new List<Shoreline>();
public IEnumerable<Occupant> Occupants
{
get { return _occupants; }
}
public IEnumerable<Shoreline> ShoreLines
{
get { return _shoreLines; }
}
public Game()
{
var duck = new Duck();
var fox = new Fox();
var farmer = new Farmer();
var corn = new Corn();
_occupants.Add(farmer);
_occupants.Add(duck);
_occupants.Add(fox);
_occupants.Add(corn);
var shorelineStart = new Shoreline();
var shoreLineEnd = new Shoreline();
_shoreLines.Add(shorelineStart);
_shoreLines.Add(shoreLineEnd);
foreach (var o in _occupants)
{
_shoreLines[0].AddOccupant(o);
}
}
public void SendAcrossRiver(Occupant duck)
{
}
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlTypes;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace Project.Service.Service
{
public interface IVehicleModel
{
IEnumerable<VehicleModel> GetAll();
VehicleModel GetModelByID(int Id);
void Create(VehicleModel vehiclemodel);
void Read(VehicleModel vehiclemodel);
void Update(VehicleModel vehiclemodel);
void Delete(int Id);
void Save();
}
public abstract class VehicleModel
{
private readonly VehicleModel vehiclemodel;
public VehicleModel(VehicleModel vehiclemodel)
{
this.vehiclemodel = vehiclemodel;
}
/*public IEnumerable<VehicleModel> GetAll()
{
}
public VehicleModel GetModelByID(int Id)
{
}*/
public void Create(VehicleModel vehiclemodel)
{
}
public void Read(VehicleModel vehiclemodel)
{
}
public void Update(VehicleModel vehiclemodel)
{
}
public void Delete(int Id)
{
}
public void Save()
{
}
}
}
|
//
// Copyright 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using Carbonfrost.Commons.Core;
using Carbonfrost.Commons.Core.Runtime;
namespace Carbonfrost.Commons.PropertyTrees.Schema {
[StreamingSource(typeof(PropertyTreeSchemaSource))]
public abstract class PropertyTreeSchema {
static readonly IDictionary<Assembly, PropertyTreeSchema> schemas = new Dictionary<Assembly, PropertyTreeSchema>();
public abstract NamespaceUri DefaultNamespace { get; set; }
// public abstract ComponentName SchemaName { get; set; }
public abstract Assembly SourceAssembly { get; }
public abstract PropertyTreeDefinitionCollection Types { get; }
public static PropertyTreeSchema FromAssembly(Assembly assembly) {
if (assembly == null)
throw new ArgumentNullException("assembly"); // $NON-NLS-1
return schemas.GetValueOrCache(assembly,
a => new ReflectedPropertyTreeSchema(a));
}
public PropertyTreeDefinition DefineType(string name) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (string.IsNullOrEmpty(name)) {
throw Failure.EmptyString("name");
}
throw new NotImplementedException();
}
public PropertyTreeDefinition DefineType(QualifiedName name) {
if (name == null)
throw new ArgumentNullException("name");
throw new NotImplementedException();
}
public PropertyTreeDefinition GetType(Type type, bool declaredOnly = false) {
if (type == null)
throw new ArgumentNullException("type");
throw new NotImplementedException();
}
public PropertyTreeDefinition ImportType(PropertyTreeDefinition definition) {
if (definition == null)
throw new ArgumentNullException("definition");
throw new NotImplementedException();
}
public static PropertyTreeSchema FromFile(string file) {
if (file == null)
throw new ArgumentNullException("file");
if (string.IsNullOrEmpty(file))
throw Failure.EmptyString("file");
return FromStreamContext(StreamContext.FromFile(file));
}
public static PropertyTreeSchema FromSource(Uri source) {
if (source == null)
throw new ArgumentNullException("source");
return FromStreamContext(StreamContext.FromSource(source));
}
public static PropertyTreeSchema FromStreamContext(StreamContext source) {
if (source == null)
throw new ArgumentNullException("source");
throw new NotImplementedException();
}
}
}
|
๏ปฟusing System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace ToDoApp.Contollers
{
public class Feladat
{
//kulcsmezล nรฉlkรผl nem lehet az adatbรกzisba adatokat feltรถlteni az Id-t automatikusan felismeri
public int Id { get; set; }
[Required] //Ez az annotรกciรณ megmondja, hogy a kรถvetkezล tulajdonsรกg(property) kรถtelezล
[MinLength(3)] //Ez a hosszรกt vizsgรกlja minimum 3
//[MaxLength(5)] //eZ is maximum 5
[DisplayName("A feladat megnevezรฉse: ")] //ezzel az annotรกciรณval a cรญmkรฉt tudjuk รกtnevezni (amit a LabelFor-al kiteszรผnk a view-ban)
public string Megnevezes { get; set; } //ez egy tulajdonsรกg(property) (getter setter)
public bool Elvegezve; //ez egy adatmezล(field)
}
} |
๏ปฟusing AssetHub.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AssetHub.ViewModels.AssetModel.Partial
{
public class AddAssetModelViewModel
{
public class PropertyEditor
{
public string Name { get; set; }
public bool IsNumeric { get; set; }
}
public AddAssetModelViewModel()
{
SelectedCategoryId = -1;
Properties = new List<PropertyEditor>();
}
[Required]
public string Name { get; set; }
[Required]
[Display(Name = "Category")]
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public List<PropertyEditor> Properties { get; set; }
}
} |
๏ปฟnamespace Domain.Enums
{
public enum BodyStyle
{
Unknown,
Sedan,
Coupe,
Sports,
Wagon,
Hatchback,
Convertible,
SUV,
Minivan,
Pickup,
Buggy,
Limousine,
Hearse
}
public enum Drivetrain
{
Unknown,
RearWheel,
FrontWheel,
AllWheel
}
public enum Transmission
{
Unknown,
Manual,
Automatic,
SemiAutomatic,
CVT
}
}
|
๏ปฟusing SMSAPI3_5;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
/// <summary>
/// Summary description for SMSR
/// </summary>
public class SMSR
{
private WebProxy objProxy1 = null;
public static string Send_smsR(string username, string password, string channel, string DCS, string flashsms, string mobile_no, string message, string unicode, string senderid, string route, string url)
{
SMSAPI obj = new SMSAPI();
//SMSSend obj = new SMSSend();
string strPostResponse="";
strPostResponse = obj.senssms(username, password, channel, DCS, flashsms, mobile_no, message, unicode, senderid, route, url);
return ("Server Response " + strPostResponse);
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Iterator.Iterators.Duckling
{
public interface IIterator<out T>
{
Boolean hasNext();
T next();
}
}
|
๏ปฟnamespace FileTransporter.Panels
{
public class LoginInfo
{
public ushort ServerPort { get; set; } = 8080;
public ushort ClientPort { get; set; } = 8080;
public string ClientConnectAddress { get; set; } = "127.0.0.1";
public string ServerPassword { get; set; }
public string ClientPassword { get; set; }
public string ClientName { get; set; } = System.Environment.MachineName;
}
} |
๏ปฟusing System;
using System.Collections.Generic;
using Webcorp.Model;
namespace Webcorp.Controller
{
public class ActionResult
{
static ActionResult()
{
Ok = new ActionResult(true, "");
}
public ActionResult(bool result,Exception e)
{
this.Result = result;
this.Message = e==null?"": e.Message??"";
this.Exception = e;
}
public ActionResult(bool result,string message)
{
this.Result = result;
this.Message = message;
}
public bool Result { get; protected set; }
public string Message { get; protected set; }
public Exception Exception { get; private set; }
public virtual void Throw()
{
if (Result) return;
Exception.Throw();
throw new Exception(Message);
}
public static ActionResult Ok { get; private set; }
public static ActionResult Create(bool result, Exception lastError)
{
return new ActionResult(result, lastError);
}
}
public class ActionResult<T,TKey>:ActionResult where T : IEntity<TKey>
{
Exception _innerException;
public ActionResult(List<ActionResult<T,TKey>> inner,T entity):base(true, "See Inner actions results")
{
this.InnerActionsResults = inner;
foreach (var item in inner)
{
if (!item.Result) {
Result = false;
_innerException = item.Exception??new Exception(item.Message);
Message = item.Message;
break;
}
}
}
public ActionResult(bool result, Exception e,T entity):base(result,e)
{
this.Entity = entity;
}
public ActionResult(bool result, string message,T entity):base(result,message)
{
this.Entity = entity;
}
public T Entity { get; private set; }
public List<ActionResult<T, TKey>> InnerActionsResults { get; private set; }
public static ActionResult<T,TKey> Create(bool result, Exception lastError,T entity)
{
return new ActionResult<T,TKey>(result, lastError,entity);
}
public static ActionResult<T, TKey> Create(List<ActionResult<T, TKey>> inner, T entity)
{
return new ActionResult<T, TKey>(inner, entity);
}
public new static ActionResult<T, TKey> Ok(T entity) => new ActionResult<T, TKey>(true,"",entity);
public override void Throw()
{
if (Result) return;
if (InnerActionsResults != null & InnerActionsResults.Count > 0) throw new Exception(Message,_innerException);
base.Throw();
}
}
public class ActionResult<T> : ActionResult<T,string> where T : IEntity<string>
{
public ActionResult(bool result, Exception e, T entity) : base(result, e,entity)
{
}
public ActionResult(bool result, string message, T entity) : base(result, message,entity)
{
}
}
/*public class InnerActionException<T,TKey> : Exception where T :IEntity<TKey>
{
public InnerActionException(string message, List<ActionResult<T, TKey>> inner):base(message)
{
this.Inner
}
}*/
}
|
using PROJECT.SERV.Model.Adm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SFP.SERVICIOS.MODEL.ADM
{
public class TCP_Adm_AreaOrg
{
public int Id { get; set; }
public string descripcion { get; set; }
public float calificacion { get; set; }
public int personas { get; set; }
public int orden { get; set; }
public float presupuesto { get; set; }
public string siglas { get; set; }
public string uni { get; set; }
public int indicador { get; set; }
public List<TCP_Adm_Obj> objetivos {get; set;}
public TCP_Adm_AreaOrg () {}
}
}
|
๏ปฟusing Key;
using NameApi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
namespace RFID_Inventarization
{
public partial class Mode1 : Form
{
private Thread findThread;
public dbFacade db = new dbFacade();
private int m_btnStop;
private string onetagInfo;
private Hook hk = new Hook();
public Mode1()
{
InitializeComponent();
Color r = Color.FromArgb(250, 236, 175);
this.BackColor = r;
DataTable bData = db.FetchAllSql("SELECT * FROM meta");
foreach (DataRow dr in bData.Rows)
{
string s = dr[0].ToString();
string a = s.Substring(0, 4) + " - " + s.Substring(4, 4) + " - " + s.Substring(8, 4);
listBox3.Items.Add(a);
}
}
private void button1_Click_1(object sender, EventArgs e)
{
if (this.m_btnStop == 0)
{
this.m_btnStop = 1;
this.findThread = new Thread(new ThreadStart(this.myThread));
this.findThread.Start();
this.button1.Text = "ะััะฐะฝะพะฒะธัั";
this.button1.ForeColor = Color.Red;
}
else
{
this.button1.Text = "ะกะบะฐะฝะธัะพะฒะฐัั";
this.m_btnStop = 0;
this.findThread.Abort();
this.button1.ForeColor = Color.Black;
}
}
private void myThread()
{
byte nTagCount = 0;
byte[] buffer = new byte[0x200];
string[] strArray = new string[50];
while (this.m_btnStop == 1)
{
if (1 == HTApi.WIrUHFInventoryOnce(ref nTagCount, ref buffer[0]))
{
// MessageBox.Show("1" + nTagCount);
int index = 0;
int num3 = 0;
int num5 = 0;
int num6 = 0;
index = 0;
while (index < nTagCount)
{
int num4 = buffer[num5++];
num6++;
for (num3 = 0; num3 < num4; num3++)
{
string str = string.Format("{0:X2}", buffer[num5++]);
if (num3 == 0)
{
strArray[index] = str;
}
else
{
string[] strArray2;
IntPtr ptr;
(strArray2 = strArray)[(int)(ptr = (IntPtr)index)] = strArray2[(int)ptr] + "" + str;
}
}
index++;
}
for (index = 0; index < num6; index++)
{
try
{
string s = strArray[index];
s = s.Substring(0, 12);
onetagInfo = s.Substring(0, 4) + " - " + s.Substring(4, 4) + " - " + s.Substring(8, 4);
listBox3.BeginInvoke(new InvokeDelegate(this.Display));
}
catch (Exception) { }
}
}
}
}
private void Display()
{
if (!listBox3.Items.Contains(onetagInfo))
{
listBox3.Items.Add(onetagInfo);
listBox3.SelectedIndex = listBox3.Items.Count - 1;
string sql = "INSERT INTO meta (rfid) VALUES ('" + onetagInfo.Replace(" - ",String.Empty) + "')";
db.FetchAllSql(sql);
}
}
private void FindForm_Closing(object sender, CancelEventArgs e)
{
//if (hard) return;
//if (MessageBox.Show("ะัะนัะธ? ะะฐะฝะฝัะต ะฑัะดัั ะฝะต ัะพั
ัะฐะฝะตะฝั!", "ะะฝะธะผะฐะฝะธะต!", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
//{
// this.Close();
//}
//else
//{
// e.Cancel = true;
//}
}
private void FindForm_KeyDown(object sender, KeyEventArgs e)
{
if ((Convert.ToInt32(e.KeyCode).ToString() == "45") && (this.m_btnStop == 0))
{
this.m_btnStop = 1;
this.findThread = new Thread(new ThreadStart(this.myThread));
this.findThread.Start();
this.button1.Text = "ะััะฐะฝะพะฒะธัั";
this.button1.ForeColor = Color.Red;
}
}
private void FindForm_KeyUp(object sender, KeyEventArgs e)
{
if ((Convert.ToInt32(e.KeyCode).ToString() == "45") && (this.m_btnStop == 1))
{
this.button1.Text = "ะกะบะฐะฝะธัะพะฒะฐัั";
this.button1.ForeColor = Color.Black;
this.m_btnStop = 0;
this.findThread.Abort();
}
}
private void FindForm_Load(object sender, EventArgs e)
{
this.m_btnStop = 0;
}
public delegate void InvokeDelegate();
private void timer1_Tick(object sender, EventArgs e)
{
try
{
base.Text = "ะะฝะฒะตะฝัะฐัะธะทะฐัะธั " + Global.getBattary();
}
catch (Exception) { }
}
private void FindForm_Closed(object sender, EventArgs e)
{
if (this.m_btnStop == 1)
{
this.button1.Text = "ะกะบะฐะฝะธัะพะฒะฐัั";
this.m_btnStop = 0;
this.findThread.Abort();
this.findThread.Join(100);
}
}
private void pictureBox4_Click(object sender, EventArgs e)
{
this.Close();
}
}
} |
๏ปฟusing QLTTHT.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLTTHT.DAO
{
class MucThanhToanDAO
{
private static MucThanhToanDAO instance;
public static MucThanhToanDAO Instance
{
get { if (instance == null) instance = new MucThanhToanDAO(); return instance; }
private set { instance = value; }
}
public List<MucThanhToan> GetAll()
{
List<MucThanhToan> list = new List<MucThanhToan>();
DataTable data = DataProvider.Instance.ExecuteQuery("GetMucTTList");
foreach (DataRow item in data.Rows)
{
MucThanhToan entry = new MucThanhToan(item);
list.Add(entry);
}
return list;
}
public MucThanhToan GetTiLeTT(int mamtt)
{
DataTable data = DataProvider.Instance.ExecuteQuery("exec GetMucThanhToan @mamtt", new object[] { mamtt });
MucThanhToan mtt = new MucThanhToan(data.Rows[0]);
return mtt;
}
}
}
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour {
public Sprite m_tichuIcon;
public Sprite m_grandTichuIcon;
public Sprite m_teamNameBar;
public Sprite m_enemyNameBar;
public Image m_rotateTurnImage;
public Text m_cardCountText;
public Image m_namebar;
public Image m_tichu;
public Image m_wishCardImg;
public Text m_wishText;
public int offsetX;
public int offsetY;
protected bool m_isCallTichu;
protected bool m_isCallLargeTichu;
protected bool m_isChooseLargeTichu;
protected int m_point;
protected int m_bonusPoint;
public Text m_pointText;
public Text m_scoreBoardPointText;
public Text m_myName;
protected List<CardData> m_myCard = new List<CardData>();
protected SelectCard m_selectedCard = new SelectCard();
protected List<CardData> m_eatCard = new List<CardData>();
protected CardData[] m_exchagnedCard = new CardData[3];
protected List<CardData> m_myCardIdxList = new List<CardData>();
protected List<CardData> m_bombCard = new List<CardData>();
protected List<CardData> m_strightBomCard = new List<CardData>();
protected bool m_bIsDraw = false;
protected bool m_bIsExchange = false;
protected bool m_bDrawMajjong = false;
protected bool m_bIsMyTurn = false;
protected bool m_bHavePhoenix = false;
protected Player m_leftPlayer;
protected Player m_rightPlayer;
protected Player m_teamPlayer;
public bool NonPlayer { get; set; }
public int TeamID { get; set; }
protected int m_nPlayerIdx;
public int PlayerIdx
{
get { return m_nPlayerIdx; }
set { m_nPlayerIdx = value; }
}
public Image GetTurnImage()
{
return m_rotateTurnImage;
}
public bool IsMyTurn()
{
return m_bIsMyTurn;
}
public bool IsCallTichu()
{
return m_isCallTichu;
}
public bool IsCallLargeTichu()
{
return m_isCallLargeTichu;
}
public bool DrawBomb()
{
if (m_bombCard.Count > 0 || m_strightBomCard.Count > 0)
{
m_bIsDraw = true;
//ํญํ์ด ์๋ค.
if (m_bombCard.Count > 0)
{
m_selectedCard.Init();
//์ผ๋ฐ ํญํ
for (int i = 0; i < m_bombCard.Count; ++i)
{
m_selectedCard.Add(m_bombCard[i]);
}
}
else
{
//์คํธ๋ ์ดํธ ํญํ
for (int i = 0; i < m_strightBomCard.Count; ++i)
{
m_selectedCard.Add(m_strightBomCard[i]);
}
}
StartCoroutine(CardDraw());
return true;
}
return false;
}
private void Awake()
{
m_isCallTichu = m_isCallLargeTichu = false;
m_point = 0;
m_bonusPoint = 0;
m_pointText.text = name + "\n" + m_point.ToString();
m_scoreBoardPointText.text = m_pointText.text;
m_myName.text = name;
NonPlayer = false;
m_tichu.gameObject.SetActive(false);
m_cardCountText.text = m_myCard.Count.ToString() + "์ฅ";
}
public void HavePhoenix()
{
m_bHavePhoenix = true;
}
public void InitPlayerInfo()
{
m_isCallTichu = m_isCallLargeTichu = false;
m_point = 0;
m_bonusPoint = 0;
m_pointText.text = name + "\n" + m_point.ToString();
m_scoreBoardPointText.text = m_pointText.text;
NonPlayer = false;
m_isChooseLargeTichu = false;
m_bHavePhoenix = false;
m_bIsExchange = false;
m_bIsDraw = false;
m_bDrawMajjong = false;
GameManager.Instance.TichuBtnEnabled(true);
m_tichu.gameObject.SetActive(false);
m_wishCardImg.gameObject.SetActive(false);
m_pointText.color = new Color(0, 0, 0);
m_scoreBoardPointText.color = new Color(0, 0, 0);
m_bombCard.Clear();
m_strightBomCard.Clear();
m_cardCountText.text = m_myCard.Count.ToString() + "์ฅ";
for (int i = 0; i < 3; ++i)
{
m_exchagnedCard[i] = null;
}
m_myCard.Clear();
m_eatCard.Clear();
m_selectedCard.Init();
StopCoroutine(AnimationClip());
}
public void SetCardOriginPosition()
{
for (int i = 0; i < m_myCard.Count; ++i)
{
m_myCard[i].SetOriginPosition();
}
}
public virtual void SetCardCount(int count)
{
m_cardCountText.text = count.ToString() + "์ฅ";
}
public virtual void SetCardCount()
{
m_cardCountText.text = m_myCard.Count.ToString() + "์ฅ";
}
public void MyCardClear()
{
//for (int i = 0; i < m_myCard.Count; ++i)
//{
// if (m_myCard[i] != null)
// {
// m_myCard[i].Init();
// }
//}
m_myCard.Clear();
}
public bool DrawMajjong()
{
return m_bDrawMajjong;
}
public Player GetTemaPlayer()
{
return m_teamPlayer;
}
public Player GetLeftPlayer()
{
return m_leftPlayer;
}
public Player GetRightPlayer()
{
return m_rightPlayer;
}
public void SetLeftPlayer(ref Player left)
{
m_leftPlayer = left;
}
public void SetRightPlayer(ref Player right)
{
m_rightPlayer = right;
}
public void RoundSet()
{
m_isCallTichu = m_isCallLargeTichu = false;
m_point = 0;
m_pointText.text = name + "\n" + m_point.ToString();
m_scoreBoardPointText.text = m_pointText.text;
}
public void AddCard(CardData cardData)
{
cardData.SetOwnerPlayer(this);
cardData.SetOwnerPlayerCardIdx(m_myCard.Count);
m_myCard.Add(cardData);
if (cardData.type == CARD_TYPE.PHOENIX)
{
m_bHavePhoenix = true;
}
}
virtual public void ArrangementCard()
{
//value ๊ฐ์ผ๋ก ์ ๋ ฌ
m_myCard.Sort(delegate (CardData a, CardData b)
{
if (a == b)
{
return 0;
}
if (a.value == b.value)
{
if (a.color > b.color)
{
return 1;
}
else
{
return -1;
}
}
return a.value.CompareTo(b.value);
}
);
int size = m_myCard.Count;
int offset = -(size / 2);
for (int i = 0; i < size; ++i)
{
if (this.name == "Player" && !m_myCard[i].IsSelected())
{
m_myCard[i].transform.position = transform.position + m_myCard[i].transform.right * (offset * 110);
m_myCard[i].SetSortingRayer(i);
}
++offset;
}
}
public void SetOriginTransform()
{
int size = m_myCard.Count;
for (int i = 0; i < size; ++i)
{
m_myCard[i].SetOriginPosition();
}
}
public void SetPlayers(ref Player left, ref Player team, ref Player right)
{
m_leftPlayer = left;
m_teamPlayer = team;
m_rightPlayer = right;
}
public void AddSelectedCard(CardData card)
{
if (GameManager.Instance.rutine == RutineState.RoundState)
{
//card.Hide(false);
m_selectedCard.Add(card);
m_bIsDraw = DrawCheck();
}
else if (GameManager.Instance.rutine == RutineState.ExchangeState)
{
int index = 0;
for (int i = 0; i < 3; ++i)
{
if (m_exchagnedCard[i] == null)
{
index = i;
break;
}
}
m_exchagnedCard[index] = card;
m_myCard.Remove(card);
//์นด๋์ ์์น๋ฅผ ์ฎ๊ฒจ์ค์ผ ๋๋ค.
switch (index)
{
case 0:
{
m_exchagnedCard[index].transform.position = GameManager.Instance.m_ExchangeUi.m_leftCard.transform.position;
m_exchagnedCard[index].transform.rotation = GameManager.Instance.m_ExchangeUi.m_leftCard.transform.rotation;
}
break;
case 1:
{
m_exchagnedCard[index].transform.position = GameManager.Instance.m_ExchangeUi.m_partnerCard.transform.position;
m_exchagnedCard[index].transform.rotation = GameManager.Instance.m_ExchangeUi.m_partnerCard.transform.rotation;
}
break;
case 2:
{
m_exchagnedCard[index].transform.position = GameManager.Instance.m_ExchangeUi.m_rightCard.transform.position;
m_exchagnedCard[index].transform.rotation = GameManager.Instance.m_ExchangeUi.m_rightCard.transform.rotation;
}
break;
}
for (int i = 0; i < 3; ++i)
{
m_bIsExchange = true;
if (m_exchagnedCard[i] == null)
{
m_bIsExchange = false;
break;
}
}
}
}
public void ReleaseCard(CardData card)
{
if (GameManager.Instance.rutine == RutineState.RoundState)
{
m_selectedCard.ReleaseCard(card);
m_bIsDraw = DrawCheck();
ArrangementCard();
}
else if (GameManager.Instance.rutine == RutineState.ExchangeState)
{
for (int i = 0; i < 3; ++i)
{
if (m_exchagnedCard[i] == card)
{
m_exchagnedCard[i] = null;
break;
}
}
m_myCard.Add(card);
card.MoveOriginPosition();
//m_exchagnedCard[idx].MoveOriginPosition();
//์ญ์ ํ๋ฉด ๋ฌด์กฐ๊ฑด false์ง?
m_bIsExchange = false;
}
}
public void SwapExchangeCard(int idx1, int idx2)
{
//idx1 = ํฌ์ง์
์ ๋ฐ๊ฟ๋ ๋จ, idx2 = ํฌ์ง์
์ ๋ฐ๊ฟ์ค์ผ ๋จ
CardData temp = m_exchagnedCard[idx1];
m_exchagnedCard[idx1] = m_exchagnedCard[idx2];
m_exchagnedCard[idx2] = temp;
if (m_exchagnedCard[idx2] == null)
return;
//์นด๋์ ์์น๋ฅผ ์ฎ๊ฒจ์ค์ผ ๋๋ค.
switch (idx2)
{
case 0:
{
m_exchagnedCard[idx2].transform.position = GameManager.Instance.m_ExchangeUi.m_leftCard.transform.position;
m_exchagnedCard[idx2].transform.rotation = GameManager.Instance.m_ExchangeUi.m_leftCard.transform.rotation;
}
break;
case 1:
{
m_exchagnedCard[idx2].transform.position = GameManager.Instance.m_ExchangeUi.m_partnerCard.transform.position;
m_exchagnedCard[idx2].transform.rotation = GameManager.Instance.m_ExchangeUi.m_partnerCard.transform.rotation;
}
break;
case 2:
{
m_exchagnedCard[idx2].transform.position = GameManager.Instance.m_ExchangeUi.m_rightCard.transform.position;
m_exchagnedCard[idx2].transform.rotation = GameManager.Instance.m_ExchangeUi.m_rightCard.transform.rotation;
}
break;
}
}
public void AddExchangeCard(CardData card, int index)
{
card.SetSelect(true);
//๋ง์ฝ null์ธ ๊ฒฝ์ฐ๋ ๊ทธ๋ฅ ์นด๋๋ฅผ ๋ฑ๋ก๋ง ํด์ค
if (m_exchagnedCard[index] == null)
{
//๋ง์ฝ ์์์ ์ฎ๊ฒจ๊ฐ ๊ฒฝ์ฐ๋?
if (m_myCard.Remove(card))
{
m_exchagnedCard[index] = card;
}
else
{
//๋ด ์นด๋์ค์ ์๋ค. ์์์ ์ฎ๊ฒจ๊ฐ ๊ฒฝ์ฐ๋ค.
for (int i = 0; i < 3; ++i)
{
if (i != index)
{
if (m_exchagnedCard[i] == card)
{
//์ด๋์ ์ฎ๊ธฐ๊ณ ์๋์ง ์์น๋ฅผ ์ฐพ์
//ํด๋น ์์น๋ ๋ฐ๊ฟ์ค์ผ ๋จ
//ํฌ์ง์
๋ ๋ฐ๊ฟ์ค์ผ ๋ ๋ฏ;
SwapExchangeCard(index, i);
break;
}
}
}
}
}
else
{
//๋ง์ฝ ์์์ ์ฎ๊ฒจ๊ฐ ๊ฒฝ์ฐ๋?
if (m_myCard.Remove(card))
{
//null์ด ์๋ ๊ฒฝ์ฐ ์นด๋๊ฐ ์์ผ๋ ๊ต์ฒด๋ฅผ ํด์ฃผ์
//์ผ๋จ ์์ ๊ฐ์ ๋นผ์ฃผ์.
m_exchagnedCard[index].MoveOriginPosition();
m_exchagnedCard[index].SetSelect(false);
m_myCard.Add(m_exchagnedCard[index]);
m_exchagnedCard[index] = null;
//๊ทธ๋ฆฌ๊ณ ์ ๊ฐ์ ๋ฃ๋๋ค.
m_exchagnedCard[index] = card;
}
else
{
//๋ด ์นด๋์ค์ ์๋ค. ์์์ ์ฎ๊ฒจ๊ฐ ๊ฒฝ์ฐ๋ค.
for (int i = 0; i < 3; ++i)
{
if (i != index)
{
if (m_exchagnedCard[i] == card)
{
//์ด๋์ ์ฎ๊ธฐ๊ณ ์๋์ง ์์น๋ฅผ ์ฐพ์
//ํด๋น ์์น๋ ๋ฐ๊ฟ์ค์ผ ๋จ
SwapExchangeCard(index, i);
break;
}
}
}
}
}
for (int i = 0; i < 3; ++i)
{
m_bIsExchange = true;
if (m_exchagnedCard[i] == null)
{
m_bIsExchange = false;
break;
}
}
}
public void RemoveExchangeCard(CardData card, int index)
{
m_exchagnedCard[index] = null;
m_myCard.Add(card);
m_bIsExchange = false;
}
public virtual bool DrawCheck()
{
int size = m_selectedCard.GetSize();
//๋ฆฌ์คํธ๊ฐ ๋น์ด์์ผ๋ฉด ์ฒดํฌํ ํ์๊ฐ ์๋ค.
if (size <= 0)
{
//๋ด๊ฐ ์ฒ์์ด๋ค?
if (CardDrawHandler.Instance.GetDrawCardType() == DRAWCARD_TYPE.NONE)
{
GameManager.Instance.SetActivePlayBtn(true);
GameManager.Instance.m_drawBtn.Inactive();
}
else
{
GameManager.Instance.SetActivePlayBtn(false);
GameManager.Instance.m_passBtn.Active();
}
return false;
}
GameManager.Instance.SetActivePlayBtn(true);
if (GameManager.Instance.GetTurnPlayer() == this)
{
GameManager.Instance.m_drawBtn.Active();
}
else
{
GameManager.Instance.m_drawBtn.Inactive();
}
DRAWCARD_TYPE eDrawCardType = CardDrawHandler.Instance.GetDrawCardType();
//์ฐธ์๊ฐ ์๋ค.
if (GameManager.Instance.m_wishCardPopup.Selected())
{
string wishCardStr = GameManager.Instance.m_wishCardPopup.GetWishCard();
//๋ด๊ฐ ์ ํํ ์นด๋์ค์ ์์์ด ์๋ค ์๋ค?
//๋ด ์นด๋์ค์ ์์์นด๋๊ฐ ์๊ณ ์ ํํ ์นด๋์์ ์์์ด ์๋์ง ์ฒดํฌ
if (HaveWishCard(wishCardStr))
{
//๋ผ์๊ฐ ์๋ค.
if (IsDrawWishCard())
{
//์ ํ์นด๋์ wish๊ฐ ์์ผ๋ฉด ๋ชป๋ธ๋ค.
if (!m_selectedCard.FindWishCard(wishCardStr))
{
return false;
}
}
}
}
// NONE ํ์
์ด๊ฑฐ๋ ๋๋ ํ์
์ด ๊ฐ์ผ๋ฉด ๋ผ์ ์๋ค.
if (eDrawCardType == DRAWCARD_TYPE.NONE)
{
return m_selectedCard.GetDrawCardType() != DRAWCARD_TYPE.NONE;
}
else if (eDrawCardType == m_selectedCard.GetDrawCardType())
{
if (CardDrawHandler.Instance.GetCardCount() == m_selectedCard.GetSize() && CardDrawHandler.Instance.GetTopValue() < m_selectedCard.GetTopValue())
{
return true;
}
}
return false;
}
public void CardDrawBtn()
{
StartCoroutine(CardDraw());
}
public IEnumerator CardDraw()
{
//if (!m_bIsMyTurn)
//{
// yield break;
//}
//m_bIsMyTurn = false;
if (m_bIsDraw)
{
//์นด๋๋ฅผ ๋ด๋ฉด ํฐ์ธ๋ฅผ ํฌ๊ธฐํ๊ฒ ๋๋ค.
if (!GameManager.Instance.m_tichuBtn.IsActive())
{
//GameManager.Instance.m_tichuBtn.gameObject.SetActive(false);
GameManager.Instance.m_tichuBtn.Inactive();
}
//์นด๋๋ฅผ ๋์ผ๋ฉด ๋ฐ๋ก ๋นํ์ฑํ ์์ผ์ฃผ์.
//GameManager.Instance.m_drawBtn.SetActive(false);
GameManager.Instance.m_drawBtn.Hide();
GameManager.Instance.SetTopPlayer(this);
List<CardData> selectedCardList = m_selectedCard.GetCardList();
CardDrawHandler.Instance.CardDrawAtList(selectedCardList, m_selectedCard.GetDrawCardType(), m_selectedCard.GetTopValue());
//์ฐธ์๊ฐ ์๋ค.
if (GameManager.Instance.m_wishCardPopup.Selected())
{
string wishCardStr = GameManager.Instance.m_wishCardPopup.GetWishCard();
//๋ด๊ฐ ์ ํํ ์นด๋์ค์ ์์์ด ์๋ค ์๋ค?
//๋ด ์นด๋์ค์ ์์์นด๋๊ฐ ์๊ณ ์ ํํ ์นด๋์์ ์์์ด ์๋์ง ์ฒดํฌ
if (HaveWishCard(wishCardStr) && m_selectedCard.FindWishCard(wishCardStr))
{
GameManager.Instance.AchieveWish();
}
}
for (int i = 0; i < selectedCardList.Count; ++i)
{
if (selectedCardList[i].value == 1)
{
m_bDrawMajjong = true;
break;
}
}
int size = m_selectedCard.GetSize();
int offset = -(size / 2);
string temp = "Palyer ๋๋ก์ฐ ์นด๋ : ";
List<Vector3> endPosList = new List<Vector3>();
for (int i = 0; i < selectedCardList.Count; ++i)
{
Vector3 endPos;
endPos = CardDrawHandler.Instance.transform.position + CardDrawHandler.Instance.transform.right * (offset * 70);
endPos = new Vector3(endPos.x + offsetX, endPos.y + offsetY, 0);
endPosList.Add(endPos);
temp += selectedCardList[i].value + " ";
++offset;
m_myCard.Remove(selectedCardList[i]);
}
yield return StartCoroutine(m_selectedCard.CardDrawMove(endPosList));
Debug.Log(temp);
m_selectedCard.Init();
//Invoke("Pass", 2f);
Pass();
ArrangementCard();
m_cardCountText.text = m_myCard.Count.ToString() + "์ฅ";
//GameManager.Instance.m_bombBtn.gameObject.SetActive(CheckBomb());
if (CheckBomb())
{
GameManager.Instance.m_bombBtn.Active();
}
else
{
GameManager.Instance.m_bombBtn.Inactive();
}
}
else
{
//๋ชป ๋ด๋๋ฐ ๋๋ ธ๋ค?
//์ผ๋จ ์ ํํ๊ฑด ์์ ์ค์ผ ๋์ง ์์๊น?
//์ด๊ธฐํ ํ๋ฉด์ ๋ฒํผ๋ ๋ค์ ๋ด๋ฆฐ๋ค.
m_selectedCard.Init();
ArrangementCard();
//GameManager.Instance.m_drawBtn.SetActive(false);
GameManager.Instance.m_drawBtn.View();
//GameManager.Instance.m_passBtn.SetActive(true);
}
}
public void Pass()
{
//GameManager.Instance.Pass();
//if (!m_bIsMyTurn)
//{
// return;
//}
//m_bIsMyTurn = false;
if (CardDrawHandler.Instance.GetDrawCardType() == DRAWCARD_TYPE.NONE)
{
//์๋ ๊ฒฝ์ฐ๋ ๋ด๊ฐ ์ ์ด๋ค ์ ์ผ๋ ํจ์ค๋ฅผ ํ๋ฉด ์๋๋ค
//๊ทธ๋ฅ ๋ฆฌํดํ์
return;
}
if (m_rotateTurnImage.gameObject.activeSelf)
{
m_rotateTurnImage.gameObject.SetActive(false);
}
StartCoroutine(GameManager.Instance.Pass());
}
virtual public void MyTurn()
{
//if (CardDrawHandler.Instance.GetDrawCardType() == DRAWCARD_TYPE.NONE)
//{
// //NONE์ธ ๊ฒฝ์ฐ ์๋ฌด๊ฒ๋ ์ ๋์๋ค.
// //์ ์ถ์ ์์ฑํ๊ณ ๊ทธ๋ ์ด ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์.
// GameManager.Instance.SetActivePlayBtn(true);
// GameManager.Instance.m_drawBtn.Inactive();
//}
//else
//{
// GameManager.Instance.m_drawBtn.Active();
// GameManager.Instance.m_passBtn.Active();
//}
m_bIsMyTurn = true;
m_bDrawMajjong = false;
DrawCheck();
Debug.Log(this.name + "์ ํด\n");
StartCoroutine(AnimationClip());
}
public void CalcPoint()
{
int eatCardSize = m_eatCard.Count;
for (int i = 0; i < eatCardSize; ++i)
{
m_point += m_eatCard[i].point;
}
m_pointText.text = name + "\n" + m_point.ToString();
m_scoreBoardPointText.text = m_pointText.text;
}
public int CalcHandCardPoint()
{
int point = 0;
int size = m_myCard.Count;
for (int i = 0; i < size; ++i)
{
point += m_myCard[i].point;
}
return point;
}
public void GivePoint(int point)
{
m_point += point;
}
public int GetPoint()
{
return m_point;
}
public void SetPoint(int point)
{
m_point = point;
}
public int GetBonusPoint()
{
return m_bonusPoint;
}
public int GetCardCount()
{
return m_myCard.Count;
}
virtual public bool IsExchagne()
{
return m_bIsExchange;
}
public void CallTichu()
{
m_isCallTichu = true;
GameManager.Instance.TichuBtnEnabled(false);
m_tichu.gameObject.SetActive(true);
m_tichu.sprite = m_tichuIcon;
GameManager.Instance.CallTichuBtn();
}
virtual public IEnumerator CardExchange(float deltaTime = 0.5f)
{
float time = 0;
List<Vector3> exchangeCardPosList = new List<Vector3>();
Vector3[] endPosList = new Vector3[3];
endPosList[0] = m_leftPlayer.transform.position;
endPosList[1] = m_teamPlayer.transform.position;
endPosList[2] = m_rightPlayer.transform.position;
for (int i = 0; i < 3; ++i)
{
exchangeCardPosList.Add(m_exchagnedCard[i].transform.position);
}
while (time >= deltaTime)
{
for (int i = 0; i < 3; ++i)
{
Vector3 startPos = exchangeCardPosList[i];
//Vector3 startPos = m_exchagnedCard[i].transform.position;
Vector3 endPos = endPosList[i];
Vector3 moveVec = endPos - startPos;
m_exchagnedCard[i].transform.position = startPos + (moveVec * (time / deltaTime));
}
time += Time.deltaTime;
yield return null;
}
//๋ง์ง๋ง ๋์ฐฉ ์์น๊ฐ ์ผ์นํ๋๋ก ํด์ฃผ์.
for (int i = 0; i < 3; ++i)
{
Vector3 startPos = exchangeCardPosList[i];
Vector3 endPos = endPosList[i];
Vector3 moveVec = endPos - startPos;
m_exchagnedCard[i].transform.position = startPos + (moveVec * 1);
}
//๋ณด๋ด๊ณ ๋์ ์จ๊ฒจ์ผ ๋๋ค.
//๋ด๊ฐ ๋ณด๋ผ ์นด๋๋ค์ ๋ค ์จ๊ฒจ์ผ ๋๋ ์ ๋ถ hide
for (int i = 0; i < 3; ++i)
{
m_exchagnedCard[i].Hide();
}
CardData leftCard = m_leftPlayer.GetCardExchangeData(2);
CardData teamCard = m_teamPlayer.GetCardExchangeData(1);
CardData rightCard = m_rightPlayer.GetCardExchangeData(0);
//Debug.Log(this.name + "\n" +
// "left : " + leftCard.GetColor() + leftCard.valueStr +
// " team : " + teamCard.GetColor() + teamCard.valueStr +
// " right : " + rightCard.GetColor() + rightCard.valueStr);
//๋ค๋ฅธ ํ๋ ์ด์ด๋ค์๊ฒ ์นด๋๋ฅผ ๋ฐ๋๋ค.
m_myCard.Add(leftCard);
m_myCard.Add(teamCard);
m_myCard.Add(rightCard);
//๊ตํํ ์นด๋๊ฐ ๋๊ตฌ์นด๋์ธ์ง ์ค์
leftCard.SetOwnerPlayer(this);
teamCard.SetOwnerPlayer(this);
rightCard.SetOwnerPlayer(this);
}
public CardData GetCardExchangeData(int index)
{
return m_exchagnedCard[index];
}
public void ViewExchangeCard()
{
//๊ทธ๋ฅ ๋ด ์นด๋ ์ ๋ถ๋ค ๋ณด์ฌ์ฃผ๊ฒ ๋ง๋ค์.
for (int i = 0; i < m_myCard.Count; ++i)
{
m_myCard[i].Flip(false);
m_myCard[i].Hide(false);
}
}
virtual public void clearExchangeData()
{
for (int i = 0; i < 3; ++i)
{
m_myCard.Remove(m_exchagnedCard[i]);
}
m_exchagnedCard[0] = null;
m_exchagnedCard[1] = null;
m_exchagnedCard[2] = null;
ArrangementCard();
}
public IEnumerator SetEatCard(List<CardData> cardDrawList)
{
yield return StartCoroutine(CardDrawHandler.Instance.EatCardMove(this.transform.position));
int cardDrawListSize = cardDrawList.Count;
for (int i = 0; i < cardDrawListSize; ++i)
{
m_point += cardDrawList[i].point;
cardDrawList[i].gameObject.SetActive(false);
}
m_eatCard.AddRange(cardDrawList);
SetPoint();
}
private void SetPoint()
{
m_pointText.text = name + "\n" + m_point.ToString();
m_scoreBoardPointText.text = m_pointText.text;
if (m_point >= 0)
{
m_pointText.color = new Color(0, 0, 0);
m_scoreBoardPointText.color = new Color(0, 0, 0);
}
else
{
m_pointText.color = new Color(248 / 255.0f, 84 / 255.0f, 84 / 255.0f);
m_scoreBoardPointText.color = new Color(248 / 255.0f, 84 / 255.0f, 84 / 255.0f);
}
}
virtual public bool IsChooseLargeTichu()
{
return m_isChooseLargeTichu;
}
public void SetTichu(int isCall)
{
if (isCall == 2)
{
m_isCallLargeTichu = true;
m_isCallTichu = false;
////์ค๋ชฐ ํฐ์ธ ๋ฒํผ์ ์์ ์.
//GameManager.Instance.TichuBtnEnabled(false);
m_tichu.gameObject.SetActive(true);
m_tichu.sprite = m_grandTichuIcon;
}
else if (isCall == 1)
{
m_isCallTichu = true;
GameManager.Instance.TichuBtnEnabled(false);
m_tichu.gameObject.SetActive(true);
m_tichu.sprite = m_tichuIcon;
}
else
{
m_isCallLargeTichu = false;
}
}
public void SuccesFirst(bool isSucces)
{
//1๋ฑ์ผ๋ก ๋๋๋ฐ ์ฑ๊ณตํ๋ค.!
if (isSucces)
{
//๋ผ์ง ํฐ์ธ๋ฅผ ํ๋๊ฐ?
if (m_isCallLargeTichu)
{
//200์ ์ถ๊ฐ!
m_bonusPoint += 200;
}
else if(m_isCallTichu)
{
//ํฐ์ธ๋ฅผ ํ๋๊ฐ?
m_bonusPoint += 100;
}
}
else
{
//ํฐ์ธ๋ฅผ ํ๋๊ฐ?
if (m_isCallLargeTichu)
{
//200์ ๋ง์ด๋์ค
m_bonusPoint -= 200;
}
else if (m_isCallTichu)
{
//ํฐ์ธ๋ฅผ ํ๋๊ฐ?
m_bonusPoint -= 100;
}
}
}
//๋ผ์งํฐ์ธ๋ฅผ ๋ถ๋ ๋ค.
public void SelectYes()
{
m_isChooseLargeTichu = true;
m_isCallLargeTichu = true;
m_isCallTichu = false;
//์ค๋ชฐ ํฐ์ธ ๋ฒํผ์ ์์ ์.
GameManager.Instance.TichuBtnEnabled(false);
m_tichu.gameObject.SetActive(true);
m_tichu.sprite = m_grandTichuIcon;
GameManager.Instance.CallLargeTichuBtn(true);
}
//๋ผ์งํฐ์ธ๋ฅผ ์ํ๋ค.
public void SelectNo()
{
m_isChooseLargeTichu = true;
m_isCallLargeTichu = false;
GameManager.Instance.CallLargeTichuBtn(false);
}
virtual public IEnumerator ChooseEatDragon()
{
yield break;
}
virtual protected IEnumerator AnimationClip()
{
if (m_rotateTurnImage.gameObject.activeSelf)
{
yield break;
}
//์ ๋๋ฉ์ด์
ํด๋ฆฝ์ ํ์ฑํ ํ๊ณ
//์ข
๋ฃ ๋ ๋๊น์ง ๊ณ์ ํ์ ์ํจ๋ค.
m_rotateTurnImage.gameObject.SetActive(true);
while (m_rotateTurnImage.gameObject.activeSelf)
{
m_rotateTurnImage.transform.Rotate(Vector3.forward * Time.deltaTime * -300f);
yield return null;
}
}
public void CallWishCard(string wish)
{
m_wishCardImg.gameObject.SetActive(true);
m_wishText.text = wish;
}
public void ClearWish()
{
m_wishCardImg.gameObject.SetActive(false);
}
public bool HaveWishCard(string wishCardStr)
{
return m_myCard.Find(card => card.valueStr == wishCardStr);
}
public bool CheckBomb()
{
//๊ฐ์ ์ซ์ ํญํ๊ณผ
//์ฐ์๋ ์ซ์์ด๋ฉด์ ์๊น์ด ๋๊ฐ์ ํญํ์ด ์๋์ง ํ์ธ
for (int i = 0; i < m_myCard.Count - 1; ++i)
{
m_bombCard.Clear();
m_bombCard.Add(m_myCard[i]);
for (int j = i + 1; j < m_myCard.Count; ++j)
{
if (m_myCard[i].value == m_myCard[j].value)
{
m_bombCard.Add(m_myCard[j]);
if (m_bombCard.Count >= 4)
{
return true;
}
}
else
{
break;
}
}
}
//๊ฐ์ ์ซ์ ํญํ์ด ์๋ค?
//์คํธ๋ ์ดํธ ํญํ์ ์ฐพ์๋ณด์.
for (int i = 0; i < m_myCard.Count - 5; ++i)
{
m_strightBomCard.Clear();
m_strightBomCard.Add(m_myCard[i]);
CardData start = m_myCard[i];
for (int j = i + 1; j < m_myCard.Count; ++j)
{
if (start.value + m_strightBomCard.Count - 1 == m_myCard[j].value)
{
continue;
}
if (start.value + m_strightBomCard.Count == m_myCard[j].value)
{
if (start.color == m_myCard[j].color)
{
m_strightBomCard.Add(m_myCard[j]);
if (m_strightBomCard.Count >= 5)
{
return true;
}
}
}
else
{
break;
//if (start.value + m_strightBomCard.Count < m_myCard[i].value)
//{
// break;
//}
}
}
}
return false;
}
public bool IsPossibleDraw()
{
return false;
}
public bool IsDrawWishCard()
{
//์์ ์นด๋๋ฅผ ๋ผ ์ ์๋์ง ์๋์ง ํ์ธํ์
DRAWCARD_TYPE eCardType = CardDrawHandler.Instance.GetDrawCardType();
float topValue = CardDrawHandler.Instance.GetTopValue();
float wishCardValue = GameManager.Instance.m_wishCardPopup.GetWishCardValue();
string wishStr = GameManager.Instance.m_wishCardPopup.GetWishCard();
int cardCount = CardDrawHandler.Instance.GetCardCount();
if (topValue < wishCardValue)
{
//๋ด๊ฐ ๋ค๊ณ ๋ง ์์ผ๋ฉด ๋ฌด์กฐ๊ฑด ๋ด์ผ ๋๋ ๊ฒฝ์ฐ
//์์, ์ฑ๊ธ, ํ์ด, ํธ๋ฆฌํ
switch (eCardType)
{
case DRAWCARD_TYPE.NONE:
case DRAWCARD_TYPE.SINGLE:
{
if (HaveWishCard(wishStr))
{
return true;
}
return false;
}
case DRAWCARD_TYPE.PAIR:
{
int wishCardCount = 0;
//wish๋ ๊ฐ์ ์นด๋๊ฐ 2์ฅ ์ด์์ด๋ค ๊ทธ๋ผ ๋ผ์ ์๋ค.
for (int i = 0; i < m_myCard.Count; ++i)
{
if (m_myCard[i].valueStr == wishStr)
{
++wishCardCount;
if (wishCardCount >= 2)
{
return true;
}
}
}
return false;
}
case DRAWCARD_TYPE.TRIPPLE:
{
int wishCardCount = 0;
//wish๋ ๊ฐ์ ์นด๋๊ฐ 3์ฅ ์ด์์ด๋ค ๊ทธ๋ผ ๋ผ์ ์๋ค.
for (int i = 0; i < m_myCard.Count; ++i)
{
if (m_myCard[i].valueStr == wishStr)
{
++wishCardCount;
if (wishCardCount >= 2)
{
return true;
}
}
}
return false;
}
}
}
//์์๋ top์ด๋ ์๊ด์์ด ์กฐํฉ์ ๋น๊ตํด์ผ ๋๋ ๊ฒฝ์ฐ
//์ฐ์ ํ์ด, ์คํธ๋ ์ดํธ, ํํ์ฐ์ค,
switch (eCardType)
{
case DRAWCARD_TYPE.FULLHOUSE:
{
//์์ ์นด๋๋ก ํธ๋ฆฌํ์ด๋ ํ์ด๊ฐ ์๋์ง ํ์ธํ๊ณ
//ํธ๋ฆฌํ์ด top๋ณด๋ค ๋์์ง ํ์ธ์ ํด์ผ ๋๋ค.
if (topValue > wishCardValue)
{
//ํ์ด ์์๋ณด๋ค ๋์ ๊ฒฝ์ฐ
//์์๋ ํธ๋ฆฌํ์ด ์๋๊ณ ํ์ด๋ก ๋ค๊ณ ์์ด์ผ ๋๋ฉฐ
//ํธ๋ฆฌํ์ด ํ๋ณด๋ค ๋์์ผ ๋๋ค.
int wishCardCount = 0;
for (int i = 0; i < m_myCard.Count; ++i)
{
if (m_myCard[i].valueStr == wishStr)
{
++wishCardCount;
if (wishCardCount >= 2)
{
break;
}
}
}
if (wishCardCount < 2)
{
return false;
}
else
{
//ํธ๋ฆฌํ์ ์ฐพ์๋ณด์ ํธ๋ฆฌํ์ ์ฐพ์๋ top๋ฒจ๋ฅ๋ณด๋ค ์ปค์ผ ๋๋ค.
for (int i = 0; i < m_myCard.Count - 2; ++i)
{
if (m_myCard[i].value == m_myCard[i + 1].value
&& m_myCard[i + 1].value == m_myCard[i + 2].value)
{
if (topValue < m_myCard[i].value)
{
return true;
}
}
}
return false;
}
}
else
{
//์์๋ก ํธ๋ฆฌํ์ด๋ ํ์ด๊ฐ ์๋์ง ํ์ธํ๋ค.
int wishCardCount = 0;
for (int i = 0; i < m_myCard.Count; ++i)
{
if (m_myCard[i].valueStr == wishStr)
{
++wishCardCount;
if (wishCardCount >= 3)
{
break;
}
}
}
if (wishCardCount == 3)
{
//์์์นด๋๋ก ํธ๋ฆฌํ์ด ์๋ค. ํ์ด๊ฐ ์๋์ง ์ฐพ์
for (int i = 0; i < m_myCard.Count - 1; ++i)
{
if (m_myCard[i].value == m_myCard[i + 1].value)
{
if (m_myCard[i].valueStr != wishStr)
{
return true;
}
}
}
}
else if (wishCardCount == 2)
{
//์์๋ก ํ์ด๊ฐ ์๋ค. ํธ๋ฆฌํ์ด ์๋์ง ์ฐพ์๋ณด์.
//ํธ๋ฆฌํ์ ์ฐพ์๋ณด์ ํธ๋ฆฌํ์ ์ฐพ์๋ top๋ฒจ๋ฅ๋ณด๋ค ์ปค์ผ ๋๋ค.
for (int i = 0; i < m_myCard.Count - 2; ++i)
{
if (m_myCard[i].value == m_myCard[i + 1].value
&& m_myCard[i + 1].value == m_myCard[i + 2].value)
{
if (topValue < m_myCard[i].value)
{
return true;
}
}
}
}
return false;
}
}
case DRAWCARD_TYPE.STRIGHT:
{
int straightCount = 0;
List<int> idxList = new List<int>();
//์คํธ๋ ์ดํธ๋ฅผ ์ฐพ์๋ณด์.
for (int i = 0; i < m_myCard.Count - cardCount; ++i)
{
straightCount = 1;
idxList.Clear();
idxList.Add(i);
for (int j = i + 1; j < m_myCard.Count; ++j)
{
if (m_myCard[i].value + straightCount - 1 == m_myCard[j].value)
{
continue;
}
if (m_myCard[i].value + straightCount == m_myCard[j].value)
{
++straightCount;
if (straightCount == cardCount)
{
bool wishOk = false;
//์คํธ๋ ์ดํธ๋ฅผ ์ฐพ์๋๋ฐ ์์๊ฐ ์๋์ง ๋ณด์.
for (int k = 0; k < idxList.Count; ++k)
{
//์์๊ฐ ์๋ ์คํธ๋ ์ดํธ๋ค
if (m_myCard[idxList[k]].valueStr == wishStr)
{
wishOk = true;
}
}
//top๋ณด๋ค ํฌ๋ฉด ๋ผ์ ์๋ค.
if (wishOk && m_myCard[j].value > topValue)
{
return true;
}
}
}
}
}
//๋ณผ์งฑ ๋ค ๋ดค๋๋ฐ๋ ๋ฆฌํด์ด ์๋๊ฒฝ์ฐ๋ฉด ์๋ค๊ณ ํ๋จ
return false;
}
case DRAWCARD_TYPE.PAIRS:
{
//์ด๊ฑด ๋ฒ๊ทธ ํด๊ฒฐ๋๋ฉด ์ฐพ์๋ณด์.
return true;
}
}
return false;
}
virtual public IEnumerator DivisionCardMove(Vector3 startPosition, bool isFirst, float deltaTime = 0.5f)
{
float time = 0;
int size = m_myCard.Count;
List<Vector3> startPosList = new List<Vector3>();
for (int i = 0; i < size; ++i)
{
startPosList.Add(m_myCard[i].transform.position);
}
int offset = -(size / 2);
while (time <= deltaTime)
{
offset = -(size / 2);
for (int i = 0; i < size; ++i)
{
Vector3 endPos = transform.position + (transform.right * (offset * 110));
Vector3 moveVec = endPos - startPosList[i];
m_myCard[i].transform.position = startPosList[i] + (moveVec * (time / deltaTime));
++offset;
}
time += Time.deltaTime;
yield return null;
}
offset = -(size / 2);
for (int i = 0; i < size; ++i)
{
Vector3 endPos = transform.position + (transform.right * (offset * 110));
Vector3 moveVec = endPos - startPosList[i];
m_myCard[i].transform.position = startPosList[i] + (moveVec * 1);
++offset;
}
for (int i = 0; i < size; ++i)
{
m_myCard[i].Flip(false);
}
}
}
|
๏ปฟusing UnityEngine;
using System.Collections;
using AssemblyCSharp;
/**
* I want this class to be one of, if not the only class, with an Update() method in it. Those methods are expensive, and I want to limit them whenever possible.
* */
public class Cursor : MonoBehaviour {
public static Cursor instance;
private Vector2 _coords;
public Vector2 coords
{
get
{
return _coords;
} set {
_coords = value;
StartCoroutine( MovedTime() );
}
}
private bool moved;
LayerMask onMap;
int mask;
private void Awake()
{
if ( instance == null )
instance = this;
moved = true;
onMap = LayerMask.NameToLayer( "OnMap" );
onMap = ~onMap;
mask = 1 << 8;
}
private void Update()
{
// Debug.Log(moved);
if ( moved )
{
// Left
if ( Input.GetKey( Globals.Controls.cursorLeftMain ) || Input.GetKey( Globals.Controls.cursorLeftSecondary ) )
{
/**
* We need to make a new Vector2 that involves subtracting one from x
*
* And then check if that is in the dictionary, and if so, update the position of cursor
* */
UpdatePosition( Globals.WEST );
}
// Right
else if ( Input.GetKey( Globals.Controls.cursorRightMain ) || Input.GetKey( Globals.Controls.cursorRightSecondary ) )
{
UpdatePosition( Globals.EAST );
}
// Up
else if ( Input.GetKey( Globals.Controls.cursorUpMain ) || Input.GetKey( Globals.Controls.cursorUpSecondary ) )
{
UpdatePosition( Globals.NORTH );
}
// Down
else if ( Input.GetKey( Globals.Controls.cursorDownMain ) || Input.GetKey( Globals.Controls.cursorDownSecondary ) )
{
UpdatePosition( Globals.SOUTH );
}
// Affirmative
else if ( Input.GetKeyDown( Globals.Controls.cursorAffirmativeMain ) || Input.GetKeyDown( Globals.Controls.cursorAffirmativeSecondary ) )
{
// Debug.Log("Click");
AnalyzeUnderCursor();
}
}
}
/**
* As the cursor is always going to be following the mouse, it's necessary to use a Physics2D raycaster to determine what you're clicking on
* */
private void OnMouseDown()
{
AnalyzeUnderCursor();
}
private void AnalyzeUnderCursor()
{
// TODO: I set this to Vector2.zero to fix a bug, I don't know if it will have unintended consequences with my raycasting in the future
RaycastHit2D[] hit = Physics2D.RaycastAll( this.transform.position, Vector2.zero, 2f, mask );
if ( hit.Length == 0 )
return;
if ( hit[0].collider != null )
{
// print(hit[1].collider.gameObject.name);
AnalyzeRayClass( hit[0].collider.gameObject );
}
}
/**
* This method analyzes the result of a RaycastHit2D collider's gameobject
*
* And then it determines whether or not that particular object would implement the IClickable interface, and then calls it
* */
private void AnalyzeRayClass( GameObject hitObject )
{
// this method takes in the string of the object hit, determining if gameobject has an IClickable method attached to it
string tag = hitObject.tag;
// I need to adjust the name to be a valid switch state expression. Meaning I need to analyze it, and take off the (clone) bit
// tag = RemoveClone( tag );
switch( tag )
{
case "Player":
Player playerScript = hitObject.GetComponent<Player>();
if ( !playerScript.moveGridSpawned )
playerScript.OnMouseClick();
else
return;
break;
// TODO: Make something happen when you click enemies
case "Enemy":
break;
case "MoveTile":
MovementGrid moveScript = hitObject.GetComponent<MovementGrid>();
moveScript.OnMouseClick();
break;
default:
Debug.Log("AnalyzeRayClass was given an object that did not implement the IClickable interface.");
Debug.Log("It was given: " + tag);
break;
}
}
/**
* A simple helper method for removing the "(Clone)" from a strings name
* */
private string RemoveClone( string name )
{
int index = name.IndexOf( "(" );
return name.Remove(index);
}
/**
* Returns true if there is a valid Tile to move in that direction
*
* Returns false if there not
* */
private bool CheckMovement( Vector2 direction, out Vector2 checkVector )
{
checkVector = new Vector2( this.coords.x + direction.x, this.coords.y + direction.y );
// If a movement grid is spawned, check to see if there's a movement grid at that position
if ( Globals.moveGridSpawned )
{
if ( Globals.moveGridList.ContainsKey( checkVector ) )
return true;
else
return false;
} else { // Otherwise just check for a regular tile at that position
if ( Globals.tileList.ContainsKey( checkVector ) )
return true;
else
return false;
}
}
private void UpdatePosition( Vector2 direction )
{
Vector2 checkVector;
if ( CheckMovement( direction, out checkVector ) )
{
// Update cursor position
this.gameObject.transform.position = Globals.tileList[ checkVector ].transform.position;
this.coords = checkVector;
}
}
private IEnumerator MovedTime()
{
moved = false;
yield return new WaitForSeconds(0.075f);
moved = true;
}
}
|
๏ปฟusing RestauranteOnline.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RestauranteOnline.Controllers
{
public class AutenticaUsuarioController : Controller
{
public JsonResult AutenticacaoUsuario(string Login, string Senha)
{
if (RepositorioUsuarios.AutenticarUsuario(Login, Senha))
{
return Json(new { OK = true, Mensagem = "Usuario encontrado Redirecionando..." },
JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { OK = false, Mensagem = "Usuario nรฃo encontrado" },
JsonRequestBehavior.AllowGet);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.