text stringlengths 13 6.01M |
|---|
namespace Webstore
{
using System.Data.Entity;
using Infrastructure.Models;
public class WebModel : DbContext
{
/*
The target context 'Webstore.WebModel' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
*/
public WebModel() : base("name=DefaultConnection") // would generate Webstore.WebModel db unless given overload
{ }
public virtual DbSet<ContentTypeToExtn> ContentTypeToExtns { get; set; }
//public virtual DbSet<Host> Hosts { get; set; }
public virtual DbSet<WebPage> WebPages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new CreateDatabaseIfNotExists<WebModel>()); // default
modelBuilder.Entity<ContentTypeToExtn>()
.Property(e => e.Template)
.IsUnicode(unicode: false);
modelBuilder.Entity<ContentTypeToExtn>()
.Property(e => e.Extn)
.IsUnicode(unicode: false);
modelBuilder.Entity<WebPage>()
.HasMany(e => e.ConsumeFrom)
.WithMany(e => e.SupplyTo)
.Map(m => m.ToTable("Depends").MapLeftKey("ChildId").MapRightKey("ParentId"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace BagBag.Models
{
public class Encrypt
{
public static string MD5_Encode(string strSoure)
{
MD5 md5 = MD5.Create();
byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(strSoure));
//Create Obj builder
StringBuilder strBuilder = new StringBuilder();
//check database
for (int i = 0; i < data.Length; i++)
{
//exchange byte to hex
strBuilder.Append(data[i].ToString("x2"));
}
return strBuilder.ToString();
}
public static bool MD5_Verify(string strSoure, string hashSoure)
{
string hashTemp = MD5_Encode(strSoure);
//compare
if (String.Compare(hashTemp, hashSoure, true) == 0)
{
return true;
}
else
{
return false;
}
}
internal static void MD5_Encode()
{
throw new NotImplementedException();
}
}
} |
using System.Threading.Tasks;
namespace Mitheti.Core.Services
{
// TODO: add servicing service, with this and other (optimizing and clear records) services on tasks;
public interface ISizeLimitDatabaseService
{
Task LimitDatabase();
long GetSize();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace LibEqmtDriver.SCU
{
public class AeWofer : IISwitch
{
int _mRetVal, _session, _hSys;
string _apiName = "";
public AeWofer(int sysId)
{
Createsession(null);
AMB1340C_CREATEINSTANCE(sysId, 0);
}
#region iSwitch Members
void IISwitch.Initialize()
{
try
{
_apiName = "INITIALIZE"; RetVal = AMb1340C.INITIALIZE(_hSys);
AMB1340C_SETPORTDIRECTION(65535);
}
catch (Exception ex)
{
throw new Exception("AeWofer: Initialize -> " + ex.Message);
}
}
void IISwitch.SetPath(string val)
{
string[] tempdata;
tempdata = val.Split(';');
//string val0 = tempdata[0];
//string val1 = tempdata[1];
try
{
for (int i = 0; i < tempdata.Length; i++)
{
//AMB1340C_DRIVETHISPORT(0, Convert.ToInt32(val0));
//AMB1340C_DRIVETHISPORT(1, Convert.ToInt32(val1));
AMB1340C_DRIVETHISPORT(i, Convert.ToInt32(tempdata[i]));
}
}
catch (Exception ex)
{
throw new Exception("AeWofer: SetPath -> " + ex.Message);
}
}
void IISwitch.Reset()
{
try
{
Resetboards();
}
catch (Exception ex)
{
throw new Exception("AeWofer: Reset -> " + ex.Message);
}
}
#endregion
private void Resetboards()
{
_apiName = "RESETBOARDS"; RetVal = AMb1340C.RESETBOARDS();
}
private void Createsession(string hostname)
{
_apiName = "CREATESESSION"; RetVal = AMb1340C.CREATESESSION(hostname, out _session);
}
private void Closesession()
{
_apiName = "CLOSESESSION"; RetVal = AMb1340C.CLOSESESSION(_session);
}
private void AMB1340C_CREATEINSTANCE(int sysId, int offlinemode)
{
_apiName = "AMB1340C_CREATEINSTANCE"; RetVal = AMb1340C.AMB1340C_CREATEINSTANCE(_session, sysId, offlinemode, out _hSys);
}
private void AMB1340C_DELETEINSTANCE()
{
_apiName = "AMB1340C_DELETEINSTANCE"; RetVal = AMb1340C.AMB1340C_DELETEINSTANCE(_hSys);
}
private void AMB1340C_DRIVEPORT(int value)
{
_apiName = "AMB1340C_DRIVEPORT"; RetVal = AMb1340C.DRIVEPORT(_hSys, value);
}
private void AMB1340C_DRIVETHISPORT(int port, int value)
{
_apiName = "AMB1340C_DRIVETHISPORT"; RetVal = AMb1340C.DRIVETHISPORT(_hSys, port, value);
}
private void AMB1340C_DRIVEPIN(int pin, int value)
{
_apiName = "AMB1340C_DRIVEPIN"; RetVal = AMb1340C.DRIVEPIN(_hSys, pin, value);
}
private void AMB1340C_READPORT(out int value)
{
_apiName = "AMB1340C_READPORT"; RetVal = AMb1340C.READPORT(_hSys, out value);
}
private void AMB1340C_READPIN(int pin, out int value)
{
_apiName = "AMB1340C_READPIN"; RetVal = AMb1340C.READPIN(_hSys, pin, out value);
}
private void AMB1340C_SETPORTDIRECTION(int value)
{
_apiName = "AMB1340C_SETPORTDIRECTION"; RetVal = AMb1340C.SETPORTDIRECTION(_hSys, value);
}
private void AMB1340C_SETPINDIRECTION(int pin, int value)
{
_apiName = "AMB1340C_SETPINDIRECTION"; RetVal = AMb1340C.SETPINDIRECTION(_hSys, pin, value);
}
private void AMB1340C_GETPORTDIRECTION(out int value)
{
_apiName = "AMB1340C_GETPORTDIRECTION"; RetVal = AMb1340C.GETPORTDIRECTION(_hSys, out value);
}
private void AMB1340C_GETPINDIRECTION(int pin, out int value)
{
_apiName = "AMB1340C_GETPINDIRECTION"; RetVal = AMb1340C.GETPINDIRECTION(_hSys, pin, out value);
}
private void Drivevoltage(int chset, int mVvalue, int sign)
{
_apiName = "DRIVEVOLTAGE"; RetVal = AMb1340C.DRIVEVOLTAGE(_hSys, chset, mVvalue, sign);
}
private void Drivecurrent(int chset, int nAvalue, int sign)
{
_apiName = "DRIVECURRENT"; RetVal = AMb1340C.DRIVECURRENT(_hSys, chset, nAvalue, sign);
}
private void Clampvoltage(int chset, int mVvalue)
{
_apiName = "CLAMPVOLTAGE"; RetVal = AMb1340C.CLAMPVOLTAGE(_hSys, chset, mVvalue);
}
private void Clampcurrent(int chset, int nAvalue)
{
_apiName = "CLAMPCURRENT"; RetVal = AMb1340C.CLAMPCURRENT(_hSys, chset, nAvalue);
}
private void Readvoltage(int chset, out int mVvalue)
{
_apiName = "READVOLTAGE"; RetVal = AMb1340C.READVOLTAGE(_hSys, chset, out mVvalue);
}
private void Readcurrent(int chset, out int nAvalue)
{
_apiName = "READCURRENT"; RetVal = AMb1340C.READCURRENT(_hSys, chset, out nAvalue);
}
private void Readcurrentrate(int chset, out int nAvalue)
{
_apiName = "READCURRENTRATE"; RetVal = AMb1340C.READCURRENTRATE(_hSys, chset, out nAvalue);
}
private void Readvoltagevolt(int chset, out float volt)
{
_apiName = "READVOLTAGEVOLT"; RetVal = AMb1340C.READVOLTAGEVOLT(_hSys, chset, out volt);
}
private void Readcurrentamp(int chset, out float ampere)
{
_apiName = "READCURRENTAMP"; RetVal = AMb1340C.READCURRENTAMP(_hSys, chset, out ampere);
}
private void Readcurrentamprate(int chset, out float ampere)
{
_apiName = "READCURRENTAMPRATE"; RetVal = AMb1340C.READCURRENTAMPRATE(_hSys, chset, out ampere);
}
private void Readvoltagewithaverage(int chset, int average, out int average_MV, out int every_MV)
{
_apiName = "READVOLTAGEWITHAVERAGE"; RetVal = AMb1340C.READVOLTAGEWITHAVERAGE(_hSys, chset, average, out average_MV, out every_MV);
}
private void Readcurrentwithaverage(int chset, int average, out int average_NA, out int every_NA)
{
_apiName = "READCURRENTWITHAVERAGE"; RetVal = AMb1340C.READCURRENTWITHAVERAGE(_hSys, chset, average, out average_NA, out every_NA);
}
private void Readcurrentautorange(int chset, out int nAvalue)
{
_apiName = "READCURRENTAUTORANGE"; RetVal = AMb1340C.READCURRENTAUTORANGE(_hSys, chset, out nAvalue);
}
private void Readcurrentfromrange(int chset, out int nAvalue)
{
_apiName = "READCURRENTFROMRANGE"; RetVal = AMb1340C.READCURRENTFROMRANGE(_hSys, chset, out nAvalue);
}
private void Onsmupin(int pin)
{
_apiName = "ONSMUPIN"; RetVal = AMb1340C.ONSMUPIN(_hSys, pin);
}
private void Offsmupin(int pin)
{
_apiName = "OFFSMUPIN"; RetVal = AMb1340C.OFFSMUPIN(_hSys, pin);
}
private void Setanapinbandwidth(int pin, int setting)
{
_apiName = "SETANAPINBANDWIDTH"; RetVal = AMb1340C.SETANAPINBANDWIDTH(_hSys, pin, setting);
}
private void Setintegration(int chdat)
{
_apiName = "SETINTEGRATION"; RetVal = AMb1340C.SETINTEGRATION(_hSys, chdat);
}
private void Setintegrationpowercycles(int setting, int powerCycles)
{
_apiName = "SETINTEGRATIONPOWERCYCLES"; RetVal = AMb1340C.SETINTEGRATIONPOWERCYCLES(_hSys, setting, powerCycles);
}
private void Biassmupin(int chset, out int chdat)
{
_apiName = "BIASSMUPIN"; RetVal = AMb1340C.BIASSMUPIN(_hSys, chset, out chdat);
}
private void Readsmupin(int chset, out int chdat, out int chRead)
{
_apiName = "READSMUPIN"; RetVal = AMb1340C.READSMUPIN(_hSys, chset, out chdat, out chRead);
}
//Modified by ChoonChin for IccCal
private int READSMUPIN_int(int chset, out int chdat, out int chRead)
{
_apiName = "READSMUPIN"; int a = AMb1340C.READSMUPIN(_hSys, chset, out chdat, out chRead);
return a;
}
private void Readsmupinrate(int chset, out int chdat, out int chRead)
{
_apiName = "READSMUPINRATE"; RetVal = AMb1340C.READSMUPINRATE(_hSys, chset, out chdat, out chRead);
}
private void Onoffsmupin(int chset, out int chdat)
{
_apiName = "ONOFFSMUPIN"; RetVal = AMb1340C.ONOFFSMUPIN(_hSys, chset, out chdat);
}
private void Armreadsmupin(int measset, out int chdat)
{
_apiName = "ARMREADSMUPIN"; RetVal = AMb1340C.ARMREADSMUPIN(_hSys, measset, out chdat);
}
private void Retrievereadsmupin(int measset, out int chdat, out int chRead)
{
_apiName = "RETRIEVEREADSMUPIN"; RetVal = AMb1340C.RETRIEVEREADSMUPIN(_hSys, measset, out chdat, out chRead);
}
private void Sourcedelaymeasuresmupin(int chset, out int chdat, out int chRead, int sequence)
{
_apiName = "SOURCEDELAYMEASURESMUPIN";
RetVal = AMb1340C.SOURCEDELAYMEASURESMUPIN(_hSys, chset, out chdat, out chRead, sequence);
}
private void AMB1340C_SOURCEDELAYMEASURESMUPIN(int pinset, out float pindat, out int measset, out float pinRead, int sequence)
{
_apiName = "AMB1340C_SOURCEDELAYMEASURESMUPIN";
RetVal = AMb1340C.AMB1340C_SOURCEDELAYMEASURESMUPIN(_hSys, pinset, out pindat, out measset, out pinRead, sequence);
}
private void AM330_DRIVEPULSEVOLTAGE(int pin, float _base, float pulse, float pulseS, float holdS,
int drVrange, int cycles, int measCh, int measSel, int measVrange, int trigPercentage,
int armExtTriginH, float timeoutS)
{
_apiName = "AM330_DRIVEPULSEVOLTAGE"; RetVal = AMb1340C.AM330_DRIVEPULSEVOLTAGE(_hSys, pin, _base, pulse, pulseS, holdS, drVrange, cycles, measCh, measSel, measVrange, trigPercentage, armExtTriginH, timeoutS);
}
private void AM371_DRIVEVOLTAGE(int pin, float volt)
{
_apiName = "AM371_DRIVEVOLTAGE"; RetVal = AMb1340C.AM371_DRIVEVOLTAGE(_hSys, pin, volt);
}
private void AM371_DRIVECURRENT(int pin, float ampere)
{
_apiName = "AM371_DRIVECURRENT"; RetVal = AMb1340C.AM371_DRIVECURRENT(_hSys, pin, ampere);
}
private void AM371_DRIVEVOLTAGESETVRANGE(int pin, float volt, int vrange)
{
_apiName = "AM371_DRIVEVOLTAGESETVRANGE"; RetVal = AMb1340C.AM371_DRIVEVOLTAGESETVRANGE(_hSys, pin, volt, vrange);
}
private void AM371_DRIVECURRENTSETIRANGE(int pin, float ampere, int irange)
{
_apiName = "AM371_DRIVECURRENTSETIRANGE"; RetVal = AMb1340C.AM371_DRIVECURRENTSETIRANGE(_hSys, pin, ampere, irange);
}
private void AM371_CLAMPVOLTAGE(int pin, float volt)
{
_apiName = "AM371_CLAMPVOLTAGE"; RetVal = AMb1340C.AM371_CLAMPVOLTAGE(_hSys, pin, volt);
}
private void AM371_CLAMPCURRENT(int pin, float ampere)
{
_apiName = "AM371_CLAMPCURRENT"; RetVal = AMb1340C.AM371_CLAMPCURRENT(_hSys, pin, ampere);
}
private void AM371_CLAMPVOLTAGESETVRANGE(int pin, float volt, int vrange)
{
_apiName = "AM371_CLAMPVOLTAGESETVRANGE"; RetVal = AMb1340C.AM371_CLAMPVOLTAGESETVRANGE(_hSys, pin, volt, vrange);
}
private void AM371_CLAMPCURRENTSETIRANGE(int pin, float ampere, int irange)
{
_apiName = "AM371_CLAMPCURRENTSETIRANGE"; RetVal = AMb1340C.AM371_CLAMPCURRENTSETIRANGE(_hSys, pin, ampere, irange);
}
private void AM371_READVOLTAGE(int pin, out float volt)
{
_apiName = "AM371_READVOLTAGE"; RetVal = AMb1340C.AM371_READVOLTAGE(_hSys, pin, out volt);
}
private void AM371_READVOLTAGEGETVRANGE(int pin, out float volt, out int vrange)
{
_apiName = "AM371_READVOLTAGEGETVRANGE"; RetVal = AMb1340C.AM371_READVOLTAGEGETVRANGE(_hSys, pin, out volt, out vrange);
}
private void AM371_READCURRENT(int pin, out float ampere)
{
_apiName = "AM371_READCURRENT"; RetVal = AMb1340C.AM371_READCURRENT(_hSys, pin, out ampere);
}
private void AM371_READCURRENTRATE(int pin, out float ampere)
{
_apiName = "AM371_READCURRENTRATE"; RetVal = AMb1340C.AM371_READCURRENTRATE(_hSys, pin, out ampere);
}
private void AM371_READCURRENTGETIRANGE(int pin, out float ampere, out int irange)
{
_apiName = "AM371_READCURRENTGETIRANGE"; RetVal = AMb1340C.AM371_READCURRENTGETIRANGE(_hSys, pin, out ampere, out irange);
}
private void AM371_ONSMUPIN(int pin, int remoteSenseH)
{
_apiName = "AM371_ONSMUPIN"; RetVal = AMb1340C.AM371_ONSMUPIN(_hSys, pin, remoteSenseH);
}
private void AM371_OFFSMUPIN(int pin)
{
_apiName = "AM371_OFFSMUPIN"; RetVal = AMb1340C.AM371_OFFSMUPIN(_hSys, pin);
}
private int AM371_EXTTRIGARM_READCURRENTARRAY(int pin, int posedgeH, float delayS, int nsample, float sampleDelayS)
{
_apiName = "AM371_EXTTRIGARM_READCURRENTARRAY";
return AMb1340C.AM371_EXTTRIGARM_READCURRENTARRAY(_hSys, pin, posedgeH, delayS, nsample, sampleDelayS);
}
private int AM371_EXTTRIGGET_READCURRENTARRAY_WITH_MINMAX(int pin, out int nsample, float[] iarray, out float min, out float max, out float average)
{
_apiName = "AM371_EXTTRIGGET_READCURRENTARRAY_WITH_MINMAX";
return AMb1340C.AM371_EXTTRIGGET_READCURRENTARRAY_WITH_MINMAX(_hSys, pin, out nsample, iarray, out min, out max, out average);
}
private void AM371_EXTTRIGARM_RELEASE(int pin)
{
_apiName = "AM371_EXTTRIGARM_RELEASE"; RetVal = AMb1340C.AM371_EXTTRIGARM_RELEASE(_hSys, pin);
}
private void AM371_USERBWSEL(int pin, int drvCoarseBw, int drvBoostEn, int clmpCoarseBw, int clmpBoostEn)
{
_apiName = "AM371_USERBWSEL"; RetVal = AMb1340C.AM371_USERBWSEL(_hSys, pin, drvCoarseBw, drvBoostEn, clmpCoarseBw, clmpBoostEn);
}
private void AM371_READCURRENT10X(int pin, out float avalue)
{
_apiName = "AM371_READCURRENT10X"; RetVal = AMb1340C.AM371_READCURRENT10X(_hSys, pin, out avalue);
}
private void AM371_READCURRENT10XRATE(int pin, out float avalue)
{
_apiName = "AM371_READCURRENT10XRATE"; RetVal = AMb1340C.AM371_READCURRENT10XRATE(_hSys, pin, out avalue);
}
private void AM330_EXTTRIGARM_READSMUPIN(int measset, out int chdat, int trigMode, float delayAfterTrigS)
{
_apiName = "AM330_EXTTRIGARM_READSMUPIN"; RetVal = AMb1340C.AM330_EXTTRIGARM_READSMUPIN(_hSys, measset, out chdat, trigMode, delayAfterTrigS);
}
private int AM330_EXTTRIGARM_RETRIEVEREADSMUPIN(int measset, out int chdat, out int chRead)
{
_apiName = "AM330_EXTTRIGARM_RETRIEVEREADSMUPIN";
return AMb1340C.AM330_EXTTRIGARM_RETRIEVEREADSMUPIN(_hSys, measset, out chdat, out chRead);
}
private void AM330_EXTTRIGARM_GETSTATUS(out int armedH, out int triggeredH, out int timeoutH)
{
_apiName = "AM330_EXTTRIGARM_GETSTATUS"; RetVal = AMb1340C.AM330_EXTTRIGARM_GETSTATUS(_hSys, out armedH, out triggeredH, out timeoutH);
}
private void AM330_EXTTRIGARM_RELEASE()
{
_apiName = "AM330_EXTTRIGARM_RELEASE"; RetVal = AMb1340C.AM330_EXTTRIGARM_RELEASE(_hSys);
}
private void AM330_EXTTRIGARM_SETTIMEOUTLIMIT(float timeoutS)
{
_apiName = "AM330_EXTTRIGARM_SETTIMEOUTLIMIT"; RetVal = AMb1340C.AM330_EXTTRIGARM_SETTIMEOUTLIMIT(_hSys, timeoutS);
}
private int RetVal
{
set
{
try
{
_mRetVal = value;
if (_mRetVal != 0)
throw new Exception("AM1340c " + _apiName + " Error: " + String.Format("{0:x8}", _mRetVal).ToUpper());
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
}
}
}
abstract class AMb1340C
{
[DllImport("AMB1340C.dll", EntryPoint = "AM330_EXTTRIGARM_READSMUPIN")]
public static extern int AM330_EXTTRIGARM_READSMUPIN(int hSys, int measset, out int chdat, int trigMode, float delayAfterTrigS);
[DllImport("AMB1340C.dll", EntryPoint = "AM330_EXTTRIGARM_RETRIEVEREADSMUPIN")]
public static extern int AM330_EXTTRIGARM_RETRIEVEREADSMUPIN(int hSys, int measset, out int chdat, out int chRead);
[DllImport("AMB1340C.dll", EntryPoint = "AM330_EXTTRIGARM_GETSTATUS")]
public static extern int AM330_EXTTRIGARM_GETSTATUS(int hSys, out int armedH, out int triggeredH, out int timeoutH);
[DllImport("AMB1340C.dll", EntryPoint = "AM330_EXTTRIGARM_RELEASE")]
public static extern int AM330_EXTTRIGARM_RELEASE(int hSys);
[DllImport("AMB1340C.dll", EntryPoint = "AM330_EXTTRIGARM_SETTIMEOUTLIMIT")]
public static extern int AM330_EXTTRIGARM_SETTIMEOUTLIMIT(int hSys, float timeoutS);
[DllImport("AMB1340C.dll", EntryPoint = "INITIALIZE")]
public static extern int INITIALIZE(int hSys);
[DllImport("AMB1340C.dll", EntryPoint = "RESETBOARDS")]
public static extern int RESETBOARDS();
[DllImport("AMB1340C.dll", EntryPoint = "CREATESESSION")]
public static extern int CREATESESSION(string hostname, out int session);
[DllImport("AMB1340C.dll", EntryPoint = "CLOSESESSION")]
public static extern int CLOSESESSION(int session);
[DllImport("AMB1340C.dll", EntryPoint = "AMB1340C_CREATEINSTANCE")]
public static extern int AMB1340C_CREATEINSTANCE(int session, int sysId, int offlinemode, out int hSys);
[DllImport("AMB1340C.dll", EntryPoint = "AMB1340C_DELETEINSTANCE")]
public static extern int AMB1340C_DELETEINSTANCE(int hSys);
[DllImport("AMB1340C.dll", EntryPoint = "DRIVEPORT")]
public static extern int DRIVEPORT(int hSys, int value);
[DllImport("AMB1340C.dll", EntryPoint = "DRIVETHISPORT")]
public static extern int DRIVETHISPORT(int hSys,int port, int value);
[DllImport("AMB1340C.dll", EntryPoint = "DRIVEPIN")]
public static extern int DRIVEPIN(int hSys, int pin, int value);
[DllImport("AMB1340C.dll", EntryPoint = "READPORT")]
public static extern int READPORT(int hSys, out int value);
[DllImport("AMB1340C.dll", EntryPoint = "READPIN")]
public static extern int READPIN(int hSys, int pin, out int value);
[DllImport("AMB1340C.dll", EntryPoint = "SETPORTDIRECTION")]
public static extern int SETPORTDIRECTION(int hSys, int value);
[DllImport("AMB1340C.dll", EntryPoint = "SETPINDIRECTION")]
public static extern int SETPINDIRECTION(int hSys, int pin, int value);
[DllImport("AMB1340C.dll", EntryPoint = "GETPORTDIRECTION")]
public static extern int GETPORTDIRECTION(int hSys, out int value);
[DllImport("AMB1340C.dll", EntryPoint = "GETPINDIRECTION")]
public static extern int GETPINDIRECTION(int hSys, int pin, out int value);
[DllImport("AMB1340C.dll", EntryPoint = "DRIVEVOLTAGE")]
public static extern int DRIVEVOLTAGE(int hSys, int pin, int mVvalue, int sign);
[DllImport("AMB1340C.dll", EntryPoint = "DRIVECURRENT")]
public static extern int DRIVECURRENT(int hSys, int pin, int nAvalue, int sign);
[DllImport("AMB1340C.dll", EntryPoint = "CLAMPVOLTAGE")]
public static extern int CLAMPVOLTAGE(int hSys, int pin, int mVvalue);
[DllImport("AMB1340C.dll", EntryPoint = "CLAMPCURRENT")]
public static extern int CLAMPCURRENT(int hSys, int pin, int nAvalue);
[DllImport("AMB1340C.dll", EntryPoint = "READVOLTAGE")]
public static extern int READVOLTAGE(int hSys, int pin, out int mVvalue);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENT")]
public static extern int READCURRENT(int hSys, int pin, out int nAvalue);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTABS")]
public static extern int READCURRENTRATE(int hSys, int pin, out int nAvalue);
[DllImport("AMB1340C.dll", EntryPoint = "READVOLTAGEVOLT")]
public static extern int READVOLTAGEVOLT(int hSys, int pin, out float volt);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTAMP")]
public static extern int READCURRENTAMP(int hSys, int pin, out float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTAMPABS")]
public static extern int READCURRENTAMPRATE(int hSys, int pin, out float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "READVOLTAGEWITHAVERAGE")]
public static extern int READVOLTAGEWITHAVERAGE(int hSys, int pin, int average, out int average_MV, out int every_MV);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTWITHAVERAGE")]
public static extern int READCURRENTWITHAVERAGE(int hSys, int pin, int average, out int average_NA, out int every_NA);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTAUTORANGE")]
public static extern int READCURRENTAUTORANGE(int hSys, int pin, out int nAvalue);
[DllImport("AMB1340C.dll", EntryPoint = "READCURRENTFROMRANGE")]
public static extern int READCURRENTFROMRANGE(int hSys, int channel, out int nAvalue);
[DllImport("AMB1340C.dll", EntryPoint = "ONSMUPIN")]
public static extern int ONSMUPIN(int hSys, int pin);
[DllImport("AMB1340C.dll", EntryPoint = "OFFSMUPIN")]
public static extern int OFFSMUPIN(int hSys, int pin);
[DllImport("AMB1340C.dll", EntryPoint = "SETANAPINBANDWIDTH")]
public static extern int SETANAPINBANDWIDTH(int hSys, int pin, int setting);
[DllImport("AMB1340C.dll", EntryPoint = "SETINTEGRATION")]
public static extern int SETINTEGRATION(int hSys, int chdat);
[DllImport("AMB1340C.dll", EntryPoint = "SETINTEGRATIONPOWERCYCLES")]
public static extern int SETINTEGRATIONPOWERCYCLES(int hSys, int setting, int powerCycles);
[DllImport("AMB1340C.dll", EntryPoint = "SETNPLC")]
public static extern int SETNPLC(int hSys, int pin, float nplc); // 0.0009 ~ 60
[DllImport("AMB1340C.dll", EntryPoint = "BIASSMUPIN")]
public static extern int BIASSMUPIN(int hSys, int chset, out int chdat);
[DllImport("AMB1340C.dll", EntryPoint = "READSMUPIN")]
public static extern int READSMUPIN(int hSys, int chset, out int chdat, out int chRead);
[DllImport("AMB1340C.dll", EntryPoint = "READSMUPINABS")]
public static extern int READSMUPINRATE(int hSys, int chset, out int chdat, out int chRead);
[DllImport("AMB1340C.dll", EntryPoint = "ONOFFSMUPIN")]
public static extern int ONOFFSMUPIN(int hSys, int chset, out int chdat);
[DllImport("AMB1340C.dll", EntryPoint = "ARMREADSMUPIN")]
public static extern int ARMREADSMUPIN(int hSys, int measset, out int chdat);
[DllImport("AMB1340C.dll", EntryPoint = "RETRIEVEREADSMUPIN")]
public static extern int RETRIEVEREADSMUPIN(int hSys, int measset, out int chdat, out int chRead);
[DllImport("AMB1340C.dll", EntryPoint = "SOURCEDELAYMEASURESMUPIN")]
public static extern int SOURCEDELAYMEASURESMUPIN(int hSys, int chset, out int chdat, out int chRead, int sequence);
[DllImport("AMB1340C.dll", EntryPoint = "AMB1340C_SOURCEDELAYMEASURESMUPIN")]
public static extern int AMB1340C_SOURCEDELAYMEASURESMUPIN(int hSys, int pinset, out float pindat, out int measset, out float pinRead, int sequence);
[DllImport("AMB1340C.dll", EntryPoint = "AM330_DRIVEPULSEVOLTAGE")]
public static extern int AM330_DRIVEPULSEVOLTAGE(int hSys, int pin, float _base, float pulse, float pulseS, float holdS, int drVrange, int cycles, int measCh, int measSel, int measVrange, int trigPercentage, int armExtTriginH, float timeoutS);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_DRIVEVOLTAGE")]
public static extern int AM371_DRIVEVOLTAGE(int hSys, int pin, float volt);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_DRIVEVOLTAGESETVRANGE")]
public static extern int AM371_DRIVEVOLTAGESETVRANGE(int hSys, int pin, float volt, int vrange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_DRIVECURRENT")]
public static extern int AM371_DRIVECURRENT(int hSys, int pin, float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_DRIVECURRENTSETIRANGE")]
public static extern int AM371_DRIVECURRENTSETIRANGE(int hSys, int pin, float ampere, int irange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_CLAMPVOLTAGE")]
public static extern int AM371_CLAMPVOLTAGE(int hSys, int pin, float volt);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_CLAMPVOLTAGESETVRANGE")]
public static extern int AM371_CLAMPVOLTAGESETVRANGE(int hSys, int pin, float volt, int vrange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_CLAMPCURRENT")]
public static extern int AM371_CLAMPCURRENT(int hSys, int pin, float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_CLAMPCURRENTSETIRANGE")]
public static extern int AM371_CLAMPCURRENTSETIRANGE(int hSys, int pin, float ampere, int irange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READVOLTAGE")]
public static extern int AM371_READVOLTAGE(int hSys, int pin, out float volt);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READVOLTAGEGETVRANGE")]
public static extern int AM371_READVOLTAGEGETVRANGE(int hSys, int pin, out float volt, out int vrange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READCURRENT")]
public static extern int AM371_READCURRENT(int hSys, int pin, out float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READCURRENTABS")]
public static extern int AM371_READCURRENTRATE(int hSys, int pin, out float ampere);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READCURRENTGETIRANGE")]
public static extern int AM371_READCURRENTGETIRANGE(int hSys, int pin, out float ampere, out int irange);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_ONSMUPIN")]
public static extern int AM371_ONSMUPIN(int hSys, int pin, int remoteSenseH);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_OFFSMUPIN")]
public static extern int AM371_OFFSMUPIN(int hSys, int pin);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_EXTTRIGARM_READCURRENTARRAY")]
public static extern int AM371_EXTTRIGARM_READCURRENTARRAY(int hSys, int pin, int posedgeH, float delayS, int nsample, float sampleDelayS);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_EXTTRIGGET_READCURRENTARRAY_WITH_MINMAX")]
public static extern int AM371_EXTTRIGGET_READCURRENTARRAY_WITH_MINMAX(int hSys, int pin, out int nsample, [MarshalAs(UnmanagedType.LPArray)] float[] iarray, out float min, out float max, out float average);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_EXTTRIGARM_RELEASE")]
public static extern int AM371_EXTTRIGARM_RELEASE(int hSys, int pin);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_USERBWSEL")]
public static extern int AM371_USERBWSEL(int hSys, int pin, int drvCoarseBw, int drvBoostEn, int clmpCoarseBw, int clmpBoostEn);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READCURRENT10X")]
public static extern int AM371_READCURRENT10X(int hSys, int pin, out float avalue);
[DllImport("AMB1340C.dll", EntryPoint = "AM371_READCURRENT10XABS")]
public static extern int AM371_READCURRENT10XRATE(int hSys, int pin, out float avalue);
[DllImport("AMB1340C.dll", EntryPoint = "WLF_SETVOLTAGELEVEL")]
public static extern int WLF_SETVOLTAGELEVEL(int hSys, int switchNum, int setting);
[DllImport("AMB1340C.dll", EntryPoint = "WLF_DRIVESINGLESWITCH")]
public static extern int WLF_DRIVESINGLESWITCH(int hSys, int switchNum, int val);
[DllImport("AMB1340C.dll", EntryPoint = "WLF_DRIVEALLSWITCH")]
public static extern int WLF_DRIVEALLSWITCH(int hSys, int val);
}
}
|
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BUS
{
public class t_pgiam
{
KetNoiDBDataContext db = new KetNoiDBDataContext();
public void moipg(string id, DateTime ngaynhap, string iddt, string iddv, string idnv, string ghichu, int so, string loainhap, string tiente, double tygia, bool giamgiatri, string idnvmhang, string link)
{
pgiam pn = new pgiam();
pn.id = id;
pn.ngaynhap = ngaynhap;
pn.iddt = iddt;
pn.iddv = iddv;
pn.idnv = idnv;
pn.ghichu = ghichu;
pn.so = so;
pn.link = link;
pn.giamgiatri = giamgiatri;
pn.idnvmhang = idnvmhang;
pn.loainhap = loainhap;
pn.tiente = tiente;
pn.tygia = tygia;
db.pgiams.InsertOnSubmit(pn);
db.SubmitChanges();
}
public void moict(string idsp, string diengiai, double sl, double dongia, string idcv, string loaithue, double thue, double chietkhau, double thanhtien, string idpgiamgia, string id, string tiente, double tygia, double nguyente, double chiphi, double giavon)
{
pgiamct ct = new pgiamct();
ct.idsanpham = idsp;
ct.diengiai = diengiai;
ct.soluong = sl;
ct.dongia = dongia;
ct.idcv = idcv;
ct.loaithue = loaithue;
ct.thue = thue;
ct.chietkhau = chietkhau;
ct.thanhtien = thanhtien;
ct.idpgiamgia = idpgiamgia;
ct.id = id;
ct.tiente = tiente;
ct.tygia = tygia;
ct.nguyente = nguyente;
ct.chiphi = chiphi;
ct.giavon = giavon;
db.pgiamcts.InsertOnSubmit(ct);
db.SubmitChanges();
}
public void suapg(string id, DateTime ngaynhap, string iddt, string iddv, string idnv, string ghichu, int so, string loainhap, string tiente, double tygia, bool giamgiatri, string idnvmhang, string link)
{
pgiam pn = (from c in db.pgiams select c).Single(x => x.id == id);
pn.ngaynhap = ngaynhap;
pn.iddt = iddt;
pn.iddv = iddv;
pn.idnv = idnv;
pn.ghichu = ghichu;
pn.so = so;
pn.link = link;
pn.giamgiatri = giamgiatri;
pn.idnvmhang = idnvmhang;
pn.loainhap = loainhap;
pn.tiente = tiente;
pn.tygia = tygia;
db.SubmitChanges();
}
//public void suact(string id, double chiphi, double giavon)
//{
// pnhapct ct = (from c in db.pnhapcts select c).Single(x => x.id == id);
// ct.chiphi = chiphi;
// ct.giavon = giavon;
// db.SubmitChanges();
//}
public void xoapg(string id)
{
pgiam pn = (from c in db.pgiams select c).Single(x => x.id == id);
db.pgiams.DeleteOnSubmit(pn);
db.SubmitChanges();
}
public void xoact(string id)
{
pgiamct ct = (from c in db.pgiamcts select c).Single(x => x.id == id);
db.pgiamcts.DeleteOnSubmit(ct);
db.SubmitChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPortal
{
class Student
{
public string name { get; set; }
public int id { get; set; }
public String address { get; set; }
public Student(int Id, String Name, String Address)
{
this.id = Id;
this.name = Name;
this.address = Address;
}
public Student()
{
}
}
class Program
{
int count;
Student[] studentarray = new Student[2];
void readDetails()
{
//studentarray[i] = new Student();
Console.WriteLine("Enter the number of Student records you want to enter:");
String input = Console.ReadLine();
Int32.TryParse(input, out count);
for(int i = 0; i<count; i++)
{
Student o = new Student();
Console.WriteLine("Enter the Student ID:");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Student Name:");
string name1 = Console.ReadLine();
Console.WriteLine("Enter the Student Address:");
String addrss = Console.ReadLine();
// displayDetails();
studentarray[i] = new Student() {
id = number,
name = name1,
address = addrss};
}
}
void displayDetails()
{
Console.WriteLine("------STUDENT DETAILS------");
for (int i = 0; i<count; i++)
{
//studentarray[i] = new Student();
Console.WriteLine("Student ID:" + studentarray[i].id);
Console.WriteLine("Student Name:" + studentarray[i].name);
Console.WriteLine("Student Address:" + studentarray[i].address);
Console.WriteLine("------------------------");
}
}
void startup()
{
Program p = new Program();
Console.WriteLine(" Enter Student Details");
p.readDetails();
Console.WriteLine("Do you want to display the details? (y/n)");
string res = Console.ReadLine();
if(res.ToLower() == "y")
{
p.displayDetails();
}
else
{
Console.WriteLine("Thank you for Using Student Portal");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Program s = new Program();
s.startup();
// p.readDetails();
// p.displayDetails();
Console.ReadKey();
}
}
}
|
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Meziantou.Analyzer.Test")]
|
using System;
namespace CSExercises
{
//Electrifying Electronics Pte Ltd. manufactures
//three audio-visual electronic products named
//as TV, DVD, and MP3. The table below gives
//the unit price for each of these products:
//PRODUCT PRICE
//TV $900
//DVD $500
//MP3 $700
//Retailers make orders for these products.
//Each order will have the product code and quantity
//(only one product in an order). The company has a policy
//that discount of 10% is given when the order amount exceeds
//$5000 and 15% discount when the order amount exceeds $10000.
//These discounts apply to TV and DVD only and no discount is provided for MP3.
//Write a program that would prompt the user successively
//the three product codes viz., TV, DVD, MP3 and after each prompt,
//the user enters the order quantity for that product.
//Then apply the price computations. (Obviously, if the user does not
//wish to order the item prompted he/she would enter a zero for the order quantity).
public class ExC6
{
public static void Main(string[] args)
{
Console.WriteLine("Enter the quantity of TV you need to be order");
int tv = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the quantity of DVD you need to be order");
int dvd = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the quantity of MP3 you need to be order");
int mp3 = Convert.ToInt32(Console.ReadLine());
double discountedPrice = CalculateTotalPrice(tv, dvd, mp3);
Console.WriteLine("The discounted price is {0}", discountedPrice);
}
public static double CalculateTotalPrice(int tvQty, int dvdQty, int mp3Qty)
{
double discountedPrice;
int tvdvdprice = 900 * tvQty + 500 * dvdQty;
int mp3price = 700 * mp3Qty;
if (tvdvdprice <= 5000)
{ discountedPrice = tvdvdprice + mp3price;
}
else if ((tvdvdprice > 5000) && (tvdvdprice <= 10000))
{
discountedPrice = 0.9 * tvdvdprice + mp3price;
}
else
{ discountedPrice = 0.85 * tvdvdprice + mp3price;
}
return discountedPrice;
}
}
} |
namespace Devices.Adafruit
{
public static class Constants
{
public const float SENSORS_GRAVITY_EARTH = 9.80665F; /**< Earth's gravity in m/s^2 */
public const float SENSORS_GRAVITY_MOON = 1.6F; /**< The moon's gravity in m/s^2 */
public const float SENSORS_GRAVITY_SUN = 275.0F; /**< The sun's gravity in m/s^2 */
public const float SENSORS_GRAVITY_STANDARD = SENSORS_GRAVITY_EARTH;
public const float SENSORS_MAGFIELD_EARTH_MAX = 60.0F; /**< Maximum magnetic field on Earth's surface */
public const float SENSORS_MAGFIELD_EARTH_MIN = 30.0F; /**< Minimum magnetic field on Earth's surface */
public const float SENSORS_PRESSURE_SEALEVELHPA = 1013.25F; /**< Average sea level pressure is 1013.25 hPa */
public const float SENSORS_DPS_TO_RADS = 0.017453293F; /**< Degrees/s to rad/s multiplier */
public const float SENSORS_GAUSS_TO_MICROTESLA = 100; /**< Gauss to micro-Tesla multiplier */
}
} |
using System;
using System.Linq;
using DSharpPlus;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using Requestrr.WebApi.RequestrrBot.ChatClients.Discord;
using Requestrr.WebApi.RequestrrBot.DownloadClients;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Ombi;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Overseerr;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Sonarr;
using Requestrr.WebApi.RequestrrBot.Notifications;
using Requestrr.WebApi.RequestrrBot.Notifications.TvShows;
namespace Requestrr.WebApi.RequestrrBot.TvShows
{
public class TvShowWorkflowFactory
{
private readonly TvShowsSettingsProvider _tvShowsSettingsProvider;
private readonly DiscordSettingsProvider _settingsProvider;
private readonly TvShowNotificationsRepository _notificationsRepository;
private OverseerrClient _overseerrClient;
private OmbiClient _ombiDownloadClient;
private SonarrClient _sonarrDownloadClient;
public TvShowWorkflowFactory(
TvShowsSettingsProvider tvShowsSettingsProvider,
DiscordSettingsProvider settingsProvider,
TvShowNotificationsRepository notificationsRepository,
OverseerrClient overseerrClient,
OmbiClient ombiDownloadClient,
SonarrClient radarrDownloadClient)
{
_tvShowsSettingsProvider = tvShowsSettingsProvider;
_settingsProvider = settingsProvider;
_notificationsRepository = notificationsRepository;
_overseerrClient = overseerrClient;
_ombiDownloadClient = ombiDownloadClient;
_sonarrDownloadClient = radarrDownloadClient;
}
public TvShowRequestingWorkflow CreateRequestingWorkflow(DiscordInteraction interaction, int categoryId)
{
var settings = _settingsProvider.Provide();
return new TvShowRequestingWorkflow(new TvShowUserRequester(interaction.User.Id.ToString(), interaction.User.Username),
categoryId,
GetTvShowClient<ITvShowSearcher>(settings),
GetTvShowClient<ITvShowRequester>(settings),
new DiscordTvShowUserInterface(interaction),
CreateMovieNotificationWorkflow(interaction, settings, GetTvShowClient<ITvShowSearcher>(settings)),
_tvShowsSettingsProvider.Provide());
}
public ITvShowNotificationWorkflow CreateNotificationWorkflow(DiscordInteraction interaction)
{
var settings = _settingsProvider.Provide();
return CreateMovieNotificationWorkflow(interaction, settings, GetTvShowClient<ITvShowSearcher>(settings));
}
public TvShowNotificationEngine CreateTvShowNotificationEngine(DiscordClient client, ILogger logger)
{
var settings = _settingsProvider.Provide();
ITvShowNotifier tvShowNotifier = null;
if (settings.NotificationMode == NotificationMode.PrivateMessage)
{
tvShowNotifier = new PrivateMessageTvShowNotifier(client, _settingsProvider, logger);
}
else if (settings.NotificationMode == NotificationMode.Channels)
{
tvShowNotifier = new ChannelTvShowNotifier(client, _settingsProvider, settings.NotificationChannels.Select(x => ulong.Parse(x)).ToArray(), logger);
}
else
{
throw new Exception($"Could not create tv show notifier of type \"{settings.NotificationMode}\"");
}
return new TvShowNotificationEngine(GetTvShowClient<ITvShowSearcher>(settings), tvShowNotifier, logger, _notificationsRepository);
}
private ITvShowNotificationWorkflow CreateMovieNotificationWorkflow(DiscordInteraction interaction, DiscordSettings settings, ITvShowSearcher tvShowSearcher)
{
var userInterface = new DiscordTvShowUserInterface(interaction);
ITvShowNotificationWorkflow movieNotificationWorkflow = new DisabledTvShowNotificationWorkflow(userInterface);
if (settings.NotificationMode != NotificationMode.Disabled)
{
movieNotificationWorkflow = new TvShowNotificationWorkflow(_notificationsRepository, userInterface, tvShowSearcher, settings.AutomaticallyNotifyRequesters);
}
return movieNotificationWorkflow;
}
private T GetTvShowClient<T>(DiscordSettings settings) where T : class
{
if (settings.TvShowDownloadClient == DownloadClient.Sonarr)
{
return _sonarrDownloadClient as T;
}
else if (settings.TvShowDownloadClient == DownloadClient.Ombi)
{
return _ombiDownloadClient as T;
}
else if (settings.TvShowDownloadClient == DownloadClient.Overseerr)
{
return _overseerrClient as T;
}
else
{
throw new Exception($"Invalid configured tv show download client {settings.TvShowDownloadClient}");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
namespace Pokemon
{
class Program
{
static void Main(string[] args)
{
string input;
Dictionary<string, Trainer> trainers = new Dictionary<string, Trainer>();
while ((input=Console.ReadLine())!="Tournament")
{
string [] curentTrainer = input.Split(" ");
Trainer trainer = new Trainer(curentTrainer[0]);
Pokemon pokemon = new Pokemon(curentTrainer[1], curentTrainer[2], double.Parse(curentTrainer[3]));
if (!trainers.ContainsKey(trainer.Name))
{
trainer.Colection.Add(pokemon);
trainers[trainer.Name] = trainer;
}
else
{
trainers[trainer.Name].Colection.Add(pokemon);
}
}
string input2;
while ((input2=Console.ReadLine())!="End")
{
foreach (var item in trainers)
{
if (item.Value.Colection.Any(x=>x.Element==input2))
{
item.Value.NumberOfBadge++;
}
else
{
item.Value.Colection = HealthCheck(item.Value.Colection);
}
}
}
trainers = trainers.OrderByDescending(x => x.Value.NumberOfBadge).ToDictionary(x=>x.Key,x=>x.Value);
foreach (var item in trainers)
{
Console.WriteLine("{0} {1} {2}",item.Value.Name,item.Value.NumberOfBadge,item.Value.Colection.Count);
}
}
public static List<Pokemon> HealthCheck(List<Pokemon>pokemons)
{
foreach (var item in pokemons)
{
item.Health -= 10;
}
pokemons = pokemons.Where(x => x.Health > 0).ToList();
return pokemons;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace Predicate_party__
{
class Program
{
static void Main(string[] args)
{
List<string> peoples = new List<string>();
peoples = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).ToList();
string input;
while ((input = Console.ReadLine()) != "Party!")
{
string[] comand = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
if (comand[0] == "Remove")
{
peoples = Remove(peoples, comand);
}
else if (comand[0]=="Double")
{
peoples = Double(peoples, comand);
}
}
if (peoples.Count!=0)
{
Console.Write(string.Join(", ", peoples));
Console.Write(" are going to the party!");
}
else
{
Console.WriteLine("Nobody is going to the party!");
}
}
static List<string> Double(List<string> peoples,string[] comand)
{
List<string> resultList = new List<string>();
Func<string, string, bool> func = Operation(comand);
for (int i = 0; i < peoples.Count; i++)
{
if (func(peoples[i], comand[2]))
{
resultList.Add(peoples[i]);
}
resultList.Add(peoples[i]);
}
return resultList;
}
static Func<string, string, bool> Operation(string[] comand)
{
if (comand[1] == "StartsWith")
{
return (x, y) => x.Substring(0, y.Length) == y;
}
else if (comand[1] == "EndsWith")
{
return (x, y) => x.Substring(x.Length - y.Length, y.Length) == y;
}
else
{
return (x, y) => x.Length == int.Parse(y);
}
}
static List<string> Remove(List<string> peoples, string[] comand)
{
Func<string, string, bool> func = Operation(comand);
for (int i = 0; i < peoples.Count; i++)
{
if (func(peoples[i],comand[2]))
{
peoples.RemoveAt(i);
i--;
}
}
return peoples;
}
}
}
|
namespace cn.bmob.io
{
internal class Delete : Operate
{
public override void write(BmobOutput output, bool all)
{
base.write(output, all);
output.Put(OP_NAME, "Delete");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApp1
{
class patient
{
private const String SERVER = "35.185.184.170";
private const String DATABASE = "PriClinic";
private const String UID = "lac";
private const String PASSWORD = "laclaclaclaclac";
private static MySqlConnection dbConn;
public int patient_id { get; private set; }
public String name { get; private set; }
public String birthday { get; private set; }
public String gender { get; private set; }
public String addres { get; private set; }
public String phone { get; private set; }
private patient(int idP, String n, String dob, String ge, String addr, String pnNum)
{
patient_id = idP;
name = n;
birthday = dob;
gender = ge;
addres = addr;
phone = pnNum;
}
public static void InitializeDB()
{
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Server = SERVER;
builder.UserID = UID;
builder.Password = PASSWORD;
builder.Database = DATABASE;
String connString = builder.ToString();
builder = null;
Console.WriteLine(connString);
dbConn = new MySqlConnection(connString);
Application.ApplicationExit += (sender, args) =>
{
if (dbConn != null)
{
dbConn.Dispose();
dbConn = null;
}
};
}
public static List<patient> GetPatients()
{
List<patient> patients = new List<patient>();
String query = "SELECT * FROM Patient";
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = (int)reader["patient_id"];
String n = reader["name"].ToString();
String yob = reader["birthday"].ToString();
String gender = reader["gender"].ToString();
String Addr = reader["addres"].ToString();
String phone = reader["phone"].ToString();
patient p = new patient(id, n, yob,gender,Addr,phone);
patients.Add(p);
}
reader.Close();
dbConn.Close();
return patients;
}
public static patient Insert(String n,String yob, String gender, String Addr,String pnNum)
{
String query = string.Format("INSERT INTO Patient(name,birthday,gender,addres,phone) VALUES ('{0}', '{1}','{2}','{3}','{4}')",
n,yob,gender,Addr, pnNum);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
cmd.ExecuteNonQuery();
int id = (int)cmd.LastInsertedId;
patient p = new patient(id, n, yob, gender, Addr, pnNum);
dbConn.Close();
return p;
}
public void Update(String n, String yob, String gender, String Addr, String pnNum)
{
String query = string.Format("UPDATE Patient SET name='{0}', birthday='{1}',gender='{2}',addres='{3}',phone='{4}' WHERE patient_id={5}",
n,yob,gender,Addr,pnNum, patient_id);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
cmd.ExecuteNonQuery();
dbConn.Close();
}
public void Delete()
{
String query = string.Format("DELETE FROM Patient WHERE patient_id={0}", patient_id);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
cmd.ExecuteNonQuery();
dbConn.Close();
}
public static List<patient> FastQuery(int searching)
{
List<patient> patients = new List<patient>();
String query = String.Format("SELECT * FROM Patient WHERE patient_id LIKE '%{0}%'", searching);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = (int)reader["patient_id"];
String n = reader["name"].ToString();
String yob = reader["birthday"].ToString();
String gender = reader["gender"].ToString();
String Addr = reader["addres"].ToString();
String phone = reader["phone"].ToString();
patient p = new patient(id, n, yob, gender, Addr,phone);
patients.Add(p);
}
reader.Close();
dbConn.Close();
return patients;
}
public static List<patient> QueryByName(string name)
{
List<patient> patients = new List<patient>();
String query = String.Format("SELECT * FROM Patient WHERE name LIKE '%{0}%'", name);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = (int)reader["patient_id"];
String n = reader["name"].ToString();
String yob = reader["birthday"].ToString();
String gender = reader["gender"].ToString();
String Addr = reader["addres"].ToString();
String phone = reader["phone"].ToString();
patient p = new patient(id, n, yob, gender, Addr, phone);
patients.Add(p);
}
reader.Close();
dbConn.Close();
return patients;
}
public static List<patient> QueryByPhone(string phoneNum)
{
List<patient> patients = new List<patient>();
String query = String.Format("SELECT * FROM Patient WHERE phone LIKE '%{0}%'", phoneNum);
MySqlCommand cmd = new MySqlCommand(query, dbConn);
dbConn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = (int)reader["patient_id"];
String n = reader["name"].ToString();
String yob = reader["birthday"].ToString();
String gender = reader["gender"].ToString();
String Addr = reader["addres"].ToString();
String phone = reader["phone"].ToString();
patient p = new patient(id, n, yob, gender, Addr, phone);
patients.Add(p);
}
reader.Close();
dbConn.Close();
return patients;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.API;
using Discord.Commands;
using System.Configuration;
namespace JeanGuyTremblayBot
{
class Program
{
#region hey
const string _PSWD = "jgt_bot";
const string _USERNAME = "williambalthazar@outlook.com";
#endregion
static void Main(string[] args)
{
Console.Title = "Jean Guy Tremblay Bot";
//Instancie un bot avec un login et un client
DiscordBot bot = new DiscordBot(new DiscordClient(new DiscordClientConfig
{
LogLevel = LogMessageSeverity.Debug
}));
Console.WriteLine("closing...");
Console.ReadKey();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lighter : MonoBehaviour {
public ParticleSystem fire;
public GameObject light;
// Use this for initialization
void Start () {
fire.Stop();
}
// Update is called once per frame
void Update () {
}
public void StartFire()
{
fire.Play();
fire.GetComponent<Fire>().lit = true;
light.SetActive(true);
}
public void StopFire()
{
fire.Stop();
fire.GetComponent<Fire>().lit = false;
light.SetActive(false);
}
}
|
using Newtonsoft.Json;
using System;
namespace Minecraft4Dev.Web.Models
{
public class DeathLog
{
[JsonProperty("playerName")]
public string PlayerName { get; set; }
[JsonProperty("deathReason")]
public string DeathReason { get; set; }
[JsonProperty("deathDate")]
public DateTime DeathDate { get; set; }
}
} |
using PNPUCore.Database;
using PNPUTools;
using PNPUTools.DataManager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom d'interface "IService1" à la fois dans le code et le fichier de configuration.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "clients/dashboard/{workflowId}")]
IEnumerable<InfoClientStep> GetInfoAllClient(string workflowId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "clients/{ClientName}")]
string GetInfoOneClient(string ClientName);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "process")]
IEnumerable<PNPU_PROCESS> GetAllProcesses();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "workflow/historic")]
IEnumerable<PNPU_H_WORKFLOW> GetHWorkflow();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "process/{processId}")]
PNPU_PROCESS getProcess(string processId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "workflow")]
IEnumerable<PNPU_WORKFLOW> GetAllWorkFLow();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "workflow/{workflowId}")]
PNPU_WORKFLOW getWorkflow(string workflowId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "report/{workflowId}/{idProcess}/{clientId}")]
IEnumerable<PNPU_H_REPORT> getReport(string idProcess, string workflowId, string clientId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "workflow/{workflowId}/processus")]
IEnumerable<PNPU_WORKFLOWPROCESSES> GetWorkflowProcesses(string workflowId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "processuscritique")]
string GetProcessusCritiquesAllCLient();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "processuscritique/{ClientName}")]
string GetProcessusCritiquesOneClient(string ClientName);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "idorga")]
string GetIdOrgaAllClient();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "idorga/{ClientName}")]
string GetIdOrgaOneClient(string ClientName);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "typologie")]
string GetTypoAllClient();
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "typologie/{ClientName}")]
string GetTypoOneClient(string ClientName);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Workflow/{WorkflowName}/Run")]
string RunWorkflow(string WorkflowName);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Alacon/{test}")]
string Alacon(string test);
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Workflow/CreateWorkflow/")]
string CreateWorkflow(PNPU_WORKFLOW input);
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Workflow/{workflowID}")]
string AffectWorkflowsProcesses(PNPU_STEP input, string workflowID);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Workflow/{workflowID}/maxstep")]
string GetMaxStep(string workflowID);
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "process/CreateProcess/")]
string CreateProcess(PNPU_PROCESS input);
[OperationContract]
[WebInvoke(Method = "PUT",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Workflow/{workflowID}")]
string ModifyWorkflow(PNPU_WORKFLOW input, string workflowID);
[OperationContract]
[WebInvoke(Method = "PUT",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "process/{processID}")]
string ModifyProcessus(PNPU_PROCESS input, string processID);
[OperationContract]
[WebInvoke(Method = "DELETE",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Workflow/{workflowID}/Delete")]
string DeleteWorkflow(string workflowID);
[OperationContract]
[WebInvoke(Method = "DELETE",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "process/{processID}/Delete")]
string DeleteProcess(string processID);
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "worflow/{WorkflowId}/uploadFile")]
void UploadFile(Stream stream, string WorkflowId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "clientsByTypo/{TypologyId}")]
IEnumerable<InfoClient> getListClientsByTypo( string TypologyId);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "clientsByTypo")]
IEnumerable<InfoClient> getListClients();
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*", ResponseFormat = WebMessageFormat.Json)]
void preflightRequest();
}
}
|
using System.Threading.Tasks;
namespace Micro.Net.Abstractions.Sagas
{
public interface ISagaTerminateHandler<TData>
{
Task HandleTerminate(ISagaTerminateContext<TData> context);
}
public interface ISagaTerminateHandler
{
Task HandleTerminate<TData>(TData data, ISagaTerminateContext context);
}
} |
namespace GrandCloud.CS.Model
{
/// <summary>
/// The ListBucketsRequest contains the parameters used for the ListAllBuckets operation.
/// No parameters are needed for this request.
/// </summary>
public class ListBucketsRequest : CSRequest
{
}
} |
namespace Plus.Utilities.Enclosure.Algorithm
{
public class FieldUpdate
{
public FieldUpdate(int x, int y, byte value)
{
X = x;
Y = y;
Value = value;
}
public byte Value { get; }
public int Y { get; }
public int X { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using trial_api.Models;
using trial_api.PasswordHashing;
namespace trial_api.Data
{
//this adds some static data to db
public class TestData
{
public static void Initialize(IApplicationBuilder app)
{
using(var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<DataContext>();
context.Database.EnsureCreated();
if(context.Books != null && context.Books.Any())
return;
var users = TestData.GetAllUsers().ToArray();
context.Books.AddRange(users);
context.SaveChanges();
}
}
public static List<Book> GetAllUsers()
{
PasswordHasher ph = new PasswordHasher();
// string hash1 = ph.hashPass("Cvb123");
List<Book> userList = new()
{
new Book
{
Id = Guid.NewGuid(),
BookName = "User1",
Password = ph.hashPass("Cvb123"),
Author = "author"
},
new Book
{
Id = Guid.NewGuid(),
BookName = "User2",
Password = ph.hashPass("Cvb12322"),
Author = "author2"
}
};
return userList;
}
}
} |
namespace MyAppBack.Models
{
public class AppSettings
{
public string ServiceDomainUrl { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MODEL.SYSTEM
{
public class UserLoginLimitModel
{
private int userid = int.MaxValue;
private string logintype = string.Empty;
private string ukeyid = string.Empty;
private int isstart = 1;
/// <summary>
/// UserID
/// </summary>
public int UserID
{
set { userid = value; }
get { return userid; }
}
/// <summary>
/// LoginType
/// </summary>
public string LoginType
{
set { logintype = value; }
get { return logintype; }
}
/// <summary>
/// UKeyID
/// </summary>
public string UKeyID
{
set { ukeyid = value; }
get { return ukeyid; }
}
/// <summary>
/// IsStart
/// </summary>
public int IsStart
{
set { isstart = value; }
get { return isstart; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MoreMountains.Tools;
using MoreMountains.CorgiEngine;
public class CharacterHandleShootingGun : CharacterHandleWeapon
{
protected override void HandleInput()
{
}
protected override void Initialization()
{
base.Initialization();
}
}
|
using Airfield_Simulator.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Airfield_Simulator.Core.Airplane;
namespace Airfield_Simulator.Core.Simulation
{
public class AirplaneManager : SimulationObject, IAirplaneManager
{
public List<Aircraft> AircraftList { get; private set; }
public event CollisionEventHandler Collision;
private ISimulationProperties SimulationProperties { get; set; }
public AirplaneManager(ISimulationProperties simprops)
{
AircraftList = new List<Aircraft>();
SimulationProperties = simprops;
}
public override void AfterUpdate()
{
CheckForCollision();
}
public Aircraft CreateAircraft(GeoPoint position, int heading)
{
var ac = new Aircraft(position, heading, SimulationProperties);
AircraftList.Add(ac);
return ac;
}
public void RemoveAircraft(Aircraft aircaft)
{
AircraftList.Remove(aircaft);
}
public void Reset()
{
AircraftList.Clear();
}
private void OnCollision(object sender, CollisionEventArgs e)
{
Collision?.Invoke(sender, e);
}
private void CheckForCollision()
{
foreach (var ac in AircraftList.ToList())
{
foreach (var ac2 in AircraftList.ToList())
{
if (ac == ac2) break;
var distance = GeoPoint.GetDistance(ac.Position, ac2.Position);
if (distance < 500)
{
OnCollision(ac, new CollisionEventArgs(ac2));
}
}
}
}
}
}
|
namespace Bindable.Linq.SampleApplication
{
using System.Windows;
using Samples;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Window w = new SyncLinqFilteredWindow();
MainWindow = w;
w.Show();
}
}
} |
using DAL.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Interfaces
{
public interface IUser
{
Task<User> Adduser(string username, string emailAddress, string password, int authLevelId);
Task<List<User>> GetAllUsers();
}
}
|
using System;
using System.Diagnostics;
using SharpDX;
using SumoNinjaMonkey.Framework.Controls.DrawingSurface;
using CommonDX;
using SharpDX.Direct3D11;
using Windows.UI.Xaml;
using SharpDX.IO;
using SharpDX.DXGI;
using SharpDX.Direct3D;
using System.Collections.Generic;
using ModernCSApp.Services;
using Sandbox.DxRenderer;
using ModernCSApp.Views;
namespace ModernCSApp.DxRenderer
{
public partial class MagicComposer : BaseRenderer, IRenderer, ISpriteRenderer
{
private DeviceManager _deviceManager;
private SpriteBatch spriteBatch;
public bool EnableClear { get; set; }
public bool Show { get; set; }
private UIElement _root;
private DependencyObject _rootParent;
private Stopwatch clock;
private float _appWidth;
private float _appHeight;
public SumoNinjaMonkey.Framework.Controls.DrawingSurfaceSIS DrawingSurface;
private Vector2 _currentPointerPosition = new Vector2(0, 0);
private Texture2D _textureDot;
private Texture2D _textureStar;
private bool _moveBurst = false;
public float Scale { get; set; }
public MagicComposer()
{
Scale = 1.0f;
EnableClear = true;
clock = new Stopwatch();
_moveBurst = false;
_currentPointerPosition = new Vector2(0, 0);
spriteBatch = new SpriteBatch();
}
public void UpdateState(GlobalState state)
{
State = state;
}
public void Initialize(DeviceManager deviceManager)
{
_deviceManager = deviceManager;
// Remove previous buffer
//SafeDispose(ref constantBuffer);
// Setup local variables
var d3dDevice = deviceManager.DeviceDirect3D;
var d3dContext = deviceManager.ContextDirect3D;
spriteBatch.Initialize(d3dDevice, d3dContext, 5000);
//// Load texture and create sampler
using (var bitmap = TextureLoader.LoadBitmap(deviceManager.WICFactory, "Assets\\DotPink.png"))
_textureDot = TextureLoader.CreateTexture2DFromBitmap(d3dDevice, bitmap);
spriteBatch.AddTexture(_textureDot);
using (var bitmap = TextureLoader.LoadBitmap(deviceManager.WICFactory, "Assets\\gold-star.png"))
_textureStar = TextureLoader.CreateTexture2DFromBitmap(d3dDevice, bitmap);
spriteBatch.AddTexture(_textureStar);
GestureService.OnGestureRaised += (o, a) =>
{
CustomGestureArgs gestureArgs = (CustomGestureArgs)a;
if (gestureArgs.ManipulationStartedArgs != null)
{
}
else if (gestureArgs.ManipulationInertiaStartingArgs != null)
{
}
else if (gestureArgs.ManipulationUpdatedArgs != null)
{
}
else if (gestureArgs.ManipulationCompletedArgs != null)
{
}
else if (gestureArgs.TappedEventArgs != null)
{
}
else if (gestureArgs.PressedPointerRoutedEventArgs != null)
{
//spriteBatch.IsEnabled = true;
//moveDot(gestureArgs.PressedPointerRoutedEventArgs.GetCurrentPoint(null).Position);
}
else if (gestureArgs.MovedPointerRoutedEventArgs != null)
{
//moveDot(gestureArgs.MovedPointerRoutedEventArgs.GetCurrentPoint(null).Position);
}
else if (gestureArgs.ReleasedPointerRoutedEventArgs != null)
{
//spriteBatch.IsEnabled = false;
//moveDot(gestureArgs.ReleasedPointerRoutedEventArgs.GetCurrentPoint(null).Position);
}
};
clock = new Stopwatch();
clock.Start();
}
public void InitializeUI(UIElement rootForPointerEvents, UIElement rootOfLayout)
{
_root = rootForPointerEvents;
_rootParent = rootOfLayout;
_appWidth = (float)((FrameworkElement)_root).ActualWidth;
_appHeight = (float)((FrameworkElement)_root).ActualHeight;
}
public void Update(SharpDX.Toolkit.GameTime gameTime)
{
}
public void Render(TargetBase target)
{
var d3dContext = target.DeviceManager.ContextDirect3D;
var d2dContext = target.DeviceManager.ContextDirect2D;
// Set targets (This is mandatory in the loop)
d3dContext.OutputMerger.SetTargets(target.DepthStencilView, target.RenderTargetView);
// Clear the views
d3dContext.ClearDepthStencilView(target.DepthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);
if (EnableClear)
{
d3dContext.ClearRenderTargetView(target.RenderTargetView, new Color4(0.0f, 0.0f, 0.0f, 0.0f));
}
spriteBatch.Begin(target);
for (int i = 0; i < 50; i++)
{
spriteBatch.Draw(_textureDot, _currentPointerPosition * new Vector2(1, -1));
}
spriteBatch.End();
}
public void LoadLocalAsset(string assetUri)
{
throw new NotImplementedException();
}
public void AddSprite(double x, double y, double z, double duration)
{
DispatcherTimer dt = new DispatcherTimer();
dt.Tick += (o,e) => {
spriteBatch.IsEnabled = false;
dt.Stop();
};
dt.Interval = TimeSpan.FromSeconds(duration);
dt.Start();
spriteBatch.IsEnabled = true;
moveDot(new Windows.Foundation.Point(x, y));
}
private void moveDot(Windows.Foundation.Point newPosition)
{
Vector2 origin = spriteBatch.CalculatePointerPosition(
new Vector2((float)newPosition.X, (float)newPosition.Y),
PositionUnits.Pixels);
//TODO : Need to work out how to calculate this 35/28 factor
Vector2 offset = new Vector2(63.0f, 35.0f) * origin;
_currentPointerPosition.X = offset.X;
_currentPointerPosition.Y = offset.Y;
}
public void Unload() { }
}
}
|
namespace AdventOfCode.Base;
public abstract class SolverBase
{
string DayDirectory => $"{AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin"))}\\{GetType().Name.Substring(0, 5)}\\";
List<string> Load(string inputFileName)
=> File.ReadAllLines(DayDirectory + inputFileName).ToList();
string Save(string outputFileName, string data)
{
File.WriteAllText(DayDirectory + outputFileName, data);
return data;
}
public string ExecutePuzzle1(string inputFileName = "input.txt", string outputFileName = "output1.txt")
{
Parse(Load(inputFileName));
return Save(outputFileName, Solve1()?.ToString());
}
public string ExecutePuzzle2(string inputFileName = "input.txt", string outputFileName = "output2.txt")
{
Parse(Load(inputFileName));
return Save(outputFileName, Solve2()?.ToString());
}
public void ExecuteExample1(string expectedResult)
{
Parse(Load("Example.txt"));
Assert.Equal(expectedResult, Solve1()?.ToString());
}
public void ExecuteExample2(string expectedResult)
{
Parse(Load("Example.txt"));
Assert.Equal(expectedResult, Solve2()?.ToString());
}
protected abstract void Parse(List<string> data);
protected abstract object Solve1();
protected abstract object Solve2();
}
|
using System.Collections.Generic;
namespace CfgComparator.Models
{
/// <summary>
/// Holds source and target <see cref="ConfigurationFile"/> and list of <see cref="ParameterDifference"/>.
/// </summary>
public class ConfigurationsCompareResult
{
public ConfigurationFile Source { get; }
public ConfigurationFile Target { get; }
public List<ParameterDifference> Differences { get; set; } = new();
public ConfigurationsCompareResult(ConfigurationFile source, ConfigurationFile target)
{
Source = source;
Target = target;
}
}
}
|
using UnityEngine;
[System.Serializable]
public class Sound
{
public string soundName;
public AudioClip[] clip;
[Range(0,5)]
public float delay;
[Range(0, 1)]
public float volume = 0.5f;
[Range(0, 1.5f)]
public float pitch = 1;
private AudioSource source;
Sound() {
volume = 1;
pitch = 1;
}
public void SetSource(AudioSource _source) {
source = _source;
int randomNumber = Random.Range(0, clip.Length);
if(clip.Length != 0) {
source.clip = clip[randomNumber];
} else {
Debug.Log("no sound");
}
}
public void Play() {
if(!source.isPlaying) {
if(clip.Length > 1) {
SetSource(source);
}
source.pitch = pitch + Random.Range(-0.1f,0.1f);
source.volume = volume;
source.Play();
}
}
}
|
using CVBuilder.Core.Models;
using CVBuilder.Core.Printers;
using NUnit.Framework;
using System;
using System.Linq;
using CV = CVBuilder.Core;
namespace CVBuilder.Tests
{
public class CurriculumVitaeBuilderTests
{
[SetUp]
public void Setup()
{
}
[Test]
public void Create_CurriculumVitae_Minimum_Information_Successfully()
{
// Create Curriculum Vitae using CurriculumVitae builder
CurriculumVitae curriculum = CVBuilder.Core.CurriculumVitaeBuilder
.Start()
.WithFirstName("Daniel")
.WithLastName("Bran")
.WithPhoneNumber("0040734***375")
.WithEmail("bran******@gmail.com")
.WithAddress()
.WithCountry("Romania")
.WithCounty("Bihor")
.WithCity("Oradea")
.Update()
.WithLanguage("English")
.WithLanguage("Spanish")
.WithLanguage("Romanian")
.WithNationaity("Romanian")
.WithEducationItem(
new Education()
{
Id = 1,
Title = "Coumputer Science Faculty",
Description = "Coumputer Science Faculty at University of Oradea"
})
.WithEducationItem(
new Education()
{
Id = 2,
Title = "Master of Computer Science",
Description = "Master of Computer Science at University of Oradea, theme Distributed systems in internet"
})
.WithBirthday(DateTime.Now.AddYears(-18))
.AddPhoto("https://media-exp1.licdn.com/dms/image/C5103AQGKJtoudXZHSg/profile-displayphoto-shrink_200_200/0?e=1584576000&v=beta&t=B1EuznIzsSR6CEJVoSzXEzIAJudSsIpC8Ky8_EGqBnw")
.Finish();
// Create new console printer to display the curriculum into Test output.
ConsolePrinter consolePrinter = new ConsolePrinter();
// Print CV into Test output.
consolePrinter.Print(curriculum);
// Test asserts
Assert.AreEqual(curriculum.FullName, "Daniel Bran");
Assert.AreEqual(curriculum.PhoneNumber, "0040734***375");
Assert.AreEqual(curriculum.EmailAddress, "bran******@gmail.com");
Assert.AreEqual(curriculum.Address.Country, "Romania");
Assert.AreEqual(curriculum.Address.County, "Bihor");
Assert.AreEqual(curriculum.Address.City, "Oradea");
Assert.IsTrue(curriculum.Languages.Count == 3);
Assert.AreEqual(curriculum.Nationality, "Romanian");
Assert.IsTrue(curriculum.Educations.ToList().Count == 2);
Assert.Pass();
}
[Test]
public void Create_CurriculumVitae_AllData_And_Options_Successfully()
{
CurriculumVitae curriculum = CV.CurriculumVitaeBuilder
.Start()
.WithFirstName("Daniel")
.WithLastName("Bran")
.WithPhoneNumber("0040734***375")
.WithEmail("bran******@gmail.com")
.WithAddress(new Address()
{
Country = "Romania",
City = "Oradea",
County = "Bihor",
Street = "private",
PostalCode = "private",
StreetNumber = "private"
})
.WithLanguage("English")
.WithLanguage("Spanish")
.WithLanguage("Romanian")
.WithNationaity("Romanian")
.WithEducationItem(
new Education()
{
Id = 1,
Title = "Coumputer Science Faculty",
Description = "Coumputer Science Faculty at University of Oradea"
})
.WithEducationItem(
new Education()
{
Id = 2,
Title = "Master of Computer Science",
Description = "Master of Computer Science at University of Oradea, theme Distributed systems in internet"
})
.WithBirthday(DateTime.Now.AddYears(-18))
.WithTrainingItem(new Training()
{
Institution = "Fortech",
Title = "Azure Training",
Description = "Azure training internal at Fortech with Alex Mang"
})
.WithProjectPortofolioItem(
new ProjectPortofolio()
{
Title = "Private Project",
Description = "Private description"
})
.WithWorkingExperienceItem(
new WorkingExperience()
{
Title = "Fortech Romania",
Description = "I am working at Fortech since 2016"
})
.WithWorkingExperienceItem(
new WorkingExperience()
{
Title = "Before Fortech",
Description = "I was working on several projects for several Romanian institutions, websites, desktop applications"
})
.WithPublicAppearanceItem(
new PublicAppearance()
{
PublicAppearanceType = PublicAppearanceType.Newspaper,
Title = "Mentor at DPIT contest, third place",
Description = "My team with me as mentor took the third place DPIT 2019 contest."
})
.WithPublicAppearanceItem(
new PublicAppearance()
{
PublicAppearanceType = PublicAppearanceType.TV,
Title = "Mentor at DPIT contest, third place",
Description = "My team with me as mentor took the third place DPIT 2019 contest."
})
.AddPhoto("https://media-exp1.licdn.com/dms/image/C5103AQGKJtoudXZHSg/profile-displayphoto-shrink_200_200/0?e=1584576000&v=beta&t=B1EuznIzsSR6CEJVoSzXEzIAJudSsIpC8Ky8_EGqBnw")
.AddPhoto("http://linkedin/daniel.bran")
.Validate()
.Finish();
// Test asserts
Assert.AreEqual(curriculum.FullName, "Daniel Bran");
Assert.AreEqual(curriculum.PhoneNumber, "0040734***375");
Assert.AreEqual(curriculum.EmailAddress, "bran******@gmail.com");
Assert.AreEqual(curriculum.Address.Country, "Romania");
Assert.AreEqual(curriculum.Address.County, "Bihor");
Assert.AreEqual(curriculum.Address.City, "Oradea");
Assert.IsTrue(curriculum.Languages.Count == 3);
Assert.AreEqual(curriculum.Nationality, "Romanian");
Assert.IsTrue(curriculum.Educations.Count == 2);
Assert.IsTrue(curriculum.Trainings.Count == 1);
Assert.IsTrue(curriculum.ProjectsPortofolio.Count == 1);
Assert.IsTrue(curriculum.PublicAppearances.Count == 2);
Assert.IsTrue(curriculum.WorkingExperiences.Count == 2);
Assert.Pass();
}
[Test]
public void Create_CurriculumVitae_Minimum_Information_Failing_invalid_age()
{
Exception exception = null;
try
{
// Create Curriculum Vitae using CurriculumVitae builder
CurriculumVitae curriculum = CVBuilder.Core.CurriculumVitaeBuilder
.Start()
.WithFirstName("Daniel")
.WithLastName("Bran")
.WithPhoneNumber("0040734***375")
.WithEmail("bran******@gmail.com")
.WithAddress()
.WithCountry("Romania")
.WithCounty("Bihor")
.WithCity("Oradea")
.Update()
.WithLanguage("English")
.WithLanguage("Spanish")
.WithLanguage("Romanian")
.WithNationaity("Romanian")
.WithEducationItem(
new Education()
{
Id = 1,
Title = "Coumputer Science Faculty",
Description = "Coumputer Science Faculty at University of Oradea"
})
.WithEducationItem(
new Education()
{
Id = 2,
Title = "Master of Computer Science",
Description = "Master of Computer Science at University of Oradea, theme Distributed systems in internet"
})
.WithBirthday(DateTime.Now.AddYears(-17))
.AddPhoto("https://media-exp1.licdn.com/dms/image/C5103AQGKJtoudXZHSg/profile-displayphoto-shrink_200_200/0?e=1584576000&v=beta&t=B1EuznIzsSR6CEJVoSzXEzIAJudSsIpC8Ky8_EGqBnw")
.Validate()
.Finish();
}
catch (Exception ex)
{
exception = ex;
}
Assert.IsNotNull(exception);
Assert.AreEqual(exception.Message, "PredicateValidator You need to have at least 18 years. \n");
Assert.Pass();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Navegacao_botao_voltar
{
/*
IMPLEMENTACAO DO BOTAO VOLTAR
The real essence of using this technique is to implement SystemNavigationManager in a way so that you don't need to
write this code in every page but you can manage it throughout the App.
To do that, you need to make some changes in App.xaml.cs file of your App.
You need to add some code to your OnLaunched event handler.
ADICIONAR NO APP.XML AS SEGUINTES LINHAS:
METODO OnLaunched, ADICIONAR:
rootFrame.Navigated += RootFrame_Navigated;
// Register a handler for BackRequested events and set the
// visibility of the Back button
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
ADICIONAR DOIS EVENT HANDLERS
Now, add two event handlers in App.xaml.cs file as below which we've declared in above code.
private void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
// Each time a navigation event occurs, update the Back button's visibility
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
((Frame)sender).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
e.Handled = true;
rootFrame.GoBack();
}
}
DESTA FORMA, O BOTAO VOLTAR VAI ESTAR DISPONIVEL EM TODAS AS PAGINAS DA APLICACAO.
*/
sealed partial class App : Application
{
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
//BOTAO VOLTAR
//adicionar esta linha para implementar o botao voltar
rootFrame.Navigated += RootFrame_Navigated;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
Window.Current.Content = rootFrame;
// BOTAO VOLTAR
// Register a handler for BackRequested events and set the
// visibility of the Back button
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
}
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
Window.Current.Activate();
}
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
//BOTAO VOLTAR
private void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
// Each time a navigation event occurs, update the Back button's visibility
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
((Frame)sender).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
}
//BOTAO VOLTAR
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
e.Handled = true;
rootFrame.GoBack();
}
}
}
}
|
namespace E19_GroupedByGroupNameExtensions
{
using System;
using System.Linq;
using E09_StudentGroups;
public class GroupedByGroupNameExtensions
{
public static void Main(string[] args)
{
// Rewrite the previous using extension methods.
Console.WriteLine("Extension methods: ");
Console.WriteLine();
var selectStudentsExtension = StudentsList
.students
.OrderBy(st => StudentsList
.groups[st.GroupNumber]
.DepartmentName);
foreach (var student in selectStudentsExtension)
{
Console.WriteLine(string.Join(" - ", student.FullName,
StudentsList.groups[student.GroupNumber].DepartmentName));
}
Console.WriteLine();
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tools.Response.Json;
namespace Tools.Response
{
public class JsonResponse
{
/// <summary>
/// 状态码
/// </summary>
public ResponseStatus StatusCode { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string Message { get; set; }
/// <summary>
/// Convert To Json Result
/// </summary>
/// <param name="controller">控制器</param>
/// <returns>JsonResult</returns>
public Microsoft.AspNetCore.Mvc.JsonResult ToJsonResult(Microsoft.AspNetCore.Mvc.Controller controller)
{
return controller.JsonSuccess(this);
}
}
/// <summary>
/// 一个数据模型的 json result
/// </summary>
/// <typeparam name="T">数据模型</typeparam>
public class JsonResponse1<T>:JsonResponse
{
/// <summary>
/// 数据模型1
/// </summary>
public T JsonData { get; set; }
}
/// <summary>
/// 一个数据模型的 json result
/// </summary>
/// <typeparam name="T">数据模型1</typeparam>
/// <typeparam name="P">数据模型2</typeparam>
public class JsonResponse2<T, P> : JsonResponse1<T>
{
/// <summary>
/// 数据模型2
/// </summary>
public P JsonData1 { get; set; }
}
/// <summary>
/// 一个数据模型的 json result
/// </summary>
/// <typeparam name="T">数据模型1</typeparam>
/// <typeparam name="P">数据模型2</typeparam>
/// <typeparam name="H">数据模型3</typeparam>
public class JsonResponse3<T, P, H> : JsonResponse2<T,P>
{
/// <summary>
/// 数据模型3
/// </summary>
public H JsonData2 { get; set; }
}
/// <summary>
/// 一个数据模型的 json result
/// </summary>
/// <typeparam name="T">数据模型1</typeparam>
/// <typeparam name="P">数据模型2</typeparam>
/// <typeparam name="H">数据模型3</typeparam>
/// <typeparam name="I">数据模型4</typeparam>
public class JsonResponse4<T, P, H,I> : JsonResponse3<T,P,H>
{
/// <summary>
/// 数据模型4
/// </summary>
public H JsonData3 { get; set; }
}
/// <summary>
/// 一个数据模型的 json result
/// </summary>
/// <typeparam name="T">数据模型1</typeparam>
/// <typeparam name="P">数据模型2</typeparam>
/// <typeparam name="H">数据模型3</typeparam>
/// <typeparam name="I">数据模型4</typeparam>
/// <typeparam name="J">数据模型5</typeparam>
public class JsonResponse5<T, P, H,I,J> : JsonResponse4<T,P,H,I>
{
/// <summary>
/// 数据模型5
/// </summary>
public H JsonData4 { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Waffles;
using Waffles.UserControls;
public partial class webs_view : AdminModal
{
public override void Build()
{
SPWebCollection webs = WContext.GetWebs(Web);
Dictionary<string, string> web_lists = new Dictionary<string, string>();
WHTML.Table table = new WHTML.Table();
if (webs.Count > 0)
{
table = new WHTML.Table();
table.THEAD.Add("", "Web Title", "Pages", "Lists");
foreach (SPWeb web in webs)
{
string[] web_url = web.RootFolder.ServerRelativeUrl.Trim('/').Split('/');
string web_slug = web_url[web_url.Length - 1];
table.TBODY.Add(new WHTML.Table.TR(
new WHTML.Table.TR.TD(
"<a href='" + web.ServerRelativeUrl + "#/web-edit' class='edit' title='Edit'><i class='fa fa-edit'></i></a>",
"actions"
),
"<a href='" + web.ServerRelativeUrl + "'>" + web.Title + "</a>" + (web.Description.Length > 0 ? "<br>" + web.Description : ""),
web.Lists["Pages"].ItemCount,
web.Lists.Count
));
}
Modal.Body.Append(table);
}
else
Modal.Body.Append("<p>There are no sub webs in this web.</p>");
Modal.Label.Append("All Webs");
Modal.ButtonsLeft.Add(new WHTML.Button("New Web", "plus-circle", "#/web-new", "", "", false));
Modal.Size = WAdminModal.Sizes.Large;
}
} |
using System;
namespace View
{
public class OutputView
{
public void ShowStart()
{
Console.WriteLine("|-----------------------------------------|");
Console.WriteLine("|--------- Welkom bij Goudkoorts ---------|");
Console.WriteLine("|-----------------------------------------|");
Console.WriteLine();
Console.WriteLine("|---------------- Uitleg -----------------|");
Console.WriteLine("|--------- Druk op toets 1 t/m 5 ---------|");
Console.WriteLine("|-------- op de rails te wisselen --------|");
Console.WriteLine("|-----------------------------------------|");
Console.WriteLine();
Console.WriteLine("Druk op een toets om te beginnen.");
Console.ReadKey();
}
public void ShowGameOver(Model.GameBoard game)
{
Console.Clear();
Console.WriteLine("|-----------------------------------------|");
Console.WriteLine("|--------------- GAMEOVER ----------------|");
Console.WriteLine("|-----------------------------------------|");
Console.WriteLine("|------ Je hebt " + game.TotalScore.ToString() + " punten gescoord -------|");
Console.WriteLine();
Console.ReadLine();
}
public void UpdateBoard(Model.GameBoard game)
{
Console.Clear();
int nRows = game.Height;
int nCols = game.Width;
Model.Tile current = game.Origin;
Model.Tile neighbourBelow = current.TileBelow;
for (int r = 0; r < nRows; r++)
{
for (int c = 0; c < nCols; c++)
{
Console.Write(current.ToChar());
current = current.TileToRight;
}
current = neighbourBelow;
if (neighbourBelow != null)
{
neighbourBelow = current.TileBelow;
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("------------------------------------------");
Console.WriteLine("------- gebruik de toetsen 1 t/m 5 -------");
Console.WriteLine("----------- Jouw score: " + game.TotalScore.ToString() + " -----------");
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CyberPunkRPG
{
class Blind : GameObject
{
Rectangle position;
public Rectangle blindHitBox;
public bool isBlind = true;
public Blind(Vector2 pos, Rectangle position) : base(pos)
{
this.pos = pos;
this.position = position;
blindHitBox = position;
}
public override void Draw(SpriteBatch sb)
{
if (isBlind == true)
{
sb.Draw(AssetManager.blindTex, position, Color.White);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
static class StringBuilderExtensionMethods
{
//test
static void Main()
{
StringBuilder str = new StringBuilder();
str.Append("stringbuilder");
StringBuilder res = str.Substring(4, 9);
Console.WriteLine(res);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DMIPrivateServices.Model
{
public class LiveTemperature
{
private static LiveTemperature instance;
public double LiveTemp;
private LiveTemperature() { }
public static LiveTemperature Instance
{
get
{
if (instance == null)
{
instance = new LiveTemperature();
}
return instance;
}
}
}
} |
using System;
namespace Template
{
internal class Program
{
private static void Main(string[] args)
{
int cantidad = 0;
string tipo = string.Empty;
IPrimitiva calidad = null;
double total = 0;
Console.WriteLine("1-Barato, 2-Normal");
tipo = Console.ReadLine();
if (tipo == "1")
{
calidad = new Barato();
}
if (tipo == "2")
{
calidad = new Normal();
}
Console.WriteLine("Cuantos juguetes a producir?");
cantidad = Convert.ToInt32(Console.ReadLine());
var algoritmo = new Algoritmo();
total = algoritmo.MetodoTemplate(calidad, cantidad);
Console.WriteLine($"El total es {total}");
}
}
}
|
using System;
using StratCorp.CorpSMS.Entities;
using StratCorp.CorpSMS.ServiceLibrary.DataContracts;
namespace StratCorp.CorpSMS.ServiceLibrary.Translators
{
public static class MessageTranslator
{
public static MessageEntity MessageContractToMessageEntity(Message contract)
{
MessageEntity entity = new MessageEntity()
{
MessageId = contract.MessageId,
NumberTo = contract.Number,
Text = contract.Text,
OriginId = contract.OriginID,
UniqueId = contract.UniqueID,
DateCreated = contract.DateCreated
};
return entity;
}
public static Message MessageEntityToSendMessageContract(MessageEntity entity)
{
Message contract = new Message()
{
MessageId = entity.MessageId,
Number = entity.NumberTo,
Text = entity.Text,
EncryptedText = entity.EncryptedText,
OriginID = entity.OriginId,
UniqueID = entity.UniqueId,
DateCreated = entity.DateCreated
};
return contract;
}
public static DeliveryReport MessageEntityToDeliveryReport(MessageEntity entity)
{
if (entity == null) throw new ArgumentNullException("entity");
DeliveryReport report = new DeliveryReport()
{
//Number = entity.Number,
//Text = entity.Text,
//OriginID = entity.OriginId,
//UniqueID = entity.UniqueId
};
//if (entity.MessageDetail != null)
//{
// entity.MessageDetail.ForAll(detail =>
// {
// report.MessageStatus.Add(new MessageStatus()
// {
// Status = detail.StatusDescription,
// StatusDate = detail.StatusDate,
// Reason = detail.Reason
// });
// });
//}
return report;
}
}
}
|
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
using TableTopCrucible.Core.Models.ValueTypes;
namespace TableTopCrucible.Core.Models.Sources
{
[Serializable]
public struct LibraryLocation
{
public LibraryLocation(bool isPinned, string path, DateTime lastUse)
{
IsPinned = isPinned;
Path = path;
LastUse = lastUse;
}
[Reactive]public bool IsPinned { get; set; }
[Reactive]public string Path { get; set; }
[Reactive]public DateTime LastUse { get; set; }
}
}
|
using Ghost.Utility;
using System;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class RoleFollowInfo : IReuseableObject<Transform, RoleComplete, Vector3, int>, IReuseableObjectBase
{
public Transform transform;
public RoleComplete role;
public Vector3 offset;
public Vector3 tempOffset;
public int epID;
public Action<Transform, object> lostCallback;
public object lostCallbackArg;
public bool cpMode;
public bool reused
{
get;
set;
}
public void CallbackLost()
{
if (this.lostCallback != null)
{
this.lostCallback.Invoke(this.transform, this.lostCallbackArg);
}
}
public bool Update()
{
if (null == this.transform)
{
return false;
}
if (null == this.role || null == this.role.get_transform())
{
return false;
}
if (this.cpMode)
{
Transform transform = null;
if (0 < this.epID)
{
transform = this.role.GetCP(this.epID);
}
if (null == transform)
{
transform = this.role.get_transform();
}
this.transform.set_position(transform.get_position());
this.transform.set_rotation(transform.get_rotation());
this.transform.set_localScale(transform.get_lossyScale());
}
else if (0 < this.epID)
{
Transform eP = this.role.GetEP(this.epID);
if (null != eP)
{
this.transform.set_position(eP.get_position() + this.offset);
}
else
{
this.transform.set_position(this.role.get_transform().get_position() + this.tempOffset);
}
}
else
{
this.transform.set_position(this.role.get_transform().get_position() + this.offset);
}
return true;
}
public void Construct(Transform t, RoleComplete r, Vector3 o, int e)
{
this.transform = t;
this.role = r;
this.offset = o;
this.epID = e;
this.lostCallback = null;
this.lostCallbackArg = null;
this.cpMode = false;
}
public void Destruct()
{
this.transform = null;
this.role = null;
}
public void Destroy()
{
this.Destruct();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ViewEvent {
PlayerTurnLeft,
PlayerTurnRight,
PlayerTurnUp,
PlayerTurnDown,
CamClockwise,//镜头顺时针旋转
CamCounterClockwise//镜头逆时针旋转
}
|
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
namespace Yasl
{
public class PrimitiveSerializer<T> : StructSerializer<T>
where T : struct
{
public override void SerializeConstructor(ref T value, ISerializationWriter writer)
{
writer.WritePrimitive<T>(value);
}
public override void DeserializeConstructor(out T value, int version, ISerializationReader reader)
{
value = reader.ReadPrimitive<T>();
}
}
}
|
/*
* This class is used to demonstrate the concept of Inheritence.
* This inherits the class Company.
*
* Please notice that the methods in Company class is re-used,
* abstract classes are impemented
* and virtual methods are over-riddedn.
*
* Below cocepts will be demoed using this file and it's interface:
* - Inheritence
* - Abstract class
* - Virtual Methods
* - Method over-riding
*/
using System.Collections.Generic;
namespace CSBasic
{
class CompanyIT : Company
{
public CompanyIT(int id, string name) : base(id, name)
{
CompanyID = id;
CompanyName = name;
EmployeeList = new List<int> { 100, 101, 102, 103 };
}
private List<int> EmployeeList;
// This is a method to add an employee number to employee database
public override void AddEmployee(int employeeNumber)
{
EmployeeList.Add(employeeNumber);
}
// This method lists the employee count
public override void GetEmployeeCount()
{
System.Console.WriteLine($"No of employees in the company is {EmployeeList.Count}");
}
// This method will list all the employee numbers
public override void ListEmployeeNumbers()
{
System.Console.WriteLine($"Listing the employee for {CompanyName}");
foreach (var empNo in EmployeeList)
{
System.Console.WriteLine(empNo);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using PST_BL;
namespace PST_SI
{
public class PSTInterface
{
public PSTInterface()
{
// TODO: Add constructor logic here
}
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(PSTInterface));
/// <summary>
/// This Method is a interface to searchCriteria function
/// </summary>
/// <param name="searchCriteria_SI"></param>
/// <returns></returns>
/// <history>
/// Hari haran 07/05/2012 created
/// </history>
public PST_OutputEntity employeeSearch_SI(PST_InputEntity searchCriteria_SI)
{
try
{
logger.Info("Control Flow : Method - employeeSearch_SI Start");
logger.DebugFormat("Employee Name : {0} ",searchCriteria_SI.name);
PST_BAL search_BAL = new PST_BAL();
return (search_BAL.employeeSearch_BAL(searchCriteria_SI));
}
catch (OracleException dbEx)
{
logger.Fatal("Database Exception At PSTInterface - searchCriteria_SI : " + dbEx.Message.ToString());
logger.Error("Control Flow : Method - searchCriteria_SI Stop");
throw dbEx;
}
catch (Exception ex)
{
logger.Fatal("Exception At PSTInterface - searchCriteria_SI : " + ex.Message.ToString());
logger.Error("Control Flow : Method - searchCriteria_SI Stop");
throw ex;
}
}
}
}
|
using GeneticAlgorithm.Genes;
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Immutable;
using System.Linq;
namespace GeneticAlgorithm
{
public abstract class OrderMaintainingChromosome<TSol, TGene, TFitness> : GeneMutatingChromosome<TSol, TGene, TFitness> where TGene : Gene<TGene> where TFitness : IComparable<TFitness> where TSol : OrderMaintainingChromosome<TSol, TGene, TFitness>
{
public OrderMaintainingChromosome(IImmutableList<TGene> genes) : base(genes) {
}
private static readonly Random numberGenerator = new Random();
protected sealed override IImmutableList<TGene> crossGenesWith(IImmutableList<TGene> otherGenes) {
if(this.Genes.Count != otherGenes.Count) {
throw new InvalidOperationException("Each chromosome must have the same number of genes to cross over");
}
int crossPoint = numberGenerator.Next(Genes.Count);
if(crossPoint == 0) { //check if no is actually no crossing needed
return otherGenes;
}
if(crossPoint == this.Genes.Count) {
return this.Genes;
}
return this.Genes.Take(crossPoint).Concat(otherGenes.Skip(crossPoint)).ToImmutableList();
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Globalization;
//using System.IO;
//using System.Xml;
//using System.Linq;
//using System.Text.RegularExpressions;
//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using ORTRulesEngine;
//using ORTRulesEngine.Entities;
//namespace UnitTestProject1
//{
// [TestClass]
// public class UnitTest1
// {
// [TestMethod]
// public void Unique_Rule_Test()
// {
// //IList<string> statesList = new List<string> { "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" };
// IList<string> statesList = new List<string> {"AL", "AK", "AZ", "AR"};
// IList<string> underwriterList = new List<string> {"AGTIC", "ORNTIC"};
// IList<string> letterTypeList = new List<string> {"ALTA8", "AL00"};
// IList<string> transactionTypeList = new List<string> {"Blanket", "Cash", "Single"};
// var iTestCounter = 0;
// var testStart = DateTime.Now.Ticks;
// foreach (string state in statesList)
// {
// foreach (var underwriter in underwriterList)
// {
// foreach (var transactionType in transactionTypeList)
// {
// foreach (var letterType in letterTypeList)
// {
// iTestCounter++;
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// Assert.IsTrue(Get_Statisfying_Groups(cpl, "CPL_Letter_File_Name", "CPL"));
// }
// }
// }
// }
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed " + iTestCounter + " CPL Tests in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Test_All_Oututs()
// {
// IList<string> statesList = new List<string>
// {
// "AL",
// "AK",
// "AZ",
// "AR",
// "CA",
// "CO",
// "CT",
// "DE",
// "FL",
// "GA",
// "HI",
// "ID",
// "IL",
// "IN",
// "IA",
// "KS",
// "KY",
// "LA",
// "ME",
// "MD",
// "MA",
// "MI",
// "MN",
// "MS",
// "MO",
// "MT",
// "NE",
// "NV",
// "NH",
// "NJ",
// "NM",
// "NY",
// "NC",
// "ND",
// "OH",
// "OK",
// "OR",
// "PA",
// "RI",
// "SC",
// "SD",
// "TN",
// "TX",
// "UT",
// "VT",
// "VA",
// "WA",
// "WV",
// "WI",
// "WY"
// };
// //IList<string> statesList = new List<string> { "AL", "AK", "AZ", "AR" };
// IList<string> underwriterList = new List<string> {"AGTIC", "ORNTIC"};
// IList<string> letterTypeList = new List<string> {"ALTA8", "AL00"};
// IList<string> transactionTypeList = new List<string> {"Blanket", "Cash", "Single"};
// var iTestCounter = 0;
// var testStart = DateTime.Now.Ticks;
// IDictionary<CPLLetterBodyRule, RuleInformation> ruleInformationDictionary =
// new Dictionary<CPLLetterBodyRule, RuleInformation>();
// foreach (string state in statesList)
// {
// foreach (var underwriter in underwriterList)
// {
// foreach (var transactionType in transactionTypeList)
// {
// foreach (var letterType in letterTypeList)
// {
// iTestCounter++;
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// Write_Results(cpl);
// }
// }
// }
// }
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/TimeSpan.TicksPerMillisecond);
// Console.WriteLine("Executed " + iTestCounter + " CPL Tests in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_ALTA8_B_2005_12()
// {
// var expectedResult = "ALTA8-B-2005-12";
// //var state = "AK";
// //var underwriter = "ORNTIC";
// //var transactionType = "Blanket";
// //var letterType = "ALTA8";
// var cpl = new CPLAgentDisplayRule();
// cpl.TransactionPropertyState = "AR";
// cpl.LetterType = "AR01";
// var testStart = DateTime.Now.Ticks;
// var result = cpl.CPLAgentDisplay;
// //Assert.AreEqual(expectedResult, cpl.CPLAgentDisplay);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_ALTA8_CASH_ORNTIC()
// {
// var expectedResult = "ALTA8-CASH-ORNTIC";
// var state = "AK";
// var underwriter = "ORNTIC";
// var transactionType = "Cash";
// var letterType = "ALTA8";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_ALTA8_S_2015_12()
// {
// var expectedResult = "ALTA8-S-2015-12";
// var state = "AK";
// var underwriter = "ORNTIC";
// var transactionType = "Single";
// var letterType = "ALTA8";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AL_00_AGT_C()
// {
// var expectedResult = "AL-00-AGT";
// var state = "AL";
// var underwriter = "AGTIC";
// var transactionType = "Cash";
// var letterType = "AL00";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AL_00_AGT_S()
// {
// var expectedResult = "AL-00-AGT";
// var state = "AL";
// var underwriter = "AGTIC";
// var transactionType = "Single";
// var letterType = "AL00";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AL_00_C()
// {
// var expectedResult = "AL-00";
// var state = "AL";
// var underwriter = "ORNTIC";
// var transactionType = "Cash";
// var letterType = "AL00";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AL_00_S()
// {
// var expectedResult = "AL-00";
// var state = "AL";
// var underwriter = "ORNTIC";
// var transactionType = "Single";
// var letterType = "AL00";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AR_01_AGT_C()
// {
// var expectedResult = "AR-01-AGT";
// var state = "AR";
// var underwriter = "AGTIC";
// var transactionType = "Cash";
// var letterType = "AR01";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AR_01_AGT_S()
// {
// var expectedResult = "AR-01-AGT";
// var state = "AR";
// var underwriter = "AGTIC";
// var transactionType = "Single";
// var letterType = "AR01";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AR_01_S()
// {
// var expectedResult = "AR-01-AGT";
// var state = "AR";
// var underwriter = "AGTIC";
// var transactionType = "Single";
// var letterType = "AR01";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_AR_01_C()
// {
// var expectedResult = "AR-01-AGT";
// var state = "AR";
// var underwriter = "AGTIC";
// var transactionType = "Cash";
// var letterType = "AR01";
// var cpl = new CPLLetterBodyRule(state: state, transactionType: transactionType,
// underwriter: underwriter, letterType: letterType);
// var testStart = DateTime.Now.Ticks;
// Assert.AreEqual(expectedResult, cpl.CPL_Letter_File_Name);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// private bool Get_Statisfying_Groups(CPLLetterBodyRule cpl, string property, string domain)
// {
// var target = new RuleEngine<CPLLetterBodyRule>();
// var result = target.Get_Satisfying_Specfications(cpl, property, domain);
// Console.WriteLine("---");
// Console.WriteLine(string.Concat("Transaction: '", cpl.TransactionType, "'"));
// Console.WriteLine(string.Concat("State: '", cpl.State, "'"));
// Console.WriteLine(string.Concat("Underwriter: '", cpl.Underwriter, "'"));
// Console.WriteLine(string.Concat("Letter Type '", cpl.LetterType, "'"));
// Console.WriteLine(result.Count > 0
// ? string.Concat("Satisfied by Rule Group: ", string.Join(";", result))
// : "Satisfied by Rule Group: None");
// Console.WriteLine("---");
// Console.WriteLine();
// return result.Count < 2;
// }
// private void Write_Results(CPLLetterBodyRule cpl)
// {
// // Find the matching cpl in the dictionary
// Console.WriteLine("---");
// Console.WriteLine("CPL Rule Results: ");
// Console.WriteLine(string.Concat("Transaction: '", cpl.TransactionType, "'"));
// Console.WriteLine(string.Concat("State: '", cpl.State, "'"));
// Console.WriteLine(string.Concat("Underwriter: '", cpl.Underwriter, "'"));
// Console.WriteLine(string.Concat("Letter Type '", cpl.LetterType, "'"));
// Console.WriteLine(string.Concat("Results '", cpl.CPL_Letter_File_Name, "'"));
// Console.WriteLine("---");
// Console.WriteLine();
// }
// [TestMethod]
// public void
// Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_True_For_IsOrtis_And_IsParent_And_IsNational
// ()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = true;
// mergeData.Agent.IsORTRIS = true;
// mergeData.Agent.isNational = true;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart)/10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_True_For_IsOrtis_And_IsParent_And_Not_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = true;
// mergeData.Agent.IsORTRIS = true;
// mergeData.Agent.isNational = false;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_True_For_Not_IsOrtis_And_IsParent_And_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = true;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = true;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_True_For_IsOrtis_And_Not_IsParent_And_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = true;
// mergeData.Agent.isNational = true;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_True_For_Not_IsOrtis_And_Not_IsParent_And_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = true;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_False_For_Not_IsOrtis_And_Not_IsParent_And_Not_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsFalse(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_False_For_IsOrtis_And_Not_IsParent_And_Not_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = true;
// mergeData.Agent.isNational = false;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsFalse(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Ortis_Parent_Or_National_Should_Be_False_For_Not_IsOrtis_And_IsParent_And_Not_IsNational()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = true;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsFalse(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_Is_Parent_Should_Be_True()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = true;
// mergeData.Agent.IsORTRIS = true;
// mergeData.Agent.isNational = true;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.IsOrtisParentOrNational;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Not_IsOrtisParentOrNational_And_Blanket_Letter_Should_Be_False()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NNJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Blanket;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.HideAgentInfoForNJLetter;
// Assert.IsFalse(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Not_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_No_Closing_Attorney_Should_Be_False()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NNJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.HideAgentInfoForNJLetter;
// Assert.IsFalse(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Not_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_Has_Closing_Attorney_Should_Be_True()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// // Set LetterTransaction Type
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// // Set the ClosingAttorney
// mergeData.ClosingAttorney = new ClosingAttorneyInformation();
// mergeData.ClosingAttorney.NameLine1 = "Test";
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.HideAgentInfoForNJLetter;
// Assert.IsTrue(bool.Parse(result));
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Not_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_Has_Closing_Attorney_Should_Be_Empty()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// // Set LetterTransaction Type
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// // Set the ClosingAttorney
// mergeData.ClosingAttorney = new ClosingAttorneyInformation();
// mergeData.ClosingAttorney.NameLine1 = "Test";
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.CPLAgentDisplay;
// Assert.AreEqual(result, string.Empty);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Not_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_No_Closing_Attorney_Should_Not_Be_Empty()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// // Set LetterTransaction Type
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.CPLAgentDisplay;
// Assert.AreNotEqual(result, string.Empty);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_Not_NJ00_And_Not_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_Has_Closing_Attorney_Should_Not_Be_Empty()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is false
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = false;
// // Make sure the lettertype is NJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.AL00;
// mergeData.LetterType = letterType;
// // Set LetterTransaction Type
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// // Set the ClosingAttorney
// mergeData.ClosingAttorney = new ClosingAttorneyInformation();
// mergeData.ClosingAttorney.NameLine1 = "Test";
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.CPLAgentDisplay;
// Assert.AreNotEqual(result, string.Empty);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// [TestMethod]
// public void Specification_Pattern_Agent_Info_For_Letter_Type_Is_NJ00_And_Is_IsOrtisParentOrNational_And_Not_Blanket_Letter_And_Has_Closing_Attorney_Should_Not_Be_Empty()
// {
// //IsOrtisParentOrNational
// var mergeData = new FakeMergeData();
// // Make sure IsOrtrisParentOrNational is True
// // (IsParent && IsORTRIS) || IsNational
// mergeData.Agent = new Agent();
// mergeData.Agent.IsParent = false;
// mergeData.Agent.IsORTRIS = false;
// mergeData.Agent.isNational = true;
// // Make sure the lettertype is NJ00
// var letterType = new LetterType();
// letterType.Code = LetterTypeValue.NJ00;
// mergeData.LetterType = letterType;
// // Set LetterTransaction Type
// mergeData.ValidatedLetterRequest.LetterTransactionType = LetterTransactionType.Single;
// // Set the ClosingAttorney
// mergeData.ClosingAttorney = new ClosingAttorneyInformation();
// mergeData.ClosingAttorney.NameLine1 = "Test";
// var agentRules = new FakeAgentDisplayRule(mergeData);
// var testStart = DateTime.Now.Ticks;
// var result = agentRules.CPLAgentDisplay;
// Assert.AreNotEqual(result, string.Empty);
// var testEnd = DateTime.Now.Ticks;
// var testTotal = ((testEnd - testStart) / 10000);
// Console.WriteLine("Executed test in " + testTotal + " milli seconds.");
// }
// }
//}
|
using UnityEngine;
public class PlatformSpawner : MonoBehaviour
{
[SerializeField] private GameObject _platform;
[SerializeField] private Transform _generationPoint;
private float _platformLength;
private void Awake()
{
_platformLength = _platform.transform.localScale.z;
}
private void Update()
{
if (transform.position.z < _generationPoint.position.z)
{
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + _platformLength);
Instantiate(_platform, transform.position, Quaternion.identity, transform.parent);
}
}
}
|
using System;
using System.Runtime.Serialization;
using FluentAssertions;
using NUnit.Framework;
using Utilities.NET.Extensions;
namespace Utilities.NET.Tests.Extensions
{
public class EnumExtensionsTests : UnitTestBase
{
public enum FooEnum
{
Foo = 0,
Bar = 1,
Lol = 3,
Not = 5,
Ping = 10,
[EnumMember(Value = "Panser")]
Super,
[EnumMember(Value = "Bio")]
Bio
}
public enum BarEnum
{
Bar = 0,
Foo = 1,
Lol = 4,
[EnumMember(Value = "Ping")]
Pong = 20,
[EnumMember(Value = "Panser")]
Mann,
[EnumMember(Value = "Avfall")]
Bio
}
[Test]
[TestCase(FooEnum.Foo, ExpectedResult = BarEnum.Bar)]
[TestCase(FooEnum.Bar, ExpectedResult = BarEnum.Foo)]
[TestCase(FooEnum.Lol, ExpectedResult = BarEnum.Lol)]
[TestCase(FooEnum.Ping, ExpectedResult = BarEnum.Pong)]
[TestCase(FooEnum.Super, ExpectedResult = BarEnum.Mann)]
public BarEnum ToEnum(FooEnum fooEnum)
{
return fooEnum.Map<BarEnum>();
}
[Test]
[TestCase(FooEnum.Not)]
[TestCase(FooEnum.Bio)] //Both FooEnum.Bio and BarEnum.Bio has EnumMember set, and therefore will only compare those and not the ToString representation.
public void ToEnumShouldThrowException(FooEnum fooEnum)
{
Action action = () => fooEnum.Map<BarEnum>();
action.Should().Throw<ArgumentException>();
}
}
} |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OmniSharp.Extensions.JsonRpc.Generators.Contexts;
namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies
{
internal class HandlerRegistryActionContextRunnerStrategy : IExtensionMethodGeneratorStrategy
{
private readonly ImmutableArray<IExtensionMethodContextGeneratorStrategy> _strategies;
public HandlerRegistryActionContextRunnerStrategy(ImmutableArray<IExtensionMethodContextGeneratorStrategy> strategies)
{
_strategies = strategies;
}
public IEnumerable<MemberDeclarationSyntax> Apply(SourceProductionContext context, GeneratorData item)
{
foreach (var diagnostic in item.JsonRpcAttributes.HandlerRegistryDiagnostics)
{
context.ReportDiagnostic(diagnostic);
}
return item.JsonRpcAttributes.HandlerRegistries
.Select(
registry => new ExtensionMethodContext(
item.JsonRpcAttributes.GenerateHandlerMethods!.Data, item.TypeDeclaration, item.TypeSymbol, registry, item.JsonRpcAttributes.HandlerRegistries
) { IsRegistry = true }
)
.SelectMany(_ => _strategies, (actionContext, strategy) => new { actionContext, strategy })
.SelectMany(@t => @t.strategy.Apply(context, @t.actionContext, item));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObserverPattern
{
public class WeatherData : Subject
{
private List<Observer> observers { get; set; }
private float temperature { get; set; }
private float humidity { get; set; }
private float pressure { get; set; }
public WeatherData()
{
observers = new List<Observer>();
}
public void RegisterObserver(Observer o)
{
observers.Add(o);
}
public void RemoveObserver(Observer o)
{
if (observers.Contains(o))
observers.Remove(o);
}
public void NotifyObservers()
{
foreach(Observer obs in observers)
{
obs.Update(temperature, humidity, pressure);
}
}
public void MeasurementsChanged()
{
NotifyObservers();
}
public void SetMeasurements(float t, float h, float p)
{
this.temperature = t;
this.humidity = h;
this.pressure = p;
MeasurementsChanged();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToDoApp.Db;
using ToDoApp.Db.Domain;
using ToDoApp.Db.Extensions;
namespace ToDoApp.Api.Repositories
{
public class ElementRepository : IElementRepository
{
private readonly ToDoAppContext _context;
public ElementRepository(ToDoAppContext context)
{
_context = context;
}
public async Task<bool> Add(ToDoElement element)
{
_context.ToDoElements.Add(element);
return await _context.SaveChangesAsync() > 0;
}
public async Task<ICollection<ToDoElement>> GetForUser(Guid userId, string phrase, bool? isFinished)
{
return await _context
.ToDoElements
.Where(e => e.ToDoList.UserId == userId)
.SearchByTitle(phrase)
.FilterByFinishedStatus(isFinished)
.ToListAsync();
}
public async Task<ToDoElement> GetById(Guid id)
{
return await _context.ToDoElements.SingleOrDefaultAsync(e => e.Id == id);
}
public async Task<bool> Remove(ToDoElement element)
{
_context.Remove(element);
return await _context.SaveChangesAsync() > 0;
}
public async Task<bool> Update(ToDoElement element)
{
return await _context.SaveChangesAsync() > 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace AutoBazar
{
public class BusDB : MenuProperties
{
public static List<DataBus> car = new List<DataBus>();
public static int selectMotorType = 0;
public static int maxMotorType = Enum.GetNames(typeof(DataBus.MotorTypeEnum)).Length;
public static int selectColorType = 0;
public static int maxColorType = Enum.GetNames(typeof(DataBus.ColorTypeEnum)).Length;
public static int selectGearBoxType = 0;
public static int maxGearBoxType = Enum.GetNames(typeof(DataBus.GearBoxTypeEnum)).Length;
public static int selectTypeCar = 0;
public static int maxTypeCar = Enum.GetNames(typeof(DataBus.TypeCarEnum)).Length;
public static int selectFuelType = 0;
public static int maxFuelType = Enum.GetNames(typeof(DataBus.FuelTypeEnum)).Length;
public BusDB()
{
Console.Clear();
DrawDataCar();
}
public static void CreateNewCar()
{
Console.Clear();
if (car == null)
{
car = new List<DataBus>();
}
int selectItemID = 0;
string name = string.Empty;
string textPref = string.Empty;
string fuel = string.Empty;
int power = 0;
int valueInCm = 0;
int loadCapacity = 0;
int capacity = 0;
do
{
if (selectMotorType > maxMotorType)
{
selectMotorType = maxMotorType;
}
if (selectColorType > maxColorType)
{
selectColorType = maxColorType;
}
if (selectGearBoxType > maxGearBoxType)
{
selectGearBoxType = maxGearBoxType;
}
if (selectTypeCar > maxTypeCar)
{
selectTypeCar = maxTypeCar;
}
if (selectFuelType > maxFuelType)
{
selectFuelType = maxFuelType;
}
CheckStringSelectBusEnum(out string motorType, out string colorType, out string gearBoxType,
out string typeCar, out string fuelType, selectMotorType, selectColorType, selectGearBoxType,
selectFuelType, selectTypeCar);
Console.Clear();
WriteTextWithCursorPosition("Autobusy", 1, ConsoleColor.White, ConsoleColor.Black);
WriteTextWithCursorPosition("Vytvoření vozidla", 2, ConsoleColor.White, ConsoleColor.Black);
WriteButton("Jméno - " + name, 0, 0, selectItemID);
WriteButton("typ karoserie - " + typeCar, 1, 1, selectItemID);
WriteButton("Síla motoru - " + power, 2, 2, selectItemID);
WriteButton("Objem motoru v cm - " + valueInCm, 3, 3, selectItemID);
WriteButton("Převodovka - " + gearBoxType, 4, 4, selectItemID);
WriteButton("Barva - " + colorType, 5, 5, selectItemID);
WriteButton("typ motoru - " + motorType, 6, 6, selectItemID);
WriteButton("typ paliva - " + fuelType, 7, 7, selectItemID);
WriteButton("Kapacita v tunech - " + loadCapacity, 8, 8, selectItemID);
WriteButton("Kapacita cestujících - " + capacity, 9, 9, selectItemID);
WriteButton("Odejít", 10, 10, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
WriteButton("Vymazat", 11, 11, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
ConsoleKeyInfo ans = Console.ReadKey(true);
ConsoleTextSelect(0, 11, ans, ref selectItemID);
ConsoleTypeSelect(0, maxMotorType, ans, ref selectMotorType, 6, selectItemID);
ConsoleTypeSelect(0, maxColorType, ans, ref selectColorType, 5, selectItemID);
ConsoleTypeSelect(0, maxGearBoxType, ans, ref selectGearBoxType, 4, selectItemID);
ConsoleTypeSelect(0, maxTypeCar, ans, ref selectTypeCar, 1, selectItemID);
ConsoleTypeSelect(0, maxFuelType, ans, ref selectFuelType, 7, selectItemID);
if (ans.Key == ConsoleKey.Enter)
{
switch (selectItemID)
{
case 0:
WriteToButton(0, "Jméno - ");
name = Console.ReadLine();
break;
case 2:
WriteToButton(2, "Síla motoru - ");
power = int.Parse(Console.ReadLine());
break;
case 3:
WriteToButton(3, "Objem motoru v cm - ");
valueInCm = int.Parse(Console.ReadLine());
break;
case 9:
DataBus addCar = new DataBus
{
FuelType = (DataBus.FuelTypeEnum)selectFuelType,
NameText = name,
BusType = (DataBus.TypeBusEnum)selectTypeCar,
MotorPowerInKW = power,
MotorValueInCm = valueInCm,
GearType = (DataCar.GearBoxTypeEnum)selectGearBoxType,
Color = (DataCar.ColorTypeEnum)selectColorType,
MotorType = (DataCar.MotorTypeEnum)selectMotorType,
LoadCapacity = loadCapacity,
Capacity = capacity
};
car.Add(addCar);
Console.Clear();
string jsonCar = JsonConvert.SerializeObject(car);
File.WriteAllText(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveBus.txt"), jsonCar);
return;
case 10:
Console.Clear();
return;
default:
break;
}
}
} while (true);
}
static void DrawDataCar()
{
bool enableArrow = true;
Console.Clear();
if (!File.Exists(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveBus.txt")))
{
Directory.CreateDirectory(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects"));
FileStream DB = new FileStream(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveCargoCar.txt"), FileMode.Create);
DB.Close();
//File.Create(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveBus.txt"));
DataBus newCar = new DataBus();
string jsonCarNew = JsonConvert.SerializeObject(newCar);
File.WriteAllText(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveBus.txt"), jsonCarNew);
CreateNewCar();
}
else
{
string jsonCar = File.ReadAllText(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveBus.txt"));
List<DataBus> deserializedCar = JsonConvert.DeserializeObject<List<DataBus>>(jsonCar);
car = deserializedCar;
}
int selectItemID = 0;
int selectCar = 0;
if (car == null || car.Count == 0)
{
CreateNewCar();
}
else
{
do
{
if (selectMotorType > maxMotorType)
{
selectMotorType = maxMotorType;
}
if (selectColorType > maxColorType)
{
selectColorType = maxColorType;
}
if (selectGearBoxType > maxGearBoxType)
{
selectGearBoxType = maxGearBoxType;
}
if (selectTypeCar > maxTypeCar)
{
selectTypeCar = maxTypeCar;
}
if (selectFuelType > maxFuelType)
{
selectFuelType = maxFuelType;
}
WriteTextWithCursorPosition("Autobusy", 1, ConsoleColor.White, ConsoleColor.Black);
WriteTextWithCursorPosition("Vykreslení seznamu", 2, ConsoleColor.White, ConsoleColor.Black);
WriteButton("Jméno - " + car[selectCar].NameText, 0, 0, selectItemID);
WriteButton("typ karoserie - " + car[selectCar].BusType, 1, 1, selectItemID);
WriteButton("Síla motoru - " + car[selectCar].MotorPowerInKW + " KW|Koně - " + car[selectCar].MotorPowerInKW * 1.34102209f, 2, 2, selectItemID);
WriteButton("Objem motoru v cm - " + car[selectCar].MotorValueInCm, 3, 3, selectItemID);
WriteButton("Převodovka - " + car[selectCar].GearType, 4, 4, selectItemID);
WriteButton("Barva - " + car[selectCar].Color, 5, 5, selectItemID);
WriteButton("typ motoru - " + car[selectCar].MotorType, 6, 6, selectItemID);
WriteButton("typ paliva - " + car[selectCar].FuelType, 7, 7, selectItemID);
WriteButton("Kapacita v tunech - " + car[selectCar].LoadCapacity, 8, 8, selectItemID);
WriteButton("Kapacita cestujících - " + car[selectCar].Capacity, 9, 9, selectItemID);
WriteButton("Odejít", 10, 10, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
WriteButton("Vymazat", 11, 11, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
ConsoleKeyInfo ans = Console.ReadKey(true);
ConsoleTextSelect(0, 11, ans, ref selectItemID);
switch (selectItemID)
{
case 1:
ConsoleTypeSelect(0, maxTypeCar, ans, ref selectTypeCar, 1, selectItemID);
car[selectCar].BusType = (DataBus.TypeBusEnum)selectTypeCar;
SaveDataBus(car);
enableArrow = false;
break;
case 4:
ConsoleTypeSelect(0, maxGearBoxType, ans, ref selectGearBoxType, 4, selectItemID);
enableArrow = false;
break;
case 5:
ConsoleTypeSelect(0, maxColorType, ans, ref selectColorType, 5, selectItemID);
enableArrow = false;
break;
case 6:
ConsoleTypeSelect(0, maxMotorType, ans, ref selectMotorType, 6, selectItemID);
enableArrow = false;
break;
case 7:
ConsoleTypeSelect(0, maxFuelType, ans, ref selectFuelType, 7, selectItemID);
enableArrow = false;
break;
default:
enableArrow = true;
break;
}
if (ans.Key == ConsoleKey.Enter)
{
switch (selectItemID)
{
case 0:
WriteToButton(0, "Jméno - ");
car[selectCar].NameText = Console.ReadLine();
SaveDataBus(car);
break;
case 10:
Console.Clear();
return;
case 11:
if (car.Count == 1)
{
car.RemoveAt(selectCar);
SaveDataBus(car);
return;
}
else
{
car.RemoveAt(selectCar);
SaveDataBus(car);
Console.Clear();
break;
}
default:
break;
}
}
else if (ans.Key == ConsoleKey.RightArrow && enableArrow)
{
if (selectCar == car.Count)
{
CreateNewCar();
Console.Clear();
}
else
{
selectCar++;
if (selectCar == car.Count)
{
Console.Clear();
CreateNewCar();
}
Console.Clear();
}
}
else if (ans.Key == ConsoleKey.LeftArrow && enableArrow)
{
if (selectCar != 0)
{
selectCar--;
Console.Clear();
}
}
} while (true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using Karkas.Core.DataUtil;
using Karkas.Ornek.TypeLibrary;
using Karkas.Ornek.TypeLibrary.Ornekler;
namespace Karkas.Ornek.Dal.Ornekler
{
public partial class DenemeGuidIdentityDal : BaseDal<DenemeGuidIdentity>
{
public override string DatabaseName
{
get
{
return "Karkas.Ornek";
}
}
protected override void identityKolonDegeriniSetle(DenemeGuidIdentity pTypeLibrary,long pIdentityKolonValue)
{
pTypeLibrary.DenemeNo = (int )pIdentityKolonValue;
}
protected override string SelectCountString
{
get
{
return @"SELECT COUNT(*) FROM ORNEKLER.DENEME_GUID_IDENTITY";
}
}
protected override string SelectString
{
get
{
return @"SELECT DenemeKey,DenemeNo,DenemeKolon FROM ORNEKLER.DENEME_GUID_IDENTITY";
}
}
protected override string DeleteString
{
get
{
return @"DELETE FROM ORNEKLER.DENEME_GUID_IDENTITY WHERE DenemeKey = @DenemeKey ";
}
}
protected override string UpdateString
{
get
{
return @"UPDATE ORNEKLER.DENEME_GUID_IDENTITY
SET
DenemeKolon = @DenemeKolon
WHERE
DenemeKey = @DenemeKey
";
}
}
protected override string InsertString
{
get
{
return @"INSERT INTO ORNEKLER.DENEME_GUID_IDENTITY
(DenemeKey,DenemeKolon)
VALUES
(@DenemeKey,@DenemeKolon);SELECT scope_identity();";
}
}
public DenemeGuidIdentity SorgulaDenemeKeyIle(Guid p1)
{
List<DenemeGuidIdentity> liste = new List<DenemeGuidIdentity>();
SorguCalistir(liste,String.Format(" DenemeKey = '{0}'", p1));
if (liste.Count > 0)
{
return liste[0];
}
else
{
return null;
}
}
protected override bool IdentityVarMi
{
get
{
return true;
}
}
protected override bool PkGuidMi
{
get
{
return true;
}
}
public override string PrimaryKey
{
get
{
return "DenemeKey";
}
}
public virtual void Sil(Guid DenemeKey)
{
DenemeGuidIdentity satir = new DenemeGuidIdentity();
satir.DenemeKey = DenemeKey;
base.Sil(satir);
}
protected override void ProcessRow(IDataReader dr, DenemeGuidIdentity satir)
{
satir.DenemeKey = dr.GetGuid(0);
satir.DenemeNo = dr.GetInt32(1);
satir.DenemeKolon = dr.GetString(2);
}
protected override void InsertCommandParametersAdd(DbCommand cmd, DenemeGuidIdentity satir)
{
ParameterBuilder builder = Template.getParameterBuilder();
builder.Command = cmd;
builder.parameterEkle("@DenemeKey",SqlDbType.UniqueIdentifier, satir.DenemeKey);
builder.parameterEkle("@DenemeKolon",SqlDbType.VarChar, satir.DenemeKolon,50);
}
protected override void UpdateCommandParametersAdd(DbCommand cmd, DenemeGuidIdentity satir)
{
ParameterBuilder builder = Template.getParameterBuilder();
builder.Command = cmd;
builder.parameterEkle("@DenemeKey",SqlDbType.UniqueIdentifier, satir.DenemeKey);
builder.parameterEkle("@DenemeKolon",SqlDbType.VarChar, satir.DenemeKolon,50);
}
protected override void DeleteCommandParametersAdd(DbCommand cmd, DenemeGuidIdentity satir)
{
ParameterBuilder builder = Template.getParameterBuilder();
builder.Command = cmd;
builder.parameterEkle("@DenemeKey",SqlDbType.UniqueIdentifier, satir.DenemeKey);
}
public override string DbProviderName
{
get
{
return "System.Data.SqlClient";
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Knife : Item
{
public Collider2D swingCol;
public SpriteRenderer swingSR;
private LookAtMouse LAM;
public SpriteRenderer knife2;
private bool onCooldown;
private Coroutine swingCoroutine = null;
protected override void Awake()
{
base.Awake();
base.SetItemName("Knife");
LAM = GetComponentInChildren<LookAtMouse>();
}
public override void EquipItem()
{
base.EquipItem();
PR.SetSprites(PR.GetCurrentCharacterSprites().frontOneArm1, PR.GetCurrentCharacterSprites().backOneArm1);
}
public override void UnequipItem()
{
base.UnequipItem();
PR.SetSprites(PR.GetCurrentCharacterSprites().frontIdle, PR.GetCurrentCharacterSprites().backIdle);
if (swingCoroutine != null)
{
StopCoroutine(swingCoroutine);
swingCol.enabled = false;
swingSR.enabled = false;
LAM.enabled = true;
onCooldown = false;
knife2.enabled = false;
}
}
public override void ItemLeftClick()
{
if (!onCooldown)
swingCoroutine = StartCoroutine(Swipe());
}
private IEnumerator Swipe()
{
PR.SetSprites(PR.GetCurrentCharacterSprites().frontOneArm2, PR.GetCurrentCharacterSprites().backOneArm2);
itemSR.enabled = false;
knife2.enabled = true;
AudioManager.instance.Play("KnifeSwing");
onCooldown = true;
swingCol.enabled = true;
swingSR.enabled = true;
LAM.enabled = false;
yield return new WaitForSeconds(0.05f); //Disable the collider quickly to prevent unintended additional hits
swingCol.enabled = false;
yield return new WaitForSeconds(0.1f); //Disable everything else after the attack ends
swingSR.enabled = false;
LAM.enabled = true;
PR.SetSprites(PR.GetCurrentCharacterSprites().frontOneArm1, PR.GetCurrentCharacterSprites().backOneArm1);
itemSR.enabled = true;
knife2.enabled = false;
yield return new WaitForSeconds(0.125f); //Cooldown
onCooldown = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WebApiDemo.Model.Response
{
public class BaseResponse: ISerializable
{
/// <summary>
/// 表示业务是否正常
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 返回消息,成功的消息和错误消息都在这里
/// </summary>
public string Message { get; set; }
/// <summary>
/// 用于返回复杂结果
/// </summary>
public object Data { get; set; }
/// <summary>
/// 自定义序列化方法
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// 运用info对象来添加你所需要序列化的项
info.AddValue("IsSuccess", IsSuccess);
info.AddValue("Message", Message);
if (Data != null)
{
info.AddValue("Data", Convert.ChangeType(Data, Data.GetType()));
}
else
{
info.AddValue("Data", null);
}
}
public BaseResponse() { }
}
}
|
using Pchp.Core;
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.Sym
{
/**
* The EventDispatcherInterface is the central point of Symfony's event listener system.
* Listeners are registered on the manager and events are dispatched through the
* manager.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
*/
public interface EventDispatcherInterface
{
/**
* Dispatches an event to all registered listeners.
*
* @param string eventName The name of the event to dispatch. The name of
* the event is the name of the method that is
* invoked on listeners.
* @param Event event The event to pass to the event handlers/listeners.
* If not supplied, an empty Event instance is created.
*
* @return Event
*
* @api
*/
ext.Event dispatch(string eventName, ext.Event eventp = null);
/**
* Adds an event listener that listens on the specified events.
*
* @param string eventName The event to listen on
* @param callable listener The listener
* @param integer priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*
* @api
*/
void addListener(string eventName, ext.Event listener, int priority = 0);
/**
* Adds an event subscriber.
*
* The subscriber is asked for all the events he is
* interested in and added as a listener for these events.
*
* @param EventSubscriberInterface subscriber The subscriber.
*
* @api
*/
void addSubscriber(ext.Event subscriber);
/**
* Removes an event listener from the specified events.
*
* @param string|array eventName The event(s) to remove a listener from
* @param callable listener The listener to remove
*/
void removeListener(string eventName, ext.Event listener);
/**
* Removes an event subscriber.
*
* @param EventSubscriberInterface subscriber The subscriber
*/
void removeSubscriber(ext.Event subscriber);
/**
* Gets the listeners of a specific event or all listeners.
*
* @param string eventName The name of the event
*
* @return array The event listeners for the specified event, or all event listeners by event name
*/
PhpArray getListeners(string eventName = null);
/**
* Checks whether an event has any registered listeners.
*
* @param string eventName The name of the event
*
* @return Boolean true if the specified event has any listeners, false otherwise
*/
bool hasListeners(string eventName = null);
}
} |
using System;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Timers
{
public class ContinuousClock : GameTimer
{
public ContinuousClock(double intervalSeconds)
: base(intervalSeconds)
{
}
public ContinuousClock(TimeSpan interval)
: base(interval)
{
}
public event EventHandler Tick;
public TimeSpan NextTickTime { get; protected set; }
protected override void OnStopped()
{
NextTickTime = CurrentTime + Interval;
}
protected override void OnUpdate(GameTime gameTime)
{
if (CurrentTime >= NextTickTime)
{
NextTickTime = CurrentTime + Interval;
Tick.Raise(this, EventArgs.Empty);
}
}
}
}
|
namespace SpaceEngineersCalculator.Models
{
class Ingot
{
public string Name { get; private set; }
public (Ore ore, double count) Ore { get; private set; }
public Ingot(string name)
{
this.Name = name;
}
public Ingot(string name, Ore ore, int countOre)
{
this.Name = name;
this.Ore = (ore, countOre);
}
}
}
|
using BPiaoBao.AppServices.Contracts.Cashbag;
using BPiaoBao.Client.UIExt;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using System;
using System.Threading.Tasks;
namespace BPiaoBao.Client.SystemSetting.ViewModel
{
/// <summary>
/// 修改支付密码视图模型
/// </summary>
public class ChangePayPasswordViewModel : ChangePasswordViewModel
{
#region 公开属性
#region IsSending
/// <summary>
/// The <see cref="IsSending" /> property's name.
/// </summary>
private const string IsSendingPropertyName = "IsSending";
private bool _isSending;
/// <summary>
/// 是否正在发送短信
/// </summary>
public bool IsSending
{
get { return _isSending; }
set
{
if (_isSending == value) return;
RaisePropertyChanging(IsSendingPropertyName);
_isSending = value;
RaisePropertyChanged(IsSendingPropertyName);
}
}
#endregion
#region ValidateCode
/// <summary>
/// The <see cref="ValidateCode" /> property's name.
/// </summary>
private const string ValidateCodePropertyName = "ValidateCode";
private string _validateCode;
/// <summary>
/// 短息验证码
/// </summary>
public string ValidateCode
{
get { return _validateCode; }
set
{
if (_validateCode == value) return;
RaisePropertyChanging(ValidateCodePropertyName);
_validateCode = value;
RaisePropertyChanged(ValidateCodePropertyName);
}
}
#endregion
#endregion
#region 属性验证
/// <summary>
/// 获取具有给定名称的属性的错误信息。
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
public override string this[string columnName]
{
get
{
switch (columnName)
{
case ValidateCodePropertyName:
if (ValidateCode == null)
return "";
if (String.IsNullOrWhiteSpace(ValidateCode))
return "请输入短信验证码";
break;
case OldPasswordPropertyName:
return null;
}
return base[columnName];
}
}
#endregion
#region 公开命令
#region GetValidateCodeCommand
private RelayCommand _getValidateCodeCommand;
/// <summary>
/// 获取短信验证码命令
/// </summary>
public RelayCommand GetValidateCodeCommand
{
get
{
return _getValidateCodeCommand ?? (_getValidateCodeCommand = new RelayCommand(ExecuteGetValidateCodeCommand, CanExecuteGetValidateCodeCommand));
}
}
private void ExecuteGetValidateCodeCommand()
{
IsSending = true;
Action action = () => CommunicateManager.Invoke<IAccountService>(service =>
{
var temp = service.GetValidateCode();
var test = temp;
}, UIManager.ShowErr);
Task.Factory.StartNew(action).ContinueWith(task =>
{
Action setAction = () => { IsSending = false; };
DispatcherHelper.UIDispatcher.Invoke(setAction);
});
}
private bool CanExecuteGetValidateCodeCommand()
{
return !_isSending;
}
#endregion
#region 修改密码
protected override void ExecuteSaveCommand()
{
IsBusy = true;
ErrorMessage = null;
Action action = () => CommunicateManager.Invoke<IAccountService>(service =>
{
service.SetPayPassword(NewPassword, ValidateCode);
UIManager.ShowMessage("修改支付密码成功");
IsChanged = true;
}, ex =>
{
ErrorMessage = ex.Message;
});
Task.Factory.StartNew(action).ContinueWith(task =>
{
Action setAction = () => { IsBusy = false; };
DispatcherHelper.UIDispatcher.Invoke(setAction);
});
}
protected override bool CanExecuteSaveCommand()
{
var can = String.IsNullOrEmpty(ValidateNewPwd()) && String.IsNullOrEmpty(ValidateComparisonPassword());
if (!can)
return false;
return !IsBusy && !String.IsNullOrWhiteSpace(ValidateCode);
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading.Tasks;
namespace InspectorLib
{
public class FunctionInsp
{
static public string GInsp = ("Васильев Василий Иванович");
static public string sot = ("Иванов И.И.;Зиронов Т.А.;Миронов А.В.;Васильев В.И.");
static public string[] sot2;
static public string Newsot;
static public string NewGInsp;
/// <summary>
/// Выводит на экран ФИО главного инспектора
/// </summary>
static public void GetInspector()
{
Console.WriteLine($"Главный инспектор – {GInsp}");
}
/// <summary>
/// Выводит на экран название автоинспекции
/// </summary>
static public void GetСarInspection()
{
Console.WriteLine("Название – Автоинспекция г. Чита");
}
/// <summary>
/// Выводит на экран ФИО сотрудников автоинспекции
/// </summary>
static public void GetWorker()
{
sot2 = sot.Split(new Char[] { ';' });
Console.WriteLine($"ФИО сотрудников автоинспекции: {sot}");
}
/// <summary>
/// Устанавливает нового главного инспектора
/// </summary>
static public void SetInspector()
{
Console.WriteLine("Введите полное имя нового главного инспектора");
NewGInsp = Console.ReadLine();
for (int i = 0; i <= 3; i++)
{
if (NewGInsp == sot2[i])
{
GInsp = NewGInsp;
}
}
}
/// <summary>
/// Добовляет нового сотрудника в переменную sot
/// </summary>
static public void AddWorker()
{
Console.WriteLine("Введите ФИО нового сотрудника");
Newsot = Console.ReadLine();
sot = sot + ";" + Newsot;
}
/// <summary>
/// Выводит на экран госномер при условии что переменная code=75
/// </summary>
/// <param name="number"></param>
/// <param name="symbol"></param>
/// <param name="code"></param>
static public void GenerateNumber(int number, string symbol, int code)
{
if (code == 75) Console.WriteLine($"Госномер - {symbol.ToUpper()}{number}_{code}");
else Console.WriteLine("Введён не верный номер региона");
}
}
} |
using System.Diagnostics;
namespace iQuest.VendingMachine.ProgramConfiguration
{
internal class EventViewerErrorWriter : IEventViewerErrorWriter
{
private int eventID = 1;
public void EventLogger(string message)
{
EventLog eventLog = new EventLog();
if(!EventLog.SourceExists("Vending-Machine"))
{
EventLog.CreateEventSource("Vending-Machine", "Application");
}
eventLog.Source = "Vending-Machine";
for(;;)
{
eventLog.WriteEntry(message, EventLogEntryType.Error, eventID);
eventID++;
break;
}
eventLog.Close();
}
}
}
|
using Archimedes.Library.Message.Dto;
namespace Archimedes.Service.Price
{
public interface IPriceRequestManager
{
void SendToQueue(MarketDto market);
}
} |
using Learn.IRepository;
using Learn.IService;
using Learn.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Learn.Service
{
public class WriterService:BaseService<Writer>,IWriterService
{
private readonly IWriterRepository _iWriterRepository;
public WriterService(IWriterRepository iWriterRepository)
{
base._iBaseRepository = iWriterRepository;
_iWriterRepository = iWriterRepository;
}
}
}
|
using HangoutsDbLibrary.Data;
using HangoutsDbLibrary.Model;
using HangoutsDbLibrary.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Mappers;
using WebAPI.ViewModels;
namespace WebAPI.Services
{
public class ServiceUser : IServiceUser
{
private HangoutsContext context;
private UnitOfWork CreateUnitOfWork()
{
DesignTimeDbContextFactory designTimeDbContextFactory = new DesignTimeDbContextFactory();
context = designTimeDbContextFactory.CreateDbContext(new string[] { });
return new UnitOfWork(context);
}
public void UpdateUser(User user)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
unitOfWork.UserRepository.Update(user);
unitOfWork.save();
}
}
public void AddUser(User user)
{
//Moare unit of work dupa fiecare folosire de metode (speranta lui de viata e mica haha)
using(UnitOfWork unitOfWork = CreateUnitOfWork())
{
unitOfWork.UserRepository.Add(user);
unitOfWork.save();
}
}
public User GetUserById(int id)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
return unitOfWork.UserRepository.FindBy(u => u.Id == id);
}
}
public User GetUserById(int id, UnitOfWork unitOfWork)
{
return unitOfWork.UserRepository.FindBy(u => u.Id == id);
}
public User GetUserByUsername(string Username)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
return unitOfWork.UserRepository.FindBy(u => u.Username == Username);
}
}
public User GetUserByUsername(string userName, UnitOfWork unitOfWork)
{
return unitOfWork.UserRepository.FindBy(u => u.Username == userName);
}
public void DeleteUser(User user)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
unitOfWork.UserRepository.Delete(user);
unitOfWork.save();
}
}
public List<User> GetAllUsers()
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
return unitOfWork.UserRepository.GetAll().ToList();
}
}
public void AddInterestToAUser(string userName, int idInterest)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
ServiceInterest serviceInterest = new ServiceInterest();
User user = GetUserByUsername(userName, unitOfWork);
user.Interests.Add(serviceInterest.GetInterestById(idInterest, unitOfWork));
unitOfWork.save();
}
}
}
}
|
using Alfheim.FuzzyLogic.Functions;
namespace Alfheim.FuzzyLogic
{
public interface IFunction
{
FuzzyFunctionType Type { get; }
double GetValue(double x);
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// If an item can have an action performed on it (like \"Dismantle\"), it will be defined here if you care.
/// </summary>
[DataContract]
public partial class DestinyDefinitionsDestinyItemActionBlockDefinition : IEquatable<DestinyDefinitionsDestinyItemActionBlockDefinition>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyItemActionBlockDefinition" /> class.
/// </summary>
/// <param name="VerbName">Localized text for the verb of the action being performed..</param>
/// <param name="VerbDescription">Localized text describing the action being performed..</param>
/// <param name="IsPositive">The content has this property, however it's not entirely clear how it is used..</param>
/// <param name="OverlayScreenName">If the action has an overlay screen associated with it, this is the name of that screen. Unfortunately, we cannot return the screen's data itself..</param>
/// <param name="OverlayIcon">The icon associated with the overlay screen for the action, if any..</param>
/// <param name="RequiredCooldownSeconds">The number of seconds to delay before allowing this action to be performed again..</param>
/// <param name="RequiredItems">If the action requires other items to exist or be destroyed, this is the list of those items and requirements..</param>
/// <param name="ProgressionRewards">If performing this action earns you Progression, this is the list of progressions and values granted for those progressions by performing this action..</param>
/// <param name="ActionTypeLabel">The internal identifier for the action..</param>
/// <param name="RequiredLocation">Theoretically, an item could have a localized string for a hint about the location in which the action should be performed. In practice, no items yet have this property..</param>
/// <param name="RequiredCooldownHash">The identifier hash for the Cooldown associated with this action. We have not pulled this data yet for you to have more data to use for cooldowns..</param>
/// <param name="DeleteOnAction">If true, the item is deleted when the action completes..</param>
/// <param name="ConsumeEntireStack">If true, the entire stack is deleted when the action completes..</param>
/// <param name="UseOnAcquire">If true, this action will be performed as soon as you earn this item. Some rewards work this way, providing you a single item to pick up from a reward-granting vendor in-game and then immediately consuming itself to provide you multiple items..</param>
public DestinyDefinitionsDestinyItemActionBlockDefinition(string VerbName = default(string), string VerbDescription = default(string), bool? IsPositive = default(bool?), string OverlayScreenName = default(string), string OverlayIcon = default(string), int? RequiredCooldownSeconds = default(int?), List<DestinyDefinitionsDestinyItemActionRequiredItemDefinition> RequiredItems = default(List<DestinyDefinitionsDestinyItemActionRequiredItemDefinition>), List<DestinyDefinitionsDestinyProgressionRewardDefinition> ProgressionRewards = default(List<DestinyDefinitionsDestinyProgressionRewardDefinition>), string ActionTypeLabel = default(string), string RequiredLocation = default(string), uint? RequiredCooldownHash = default(uint?), bool? DeleteOnAction = default(bool?), bool? ConsumeEntireStack = default(bool?), bool? UseOnAcquire = default(bool?))
{
this.VerbName = VerbName;
this.VerbDescription = VerbDescription;
this.IsPositive = IsPositive;
this.OverlayScreenName = OverlayScreenName;
this.OverlayIcon = OverlayIcon;
this.RequiredCooldownSeconds = RequiredCooldownSeconds;
this.RequiredItems = RequiredItems;
this.ProgressionRewards = ProgressionRewards;
this.ActionTypeLabel = ActionTypeLabel;
this.RequiredLocation = RequiredLocation;
this.RequiredCooldownHash = RequiredCooldownHash;
this.DeleteOnAction = DeleteOnAction;
this.ConsumeEntireStack = ConsumeEntireStack;
this.UseOnAcquire = UseOnAcquire;
}
/// <summary>
/// Localized text for the verb of the action being performed.
/// </summary>
/// <value>Localized text for the verb of the action being performed.</value>
[DataMember(Name="verbName", EmitDefaultValue=false)]
public string VerbName { get; set; }
/// <summary>
/// Localized text describing the action being performed.
/// </summary>
/// <value>Localized text describing the action being performed.</value>
[DataMember(Name="verbDescription", EmitDefaultValue=false)]
public string VerbDescription { get; set; }
/// <summary>
/// The content has this property, however it's not entirely clear how it is used.
/// </summary>
/// <value>The content has this property, however it's not entirely clear how it is used.</value>
[DataMember(Name="isPositive", EmitDefaultValue=false)]
public bool? IsPositive { get; set; }
/// <summary>
/// If the action has an overlay screen associated with it, this is the name of that screen. Unfortunately, we cannot return the screen's data itself.
/// </summary>
/// <value>If the action has an overlay screen associated with it, this is the name of that screen. Unfortunately, we cannot return the screen's data itself.</value>
[DataMember(Name="overlayScreenName", EmitDefaultValue=false)]
public string OverlayScreenName { get; set; }
/// <summary>
/// The icon associated with the overlay screen for the action, if any.
/// </summary>
/// <value>The icon associated with the overlay screen for the action, if any.</value>
[DataMember(Name="overlayIcon", EmitDefaultValue=false)]
public string OverlayIcon { get; set; }
/// <summary>
/// The number of seconds to delay before allowing this action to be performed again.
/// </summary>
/// <value>The number of seconds to delay before allowing this action to be performed again.</value>
[DataMember(Name="requiredCooldownSeconds", EmitDefaultValue=false)]
public int? RequiredCooldownSeconds { get; set; }
/// <summary>
/// If the action requires other items to exist or be destroyed, this is the list of those items and requirements.
/// </summary>
/// <value>If the action requires other items to exist or be destroyed, this is the list of those items and requirements.</value>
[DataMember(Name="requiredItems", EmitDefaultValue=false)]
public List<DestinyDefinitionsDestinyItemActionRequiredItemDefinition> RequiredItems { get; set; }
/// <summary>
/// If performing this action earns you Progression, this is the list of progressions and values granted for those progressions by performing this action.
/// </summary>
/// <value>If performing this action earns you Progression, this is the list of progressions and values granted for those progressions by performing this action.</value>
[DataMember(Name="progressionRewards", EmitDefaultValue=false)]
public List<DestinyDefinitionsDestinyProgressionRewardDefinition> ProgressionRewards { get; set; }
/// <summary>
/// The internal identifier for the action.
/// </summary>
/// <value>The internal identifier for the action.</value>
[DataMember(Name="actionTypeLabel", EmitDefaultValue=false)]
public string ActionTypeLabel { get; set; }
/// <summary>
/// Theoretically, an item could have a localized string for a hint about the location in which the action should be performed. In practice, no items yet have this property.
/// </summary>
/// <value>Theoretically, an item could have a localized string for a hint about the location in which the action should be performed. In practice, no items yet have this property.</value>
[DataMember(Name="requiredLocation", EmitDefaultValue=false)]
public string RequiredLocation { get; set; }
/// <summary>
/// The identifier hash for the Cooldown associated with this action. We have not pulled this data yet for you to have more data to use for cooldowns.
/// </summary>
/// <value>The identifier hash for the Cooldown associated with this action. We have not pulled this data yet for you to have more data to use for cooldowns.</value>
[DataMember(Name="requiredCooldownHash", EmitDefaultValue=false)]
public uint? RequiredCooldownHash { get; set; }
/// <summary>
/// If true, the item is deleted when the action completes.
/// </summary>
/// <value>If true, the item is deleted when the action completes.</value>
[DataMember(Name="deleteOnAction", EmitDefaultValue=false)]
public bool? DeleteOnAction { get; set; }
/// <summary>
/// If true, the entire stack is deleted when the action completes.
/// </summary>
/// <value>If true, the entire stack is deleted when the action completes.</value>
[DataMember(Name="consumeEntireStack", EmitDefaultValue=false)]
public bool? ConsumeEntireStack { get; set; }
/// <summary>
/// If true, this action will be performed as soon as you earn this item. Some rewards work this way, providing you a single item to pick up from a reward-granting vendor in-game and then immediately consuming itself to provide you multiple items.
/// </summary>
/// <value>If true, this action will be performed as soon as you earn this item. Some rewards work this way, providing you a single item to pick up from a reward-granting vendor in-game and then immediately consuming itself to provide you multiple items.</value>
[DataMember(Name="useOnAcquire", EmitDefaultValue=false)]
public bool? UseOnAcquire { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyDefinitionsDestinyItemActionBlockDefinition {\n");
sb.Append(" VerbName: ").Append(VerbName).Append("\n");
sb.Append(" VerbDescription: ").Append(VerbDescription).Append("\n");
sb.Append(" IsPositive: ").Append(IsPositive).Append("\n");
sb.Append(" OverlayScreenName: ").Append(OverlayScreenName).Append("\n");
sb.Append(" OverlayIcon: ").Append(OverlayIcon).Append("\n");
sb.Append(" RequiredCooldownSeconds: ").Append(RequiredCooldownSeconds).Append("\n");
sb.Append(" RequiredItems: ").Append(RequiredItems).Append("\n");
sb.Append(" ProgressionRewards: ").Append(ProgressionRewards).Append("\n");
sb.Append(" ActionTypeLabel: ").Append(ActionTypeLabel).Append("\n");
sb.Append(" RequiredLocation: ").Append(RequiredLocation).Append("\n");
sb.Append(" RequiredCooldownHash: ").Append(RequiredCooldownHash).Append("\n");
sb.Append(" DeleteOnAction: ").Append(DeleteOnAction).Append("\n");
sb.Append(" ConsumeEntireStack: ").Append(ConsumeEntireStack).Append("\n");
sb.Append(" UseOnAcquire: ").Append(UseOnAcquire).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyDefinitionsDestinyItemActionBlockDefinition);
}
/// <summary>
/// Returns true if DestinyDefinitionsDestinyItemActionBlockDefinition instances are equal
/// </summary>
/// <param name="input">Instance of DestinyDefinitionsDestinyItemActionBlockDefinition to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyDefinitionsDestinyItemActionBlockDefinition input)
{
if (input == null)
return false;
return
(
this.VerbName == input.VerbName ||
(this.VerbName != null &&
this.VerbName.Equals(input.VerbName))
) &&
(
this.VerbDescription == input.VerbDescription ||
(this.VerbDescription != null &&
this.VerbDescription.Equals(input.VerbDescription))
) &&
(
this.IsPositive == input.IsPositive ||
(this.IsPositive != null &&
this.IsPositive.Equals(input.IsPositive))
) &&
(
this.OverlayScreenName == input.OverlayScreenName ||
(this.OverlayScreenName != null &&
this.OverlayScreenName.Equals(input.OverlayScreenName))
) &&
(
this.OverlayIcon == input.OverlayIcon ||
(this.OverlayIcon != null &&
this.OverlayIcon.Equals(input.OverlayIcon))
) &&
(
this.RequiredCooldownSeconds == input.RequiredCooldownSeconds ||
(this.RequiredCooldownSeconds != null &&
this.RequiredCooldownSeconds.Equals(input.RequiredCooldownSeconds))
) &&
(
this.RequiredItems == input.RequiredItems ||
this.RequiredItems != null &&
this.RequiredItems.SequenceEqual(input.RequiredItems)
) &&
(
this.ProgressionRewards == input.ProgressionRewards ||
this.ProgressionRewards != null &&
this.ProgressionRewards.SequenceEqual(input.ProgressionRewards)
) &&
(
this.ActionTypeLabel == input.ActionTypeLabel ||
(this.ActionTypeLabel != null &&
this.ActionTypeLabel.Equals(input.ActionTypeLabel))
) &&
(
this.RequiredLocation == input.RequiredLocation ||
(this.RequiredLocation != null &&
this.RequiredLocation.Equals(input.RequiredLocation))
) &&
(
this.RequiredCooldownHash == input.RequiredCooldownHash ||
(this.RequiredCooldownHash != null &&
this.RequiredCooldownHash.Equals(input.RequiredCooldownHash))
) &&
(
this.DeleteOnAction == input.DeleteOnAction ||
(this.DeleteOnAction != null &&
this.DeleteOnAction.Equals(input.DeleteOnAction))
) &&
(
this.ConsumeEntireStack == input.ConsumeEntireStack ||
(this.ConsumeEntireStack != null &&
this.ConsumeEntireStack.Equals(input.ConsumeEntireStack))
) &&
(
this.UseOnAcquire == input.UseOnAcquire ||
(this.UseOnAcquire != null &&
this.UseOnAcquire.Equals(input.UseOnAcquire))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.VerbName != null)
hashCode = hashCode * 59 + this.VerbName.GetHashCode();
if (this.VerbDescription != null)
hashCode = hashCode * 59 + this.VerbDescription.GetHashCode();
if (this.IsPositive != null)
hashCode = hashCode * 59 + this.IsPositive.GetHashCode();
if (this.OverlayScreenName != null)
hashCode = hashCode * 59 + this.OverlayScreenName.GetHashCode();
if (this.OverlayIcon != null)
hashCode = hashCode * 59 + this.OverlayIcon.GetHashCode();
if (this.RequiredCooldownSeconds != null)
hashCode = hashCode * 59 + this.RequiredCooldownSeconds.GetHashCode();
if (this.RequiredItems != null)
hashCode = hashCode * 59 + this.RequiredItems.GetHashCode();
if (this.ProgressionRewards != null)
hashCode = hashCode * 59 + this.ProgressionRewards.GetHashCode();
if (this.ActionTypeLabel != null)
hashCode = hashCode * 59 + this.ActionTypeLabel.GetHashCode();
if (this.RequiredLocation != null)
hashCode = hashCode * 59 + this.RequiredLocation.GetHashCode();
if (this.RequiredCooldownHash != null)
hashCode = hashCode * 59 + this.RequiredCooldownHash.GetHashCode();
if (this.DeleteOnAction != null)
hashCode = hashCode * 59 + this.DeleteOnAction.GetHashCode();
if (this.ConsumeEntireStack != null)
hashCode = hashCode * 59 + this.ConsumeEntireStack.GetHashCode();
if (this.UseOnAcquire != null)
hashCode = hashCode * 59 + this.UseOnAcquire.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using System;
using System.Collections.Generic;
#nullable disable
namespace Repository.Models
{
/// <summary>
/// Repo model from database-first scaffolding
/// </summary>
public partial class Comment
{
public Comment()
{
UserLikes = new HashSet<UserLike>();
}
public string CommentId { get; set; }
public string DiscussionId { get; set; }
public string UserId { get; set; }
public DateTime CreationTime { get; set; }
public string CommentText { get; set; }
public bool IsSpoiler { get; set; }
public string ParentCommentid { get; set; }
public int? Likes { get; set; }
public virtual Discussion Discussion { get; set; }
public virtual ICollection<UserLike> UserLikes { get; set; }
}
}
|
using System;
using Entity;
namespace Business
{
public class UserBO
{
public static ListUserEntity SelectAll()
{
return DataAccess.UserDA.SelectAll();
}
public static UserEntity SelectByUserName(String username)
{
return DataAccess.UserDA.SelectByUserName(username);
}
public static Int32 Insert(UserEntity user)
{
return DataAccess.UserDA.Insert(user);
}
public static Int32 Update(UserEntity user)
{
return DataAccess.UserDA.Update(user);
}
public static Int32 ChangePass(String username, String password)
{
return DataAccess.UserDA.ChangePass(username, password);
}
public static Int32 Delete(String username)
{
return DataAccess.UserDA.Delete(username);
}
}
}
|
// Copyright 2020 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 NtApiDotNet;
using System;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Get the object ID for a file.</para>
/// <para type="description">This cmdlet gets the object ID for a file.</para>
/// </summary>
/// <example>
/// <code>Get-NtFileObjectId -File $f</code>
/// <para>Get the object ID for the file.</para>
/// </example>
/// <example>
/// <code>Get-NtFileObjectId -Path "\??\c:\windows\notepad.exe"</code>
/// <para>Get the object ID for the file by path</para>
/// </example>
/// <example>
/// <code>Get-NtFileObjectId -Path "c:\windows\notepad.exe" -Win32Path</code>
/// <para>Get the object ID for the file by win32 path</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "NtFileObjectId", DefaultParameterSetName = "Default")]
[OutputType(typeof(Guid), typeof(FileObjectIdBuffer))]
public class GetNtFileObjectIdCmdlet : BaseNtFilePropertyCmdlet
{
/// <summary>
/// <para type="description">Specify to get extended object ID information.</para>
/// </summary>
[Parameter]
public SwitchParameter ExtendedInformation { get; set; }
/// <summary>
/// <para type="description">Specify to create the object ID if it doesn't already exist.</para>
/// </summary>
[Parameter]
public SwitchParameter Create { get; set; }
/// <summary>
/// Constructor.
/// </summary>
public GetNtFileObjectIdCmdlet()
: base(FileAccessRights.Synchronize, FileShareMode.None, FileOpenOptions.None)
{
}
private protected override void HandleFile(NtFile file)
{
var objid = Create ? file.CreateOrGetObjectId() : file.GetObjectId();
if (ExtendedInformation)
{
WriteObject(objid);
}
else
{
WriteObject(objid.ObjectId);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Prism.Logging;
using Ninject;
namespace Webcorp.rx_mvvm
{
public class Logger : ILogger
{
[Inject]
public ILoggerFacade LoggerFacade { get; set; }
[Inject]
public ILoggerFormatter Formatter { get; set; }
protected virtual string Format(string message,string caller = "")
{
return Formatter.Format(message, caller);
}
public void Debug([CallerMemberName] string message = "")
{
LoggerFacade.Log(Format(message), Category.Debug, Priority.Low);
}
public void Debug(string message, [CallerMemberName] string caller = "")
{
LoggerFacade.Log(Format(message,caller), Category.Debug, Priority.Low);
}
public void Exception([CallerMemberName] string message = "")
{
LoggerFacade.Log(Format(message), Category.Exception, Priority.High);
}
public void Exception(string message, [CallerMemberName] string caller = "")
{
LoggerFacade.Log(Format(message,caller), Category.Exception, Priority.High);
}
public void Info([CallerMemberName] string message = "")
{
LoggerFacade.Log(Format(message), Category.Info, Priority.Low);
}
public void Info(string message, [CallerMemberName] string caller = "")
{
LoggerFacade.Log(Format(message,caller), Category.Info, Priority.Low);
}
public void Warn([CallerMemberName] string message = "")
{
LoggerFacade.Log(Format(message), Category.Warn, Priority.Medium);
}
public void Warn(string message, [CallerMemberName] string caller = "")
{
LoggerFacade.Log(Format(message,caller), Category.Warn, Priority.Medium);
}
}
public class LoggerFormatter : ILoggerFormatter
{
public string Format(string message, string caller = "")
{
if (caller.IsNullOrEmpty()) return message;
return caller + "-" + message;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lineTrack : MonoBehaviour {
public GameObject trackObject;
public Vector3 startOffset;
private LineRenderer line;
private UiBox uiBox;
private dataMaster data;
public int boxIndexActivate;
public string dockTypeActivate;
// Use this for initialization
void Start () {
try { line = GetComponent<LineRenderer>(); }
catch { Debug.Log("No Line Renderer on " + name); }
try { uiBox = FindObjectOfType<UiBox>(); }
catch { Debug.Log("No UiBox in Scene"); }
try { data = FindObjectOfType<dataMaster>(); }
catch { Debug.Log("No DataMaster in Scene"); }
}
// Update is called once per frame
void Update () {
line.SetPosition(0, transform.position + startOffset);
line.SetPosition(1, trackObject.transform.position);
try
{
if (boxIndexActivate >= 0)
{
if (UiBox.box.index == boxIndexActivate)
line.enabled = true;
else
line.enabled = false;
}
}
catch { /*Debug.Log("UiBox was not assigned");*/ }
try
{
if (dockTypeActivate != "null")
{
if (data.currentLogger.GetComponent<dataRecordingController>().activeDockStyle == dockTypeActivate)
line.enabled = true;
else
line.enabled = false;
}
}
catch { /*Debug.Log("DataMaster was not assigned");*/ }
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameWindow : GenericWindow {
} |
using System.Collections.Generic;
using AgeBaseTemplate.Core.ContentTypes;
namespace AgeBaseTemplate.Core.Services
{
public interface ILanguagePageService
{
IEnumerable<LanguagePage> GetAllLanguagePages();
LanguagePage GetCurrentLanguagePage();
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Item = Compiler.LinkList<Compiler.Parser.LR1Production>;
namespace Compiler
{
class Program
{
static void Main(string[] args)
{
string s = "S-L=R|R L-*R|x R-L";
//E-TE' E'-+TE'|0 T-FT' T'-*FT'|0 F-(E)|a
//L-E E-E+T|E=T|T T-T*F|T/F|F F-(E)|x
//L-E E-TE' E'-+TE'|=TE'|0 T-FT' T'-*FT'|/FT'|0 F-(E)|x
//S-L=R|R L-*R|x R-L
Parser parser = new Parser {Src = s, Input = "aaa"};
parser.Excute();
//parser.Print();
}
}
internal static class Extension
{
public static void Append(this HashSet<string> h1, HashSet<string> h2)
{
foreach (string s in h2)
{
h1.Add(s);
}
}
public static void Append(this HashSet<string> h1, List<string> h2)
{
foreach (string s in h2)
{
h1.Add(s);
}
}
public static void AppendWithoutNull(this HashSet<string> h1, HashSet<string> h2)
{
foreach (string s in h2)
{
if (s != "0")
{
h1.Add(s);
}
}
}
public static List<string> Merge(this List<string> list1, List<string> list2)
{
var result= list1.ToList();
result.AddRange(list2);
return result;
}
public static bool Equal<T>(this HashSet<T> s1, HashSet<T> s2)
{
return s1.All(s2.Contains) && s2.All(s1.Contains);
}
}
internal static class Util
{
public static bool IsLetter(char c)
{
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
return true;
return false;
}
public static bool IsDigit(char c)
{
if (c >= '0' && c <= '9')
return true;
return false;
}
public static string GetChar(string s, int i = 0)
{
string c = s[i].ToString();
if (i != s.Length - 1 && s[i + 1] == '\'')
{
c = c + "\'";
}
return c;
}
public static List<string> GetChars(string s, int i = 0)
{
var list = new List<string>();
for (; i < s.Length; i++)
{
var c = GetChar(s, i);
list.Add(c);
if (c.Length > 1)
{
i++;
}
}
return list;
}
}
internal class LinkList<T>
{
internal class Node<T>
{
public T Element;
public Node<T> Next;
}
private Node<T> _first;
private Node<T> _last;
private Node<T> _current;
private int _count;
private int _currentNum;
public LinkList()
{
_first = _current = _last = new Node<T>();
_count = 0;
_currentNum = -1;
}
public void Add(T element)
{
_last.Next = new Node<T>();
_last = _last.Next;
_last.Element = element;
_count++;
}
public int Count()
{
return _count;
}
public T First()
{
return _first.Next.Element;
}
public T Current()
{
return _current.Element;
}
public Node<T> CurrentPos()
{
return _current;
}
public bool TryMove()
{
if (_last != _current)
{
_current = _current.Next;
_currentNum++;
return true;
}
return false;
}
public void Reset()
{
_current = _first;
_currentNum = -1;
}
public int CurrentNum()
{
return _currentNum;
}
public override bool Equals(object obj)
{
if (!(obj is LinkList<T> linkList))
return false;
if (linkList._count != _count)
return false;
var objCurrent = linkList._current;
var thisCurrent = _current;
linkList.Reset();
Reset();
while (linkList.TryMove() && TryMove())
{
var left = Current();
var right = linkList.Current();
if (!left.Equals(right))
{
linkList._current = objCurrent;
_current = thisCurrent;
return false;
}
}
linkList._current = objCurrent;
_current = thisCurrent;
return true;
}
public T IteForEqual(T e)
{
var current = _current;
Reset();
while (TryMove())
{
var e1 = Current();
if (!e1.Equals(e)) continue;
_current = current;
return e;
}
_current = current;
return default;
}
}
internal class LexicalAnalyzer
{
internal class KeyValue
{
public string Key;
public string Value;
public KeyValue(string key, string value)
{
this.Key = key;
this.Value = value;
}
}
//关键字表
private static string[] keyWords =
{
"auto", "break", "case", "char", "const", "continue",
"default", "do", "double", "else", "enum", "extern",
"float", "for", "goto", "if", "int", "long",
"register", "return", "short", "signed", "sizeof", "static",
"struct", "switch", "typedef", "union", "unsigned", "void",
"volatile", "while"
};
private static string[] op =
{
"+", "-", "*", "/", "<", "<=", ">", ">=", "=", "==",
"!=", ";", "(", ")", "^", ",", "\"", "\'", "#", "&",
"&&", "|", "||", "%", "~", "<<", ">>", "[", "]", "{",
"}", "\\", ".", "?", ":", "!"
};
string source; //源文件代码
char endSymbol = '\r'; //结束标志
int offset = 0; //源代码指针
StringBuilder token = new StringBuilder();
public List<KeyValue> result = new List<KeyValue>();
public LexicalAnalyzer(string source)
{
this.source = source;
}
bool IsLetterOrLine(char head)
{
if (Util.IsLetter(head) || head == '_')
return true;
return false;
}
public void DelAnnotation()
{
if (++offset == source.Length - 1)
throw new Exception("注释格式错误:single \"/\"");
if (source[offset] == '/')
{
do
{
if (++offset == source.Length - 1)
throw new Exception("注释格式错误:single \"/\"");
} while (source[offset] != '\n');
offset++;
return;
}
if (source[offset] == '*')
{
do
{
if (++offset == source.Length - 1)
throw new Exception("注释格式错误:missing */");
} while (source[offset] != '*');
if (++offset == source.Length - 1 || source[++offset] != '/')
throw new Exception("注释格式错误:missing /");
return;
}
throw new Exception("注释格式错误:single \"/\"");
}
//Two-Operator
private void TwoOp(char first, params char[] list)
{
offset++;
foreach (var second in list)
{
if (source[offset] == second)
{
var o2p = new StringBuilder().Append(first).Append(second).ToString();
result.Add(new KeyValue(o2p, Array.IndexOf(op, o2p).ToString()));
goto end;
}
}
offset--;
result.Add(new KeyValue(first.ToString(), Array.IndexOf(op, first.ToString()).ToString()));
end :
offset++;
}
public void Scanner()
{
while (true)
{
var head = source[offset];
if (IsLetterOrLine(head))
{
//开头是字母或_
while (Util.IsDigit(source[offset]) || IsLetterOrLine(source[offset]))
{
token.Append(source[offset++]);
}
int num;
var tmp = new KeyValue(token.ToString(),
(num = Array.IndexOf(keyWords, token.ToString())) != -1
? num.ToString()
: "Identifier");
result.Add(tmp);
token.Clear();
}
else if (Util.IsDigit(head))
{
//开头是数字
while (Util.IsDigit(source[offset]))
{
token.Append(source[offset++]);
}
var tmp = new KeyValue(token.ToString(), "Digit");
result.Add(tmp);
token.Clear();
}
else if (head == ' ')
{
offset++;
}
else if (head == '+' || head == '-' || head == '*' || head == '/' || head == ';' || head == '(' ||
head == ')' || head == '^' || head == ',' || head == '\"' || head == '\'' || head == '~' ||
head == '#' || head == '%' || head == '[' || head == ']' || head == '{' || head == '}' ||
head == '\\' || head == '.' || head == '?' || head == ':')
{
var tmp = new KeyValue(head.ToString(), Array.IndexOf(op, head.ToString()).ToString());
result.Add(tmp);
offset++;
}
else if (head == '<')
{
TwoOp('<', '=', '<');
}
else if (head == '>')
{
TwoOp('>', '=', '>');
}
else if (head == '=')
{
TwoOp('=', '=');
}
else if (source[offset] == endSymbol)
{
return;
}
else
{
Console.WriteLine("scanner_error");
return;
}
}
}
}
internal class Parser
{
internal class Vertex
{
public string Name;
public bool Nil;
public HashSet<string> S;
public Vertex(string name)
{
this.Name = name;
Nil = false;
S = new HashSet<string>();
}
}
internal class Graph
{
public List<Vertex> Vertices = new List<Vertex>();
public bool[,] Edges;
public void InitEdges(int n)
{
Edges = new bool[n, n];
}
public Vertex FindVertex(string name)
{
foreach (var vertex in Vertices)
if (vertex.Name == name)
return vertex;
return null;
}
public void AddVertex(Vertex v)
{
Vertices.Add(v);
}
public void Show()
{
foreach (var vertex in Vertices)
{
Console.Write("name:" + vertex.Name + " " + "null:" + vertex.Nil + " " + "s:");
foreach (string s in vertex.S)
{
Console.Write(s + " ");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < Edges.GetLength(0); i++)
{
for (int j = 0; j < Edges.GetLength(1); j++)
{
Console.Write(Edges[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
internal class Production
{
public string Left;
public string Right;
public Production(string left, string right)
{
Left = left;
Right = right;
}
public override string ToString()
{
return Left + "->" + Right;
}
}
public string Src { get; set; }
public string Input { get; set; }
public List<string> Vn = new List<string>();
public List<string> Vt = new List<string>();
public List<string> V;
private Graph _graph = new Graph();
List<string> _list = new List<string>();
private bool _change = false;
public HashSet<string>[] First;
public HashSet<string>[] Follow;
private List<Production> _productions;
public Production[][] Table;
private List<LexicalAnalyzer.KeyValue> _lexicalResult;
void Init()
{
// var lexicalAnalyzer =new LexicalAnalyzer(Input);
// lexicalAnalyzer.Scanner();
// _lexicalResult = lexicalAnalyzer.result;
Vn.Add(Src[0].ToString());
var regex = new Regex(@"( [A-Z]'?\-)+");
var matches = regex.Matches(Src);
foreach (Match match in matches)
{
var s = match.Value;
Vn.Add(new string(s.ToCharArray(1, s.Length - 2)));
}
_graph.InitEdges(Vn.Count);
regex = new Regex(@"[^A-Z' \-0|]");
matches = regex.Matches(Src);
foreach (Match match in matches)
{
Vt.Add(match.Value);
}
Vt.Add("$");
First = new HashSet<string>[Vn.Count];
Follow = new HashSet<string>[Vn.Count];
for (var i = 0; i < Follow.Length; i++)
{
Follow[i] = new HashSet<string>();
}
Follow[0].Add("$");
_productions = new List<Production>();
Table = new Production[Vn.Count][];
for (var i = 0; i < Table.Length; i++)
{
Table[i] = new Production[Vt.Count];
}
Productions = new List<string>[Vn.Count];
}
void CalGraph()
{
Regex vnRule = new Regex("^[A-Z]'?");
var productions = Src.Split(" ");
for (var i = 0; i < productions.Length; i++)
{
var production = productions[i];
var leftright = production.Split("-");
var left = leftright[0];
var rights = leftright[1].Split("|");
Productions[i] = new List<string>();
Vertex v = new Vertex(left);
foreach (var right in rights)
{
_productions.Add(new Production(left, right));
Productions[i].Add(right);
var start = vnRule.Match(right).Value;
if (start != "")
{
MakeArc(left, right, start);
}
else if (right == "0")
{
v.Nil = true;
}
else
{
v.S.Add(right[0].ToString());
}
}
_graph.AddVertex(v);
}
list:
for (int i = 0; i < _list.Count; i += 2)
{
var left = _list[i];
var right = _list[i + 1];
var start = vnRule.Match(right).Value;
var a = _graph.FindVertex(left);
if (_graph.FindVertex(start).Nil)
{
if (start.Length == right.Length)
{
_list.RemoveAt(i);
_list.RemoveAt(i);
i -= 2;
if (!a.Nil)
{
a.Nil = true;
_change = true;
}
}
else if (Vt.Contains(right[start.Length].ToString()))
{
string str = right[start.Length].ToString();
if (!a.S.Contains(str))
{
a.S.Add(str);
}
_list.RemoveAt(i);
_list.RemoveAt(i);
i -= 2;
}
else
{
_list.RemoveAt(i);
_list.RemoveAt(i);
i -= 2;
right = new string(right.ToCharArray(start.Length, right.Length - 1));
start = vnRule.Match(right).Value;
MakeArc(left, right, start);
}
}
}
if (_change)
{
_change = false;
goto list;
}
}
void GetFirst()
{
var v = _graph.Vertices;
bool[] visited = new bool[v.Count];
for (int i = 0; i < _graph.Edges.GetLength(0); i++)
{
First[i] = new HashSet<string>();
if (v[i].Nil)
{
First[i].Add("0");
}
Dfs(First[i], i, visited);
visited = new bool[v.Count];
}
}
void GetFollow()
{
List<int>[] follow = new List<int>[Vn.Count];
for (var i = 0; i < follow.Length; i++)
{
follow[i] = new List<int>();
}
Regex regex = new Regex(@"[A-Z][^\s|\|]*");
var productions = Src.Split(" ");
for (var i = 0; i < productions.Length; i++)
{
//一条生成式
var leftright = productions[i].Split("-");
var matches = regex.Matches(leftright[1]);
if (matches.Count == 0)
continue;
foreach (Match right in matches)
{
//一条生成式的右半部分
var str = right.Value;
var chars = Util.GetChars(str, 0);
for (int j = 0; j < chars.Count; j++)
{
//右半部分的一项
int index = Vn.IndexOf(chars[j]);
if (index == -1)
{
continue;
}
int k = j + 1;
for (; k < chars.Count; k++)
{
//去掉首字符的一项
var c = chars[k];
var ci = Vn.IndexOf(c);
if (ci == -1)
{
Follow[index].Add(c);
break;
}
Follow[index].AppendWithoutNull(First[ci]);
if (!_graph.FindVertex(c).Nil)
{
break;
}
}
if (k == chars.Count && index != i)
{
follow[index].Add(i);
}
}
}
}
loop:
bool end = true;
for (int i = 0; i < follow.Length; i++)
{
if (follow[i].Count != 0)
{
for (var j = 0; j < follow[i].Count; j++)
{
int i1 = follow[i][j];
if (follow[i1].Count == 0)
{
Follow[i].Append(Follow[i1]);
follow[i].RemoveAt(j--);
}
else
{
end = false;
}
}
}
}
if (!end)
goto loop;
}
void GetTable()
{
foreach (var production in _productions)
{
var vni = Vn.IndexOf(production.Left);
var c = Util.GetChar(production.Right, 0);
if (Vn.Contains(c))
{
foreach (string s in First[Vn.IndexOf(c)])
{
var vti = Vt.IndexOf(s);
Table[vni][vti] = production;
}
}
else if (c == "0")
{
foreach (string s in Follow[vni])
{
var vti = Vt.IndexOf(s);
Table[vni][vti] = production;
}
}
else
{
var vti = Vt.IndexOf(c);
Table[vni][vti] = production;
}
}
for (int i = 0; i < Vn.Count; i++)
{
foreach (var c in Follow[i])
{
var vti = Vt.IndexOf(c);
if (Table[i][vti] == null)
{
Table[i][vti] = new Production("synch", "");
}
}
}
}
void Up2DownParse()
{
Stack<string> stack = new Stack<string>();
stack.Push("$");
var x = Vn[0];
stack.Push(x);
for (int ip = 0; x != "$"; x = stack.Peek())
{
var stackOutput = new StringBuilder();
foreach (string s in stack)
{
stackOutput.Append(s);
}
Console.Write("{0,10}", stackOutput);
var input = new StringBuilder();
for (var i = ip; i < Input.Length; i++)
{
input.Append(Input[i]);
}
Console.Write("{0,10}", input);
if (x == Input[ip].ToString())
{
stack.Pop();
Console.WriteLine(" 匹配" + Input[ip]);
ip++;
continue;
}
int vni = Vn.IndexOf(x);
int vti = Vt.IndexOf(Input[ip].ToString());
var tableItem = Table[vni][vti];
if (tableItem == null)
{
Console.WriteLine(" 错误:忽略" + Input[ip]);
ip++;
}
else if (tableItem.Left == "synch")
{
Console.WriteLine(" 错误:弹出" + stack.Peek());
stack.Pop();
}
else if (tableItem.Left == x)
{
Console.WriteLine(" 输出" + tableItem.ToString());
stack.Pop();
if (tableItem.Right == "0")
continue;
var strs = Util.GetChars(tableItem.Right, 0);
for (int i = strs.Count - 1; i >= 0; i--)
{
stack.Push(strs[i]);
}
}
}
}
private List<string>[] Productions;
internal class LR1Production
{
public string Left { get; }
public string Right { get; }
public int Current { get; }
public HashSet<string> Forward { get; set; }
public LR1Production(string left, string right, HashSet<string> forward, int current = 0)
{
Left = left;
Right = right;
Current = current;
Forward = forward;
}
public override bool Equals(object obj)
{
if (!(obj is LR1Production p))
return false;
if (Current != p.Current)
return false;
if (Left != p.Left)
return false;
if (Right != p.Right)
return false;
return p.Forward.Equal(Forward);
}
public bool EqualsWithoutForward(LR1Production p)
{
if (Left != p.Left)
return false;
if (Right != p.Right)
return false;
if (Current != p.Current)
return false;
return !Forward.Equal(p.Forward);
}
}
private ActionItem[][] Action;
private int[][] Goto;
private List<Item> items;
internal class ActionItem
{
public int Type;
public int Shift;
public string ReduceLeft;
public string ReduceRight;
public ActionItem(int type=0,int shift=-1,string reduceLeft="",string reduceRight="")
{
Type = type;
Shift = shift;
ReduceLeft = reduceLeft;
ReduceRight = reduceRight;
}
public override bool Equals(object obj)
{
if (!(obj is ActionItem a))
return false;
if (Type != a.Type)
return false;
if (Shift != a.Shift)
return false;
if (ReduceLeft != a.ReduceLeft)
return false;
return ReduceRight == a.ReduceRight;
}
}
HashSet<string> FIRST(LR1Production production)
{
var result = new HashSet<string>();
var chars = Util.GetChars(production.Right, production.Current);
var forward = production.Forward;
if (chars.Count == 1)
{
//说明·后面只有一个符号
result.Append(forward);
}
else
{
var vn = chars[1];
var vnIndex = Vn.IndexOf(vn);
if (vnIndex == -1)
{
//说明是终结符
result.Add(vn);
}
else
{
var first = First[vnIndex];
foreach (string s in first)
{
if (s == "0")
{
result.Append(forward);
}
else
{
result.Add(s);
}
}
}
}
return result;
}
Item Simply(Item items)
{
items.Reset();
items.TryMove();
var added = new bool[items.Count()];
var result = new Item();
result.Add(items.Current());
added[0] = true;
while (result.TryMove())
{
var current = result.Current();
items.Reset();
var oneAdded = false;
while (items.TryMove())
{
if(added[items.CurrentNum()])
continue;
var item = items.Current();
if (current.EqualsWithoutForward(item))
{
current.Forward.Append(item.Forward);
added[items.CurrentNum()] = true;
}
else if(!oneAdded)
{
result.Add(item);
added[items.CurrentNum()] = true;
oneAdded = true;
}
}
}
items.Reset();
return result;
}
Item GOTO(Item item, string start)
{
var result = new Item();
var itemNum = items.IndexOf(item);
item.Reset();
while (item.TryMove())
{
var current = item.Current();
if (current.Right.Length == current.Current)
{
//已经是结束项了,GOTO为空
if (current.Left == "Ex")
{
//接受
Action[itemNum][Vt.Count-1]=new ActionItem(3);
}
else
{
//规约
foreach (string forward in current.Forward)
{
var x = items.IndexOf(item);
var y = Vt.IndexOf(forward);
var willAdd = new ActionItem(2, -1, current.Left, current.Right);
if (Action[x][y] != null && !Action[x][y].Equals(willAdd))
{
var type = Action[x][y].Type;
if (type == 1)
{
throw new Exception("移入规约冲突");
}
if (type == 2)
{
throw new Exception("规约规约冲突");
}
}
Action[x][y]=willAdd;
}
}
continue;
}
var v = Util.GetChar(current.Right, current.Current);
if (v == start)
{
//·后的符号就是GOTO的第二个参数(即检测到的符号),此时生成下一项(下一项存放在result中)
result.Add(new LR1Production(current.Left, current.Right, current.Forward, current.Current + 1));
}
}
if (result.Count() == 0)
{
return null;
}
result = Closure(result);
item.Reset();
return result;
}
void Items()
{
items=new List<Item>();
var i0 = new Item();
i0.Add(new LR1Production("Ex", Vn[0], new HashSet<string> {"$"}));
i0 = Closure(i0);
items.Add(i0);
//ite用于迭代,items用于存储,两者内容上是一样的
var ite = new LinkList<Item>();
ite.Add(i0);
var iteNum = 0;//迭代的次数
while (ite.TryMove())
{
var iteItem = ite.Current();
PrintIteItem(iteNum++,iteItem);
foreach (string v in V)
{
var vti = Vt.IndexOf(v);
var destination = GOTO(iteItem, v);
if (destination != null)
{
//选择items而不是ite进行迭代,ite用于在迭代中增加项的情况,items用于不改变items的情况下
foreach (Item item in items)
{
if (item.First().Equals(destination.First()))
{
goto equal;
}
}
ite.Add(destination);
items.Add(destination);
Console.WriteLine("添加I{0}:",items.IndexOf(destination));
PrintItem(destination);
equal: //destination在items中则进行下一次循环
if (vti != -1)
{
//移入
Action[items.IndexOf(iteItem)][vti] = new ActionItem(1,items.IndexOf(destination));
}
else
{
var vni = Vn.IndexOf(v);
var x = items.IndexOf(iteItem);
var y = items.IndexOf(destination);
Goto[x][vni] = y;
}
}
}
}
}
void PrintIteItem(int iteNum,Item item)
{
Console.WriteLine("正在处理I{0}:",iteNum);
PrintItem(item);
//Thread.Sleep(1000);
}
void PrintItem(Item item)
{
item.Reset();
while (item.TryMove())
{
var current = item.Current();
Console.Write(current.Left +"->");
var right = current.Right;
for (int i = 0; i < right.Length; i++)
{
if (i == current.Current)
{
Console.Write("·");
}
Console.Write(right[i]);
}
if (right.Length == current.Current)
{
Console.Write("·");
}
Console.Write(" , ");
foreach (string s in current.Forward)
{
Console.Write(s +" ");
}
Console.WriteLine();
}
Console.WriteLine();
item.Reset();
//Thread.Sleep(1000);
}
void LR1Drive()
{
var state=new Stack<int>();
var symbol=new Stack<string>();
var symbolProperty=new Stack<(string,int)>();
state.Push(0);
for (var index = 0; index < Input.Length; )
{
char c = Input[index];
var s = c.ToString();
var vti = Vt.IndexOf(s);
var stateTop = state.Peek();
var lex = _lexicalResult[index];
if (vti == -1)
{
Console.WriteLine("无此符号");
return;
}
var action = Action[stateTop][vti];
if (action == null || action.Type == 0)
{
Console.WriteLine("error");
return;
}
if (action.Type == 1)
{
state.Push(action.Shift);
symbol.Push(s);
//symbolProperty.Push(lex.Value == "Digit" ? ("Digit", int.Parse(lex.Key)) : ("Symbol", -1));
index++;
}
else if (action.Type == 2)
{
var popNum = Util.GetChars(action.ReduceRight).Count;
for (int i = 0; i < popNum; i++)
{
symbol.Pop();
//symbolProperty.Pop();
state.Pop();
}
stateTop = state.Peek();
var gotoi = Goto[stateTop][Vn.IndexOf(action.ReduceLeft)];
symbol.Push(action.ReduceLeft);
state.Push(gotoi);
}
else
{
Console.WriteLine("Accept");
return;
}
}
}
void LR1()
{
V = Vn.Merge(Vt);
//规定0为无动作,1为移入,2为规约,3为接受
int itemNum = 100;
Action = new ActionItem[itemNum][];
for (int i = 0; i < Action.Length; i++)
{
Action[i] = new ActionItem[Vt.Count];
}
Goto = new int[itemNum][];
for (int i = 0; i < Goto.Length; i++)
{
Goto[i] = new int[Vn.Count];
}
Items();
//PrintItems();
//LR1Drive();
}
void PrintActionGoto()
{
for (int i = 0; i < items.Count; i++)
{
for (int j = 0; j < Vt.Count; j++)
{
var a = Action[i][j];
if (a == null)
{
Console.Write("error ");
}
else
{
if (a.Type == 1)
{
Console.Write("s");
Console.Write(a.Shift);
Console.Write(" ");
}
else if(a.Type ==2)
{
Console.Write("r");
Console.Write(a.ReduceLeft + "->");
Console.Write(a.ReduceRight + " ");
}
else if (a.Type == 3)
{
Console.Write("acc");
}
}
}
for (int j = 0; j < Vn.Count;j++)
{
var g = Goto[i][j];
Console.Write(g);
Console.Write(" ");
}
Console.WriteLine();
}
}
public void PrintItems()
{
int num = 0;
foreach (Item item in items)
{
Console.WriteLine("I{0}:",num++);
item.Reset();
while (item.TryMove())
{
var current = item.Current();
Console.Write(current.Left +"->");
var right = current.Right;
for (int i = 0; i < right.Length; i++)
{
if (i == current.Current)
{
Console.Write("·");
}
Console.Write(right[i]);
}
if (right.Length == current.Current)
{
Console.Write("·");
}
Console.Write(" , ");
foreach (string s in current.Forward)
{
Console.Write(s +" ");
}
Console.WriteLine();
}
item.Reset();
Console.WriteLine();
}
}
void Dfs(HashSet<string> firstSet, int i, bool[] visited)
{
firstSet.Append(_graph.Vertices[i].S);
visited[i] = true;
for (int j = 0; j < _graph.Vertices.Count; j++)
{
if (_graph.Edges[i, j] && !visited[j])
{
Dfs(firstSet, j, visited);
}
}
}
void MakeArc(string left, string right, string start)
{
_list.Add(left);
_list.Add(right);
if (left != start && !_graph.Edges[Vn.IndexOf(left), Vn.IndexOf(start)])
{
_graph.Edges[Vn.IndexOf(left), Vn.IndexOf(start)] = true;
}
}
public Item Closure(Item items)
{
while (items.TryMove())
{
var item = items.Current();
if (item.Right.Length == item.Current)
{
//说明·后没有字符
continue;
}
var v = Util.GetChar(item.Right, item.Current);
var vi = Vn.IndexOf(v);
if (vi == -1)
{
//说明·后第一个字符是终结符
continue;
}
var rights = Productions[vi];
var endSymbols = FIRST(item);
foreach (string right in rights)
{
var willAdd = new LR1Production(v, right, endSymbols);
if (items.IteForEqual(willAdd) != null)
continue;
items.Add(willAdd);
}
}
items = Simply(items);
//PrintItem(items);
return items;
}
public void Excute()
{
Init();
CalGraph();
GetFirst();
GetFollow();
GetTable();
Up2DownParse();
//LR1();
//LR1Drive();
}
public void Print()
{
_graph.Show();
Console.WriteLine();
for (var i = 0; i < First.Length; i++)
{
Console.Write("FIRST(" + Vn[i] + ") : {");
foreach (string s1 in First[i])
{
Console.Write(s1 + ",");
}
Console.WriteLine("}");
}
Console.WriteLine();
for (var i = 0; i < Follow.Length; i++)
{
Console.Write("Follow(" + Vn[i] + ") : {");
foreach (string s1 in Follow[i])
{
Console.Write(s1 + ",");
}
Console.WriteLine("}");
}
Console.WriteLine();
for (int i = 0; i < Vt.Count; i++)
{
Console.Write(" " + Vt[i] + " ");
}
Console.WriteLine();
for (int i = 0; i < Table.Length; i++)
{
Console.Write(Vn[i] + " ");
for (int j = 0; j < Table[i].Length; j++)
{
if (Table[i][j] == null)
{
Console.Write("null ");
}
else
{
Console.Write(Table[i][j].Left + "-" + Table[i][j].Right + " ");
}
}
Console.WriteLine();
}
PrintActionGoto();
PrintItems();
}
}
} |
using System.Threading;
using static IoUring.Internal.ThrowHelper;
using static IoUring.Internal.Helpers;
using Tmds.Linux;
namespace IoUring.Internal
{
internal sealed unsafe partial class CompletionQueue
{
public bool TryRead(out Completion result)
{
uint head;
uint next;
uint tail;
do
{
head = Volatile.Read(ref *_head);
tail = *_tail;
if (head == tail)
{
result = default;
return false;
}
next = unchecked(head + 1);
var index = head & _ringMask;
var cqe = &_cqes[index];
result = Completion.FromCqe(cqe);
} while (CompareExchange(ref *_head, next, head) != head);
// piggy-back on the read-barrier above to verify that we have no overflows
uint overflow = *_overflow;
if (overflow > 0)
{
ThrowOverflowException(overflow);
}
return true;
}
}
} |
using System;
using UnityEngine;
namespace ProBuilder2.Common
{
[Serializable]
public class pb_Renderable : ScriptableObject
{
public Mesh mesh;
public Material[] materials;
public Matrix4x4 matrix = Matrix4x4.get_identity();
public static pb_Renderable CreateInstance(Mesh InMesh, Material[] InMaterials)
{
pb_Renderable pb_Renderable = ScriptableObject.CreateInstance<pb_Renderable>();
pb_Renderable.mesh = InMesh;
pb_Renderable.materials = InMaterials;
return pb_Renderable;
}
public static pb_Renderable CreateInstance(Mesh InMesh, Material InMaterial)
{
pb_Renderable pb_Renderable = ScriptableObject.CreateInstance<pb_Renderable>();
pb_Renderable.mesh = InMesh;
pb_Renderable.materials = new Material[]
{
InMaterial
};
return pb_Renderable;
}
public void OnDestroy()
{
Object.DestroyImmediate(this.mesh);
if (this.materials != null)
{
for (int i = 0; i < this.materials.Length; i++)
{
if (this.materials[i] != null)
{
Object.DestroyImmediate(this.materials[i]);
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP
{
/**
* Interface ICacheFactory
*
* @package OCP
* @since 7.0.0
*/
public interface ICacheFactory
{
/**
* Get a distributed memory cache instance
*
* All entries added trough the cache instance will be namespaced by prefix to prevent collisions between apps
*
* @param string prefix
* @return ICache
* @since 7.0.0
* @deprecated 13.0.0 Use either createLocking, createDistributed or createLocal
*/
ICache create(string prefix = "");
/**
* Check if any memory cache backend is available
*
* @return bool
* @since 7.0.0
*/
bool isAvailable();
/**
* Check if a local memory cache backend is available
*
* @return bool
* @since 14.0.0
*/
bool isLocalCacheAvailable();
/**
* create a cache instance for storing locks
*
* @param string prefix
* @return IMemcache
* @since 13.0.0
*/
IMemcache createLocking(string prefix= "");
/**
* create a distributed cache instance
*
* @param string prefix
* @return ICache
* @since 13.0.0
*/
ICache createDistributed(string prefix = "");
/**
* create a local cache instance
*
* @param string prefix
* @return ICache
* @since 13.0.0
*/
ICache createLocal(string prefix = "");
}
}
|
using FluentValidation;
namespace DDDSouthWest.Domain.Features.Account.Admin.ManageProfile.UpdateExistingProfile
{
public class UpsertSpeakerProfileValidator : AbstractValidator<UpsertSpeakerProfile.Command>
{
public UpsertSpeakerProfileValidator()
{
RuleFor(x => x.GivenName).NotEmpty();
RuleFor(x => x.FamilyName).NotEmpty();
}
}
} |
using System;
using System.Globalization;
using Newtonsoft.Json;
using Omu.AwesomeMvc;
using Omu.Awem.Utils;
namespace Omu.Awem
{
internal static class Autil
{
internal static string Serialize(object input)
{
return JsonConvert.SerializeObject(input);
}
internal static CultureInfo CurrentCulture()
{
return CultureInfo.CurrentCulture;
}
internal static string ToShortDateString(this DateTime input)
{
return input.ToString("d");
}
internal static bool IsMobileOrTablet<T>(AwesomeHtmlHelper<T> ahtml)
{
return MobileUtils.IsMobileOrTablet(ahtml.Html.ViewContext.HttpContext.Request);
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Savaged.HasMyPasswordBeenPwned.Lib;
namespace Savaged.HasMyPasswordBeenPwned.Test
{
[TestClass]
public class HashServiceTests
{
[TestMethod]
public void TestHash()
{
var hashServ = new HashService("password");
var result = hashServ.Hash;
Assert.AreEqual(
"5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8",
result);
}
}
}
|
using AutoMapper;
using ImmedisHCM.Data.Entities;
using ImmedisHCM.Services.Models.Core;
using NHibernate;
namespace ImmedisHCM.Services.Mapping
{
public class ScheduleTypeMapping : Profile
{
public ScheduleTypeMapping()
{
CreateMap<ScheduleType, ScheduleTypeServiceModel>()
.ForMember(dest => dest.Jobs, opts => opts.PreCondition(src => NHibernateUtil.IsInitialized(src.Jobs)))
.ReverseMap();
}
}
}
|
using Ganss.Excel.Exceptions;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Ganss.Excel
{
/// <summary>
/// Map objects to Excel files.
/// </summary>
public class ExcelMapper
{
/// <summary>
/// Gets or sets the <see cref="TypeMapper"/> factory.
/// Default is a static <see cref="Ganss.Excel.TypeMapperFactory"/> object that caches <see cref="TypeMapper"/>s statically across <see cref="ExcelMapper"/> instances.
/// </summary>
/// <value>
/// The <see cref="TypeMapper"/> factory.
/// </value>
public ITypeMapperFactory TypeMapperFactory { get; set; } = DefaultTypeMapperFactory;
/// <summary>
/// Gets or sets a value indicating whether the Excel file contains a header row of column names. Default is <c>true</c>.
/// </summary>
/// <value>
/// <c>true</c> if the Excel file contains a header row; otherwise, <c>false</c>.
/// </value>
public bool HeaderRow { get; set; } = true;
/// <summary>
/// Gets or sets the row number of the header row. Default is 0.
/// The header row may be outside of the range of <see cref="MinRowNumber"/> and <see cref="MaxRowNumber"/>.
/// </summary>
/// <value>
/// The header row number.
/// </value>
public int HeaderRowNumber { get; set; } = 0;
/// <summary>
/// Gets or sets the minimum row number of the rows that may contain data. Default is 0.
/// </summary>
/// <value>
/// The minimum row number.
/// </value>
public int MinRowNumber { get; set; } = 0;
/// <summary>
/// Gets or sets the inclusive maximum row number of the rows that may contain data. Default is <see cref="int.MaxValue"/>.
/// </summary>
/// <value>
/// The maximum row number.
/// </value>
public int MaxRowNumber { get; set; } = int.MaxValue;
/// <summary>
/// Gets or sets a value indicating whether to track objects read from the Excel file. Default is true.
/// If object tracking is enabled, the <see cref="ExcelMapper"/> object keeps track of objects it yields through the Fetch() methods.
/// You can then modify these objects and save them back to an Excel file without having to specify the list of objects to save.
/// </summary>
/// <value>
/// <c>true</c> if object tracking is enabled; otherwise, <c>false</c>.
/// </value>
public bool TrackObjects { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to skip blank rows when reading from Excel files. Default is true.
/// </summary>
/// <value>
/// <c>true</c> if blank lines are skipped; otherwise, <c>false</c>.
/// </value>
public bool SkipBlankRows { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to skip blank cells when reading from Excel files. Default is true.
/// </summary>
/// <value>
/// <c>true</c> if blank lines are skipped; otherwise, <c>false</c>.
/// </value>
public bool SkipBlankCells { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to create columns in existing Excel files for properties where
/// the corresponding header does not yet exist. If this is false and properties are mapped by name,
/// their corresponding headers must already be present in existing files.
/// Default is false.
/// </summary>
/// <value>
/// <c>true</c> if missing headers should be created; otherwise, <c>false</c>.
/// </value>
public bool CreateMissingHeaders { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore nested types.
/// Default is false.
/// </summary>
/// <value>
/// <c>true</c> if nested types should be ignored; otherwise, <c>false</c>.
/// </value>
public bool IgnoreNestedTypes { get; set; }
/// <summary>
/// Gets or sets the <see cref="DataFormatter"/> object to use when formatting cell values.
/// </summary>
/// <value>
/// The <see cref="DataFormatter"/> object to use when formatting cell values.
/// </value>
public DataFormatter DataFormatter { get; set; } = new DataFormatter(CultureInfo.InvariantCulture);
/// <summary>
/// Occurs before saving and allows the workbook to be manipulated.
/// </summary>
public event EventHandler<SavingEventArgs> Saving;
/// <summary>
/// Occurs while parsing when value is not convertible.
/// Set Cancel to <c>true</c> to Cancel Exception, also, see <see cref="ParsingErrorEventArgs"/>
/// </summary>
public event EventHandler<ParsingErrorEventArgs> ErrorParsingCell;
private Func<string, string> NormalizeName { get; set; }
readonly Dictionary<Type, Func<object>> ObjectFactories = new();
Dictionary<string, Dictionary<int, object>> Objects { get; set; } = new();
IWorkbook Workbook { get; set; }
static readonly TypeMapperFactory DefaultTypeMapperFactory = new();
/// <summary>
/// Initializes a new instance of the <see cref="ExcelMapper"/> class.
/// </summary>
public ExcelMapper() { }
/// <summary>
/// Initializes a new instance of the <see cref="ExcelMapper"/> class.
/// </summary>
/// <param name="workbook">The workbook.</param>
public ExcelMapper(IWorkbook workbook)
{
Workbook = workbook;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExcelMapper"/> class.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
public ExcelMapper(string file)
{
Workbook = WorkbookFactory.Create(file);
}
/// <summary>
/// Initializes a new instance of the <see cref="ExcelMapper"/> class.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
public ExcelMapper(Stream stream)
{
Workbook = WorkbookFactory.Create(stream);
}
/// <summary>
/// Attaches the Excel file from the provided <see cref="IWorkbook"/>.
/// </summary>
/// <param name="workbook">The workbook.</param>
public void Attach(IWorkbook workbook)
{
Workbook = workbook;
}
/// <summary>
/// Attaches the Excel file from the provided path.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
public void Attach(string file)
{
Workbook = WorkbookFactory.Create(file);
}
/// <summary>
/// Attaches the Excel file read from the provided <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
public void Attach(Stream stream)
{
Workbook = WorkbookFactory.Create(stream);
}
/// <summary>
/// Sets a factory function to create objects of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of objects to create.</typeparam>
/// <param name="factory">The factory function.</param>
public void CreateInstance<T>(Func<T> factory)
{
ObjectFactories[typeof (T)] = () => factory();
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<T> Fetch<T>(string file, string sheetName, Func<string, object, object> valueParser = null)
{
return Fetch(file, typeof(T), sheetName, valueParser).OfType<T>();
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable Fetch(string file, Type type, string sheetName, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(file);
return Fetch(type, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<dynamic> Fetch(string file, string sheetName, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(file);
return Fetch(sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<T> Fetch<T>(string file, int sheetIndex, Func<string, object, object> valueParser = null)
{
return Fetch(file, typeof(T), sheetIndex, valueParser).OfType<T>();
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable Fetch(string file, Type type, int sheetIndex, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(file);
return Fetch(type, sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<dynamic> Fetch(string file, int sheetIndex, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(file);
return Fetch(sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<T> Fetch<T>(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
{
return Fetch(stream, typeof(T), sheetName, valueParser).OfType<T>();
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable Fetch(Stream stream, Type type, string sheetName, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(stream);
return Fetch(type, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<dynamic> Fetch(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(stream);
return Fetch(sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<T> Fetch<T>(Stream stream, int sheetIndex, Func<string, object, object> valueParser = null)
{
return Fetch(stream, typeof(T), sheetIndex, valueParser).OfType<T>();
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable Fetch(Stream stream, Type type, int sheetIndex, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(stream);
return Fetch(type, sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<dynamic> Fetch(Stream stream, int sheetIndex, Func<string, object, object> valueParser = null)
{
Workbook = WorkbookFactory.Create(stream);
return Fetch(sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
public IEnumerable<T> Fetch<T>(string sheetName, Func<string, object, object> valueParser = null)
{
return Fetch(typeof(T), sheetName, valueParser).OfType<T>();
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
public IEnumerable Fetch(Type type, string sheetName, Func<string, object, object> valueParser = null)
{
PrimitiveCheck(type);
var sheet = Workbook.GetSheet(sheetName) ?? throw new ArgumentOutOfRangeException(nameof(sheetName), sheetName, "Sheet not found");
return Fetch(sheet, type, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name.
/// </summary>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when a sheet is not found</exception>
public IEnumerable<dynamic> Fetch(string sheetName, Func<string, object, object> valueParser = null)
{
var sheet = Workbook.GetSheet(sheetName) ?? throw new ArgumentOutOfRangeException(nameof(sheetName), sheetName, "Sheet not found");
return Fetch(sheet, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<T> Fetch<T>(int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
var sheet = Workbook.GetSheetAt(sheetIndex);
return Fetch<T>(sheet, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable Fetch(Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
PrimitiveCheck(type);
var sheet = Workbook.GetSheetAt(sheetIndex);
return Fetch(sheet, type, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index.
/// </summary>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public IEnumerable<dynamic> Fetch(int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
var sheet = Workbook.GetSheetAt(sheetIndex);
return Fetch(sheet, valueParser);
}
IEnumerable<T> Fetch<T>(ISheet sheet, Func<string, object, object> valueParser = null)
{
return Fetch(sheet, typeof(T), valueParser).OfType<T>();
}
IEnumerable Fetch(ISheet sheet, Type type, Func<string, object, object> valueParser = null)
{
var firstRowNumber = HeaderRowNumber;
if (!HeaderRow)
firstRowNumber = sheet.Rows().Where(r => r.RowNum >= MinRowNumber && r.RowNum <= MaxRowNumber)
.OrderByDescending(r => r.LastCellNum).FirstOrDefault()?.RowNum ?? 0;
var firstRow = sheet.GetRow(firstRowNumber);
if (firstRow == null)
yield break;
var cells = Enumerable.Range(0, firstRow.LastCellNum).Select(i => firstRow.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK));
var firstRowCells = cells
.Where(c => !HeaderRow || !string.IsNullOrWhiteSpace(c.ToString()));
var typeMapper = type != null ? TypeMapperFactory.Create(type) : TypeMapper.Create(firstRowCells, HeaderRow);
if (TrackObjects) Objects[sheet.SheetName] = new Dictionary<int, object>();
var objInstanceIdx = 0;
foreach (IRow row in sheet)
{
var i = row.RowNum;
if (i < MinRowNumber) continue;
if (i > MaxRowNumber) break;
// optionally skip header row and blank rows
if ((!HeaderRow || i != HeaderRowNumber) && (!SkipBlankRows || row.Cells.Exists(c => !IsCellBlank(c))))
{
object o = MapCells(type, valueParser, typeMapper, firstRowCells, ref objInstanceIdx, row, new HashSet<Type> { type });
yield return o;
}
}
}
IEnumerable<dynamic> Fetch(ISheet sheet, Func<string, object, object> valueParser = null) =>
Fetch(sheet, type: null, valueParser).Cast<dynamic>();
private object MapCells(Type type, Func<string, object, object> valueParser, TypeMapper typeMapper,
IEnumerable<ICell> cells, ref int objInstanceIdx, IRow row, ISet<Type> callChain)
{
var sheet = row.Sheet;
var i = row.RowNum;
List<(ColumnInfo Col, object CellValue, ICell Cell, int ColumnIndex)> initValues = new();
var columns = cells
.Select(c => (Index: c.ColumnIndex,
Columns: GetColumnInfo(typeMapper, c).Where(c => c.Directions.HasFlag(MappingDirections.ExcelToObject) && !c.IsSubType).ToList()))
.Where(c => c.Columns.Any())
.ToList();
foreach (var (columnIndex, columnInfos) in columns)
{
var cell = row.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (cell != null && (!SkipBlankCells || !IsCellBlank(cell)))
{
foreach (var ci in columnInfos)
{
object cellValue;
try
{
cellValue = GetCellValue(cell, ci);
}
catch (Exception e)
{
cellValue = GetCellValue(cell);
TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
}
try
{
if (valueParser != null)
cellValue = valueParser(string.IsNullOrWhiteSpace(ci.Name) ? columnIndex.ToString() : ci.Name, cellValue);
initValues.Add((ci, cellValue, cell, columnIndex));
}
catch (Exception e)
{
TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
}
}
}
}
if (!IgnoreNestedTypes)
{
foreach (var ci in typeMapper.ColumnsByName.SelectMany(c => c.Value).Where(c => c.IsSubType))
{
if (!callChain.Contains(ci.PropertyType) // check for cycle in type hierarchy
&& !initValues.Exists(v => v.Col.Property.IsIdenticalTo(ci.Property))) // map subtypes only if not already mapped
{
callChain.Add(ci.PropertyType);
var subTypeMapper = TypeMapperFactory.Create(ci.PropertyType);
var subObject = MapCells(ci.PropertyType, valueParser, subTypeMapper, cells, ref objInstanceIdx, row, callChain);
initValues.Add((ci, subObject, null, -1));
}
}
}
object o;
if (type == null)
o = typeMapper.CreateExpando();
else
{
if (typeMapper.Constructor != null)
{
var parms = typeMapper.Constructor.GetParameters();
var vals = parms.Select(p => GetDefault(p.ParameterType)).ToArray();
foreach (var initVal in initValues.ToList())
{
if (typeMapper.ConstructorParams.TryGetValue(initVal.Col.Property.Name, out var parm))
{
try
{
object v;
if (initVal.Cell != null)
v = initVal.Col.GetPropertyValue(null, initVal.CellValue, initVal.Cell);
else
v = initVal.CellValue;
vals[parm.Position] = v;
initValues.Remove(initVal);
}
catch (Exception ex)
{
TriggerOrThrowParsingError(new ExcelMapperConvertException(initVal.CellValue, initVal.Col.PropertyType, i, initVal.ColumnIndex, ex));
}
}
}
try
{
o = typeMapper.Constructor.Invoke(vals);
}
catch (Exception ex)
{
throw new ExcelMapperConvertException($"Failed to initialize type {type.FullName}.", ex);
}
}
else
{
if (ObjectFactories.TryGetValue(type, out var factory))
{
o = factory();
}
else
{
try
{
o = Activator.CreateInstance(type);
}
catch (Exception)
{
o = null;
}
}
if (o == null)
return null;
}
}
if (initValues.Any())
{
typeMapper?.BeforeMappingActionInvoker?.Invoke(o, objInstanceIdx);
foreach (var val in initValues)
{
try
{
if (val.Cell != null)
val.Col.SetProperty(o, val.CellValue, val.Cell);
else
val.Col.Property.SetValue(o, val.CellValue);
}
catch (Exception ex)
{
TriggerOrThrowParsingError(new ExcelMapperConvertException(val.CellValue, val.Col.PropertyType, i, val.ColumnIndex, ex));
}
}
}
if (TrackObjects) Objects[sheet.SheetName][i] = o;
typeMapper?.AfterMappingActionInvoker?.Invoke(o, objInstanceIdx);
objInstanceIdx++;
return o;
}
private void TriggerOrThrowParsingError(ExcelMapperConvertException excelMapperConvertException)
{
var parsingError = new ParsingErrorEventArgs(excelMapperConvertException);
ErrorParsingCell?.Invoke(this, parsingError);
if (!parsingError.Cancel)
throw excelMapperConvertException;
}
static object GetDefault(Type t) => t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null;
/// <summary>
/// Fetches objects from the specified sheet name using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<T>> FetchAsync<T>(string file, string sheetName, Func<string, object, object> valueParser = null)
{
return (await FetchAsync(file, typeof(T), sheetName, valueParser)).OfType<T>();
}
/// <summary>
/// Fetches dynamic objects from the specified sheet name using async I/O.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<dynamic>> FetchAsync(string file, string sheetName, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(file);
return Fetch(ms, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name using async I/O.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable> FetchAsync(string file, Type type, string sheetName, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(file);
return Fetch(ms, type, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<T>> FetchAsync<T>(string file, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(file);
return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
}
/// <summary>
/// Fetches dynamic objects from the specified sheet index using async I/O.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<dynamic>> FetchAsync(string file, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(file);
return Fetch(ms, sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index using async I/O.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable> FetchAsync(string file, Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(file);
return Fetch(ms, type, sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, typeof(T), sheetName, valueParser).OfType<T>();
}
/// <summary>
/// Fetches dynamic objects from the specified sheet name using async I/O.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<dynamic>> FetchAsync(Stream stream, string sheetName, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet name using async I/O.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable> FetchAsync(Stream stream, Type type, string sheetName, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, type, sheetName, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects the Excel file is mapped to.</typeparam>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
}
/// <summary>
/// Fetches dynamic objects from the specified sheet index using async I/O.
/// </summary>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable<dynamic>> FetchAsync(Stream stream, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, sheetIndex, valueParser);
}
/// <summary>
/// Fetches objects from the specified sheet index using async I/O.
/// </summary>
/// <param name="type">The type of objects the Excel file is mapped to.</param>
/// <param name="stream">The stream the Excel file is read from.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="valueParser">Allow value parsing</param>
/// <returns>The objects read from the Excel file.</returns>
public async Task<IEnumerable> FetchAsync(Stream stream, Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
{
using var ms = await ReadAsync(stream);
return Fetch(ms, type, sheetIndex, valueParser);
}
/// <summary>
/// Fetches the names of all sheets.
/// </summary>
/// <returns>The sheet names.</returns>
public IEnumerable<string> FetchSheetNames() => FetchSheetNames(ignoreHidden: false);
/// <summary>
/// Fetches the names of all sheets.
/// </summary>
/// <param name="ignoreHidden">Indicates if hidden sheets should be ignored.</param>
/// <returns>The sheet names.</returns>
public IEnumerable<string> FetchSheetNames(bool ignoreHidden) => Workbook == null ? Array.Empty<string>()
: Enumerable.Range(0, Workbook.NumberOfSheets).Where(i => !ignoreHidden || !Workbook.IsSheetHidden(i)).Select(i => Workbook.GetSheetName(i));
static async Task<Stream> ReadAsync(string file)
{
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
var ms = new MemoryStream();
await fs.CopyToAsync(ms);
return ms;
}
static async Task<Stream> ReadAsync(Stream stream)
{
var ms = new MemoryStream();
await stream.CopyToAsync(ms);
return ms;
}
private static bool IsCellBlank(ICell cell)
{
return cell.CellType switch
{
CellType.String => string.IsNullOrWhiteSpace(cell.StringCellValue),
CellType.Blank => true,
_ => false,
};
}
List<ColumnInfo> GetColumnInfo(TypeMapper typeMapper, ICell cell)
{
var colByIndex = typeMapper.GetColumnByIndex(cell.ColumnIndex);
if (!HeaderRow || colByIndex != null)
return colByIndex ?? new();
var name = cell.ToString();
var normalizedName = NormalizeCellName(typeMapper, name);
var colByName = typeMapper.GetColumnByName(normalizedName);
// map column by name only if it hasn't been mapped to another property by index
if (colByName != null
&& !typeMapper.ColumnsByIndex.SelectMany(ci => ci.Value).Any(c => c.Property.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
return colByName;
return new();
}
private string NormalizeCellName(TypeMapper typeMapper, string name)
{
if (typeMapper.NormalizeName != null) return typeMapper.NormalizeName(name);
else if (NormalizeName != null) return NormalizeName(name);
return name;
}
/// <summary>
/// Saves the specified objects to the specified Excel file.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save<T>(string file, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
Save(fs, objects, sheetName, xlsx, valueConverter);
}
/// <summary>
/// Saves the specified objects to the specified Excel file.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save<T>(string file, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
Save(fs, objects, sheetIndex, xlsx, valueConverter);
}
/// <summary>
/// Saves the specified objects to the specified stream.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save<T>(Stream stream, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
var sheet = Workbook.GetSheet(sheetName);
sheet ??= Workbook.CreateSheet(sheetName);
Save(stream, sheet, objects, valueConverter);
}
/// <summary>
/// Saves the specified objects to the specified stream.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
ISheet sheet;
if (Workbook.NumberOfSheets > sheetIndex)
sheet = Workbook.GetSheetAt(sheetIndex);
else
sheet = Workbook.CreateSheet();
Save(stream, sheet, objects, valueConverter);
}
/// <summary>
/// Saves tracked objects to the specified Excel file.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save(string file, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
Save(fs, sheetName, xlsx, valueConverter);
}
/// <summary>
/// Saves tracked objects to the specified Excel file.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save(string file, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var fs = File.Open(file, FileMode.Create, FileAccess.Write);
Save(fs, sheetIndex, xlsx, valueConverter);
}
/// <summary>
/// Saves tracked objects to the specified stream.
/// </summary>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save(Stream stream, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
var sheet = Workbook.GetSheet(sheetName);
sheet ??= Workbook.CreateSheet(sheetName);
Save(stream, sheet, valueConverter);
}
/// <summary>
/// Saves tracked objects to the specified stream.
/// </summary>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public void Save(Stream stream, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
Workbook ??= xlsx ? (IWorkbook)new XSSFWorkbook() : (IWorkbook)new HSSFWorkbook();
var sheet = Workbook.GetSheetAt(sheetIndex);
sheet ??= Workbook.CreateSheet();
Save(stream, sheet, valueConverter);
}
void Save(Stream stream, ISheet sheet, Func<string, object, object> valueConverter = null)
{
var objects = Objects[sheet.SheetName];
var typeMapper = TypeMapperFactory.Create(objects.First().Value);
var columnsByIndex = typeMapper.ColumnsByIndex;
columnsByIndex = columnsByIndex.Where(kvp => !kvp.Value.TrueForAll(ci => ci.Directions == MappingDirections.ExcelToObject))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
GetColumns(sheet, typeMapper, columnsByIndex);
SetColumnStyles(sheet, columnsByIndex);
foreach (var o in objects)
{
var i = o.Key;
var row = sheet.GetRow(i);
row ??= sheet.CreateRow(i);
SetCells(typeMapper, columnsByIndex, o.Value, row, valueConverter);
}
Saving?.Invoke(this, new SavingEventArgs(sheet));
Workbook.Write(stream, leaveOpen: true);
}
void Save<T>(Stream stream, ISheet sheet, IEnumerable<T> objects, Func<string, object, object> valueConverter = null)
{
var firstObject = objects.FirstOrDefault();
var typeMapper = firstObject is ExpandoObject ? TypeMapperFactory.Create(firstObject) : TypeMapperFactory.Create(typeof(T));
var columnsByIndex = typeMapper.ColumnsByIndex;
var i = MinRowNumber;
columnsByIndex = columnsByIndex.Where(kvp => !kvp.Value.TrueForAll(ci => ci.Directions == MappingDirections.ExcelToObject))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
GetColumns(sheet, typeMapper, columnsByIndex);
SetColumnStyles(sheet, columnsByIndex);
foreach (var o in objects)
{
if (i > MaxRowNumber) break;
if (HeaderRow && i == HeaderRowNumber)
i++;
var row = sheet.GetRow(i);
row ??= sheet.CreateRow(i);
SetCells(typeMapper, columnsByIndex, o, row, valueConverter);
i++;
}
if (SkipBlankCells)
{
while (i <= sheet.LastRowNum && i <= MaxRowNumber)
{
var row = sheet.GetRow(i);
while (row.Cells.Any())
row.RemoveCell(row.GetCell(row.FirstCellNum));
i++;
}
}
Saving?.Invoke(this, new SavingEventArgs(sheet));
Workbook.Write(stream, leaveOpen: true);
}
private void SetCells(TypeMapper typeMapper,
Dictionary<int, List<ColumnInfo>> columnsByIndex,
object o, IRow row,
Func<string, object, object> valueConverter = null)
{
var columnsByName = typeMapper.ColumnsByName;
foreach (var col in columnsByIndex)
{
var cell = row.GetCell(col.Key, MissingCellPolicy.CREATE_NULL_AS_BLANK);
foreach (var ci in col.Value.Where(c => (c is DynamicColumnInfo)
|| (c.Directions.HasFlag(MappingDirections.ObjectToExcel)
&& (c?.Property?.DeclaringType.IsAssignableFrom(typeMapper.Type) == true))))
{
SetCell(valueConverter, o, cell, ci);
}
}
if (!IgnoreNestedTypes)
{
foreach (var col in columnsByName.SelectMany(c => c.Value.Where(c => c.Directions.HasFlag(MappingDirections.ObjectToExcel) && c.IsSubType)))
{
var subTypeMapper = TypeMapperFactory.Create(col.PropertyType);
var subObject = col.Property.GetValue(o);
if (subObject != null)
{
SetCells(subTypeMapper, columnsByIndex, subObject, row, valueConverter);
}
}
}
}
private static void SetCell<T>(Func<string, object, object> valueConverter, T objInstance, ICell cell, ColumnInfo ci)
{
Type oldType = null;
object val = ci.GetProperty(objInstance);
if (valueConverter != null)
{
val = valueConverter(ci.Name, val);
}
//When the value is a dynamic type or has a specified value conversion function, the type may be inconsistent, and the type needs to be changed
var newType = val?.GetType() ?? ci.PropertyType;
if (newType != ci.PropertyType)
{
oldType = ci.PropertyType;
ci.ChangeSetterType(newType);
}
ci.SetCellStyle(cell);
ci.SetCell(cell, val);
if (oldType != null)
ci.ChangeSetterType(oldType);
}
/// <summary>
/// Saves the specified objects to the specified Excel file using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync<T>(string file, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, objects, sheetName, xlsx, valueConverter);
await SaveAsync(file, ms.ToArray());
}
/// <summary>
/// Saves the specified objects to the specified Excel file using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="file">The path to the Excel file.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync<T>(string file, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, objects, sheetIndex, xlsx, valueConverter);
await SaveAsync(file, ms.ToArray());
}
/// <summary>
/// Saves the specified objects to the specified stream using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, objects, sheetName, xlsx, valueConverter);
await SaveAsync(stream, ms);
}
/// <summary>
/// Saves the specified objects to the specified stream using async I/O.
/// </summary>
/// <typeparam name="T">The type of objects to save.</typeparam>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="objects">The objects to save.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync<T>(Stream stream, IEnumerable<T> objects, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, objects, sheetIndex, xlsx, valueConverter);
await SaveAsync(stream, ms);
}
/// <summary>
/// Saves tracked objects to the specified Excel file using async I/O.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync(string file, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, sheetName, xlsx, valueConverter);
await SaveAsync(file, ms.ToArray());
}
/// <summary>
/// Saves tracked objects to the specified Excel file using async I/O.
/// </summary>
/// <param name="file">The path to the Excel file.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync(string file, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, sheetIndex, xlsx, valueConverter);
await SaveAsync(file, ms.ToArray());
}
/// <summary>
/// Saves tracked objects to the specified stream using async I/O.
/// </summary>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="sheetName">Name of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync(Stream stream, string sheetName, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, sheetName, xlsx, valueConverter);
await SaveAsync(stream, ms);
}
/// <summary>
/// Saves tracked objects to the specified stream using async I/O.
/// </summary>
/// <param name="stream">The stream to save the objects to.</param>
/// <param name="sheetIndex">Index of the sheet.</param>
/// <param name="xlsx">if set to <c>true</c> saves in .xlsx format; otherwise, saves in .xls format.</param>
/// <param name="valueConverter">converter receiving property name and value</param>
public async Task SaveAsync(Stream stream, int sheetIndex = 0, bool xlsx = true, Func<string, object, object> valueConverter = null)
{
using var ms = new MemoryStream();
Save(ms, sheetIndex, xlsx, valueConverter);
await SaveAsync(stream, ms);
}
static async Task SaveAsync(string file, byte[] buf)
{
using var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
await fs.WriteAsync(buf, 0, buf.Length);
}
static async Task SaveAsync(Stream stream, MemoryStream ms)
{
var buf = ms.ToArray();
await stream.WriteAsync(buf, 0, buf.Length);
}
static void SetColumnStyles(ISheet sheet, Dictionary<int, List<ColumnInfo>> columnsByIndex)
{
foreach (var col in columnsByIndex)
col.Value.Where(c => c.Directions.HasFlag(MappingDirections.ObjectToExcel))
.ToList().ForEach(ci => ci.SetColumnStyle(sheet, col.Key));
}
void GetColumns(ISheet sheet, TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex)
{
var callChain = new HashSet<Type> { typeMapper.Type };
if (HeaderRow)
{
var headerRow = sheet.GetRow(HeaderRowNumber);
if (headerRow == null)
{
headerRow = sheet.CreateRow(HeaderRowNumber);
var columnIndex = 0;
PopulateHeaderRow(typeMapper, columnsByIndex, headerRow, ref columnIndex, callChain);
}
else
{
if (CreateMissingHeaders)
{
UpdateHeaderRow(typeMapper, columnsByIndex, headerRow, callChain);
}
else
{
ReadHeaderRow(typeMapper, columnsByIndex, headerRow, callChain);
}
}
}
else
{
columnsByIndex.Clear();
GatherColumnIndexes(typeMapper, columnsByIndex, callChain);
}
}
private void GatherColumnIndexes(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, ISet<Type> callChain)
{
var columnsByName = typeMapper.ColumnsByName;
foreach (var (index, columns) in typeMapper.ColumnsByIndex.Select(p => (Index: p.Key,
Columns: p.Value.Where(c => c.Directions != MappingDirections.ExcelToObject && !c.IsSubType))))
{
if (!columnsByIndex.TryGetValue(index, out var columnInfos))
columnsByIndex[index] = columnInfos = new();
columnInfos.AddRange(columns);
}
if (!IgnoreNestedTypes)
{
foreach (var propertyType in columnsByName.SelectMany(c => c.Value.Where(c => c.Directions != MappingDirections.ExcelToObject && c.IsSubType))
.Select(c => c.PropertyType))
{
if (!callChain.Contains(propertyType))
{
callChain.Add(propertyType);
var subTypeMapper = TypeMapperFactory.Create(propertyType);
GatherColumnIndexes(subTypeMapper, columnsByIndex, callChain);
}
}
}
}
private void UpdateHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, IRow headerRow, ISet<Type> callChain)
{
var columnsByName = typeMapper.ColumnsByName;
foreach (var col in columnsByName)
{
foreach (var columnInfo in col.Value.Where(c => c.Directions != MappingDirections.ExcelToObject))
{
if (!columnInfo.IsSubType)
{
var columnInfoByIndex = columnsByIndex.FirstOrDefault(c => c.Value.Exists(v =>
v.Directions != MappingDirections.ObjectToExcel && v.Property.IsIdenticalTo(columnInfo.Property)));
var columnIndex = 0;
if (columnInfoByIndex.Value == null)
{
for (; columnIndex < headerRow.LastCellNum; columnIndex++)
{
var c = headerRow.GetCell(columnIndex, MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (c == null || string.IsNullOrEmpty(c.ToString()))
break;
}
}
else
{
columnIndex = columnInfoByIndex.Key;
}
var cell = headerRow.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
columnsByIndex[columnIndex] = col.Value;
cell.SetCellValue(col.Key);
}
else if (!IgnoreNestedTypes && !callChain.Contains(columnInfo.PropertyType))
{
callChain.Add(columnInfo.PropertyType);
var subTypeMapper = TypeMapperFactory.Create(columnInfo.PropertyType);
UpdateHeaderRow(subTypeMapper, columnsByIndex, headerRow, callChain);
}
}
}
}
private void ReadHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex, IRow headerRow, ISet<Type> callChain)
{
foreach (var cols in headerRow.Cells
.Where(c => !string.IsNullOrWhiteSpace(c.ToString()))
.Select(c =>
{
var name = c.ToString();
var normalizedName = NormalizeCellName(typeMapper, name);
var val = new { c.ColumnIndex, ColumnInfo = typeMapper.GetColumnByName(normalizedName), ColumnName = c.ToString() };
return val;
})
.Where(c => c.ColumnInfo != null))
{
var columnIndex = cols.ColumnIndex;
if (!columnsByIndex.TryGetValue(columnIndex, out var columnInfos))
columnsByIndex[columnIndex] = columnInfos = new();
foreach (var col in cols.ColumnInfo.Where(c => c.Directions != MappingDirections.ExcelToObject && !c.IsSubType))
{
columnInfos.Add(col);
}
}
if (!IgnoreNestedTypes)
{
foreach (var columns in typeMapper.ColumnsByName)
{
foreach (var propertyType in columns.Value.Where(c => c.IsSubType && !callChain.Contains(c.PropertyType))
.Select(c => c.PropertyType))
{
callChain.Add(propertyType);
var subTypeMapper = TypeMapperFactory.Create(propertyType);
ReadHeaderRow(subTypeMapper, columnsByIndex, headerRow, callChain);
}
}
}
}
private void PopulateHeaderRow(TypeMapper typeMapper, Dictionary<int, List<ColumnInfo>> columnsByIndex,
IRow headerRow, ref int columnIndex, ISet<Type> callChain)
{
var typeColumnsByName = typeMapper.ColumnsByName;
var typeColumnsByIndex = typeMapper.ColumnsByIndex;
foreach (var columns in typeColumnsByName)
{
var noSubTypeColumns = columns.Value.Where(c => !c.IsSubType && c.Directions != MappingDirections.ExcelToObject).ToList();
if (noSubTypeColumns.Any())
{
var columnIndexes = typeColumnsByIndex.Where(c =>
c.Value.Exists(v => v.Directions != MappingDirections.ExcelToObject && noSubTypeColumns.Exists(n => n.Name == v.Name)))
.Select(c => c.Key);
if (columnIndexes.Any())
{
columnIndex = columnIndexes.First();
}
else
{
if (!columnsByIndex.TryGetValue(columnIndex, out var columnInfos))
columnsByIndex[columnIndex] = noSubTypeColumns;
else
columnInfos.AddRange(noSubTypeColumns);
}
var cell = headerRow.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellValue(columns.Key);
columnIndex++;
}
if (!IgnoreNestedTypes)
{
foreach (var propertyType in columns.Value.Where(c => c.IsSubType && !callChain.Contains(c.PropertyType))
.Select(c => c.PropertyType))
{
callChain.Add(propertyType);
var subTypeMapper = TypeMapperFactory.Create(propertyType);
PopulateHeaderRow(subTypeMapper, columnsByIndex, headerRow, ref columnIndex, callChain);
}
}
}
}
object GetCellValue(ICell cell, ColumnInfo targetColumn)
{
var formulaResult = cell.CellType == CellType.Formula && (targetColumn.PropertyType != typeof(string) || targetColumn.FormulaResult);
var cellType = formulaResult ? cell.CachedFormulaResultType : cell.CellType;
const int maxDate = 2958465; // 31/12/9999
switch (cellType)
{
case CellType.Numeric:
if (!formulaResult && targetColumn.PropertyType == typeof(string))
{
return DataFormatter.FormatCellValue(cell);
}
else if (cell.NumericCellValue <= maxDate && DateUtil.IsCellDateFormatted(cell))
{
return cell.DateCellValue;
}
else
return cell.NumericCellValue;
case CellType.Formula:
return cell.CellFormula;
case CellType.Boolean:
return cell.BooleanCellValue;
case CellType.Error:
var targetType = targetColumn.PropertyType;
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
case CellType.Unknown:
case CellType.Blank:
case CellType.String:
default:
if (targetColumn.Json)
return JsonSerializer.Deserialize(cell.StringCellValue, targetColumn.PropertyType);
else
return cell.StringCellValue;
}
}
object GetCellValue(ICell cell)
{
return cell.CellType switch
{
CellType.Numeric => cell.NumericCellValue,
CellType.Formula => cell.CellFormula,
CellType.Boolean => cell.BooleanCellValue,
CellType.Error => cell.ErrorCellValue,
CellType.String => cell.StringCellValue,
CellType.Blank => string.Empty,
_ => "<unknown>",
};
}
static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> propertyExpression)
{
var exp = (LambdaExpression)propertyExpression;
var mExp = (exp.Body.NodeType == ExpressionType.MemberAccess) ?
(MemberExpression)exp.Body :
(MemberExpression)((UnaryExpression)exp.Body).Operand;
return (PropertyInfo)mExp.Member;
}
static void PrimitiveCheck(Type type)
{
if (type.IsPrimitive || typeof(string).Equals(type) || typeof(object).Equals(type) || Nullable.GetUnderlyingType(type) != null)
{
throw new ArgumentException($"{type.Name} can not be used to map an excel because it is a primitive type");
}
}
/// <summary>
/// Action to call after an object is mapped
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <returns></returns>
public ExcelMapper AddAfterMapping<T>(Action<T, int> action)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
typeMapper.AfterMappingActionInvoker = ActionInvoker.CreateInstance(action);
return this;
}
/// <summary>
/// Action to call before an object is mapped
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <returns></returns>
public ExcelMapper AddBeforeMapping<T>(Action<T, int> action)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
typeMapper.BeforeMappingActionInvoker = ActionInvoker.CreateInstance(action);
return this;
}
/// <summary>
/// Adds a mapping from a column name to a property.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columnName">Name of the column.</param>
/// <param name="propertyExpression">The property expression.</param>
public ColumnInfo AddMapping<T>(string columnName, Expression<Func<T, object>> propertyExpression)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
var prop = GetPropertyInfo(propertyExpression);
if (!typeMapper.ColumnsByName.ContainsKey(columnName))
typeMapper.ColumnsByName.Add(columnName, new List<ColumnInfo>());
var columnInfo = typeMapper.ColumnsByName[columnName].Find(ci => ci.Property.Name == prop.Name);
if (columnInfo is null)
{
columnInfo = new ColumnInfo(prop);
typeMapper.ColumnsByName[columnName].Add(columnInfo);
}
return columnInfo;
}
/// <summary>
/// Adds a mapping from a column index to a property.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columnIndex">Index of the column.</param>
/// <param name="propertyExpression">The property expression.</param>
public ColumnInfo AddMapping<T>(int columnIndex, Expression<Func<T, object>> propertyExpression)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
var prop = GetPropertyInfo(propertyExpression);
var idx = columnIndex - 1;
if (!typeMapper.ColumnsByIndex.ContainsKey(idx))
typeMapper.ColumnsByIndex.Add(idx, new List<ColumnInfo>());
var columnInfo = typeMapper.ColumnsByIndex[idx].Find(ci => ci.Property.Name == prop.Name);
if (columnInfo is null)
{
columnInfo = new ColumnInfo(prop);
typeMapper.ColumnsByIndex[idx].Add(columnInfo);
}
return columnInfo;
}
/// <summary>
/// Adds a mapping from a column name to a property.
/// </summary>
/// <param name="t">The type that contains the property to map to.</param>
/// <param name="columnName">Name of the column.</param>
/// <param name="propertyName">Name of the property.</param>
public ColumnInfo AddMapping(Type t, string columnName, string propertyName)
{
var typeMapper = TypeMapperFactory.Create(t);
var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
if (!typeMapper.ColumnsByName.ContainsKey(columnName))
typeMapper.ColumnsByName.Add(columnName, new List<ColumnInfo>());
var columnInfo = typeMapper.ColumnsByName[columnName].Find(ci => ci.Property.Name == prop.Name);
if (columnInfo is null)
{
columnInfo = new ColumnInfo(prop);
typeMapper.ColumnsByName[columnName].Add(columnInfo);
}
return columnInfo;
}
/// <summary>
/// Adds a mapping from a column name to a property.
/// </summary>
/// <param name="t">The type that contains the property to map to.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <param name="propertyName">Name of the property.</param>
public ColumnInfo AddMapping(Type t, int columnIndex, string propertyName)
{
var typeMapper = TypeMapperFactory.Create(t);
var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
var idx = columnIndex - 1;
if (!typeMapper.ColumnsByIndex.ContainsKey(idx))
typeMapper.ColumnsByIndex.Add(idx, new List<ColumnInfo>());
var columnInfo = typeMapper.ColumnsByIndex[idx].Find(ci => ci.Property.Name == prop.Name);
if (columnInfo is null)
{
columnInfo = new ColumnInfo(prop);
typeMapper.ColumnsByIndex[idx].Add(columnInfo);
}
return columnInfo;
}
/// <summary>
/// Ignores a property.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="propertyExpression">The property expression.</param>
public void Ignore<T>(Expression<Func<T, object>> propertyExpression)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
var prop = GetPropertyInfo(propertyExpression);
typeMapper.ColumnsByName.Where(c => c.Value.Exists(cc => cc.Property.IsIdenticalTo(prop)))
.ToList().ForEach(kvp => typeMapper.ColumnsByName.Remove(kvp.Key));
}
/// <summary>
/// Ignores a property.
/// </summary>
/// <param name="t">The type that contains the property to map to.</param>
/// <param name="propertyName">Name of the property.</param>
public void Ignore(Type t, string propertyName)
{
var typeMapper = TypeMapperFactory.Create(t);
var prop = t.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
typeMapper.ColumnsByName.Where(c => c.Value.Exists(cc => cc.Property.IsIdenticalTo(prop)))
.ToList().ForEach(kvp => typeMapper.ColumnsByName.Remove(kvp.Key));
}
/// <summary>
/// Sets a name normalization function.
/// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
/// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
/// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
/// The default is the identity function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="normalizeName">The name normalization function.</param>
public void NormalizeUsing<T>(Func<string, string> normalizeName)
{
var typeMapper = TypeMapperFactory.Create(typeof(T));
typeMapper.NormalizeName = normalizeName;
}
/// <summary>
/// Sets a name normalization function.
/// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
/// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
/// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
/// The default is the identity function.
/// </summary>
/// <param name="t">The type that contains the property to map to.</param>
/// <param name="normalizeName">The name normalization function.</param>
public void NormalizeUsing(Type t, Func<string, string> normalizeName)
{
var typeMapper = TypeMapperFactory.Create(t);
typeMapper.NormalizeName = normalizeName;
}
/// <summary>
/// Sets a default name normalization function.
/// This function is used when the <see cref="ExcelMapper"/> object tries to find a property name from a header cell value.
/// It can be used if the input header cell values may contain a larger number of possible values that can be easily mapped
/// backed to a single property name through a function, e.g. if the header cell may contain varying amounts of whitespace.
/// This default normalization function works across types. If a normalization function is set for a specific type it takes
/// precedence over this default function.
/// The default is the identity function.
/// </summary>
/// <param name="normalizeName">The name normalization function.</param>
public void NormalizeUsing(Func<string, string> normalizeName)
{
NormalizeName = normalizeName;
}
internal static readonly Regex ColumnLetterRegex = new("^\\$?[A-Z]+$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
/// <summary>
/// Converts Excel column letters to column indexes (e.g. "A" yields 1).
/// </summary>
/// <param name="letter">The Excel column letter.</param>
/// <returns>The column index.</returns>
public static int LetterToIndex(string letter)
{
if (letter == null || !ColumnLetterRegex.IsMatch(letter))
throw new ArgumentException($"Column letters out of range: {letter}", nameof(letter));
return CellReference.ConvertColStringToIndex(letter) + 1;
}
/// <summary>
/// Converts a column index to the corresponding Excel column letter or letters (e.g. 1 yields "A").
/// </summary>
/// <param name="index">The column index.</param>
/// <returns>The Excel column letter or letters.</returns>
public static string IndexToLetter(int index)
{
if (index < 1)
throw new ArgumentException($"Column index out of range: {index}", nameof(index));
return CellReference.ConvertNumToColString(index - 1);
}
}
}
|
//Based on the class originated from github.com/Microsoft/HoloToolkit-Unity/
//The button class controls the state of all the button used in the project.
using UnityEngine;
using Scripts;
using UnityEngine.Events;
public class Button : Singleton<Button>
{
public State StartingState;
private Renderer buttonRenderer;
public State currentState = State.Inactive;
public enum State { Inactive, Active, Gazed, Selected };
void Awake()
{
buttonRenderer = GetComponent<Renderer>();
ChangeButtonState(StartingState);
}
public bool IsOn()
{
return currentState != State.Inactive;
}
public void SetActive(bool setOn)
{
if (setOn)
{
ChangeButtonState(State.Active);
if (InteractibleManager.Instance.FocusedGameObject == gameObject)
{
ChangeButtonState(State.Gazed);
}
}
else
{
ChangeButtonState(State.Inactive);
}
}
public void ChangeButtonState(State newState)
{
State oldState = currentState;
currentState = newState;
if (newState > oldState)
{
for (int j = (int)newState; j > (int)oldState; j--)
{
buttonRenderer.material.SetFloat("_BlendTex0" + j, 1.0f);
}
}
else
{
for (int j = (int)oldState; j > (int)newState; j--)
{
buttonRenderer.material.SetFloat("_BlendTex0" + j, 0.0f);
}
}
}
}
|
using UnityEngine;
using Mog;
using UnityEngine.UI;
public class ImageBlinker : MogImage {
public Sprite[] images;
public float blinkTime = 0.5F;
private int count;
private float lastBlinkTime = 0F;
protected void OnEnable () {
count = 0;
}
int IncrementCount () {
count = (count + 1) % images.Length;
return count;
}
void Update () {
if (images != null && images.Length > 0 && Time.realtimeSinceStartup - lastBlinkTime > blinkTime) {
lastBlinkTime = Time.realtimeSinceStartup;
base.Set(images[IncrementCount()]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ext;
using OCP.Files;
using File = System.IO.File;
namespace OC.Files
{
/**
* Class to provide access to ownCloud filesystem via a "view", and methods for
* working with files within that view (e.g. read, write, delete, etc.). Each
* view is restricted to a set of directories via a virtual root. The default view
* uses the currently logged in user's data directory as root (parts of
* OC_Filesystem are merely a wrapper for OC\Files\View).
*
* Apps that need to access files outside of the user data folders (to modify files
* belonging to a user other than the one currently logged in, for example) should
* use this class directly rather than using OC_Filesystem, or making use of PHP's
* built-in file manipulation functions. This will ensure all hooks and proxies
* are triggered correctly.
*
* Filesystem functions are not called directly; they are passed to the correct
* \OC\Files\Storage\Storage object
*/
public class View
{
/** @var string */
private string fakeRoot = "";
/**
* @var \OCP\Lock\ILockingProvider
*/
protected OCP.Lock.ILockingProvider lockingProvider;
private bool lockingEnabled;
private bool updaterEnabled = true;
/** @var \OC\User\Manager */
private User.Manager userManager;
/** @var \OCP\ILogger */
private OCP.ILogger logger;
/**
* @param string root
* @throws \Exception If root contains an invalid path
*/
public View(string root = "")
{
if (root == null)
{
throw new ArgumentNullException("Root can\'t be null");
}
if (!File.Exists(root))
{
throw new Exception();
}
this.fakeRoot = root;
this.lockingProvider = OC.server.getLockingProvider();
this.lockingEnabled = !(this.lockingProvider is OC.Lock.NoopLockingProvider);
this.userManager = OC::server.getUserManager();
this.logger = OC::server.getLogger();
}
public string getAbsolutePath(string path = "/")
{
if (path.IsEmpty())
{
return null;
}
this.assertPathLength(path);
if (path == "") {
path = "/";
}
if (path[0] != '/') {
path = "/" + path;
}
return this.fakeRoot + path;
}
/**
* change the root to a fake root
*
* @param string fakeRoot
* @return boolean|null
*/
public void chroot(string fakeRoot)
{
if (fakeRoot.IsNotEmpty()) {
if (fakeRoot[0] != '/') {
fakeRoot = "/" + fakeRoot;
}
}
this.fakeRoot = fakeRoot;
}
/**
* get the fake root
*
* @return string
*/
public string getRoot()
{
return this.fakeRoot;
}
/**
* get path relative to the root of the view
*
* @param string path
* @return string
*/
public string getRelativePath(string path)
{
this.assertPathLength(path);
if (this.fakeRoot.IsEmpty()) {
return path;
}
if (path.TrimEnd('/') == this.fakeRoot.TrimEnd('/'))
{
return "/";
}
// missing slashes can cause wrong matches!
var root = this.fakeRoot.TrimEnd('/') + "/";
// if (strpos($path, $root) !== 0) {
if (path.IndexOf(root) != 0)
{
return null;
}
else
{
path = path.Substring(this.fakeRoot.Length);
if (path.Length == 0)
{
return "/";
}
else
{
return path;
}
}
}
/**
* get the mountpoint of the storage object for a path
* ( note: because a storage is not always mounted inside the fakeroot, the
* returned mountpoint is relative to the absolute root of the filesystem
* and does not take the chroot into account )
*
* @param string path
* @return string
*/
public string getMountPoint(string path)
{
return Filesystem::getMountPoint(this.getAbsolutePath(path));
}
/**
* get the mountpoint of the storage object for a path
* ( note: because a storage is not always mounted inside the fakeroot, the
* returned mountpoint is relative to the absolute root of the filesystem
* and does not take the chroot into account )
*
* @param string path
* @return \OCP\Files\Mount\IMountPoint
*/
public function getMount(path)
{
return Filesystem::getMountManager().find(this.getAbsolutePath(path));
}
/**
* resolve a path to a storage and internal path
*
* @param string path
* @return array an array consisting of the storage and the internal path
*/
public function resolvePath(path)
{
a = this.getAbsolutePath(path);
p = Filesystem::normalizePath(a);
return Filesystem::resolvePath(p);
}
/**
* return the path to a local version of the file
* we need this because we can't know if a file is stored local or not from
* outside the filestorage and for some purposes a local file is needed
*
* @param string path
* @return string
*/
public function getLocalFile(path)
{
parent = substr(path, 0, strrpos(path, '/'));
path = this.getAbsolutePath(path);
list(storage, internalPath) = Filesystem::resolvePath(path);
if (Filesystem::isValidPath(parent) and storage) {
return storage.getLocalFile(internalPath);
} else
{
return null;
}
}
/**
* @param string path
* @return string
*/
public function getLocalFolder(path)
{
parent = substr(path, 0, strrpos(path, '/'));
path = this.getAbsolutePath(path);
list(storage, internalPath) = Filesystem::resolvePath(path);
if (Filesystem::isValidPath(parent) and storage) {
return storage.getLocalFolder(internalPath);
} else
{
return null;
}
}
/**
* the following functions operate with arguments and return values identical
* to those of their PHP built-in equivalents. Mostly they are merely wrappers
* for \OC\Files\Storage\Storage via basicOperation().
*/
public function mkdir(path)
{
return this.basicOperation('mkdir', path, array('create', 'write'));
}
/**
* remove mount point
*
* @param \OC\Files\Mount\MoveableMount mount
* @param string path relative to data/
* @return boolean
*/
protected function removeMount(mount, path)
{
if (mount instanceof MoveableMount) {
// cut of /user/files to get the relative path to data/user/files
pathParts = explode('/', path, 4);
relPath = '/'. pathParts[3];
this.lockFile(relPath, ILockingProvider::LOCK_SHARED, true);
\OC_Hook::emit(
Filesystem::CLASSNAME, "umount",
array(Filesystem::signal_param_path => relPath)
);
this.changeLock(relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
result = mount.removeMount();
this.changeLock(relPath, ILockingProvider::LOCK_SHARED, true);
if (result) {
\OC_Hook::emit(
Filesystem::CLASSNAME, "post_umount",
array(Filesystem::signal_param_path => relPath)
);
}
this.unlockFile(relPath, ILockingProvider::LOCK_SHARED, true);
return result;
} else
{
// do not allow deleting the storage's root / the mount point
// because for some storages it might delete the whole contents
// but isn't supposed to work that way
return false;
}
}
public function disableCacheUpdate()
{
this.updaterEnabled = false;
}
public function enableCacheUpdate()
{
this.updaterEnabled = true;
}
protected function writeUpdate(Storage storage, internalPath, time = null)
{
if (this.updaterEnabled) {
if (is_null(time))
{
time = time();
}
storage.getUpdater().update(internalPath, time);
}
}
protected function removeUpdate(Storage storage, internalPath)
{
if (this.updaterEnabled) {
storage.getUpdater().remove(internalPath);
}
}
protected function renameUpdate(Storage sourceStorage, Storage targetStorage, sourceInternalPath, targetInternalPath)
{
if (this.updaterEnabled) {
targetStorage.getUpdater().renameFromStorage(sourceStorage, sourceInternalPath, targetInternalPath);
}
}
/**
* @param string path
* @return bool|mixed
*/
public function rmdir(path)
{
absolutePath = this.getAbsolutePath(path);
mount = Filesystem::getMountManager().find(absolutePath);
if (mount.getInternalPath(absolutePath) === '') {
return this.removeMount(mount, absolutePath);
}
if (this.is_dir(path)) {
result = this.basicOperation('rmdir', path, array('delete'));
} else
{
result = false;
}
if (!result && !this.file_exists(path)) { //clear ghost files from the cache on delete
storage = mount.getStorage();
internalPath = mount.getInternalPath(absolutePath);
storage.getUpdater().remove(internalPath);
}
return result;
}
/**
* @param string path
* @return resource
*/
public function opendir(path) {
return this.basicOperation('opendir', path, array('read'));
}
/**
* @param string path
* @return bool|mixed
*/
public function is_dir(path) {
if (path == '/') {
return true;
}
return this.basicOperation('is_dir', path);
}
/**
* @param string path
* @return bool|mixed
*/
public function is_file(path) {
if (path == '/') {
return false;
}
return this.basicOperation('is_file', path);
}
/**
* @param string path
* @return mixed
*/
public function stat(path) {
return this.basicOperation('stat', path);
}
/**
* @param string path
* @return mixed
*/
public function filetype(path) {
return this.basicOperation('filetype', path);
}
/**
* @param string path
* @return mixed
*/
public function filesize(path) {
return this.basicOperation('filesize', path);
}
/**
* @param string path
* @return bool|mixed
* @throws \OCP\Files\InvalidPathException
*/
public function readfile(path) {
this.assertPathLength(path);
@ob_end_clean();
handle = this.fopen(path, 'rb');
if (handle) {
chunkSize = 8192; // 8 kB chunks
while (!feof(handle)) {
echo fread(handle, chunkSize);
flush();
}
fclose(handle);
return this.filesize(path);
}
return false;
}
/**
* @param string path
* @param int from
* @param int to
* @return bool|mixed
* @throws \OCP\Files\InvalidPathException
* @throws \OCP\Files\UnseekableException
*/
public function readfilePart(path, from, to) {
this.assertPathLength(path);
@ob_end_clean();
handle = this.fopen(path, 'rb');
if (handle) {
chunkSize = 8192; // 8 kB chunks
startReading = true;
if (from !== 0 && from !== '0' && fseek(handle, from) !== 0) {
// forward file handle via chunked fread because fseek seem to have failed
end = from + 1;
while (!feof(handle) && ftell(handle) < end) {
len = from - ftell(handle);
if (len > chunkSize) {
len = chunkSize;
}
result = fread(handle, len);
if (result === false) {
startReading = false;
break;
}
}
}
if (startReading) {
end = to + 1;
while (!feof(handle) && ftell(handle) < end) {
len = end - ftell(handle);
if (len > chunkSize) {
len = chunkSize;
}
echo fread(handle, len);
flush();
}
return ftell(handle) - from;
}
throw new \OCP\Files\UnseekableException('fseek error');
}
return false;
}
/**
* @param string path
* @return mixed
*/
public function isCreatable(path) {
return this.basicOperation('isCreatable', path);
}
/**
* @param string path
* @return mixed
*/
public function isReadable(path) {
return this.basicOperation('isReadable', path);
}
/**
* @param string path
* @return mixed
*/
public function isUpdatable(path) {
return this.basicOperation('isUpdatable', path);
}
/**
* @param string path
* @return bool|mixed
*/
public function isDeletable(path) {
absolutePath = this.getAbsolutePath(path);
mount = Filesystem::getMountManager().find(absolutePath);
if (mount.getInternalPath(absolutePath) === '') {
return mount instanceof MoveableMount;
}
return this.basicOperation('isDeletable', path);
}
/**
* @param string path
* @return mixed
*/
public function isSharable(path) {
return this.basicOperation('isSharable', path);
}
/**
* @param string path
* @return bool|mixed
*/
public function file_exists(path) {
if (path == '/') {
return true;
}
return this.basicOperation('file_exists', path);
}
/**
* @param string path
* @return mixed
*/
public function filemtime(path) {
return this.basicOperation('filemtime', path);
}
/**
* @param string path
* @param int|string mtime
* @return bool
*/
public function touch(path, mtime = null) {
if (!is_null(mtime) and !is_numeric(mtime)) {
mtime = strtotime(mtime);
}
hooks = array('touch');
if (!this.file_exists(path)) {
hooks[] = 'create';
hooks[] = 'write';
}
result = this.basicOperation('touch', path, hooks, mtime);
if (!result) {
// If create file fails because of permissions on external storage like SMB folders,
// check file exists and return false if not.
if (!this.file_exists(path)) {
return false;
}
if (is_null(mtime)) {
mtime = time();
}
//if native touch fails, we emulate it by changing the mtime in the cache
this.putFileInfo(path, array('mtime' => floor(mtime)));
}
return true;
}
/**
* @param string path
* @return mixed
*/
public function file_get_contents(path) {
return this.basicOperation('file_get_contents', path, array('read'));
}
/**
* @param bool exists
* @param string path
* @param bool run
*/
protected function emit_file_hooks_pre(exists, path, &run) {
if (!exists) {
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
Filesystem::signal_param_path => this.getHookPath(path),
Filesystem::signal_param_run => &run,
));
} else {
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
Filesystem::signal_param_path => this.getHookPath(path),
Filesystem::signal_param_run => &run,
));
}
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
Filesystem::signal_param_path => this.getHookPath(path),
Filesystem::signal_param_run => &run,
));
}
/**
* @param bool exists
* @param string path
*/
protected function emit_file_hooks_post(exists, path) {
if (!exists) {
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
Filesystem::signal_param_path => this.getHookPath(path),
));
} else {
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
Filesystem::signal_param_path => this.getHookPath(path),
));
}
\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
Filesystem::signal_param_path => this.getHookPath(path),
));
}
/**
* @param string path
* @param string|resource data
* @return bool|mixed
* @throws \Exception
*/
public function file_put_contents(path, data) {
if (is_resource(data)) { //not having to deal with streams in file_put_contents makes life easier
absolutePath = Filesystem::normalizePath(this.getAbsolutePath(path));
if (Filesystem::isValidPath(path)
and !Filesystem::isFileBlacklisted(path)
) {
path = this.getRelativePath(absolutePath);
this.lockFile(path, ILockingProvider::LOCK_SHARED);
exists = this.file_exists(path);
run = true;
if (this.shouldEmitHooks(path)) {
this.emit_file_hooks_pre(exists, path, run);
}
if (!run) {
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
return false;
}
this.changeLock(path, ILockingProvider::LOCK_EXCLUSIVE);
/** @var \OC\Files\Storage\Storage storage */
list(storage, internalPath) = this.resolvePath(path);
target = storage.fopen(internalPath, 'w');
if (target) {
list (, result) = \OC_Helper::streamCopy(data, target);
fclose(target);
fclose(data);
this.writeUpdate(storage, internalPath);
this.changeLock(path, ILockingProvider::LOCK_SHARED);
if (this.shouldEmitHooks(path) && result !== false) {
this.emit_file_hooks_post(exists, path);
}
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
return result;
} else {
this.unlockFile(path, ILockingProvider::LOCK_EXCLUSIVE);
return false;
}
} else {
return false;
}
} else {
hooks = this.file_exists(path) ? array('update', 'write') : array('create', 'write');
return this.basicOperation('file_put_contents', path, hooks, data);
}
}
/**
* @param string path
* @return bool|mixed
*/
public function unlink(path) {
if (path === '' || path === '/') {
// do not allow deleting the root
return false;
}
postFix = (substr(path, -1) === '/') ? '/' : '';
absolutePath = Filesystem::normalizePath(this.getAbsolutePath(path));
mount = Filesystem::getMountManager().find(absolutePath . postFix);
if (mount and mount.getInternalPath(absolutePath) === '') {
return this.removeMount(mount, absolutePath);
}
if (this.is_dir(path)) {
result = this.basicOperation('rmdir', path, ['delete']);
} else {
result = this.basicOperation('unlink', path, ['delete']);
}
if (!result && !this.file_exists(path)) { //clear ghost files from the cache on delete
storage = mount.getStorage();
internalPath = mount.getInternalPath(absolutePath);
storage.getUpdater().remove(internalPath);
return true;
} else {
return result;
}
}
/**
* @param string directory
* @return bool|mixed
*/
public function deleteAll(directory) {
return this.rmdir(directory);
}
/**
* Rename/move a file or folder from the source path to target path.
*
* @param string path1 source path
* @param string path2 target path
*
* @return bool|mixed
*/
public function rename(path1, path2) {
absolutePath1 = Filesystem::normalizePath(this.getAbsolutePath(path1));
absolutePath2 = Filesystem::normalizePath(this.getAbsolutePath(path2));
result = false;
if (
Filesystem::isValidPath(path2)
and Filesystem::isValidPath(path1)
and !Filesystem::isFileBlacklisted(path2)
) {
path1 = this.getRelativePath(absolutePath1);
path2 = this.getRelativePath(absolutePath2);
exists = this.file_exists(path2);
if (path1 == null or path2 == null) {
return false;
}
this.lockFile(path1, ILockingProvider::LOCK_SHARED, true);
try {
this.lockFile(path2, ILockingProvider::LOCK_SHARED, true);
run = true;
if (this.shouldEmitHooks(path1) && (Cache\Scanner::isPartialFile(path1) && !Cache\Scanner::isPartialFile(path2))) {
// if it was a rename from a part file to a regular file it was a write and not a rename operation
this.emit_file_hooks_pre(exists, path2, run);
} elseif (this.shouldEmitHooks(path1)) {
\OC_Hook::emit(
Filesystem::CLASSNAME, Filesystem::signal_rename,
array(
Filesystem::signal_param_oldpath => this.getHookPath(path1),
Filesystem::signal_param_newpath => this.getHookPath(path2),
Filesystem::signal_param_run => &run
)
);
}
if (run) {
this.verifyPath(dirname(path2), basename(path2));
manager = Filesystem::getMountManager();
mount1 = this.getMount(path1);
mount2 = this.getMount(path2);
storage1 = mount1.getStorage();
storage2 = mount2.getStorage();
internalPath1 = mount1.getInternalPath(absolutePath1);
internalPath2 = mount2.getInternalPath(absolutePath2);
this.changeLock(path1, ILockingProvider::LOCK_EXCLUSIVE, true);
try {
this.changeLock(path2, ILockingProvider::LOCK_EXCLUSIVE, true);
if (internalPath1 === '') {
if (mount1 instanceof MoveableMount) {
if (this.isTargetAllowed(absolutePath2)) {
/**
* @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount mount1
*/
sourceMountPoint = mount1.getMountPoint();
result = mount1.moveMount(absolutePath2);
manager.moveMount(sourceMountPoint, mount1.getMountPoint());
} else {
result = false;
}
} else {
result = false;
}
// moving a file/folder within the same mount point
} elseif (storage1 === storage2) {
if (storage1) {
result = storage1.rename(internalPath1, internalPath2);
} else {
result = false;
}
// moving a file/folder between storages (from storage1 to storage2)
} else {
result = storage2.moveFromStorage(storage1, internalPath1, internalPath2);
}
if ((Cache\Scanner::isPartialFile(path1) && !Cache\Scanner::isPartialFile(path2)) && result !== false) {
// if it was a rename from a part file to a regular file it was a write and not a rename operation
this.writeUpdate(storage2, internalPath2);
} else if (result) {
if (internalPath1 !== '') { // don't do a cache update for moved mounts
this.renameUpdate(storage1, storage2, internalPath1, internalPath2);
}
}
} catch(\Exception e) {
throw e;
} finally {
this.changeLock(path1, ILockingProvider::LOCK_SHARED, true);
this.changeLock(path2, ILockingProvider::LOCK_SHARED, true);
}
if ((Cache\Scanner::isPartialFile(path1) && !Cache\Scanner::isPartialFile(path2)) && result !== false) {
if (this.shouldEmitHooks()) {
this.emit_file_hooks_post(exists, path2);
}
} elseif (result) {
if (this.shouldEmitHooks(path1) and this.shouldEmitHooks(path2)) {
\OC_Hook::emit(
Filesystem::CLASSNAME,
Filesystem::signal_post_rename,
array(
Filesystem::signal_param_oldpath => this.getHookPath(path1),
Filesystem::signal_param_newpath => this.getHookPath(path2)
)
);
}
}
}
} catch(\Exception e) {
throw e;
} finally {
this.unlockFile(path1, ILockingProvider::LOCK_SHARED, true);
this.unlockFile(path2, ILockingProvider::LOCK_SHARED, true);
}
}
return result;
}
/**
* Copy a file/folder from the source path to target path
*
* @param string path1 source path
* @param string path2 target path
* @param bool preserveMtime whether to preserve mtime on the copy
*
* @return bool|mixed
*/
public function copy(path1, path2, preserveMtime = false) {
absolutePath1 = Filesystem::normalizePath(this.getAbsolutePath(path1));
absolutePath2 = Filesystem::normalizePath(this.getAbsolutePath(path2));
result = false;
if (
Filesystem::isValidPath(path2)
and Filesystem::isValidPath(path1)
and !Filesystem::isFileBlacklisted(path2)
) {
path1 = this.getRelativePath(absolutePath1);
path2 = this.getRelativePath(absolutePath2);
if (path1 == null or path2 == null) {
return false;
}
run = true;
this.lockFile(path2, ILockingProvider::LOCK_SHARED);
this.lockFile(path1, ILockingProvider::LOCK_SHARED);
lockTypePath1 = ILockingProvider::LOCK_SHARED;
lockTypePath2 = ILockingProvider::LOCK_SHARED;
try {
exists = this.file_exists(path2);
if (this.shouldEmitHooks()) {
\OC_Hook::emit(
Filesystem::CLASSNAME,
Filesystem::signal_copy,
array(
Filesystem::signal_param_oldpath => this.getHookPath(path1),
Filesystem::signal_param_newpath => this.getHookPath(path2),
Filesystem::signal_param_run => &run
)
);
this.emit_file_hooks_pre(exists, path2, run);
}
if (run) {
mount1 = this.getMount(path1);
mount2 = this.getMount(path2);
storage1 = mount1.getStorage();
internalPath1 = mount1.getInternalPath(absolutePath1);
storage2 = mount2.getStorage();
internalPath2 = mount2.getInternalPath(absolutePath2);
this.changeLock(path2, ILockingProvider::LOCK_EXCLUSIVE);
lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
if (mount1.getMountPoint() == mount2.getMountPoint()) {
if (storage1) {
result = storage1.copy(internalPath1, internalPath2);
} else {
result = false;
}
} else {
result = storage2.copyFromStorage(storage1, internalPath1, internalPath2);
}
this.writeUpdate(storage2, internalPath2);
this.changeLock(path2, ILockingProvider::LOCK_SHARED);
lockTypePath2 = ILockingProvider::LOCK_SHARED;
if (this.shouldEmitHooks() && result !== false) {
\OC_Hook::emit(
Filesystem::CLASSNAME,
Filesystem::signal_post_copy,
array(
Filesystem::signal_param_oldpath => this.getHookPath(path1),
Filesystem::signal_param_newpath => this.getHookPath(path2)
)
);
this.emit_file_hooks_post(exists, path2);
}
}
} catch (\Exception e) {
this.unlockFile(path2, lockTypePath2);
this.unlockFile(path1, lockTypePath1);
throw e;
}
this.unlockFile(path2, lockTypePath2);
this.unlockFile(path1, lockTypePath1);
}
return result;
}
/**
* @param string path
* @param string mode 'r' or 'w'
* @return resource
*/
public function fopen(path, mode) {
mode = str_replace('b', '', mode); // the binary flag is a windows only feature which we do not support
hooks = array();
switch (mode) {
case 'r':
hooks[] = 'read';
break;
case 'r+':
case 'w+':
case 'x+':
case 'a+':
hooks[] = 'read';
hooks[] = 'write';
break;
case 'w':
case 'x':
case 'a':
hooks[] = 'write';
break;
default:
\OCP\Util::writeLog('core', 'invalid mode (' . mode . ') for ' . path, ILogger::ERROR);
}
if (mode !== 'r' && mode !== 'w') {
\OC::server.getLogger().info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
}
return this.basicOperation('fopen', path, hooks, mode);
}
/**
* @param string path
* @return bool|string
* @throws \OCP\Files\InvalidPathException
*/
public function toTmpFile(path) {
this.assertPathLength(path);
if (Filesystem::isValidPath(path)) {
source = this.fopen(path, 'r');
if (source) {
extension = pathinfo(path, PATHINFO_EXTENSION);
tmpFile = \OC::server.getTempManager().getTemporaryFile(extension);
file_put_contents(tmpFile, source);
return tmpFile;
} else {
return false;
}
} else {
return false;
}
}
/**
* @param string tmpFile
* @param string path
* @return bool|mixed
* @throws \OCP\Files\InvalidPathException
*/
public function fromTmpFile(tmpFile, path) {
this.assertPathLength(path);
if (Filesystem::isValidPath(path)) {
// Get directory that the file is going into
filePath = dirname(path);
// Create the directories if any
if (!this.file_exists(filePath)) {
result = this.createParentDirectories(filePath);
if (result === false) {
return false;
}
}
source = fopen(tmpFile, 'r');
if (source) {
result = this.file_put_contents(path, source);
// this.file_put_contents() might have already closed
// the resource, so we check it, before trying to close it
// to avoid messages in the error log.
if (is_resource(source)) {
fclose(source);
}
unlink(tmpFile);
return result;
} else {
return false;
}
} else {
return false;
}
}
/**
* @param string path
* @return mixed
* @throws \OCP\Files\InvalidPathException
*/
public function getMimeType(path) {
this.assertPathLength(path);
return this.basicOperation('getMimeType', path);
}
/**
* @param string type
* @param string path
* @param bool raw
* @return bool|null|string
*/
public function hash(type, path, raw = false) {
postFix = (substr(path, -1) === '/') ? '/' : '';
absolutePath = Filesystem::normalizePath(this.getAbsolutePath(path));
if (Filesystem::isValidPath(path)) {
path = this.getRelativePath(absolutePath);
if (path == null) {
return false;
}
if (this.shouldEmitHooks(path)) {
\OC_Hook::emit(
Filesystem::CLASSNAME,
Filesystem::signal_read,
array(Filesystem::signal_param_path => this.getHookPath(path))
);
}
list(storage, internalPath) = Filesystem::resolvePath(absolutePath . postFix);
if (storage) {
return storage.hash(type, internalPath, raw);
}
}
return null;
}
/**
* @param string path
* @return mixed
* @throws \OCP\Files\InvalidPathException
*/
public function free_space(path = '/') {
this.assertPathLength(path);
result = this.basicOperation('free_space', path);
if (result === null) {
throw new InvalidPathException();
}
return result;
}
/**
* abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
*
* @param string operation
* @param string path
* @param array hooks (optional)
* @param mixed extraParam (optional)
* @return mixed
* @throws \Exception
*
* This method takes requests for basic filesystem functions (e.g. reading & writing
* files), processes hooks and proxies, sanitises paths, and finally passes them on to
* \OC\Files\Storage\Storage for delegation to a storage backend for execution
*/
private function basicOperation(operation, path, hooks = [], extraParam = null) {
postFix = (substr(path, -1) === '/') ? '/' : '';
absolutePath = Filesystem::normalizePath(this.getAbsolutePath(path));
if (Filesystem::isValidPath(path)
and !Filesystem::isFileBlacklisted(path)
) {
path = this.getRelativePath(absolutePath);
if (path == null) {
return false;
}
if (in_array('write', hooks) || in_array('delete', hooks) || in_array('read', hooks)) {
// always a shared lock during pre-hooks so the hook can read the file
this.lockFile(path, ILockingProvider::LOCK_SHARED);
}
run = this.runHooks(hooks, path);
/** @var \OC\Files\Storage\Storage storage */
list(storage, internalPath) = Filesystem::resolvePath(absolutePath . postFix);
if (run and storage) {
if (in_array('write', hooks) || in_array('delete', hooks)) {
try {
this.changeLock(path, ILockingProvider::LOCK_EXCLUSIVE);
} catch (LockedException e) {
// release the shared lock we acquired before quiting
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
throw e;
}
}
try {
if (!is_null(extraParam)) {
result = storage.operation(internalPath, extraParam);
} else {
result = storage.operation(internalPath);
}
} catch (\Exception e) {
if (in_array('write', hooks) || in_array('delete', hooks)) {
this.unlockFile(path, ILockingProvider::LOCK_EXCLUSIVE);
} else if (in_array('read', hooks)) {
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
}
throw e;
}
if (result && in_array('delete', hooks) and result) {
this.removeUpdate(storage, internalPath);
}
if (result && in_array('write', hooks, true) && operation !== 'fopen' && operation !== 'touch') {
this.writeUpdate(storage, internalPath);
}
if (result && in_array('touch', hooks)) {
this.writeUpdate(storage, internalPath, extraParam);
}
if ((in_array('write', hooks) || in_array('delete', hooks)) && (operation !== 'fopen' || result === false)) {
this.changeLock(path, ILockingProvider::LOCK_SHARED);
}
unlockLater = false;
if (this.lockingEnabled && operation === 'fopen' && is_resource(result)) {
unlockLater = true;
// make sure our unlocking callback will still be called if connection is aborted
ignore_user_abort(true);
result = CallbackWrapper::wrap(result, null, null, function () use (hooks, path) {
if (in_array('write', hooks)) {
this.unlockFile(path, ILockingProvider::LOCK_EXCLUSIVE);
} else if (in_array('read', hooks)) {
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
}
});
}
if (this.shouldEmitHooks(path) && result !== false) {
if (operation != 'fopen') { //no post hooks for fopen, the file stream is still open
this.runHooks(hooks, path, true);
}
}
if (!unlockLater
&& (in_array('write', hooks) || in_array('delete', hooks) || in_array('read', hooks))
) {
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
}
return result;
} else {
this.unlockFile(path, ILockingProvider::LOCK_SHARED);
}
}
return null;
}
/**
* get the path relative to the default root for hook usage
*
* @param string path
* @return string
*/
private function getHookPath(path) {
if (!Filesystem::getView()) {
return path;
}
return Filesystem::getView().getRelativePath(this.getAbsolutePath(path));
}
private function shouldEmitHooks(path = '') {
if (path && Cache\Scanner::isPartialFile(path)) {
return false;
}
if (!Filesystem::loaded) {
return false;
}
defaultRoot = Filesystem::getRoot();
if (defaultRoot === null) {
return false;
}
if (this.fakeRoot === defaultRoot) {
return true;
}
fullPath = this.getAbsolutePath(path);
if (fullPath === defaultRoot) {
return true;
}
return (strlen(fullPath) > strlen(defaultRoot)) && (substr(fullPath, 0, strlen(defaultRoot) + 1) === defaultRoot . '/');
}
/**
* @param string[] hooks
* @param string path
* @param bool post
* @return bool
*/
private function runHooks(hooks, path, post = false) {
relativePath = path;
path = this.getHookPath(path);
prefix = post ? 'post_' : '';
run = true;
if (this.shouldEmitHooks(relativePath)) {
foreach (hooks as hook) {
if (hook != 'read') {
\OC_Hook::emit(
Filesystem::CLASSNAME,
prefix . hook,
array(
Filesystem::signal_param_run => &run,
Filesystem::signal_param_path => path
)
);
} elseif (!post) {
\OC_Hook::emit(
Filesystem::CLASSNAME,
prefix . hook,
array(
Filesystem::signal_param_path => path
)
);
}
}
}
return run;
}
/**
* check if a file or folder has been updated since time
*
* @param string path
* @param int time
* @return bool
*/
public function hasUpdated(path, time) {
return this.basicOperation('hasUpdated', path, array(), time);
}
/**
* @param string ownerId
* @return \OC\User\User
*/
private function getUserObjectForOwner(ownerId) {
owner = this.userManager.get(ownerId);
if (owner instanceof IUser) {
return owner;
} else {
return new User(ownerId, null, \OC::server.getEventDispatcher());
}
}
/**
* Get file info from cache
*
* If the file is not in cached it will be scanned
* If the file has changed on storage the cache will be updated
*
* @param \OC\Files\Storage\Storage storage
* @param string internalPath
* @param string relativePath
* @return ICacheEntry|bool
*/
private function getCacheEntry(storage, internalPath, relativePath) {
cache = storage.getCache(internalPath);
data = cache.get(internalPath);
watcher = storage.getWatcher(internalPath);
try {
// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
if (!data || data['size'] === -1) {
if (!storage.file_exists(internalPath)) {
return false;
}
// don't need to get a lock here since the scanner does it's own locking
scanner = storage.getScanner(internalPath);
scanner.scan(internalPath, Cache\Scanner::SCAN_SHALLOW);
data = cache.get(internalPath);
} else if (!Cache\Scanner::isPartialFile(internalPath) && watcher.needsUpdate(internalPath, data)) {
this.lockFile(relativePath, ILockingProvider::LOCK_SHARED);
watcher.update(internalPath, data);
storage.getPropagator().propagateChange(internalPath, time());
data = cache.get(internalPath);
this.unlockFile(relativePath, ILockingProvider::LOCK_SHARED);
}
} catch (LockedException e) {
// if the file is locked we just use the old cache info
}
return data;
}
/**
* get the filesystem info
*
* @param string path
* @param boolean|string includeMountPoints true to add mountpoint sizes,
* 'ext' to add only ext storage mount point sizes. Defaults to true.
* defaults to true
* @return \OC\Files\FileInfo|false False if file does not exist
*/
public function getFileInfo(path, includeMountPoints = true) {
this.assertPathLength(path);
if (!Filesystem::isValidPath(path)) {
return false;
}
if (Cache\Scanner::isPartialFile(path)) {
return this.getPartFileInfo(path);
}
relativePath = path;
path = Filesystem::normalizePath(this.fakeRoot . '/' . path);
mount = Filesystem::getMountManager().find(path);
if (!mount) {
\OC::server.getLogger().warning('Mountpoint not found for path: ' . path);
return false;
}
storage = mount.getStorage();
internalPath = mount.getInternalPath(path);
if (storage) {
data = this.getCacheEntry(storage, internalPath, relativePath);
if (!data instanceof ICacheEntry) {
\OC::server.getLogger().debug('No cache entry found for ' . path . ' (storage: ' . storage.getId() . ', internalPath: ' . internalPath . ')');
return false;
}
if (mount instanceof MoveableMount && internalPath === '') {
data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
}
ownerId = storage.getOwner(internalPath);
owner = null;
if (ownerId !== null) {
// ownerId might be null if files are accessed with an access token without file system access
owner = this.getUserObjectForOwner(ownerId);
}
info = new FileInfo(path, storage, internalPath, data, mount, owner);
if (data and isset(data['fileid'])) {
if (includeMountPoints and data['mimetype'] === 'httpd/unix-directory') {
//add the sizes of other mount points to the folder
extOnly = (includeMountPoints === 'ext');
mounts = Filesystem::getMountManager().findIn(path);
info.setSubMounts(array_filter(mounts, function (IMountPoint mount) use (extOnly) {
subStorage = mount.getStorage();
return !(extOnly && subStorage instanceof \OCA\Files_Sharing\SharedStorage);
}));
}
}
return info;
} else {
\OC::server.getLogger().warning('Storage not valid for mountpoint: ' . mount.getMountPoint());
}
return false;
}
/**
* get the content of a directory
*
* @param string directory path under datadirectory
* @param string mimetype_filter limit returned content to this mimetype or mimepart
* @return FileInfo[]
*/
public IList<FileInfo> getDirectoryContent(string directory, string mimetype_filter = "") {
this.assertPathLength(directory);
if (!Filesystem::isValidPath(directory)) {
return [];
}
path = this.getAbsolutePath(directory);
path = Filesystem::normalizePath(path);
mount = this.getMount(directory);
if (!mount) {
return [];
}
storage = mount.getStorage();
internalPath = mount.getInternalPath(path);
if (storage) {
cache = storage.getCache(internalPath);
user = \OC_User::getUser();
data = this.getCacheEntry(storage, internalPath, directory);
if (!data instanceof ICacheEntry || !isset(data['fileid']) || !(data.getPermissions() && Constants::PERMISSION_READ)) {
return [];
}
folderId = data['fileid'];
contents = cache.getFolderContentsById(folderId); //TODO: mimetype_filter
sharingDisabled = \OCP\Util::isSharingDisabledForUser();
fileNames = array_map(function(ICacheEntry content) {
return content.getName();
}, contents);
/**
* @var \OC\Files\FileInfo[] fileInfos
*/
fileInfos = array_map(function (ICacheEntry content) use (path, storage, mount, sharingDisabled) {
if (sharingDisabled) {
content['permissions'] = content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
}
owner = this.getUserObjectForOwner(storage.getOwner(content['path']));
return new FileInfo(path . '/' . content['name'], storage, content['path'], content, mount, owner);
}, contents);
files = array_combine(fileNames, fileInfos);
//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
mounts = Filesystem::getMountManager().findIn(path);
dirLength = strlen(path);
foreach (mounts as mount) {
mountPoint = mount.getMountPoint();
subStorage = mount.getStorage();
if (subStorage) {
subCache = subStorage.getCache('');
rootEntry = subCache.get('');
if (!rootEntry) {
subScanner = subStorage.getScanner('');
try {
subScanner.scanFile('');
} catch (\OCP\Files\StorageNotAvailableException e) {
continue;
} catch (\OCP\Files\StorageInvalidException e) {
continue;
} catch (\Exception e) {
// sometimes when the storage is not available it can be any exception
\OC::server.getLogger().logException(e, [
'message' => 'Exception while scanning storage "' . subStorage.getId() . '"',
'level' => ILogger::ERROR,
'app' => 'lib',
]);
continue;
}
rootEntry = subCache.get('');
}
if (rootEntry && (rootEntry.getPermissions() && Constants::PERMISSION_READ)) {
relativePath = trim(substr(mountPoint, dirLength), '/');
if (pos = strpos(relativePath, '/')) {
//mountpoint inside subfolder add size to the correct folder
entryName = substr(relativePath, 0, pos);
foreach (files as &entry) {
if (entry.getName() === entryName) {
entry.addSubEntry(rootEntry, mountPoint);
}
}
} else { //mountpoint in this folder, add an entry for it
rootEntry['name'] = relativePath;
rootEntry['type'] = rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
permissions = rootEntry['permissions'];
// do not allow renaming/deleting the mount point if they are not shared files/folders
// for shared files/folders we use the permissions given by the owner
if (mount instanceof MoveableMount) {
rootEntry['permissions'] = permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
} else {
rootEntry['permissions'] = permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
}
rootEntry['path'] = substr(Filesystem::normalizePath(path . '/' . rootEntry['name']), strlen(user) + 2); // full path without /user/
// if sharing was disabled for the user we remove the share permissions
if (\OCP\Util::isSharingDisabledForUser()) {
rootEntry['permissions'] = rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
}
owner = this.getUserObjectForOwner(subStorage.getOwner(''));
files[rootEntry.getName()] = new FileInfo(path . '/' . rootEntry['name'], subStorage, '', rootEntry, mount, owner);
}
}
}
}
if (mimetype_filter) {
files = array_filter(files, function (FileInfo file) use (mimetype_filter) {
if (strpos(mimetype_filter, '/')) {
return file.getMimetype() === mimetype_filter;
} else {
return file.getMimePart() === mimetype_filter;
}
});
}
return array_values(files);
} else {
return [];
}
}
/**
* change file metadata
*
* @param string path
* @param array|\OCP\Files\FileInfo data
* @return int
*
* returns the fileid of the updated file
*/
public function putFileInfo(path, data) {
this.assertPathLength(path);
if (data instanceof FileInfo) {
data = data.getData();
}
path = Filesystem::normalizePath(this.fakeRoot . '/' . path);
/**
* @var \OC\Files\Storage\Storage storage
* @var string internalPath
*/
list(storage, internalPath) = Filesystem::resolvePath(path);
if (storage) {
cache = storage.getCache(path);
if (!cache.inCache(internalPath)) {
scanner = storage.getScanner(internalPath);
scanner.scan(internalPath, Cache\Scanner::SCAN_SHALLOW);
}
return cache.put(internalPath, data);
} else {
return -1;
}
}
/**
* search for files with the name matching query
*
* @param string query
* @return FileInfo[]
*/
public function search(query) {
return this.searchCommon('search', array('%' . query . '%'));
}
/**
* search for files with the name matching query
*
* @param string query
* @return FileInfo[]
*/
public function searchRaw(query) {
return this.searchCommon('search', array(query));
}
/**
* search for files by mimetype
*
* @param string mimetype
* @return FileInfo[]
*/
public function searchByMime(mimetype) {
return this.searchCommon('searchByMime', array(mimetype));
}
/**
* search for files by tag
*
* @param string|int tag name or tag id
* @param string userId owner of the tags
* @return FileInfo[]
*/
public function searchByTag(tag, userId) {
return this.searchCommon('searchByTag', array(tag, userId));
}
/**
* @param string method cache method
* @param array args
* @return FileInfo[]
*/
private function searchCommon(method, args) {
files = array();
rootLength = strlen(this.fakeRoot);
mount = this.getMount('');
mountPoint = mount.getMountPoint();
storage = mount.getStorage();
if (storage) {
cache = storage.getCache('');
results = call_user_func_array(array(cache, method), args);
foreach (results as result) {
if (substr(mountPoint . result['path'], 0, rootLength + 1) === this.fakeRoot . '/') {
internalPath = result['path'];
path = mountPoint . result['path'];
result['path'] = substr(mountPoint . result['path'], rootLength);
owner = \OC::server.getUserManager().get(storage.getOwner(internalPath));
files[] = new FileInfo(path, storage, internalPath, result, mount, owner);
}
}
mounts = Filesystem::getMountManager().findIn(this.fakeRoot);
foreach (mounts as mount) {
mountPoint = mount.getMountPoint();
storage = mount.getStorage();
if (storage) {
cache = storage.getCache('');
relativeMountPoint = substr(mountPoint, rootLength);
results = call_user_func_array(array(cache, method), args);
if (results) {
foreach (results as result) {
internalPath = result['path'];
result['path'] = rtrim(relativeMountPoint . result['path'], '/');
path = rtrim(mountPoint . internalPath, '/');
owner = \OC::server.getUserManager().get(storage.getOwner(internalPath));
files[] = new FileInfo(path, storage, internalPath, result, mount, owner);
}
}
}
}
}
return files;
}
/**
* Get the owner for a file or folder
*
* @param string path
* @return string the user id of the owner
* @throws NotFoundException
*/
public function getOwner(path) {
info = this.getFileInfo(path);
if (!info) {
throw new NotFoundException(path . ' not found while trying to get owner');
}
return info.getOwner().getUID();
}
/**
* get the ETag for a file or folder
*
* @param string path
* @return string
*/
public function getETag(path) {
/**
* @var Storage\Storage storage
* @var string internalPath
*/
list(storage, internalPath) = this.resolvePath(path);
if (storage) {
return storage.getETag(internalPath);
} else {
return null;
}
}
/**
* Get the path of a file by id, relative to the view
*
* Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
*
* @param int id
* @throws NotFoundException
* @return string
*/
public function getPath(id) {
id = (int)id;
manager = Filesystem::getMountManager();
mounts = manager.findIn(this.fakeRoot);
mounts[] = manager.find(this.fakeRoot);
// reverse the array so we start with the storage this view is in
// which is the most likely to contain the file we're looking for
mounts = array_reverse(mounts);
foreach (mounts as mount) {
/**
* @var \OC\Files\Mount\MountPoint mount
*/
if (mount.getStorage()) {
cache = mount.getStorage().getCache();
internalPath = cache.getPathById(id);
if (is_string(internalPath)) {
fullPath = mount.getMountPoint() . internalPath;
if (!is_null(path = this.getRelativePath(fullPath))) {
return path;
}
}
}
}
throw new NotFoundException(sprintf('File with id "%s" has not been found.', id));
}
/**
* @param string path
* @throws InvalidPathException
*/
private void assertPathLength(string path)
{
var maxLen = 260; // min(MAX_PATH, 4000);
// Check for the string length - performed using isset() instead of strlen()
// because isset() is about 5x-40x faster.
if (path.Length > maxLen ) {
var pathLen = path.Length;
throw new Exception($"Path length({pathLen}) exceeds max path length({maxLen}): path");
}
}
/**
* check if it is allowed to move a mount point to a given target.
* It is not allowed to move a mount point into a different mount point or
* into an already shared folder
*
* @param string target path
* @return boolean
*/
private function isTargetAllowed(target) {
list(targetStorage, targetInternalPath) = \OC\Files\Filesystem::resolvePath(target);
if (!targetStorage.instanceOfStorage('\OCP\Files\IHomeStorage')) {
\OCP\Util::writeLog('files',
'It is not allowed to move one mount point into another one',
ILogger::DEBUG);
return false;
}
// note: cannot use the view because the target is already locked
fileId = (int)targetStorage.getCache().getId(targetInternalPath);
if (fileId === -1) {
// target might not exist, need to check parent instead
fileId = (int)targetStorage.getCache().getId(dirname(targetInternalPath));
}
// check if any of the parents were shared by the current owner (include collections)
shares = \OCP\Share::getItemShared(
'folder',
fileId,
\OCP\Share::FORMAT_NONE,
null,
true
);
if (count(shares) > 0) {
\OCP\Util::writeLog('files',
'It is not allowed to move one mount point into a shared folder',
ILogger::DEBUG);
return false;
}
return true;
}
/**
* Get a fileinfo object for files that are ignored in the cache (part files)
*
* @param string path
* @return \OCP\Files\FileInfo
*/
private function getPartFileInfo(path) {
mount = this.getMount(path);
storage = mount.getStorage();
internalPath = mount.getInternalPath(this.getAbsolutePath(path));
owner = \OC::server.getUserManager().get(storage.getOwner(internalPath));
return new FileInfo(
this.getAbsolutePath(path),
storage,
internalPath,
[
'fileid' => null,
'mimetype' => storage.getMimeType(internalPath),
'name' => basename(path),
'etag' => null,
'size' => storage.filesize(internalPath),
'mtime' => storage.filemtime(internalPath),
'encrypted' => false,
'permissions' => \OCP\Constants::PERMISSION_ALL
],
mount,
owner
);
}
/**
* @param string path
* @param string fileName
* @throws InvalidPathException
*/
public function verifyPath(path, fileName) {
try {
/** @type \OCP\Files\Storage storage */
list(storage, internalPath) = this.resolvePath(path);
storage.verifyPath(internalPath, fileName);
} catch (ReservedWordException ex) {
l = \OC::server.getL10N('lib');
throw new InvalidPathException(l.t('File name is a reserved word'));
} catch (InvalidCharacterInPathException ex) {
l = \OC::server.getL10N('lib');
throw new InvalidPathException(l.t('File name contains at least one invalid character'));
} catch (FileNameTooLongException ex) {
l = \OC::server.getL10N('lib');
throw new InvalidPathException(l.t('File name is too long'));
} catch (InvalidDirectoryException ex) {
l = \OC::server.getL10N('lib');
throw new InvalidPathException(l.t('Dot files are not allowed'));
} catch (EmptyFileNameException ex) {
l = \OC::server.getL10N('lib');
throw new InvalidPathException(l.t('Empty filename is not allowed'));
}
}
/**
* get all parent folders of path
*
* @param string path
* @return string[]
*/
private function getParents(path) {
path = trim(path, '/');
if (!path) {
return [];
}
parts = explode('/', path);
// remove the single file
array_pop(parts);
result = array('/');
resultPath = '';
foreach (parts as part) {
if (part) {
resultPath .= '/' . part;
result[] = resultPath;
}
}
return result;
}
/**
* Returns the mount point for which to lock
*
* @param string absolutePath absolute path
* @param bool useParentMount true to return parent mount instead of whatever
* is mounted directly on the given path, false otherwise
* @return \OC\Files\Mount\MountPoint mount point for which to apply locks
*/
private function getMountForLock(absolutePath, useParentMount = false) {
results = [];
mount = Filesystem::getMountManager().find(absolutePath);
if (!mount) {
return results;
}
if (useParentMount) {
// find out if something is mounted directly on the path
internalPath = mount.getInternalPath(absolutePath);
if (internalPath === '') {
// resolve the parent mount instead
mount = Filesystem::getMountManager().find(dirname(absolutePath));
}
}
return mount;
}
/**
* Lock the given path
*
* @param string path the path of the file to lock, relative to the view
* @param int type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
* @param bool lockMountPoint true to lock the mount point, false to lock the attached mount/storage
*
* @return bool False if the path is excluded from locking, true otherwise
* @throws \OCP\Lock\LockedException if the path is already locked
*/
private function lockPath(path, type, lockMountPoint = false) {
absolutePath = this.getAbsolutePath(path);
absolutePath = Filesystem::normalizePath(absolutePath);
if (!this.shouldLockFile(absolutePath)) {
return false;
}
mount = this.getMountForLock(absolutePath, lockMountPoint);
if (mount) {
try {
storage = mount.getStorage();
if (storage.instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
storage.acquireLock(
mount.getInternalPath(absolutePath),
type,
this.lockingProvider
);
}
} catch (\OCP\Lock\LockedException e) {
// rethrow with the a human-readable path
throw new \OCP\Lock\LockedException(
this.getPathRelativeToFiles(absolutePath),
e
);
}
}
return true;
}
/**
* Change the lock type
*
* @param string path the path of the file to lock, relative to the view
* @param int type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
* @param bool lockMountPoint true to lock the mount point, false to lock the attached mount/storage
*
* @return bool False if the path is excluded from locking, true otherwise
* @throws \OCP\Lock\LockedException if the path is already locked
*/
public function changeLock(path, type, lockMountPoint = false) {
path = Filesystem::normalizePath(path);
absolutePath = this.getAbsolutePath(path);
absolutePath = Filesystem::normalizePath(absolutePath);
if (!this.shouldLockFile(absolutePath)) {
return false;
}
mount = this.getMountForLock(absolutePath, lockMountPoint);
if (mount) {
try {
storage = mount.getStorage();
if (storage.instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
storage.changeLock(
mount.getInternalPath(absolutePath),
type,
this.lockingProvider
);
}
} catch (\OCP\Lock\LockedException e) {
try {
// rethrow with the a human-readable path
throw new \OCP\Lock\LockedException(
this.getPathRelativeToFiles(absolutePath),
e
);
} catch (\InvalidArgumentException e) {
throw new \OCP\Lock\LockedException(
absolutePath,
e
);
}
}
}
return true;
}
/**
* Unlock the given path
*
* @param string path the path of the file to unlock, relative to the view
* @param int type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
* @param bool lockMountPoint true to lock the mount point, false to lock the attached mount/storage
*
* @return bool False if the path is excluded from locking, true otherwise
*/
private function unlockPath(path, type, lockMountPoint = false) {
absolutePath = this.getAbsolutePath(path);
absolutePath = Filesystem::normalizePath(absolutePath);
if (!this.shouldLockFile(absolutePath)) {
return false;
}
mount = this.getMountForLock(absolutePath, lockMountPoint);
if (mount) {
storage = mount.getStorage();
if (storage && storage.instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
storage.releaseLock(
mount.getInternalPath(absolutePath),
type,
this.lockingProvider
);
}
}
return true;
}
/**
* Lock a path and all its parents up to the root of the view
*
* @param string path the path of the file to lock relative to the view
* @param int type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
* @param bool lockMountPoint true to lock the mount point, false to lock the attached mount/storage
*
* @return bool False if the path is excluded from locking, true otherwise
*/
public function lockFile(path, type, lockMountPoint = false) {
absolutePath = this.getAbsolutePath(path);
absolutePath = Filesystem::normalizePath(absolutePath);
if (!this.shouldLockFile(absolutePath)) {
return false;
}
this.lockPath(path, type, lockMountPoint);
parents = this.getParents(path);
foreach (parents as parent) {
this.lockPath(parent, ILockingProvider::LOCK_SHARED);
}
return true;
}
/**
* Unlock a path and all its parents up to the root of the view
*
* @param string path the path of the file to lock relative to the view
* @param int type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
* @param bool lockMountPoint true to lock the mount point, false to lock the attached mount/storage
*
* @return bool False if the path is excluded from locking, true otherwise
*/
public function unlockFile(path, type, lockMountPoint = false) {
absolutePath = this.getAbsolutePath(path);
absolutePath = Filesystem::normalizePath(absolutePath);
if (!this.shouldLockFile(absolutePath)) {
return false;
}
this.unlockPath(path, type, lockMountPoint);
parents = this.getParents(path);
foreach (parents as parent) {
this.unlockPath(parent, ILockingProvider::LOCK_SHARED);
}
return true;
}
/**
* Only lock files in data/user/files/
*
* @param string path Absolute path to the file/folder we try to (un)lock
* @return bool
*/
protected function shouldLockFile(path) {
path = Filesystem::normalizePath(path);
pathSegments = explode('/', path);
if (isset(pathSegments[2])) {
// E.g.: /username/files/path-to-file
return (pathSegments[2] === 'files') && (count(pathSegments) > 3);
}
return strpos(path, '/appdata_') !== 0;
}
/**
* Shortens the given absolute path to be relative to
* "user/files".
*
* @param string absolutePath absolute path which is under "files"
*
* @return string path relative to "files" with trimmed slashes or null
* if the path was NOT relative to files
*
* @throws \InvalidArgumentException if the given path was not under "files"
* @since 8.1.0
*/
public function getPathRelativeToFiles(absolutePath) {
path = Filesystem::normalizePath(absolutePath);
parts = explode('/', trim(path, '/'), 3);
// "user", "files", "path/to/dir"
if (!isset(parts[1]) || parts[1] !== 'files') {
this.logger.error(
'absolutePath must be relative to "files", value is "%s"',
[
absolutePath
]
);
throw new \InvalidArgumentException('absolutePath must be relative to "files"');
}
if (isset(parts[2])) {
return parts[2];
}
return '';
}
/**
* @param string filename
* @return array
* @throws \OC\User\NoUserException
* @throws NotFoundException
*/
public function getUidAndFilename(filename) {
info = this.getFileInfo(filename);
if (!info instanceof \OCP\Files\FileInfo) {
throw new NotFoundException(this.getAbsolutePath(filename) . ' not found');
}
uid = info.getOwner().getUID();
if (uid != \OCP\User::getUser()) {
Filesystem::initMountPoints(uid);
ownerView = new View('/' . uid . '/files');
try {
filename = ownerView.getPath(info['fileid']);
} catch (NotFoundException e) {
throw new NotFoundException('File with id ' . info['fileid'] . ' not found for user ' . uid);
}
}
return [uid, filename];
}
/**
* Creates parent non-existing folders
*
* @param string filePath
* @return bool
*/
private function createParentDirectories(filePath) {
directoryParts = explode('/', filePath);
directoryParts = array_filter(directoryParts);
foreach (directoryParts as key => part) {
currentPathElements = array_slice(directoryParts, 0, key);
currentPath = '/' . implode('/', currentPathElements);
if (this.is_file(currentPath)) {
return false;
}
if (!this.file_exists(currentPath)) {
this.mkdir(currentPath);
}
}
return true;
}
}
}
|
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using Microsoft.EntityFrameworkCore.Migrations;
namespace CarWash.ClassLibrary.Migrations
{
public partial class Schema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "DateTo",
table: "Reservation",
newName: "EndDate");
migrationBuilder.RenameColumn(
name: "DateFrom",
table: "Reservation",
newName: "StartDate");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "StartDate",
table: "Reservation",
newName: "DateFrom");
migrationBuilder.RenameColumn(
name: "EndDate",
table: "Reservation",
newName: "DateTo");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstaclePool : MonoBehaviour {
public int obstaclePoolSize = 7;
public GameObject obstaclePrefab;
public float spawnRate = 5f;
public float obstacleMin = 5f;
public float obstacleMax = 20f;
private GameObject[] obstacles;
private Vector2 objectPoolPosition = new Vector2(-15f, -25f);
private float timeSinceLastSpawned;
//private float spawnYPosition = -5f;
private float spawnYPosition = -2f;
private int currentObstacle = 0;
private float elapsedSeconds = 0;
private const int hayBaleScrollingSpeed = 50;
// Use this for initialization
void Start ()
{
obstacles = new GameObject[obstaclePoolSize];
for(int i = 0; i < obstaclePoolSize; i++)
{
obstacles[i] = (GameObject)Instantiate(obstaclePrefab, objectPoolPosition, Quaternion.identity);
}
}
// Update is called once per frame
void Update ()
{
//Ben Added - for hay bale rotating
for(int i = 0; i < obstaclePoolSize; i++)
{
obstacles [i].transform.Rotate (0f,0f, hayBaleScrollingSpeed * Time.deltaTime);
}
//Ben added - end
timeSinceLastSpawned += Time.deltaTime;
if(GameControl.instance.gameOver == false && timeSinceLastSpawned >= spawnRate) //puts spawned obstacles in random positions in front of the player
{
timeSinceLastSpawned = 0;
float spawnXPosition = Random.Range(obstacleMin, obstacleMax);
obstacles[currentObstacle].transform.position = new Vector2(spawnXPosition, spawnYPosition);
currentObstacle++;
if(currentObstacle >= obstaclePoolSize)
{
currentObstacle = 0;
}
}
elapsedSeconds += Time.deltaTime;
if (elapsedSeconds > 10.5) //makes the obstacles appear faster as time goes on
{
if(spawnRate <= 1.75)
{
return;
}
elapsedSeconds = 0;
spawnRate -= 0.35f;
}
}
}
|
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
namespace Orbital.Mapping
{
public class Tileset : ScriptableObject
{
public Material Floor;
public Material FloorCorner;
public Material Wall;
public Material Doorway;
public GameObject InsideCorner;
public GameObject OutsideCorner;
public GameObject SmallDoor;
public GameObject LargeDoor;
public float DoorPriority;
#if UNITY_EDITOR
[MenuItem("Assets/Create/Orbital/Mapping/Tileset")]
public static void CreateAsset()
{
ScriptableObjectUtility.CreateAsset<Tileset>();
}
#endif
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
Transform cameraTrans;
[SerializeField] Transform playerTrans;
[SerializeField] Vector3 cameraVec;
[SerializeField] Vector3 cameraRot;
void Start ()
{
cameraTrans = transform;
cameraTrans.rotation = Quaternion.Euler (cameraRot);
}
void LateUpdate ()
{
cameraTrans.position = Vector3.Lerp(cameraTrans.position, playerTrans.position + cameraVec, 10.0f * Time.deltaTime);
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YoctoScheduler.Core.Database
{
[System.Runtime.Serialization.DataContract]
[DatabaseKey(DatabaseName = "ID", Size = 4)]
public class GenericCommand : DatabaseItemWithIntPK
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(GenericCommand));
[System.Runtime.Serialization.DataMember]
[DatabaseProperty(Size = 4)]
public int ServerID { get; set; }
[System.Runtime.Serialization.DataMember]
[DatabaseProperty(Size = 4)]
public ServerCommand Command { get; set; }
[System.Runtime.Serialization.DataMember]
[DatabaseProperty(Size = -1)]
public string Payload { get; set; }
public GenericCommand() { }
public GenericCommand(int ServerID, ServerCommand Command, string Payload)
{
this.ServerID = ServerID;
this.Command = Command;
this.Payload = Payload;
}
public override string ToString()
{
return string.Format("{0:S}[{1:S}, ServerID={2:N0}, Command={3:S}, Payload=\"{4:S}\"]",
this.GetType().FullName,
base.ToString(), ServerID, Command.ToString(), Payload);
}
public static List<GenericCommand> DequeueByServerID(SqlConnection conn, SqlTransaction trans, int ServerID)
{
List<GenericCommand> lCommands = new List<GenericCommand>();
using (SqlCommand cmd = new SqlCommand(tsql.Extractor.Get("GenericCommand.DequeueByServerID"), conn, trans))
{
SqlParameter param = new SqlParameter("@ServerID", System.Data.SqlDbType.Int);
param.Value = ServerID;
cmd.Parameters.Add(param);
cmd.Prepare();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
GenericCommand gc = new GenericCommand();
gc.ParseFromDataReader(reader);
lCommands.Add(gc);
}
}
}
return lCommands;
}
public override void ParseFromDataReader(SqlDataReader r)
{
ID = r.GetInt32(0);
ServerID = r.GetInt32(1);
Command = (ServerCommand)r.GetInt32(2);
Payload = null;
if (!r.IsDBNull(3))
Payload = r.GetString(3);
//switch (command)
//{
// case ServerCommand.RestartServer:
// return new Commands.RestartServer(serverID, payload) { ID = id };
// case ServerCommand.KillTask:
// return new Commands.KillExecutionTask(serverID, payload) { ID = id };
//}
//throw new NotSupportedException(string.Format("Command {0:S} is not supported at this time", command));
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_AnisotropicFiltering : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.AnisotropicFiltering");
LuaObject.addMember(l, 0, "Disable");
LuaObject.addMember(l, 1, "Enable");
LuaObject.addMember(l, 2, "ForceEnable");
LuaDLL.lua_pop(l, 1);
}
}
|
namespace Belot.UI.Windows
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Belot.AI.SmartPlayer;
using Belot.Engine;
using Belot.Engine.Cards;
using Belot.Engine.Game;
using Belot.Engine.GameMechanics;
using Belot.Engine.Players;
using global::Windows.UI.Core;
using global::Windows.UI.Xaml;
using global::Windows.UI.Xaml.Controls;
using global::Windows.UI.Xaml.Input;
public sealed partial class MainPage : Page
{
private readonly UiPlayer player = new UiPlayer();
private readonly OpenCardsPlayerDecorator eastPlayer = new OpenCardsPlayerDecorator(new SmartPlayer());
private readonly OpenCardsPlayerDecorator northPlayer = new OpenCardsPlayerDecorator(new SmartPlayer());
private readonly OpenCardsPlayerDecorator westPlayer = new OpenCardsPlayerDecorator(new SmartPlayer());
private readonly BelotGame game;
//// private readonly ValidAnnouncesService validAnnouncesService;
public MainPage()
{
this.InitializeComponent();
this.game = new BelotGame(this.player, this.eastPlayer, this.northPlayer, this.westPlayer);
this.player.InfoChangedInGetBid += this.UiPlayerOnInfoChangedInGetBid;
this.player.InfoChangedInGetAnnounces += this.UiPlayerOnInfoChangedInGetAnnounces;
this.player.InfoChangedInPlayCard += this.UiPlayerOnInfoChangedInPlayCard;
Task.Run(() => this.game.PlayGame(PlayerPosition.East));
this.ProgramVersion.Text = "Belot v1.0";
}
private async void UiPlayerOnInfoChangedInGetBid(object sender, PlayerGetBidContext e)
{
await this.UpdateBaseInfo(e);
await this.Dispatcher.RunAsync(
CoreDispatcherPriority.High,
() =>
{
this.BidsPanel.Children.Clear();
foreach (BidType bidType in Enum.GetValues(typeof(BidType)))
{
var button = new Button
{
Content = bidType.ToString(),
IsEnabled = e.AvailableBids.HasFlag(bidType),
Tag = bidType,
};
button.Tapped += this.BidTapped;
this.BidsPanel.Children.Add(button);
}
this.BidsPanel.Visibility = Visibility.Visible;
});
await this.UpdateCurrentTrickActions(new List<PlayCardAction>());
}
private async void UiPlayerOnInfoChangedInGetAnnounces(object sender, PlayerGetAnnouncesContext e)
{
await this.UpdateBaseInfo(e);
await this.UpdateCurrentTrickActions(e.CurrentTrickActions);
}
private async void UiPlayerOnInfoChangedInPlayCard(object sender, PlayerPlayCardContext e)
{
await this.UpdateBaseInfo(e, e.AvailableCardsToPlay);
await this.UpdateCurrentTrickActions(e.CurrentTrickActions);
}
private async Task UpdateCurrentTrickActions(IEnumerable<PlayCardAction> currentTrickActions)
{
await this.Dispatcher.RunAsync(
CoreDispatcherPriority.High,
() =>
{
this.southCardPlayed.Visibility = Visibility.Collapsed;
this.eastCardPlayed.Visibility = Visibility.Collapsed;
this.northCardPlayed.Visibility = Visibility.Collapsed;
this.westCardPlayed.Visibility = Visibility.Collapsed;
foreach (var trickAction in currentTrickActions)
{
switch (trickAction.Player)
{
case PlayerPosition.South:
this.southCardPlayed.SetCard(trickAction.Card);
this.southCardPlayed.Visibility = Visibility.Visible;
break;
case PlayerPosition.East:
this.eastCardPlayed.SetCard(trickAction.Card);
this.eastCardPlayed.Visibility = Visibility.Visible;
break;
case PlayerPosition.North:
this.northCardPlayed.SetCard(trickAction.Card);
this.northCardPlayed.Visibility = Visibility.Visible;
break;
case PlayerPosition.West:
this.westCardPlayed.SetCard(trickAction.Card);
this.westCardPlayed.Visibility = Visibility.Visible;
break;
}
}
});
}
private async Task UpdateBaseInfo(BasePlayerContext basePlayerContext, CardCollection availableCards = null)
{
await this.Dispatcher.RunAsync(
CoreDispatcherPriority.High,
() =>
{
this.ProgramVersion.Text = basePlayerContext.CurrentContract.ToString();
this.TotalResult.Text =
$"{basePlayerContext.SouthNorthPoints} - {basePlayerContext.EastWestPoints}";
this.UpdateOtherPlayerCards();
// South player cards
this.SouthCardsPanel.Children.Clear();
var playerCards = basePlayerContext.MyCards.ToList();
for (var i = 0; i < playerCards.Count; i++)
{
var cardControl = new CardControl { Margin = new Thickness(i == 0 ? 0 : -50, 0, 0, 0) };
cardControl.Tapped += this.PlayerCardTapped;
cardControl.SetCard(playerCards[i]);
if (availableCards != null && !availableCards.Contains(playerCards[i]))
{
cardControl.Disable();
}
else
{
cardControl.Enable();
}
this.SouthCardsPanel.Children.Add(cardControl);
}
});
}
private void UpdateOtherPlayerCards()
{
// East player cards
this.EastCardsPanel.Children.Clear();
for (var i = 0; i < this.eastPlayer.Cards.ToList().Count; i++)
{
var cardControl = new CardControl { Margin = new Thickness(0, i == 0 ? 0 : -80, 0, 0), Width = 100 };
if (this.OpenCardsCheckBox.IsChecked == true)
{
var card = this.eastPlayer.Cards.ToList()[i];
cardControl.SetCard(card);
}
this.EastCardsPanel.Children.Add(cardControl);
}
// North player cards
this.NorthCardsPanel.Children.Clear();
for (var i = 0; i < this.northPlayer.Cards.ToList().Count; i++)
{
var cardControl = new CardControl { Margin = new Thickness(i == 0 ? 0 : -50, 0, 0, 0), Width = 100 };
if (this.OpenCardsCheckBox.IsChecked == true)
{
var card = this.northPlayer.Cards.ToList()[i];
cardControl.SetCard(card);
}
this.NorthCardsPanel.Children.Add(cardControl);
}
// West player cards
this.WestCardPanel.Children.Clear();
for (var i = 0; i < this.westPlayer.Cards.ToList().Count; i++)
{
var cardControl = new CardControl { Margin = new Thickness(0, i == 0 ? 0 : -80, 0, 0), Width = 100 };
if (this.OpenCardsCheckBox.IsChecked == true)
{
var card = this.westPlayer.Cards.ToList()[i];
cardControl.SetCard(card);
}
this.WestCardPanel.Children.Add(cardControl);
}
}
private void PlayerCardTapped(object sender, TappedRoutedEventArgs eventArgs)
{
// TODO: Ask for belot - var dialog = new MessageDialog(content, title);
this.player.PlayCardAction = new PlayCardAction((sender as CardControl)?.Card);
}
private void BidTapped(object sender, TappedRoutedEventArgs eventArgs)
{
this.BidsPanel.Visibility = Visibility.Collapsed;
this.player.GetBidAction = ((sender as Button)?.Tag as BidType?) ?? BidType.Pass;
}
private async void OpenCardsCheckBoxTapped(object sender, TappedRoutedEventArgs e)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, this.UpdateOtherPlayerCards);
}
}
}
|
//
// 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.Collections;
#endregion
namespace DotNetNuke.Security.Permissions
{
/// -----------------------------------------------------------------------------
/// Project : DotNetNuke
/// Namespace: DotNetNuke.Security.Permissions
/// Class : CompareModulePermissions
/// -----------------------------------------------------------------------------
/// <summary>
/// CompareModulePermissions provides the a custom IComparer implementation for
/// ModulePermissionInfo objects
/// </summary>
/// -----------------------------------------------------------------------------
internal class CompareModulePermissions : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return ((ModulePermissionInfo) x).ModulePermissionID.CompareTo(((ModulePermissionInfo) y).ModulePermissionID);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace Erwine.Leonard.T.ExampleWebApplication
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RepositoryCatalog
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]
}
}
|
using Checkout.Payment.Query.Domain;
using Checkout.Payment.Query.Domain.Interfaces;
using Checkout.Payment.Query.Domain.Models;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Threading.Tasks;
using System.Text.Json;
using Checkout.Payment.Query.Seedwork.Extensions;
using Microsoft.Extensions.Logging;
namespace Checkout.Payment.Query.Data
{
public class PaymentRepository : IPaymentRepository
{
IDistributedCache _paymentCache;
private readonly ILogger<PaymentRepository> _logger;
public PaymentRepository(IDistributedCache paymentCache, ILogger<PaymentRepository> logger)
{
_paymentCache = paymentCache;
_logger = logger;
}
public async Task<ITryResult<PaymentRequest>> TryGetPayment(Guid paymentId)
{
try
{
var paymentData = await _paymentCache.GetStringAsync($"Payment_{paymentId}");
if (paymentData != null)
{
var paymentRequest = JsonSerializer.Deserialize<PaymentRequest>(paymentData);
_logger.LogInformation($"Success getting payment from cache [paymentId={paymentId}]");
return TryResult<PaymentRequest>.CreateSuccessResult(paymentRequest);
}
else
{
_logger.LogInformation($"Not found payment from cache [paymentId={paymentId}]");
return TryResult<PaymentRequest>.CreateFailResult();
}
}
catch(Exception ex)
{
_logger.LogError($"Failed to get payment from cache [paymentId={paymentId}, message={ex.Message}]");
return TryResult<PaymentRequest>.CreateFailResult();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.