text stringlengths 13 6.01M |
|---|
/** 版本信息模板在安装目录下,可自行修改。
* OA_RISKEDURECEIVER.cs
*
* 功 能: N/A
* 类 名: OA_RISKEDURECEIVER
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014/7/22 15:35:10 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace PDTech.OA.Model
{
/// <summary>
/// 教育任务接收表
/// </summary>
[Serializable]
public partial class OA_RISKEDURECEIVER
{
public OA_RISKEDURECEIVER()
{}
#region Model
private decimal? _education_id;
private decimal? _receiver_id;
private decimal? _read_status;
private DateTime? _read_time;
private decimal? _reda_count;
/// <summary>
/// 教育任务ID
/// </summary>
public decimal? EDUCATION_ID
{
set { _education_id = value; }
get { return _education_id; }
}
/// <summary>
/// 接收人ID
/// </summary>
public decimal? RECEIVER_ID
{
set{ _receiver_id=value;}
get{return _receiver_id;}
}
/// <summary>
/// 已读状态0:未读,1:已读
/// </summary>
public decimal? READ_STATUS
{
set{ _read_status=value;}
get{return _read_status;}
}
/// <summary>
/// 阅读时间
/// </summary>
public DateTime? READ_TIME
{
set{ _read_time=value;}
get{return _read_time;}
}
/// <summary>
/// 阅读次数
/// </summary>
public decimal? READ_COUNT
{
set { _reda_count = value; }
get { return _reda_count; }
}
#endregion Model
}
}
|
using Domain.Interfaces.Generics;
using Entities.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Interfaces.InterfaceLogSistema
{
public interface ILogSistema : IGeneric<LogSistema>
{
}
}
|
using BlueSportApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlueSportApp.Services.Store
{
public interface IStoreService
{
public List<Models.StoreModel> GetAll();
StoreModel GetById(string id);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
private Camera cam;
private FieldConstructor field;
private void Start()
{
field = GetComponent<FieldConstructor>();
cam = Camera.main;
}
public Enemy CreateEnemy(Object enemyObj, Transform victimTransform)
{
Vector2 pos = GetPosition();
GameObject enemyGO = (GameObject) Instantiate(enemyObj);
enemyGO.transform.position = pos;
Enemy enemy = enemyGO.GetComponent<Enemy>();
enemy.Init(victimTransform);
return enemy;
}
private Vector2 GetPosition()
{
List<Vector2> directions = new List<Vector2>();
directions.Add(Vector2.left);
directions.Add(Vector2.right);
directions.Add(Vector2.up);
directions.Add(Vector2.down);
Vector2 worldPosition;
worldPosition = cam.ViewportToWorldPoint(Vector2.zero);
if(worldPosition.x < -field.sizeX/2)
directions.Remove(Vector2.left);
if(worldPosition.y < -field.sizeY/2)
directions.Remove(Vector2.down);
worldPosition = cam.ViewportToWorldPoint(Vector2.one);
if(worldPosition.x > field.sizeX/2)
directions.Remove(Vector2.right);
if(worldPosition.y > field.sizeY/2)
directions.Remove(Vector2.up);
if(directions.Count > 0)
{
Vector2 direction = directions[Random.Range(0, directions.Count)];
float x = (field.sizeX * direction.x)/2 + Random.Range(-field.sizeX/2, field.sizeX/2) * Mathf.Abs(direction.y);
float y = (field.sizeY * direction.y)/2 + Random.Range(-field.sizeY/2, field.sizeY/2) * Mathf.Abs(direction.x);
return new Vector2(x, y);
}
else
{
return Vector2.zero;
}
}
}
|
using System;
using System.Collections.Specialized;
//For MethodImpl
using System.Runtime.CompilerServices;
namespace Unicorn
{
public static class Force
{
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Apply(int entity, Vector3 vec, float mag);
}
}
|
using MadWizard.WinUSBNet;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace ASCOM.microlux
{
class Microlux
{
private static readonly Guid MICROLUX_GUID = new Guid("{6D4AA3C7-8867-40BA-97A2-EC1DD808C787}");
private static readonly byte[] SYNC_MARKER = new byte[] { 0x50, 0x55, 0x0C, 0xA5, 0x00, 0x5A, 0x24, 0x5A, 0x40 };
private const int FRAME_WIDTH = 1284;
private const int FRAME_HEIGHT = 968;
private const int FRAME_SIZE = FRAME_WIDTH * FRAME_HEIGHT * 2;
private const int FRAME_BUFFER_SIZE = FRAME_SIZE * 4;
private const int QUEUE_DEPTH = 512;
private const int BUFFER_SIZE = 16384;
private const int ZEBRA_SIZE = 23112;
private readonly string serialNumber;
private readonly BlockingCollection<Buffer> bufferQueue = new BlockingCollection<Buffer>(new ConcurrentQueue<Buffer>(), QUEUE_DEPTH);
private readonly BlockingCollection<byte[]> frameDataQueue = new BlockingCollection<byte[]>(new ConcurrentQueue<byte[]>(), 4);
private readonly BlockingCollection<int[,]> frameQueue = new BlockingCollection<int[,]>(new ConcurrentQueue<int[,]>(), 1);
private Connection connection;
private USBDevice device;
private TransferQueue transferQueue;
public Microlux(string serialNumber)
{
this.serialNumber = serialNumber;
}
public void Connect()
{
device = Open(serialNumber);
if (device == null)
{
throw new ASCOM.NotConnectedException("Failed to open USB device");
}
device.ControlPipeTimeout = 0;
var fifoInterface = device.Interfaces[2];
var fifoPipe = fifoInterface.InPipe;
fifoPipe.Policy.RawIO = true;
transferQueue = new TransferQueue(fifoPipe, QUEUE_DEPTH, BUFFER_SIZE);
connection = new Connection();
new Thread(DecodeThread).Start();
new Thread(BufferThread).Start();
new Thread(TransferThread).Start();
}
public void StartExposure(int startX, int endX, int startY, int endY, int gain, int offset, int exposureCoarse, int exposureFine, int lineLength)
{
byte[] data = new byte[16];
var wrap = new BinaryWriter(new MemoryStream(data));
startX = 0;
startY = 2;
endX = 1283;
endY = 965;
wrap.Write((short)startX);
wrap.Write((short)endX);
wrap.Write((short)startY);
wrap.Write((short)endY);
wrap.Write((byte)gain);
wrap.Write((byte)offset);
wrap.Write((short)exposureCoarse);
wrap.Write((short)exposureFine);
wrap.Write((short)lineLength);
device.ControlOut(0x41, 0x80, 0, 2, data);
}
public void StopExposure()
{
device.ControlOut(0x41, 0x81, 0, 2);
frameQueue.Add(new int[1284, 966]);
}
public int[,] ReadFrame()
{
return frameQueue.Take();
}
public void DecodeThread()
{
var connection = this.connection;
while (true)
{
lock (connection)
{
if (!connection.Connected) return;
}
if (!frameDataQueue.TryTake(out byte[] data, 1000)) continue;
var frame = new int[FRAME_WIDTH, FRAME_HEIGHT];
for (var y = 0; y < FRAME_HEIGHT; y++)
{
var lineStart = y * FRAME_WIDTH * 2;
for (var x = 0; x < FRAME_WIDTH; x++)
{
var pb = data[(lineStart + (x << 1))] & 0xFF;
var pd = data[(lineStart + (x << 1)) | 1] & 0x0F;
var p = (R8(pb) << 4) | ((R8(pd) >> 4) & 0x0F);
frame[x, y] = (R8(pb) << 8) | (R8(pd) & 0xF0);
}
}
frameQueue.TryTake(out int[,] clear);
frameQueue.TryAdd(frame);
}
}
public void BufferThread()
{
var connection = this.connection;
var ringBuffer = new RingBuffer(FRAME_BUFFER_SIZE);
var syncing = true;
try
{
while (true)
{
lock (connection)
{
if (!connection.Connected) return;
}
if (!bufferQueue.TryTake(out Buffer buffer, 1000)) continue;
ringBuffer.Write(buffer.Data, 0, buffer.Length);
if (syncing)
{
if (ringBuffer.Sync(SYNC_MARKER))
{
syncing = false;
}
}
else
{
if (ringBuffer.Available() >= FRAME_SIZE)
{
byte[] frameData = ringBuffer.Read(FRAME_SIZE);
frameDataQueue.TryAdd(frameData);
ringBuffer.Consume(ZEBRA_SIZE);
syncing = true;
}
}
}
}
catch (Exception)
{
Disconnect();
}
}
public void TransferThread()
{
var connection = this.connection;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
try
{
while (true)
{
lock (connection)
{
if (!connection.Connected) return;
}
bufferQueue.TryAdd(transferQueue.Read());
}
} catch (Exception) {
Disconnect();
}
}
public void Disconnect()
{
try
{
StopExposure();
} catch (Exception) {}
lock(connection)
{
connection.Connected = false;
}
device.Dispose();
}
public static int R8(int i)
{
return table[i];
}
public static readonly int[] table = {
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
};
public static USBDevice Open(string serialNumber)
{
var list = List();
if (list.Count == 0) return null;
if (string.IsNullOrEmpty(serialNumber))
{
return new USBDevice(list.First().Info);
}
foreach (var device in list)
{
if (device.SerialNumber.Equals(serialNumber))
{
return new USBDevice(device.Info);
}
}
return null;
}
public static List<MicroluxDevice> List()
{
var list = new List<MicroluxDevice>();
var devices = USBDevice.GetDevices(MICROLUX_GUID);
var regex = new Regex(@"usb#vid_[a-f0-9]{4}&pid_[a-f0-9]{4}#([a-f0-9]{8})#", RegexOptions.IgnoreCase);
foreach (var device in devices)
{
var match = regex.Match(device.DevicePath);
if (match.Success)
{
list.Add(new MicroluxDevice(match.Groups[1].Value.ToUpper(), device));
}
else
{
list.Add(new MicroluxDevice(string.Empty, device));
}
}
return list;
}
}
class Connection
{
public bool Connected { get; set; } = true;
public object _Lock { get; } = new object();
}
class MicroluxDevice
{
public string SerialNumber {
get;
}
public USBDeviceInfo Info
{
get;
}
public MicroluxDevice(string name, USBDeviceInfo info)
{
SerialNumber = name;
Info = info;
}
public override string ToString()
{
return string.IsNullOrEmpty(SerialNumber) ? "microlux" : ("microlux [" + SerialNumber + "]");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoanShark.Domain.Core.ApplicationStages
{
public class PersonCheck : IApplicationStageCheck
{
private NameNotNullCheck _nameNotNullCheck;
private Person _person;
public PersonCheck(Person person)
{
_person = person;
_nameNotNullCheck = new NameNotNullCheck(_person.FirstName);
}
public bool Validate()
{
return _nameNotNullCheck.Validate();
}
}
}
|
using AutoMapper;
using Publicon.Core.Entities.Concrete;
using Publicon.Infrastructure.Commands.Models.Publication;
using Publicon.Infrastructure.DTOs;
using System;
namespace Publicon.Infrastructure.Profiles
{
public class PublicationProfile : Profile
{
public PublicationProfile()
{
CreateMap<CreatePublicationCommand, Publication>()
.ForMember(m => m.Id, options => options.Ignore())
.ForMember(m => m.PublicationFields, options => options.Ignore())
.ForMember(m => m.UserId, options => options.Ignore())
.ForMember(m => m.FileName, options => options.Ignore())
.ForMember(m => m.PublicationTime, options => options.MapFrom(x=>x.PublicationTime.Date))
.ForMember(m => m.AddedAt, options => options.MapFrom(x => DateTime.UtcNow))
.ForMember(m => m.FileName, options =>
{
options.PreCondition(x => x.File != null);
options.MapFrom(x => Guid.NewGuid().ToString());
});
CreateMap<EditPublicationCommand, Publication>()
.ForMember(m => m.Id, options => options.Ignore())
.ForMember(m => m.CategoryId, options => options.Ignore())
.ForMember(m => m.PublicationFields, options => options.Ignore())
.ForMember(m => m.FileName, options => options.Ignore())
.ForMember(m => m.AddedAt, options => options.Ignore())
.ForMember(m => m.FileName, options => options.Ignore());
CreateMap<Publication, PublicationDetailsDTO>()
.ForMember(m => m.UserFamilyName, opt => opt.MapFrom(m => m.User.FamilyName))
.ForMember(m => m.UserGivenName, opt => opt.MapFrom(m => m.User.GivenName))
.ForMember(m => m.UserId, opt => opt.MapFrom(m => m.User.Id))
.ForMember(m => m.HasUploadedFile, opt => opt.MapFrom(m => !string.IsNullOrWhiteSpace(m.FileName)));
CreateMap<Publication, PublicationDTO>();
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
//[System.Serializable]
public class PlayerInput : ICharacterInput
{
private Command movementCommand = new MovementCommand();
private Command skillCommand = new UseSkillCommand();
public List<Command> GetInput()
{
((MovementCommand)movementCommand).MovementeVector = Vector3.zero;
List<Command> inputCommands = new List<Command>();
inputCommands.Add(movementCommand);
if (Input.GetKey(KeyCode.LeftArrow))
{
((MovementCommand)movementCommand).MovementeVector += Vector3.left;
inputCommands.Add(movementCommand);
}
if (Input.GetKey(KeyCode.RightArrow))
{
((MovementCommand)movementCommand).MovementeVector += Vector3.right;
inputCommands.Add(movementCommand);
}
if (Input.GetKeyDown(KeyCode.Space))
{
inputCommands.Add(skillCommand);
}
return inputCommands;
}
} |
using nmct.ba.cashlessproject.model.Web;
using nmct.ssa.webapp.DataAcces;
using nmct.ssa.webapp.PresentationModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace nmct.ssa.webapp.Controllers
{
[Authorize]
public class KassaController : Controller
{
[HttpGet]
public ActionResult Index()
{
List<KassaPM> alleKassas = new List<KassaPM>();
alleKassas = KassaDA.GetAlleKassas();
List<KassaPM> ToegekendeKassas = new List<KassaPM>();
List<KassaPM> BeschikbareKassas = new List<KassaPM>();
foreach (KassaPM item in alleKassas)
{
if (item.vereniging.OrganisationName != "")
ToegekendeKassas.Add(item);
else
BeschikbareKassas.Add(item);
}
ViewBag.Kassas = alleKassas;
ViewBag.BeschikbareKassas = BeschikbareKassas;
ViewBag.ToegekendeKassas = ToegekendeKassas;
List<Vereniging> verenigingen = new List<Vereniging>();
verenigingen = VerenigingDA.GetVerenigingen();
ViewBag.Verenigingen = verenigingen;
return View();
}
[HttpGet]
public ActionResult Zoek(int vereniging)
{
List<KassaPM> kassas = new List<KassaPM>();
kassas = KassaDA.GetKassasByVereniging(vereniging);
if (kassas.Count != 0)
ViewBag.Titel = kassas.Count + " kassa(s) gevonden van " + kassas[0].vereniging.OrganisationName;
else
ViewBag.Titel = "Geen zoekresultaten gevonden.";
return View(kassas);
}
[HttpGet]
public ActionResult Nieuw()
{
return View();
}
[HttpPost]
public ActionResult Nieuw(Kassa kassa)
{
int rowsaffected = KassaDA.NieuweKassa(kassa);
if (rowsaffected == 0)
return View("Error");
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Wijzigen()
{
List<Kassa> kassas = new List<Kassa>();
kassas = KassaDA.GetKassas();
ViewBag.Kassas = kassas;
List<Vereniging> verenigingen = new List<Vereniging>();
verenigingen = VerenigingDA.GetVerenigingen();
ViewBag.Verenigingen = verenigingen;
return View();
}
[HttpPost]
public ActionResult Wijzigen(int kassa, int vereniging)
{
List<KassaPM> toekenning = new List<KassaPM>();
toekenning = KassaDA.CheckKassaToekenning(kassa, vereniging);
if (toekenning.Count == 0) //kassa nog niet toegekend aan vereniging
{
int rowsaffected = KassaDA.KassaToevoegenVereniging(kassa, vereniging);
}
else if (toekenning.Count == 1)//kassa al toegekend aan vereniging => kassa wijzigen van vereniging
{
int rowsaffected = KassaDA.UpdateVerenigingKassa(vereniging, kassa);
}
return RedirectToAction("Index", "Kassa");
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using ext;
using OC.Hooks;
using OCP;
using OCP.Sym;
namespace OC.Group
{
/**
* Class Manager
*
* Hooks available in scope \OC\Group:
* - preAddUser(\OC\Group\Group group, \OC\User\User user)
* - postAddUser(\OC\Group\Group group, \OC\User\User user)
* - preRemoveUser(\OC\Group\Group group, \OC\User\User user)
* - postRemoveUser(\OC\Group\Group group, \OC\User\User user)
* - preDelete(\OC\Group\Group group)
* - postDelete(\OC\Group\Group group)
* - preCreate(string groupId)
* - postCreate(\OC\Group\Group group)
*
* @package OC\Group
*/
public class Manager : PublicEmitter , IGroupManager {
/** @var GroupInterface[] */
private IList<GroupInterface> backends = new List<GroupInterface>();
/** @var \OC\User\Manager */
private OC.User.Manager userManager;
/** @var EventDispatcherInterface */
private EventDispatcherInterface dispatcher;
/** @var ILogger */
private ILogger logger;
/** @var \OC\Group\Group[] */
private IList<OC.Group.Group > cachedGroups = new List<OC.Group.Group>();
/** @var \OC\Group\Group[] */
private IList<OC.Group.Group> cachedUserGroups = new List<Group>();
/** @var \OC\SubAdmin */
private OC.SubAdmin subAdmin = null;
/**
* @param \OC\User\Manager userManager
* @param EventDispatcherInterface dispatcher
* @param ILogger logger
*/
public Manager(OC.User.Manager userManager,
EventDispatcherInterface dispatcher,
ILogger logger) {
this.userManager = userManager;
this.dispatcher = dispatcher;
this.logger = logger;
// cachedGroups = & this.cachedGroups;
// cachedUserGroups = & this.cachedUserGroups;
// this.listen("OC.Group", "postDelete", function (group) use (&cachedGroups, &cachedUserGroups) {
// /**
// * @var \OC\Group\Group group
// */
// unset(cachedGroups[group.getGID()]);
// cachedUserGroups = [];
// });
// this.listen('\OC\Group', 'postAddUser', function (group) use (&cachedUserGroups) {
// /**
// * @var \OC\Group\Group group
// */
// cachedUserGroups = [];
// });
// this.listen('\OC\Group', 'postRemoveUser', function (group) use (&cachedUserGroups) {
// /**
// * @var \OC\Group\Group group
// */
// cachedUserGroups = [];
// });
}
/**
* Checks whether a given backend is used
*
* @param string backendClass Full classname including complete namespace
* @return bool
*/
public bool isBackendUsed(string backendClass) {
backendClass = strtolower(ltrim(backendClass, '\\'));
foreach (this.backends as backend) {
if (strtolower(get_class(backend)) === backendClass) {
return true;
}
}
return false;
}
/**
* @param \OCP\GroupInterface backend
*/
public void addBackend(OCP.GroupInterface backend) {
this.backends.Add(backend);;
this.clearCaches();
}
public void clearBackends() {
this.backends.Clear();
this.clearCaches();
}
/**
* Get the active backends
* @return \OCP\GroupInterface[]
*/
public IList<OCP.GroupInterface> getBackends() {
return this.backends;
}
protected void clearCaches() {
this.cachedGroups .Clear();
this.cachedUserGroups.Clear();
}
/**
* @param string gid
* @return \OC\Group\Group
*/
public OCP.IGroup get(string gid) {
if (isset(this.cachedGroups[gid])) {
return this.cachedGroups[gid];
}
return this.getGroupObject(gid);
}
/**
* @param string gid
* @param string displayName
* @return \OCP\IGroup
*/
protected IGroup getGroupObject(string gid, string displayName = null) {
backends = [];
foreach (this.backends as backend) {
if (backend.implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
groupData = backend.getGroupDetails(gid);
if (is_array(groupData) && !empty(groupData)) {
// take the display name from the first backend that has a non-null one
if (is_null(displayName) && isset(groupData['displayName'])) {
displayName = groupData['displayName'];
}
backends[] = backend;
}
} else if (backend.groupExists(gid)) {
backends[] = backend;
}
}
if (count(backends) === 0) {
return null;
}
this.cachedGroups[gid] = new Group(gid, backends, this.dispatcher, this.userManager, this, displayName);
return this.cachedGroups[gid];
}
/**
* @param string gid
* @return bool
*/
public bool groupExists(string gid) {
return this.get(gid) is IGroup;
}
/**
* @param string gid
* @return \OC\Group\Group
*/
public IGroup createGroup(string gid) {
if (gid.IsEmpty()) {
return null;
} else if (this.get(gid) != null) {
return this.get(gid) ;
} else {
// this.emit("\OC\Group", "preCreate", array(gid));
foreach (var backend in this.backends)
{
if (backend.)
{
}
}
foreach (this.backends as backend) {
if (backend.implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
backend.createGroup(gid);
group = this.getGroupObject(gid);
this.emit('\OC\Group', 'postCreate', array(group));
return group;
}
}
return null;
}
}
/**
* @param string search
* @param int limit
* @param int offset
* @return \OC\Group\Group[]
*/
public IList<Group> search(string search, int limit = -1 , int offset = -1) {
groups = [];
foreach (this.backends as backend) {
groupIds = backend.getGroups(search, limit, offset);
foreach (groupIds as groupId) {
aGroup = this.get(groupId);
if (aGroup instanceof IGroup) {
groups[groupId] = aGroup;
} else {
this.logger.debug('Group "' . groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
}
}
if (!is_null(limit) and limit <= 0) {
return array_values(groups);
}
}
return array_values(groups);
}
/**
* @param IUser|null user
* @return \OC\Group\Group[]
*/
public IList<IGroup> getUserGroups(IUser user= null) {
if (!user instanceof IUser) {
return [];
}
return this.getUserIdGroups(user.getUID());
}
/**
* @param string uid the user id
* @return \OC\Group\Group[]
*/
public IList<IGroup> getUserIdGroups(string uid) {
if (isset(this.cachedUserGroups[uid])) {
return this.cachedUserGroups[uid];
}
groups = [];
foreach (this.backends as backend) {
groupIds = backend.getUserGroups(uid);
if (is_array(groupIds)) {
foreach (groupIds as groupId) {
aGroup = this.get(groupId);
if (aGroup instanceof IGroup) {
groups[groupId] = aGroup;
} else {
this.logger.debug('User "' . uid . '" belongs to deleted group: "' . groupId . '"', ['app' => 'core']);
}
}
}
}
this.cachedUserGroups[uid] = groups;
return this.cachedUserGroups[uid];
}
/**
* Checks if a userId is in the admin group
* @param string userId
* @return bool if admin
*/
public bool isAdmin(string userId) {
foreach (var backend in this.backends) {
if (backend.implementsActions(\OC\Group\Backend::IS_ADMIN) && backend.isAdmin(userId)) {
return true;
}
}
return this.isInGroup(userId, "admin");
}
/**
* Checks if a userId is in a group
* @param string userId
* @param string group
* @return bool if in group
*/
public bool isInGroup(string userId, string group) {
return array_key_exists(group, this.getUserIdGroups(userId));
}
/**
* get a list of group ids for a user
* @param IUser user
* @return array with group ids
*/
public IList<string> getUserGroupIds(IUser user) {
return array_map(function(value) {
return (string) value;
}, array_keys(this.getUserGroups(user)));
}
/**
* get an array of groupid and displayName for a user
* @param IUser user
* @return array ['displayName' => displayname]
*/
public IDictionary<string,string> getUserGroupNames(IUser user) {
return array_map(function(group) {
return array('displayName' => group.getDisplayName());
}, this.getUserGroups(user));
}
/**
* get a list of all display names in a group
* @param string gid
* @param string search
* @param int limit
* @param int offset
* @return array an array of display names (value) and user ids (key)
*/
public IDictionary<string,string> displayNamesInGroup(string gid, string search = "", int limit = -1, int offset = 0) {
group = this.get(gid);
if(is_null(group)) {
return [];
}
search = trim(search);
groupUsers = [];
if(!empty(search)) {
// only user backends have the capability to do a complex search for users
searchOffset = 0;
searchLimit = limit * 100;
if(limit === -1) {
searchLimit = 500;
}
do {
filteredUsers = this.userManager.searchDisplayName(search, searchLimit, searchOffset);
foreach(filteredUsers as filteredUser) {
if(group.inGroup(filteredUser)) {
groupUsers[]= filteredUser;
}
}
searchOffset += searchLimit;
} while(count(groupUsers) < searchLimit+offset && count(filteredUsers) >= searchLimit);
if(limit === -1) {
groupUsers = array_slice(groupUsers, offset);
} else {
groupUsers = array_slice(groupUsers, offset, limit);
}
} else {
groupUsers = group.searchUsers('', limit, offset);
}
matchingUsers = [];
foreach(groupUsers as groupUser) {
matchingUsers[groupUser.getUID()] = groupUser.getDisplayName();
}
return matchingUsers;
}
/**
* @return \OC\SubAdmin
*/
public OC.SubAdmin getSubAdmin() {
if (this.subAdmin == null) {
this.subAdmin = new OC.SubAdmin(
this.userManager,
this,
OC.server.getDatabaseConnection()
);
}
return this.subAdmin;
}
}
} |
using System.Windows.Data;
using System.Windows.Controls;
namespace TariffCreator.NewTariff.TariffCreate
{
partial class CreateTariff
{
void BtnActivate()
{
btnAdd.IsEnabled = true;
btnSave.IsEnabled = false;
btnCancel.IsEnabled = false;
if (countryListe.Count > 0) btnDelet.IsEnabled = true;
txtDescription.IsEnabled = false;
txtPrefix.IsEnabled = false;
Binding binding = new Binding("Description");
binding.Mode = BindingMode.OneWay;
txtDescription.SetBinding(TextBox.TextProperty, binding);
binding = new Binding("Prefix");
binding.Mode = BindingMode.OneWay;
txtPrefix.SetBinding(TextBox.TextProperty, binding);
binding = new Binding("PriceMin");
binding.StringFormat = "F2";
txtPriceMin.SetBinding(TextBox.TextProperty, binding);
binding = new Binding("PriceCall");
binding.StringFormat = "F2";
txtPriceCall.SetBinding(TextBox.TextProperty, binding);
listCountry.SelectedIndex = 0;
}
void BtnDeactivate()
{
txtDescription.Text = "";
txtPrefix.Text = "";
txtPriceCall.Text = "";
txtPriceMin.Text = "";
txtDescription.IsEnabled = true;
txtPrefix.IsEnabled = true;
txtPrefix.Focus();
BindingOperations.ClearBinding(txtDescription, TextBox.TextProperty);
BindingOperations.ClearBinding(txtPrefix, TextBox.TextProperty);
BindingOperations.ClearBinding(txtPriceCall, TextBox.TextProperty);
BindingOperations.ClearBinding(txtPriceMin, TextBox.TextProperty);
btnAdd.IsEnabled = false;
btnSave.IsEnabled = true;
btnCancel.IsEnabled = true;
btnDelet.IsEnabled = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public class Bibliotekarz : Osoba
{
private string dataZatrudnienia;
private double wynagrodzenie;
public Bibliotekarz()
{
}
public Bibliotekarz(string imie, string nazwisko, string dataZatrudnienia, double wynagrodzenie) : base(imie, nazwisko)
{
this.imie = imie;
this.nazwisko = nazwisko;
this.dataZatrudnienia = dataZatrudnienia;
this.wynagrodzenie = wynagrodzenie;
}
public void WypiszInfo()
{
Console.WriteLine("Bibliotekarz___________");
Console.WriteLine($"\tImię: {this.imie}");
Console.WriteLine($"\tNazwisko: {this.nazwisko}");
Console.WriteLine($"\tData zatrudnienia: {this.dataZatrudnienia}");
Console.WriteLine($"\tWynagrodzenie: {this.wynagrodzenie}");
Console.WriteLine("_____________________");
}
}
}
|
using Ast.Bll;
using Ast.IBll;
using Ast.Models;
using System.Web.Mvc;
using System;
using Ast.Web.Models;
using System.Collections;
using System.Collections.Generic;
using Ast.Common;
using SqlSugar;
namespace Ast.Web.Controllers
{
public class ForumController : BaseController
{
private IClubPostCommentListService PostCommentListService = new ClubPostCommentListService();
private IClubPostTypeService PostTypeService = new ClubPostTypeService();
private IClubPostListService PostListService = new ClubPostListService();
private IMemberListService memberListSevice = new MemberListService();
private IClubChildCommentService childCommentService = new ClubChildCommentService();
// GET: Forum
[AllowAnonymous]
#region 论坛首页
public ActionResult Index(int typeId = 0, int page = 1, int limit = 15)
{
PageModel pagemodel = new PageModel()
{
PageIndex = page,
PageSize = limit
};
ViewBag.PostType = PostTypeService.GetList(o => true);
if (typeId == 0)
{
var PostList = PostListService.GetPageList(pagemodel, o => true);
IList<PostModel> md = new List<PostModel>();
foreach (ClubPostList item in PostList.datalist)
{
var artmd = new PostModel();
artmd.postmd = item;
var memList = memberListSevice.GetSingle(o => o.Id == item.MemberId);
artmd.membermd = memList;
md.Add(artmd);
}
ViewBag.Postmodel = md;
}
else
{
var PostList = PostListService.GetPageList(pagemodel, o => o.PostTypeId == typeId);
IList<PostModel> md = new List<PostModel>();
foreach (ClubPostList item in PostList.datalist)
{
var artmd = new PostModel();
artmd.postmd = item;
var memList = memberListSevice.GetSingle(o => o.Id == item.MemberId);
artmd.membermd = memList;
md.Add(artmd);
}
ViewBag.Postmodel = md;
}
return View();
}
[ValidateInput(false)]//用来允许用户发帖时上传标签
//发帖
public JsonResult Add(ClubPostList Post)
{
var list = PostListService.GetList(o => o.Title.Contains(Post.Title));
if (list.Count > 0)
{
return Json(new { success = false, msg = "这个帖子已经发表过了" }, JsonRequestBehavior.AllowGet);
}
MemberList user = Session["Users"] as MemberList;
ClubPostList md = new ClubPostList();
md.Title = Post.Title;
md.PostContent = Post.PostContent;
md.PostTypeId = Post.PostTypeId;
md.AddTime = DateTime.Now;
md.ModifyTime = DateTime.Now;
md.LastReplyTime = DateTime.Now;
md.MemberId = user.Id;
PostListService.Add(md);
return Json(new
{
success = true,
msg = "发表成功!",
}, JsonRequestBehavior.AllowGet);
}
#endregion
#region 帖子详情
//帖子主页
[AllowAnonymous]
public ActionResult PostDetail(int id)
{
//参数的id是帖子对应的Id
IList<CommentModel> md = new List<CommentModel>();//整串对象
var Post = PostListService.GetById(id.ToString());
//每点击进来一次帖子,点击量就加一
Post.LookNum += 1;
PostListService.Update(Post);
var member = memberListSevice.GetById(Post.MemberId.ToString());
string PostTypeName = PostTypeService.GetSingle(o => o.Id == Post.PostTypeId).TypeName;
var comment = PostCommentListService.GetList(o => o.PostId == id);
for (var n = comment.Count - 1; n >= 0; n--)
{
//倒序
CommentModel commentModel = new CommentModel();//包含用户信息的评论实体对象
var user = memberListSevice.GetById(comment[n].MemberId.ToString());
var childComments = childCommentService.GetList(o => o.PostCommentId == comment[n].Id);
commentModel.Commentmd = comment[n];
commentModel.Membermd = user;
commentModel.childComments = childComments;
md.Add(commentModel);
}
PostModel am = new PostModel();
am.membermd = member;
am.postmd = Post;
am.posttypename = PostTypeName;
ViewBag.Post = am;
ViewBag.comment = comment;
ViewBag.commentModel = md;
ViewBag.PostType = PostTypeService.GetList(o => true);
return View();
}
//增加评论
public JsonResult AddComment(ClubPostCommentList comment, ClubChildComment childComment, int PostId)
{
//区分两种情况,一个是评论回复(二级);一个是评论
if (childComment.PostCommentId != 0)
{
childComment.FromUserId = CurrentUserId;
childComment.AddTime = DateTime.Now;
childComment.FromUserName = CurrentName;
childCommentService.Add(childComment);
}
else
{
comment.MemberId = CurrentUserId;
comment.AddTime = DateTime.Now;
comment.PostId = PostId;
PostCommentListService.Add(comment);
var Post = PostListService.GetById(PostId.ToString());
Post.LastReplyTime = DateTime.Now;
Post.ReplyCount += 1;
PostListService.Update(Post);
}
return Json(new { success = true, msg = "评论成功", data = PostId }, JsonRequestBehavior.AllowGet);
}
#endregion
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("Vars")]
public class Vars : MonoClass
{
public Vars(IntPtr address) : this(address, "Vars")
{
}
public Vars(IntPtr address, string className) : base(address, className)
{
}
public static string GetClientConfigPath()
{
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "Vars", "GetClientConfigPath", Array.Empty<object>());
}
public static VarKey Key(string key)
{
object[] objArray1 = new object[] { key };
return MonoClass.smethod_15<VarKey>(TritonHs.MainAssemblyPath, "", "Vars", "Key", objArray1);
}
public static void RefreshVars()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "Vars", "RefreshVars");
}
public static string CONFIG_FILE_NAME
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "Vars", "CONFIG_FILE_NAME");
}
}
}
}
|
using UnityEngine;
public class Item : MonoBehaviour
{
#region Properties
public GameObject RelatedObject
{
get
{
return _relatedObject;
}
}
public string ItemName
{
get
{
return _itemName;
}
}
public ItemTypes ItemType
{
get
{
return _itemType;
}
}
#endregion
#region Fields
[SerializeField] private GameObject _relatedObject;
[SerializeField] private string _itemName;
[SerializeField] private ItemTypes _itemType;
#endregion
}
|
using System;
using UnityEngine;
namespace RO
{
public class ActionEvent_Lua : MonoBehaviour
{
public void ActionEvent_ED_CMD(int cmdID)
{
if (null == SingleTonGO<LuaLuancher>.Me)
{
return;
}
SingleTonGO<LuaLuancher>.Me.Call("Command_ED", new object[]
{
cmdID
});
}
}
}
|
using System;
namespace Parrot
{
public class AfricanParrot : Parrot
{
private int _numberOfCoconuts;
public AfricanParrot(int numberOfCoconuts)
{
_numberOfCoconuts = numberOfCoconuts;
}
public override double GetSpeed()
{
return Math.Max(0, GetBaseSpeed() - GetLoadFactor() * _numberOfCoconuts);
}
private double GetLoadFactor()
{
return 9.0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FiveInARowApp.DAL
{
public class DataSettings
{
public string dataFilePath = HttpContext.Current.Server.MapPath("~/App_Data/BookData.xml");
}
} |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
namespace SANTI_WEB.Models
{
public partial class DbSantiWebsiteContext : DbContext
{
public DbSantiWebsiteContext(DbContextOptions<DbSantiWebsiteContext> options)
: base(options)
{
}
public virtual DbSet<Events> Events { get; set; }
public virtual DbSet<Products> Products { get; set; }
public virtual DbSet<ProductsDescription> ProductsDescription { get; set; }
public virtual DbSet<ProductsItems> ProductsItems { get; set; }
public virtual DbSet<ProductsSeo> ProductsSeo { get; set; }
public virtual DbSet<ProductsSuccessStories> ProductsSuccessStories { get; set; }
public virtual DbSet<Prospects> Prospects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Events>(entity =>
{
entity.HasKey(e => e.PkEvents);
entity.ToTable("events");
entity.Property(e => e.PkEvents).HasColumnName("pkEvents");
entity.Property(e => e.Logo)
.HasColumnName("logo")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Place)
.HasColumnName("place")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.StartDate).HasColumnName("startDate");
entity.Property(e => e.Title)
.HasColumnName("title")
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Products>(entity =>
{
entity.HasKey(e => e.PkProducts);
entity.ToTable("products");
entity.Property(e => e.PkProducts).HasColumnName("pkProducts");
entity.Property(e => e.Color)
.HasColumnName("color")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Logo)
.HasColumnName("logo")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasColumnName("name")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Route)
.HasColumnName("route")
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<ProductsDescription>(entity =>
{
entity.HasKey(e => e.PkProductsDescription);
entity.ToTable("productsDescription");
entity.Property(e => e.PkProductsDescription).HasColumnName("pkProductsDescription");
entity.Property(e => e.Description)
.HasColumnName("description")
.IsUnicode(false);
entity.Property(e => e.FkProducts).HasColumnName("fkProducts");
entity.Property(e => e.Language)
.HasColumnName("language")
.HasMaxLength(10)
.IsUnicode(false);
entity.Property(e => e.Title)
.HasColumnName("title")
.HasMaxLength(255)
.IsUnicode(false);
entity.HasOne(d => d.FkProductsNavigation)
.WithMany(p => p.ProductsDescription)
.HasForeignKey(d => d.FkProducts)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK__productsD__fkPro__02084FDA");
});
modelBuilder.Entity<ProductsItems>(entity =>
{
entity.HasKey(e => e.PkProductsItems);
entity.ToTable("productsItems");
entity.Property(e => e.PkProductsItems).HasColumnName("pkProductsItems");
entity.Property(e => e.Description)
.HasColumnName("description")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.FkProducts).HasColumnName("fkProducts");
entity.Property(e => e.Language)
.HasColumnName("language")
.HasMaxLength(10)
.IsUnicode(false);
entity.Property(e => e.Logo)
.HasColumnName("logo")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Type)
.HasColumnName("type")
.HasDefaultValueSql("((0))");
entity.HasOne(d => d.FkProductsNavigation)
.WithMany(p => p.ProductsItems)
.HasForeignKey(d => d.FkProducts)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK__productsI__fkPro__7F2BE32F");
});
modelBuilder.Entity<ProductsSeo>(entity =>
{
entity.HasKey(e => e.PkProductsSeo);
entity.ToTable("productsSEO");
entity.Property(e => e.PkProductsSeo).HasColumnName("pkProductsSEO");
entity.Property(e => e.Description)
.HasColumnName("description")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.FkProducts).HasColumnName("fkProducts");
entity.Property(e => e.Language)
.HasColumnName("language")
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Tag)
.HasColumnName("tag")
.HasMaxLength(255)
.IsUnicode(false);
entity.HasOne(d => d.FkProductsNavigation)
.WithMany(p => p.ProductsSeo)
.HasForeignKey(d => d.FkProducts)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK__productsS__fkPro__7B5B524B");
});
modelBuilder.Entity<ProductsSuccessStories>(entity =>
{
entity.HasKey(e => e.PkProductsSuccessStories);
entity.ToTable("productsSuccessStories");
entity.Property(e => e.PkProductsSuccessStories).HasColumnName("pkProductsSuccessStories");
entity.Property(e => e.Description).HasColumnName("description");
entity.Property(e => e.FkProducts).HasColumnName("fkProducts");
entity.HasOne(d => d.FkProductsNavigation)
.WithMany(p => p.ProductsSuccessStories)
.HasForeignKey(d => d.FkProducts)
.HasConstraintName("FK__productsS__fkPro__787EE5A0");
});
modelBuilder.Entity<Prospects>(entity =>
{
entity.ToTable("prospects");
entity.HasKey(e => e.PkProspects);
entity.Property(e => e.PkProspects).HasColumnName("pkProspects");
entity.Property(e => e.Email)
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Enterprise)
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Telephone)
.HasMaxLength(255)
.IsUnicode(false);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace WF.SDK.Common.Imaging
{
/// <summary>
/// Summary description for ImageConverter.
/// </summary>
public class ImageConverter
{
private const string MODNAME = "WF.ImageTools.ImageConverter";
//Static Only
private ImageConverter() { }
/// <summary>
/// Receives a page image list and returns a faxable page image list.
/// </summary>
/// <param name="pages"></param>
/// <param name="paperSize"></param>
/// <param name="faxQuality"></param>
/// <param name="result"></param>
/// <returns></returns>
internal static List<PageImage> CreateFaxTiff(List<PageImage> pages, PaperSize paperSize, FaxQuality faxQuality, ImageOperationResult result)
{
paperSize = ImageConverter.GetBestFitPaperSizeForList(pages, paperSize);
if (faxQuality == FaxQuality.Default) { faxQuality = FaxQuality.Normal; }
if (faxQuality == FaxQuality.Undefined) { faxQuality = FaxQuality.Normal; }
bool fastTrack = CanFastTrackPageImageList(pages, paperSize);
List<PageImage> ret = new List<PageImage>();
for (int i = 0; i < pages.Count; i++)
{
ret.Add(CreateFaxTiff(pages[i], paperSize, faxQuality, result, fastTrack));
}
return ret;
}
private static bool CanFastTrackPageImageList(List<PageImage> pages, PaperSize paperSize)
{
bool fastTrack = true;
PaperSize paperSizeCheck = pages[0].PageInfo.GetStandardPaperSize;
foreach (PageImage pi in pages)
{
//if (pi.PageInfo.GetStandardPaperSize != PaperSize.Auto
// && pi.PageInfo.GetStandardPaperSize != paperSizeCheck) { fastTrack = false; break; }
if (pi.PageInfo.GetStandardPaperSize != paperSizeCheck) { fastTrack = false; break; }
if (pi.PageInfo.GetStandardPaperSize == PaperSize.Undefined) { fastTrack = false; break; }
}
return fastTrack;
}
private static PageImage CreateFaxTiff(PageImage page, PaperSize paperSize, FaxQuality faxQuality, ImageOperationResult result, bool fastTrack)
{
PageImage ret = new PageImage();
//FastTrack
//if(page.PageInfo.IsStandardFaxTiff)
if (fastTrack)
{
Trace.WriteLine("FastTracking tiff creation", MODNAME);
return CreateFaxTiffFastTrack(page, paperSize, faxQuality, result);
}
else
{
Trace.WriteLine("SlowTracking tiff creation", MODNAME);
return CreateFaxTiffSlowTrack(page, paperSize, faxQuality, result);
}
}
private static PageImage CreateFaxTiffFastTrack(PageImage page, PaperSize paperSize, FaxQuality faxQuality, ImageOperationResult result)
{
PageInfo inf = null;
PageImage ret = new PageImage();
Bitmap src = null;
Bitmap destroy = null;
src = BitmapHelper.CreateCopy1BppIndexed(page._sourceBmp);
inf = new PageInfo(src);
//If the size is not right copy to other size (padding or reducing)
if (inf.GetStandardPaperSize != paperSize)
{
if (inf.GetStandardPaperSize == PaperSize.Legal && paperSize == PaperSize.Letter)
{
destroy = src;
src = BitmapHelper.CreateCopyFaxGeometry(src, faxQuality, paperSize, ImageUtility.InterpolationMode);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
}
if (inf.GetStandardPaperSize == PaperSize.Letter && paperSize == PaperSize.Legal)
{
destroy = src;
src = BitmapHelper.CreateCopyFaxGeometryPadding(src, faxQuality, paperSize);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
}
}
//Make sure its 1bpp
if (inf.PixelFormat != PixelFormat.Format1bppIndexed)
{
destroy = src;
src = BitmapHelper.CreateCopy1BppIndexed(src);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
}
//Reduce or increase quality as needed
if (inf.GetStandardFaxQuality != faxQuality)
{
if (inf.GetStandardFaxQuality == FaxQuality.Fine && faxQuality == FaxQuality.Normal)
{
destroy = src;
src = BitmapHelper.ConvertTiffHiToTiffLow(src, ImageUtility.HighToLowScaleMethod);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
}
if (inf.GetStandardFaxQuality == FaxQuality.Normal && faxQuality == FaxQuality.Fine)
{
destroy = src;
src = BitmapHelper.ConvertTiffLowToTiffHi(src);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
}
}
ret._pageInfo = null;
ret._sourceBmp = src;
return ret;
}
private static PageImage CreateFaxTiffSlowTrack(PageImage page, PaperSize paperSize, FaxQuality faxQuality, ImageOperationResult result)
{
PageInfo inf = null;
PageImage ret = new PageImage();
Bitmap src = null;
Bitmap destroy = null;
Trace.WriteLine("SlowTrack: CreateCopyExact...", MODNAME);
src = BitmapHelper.CreateCopyExact(page._sourceBmp);
Trace.WriteLine("SlowTrack: CreateCopyExact done.", MODNAME);
inf = new PageInfo(src);
if (inf.GetBestFitRotation != 0)
{
Trace.WriteLine("SlowTrack: Rotating...", MODNAME);
destroy = src;
src = BitmapHelper.CreateCopyRotate(src, 90);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
Trace.WriteLine("SlowTrack: Rotating done.", MODNAME);
}
destroy = src;
Trace.WriteLine("SlowTrack: CreateCopyFaxGeometry...", MODNAME);
src = BitmapHelper.CreateCopyFaxGeometry(src, faxQuality, paperSize, ImageUtility.InterpolationMode);
Trace.WriteLine("SlowTrack: CreateCopyFaxGeometry done.", MODNAME);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
destroy = src;
Trace.WriteLine("SlowTrack: CreateCopy1BppIndexed: " + ImageUtility.ConvertTo1BppMethod.ToString() + "...", MODNAME);
src = BitmapHelper.CreateCopy1BppIndexed(src);
Trace.WriteLine("SlowTrack: CreateCopy1BppIndexed done.", MODNAME);
if (destroy != null) { destroy.Dispose(); destroy = null; }
inf = new PageInfo(src);
ret._pageInfo = null;
ret._sourceBmp = src;
return ret;
}
internal static List<PageImage> ConvertToFaxablePageImageList(List<PageImage> pages, FaxQuality quality, PaperSize paperSize, ImageOperationResult result)
{
if (pages.Count == 0) { return new List<PageImage>(); }
FaxQuality targetquality = quality;
PaperSize targetsize = ImageConverter.GetBestFitPaperSizeForList(pages, PaperSize.Auto);
List<PageImage> ret = new List<PageImage>();
for (int i = 0; i < pages.Count; i++)
{
ret.Add(new PageImage());
}
for (int i = 0; i < ret.Count; i++)
{
ret[i] = CreateFaxTiffSlowTrack(pages[i], targetsize, targetquality, result);
}
return ret;
}
#region ConvertPixelFormat
/// <summary>
/// Creates a new PageImageList containing pages with the new pixel format. The
/// source PageImageList is not altered.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="pixelFormat">The pixel format to use.</param>
/// <returns>The new PageImageList.</returns>
private static List<PageImage> ConvertPixelFormat(List<PageImage> pages, PixelFormat pixelFormat)
{
return ImageConverter.ConvertPixelFormat(pages, pixelFormat, 500);
}
/// <summary>
/// Creates a new PageImageList containing pages with the new pixel format. The
/// source PageImageList is not altered.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="pixelFormat">The pixel format to use.</param>
/// /// <param name="threshold">The threshold to use for converting to 1bpp. Default is 500.</param>
/// <returns>The new PageImageList.</returns>
private static List<PageImage> ConvertPixelFormat(List<PageImage> pages, PixelFormat pixelFormat, int threshold)
{
List<PageImage> ret = new List<PageImage>();
//If there are no images return.
if (pages.Count == 0) { return ret; }
bool consistentPixelFormat = ImageConverter.IsListPixelFormatConsistent(pages);
PixelFormat pxfmt = pages[0].PageInfo.PixelFormat;
if (consistentPixelFormat && pxfmt == pixelFormat)
{
return ImageConverter.CreateDeepCopy(pages);
}
if (pixelFormat == PixelFormat.Format1bppIndexed) //Indexed format, need to do something special
{
ret = ImageConverter.CreateEmptyPageImageList(pages, pixelFormat);
for (int i = 0; i < pages.Count; i++)
{
ConvertPixelFormatTo1bppIndexed(pages[i], ret[i]);
}
return ret;
}
else
{
ret = ImageConverter.CreateEmptyPageImageList(pages, pixelFormat);
ImageConverter.DrawSourceToDestination(pages, ret);
return ret;
}
}
private static void ConvertPixelFormatTo1bppIndexed(PageImage source, PageImage destination)
{
// Lock source bitmap in memory
BitmapData sourceData = source.Bitmap.LockBits(new Rectangle(0, 0, source.Bitmap.Width, source.Bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Copy image data to binary array
int imageSize = sourceData.Stride * sourceData.Height;
byte[] sourceBuffer = new byte[imageSize];
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);
// Unlock source bitmap
source.Bitmap.UnlockBits(sourceData);
// Lock destination bitmap in memory
BitmapData destinationData = destination.Bitmap.LockBits(new Rectangle(0, 0, destination.Bitmap.Width, destination.Bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
// Create destination buffer
imageSize = destinationData.Stride * destinationData.Height;
byte[] destinationBuffer = new byte[imageSize];
int sourceIndex = 0;
int destinationIndex = 0;
int pixelTotal = 0;
byte destinationValue = 0;
int pixelValue = 128;
int height = source.Bitmap.Height;
int width = source.Bitmap.Width;
int threshold = 500;
// Iterate lines
for (int y = 0; y < height; y++)
{
sourceIndex = y * sourceData.Stride;
destinationIndex = y * destinationData.Stride;
destinationValue = 0;
pixelValue = 128;
// Iterate pixels
for (int x = 0; x < width; x++)
{
// Compute pixel brightness (i.e. total of Red, Green, and Blue values)
pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3];
if (pixelTotal > threshold)
{
destinationValue += (byte)pixelValue;
}
if (pixelValue == 1)
{
destinationBuffer[destinationIndex] = destinationValue;
destinationIndex++;
destinationValue = 0;
pixelValue = 128;
}
else
{
pixelValue >>= 1;
}
sourceIndex += 4;
}
if (pixelValue != 128)
{
destinationBuffer[destinationIndex] = destinationValue;
}
}
// Copy binary image data to destination bitmap
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);
// Unlock destination bitmap
destination.Bitmap.UnlockBits(destinationData);
}
#endregion
#region ApplyMonochromeFilter
/// <summary>
/// Creates a new PageImageList containing pages with only two colors (Black and White).
/// The returned pixel format will be the same as the source pixel format.
/// The given page image list is not altered.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="threshold">The threshold to use for converting to bitonal. Default is 500.</param>
/// <returns>The new PageImageList.</returns>
private static List<PageImage> ApplyMonochromeFilter(List<PageImage> pages, int threshold = 500)
{
//Get out if source is empty
if (pages.Count == 0) { return new List<PageImage>(); }
List<PageImage> ret = ImageConverter.CreateEmptyPageImageList(pages, PixelFormat.Format32bppArgb);
List<PageImage> source = null;
//If the pages are consistent 32 bit then continue
bool consistentPixelFormat = ImageConverter.IsListPixelFormatConsistent(pages);
if (consistentPixelFormat && pages[0].PageInfo.PixelFormat == PixelFormat.Format32bppArgb)
{
source = pages;
for (int i = 0; i < source.Count; i++)
{
ImageConverter.ApplyMonochromeFilter(source[i], ret[i], threshold);
}
}
else
{
source = ImageConverter.CreateEmptyPageImageList(pages, PixelFormat.Format32bppArgb);
for (int i = 0; i < pages.Count; i++)
{
ImageConverter.DrawSourcePageToDestination(pages[i], source[i], ImageUtility.InterpolationMode);
}
for (int i = 0; i < source.Count; i++)
{
ImageConverter.ApplyMonochromeFilter(source[i], ret[i], threshold);
}
ImageUtility.Dispose(source);
}
return ret;
}
private static void ApplyMonochromeFilter(PageImage source, PageImage destination, int threshold)
{
// If source and destination are not 32 BPP, ARGB format, then throw error
if (source.Bitmap.PixelFormat != PixelFormat.Format32bppArgb && destination.Bitmap.PixelFormat != PixelFormat.Format32bppArgb)
{
throw new Exception("Conversion to Monochrome requires that the source and destination both have PixelFormat.Format32bppArgb.");
}
// If source and destination are not the same size then throw error
if (source.PageInfo.WidthPixels != destination.PageInfo.WidthPixels || source.PageInfo.HeightPixels != destination.PageInfo.HeightPixels)
{
throw new Exception("Conversion to Monochrome requires that the source and destination are both the same size.");
}
// Lock source bitmap in memory
BitmapData sourceData = source.Bitmap.LockBits(new Rectangle(0, 0, source.Bitmap.Width, source.Bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Copy image data to binary array
int imageSize = sourceData.Stride * sourceData.Height;
byte[] sourceBuffer = new byte[imageSize];
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);
// Unlock source bitmap
source.Bitmap.UnlockBits(sourceData);
int pixelTotal = sourceData.Height * sourceData.Width;
byte destinationValue = 0;
// Iterate pixels
for (int i = 0; i < pixelTotal; i++)
{
pixelTotal = sourceBuffer[i * 4 + 1] + sourceBuffer[i * 4 + 2] + sourceBuffer[i * 4 + 3];
if (pixelTotal > threshold)
{
destinationValue = 255;
}
else
{
destinationValue = 0;
}
sourceBuffer[i * 4 + 1] = destinationValue;
sourceBuffer[i * 4 + 2] = destinationValue;
sourceBuffer[i * 4 + 3] = destinationValue;
}
// Lock source bitmap in memory
BitmapData destinationData = destination.Bitmap.LockBits(new Rectangle(0, 0, destination.Bitmap.Width, destination.Bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Copy binary image data to destination bitmap
Marshal.Copy(sourceBuffer, 0, destinationData.Scan0, imageSize);
// Unlock destination bitmap
destination.Bitmap.UnlockBits(destinationData);
}
#endregion
#region ConvertToFaxGeometry
/// <summary>
/// Creates a new PageImageList containing pages that have a fax geometry.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="quality">The Fax Quality. Default is Low.</param>
/// <returns>The new PageImageList (always with 32bpp pixel format)</returns>
private static List<PageImage> ConvertToFaxGeometry(List<PageImage> pages, FaxQuality quality = FaxQuality.Normal)
{
return ImageConverter.ConvertToFaxGeometry(pages, quality, ImageConverter.GetBestFitPaperSizeForList(pages, PaperSize.Auto));
}
/// <summary>
/// Creates a new PageImageList containing pages that have a fax geometry.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="quality">The Fax Quality. Default is Low.</param>
/// <param name="paperSize">The Paper size. Default is Auto.</param>
/// <returns>The new PageImageList (always with 32bpp pixel format)</returns>
private static List<PageImage> ConvertToFaxGeometry(List<PageImage> pages, FaxQuality quality, PaperSize paperSize)
{
return ImageConverter.ConvertToFaxGeometry(pages, quality, paperSize, ImageUtility.InterpolationMode);
}
/// <summary>
/// Creates a new PageImageList containing pages that have a fax geometry.
/// </summary>
/// <param name="pages">The PageImageList to alter.</param>
/// <param name="quality">The Fax Quality. Default is Low.</param>
/// <param name="paperSize">The Paper size. Default is Auto.</param>
/// <param name="interpolationMode">The Interpolation mode. Default is High, but will use the current value in Image Utility, unless defined here. size.</param>
/// <returns>The new PageImageList (always with 32bpp pixel format)</returns>
private static List<PageImage> ConvertToFaxGeometry(List<PageImage> pages, FaxQuality quality, PaperSize paperSize, InterpolationMode interpolationMode)
{
List<PageImage> ret = ImageConverter.CreateEmptyPageImageList(pages.Count, PixelFormat.Format32bppArgb, pages[0].Bitmap.Palette, quality, paperSize);
for (int i = 0; i < pages.Count; i++)
{
ImageConverter.ConvertToFaxGeometry(pages[i], ret[i], interpolationMode);
}
return ret;
}
private static void ConvertToFaxGeometry(PageImage source, PageImage destination, InterpolationMode interpolationMode)
{
Graphics g = Graphics.FromImage(destination.Bitmap);
g.InterpolationMode = interpolationMode;
GraphicsUnit gu = GraphicsUnit.Pixel;
g.DrawImage(source.Bitmap, destination.Bitmap.GetBounds(ref gu), source.Bitmap.GetBounds(ref gu), GraphicsUnit.Pixel);
g.Dispose();
}
#endregion
/// <summary>
/// Copies an existing PageImage List, including pixel data. PixelFormat,
/// Resolution, and color depth are not affected.
/// </summary>
/// <param name="list">The list to copy.</param>
/// <returns>The new page image list.</returns>
private static List<PageImage> CreateDeepCopy(List<PageImage> list)
{
return ImageUtility.LoadImage(list);
}
/// <summary>
/// Creates a new PageImageList that contains empty images (no pixel data) with the
/// appropriate PixelFormat. Image sizes and resolutions will be the same as the given list.
/// </summary>
/// <param name="list">The list to copy.</param>
/// <param name="pixelFormat">The new pixel format.</param>
/// <returns>The new page image list.</returns>
private static List<PageImage> CreateEmptyPageImageList(List<PageImage> list, PixelFormat pixelFormat)
{
List<PageImage> ret = new List<PageImage>();
//Get out if not pages in list.
if (list.Count == 0) { return ret; }
foreach (PageImage page in list)
{
PageImage newpage = ImageConverter.CreateEmptyPageImage(page, pixelFormat);
ret.Add(newpage);
}
return ret;
}
/// <summary>
/// Creates a new PageImage that contains an empty image (no pixel data) with the
/// appropriate PixelFormat. Image size and resolution will be the same as the PageImage.
/// </summary>
/// <param name="page">The page image to copy.</param>
/// <param name="pixelFormat">The new pixel format.</param>
/// <returns>The new page image.</returns>
private static PageImage CreateEmptyPageImage(PageImage page, PixelFormat pixelFormat)
{
PageImage newpage = new PageImage();
newpage._sourceBmp = BitmapHelper.CreateBitMap(page.PageInfo.WidthPixels, page.PageInfo.HeightPixels, page.PageInfo.HorizontalResolution, page.PageInfo.VerticalResolution, page.Bitmap.Palette, pixelFormat);
return newpage;
}
/// <summary>
/// Creates a new PageImageList that contains empty images (no pixel data) with the
/// appropriate PixelFormat, Size and Resolution.
/// </summary>
/// <param name="pageCount">Page count to get.</param>
/// <param name="pixelFormat">The new pixel format.</param>
/// <param name="quality">The fax quality to use (sets resolution)</param>
/// <param name="paperSize">The page size to use (width and height)</param>
/// <returns>The new page image list.</returns>
private static List<PageImage> CreateEmptyPageImageList(int pageCount, PixelFormat pixelFormat, ColorPalette palette, FaxQuality quality, PaperSize paperSize)
{
List<PageImage> ret = new List<PageImage>();
//Get out if not pages in list.
if (pageCount <= 0) { return ret; }
int width = ImageUtility.FAX_TIF_HOR_PX;
float hres = ImageUtility.FAX_TIF_HOR_RES;
int height = 0;
float vres = 0.0F;
if (quality == FaxQuality.Fine)
{
vres = ImageUtility.FAX_TIF_VER_RES_HI;
if (paperSize == PaperSize.Legal) { height = ImageUtility.FAX_TIF_VER_PX_LGL_HI; }
else { height = ImageUtility.FAX_TIF_VER_PX_LTR_HI; }
}
else
{
vres = ImageUtility.FAX_TIF_VER_RES_LOW;
if (paperSize == PaperSize.Legal) { height = ImageUtility.FAX_TIF_VER_PX_LGL_LOW; }
else { height = ImageUtility.FAX_TIF_VER_PX_LTR_LOW; }
}
for (int i = 0; i < pageCount; i++)
{
PageImage newpage = new PageImage();
newpage._sourceBmp = BitmapHelper.CreateBitMap(width, height, hres, vres, palette, pixelFormat);
ret.Add(newpage);
}
return ret;
}
/// <summary>
/// Creates a new PageImageList that contains empty images (no pixel data) with the
/// appropriate PixelFormat, Size and Resolution.
/// </summary>
/// <param name="pageCount">Page count to get.</param>
/// <param name="pixelFormat">The new pixel format.</param>
/// <param name="quality">The fax quality to use (sets resolution)</param>
/// <param name="paperSize">The page size to use (width and height)</param>
/// <returns>The new page image list.</returns>
internal static List<PageImage> CreateCroppedPageImageList(List<PageImage> list)
{
List<PageImage> ret = new List<PageImage>();
foreach (PageImage img in list)
{
PageImage newpage = new PageImage();
newpage._sourceBmp = BitmapHelper.CreateCopyCrop(img._sourceBmp);
ret.Add(newpage);
}
return ret;
}
private static void DrawSourceToDestination(List<PageImage> source, List<PageImage> destination)
{
ImageConverter.DrawSourceToDestination(source, destination, ImageUtility.InterpolationMode);
}
private static void DrawSourceToDestination(List<PageImage> source, List<PageImage> destination, InterpolationMode interpolationMode)
{
if (source.Count == 0) { return; }
for (int i = 0; i < source.Count; i++)
{
ImageConverter.DrawSourcePageToDestination(source[i], destination[i], interpolationMode);
}
}
private static void DrawSourcePageToDestination(PageImage source, PageImage destination, InterpolationMode interpolationMode)
{
Graphics g = Graphics.FromImage(destination.Bitmap);
g.InterpolationMode = interpolationMode;
GraphicsUnit gu = GraphicsUnit.Pixel;
g.DrawImage(source.Bitmap, destination.Bitmap.GetBounds(ref gu), source.Bitmap.GetBounds(ref gu), GraphicsUnit.Pixel);
g.Dispose();
}
/// <summary>
/// When paper size is Auto, determines the appropriate fax paper size for the
/// all images contained in the imageInfo object. If paper size is not Auto, then it
/// will returns the paper size.
/// </summary>
/// <param name="pages">The pages to check</param>
/// <param name="paperSize">The paper size</param>
private static PaperSize GetBestFitPaperSizeForList(List<PageImage> pages, PaperSize paperSize)
{
//If it's not auto then fix it to the requested size
if (paperSize == PaperSize.Legal) { return PaperSize.Legal; }
if (paperSize == PaperSize.Letter) { return PaperSize.Letter; }
//Track the bigest that we find.
PaperSize biggest = PaperSize.Letter;
//Otherwise, attempt to determine the best size
foreach (PageImage page in pages)
{
if (page.PageInfo.GetBestFitPaperSize == PaperSize.Legal)
{
biggest = PaperSize.Legal;
break;
}
}
return biggest;
}
/// <summary>
/// Checks for the consistency of the Pixel format in each page in the Page Image list.
/// If the list contains 0 or 1 page, always returns true.
/// </summary>
/// <param name="list">The list to check.</param>
/// <returns>Whether it is consistent or not.</returns>
private static bool IsListPixelFormatConsistent(List<PageImage> list)
{
bool ret = true;
if (list.Count == 0) { return ret; }
if (list.Count == 1) { return ret; }
PixelFormat pxfmt = list[0].PageInfo.PixelFormat;
foreach (PageImage page in list)
{
if (page.PageInfo.PixelFormat != pxfmt) { ret = false; }
}
return ret;
}
/// <summary>
/// Checks for the consistency of the Pixel format in each page in the Page Image list.
/// If the list contains 0 or 1 page, always returns true.
/// </summary>
/// <param name="list">The list to check.</param>
/// <returns>Whether it is consistent or not.</returns>
private static bool IsListStandardFax(List<PageImage> list)
{
bool ret = true;
foreach (PageImage page in list)
{
if (!page.PageInfo.IsStandardFaxTiff) { ret = false; break; }
}
return ret;
}
/// <summary>
/// Checks for the consistency of the Pixel format in each page in the Page Image list.
/// If the list contains 0 or 1 page, always returns true.
/// </summary>
/// <param name="pages">The list to check.</param>
/// <returns>Whether it is consistent or not.</returns>
//internal static bool IsListPaperSizeConsistent(PageImageList pages)
//{
// bool ret = false;
// if(pages.Count == 0){return ret;}
// if(!ImageConverter.IsListStandardFax(pages)){return ret;}
// PaperSize paperSize = PaperSize.Letter;
// paperSize = pages[0].PageInfo.GetStandardPaperSize;
// ret = true;
// foreach(PageImage page in pages)
// {
// if(paperSize != page.PageInfo.GetStandardPaperSize){ret = false;break;}
// }
// return ret;
//}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Linq;
using DAL;
namespace DKHocPhan
{
public partial class QLSV : Form
{
public QLSV()
{
InitializeComponent();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
string file = openFileDialog1.FileName;
if (string.IsNullOrEmpty(file))
return;
Image myimage = Image.FromFile(file);
pictureBox1.Image = myimage;
}
private void button2_Click(object sender, EventArgs e)
{
MemoryStream stream = new MemoryStream();
pictureBox1.Image.Save(stream, ImageFormat.Png);
DKHPDataContext db = new DKHPDataContext();
SinhVien sv = new SinhVien();
sv.hotenSV = txtTen.Text;
sv.maSV = Int32.Parse(txtMSV.Text);
sv.lop = txtLop.Text;
sv.nganh = txtChuyenNganh.Text;
sv.khoa = txtKhoa.Text;
sv.image = stream.ToArray();
db.SinhViens.InsertOnSubmit(sv);
db.SubmitChanges();
}
}
}
|
using Spine;
using System;
using UnityEngine;
public class Goblins : MonoBehaviour
{
private bool girlSkin;
private SkeletonAnimation skeletonAnimation;
private Bone headBone;
public void Start()
{
this.skeletonAnimation = base.GetComponent<SkeletonAnimation>();
this.headBone = this.skeletonAnimation.skeleton.FindBone("head");
SkeletonAnimation expr_2D = this.skeletonAnimation;
expr_2D.UpdateLocal = (SkeletonAnimation.UpdateBonesDelegate)Delegate.Combine(expr_2D.UpdateLocal, new SkeletonAnimation.UpdateBonesDelegate(this.UpdateLocal));
}
public void UpdateLocal(SkeletonAnimation skeletonAnimation)
{
this.headBone.Rotation += 15f;
}
public void OnMouseDown()
{
this.skeletonAnimation.skeleton.SetSkin((!this.girlSkin) ? "goblingirl" : "goblin");
this.skeletonAnimation.skeleton.SetSlotsToSetupPose();
this.girlSkin = !this.girlSkin;
if (this.girlSkin)
{
this.skeletonAnimation.skeleton.SetAttachment("right hand item", null);
this.skeletonAnimation.skeleton.SetAttachment("left hand item", "spear");
}
else
{
this.skeletonAnimation.skeleton.SetAttachment("left hand item", "dagger");
}
}
}
|
using System;
namespace PDV.DAO.Entidades.Estoque.InventarioEstoque
{
public class Inventario
{
public decimal IDInventario { get; set; } = -1;
public DateTime DataInventario { get; set; } = DateTime.Now;
public Inventario() { }
}
}
|
using Lab40111_MyFirstMVCApp.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lab40111_MyFirstMVCApp.Controllers
{
public class HomeController : Controller
{
//This Is The Index Page. Use This Block Of Code To Create New Pages.
public IActionResult Index()
{
return View();
}
/// <summary>
/// Making an HTTP Post request for action
/// </summary>
/// <param name="begYear"></param>
/// <param name="endYear"></param>
/// <returns></returns>
[HttpPost]
public IActionResult Index(int begYear, int endYear)
{
// redirects to the results action, given parameters
return RedirectToAction("Result", new { begYear, endYear });
}
public ViewResult Result(int begYear, int endYear)
{
//Creates a list of TimePerson file that match criteria
List<TimePerson> list = TimePerson.GetPersons(begYear, endYear);
return View(list);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cannonSelection : MonoBehaviour
{
public GameObject cannon;
public GameObject cannonPoint;
private Transform theposition;
public GameObject resourceObject;
public int cannonCost = 10;
private void Start()
{
cannon = Instantiate(Resources.Load("Cannon1", typeof(GameObject))) as GameObject; //This gives an error and that is what we want
cannonPoint = GameObject.FindGameObjectWithTag("TowerPoint");
theposition = cannonPoint.transform;
resourceObject = GameObject.FindGameObjectWithTag("resourceTarget");
}
private void FixedUpdate()
{
resourceObject = GameObject.FindGameObjectWithTag("resourceTarget");
cannonPoint = GameObject.FindGameObjectWithTag("TowerPoint");
}
public void SpawnCannon()
{
int amt = resourceObject.GetComponent<resourceGather>().getcannonResources();
if(amt >= cannonCost)
{
Transform theposition = cannonPoint.transform;
Instantiate(cannon, theposition.position, theposition.rotation);
resourceObject.GetComponent<resourceGather>().removecannonResources(cannonCost);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Collections.Generic;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Instrumentation;
#endregion
namespace DotNetNuke.Services.Search
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The SearchConfig class provides a configuration class for Search
/// </summary>
/// -----------------------------------------------------------------------------
[Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")]
[Serializable]
public class SearchConfig
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SearchConfig));
#region "Private Members"
private readonly bool _SearchIncludeCommon;
private readonly bool _SearchIncludeNumeric;
private readonly int _SearchMaxWordlLength;
private readonly int _SearchMinWordlLength;
#endregion
#region "Constructor(s)"
public SearchConfig(int portalID)
: this(PortalController.Instance.GetPortalSettings(portalID))
{
}
public SearchConfig(Dictionary<string, string> settings)
{
_SearchIncludeCommon = GetSettingAsBoolean("SearchIncludeCommon", settings, Host.SearchIncludeCommon);
_SearchIncludeNumeric = GetSettingAsBoolean("SearchIncludeNumeric", settings, Host.SearchIncludeNumeric);
_SearchMaxWordlLength = GetSettingAsInteger("MaxSearchWordLength", settings, Host.SearchMaxWordlLength);
_SearchMinWordlLength = GetSettingAsInteger("MinSearchWordLength", settings, Host.SearchMinWordlLength);
}
#endregion
#region "Public Properties"
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets whether to inlcude Common Words in the Search Index
/// </summary>
/// <remarks>Defaults to False</remarks>
/// -----------------------------------------------------------------------------
public bool SearchIncludeCommon
{
get
{
return _SearchIncludeCommon;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets whether to inlcude Numbers in the Search Index
/// </summary>
/// <remarks>Defaults to False</remarks>
/// -----------------------------------------------------------------------------
public bool SearchIncludeNumeric
{
get
{
return _SearchIncludeNumeric;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the maximum Search Word length to index
/// </summary>
/// <remarks>Defaults to 25</remarks>
/// -----------------------------------------------------------------------------
public int SearchMaxWordlLength
{
get
{
return _SearchMaxWordlLength;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the maximum Search Word length to index
/// </summary>
/// <remarks>Defaults to 3</remarks>
/// -----------------------------------------------------------------------------
public int SearchMinWordlLength
{
get
{
return _SearchMinWordlLength;
}
}
#endregion
#region "Private Methods"
private bool GetSettingAsBoolean(string key, Dictionary<string, string> settings, bool defaultValue)
{
bool retValue = Null.NullBoolean;
try
{
string setting = Null.NullString;
settings.TryGetValue(key, out setting);
if (string.IsNullOrEmpty(setting))
{
retValue = defaultValue;
}
else
{
retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase));
}
}
catch (Exception exc)
{
//we just want to trap the error as we may not be installed so there will be no Settings
Logger.Error(exc);
}
return retValue;
}
private int GetSettingAsInteger(string key, Dictionary<string, string> settings, int defaultValue)
{
int retValue = Null.NullInteger;
try
{
string setting = Null.NullString;
settings.TryGetValue(key, out setting);
if (string.IsNullOrEmpty(setting))
{
retValue = defaultValue;
}
else
{
retValue = Convert.ToInt32(setting);
}
}
catch (Exception exc)
{
//we just want to trap the error as we may not be installed so there will be no Settings
Logger.Error(exc);
}
return retValue;
}
#endregion
}
}
|
using TwinkleStar.Service;
namespace MrHai.Core
{
public abstract class MrHaiServiceBase
{
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IntegrationTechnoModel.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using CGI.Reflex.Core.Queries;
using ClosedXML.Excel;
using NHibernate;
namespace CGI.Reflex.Core.Importers.Models
{
// ReSharper disable RedundantAssignment
internal class IntegrationTechnoModel : BaseImporterModel<IntegrationTechnoLink>
{
[Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")]
public string AppSource { get; set; }
[Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")]
public string AppDest { get; set; }
[Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")]
[StringLength(255, ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "StringLength")]
public string Name { get; set; }
[Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")]
public string Technology { get; set; }
public override void Prepare(IXLWorksheet ws, string title = null)
{
SetTitle(ws, title ?? "Integrations-Technologies");
var ci = 1;
ws.Cell(3, ci++).SetValue("AppSource").Style.Font.SetBold();
ws.Cell(3, ci++).SetValue("AppDest").Style.Font.SetBold();
ws.Cell(3, ci++).SetValue("Name").Style.Font.SetBold();
ws.Cell(3, ci++).SetValue("Technology").Style.Font.SetBold();
SetAutoFilter(ws, ci - 1);
ci = 1;
ws.Column(ci++).Width = 25;
ws.Column(ci++).Width = 25;
ws.Column(ci++).Width = 25;
ws.Column(ci++).Width = 100;
SetColumnDataValidation(ws, 1, "Applications");
SetColumnDataValidation(ws, 2, "Applications");
SetColumnDataValidation(ws, 4, "Technologies");
}
public override IImporterModel ToRow(IXLRow row)
{
var ci = 1;
row.Cell(ci++).SetValue(AppSource ?? string.Empty);
row.Cell(ci++).SetValue(AppDest ?? string.Empty);
row.Cell(ci++).SetValue(Name ?? string.Empty);
row.Cell(ci++).SetValue(Technology ?? string.Empty);
return this;
}
public override IImporterModel FromRow(IXLRow row)
{
var ci = 1;
AppSource = row.Cell(ci++).GetString();
AppDest = row.Cell(ci++).GetString();
Name = row.Cell(ci++).GetString();
Technology = row.Cell(ci++).GetString();
return this;
}
public override IImporterModel ToEntity(ISession session, IntegrationTechnoLink entity)
{
var integrationQuery = session.QueryOver<Integration>().Where(i => i.Name == Name);
integrationQuery.JoinQueryOver(i => i.AppSource).Where(a => a.Name == AppSource);
integrationQuery.JoinQueryOver(i => i.AppDest).Where(a => a.Name == AppDest);
entity.Integration = integrationQuery.SingleOrDefault();
if (entity.Integration == null)
throw new ReferenceNotFoundException("Integration", string.Format("{0} => {1} ({2})", AppSource, AppDest, Name));
entity.Technology = new TechnologyByEscapedFullNameQuery { EscapedFullName = Technology }.Execute(session);
if (entity.Technology == null)
throw new ReferenceNotFoundException("Technology", Technology);
return this;
}
public override IImporterModel FromEntity(IntegrationTechnoLink entity)
{
if (entity.Integration == null)
{
AppSource = string.Empty;
AppDest = string.Empty;
Name = string.Empty;
Technology = string.Empty;
}
else
{
AppSource = entity.Integration.AppSource != null ? entity.Integration.AppSource.Name : string.Empty;
AppDest = entity.Integration.AppDest != null ? entity.Integration.AppDest.Name : string.Empty;
Name = entity.Integration.Name ?? string.Empty;
Technology = entity.Technology != null ? entity.Technology.GetEscapedFullName() : string.Empty;
}
return this;
}
}
//// ReSharper restore RedundantAssignment
}
|
#if NET472
using System;
using System.Collections.Generic;
using System.Reflection;
namespace yocto
{
internal static class TypeInfoExtensions
{
public static IEnumerable<ConstructorInfo> DeclaredConstructors(this TypeInfo extendThis)
{
return extendThis.DeclaredConstructors;
}
}
}
#endif |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UIFont : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int MarkAsChanged(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
uIFont.MarkAsChanged();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int UpdateUVRect(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
uIFont.UpdateUVRect();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int MatchSymbol(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
int offset;
LuaObject.checkType(l, 3, out offset);
int textLength;
LuaObject.checkType(l, 4, out textLength);
BMSymbol o = uIFont.MatchSymbol(text, offset, textLength);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddSymbol(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string sequence;
LuaObject.checkType(l, 2, out sequence);
string spriteName;
LuaObject.checkType(l, 3, out spriteName);
uIFont.AddSymbol(sequence, spriteName);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RemoveSymbol(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string sequence;
LuaObject.checkType(l, 2, out sequence);
uIFont.RemoveSymbol(sequence);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RenameSymbol(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string before;
LuaObject.checkType(l, 2, out before);
string after;
LuaObject.checkType(l, 3, out after);
uIFont.RenameSymbol(before, after);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int UsesSprite(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string s;
LuaObject.checkType(l, 2, out s);
bool b = uIFont.UsesSprite(s);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int CheckIfRelated_s(IntPtr l)
{
int result;
try
{
UIFont a;
LuaObject.checkType<UIFont>(l, 1, out a);
UIFont b;
LuaObject.checkType<UIFont>(l, 2, out b);
bool b2 = UIFont.CheckIfRelated(a, b);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b2);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_bmFont(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.bmFont);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_bmFont(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
BMFont bmFont;
LuaObject.checkType<BMFont>(l, 2, out bmFont);
uIFont.bmFont = bmFont;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_texWidth(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.texWidth);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_texWidth(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
int texWidth;
LuaObject.checkType(l, 2, out texWidth);
uIFont.texWidth = texWidth;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_texHeight(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.texHeight);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_texHeight(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
int texHeight;
LuaObject.checkType(l, 2, out texHeight);
uIFont.texHeight = texHeight;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_hasSymbols(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.hasSymbols);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_symbols(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.symbols);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_atlas(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.atlas);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_atlas(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
UIAtlas atlas;
LuaObject.checkType<UIAtlas>(l, 2, out atlas);
uIFont.atlas = atlas;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_material(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.material);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_material(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
Material material;
LuaObject.checkType<Material>(l, 2, out material);
uIFont.material = material;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_premultipliedAlphaShader(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.premultipliedAlphaShader);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_packedFontShader(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.packedFontShader);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_texture(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.texture);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_uvRect(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.uvRect);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_uvRect(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
Rect uvRect;
LuaObject.checkValueType<Rect>(l, 2, out uvRect);
uIFont.uvRect = uvRect;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_spriteName(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.spriteName);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_spriteName(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
string spriteName;
LuaObject.checkType(l, 2, out spriteName);
uIFont.spriteName = spriteName;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isValid(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.isValid);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_defaultSize(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.defaultSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_defaultSize(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
int defaultSize;
LuaObject.checkType(l, 2, out defaultSize);
uIFont.defaultSize = defaultSize;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_sprite(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.sprite);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_replacement(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.replacement);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_replacement(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
UIFont replacement;
LuaObject.checkType<UIFont>(l, 2, out replacement);
uIFont.replacement = replacement;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isDynamic(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.isDynamic);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_dynamicFont(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uIFont.dynamicFont);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_dynamicFont(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
Font dynamicFont;
LuaObject.checkType<Font>(l, 2, out dynamicFont);
uIFont.dynamicFont = dynamicFont;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_dynamicFontStyle(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, uIFont.dynamicFontStyle);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_dynamicFontStyle(IntPtr l)
{
int result;
try
{
UIFont uIFont = (UIFont)LuaObject.checkSelf(l);
FontStyle dynamicFontStyle;
LuaObject.checkEnum<FontStyle>(l, 2, out dynamicFontStyle);
uIFont.dynamicFontStyle = dynamicFontStyle;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UIFont");
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.MarkAsChanged));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.UpdateUVRect));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.MatchSymbol));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.AddSymbol));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.RemoveSymbol));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.RenameSymbol));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.UsesSprite));
LuaObject.addMember(l, new LuaCSFunction(Lua_UIFont.CheckIfRelated_s));
LuaObject.addMember(l, "bmFont", new LuaCSFunction(Lua_UIFont.get_bmFont), new LuaCSFunction(Lua_UIFont.set_bmFont), true);
LuaObject.addMember(l, "texWidth", new LuaCSFunction(Lua_UIFont.get_texWidth), new LuaCSFunction(Lua_UIFont.set_texWidth), true);
LuaObject.addMember(l, "texHeight", new LuaCSFunction(Lua_UIFont.get_texHeight), new LuaCSFunction(Lua_UIFont.set_texHeight), true);
LuaObject.addMember(l, "hasSymbols", new LuaCSFunction(Lua_UIFont.get_hasSymbols), null, true);
LuaObject.addMember(l, "symbols", new LuaCSFunction(Lua_UIFont.get_symbols), null, true);
LuaObject.addMember(l, "atlas", new LuaCSFunction(Lua_UIFont.get_atlas), new LuaCSFunction(Lua_UIFont.set_atlas), true);
LuaObject.addMember(l, "material", new LuaCSFunction(Lua_UIFont.get_material), new LuaCSFunction(Lua_UIFont.set_material), true);
LuaObject.addMember(l, "premultipliedAlphaShader", new LuaCSFunction(Lua_UIFont.get_premultipliedAlphaShader), null, true);
LuaObject.addMember(l, "packedFontShader", new LuaCSFunction(Lua_UIFont.get_packedFontShader), null, true);
LuaObject.addMember(l, "texture", new LuaCSFunction(Lua_UIFont.get_texture), null, true);
LuaObject.addMember(l, "uvRect", new LuaCSFunction(Lua_UIFont.get_uvRect), new LuaCSFunction(Lua_UIFont.set_uvRect), true);
LuaObject.addMember(l, "spriteName", new LuaCSFunction(Lua_UIFont.get_spriteName), new LuaCSFunction(Lua_UIFont.set_spriteName), true);
LuaObject.addMember(l, "isValid", new LuaCSFunction(Lua_UIFont.get_isValid), null, true);
LuaObject.addMember(l, "defaultSize", new LuaCSFunction(Lua_UIFont.get_defaultSize), new LuaCSFunction(Lua_UIFont.set_defaultSize), true);
LuaObject.addMember(l, "sprite", new LuaCSFunction(Lua_UIFont.get_sprite), null, true);
LuaObject.addMember(l, "replacement", new LuaCSFunction(Lua_UIFont.get_replacement), new LuaCSFunction(Lua_UIFont.set_replacement), true);
LuaObject.addMember(l, "isDynamic", new LuaCSFunction(Lua_UIFont.get_isDynamic), null, true);
LuaObject.addMember(l, "dynamicFont", new LuaCSFunction(Lua_UIFont.get_dynamicFont), new LuaCSFunction(Lua_UIFont.set_dynamicFont), true);
LuaObject.addMember(l, "dynamicFontStyle", new LuaCSFunction(Lua_UIFont.get_dynamicFontStyle), new LuaCSFunction(Lua_UIFont.set_dynamicFontStyle), true);
LuaObject.createTypeMetatable(l, null, typeof(UIFont), typeof(MonoBehaviour));
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UIDialogView : MonoBehaviour
{
public Text dialogueText;
private string currentDialogue;
public string CurrentDialogue
{
get
{
return currentDialogue;
}
set
{
currentDialogue = value;
dialogueText.text = currentDialogue;
}
}
}
|
using UnityEngine;
public class SpaceshipKey : ISpaceObjectKey<SpaceshipKey>
{
public Vector3 Position { get; }
public Quaternion Rotation { get; }
public float Destruction { get; }
public SpaceshipKey(Vector3 position,
Quaternion rotation,
float destruction)
{
Position = position;
Rotation = rotation;
Destruction = destruction;
}
public SpaceshipKey LerpWith(SpaceshipKey nextItem, float param)
{
Vector3 posRet = Vector3.Lerp(Position, nextItem.Position, param);
Quaternion rotRet = Quaternion.Lerp(Rotation, nextItem.Rotation, param);
float destruction = Mathf.Lerp(Destruction, nextItem.Destruction, param);
return new SpaceshipKey(posRet, rotRet, destruction);
}
}
|
using CommandPattern.Core.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace CommandPattern.Models.Comand
{
public class HelloCommand : ICommand
{
public string Execute(string[] args)
{
string result = $"Hello, {args[0]}";
return result;
}
}
}
|
using System.Xml.Serialization;
namespace MonoGame.Extended.Content.Pipeline.Tiled
{
public class TmxProperty
{
public TmxProperty()
{
}
public override string ToString()
{
return string.Format("{0}: {1}", Name, Value);
}
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "value")]
public string Value { get; set; }
}
} |
namespace Bridge.Renderers
{
public class ConsoleRenderer : IRenderer
{
public string Render(string key, string value)
{
return $"{key,10} : {value}";
}
}
}
|
using Contoso.Domain;
namespace Contoso.Bsl.Business.Responses
{
public class GetEntityResponse : BaseResponse
{
public EntityModelBase Entity { get; set; }
}
}
|
using System;
using Logs.Web.Areas.Administration.Models;
using NUnit.Framework;
namespace Logs.Web.Tests.ViewModelsTests.Administration.UserViewModelTests
{
[TestFixture]
public class PropertiesTests
{
[TestCase("username")]
[TestCase("batman")]
[TestCase("superman12")]
public void TestUsername_ShouldInitializeCorrectly(string username)
{
// Arrange
var model = new UserViewModel();
// Act
model.Username = username;
// Assert
Assert.AreEqual(username, model.Username);
}
[TestCase("username@abv.bg")]
[TestCase("batman@gmail.com")]
[TestCase("superman12@sudo.apt")]
public void TestEmail_ShouldInitializeCorrectly(string email)
{
// Arrange
var model = new UserViewModel();
// Act
model.Email = email;
// Assert
Assert.AreEqual(email, model.Email);
}
[TestCase("9717bdf4-1ce5-4b37-947f-3c5c910048b1")]
[TestCase("050df499-a40b-4064-9784-8ec0a2b3eba8")]
[TestCase("eddb2a8e-90e4-402f-8551-b954eccacaf4")]
public void TestUserId_ShouldInitializeCorrectly(string userId)
{
// Arrange
var model = new UserViewModel();
// Act
model.UserId = userId;
// Assert
Assert.AreEqual(userId, model.UserId);
}
[TestCase("someimageurl")]
public void TestProfileImageUrl_ShouldInitializeCorrectly(string profileImageUrl)
{
// Arrange
var model = new UserViewModel();
// Act
model.ProfileImageUrl = profileImageUrl;
// Assert
Assert.AreEqual(profileImageUrl, model.ProfileImageUrl);
}
[TestCase(true)]
[TestCase(false)]
public void TestIsAdministrator_ShouldInitializeCorrectly(bool isAdmin)
{
// Arrange
var model = new UserViewModel();
// Act
model.IsAdministrator = isAdmin;
// Assert
Assert.AreEqual(isAdmin, model.IsAdministrator);
}
[Test]
public void TestLockoutEndDate_ShouldInitializeCorrectly()
{
// Arrange
var model = new UserViewModel();
var date = new DateTime();
// Act
model.LockoutEndDateUtc = date;
// Assert
Assert.AreEqual(date, model.LockoutEndDateUtc);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AppDuoXF.Models
{
public class Achievement
{
public string Icon { get; set; }
public string Level { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Progress { get; set; }
public string Status { get; set; }
public bool IsActive { get; set; }
}
}
|
namespace StudentSystem.Services.Controllers
{
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Data;
using Models;
using StudentSystem.Models;
using System;
using System.Linq;
using System.Web.Http;
public class CoursesController : ApiController
{
private IStudentSystemData data;
public CoursesController(IStudentSystemData data)
{
this.data = data;
}
public IHttpActionResult Get()
{
var result = this.data.Courses.All().ProjectTo<CourseModel>();
return this.Ok(result);
}
public IHttpActionResult Get(Guid id)
{
var result = this.data.Courses.SearchFor(c => c.Id == id).ProjectTo<CourseModel>();
return this.Ok(result);
}
public IHttpActionResult Post([FromBody] CourseModel course)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState);
}
else
{
var result = Mapper.Map<Course>(course);
this.data.Courses.Add(result);
return this.Created(this.Url.ToString(), result);
}
}
public IHttpActionResult Put([FromBody] CourseModel course)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState);
}
else
{
var result = this.data.Courses
.SearchFor(c => c.Name == course.Name).FirstOrDefault();
if (result == null)
{
return this.NotFound();
}
else
{
result.Description = course.Description;
this.data.Courses.Update(result);
return this.Ok(result);
}
}
}
public IHttpActionResult Delete(Guid id)
{
var course = this.data.Courses.SearchFor(c => c.Id == id).FirstOrDefault();
if (course == null)
{
return this.NotFound();
}
else
{
this.data.Courses.Delete(course);
return this.Ok(course);
}
}
}
}
|
namespace GameCloud.Core
{
public class Client
{
}
} |
using Prism;
using Prism.Ioc;
using System;
namespace AppBase.Droid
{
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
} |
using Microsoft.EntityFrameworkCore;
using SGDE.Domain.Entities;
using SGDE.Domain.Helpers;
using SGDE.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SGDE.DataEFCoreMySQL.Repositories
{
public class DetailEmbargoRepository : IDetailEmbargoRepository, IDisposable
{
private readonly EFContextMySQL _context;
public DetailEmbargoRepository(EFContextMySQL context)
{
_context = context;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
}
private bool DetailEmbargoExists(int id)
{
return GetById(id) != null;
}
public QueryResult<DetailEmbargo> GetAll(int skip = 0, int take = 0, int embargoId = 0)
{
List<DetailEmbargo> data = new List<DetailEmbargo>();
if (embargoId == 0)
{
data = _context.DetailEmbargo
.Include(x => x.Embargo)
.OrderByDescending(x => x.DatePay)
.ToList();
}
if (embargoId != 0)
{
data = _context.DetailEmbargo
.Include(x => x.Embargo)
.Where(x => x.EmbargoId == embargoId)
.OrderByDescending(x => x.DatePay)
.ToList();
}
var count = data.Count;
return (skip != 0 || take != 0)
? new QueryResult<DetailEmbargo>
{
Data = data.Skip(skip).Take(take).ToList(),
Count = count
}
: new QueryResult<DetailEmbargo>
{
Data = data.Skip(0).Take(count).ToList(),
Count = count
};
}
public DetailEmbargo GetById(int id)
{
return _context.DetailEmbargo
.Include(x => x.Embargo)
.FirstOrDefault(x => x.Id == id);
}
public DetailEmbargo Add(DetailEmbargo newDetailEmbargo, bool isPaid)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_context.DetailEmbargo.Add(newDetailEmbargo);
if (isPaid)
{
var embargo = _context.Embargo.Find(newDetailEmbargo.EmbargoId);
embargo.Paid = isPaid;
_context.Embargo.Update(embargo);
}
_context.SaveChanges();
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
return newDetailEmbargo;
}
public bool Update(DetailEmbargo detailEmbargo, bool isPaid)
{
if (!DetailEmbargoExists(detailEmbargo.Id))
return false;
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_context.DetailEmbargo.Update(detailEmbargo);
var embargo = _context.Embargo.Find(detailEmbargo.EmbargoId);
embargo.Paid = isPaid;
_context.Embargo.Update(embargo);
_context.SaveChanges();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
public bool Delete(int id)
{
if (!DetailEmbargoExists(id))
return false;
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var toRemove = _context.DetailEmbargo.Find(id);
_context.DetailEmbargo.Remove(toRemove);
var embargo = _context.Embargo.Find(toRemove.EmbargoId);
embargo.Paid = false;
_context.Embargo.Update(embargo);
_context.SaveChanges();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
}
}
|
using System.Collections.Immutable;
using System.Diagnostics;
using Meziantou.Analyzer.Configurations;
using Meziantou.Analyzer.Internals;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Meziantou.Analyzer.Rules;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class DoNotUseImplicitCultureSensitiveToStringAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_stringConcatRule = new(
RuleIdentifiers.DoNotUseImplicitCultureSensitiveToString,
title: "Do not use implicit culture-sensitive ToString",
messageFormat: "Do not use implicit culture-sensitive ToString",
RuleCategories.Design,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.DoNotUseImplicitCultureSensitiveToString));
private static readonly DiagnosticDescriptor s_stringInterpolationRule = new(
RuleIdentifiers.DoNotUseImplicitCultureSensitiveToStringInterpolation,
title: "Do not use implicit culture-sensitive ToString in interpolated strings",
messageFormat: "Do not use implicit culture-sensitive ToString in interpolated strings",
RuleCategories.Design,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.DoNotUseImplicitCultureSensitiveToStringInterpolation));
private static readonly DiagnosticDescriptor s_objectToStringRule = new(
RuleIdentifiers.DoNotUseCultureSensitiveObjectToString,
title: "Do not use culture-sensitive object.ToString",
messageFormat: "Do not use culture-sensitive object.ToString",
RuleCategories.Design,
DiagnosticSeverity.Info,
isEnabledByDefault: false,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.DoNotUseCultureSensitiveObjectToString));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_stringConcatRule, s_stringInterpolationRule, s_objectToStringRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(context =>
{
var analyzerContext = new AnalyzerContext(context.Compilation);
context.RegisterOperationAction(analyzerContext.AnalyzeBinaryOperation, OperationKind.Binary);
context.RegisterOperationAction(analyzerContext.AnalyzeInterpolatedString, OperationKind.InterpolatedString);
context.RegisterOperationAction(AnalyzerContext.AnalyzeInvocation, OperationKind.Invocation);
});
}
private sealed class AnalyzerContext
{
private readonly CultureSensitiveFormattingContext _cultureSensitiveContext;
public AnalyzerContext(Compilation compilation)
{
_cultureSensitiveContext = new CultureSensitiveFormattingContext(compilation);
}
public static void AnalyzeInvocation(OperationAnalysisContext context)
{
var operation = (IInvocationOperation)context.Operation;
if (IsExcludedMethod(context, s_objectToStringRule, operation))
return;
if (operation.TargetMethod.Name == "ToString" && operation.TargetMethod.ContainingType.IsObject() && operation.TargetMethod.Parameters.Length == 0)
{
if (operation.Instance != null && operation.Instance.Type.IsObject())
{
context.ReportDiagnostic(s_objectToStringRule, operation);
}
}
}
public void AnalyzeBinaryOperation(OperationAnalysisContext context)
{
var operation = (IBinaryOperation)context.Operation;
if (operation.OperatorKind != BinaryOperatorKind.Add)
return;
if (!operation.Type.IsString())
return;
if (operation.ConstantValue.HasValue)
return;
if (IsExcludedMethod(context, s_stringConcatRule, operation))
return;
if (!IsNonCultureSensitiveOperand(context, s_stringConcatRule, operation.LeftOperand))
{
context.ReportDiagnostic(s_stringConcatRule, operation.LeftOperand);
}
if (!IsNonCultureSensitiveOperand(context, s_stringConcatRule, operation.RightOperand))
{
context.ReportDiagnostic(s_stringConcatRule, operation.RightOperand);
}
}
public void AnalyzeInterpolatedString(OperationAnalysisContext context)
{
// Check if parent is InterpolatedString.Invariant($"") or conversion to string?
var operation = (IInterpolatedStringOperation)context.Operation;
if (operation.ConstantValue.HasValue)
return;
if (IsExcludedMethod(context, s_stringInterpolationRule, operation))
return;
var options = MustUnwrapNullableTypes(context, s_stringInterpolationRule, operation) ? CultureSensitiveOptions.UnwrapNullableOfT : CultureSensitiveOptions.None;
var parent = operation.Parent;
if (parent is IConversionOperation conversionOperation)
{
// `FormattableString _ = $""` is valid whereas `string _ = $""` may not be
if (conversionOperation.Type.IsEqualTo(context.Compilation.GetBestTypeByMetadataName("System.FormattableString")))
return;
}
foreach (var part in operation.Parts.OfType<IInterpolationOperation>())
{
var expression = part.Expression;
var type = expression.Type;
if (expression == null || type == null)
continue;
if (_cultureSensitiveContext.IsCultureSensitiveOperation(part, options | CultureSensitiveOptions.UseInvocationReturnType))
{
context.ReportDiagnostic(s_stringInterpolationRule, part);
}
}
}
private static bool IsExcludedMethod(OperationAnalysisContext context, DiagnosticDescriptor descriptor, IOperation operation)
{
// ToString show culture-sensitive data by default
if (operation?.GetContainingMethod(context.CancellationToken)?.Name == "ToString")
{
return context.Options.GetConfigurationValue(operation.Syntax.SyntaxTree, descriptor.Id + ".exclude_tostring_methods", defaultValue: true);
}
return false;
}
private bool IsNonCultureSensitiveOperand(OperationAnalysisContext context, DiagnosticDescriptor rule, IOperation operand)
{
// Implicit conversion from a type number
if (operand is null)
return true;
if (operand is IConversionOperation conversion && conversion.IsImplicit && conversion.Type.IsObject() && conversion.Operand.Type != null)
{
var value = conversion.Operand;
var options = MustUnwrapNullableTypes(context, rule, operand) ? CultureSensitiveOptions.UnwrapNullableOfT : CultureSensitiveOptions.None;
if (_cultureSensitiveContext.IsCultureSensitiveOperation(value, options | CultureSensitiveOptions.UseInvocationReturnType))
return false;
}
return true;
}
private static bool MustUnwrapNullableTypes(OperationAnalysisContext context, DiagnosticDescriptor rule, IOperation operation)
{
// Avoid an allocation when creating the key
if (rule == s_stringConcatRule)
{
Debug.Assert(rule.Id == RuleIdentifiers.DoNotUseImplicitCultureSensitiveToString);
return context.Options.GetConfigurationValue(operation.Syntax.SyntaxTree, RuleIdentifiers.DoNotUseImplicitCultureSensitiveToString + ".consider_nullable_types", defaultValue: true);
}
else if (rule == s_stringInterpolationRule)
{
Debug.Assert(rule.Id == RuleIdentifiers.DoNotUseImplicitCultureSensitiveToStringInterpolation);
return context.Options.GetConfigurationValue(operation.Syntax.SyntaxTree, RuleIdentifiers.DoNotUseImplicitCultureSensitiveToStringInterpolation + ".consider_nullable_types", defaultValue: true);
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Data.OleDb;
using HSoft.SQL;
using HSoft.ClientManager.Web;
using SisoDb.Sql2012;
using SisoDb.Configurations;
using CTCT;
using CTCT.Components;
using CTCT.Components.Contacts;
using CTCT.Components.AccountService;
using CTCT.Components.EmailCampaigns;
using CTCT.Exceptions;
using Obout.Interface;
public partial class Pages_CC_Contact : System.Web.UI.Page
{
private static String ssql = String.Empty;
public ConstantContact _constantContact = null;
private string _apiKey = string.Empty;
private string _accessToken = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Tools.devlogincheat();
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
if (Session["ghirarchy"] == null) { Session["ghirarchy"] = String.Format("{0},", Session["guser"]); }
LastUpdate.Text = _sql.ExecuteScalar("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Contact' AND isdeleted = 0").ToString();
CountContacts.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status'").ToString();
CountActive.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status' AND LOWER(Value) ='active'").ToString();
CountLeads.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE isdeleted = 0 ").ToString();
Linked.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE ConstantContactID >0 AND isdeleted = 0 ").ToString();
_sql.Close();
}
}
public int UpdateContacts(DateTime lastupdate)
{
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString.CreateSql2012Db();
// SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings["ClientManagerA"].ConnectionString.CreateSql2012Db();
// lastupdate = DateTime.Parse("1980-01-01");
ConstantContact _constantContact = null;
string _apiKey = string.Empty;
string _accessToken = string.Empty;
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
int iCount = 0;
Pagination _page = null;
DateTime _last = lastupdate;
while (1 == 1)
{
ResultSet<CTCT.Components.Contacts.Contact> _contacts = null;
try
{
_contacts = _constantContact.GetContacts(lastupdate, _page);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetContacts {0}",ex.Message));
throw ex;
}
if (_contacts == null)
{
Exception ex = new Exception("No results returned, possible connection failure.");
throw ex;
}
using (var session = _siso.BeginSession())
{
foreach (CTCT.Components.Contacts.Contact _contact in _contacts.Results)
{
if (session.Query<CTCT.Components.Contacts.Contact>().Count(o => o.Id == _contact.Id) != 0)
{
session.Update(_contact);
}
else
{
session.Insert(_contact);
_last = DateTime.Parse(_contact.DateModified);
}
}
}
if (_last != lastupdate) { Tools.SetDate(_last, "Contact"); }
iCount = iCount + _contacts.Results.Count;
if (_contacts.Meta.Pagination.Next == null) { break; }
if (_page == null) { _page = new Pagination(); }
_page.Next = _contacts.Meta.Pagination.Next;
}
return iCount;
}
public Boolean upLoadToCC()
{
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString.CreateSql2012Db();
HSoft.SQL.SqlServer _sql3 = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
_apiKey = ConfigurationManager.AppSettings["APIKey"];
_accessToken = ConfigurationManager.AppSettings["AccessToken"];
if (_accessToken.Length != new Guid().ToString().Length)
{
byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
_accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
}
_constantContact = new ConstantContact(_apiKey, _accessToken);
using (var session = _siso.BeginSession())
{
IList<ContactList> _rscl = null;
try
{
_rscl = _constantContact.GetLists(null);
}
catch (Exception ex)
{
Exception ex2 = new Exception(String.Format("GetContacts {0}", ex.Message));
throw ex;
}
ContactList _cla = _rscl.FirstOrDefault(o => o.Name == "Added by Client Manager");
ContactList _cls = _rscl.FirstOrDefault(o => o.Name == "Sold Course");
ContactList _clq = _rscl.FirstOrDefault(o => o.Name == "Questionable Contact");
DataTable dt = _sql3.GetTable("SELECT * FROM Lead_Flat WHERE ConstantContactID IS NULL AND isdeleted = 0 ORDER BY Customer");
foreach (DataRow dr in dt.Rows)
{
if (Tools.IsValidEmail(dr["EMail"].ToString()))
{
String ssql = String.Format("SELECT a.Value " +
" FROM ContactStrings a, ContactStrings b " +
" WHERE a.MemberPath = 'Id' " +
" AND a.StructureId = b.StructureId " +
" AND b.MemberPath = 'EmailAddresses.EmailAddr' " +
" AND b.Value = '{0}' ", dr["EMail"].ToString().ToLower());
String Id = _sql3.ExecuteScalar(ssql).ToString();
var result = session.Query<CTCT.Components.Contacts.Contact>()
.Where(o => o.Id == Id);
if (result.FirstOrDefault() != null)
{
continue;
}
CTCT.Components.Contacts.Contact _ct = new CTCT.Components.Contacts.Contact();
CTCT.Components.Contacts.EmailAddress _em = new EmailAddress();
_em.EmailAddr = dr["EMail"].ToString();
_em.ConfirmStatus = "NO_CONFIRMATION_REQUIRED";
_em.OptInSource = "ACTION_BY_OWNER";
_em.Status = "ACTIVE";
_ct.EmailAddresses.Add(_em);
_ct.Lists.Add(_cla);
if (dr["PriorityId"].ToString().ToLower() == "F3DC2498-6F4F-449E-813C-EFDA32A9D24A".ToLower())
{
_ct.Lists.Add(_cls);
}
if ((dr["PriorityId"].ToString().ToLower() == "7c89308b-6912-4c50-b55d-2a5ae1b05e19".ToLower()) ||
(dr["PriorityId"].ToString().ToLower() == "3f9bcf7c-fb91-4b57-b2bf-cbe462e07cf2".ToLower()) ||
(dr["PriorityId"].ToString().ToLower() == "9e256177-a401-4282-8959-92e5f1ef4268".ToLower()) ||
(dr["PriorityId"].ToString().ToLower() == "9491f7a8-086d-4293-87f1-7a897208e325".ToLower()))
{
_ct.Lists.Add(_clq);
}
_ct.HomePhone = dr["Phone"].ToString();
_ct.FirstName = dr["Name"].ToString();
_ct.Source = "Client Manager";
_ct.Status = "ACTIVE";
CTCT.Components.Contacts.Contact _ctres = new CTCT.Components.Contacts.Contact();
try
{
_ctres = _constantContact.AddContact(_ct, false);
session.Insert(_ctres);
ssql = String.Format("INSERT INTO _auditt([Table], [Field], [Key], OldValue, NewValue, createdby) " +
"VALUES ('{0}','{1}','{4}','{2}','{3}','{4}') ", "ConstantContact", "ADD", dr["Customer"], _ctres.Id, "D0F06FCC-B87E-4F33-A3D3-D64354863F39");
_sql3.Execute(ssql);
ssql = String.Format("UPDATE t " +
" SET t.ConstantContactID = {0} " +
" FROM Lead_Flat t " +
" WHERE Customer = {1}", _ctres.Id, dr["Customer"]);
_sql3.Execute(ssql);
}
catch (CTCT.Exceptions.CtctException ex)
{
ssql = String.Format("INSERT INTO _auditt([Table], [Field], [Key], OldValue, NewValue, createdby) " +
"VALUES ('{0}','{1}','{4}','{2}','{3}','{4}') ", "ConstantContact", "ERROR", dr["Customer"], ex.InnerException, "D0F06FCC-B87E-4F33-A3D3-D64354863F39");
_sql3.Execute(ssql);
}
}
else
{
ssql = String.Format("UPDATE t " +
" SET t.ConstantContactID = {0} " +
" FROM Lead_Flat t " +
" WHERE Customer = {1}", -1, dr["Customer"]);
_sql3.Execute(ssql);
}
}
}
_sql3.Close();
return true;
}
protected void Btn_Command(object sender, CommandEventArgs e)
{
CC_Command(e.CommandName);
}
protected void CC_Command(string scmd)
{
switch (scmd)
{
case "ResetLoadDate" :
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
DateTime _lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Contact' AND isdeleted = 0").ToString());
Tools.SetDate(DateTime.Parse("1900-01-01"),"Contact");
_sql.Close();
}
break;
case "ResetDatabase":
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString.CreateSql2012Db();
_siso.CreateIfNotExists();
// attach MSSQLDB
using (var session = _siso.BeginSession())
{
session.DeleteByQuery<CTCT.Components.Contacts.Contact>(o => o.Id != "");
}
_sql.Execute("UPDATE t SET ConstantContactID = null FROM Lead_Flat t");
_sql.Close();
Tools.SetDate(DateTime.Parse("1900-01-01"), "Contact");
}
break;
case "UpdateDatabase":
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
DateTime _lastmod = DateTime.Parse(_sql.ExecuteScalar("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Contact' AND isdeleted = 0").ToString());
UpdateContacts(_lastmod);
_sql.Close();
}
break;
case "RelinkDatabases":
{
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
_sql.Execute("UPDATE t SET ConstantContactID = null FROM Lead_Flat t");
ssql = String.Format("UPDATE t " +
" SET t.ConstantContactID = cs2.Value " +
" FROM Lead_Flat t, ContactStrings cs, ContactStrings cs2 " +
" WHERE LOWER(t.EMail) = LOWER(cs.Value) " +
" AND cs.StructureId = cs2.StructureId " +
" AND cs2.MemberPath = 'Id' " +
" AND cs.MemberPath = 'EmailAddresses.EmailAddr' ", "");
_sql.Execute(ssql);
_sql.Close();
}
break;
case "UpdateConstantContact":
{
CC_Command("UpdateDatabase");
CC_Command("RelinkDatabases");
upLoadToCC();
CC_Command("UpdateDatabase");
}
break;
case "Refresh" :
{
}
break;
}
HSoft.SQL.SqlServer _sql2 = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
LastUpdate.Text = _sql2.ExecuteScalar("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Contact' AND isdeleted = 0").ToString();
CountContacts.Text = _sql2.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status'").ToString();
CountActive.Text = _sql2.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status' AND LOWER(Value) ='active'").ToString();
CountLeads.Text = _sql2.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE isdeleted = 0 ").ToString();
Linked.Text =_sql2.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE ConstantContactID >0 AND isdeleted = 0 ").ToString();
_sql2.Close();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MediaManager.API.Models
{
/// <summary>
/// Class to create a link
/// </summary>
public class LinkDTO
{
/// <summary>
/// Link
/// </summary>
public string Href { get; set; }
/// <summary>
/// Relation of the entity to parent entity
/// </summary>
public string Rel { get; set; }
/// <summary>
/// Pst method it supports
/// </summary>
public string Method { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="href">link</param>
/// <param name="rel">relation</param>
/// <param name="method">HTTP method</param>
public LinkDTO(string href, string rel, string method)
{
this.Href = href;
this.Rel = rel;
this.Method = method;
}
}
}
|
/*
* Created By: Evan Combs
* Created On: 8/19/2015
* Modified On: 8/19/2015
* File Name: DrawerMenuItem.cs
* Full Namespace: DeadDodo.UI.Elements.DrawerMenuItem
* Inherites:
* Purpose:
* Fields:
* Delegates:
* Methods:
* ToDo:
* Proposed Changes:
*/
using DeadDodo;
namespace DeadDodo.UI.Navigation
{
public class DrawerMenuItem : DDObject
{
public DrawerMenuItem()
{
}
}
}
|
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.Logical
{
public class BitOpCode : OpCode
{
public override string Name => "BIT";
public BitOpCode(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
public override int Execute()
{
Fetch();
var value = (ushort)(cpu.Accumulator & fetched);
ApplyFlag(CpuFlag.Zero, value.ApplyLowMask() == 0x00);
ApplyFlag(CpuFlag.Negative, (fetched & (1 << 7)) > 0);
ApplyFlag(CpuFlag.Overflow, (fetched & (1 << 6)) > 0);
return 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using yamoc.server;
namespace yamoc
{
class Program
{
static Logging log = Logging.getLogger();
static void Main()
{
var version = "1.0.0";
log.info("yamoc version " + version);
var args = Environment.GetCommandLineArgs();
var yamlPath = args.Length > 1 ? args[1] : "setting.yaml";
YamlSettings? settings = YamlSettingsUtil.loadYaml(yamlPath);
if (!settings.HasValue)
{
return;
}
log.info("");
log.info(" using `" + yamlPath + "`");
new HttpServer(settings.Value).Run();
}
}
}
|
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace UpdateExecutableCommon.Utilities
{
public class ZipUtility
{
/// <summary>
/// Create a zip file from the specified directory path and return it as a byte array
/// </summary>
/// <param name="directoryPathToZip">Directory to zip up</param>
public static byte[] CreateZipFileFromDirectory(string directoryPathToZip)
{
if (!Directory.Exists(directoryPathToZip))
throw new Exception("Directory path to zip up was not found.");
var zipDirectory = new ZipFile();
zipDirectory.AddDirectory(directoryPathToZip);
byte[] zip = null;
using (var stream = new MemoryStream())
{
zipDirectory.Save(stream);
zip = stream.ToArray();
}
return zip;
}
/// <summary>
/// Create a zip file from the specified directory path and save it
/// </summary>
/// <param name="directoryPathToZip">Directory to zip up</param>
/// <param name="destinationFilePath">File path to save the resulting zip file</param>
public static void CreateZipFileFromDirectory(string directoryPathToZip, string destinationFilePath)
{
if (!Directory.Exists(directoryPathToZip))
throw new Exception("Directory path to zip (\"" + directoryPathToZip + "\") was not found.");
var zipDirectory = new ZipFile();
zipDirectory.AddDirectory(directoryPathToZip);
zipDirectory.Save(destinationFilePath);
}
/// <summary>
/// Extract the specified zip file to the destination directory
/// </summary>
/// <param name="zipFilePath">Zip file path</param>
/// <param name="destinationDirectory">Destination directory</param>
public static void ExtractZipFile(string zipFilePath, string destinationDirectory)
{
using (ZipFile zipFile = ZipFile.Read(zipFilePath))
{
foreach (ZipEntry entry in zipFile)
{
entry.Extract(destinationDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
namespace TFS2TestRailXML
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
private TfsTeamProjectCollection _tfs;
ITestManagementTeamProject _testProject;
ITestPlanCollection _testPlanCollection;
private ITestSuiteBase _suite;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
void BtnConnect_Click(object sender, RoutedEventArgs e)
{
_tfs = null;
TbTfs.Text = null;
var tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
tpp.ShowDialog();
if (tpp.SelectedTeamProjectCollection == null) return;
_tfs = tpp.SelectedTeamProjectCollection;
var testService = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
_testProject = testService.GetTeamProject(tpp.SelectedProjects[0].Name);
TbTfs.Text = _tfs.Name + "\\" + _testProject;
_testPlanCollection = _testProject.TestPlans.Query("Select * from TestPlan");
ProjectSelected_GetTestPlans();
btnGenerateXMLFile.IsEnabled = false;
}
private void BtnOpenFileDialog_Click(object sender, RoutedEventArgs e)
{
var saveFileDialog1 = new System.Windows.Forms.SaveFileDialog
{
InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString(),
Filter = Properties.Resources.MainWindow_BtnOpenFileDialog_Click,
FilterIndex = 1
};
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TbFileName.Text = saveFileDialog1.FileName;
}
else
{
MessageBox.Show("Please choose a valid filename");
}
}
private void ProjectSelected_GetTestPlans()
{
CbTestPlans.ItemsSource = _testPlanCollection;
CbTestPlans.DisplayMemberPath = NameProperty.ToString();
}
private void CbTestPlans_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TvSuites.Items.Clear();
AddTestSuites(CbTestPlans.SelectedItem as ITestPlan);
}
private void TvSuites_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
btnGenerateXMLFile.IsEnabled = true;
}
void AddTestSuites(ITestPlan selectedTestPlan)
// Adds the selected Test Plan to the tree view as the root
// then gets all the sub suites
{
if (selectedTestPlan == null) return;
var root = new TreeViewItem {Header = selectedTestPlan.RootSuite.Title};
TvSuites.Items.Add(root);
root.Tag = selectedTestPlan.RootSuite.Id;
AddSubSuites(selectedTestPlan.RootSuite.SubSuites, root);
}
static void AddSubSuites(IEnumerable<ITestSuiteBase> subSuiteEntries, ItemsControl treeNode)
// Recursively adds all the sub suites to the tree view
{
foreach (var suite in subSuiteEntries)
{
var suiteTree = new TreeViewItem {Header = suite.Title};
treeNode.Items.Add(suiteTree);
suiteTree.Tag = suite.Id;
if (suite.TestSuiteType == TestSuiteType.StaticTestSuite)
{
var suite1 = suite as IStaticTestSuite;
if (suite1.SubSuites.Count > 0)
{
AddSubSuites(suite1.SubSuites, suiteTree);
}
}
}
}
void BtnGenerateXMLFile_Click(object sender, RoutedEventArgs e)
{
if (TbFileName.Text == null || TbFileName.Text.Length.Equals(0))
{
MessageBox.Show("Please Enter a valid file path");
}
else
{
if (TvSuites.SelectedValue != null)
{
var tvItem = TvSuites.SelectedItem as TreeViewItem;
_suite = _testProject.TestSuites.Find(Convert.ToInt32(tvItem.Tag.ToString()));
if (_suite != null)
WriteTestPlanToXml(_suite);
}
else
{
MessageBox.Show("Please select a test suite");
}
}
}
void WriteTestPlanToXml(ITestSuiteBase rootSuite)
{
try
{
var xmlDoc = new XmlDocument();
if (rootSuite.TestSuiteType == TestSuiteType.StaticTestSuite)
{
WriteRootSuite(rootSuite as IStaticTestSuite, xmlDoc);
}
if (rootSuite.TestSuiteType == TestSuiteType.DynamicTestSuite)
{
WriteRootSuite(rootSuite as IDynamicTestSuite, xmlDoc);
}
if (rootSuite.TestSuiteType == TestSuiteType.RequirementTestSuite)
{
WriteRootSuite(rootSuite as IRequirementTestSuite, xmlDoc);
}
xmlDoc.Save(TbFileName.Text);
MessageBox.Show("File has been saved at " + TbFileName.Text);
}
catch (Exception theException)
{
var errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
void WriteRootSuite(IStaticTestSuite testSuite, XmlDocument xmlDoc)
{
XmlNode rootNode = xmlDoc.CreateElement("suite");
xmlDoc.AppendChild(rootNode);
XmlNode idNode = xmlDoc.CreateElement("id");
rootNode.AppendChild(idNode);
XmlNode rootnameNode = xmlDoc.CreateElement("name");
rootnameNode.InnerText = testSuite.Plan.Name;
rootNode.AppendChild(rootnameNode);
XmlNode rootdescNode = xmlDoc.CreateElement("description");
rootdescNode.InnerText = testSuite.Plan.Description;
rootNode.AppendChild(rootdescNode);
XmlNode sectionsNode = xmlDoc.CreateElement("sections");
rootNode.AppendChild(sectionsNode);
if (testSuite.TestSuiteType == TestSuiteType.StaticTestSuite)
{
if (testSuite.Entries.Any(suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.TestCase))
{
XmlNode sectionNode = xmlDoc.CreateElement("section");
XmlNode nameNode = xmlDoc.CreateElement("name");
sectionNode.AppendChild(nameNode);
nameNode.InnerText = "All Test Cases";
XmlNode descNode = xmlDoc.CreateElement("description");
sectionNode.AppendChild(descNode);
XmlNode casesNode = xmlDoc.CreateElement("cases");
sectionNode.AppendChild(casesNode);
foreach (var suiteEntry in testSuite.Entries.Where(suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.TestCase))
{
var caseNode = WriteTestCase(suiteEntry.TestCase, xmlDoc);
casesNode.AppendChild(caseNode);
}
sectionsNode.AppendChild(sectionNode);
}
foreach (var suiteEntry in testSuite.Entries.Where(suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.StaticTestSuite ||
suiteEntry.EntryType == TestSuiteEntryType.RequirementTestSuite ||
suiteEntry.EntryType == TestSuiteEntryType.DynamicTestSuite))
{
if (suiteEntry.EntryType == TestSuiteEntryType.StaticTestSuite)
{
var suite = suiteEntry.TestSuite as IStaticTestSuite;
var subSection = GetTestSuites(suite, xmlDoc);
sectionsNode.AppendChild(subSection);
}
if (suiteEntry.EntryType == TestSuiteEntryType.RequirementTestSuite)
{
var suite = suiteEntry.TestSuite as IRequirementTestSuite;
GetTestCases(suite, xmlDoc, sectionsNode);
}
if (suiteEntry.EntryType == TestSuiteEntryType.DynamicTestSuite)
{
var suite = suiteEntry.TestSuite as IDynamicTestSuite;
GetTestCases(suite, xmlDoc, sectionsNode);
}
}
}
}
void WriteRootSuite(IDynamicTestSuite testSuite, XmlDocument xmlDoc)
{
XmlNode rootNode = xmlDoc.CreateElement("suite");
xmlDoc.AppendChild(rootNode);
XmlNode idNode = xmlDoc.CreateElement("id");
rootNode.AppendChild(idNode);
XmlNode rootnameNode = xmlDoc.CreateElement("name");
rootnameNode.InnerText = testSuite.Plan.Name;
rootNode.AppendChild(rootnameNode);
XmlNode rootdescNode = xmlDoc.CreateElement("description");
rootdescNode.InnerText = testSuite.Plan.Description;
rootNode.AppendChild(rootdescNode);
XmlNode sectionsNode = xmlDoc.CreateElement("sections");
rootNode.AppendChild(sectionsNode);
GetTestCases(testSuite, xmlDoc, sectionsNode);
}
void WriteRootSuite(IRequirementTestSuite testSuite, XmlDocument xmlDoc)
{
XmlNode rootNode = xmlDoc.CreateElement("suite");
xmlDoc.AppendChild(rootNode);
XmlNode idNode = xmlDoc.CreateElement("id");
rootNode.AppendChild(idNode);
XmlNode rootnameNode = xmlDoc.CreateElement("name");
rootnameNode.InnerText = testSuite.Plan.Name;
rootNode.AppendChild(rootnameNode);
XmlNode rootdescNode = xmlDoc.CreateElement("description");
rootdescNode.InnerText = testSuite.Plan.Description;
rootNode.AppendChild(rootdescNode);
XmlNode sectionsNode = xmlDoc.CreateElement("sections");
rootNode.AppendChild(sectionsNode);
GetTestCases(testSuite, xmlDoc, sectionsNode);
}
private XmlNode GetTestSuites(IStaticTestSuite staticTestSuite, XmlDocument xmlDoc)
{
XmlNode sectionNode = xmlDoc.CreateElement("section");
XmlNode nameNode = xmlDoc.CreateElement("name");
sectionNode.AppendChild(nameNode);
nameNode.InnerText = staticTestSuite.Title;
XmlNode descNode = xmlDoc.CreateElement("description");
sectionNode.AppendChild(descNode);
if (staticTestSuite.Entries.Any(suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.TestCase))
{
XmlNode casesNode = xmlDoc.CreateElement("cases");
sectionNode.AppendChild(casesNode);
foreach (
var suiteEntry in
staticTestSuite.Entries.Where(suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.TestCase)
)
{
var caseNode = WriteTestCase(suiteEntry.TestCase, xmlDoc);
casesNode.AppendChild(caseNode);
}
}
if (staticTestSuite.SubSuites.Count > 0)
{
XmlNode sectionsNode = xmlDoc.CreateElement("sections");
foreach (
var suiteEntry in
staticTestSuite.Entries.Where(
suiteEntry => suiteEntry.EntryType == TestSuiteEntryType.StaticTestSuite ||
suiteEntry.EntryType == TestSuiteEntryType.RequirementTestSuite ||
suiteEntry.EntryType == TestSuiteEntryType.DynamicTestSuite))
{
if (suiteEntry.EntryType == TestSuiteEntryType.StaticTestSuite)
{
var suite = suiteEntry.TestSuite as IStaticTestSuite;
var subSection = GetTestSuites(suite, xmlDoc);
sectionsNode.AppendChild(subSection);
}
if (suiteEntry.EntryType == TestSuiteEntryType.RequirementTestSuite)
{
var suite = suiteEntry.TestSuite as IRequirementTestSuite;
GetTestCases(suite, xmlDoc, sectionsNode);
}
if (suiteEntry.EntryType == TestSuiteEntryType.DynamicTestSuite)
{
var suite = suiteEntry.TestSuite as IDynamicTestSuite;
GetTestCases(suite, xmlDoc, sectionsNode);
}
}
sectionNode.AppendChild(sectionsNode);
}
return sectionNode;
}
private void GetTestCases(IRequirementTestSuite requirementTestSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
{
var casesNode = WriteSuite(requirementTestSuite, xmlDoc, node); //WriteSuite sectionsNode has to be "sections"
foreach (var testCase in requirementTestSuite.AllTestCases)
{
var caseNode = WriteTestCase(testCase, xmlDoc);
casesNode.AppendChild(caseNode);
}
}
private void GetTestCases(IDynamicTestSuite dynamicTestSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
{
var casesNode = WriteSuite(dynamicTestSuite, xmlDoc, node);
foreach (var testCase in dynamicTestSuite.AllTestCases)
{
var caseNode = WriteTestCase(testCase, xmlDoc);
casesNode.AppendChild(caseNode);
}
}
XmlNode WriteSuite(IRequirementTestSuite testSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
{
XmlNode sectionNode = xmlDoc.CreateElement("section");
node.AppendChild(sectionNode);
XmlNode nameNode = xmlDoc.CreateElement("name");
nameNode.InnerText = testSuite.Title;
sectionNode.AppendChild(nameNode);
XmlNode descNode = xmlDoc.CreateElement("description");
sectionNode.AppendChild(descNode);
XmlNode casesNode = xmlDoc.CreateElement("cases");
sectionNode.AppendChild(casesNode);
return casesNode;
}
XmlNode WriteSuite(IDynamicTestSuite testSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
{
XmlNode sectionNode = xmlDoc.CreateElement("section");
node.AppendChild(sectionNode);
XmlNode nameNode = xmlDoc.CreateElement("name");
nameNode.InnerText = testSuite.Title;
sectionNode.AppendChild(nameNode);
XmlNode descNode = xmlDoc.CreateElement("description");
sectionNode.AppendChild(descNode);
XmlNode casesNode = xmlDoc.CreateElement("cases");
sectionNode.AppendChild(casesNode);
return casesNode;
}
XmlNode WriteTestCase(ITestCase testCase, XmlDocument xmlDoc) //sectionsNode has to be "cases"
{
XmlNode caseNode = xmlDoc.CreateElement("case");
XmlNode idNode = xmlDoc.CreateElement("id");
caseNode.AppendChild(idNode);
XmlNode titleNode = xmlDoc.CreateElement("title");
titleNode.InnerText = testCase.Title;
caseNode.AppendChild(titleNode);
XmlNode typeNode = xmlDoc.CreateElement("type");
caseNode.AppendChild(typeNode);
XmlNode priorityNode = xmlDoc.CreateElement("priority");
caseNode.AppendChild(priorityNode);
XmlNode estimateNode = xmlDoc.CreateElement("estimate");
caseNode.AppendChild(estimateNode);
XmlNode milestoneNode = xmlDoc.CreateElement("milestone");
caseNode.AppendChild(milestoneNode);
XmlNode referencesNode = xmlDoc.CreateElement("references");
int i;
var j = 0;
for (i = 0; i <= testCase.WorkItem.WorkItemLinks.Count-1; i++)
{
var workItemStore = new WorkItemStore(_tfs);
var workItem = workItemStore.GetWorkItem(testCase.WorkItem.WorkItemLinks[i].TargetId);
if (workItem.Type.Name == "Product Backlog Item")
{
if (j < 1)
{
referencesNode.InnerText = testCase.WorkItem.WorkItemLinks[i].TargetId.ToString();
j++;
}
else
{
referencesNode.InnerText = referencesNode.InnerText + ", " + testCase.WorkItem.WorkItemLinks[i].TargetId.ToString();
}
}
}
caseNode.AppendChild(referencesNode);
XmlNode customNode = xmlDoc.CreateElement("custom");
caseNode.AppendChild(customNode);
XmlNode stepsNode = xmlDoc.CreateElement("steps_separated");
customNode.AppendChild(stepsNode);
i = 1;
foreach (ITestAction action in testCase.Actions)
{
var sharedRef = action as ISharedStepReference;
if (sharedRef != null)
{
var sharedStep = sharedRef.FindSharedStep();
foreach (var testStep in sharedStep.Actions.Select(sharedAction => sharedAction as ITestStep))
{
WriteTestSteps(i, testStep.Title.ToString(), testStep.ExpectedResult.ToString(), xmlDoc, stepsNode);
i++;
}
}
else
{
var testStep = action as ITestStep;
WriteTestSteps(i, testStep.Title.ToString(), testStep.ExpectedResult.ToString(), xmlDoc, stepsNode);
i++;
}
} //end of foreach test action
return caseNode;
}
void WriteTestSteps(int i, string testAction, string expectedResult, XmlDocument xmlDoc, XmlNode node)
{
XmlNode stepNode = xmlDoc.CreateElement("step");
node.AppendChild(stepNode);
XmlNode indexNode = xmlDoc.CreateElement("index");
indexNode.InnerText = i.ToString();
stepNode.AppendChild(indexNode);
XmlNode contentNode = xmlDoc.CreateElement("content");
contentNode.InnerText = testAction;
stepNode.AppendChild(contentNode);
XmlNode expectedNode = xmlDoc.CreateElement("expected");
expectedNode.InnerText = expectedResult;
stepNode.AppendChild(expectedNode);
}
}
} |
//Memo
/* 기본 규칙
1. 그날 코딩 끝나면 한번 더 정리할것 없나 보고 끄기
ex) 종료 조건있는 반복문을 for문이 아닌 while문(변수++)으로 사용해서 불필요한 변수를 추가하지는 않았는지,
줄일 수 있었는데 장황한 채로 남겨진 코드는 없는지, 기능 주석이 안적힌 함수는 없는지,
쓰려다가 안쓰고 잊어버려서 미처 지우지 못한 변수는 없는지 등
2. 각자의 스크립트가 하는 일을 확실하게 하기
ex) 플레이어 스탯,이동관련은 플레이어 스크립트 / 전반적인 배경, 흐름은 게임매니저 / 아이템 수집, 조합 등은 아이템매니저 등
3. 무분별한 Instantiate -> Destory 지양. 이유있는 상황이 아니면 오브젝트 풀링 사용하기
-[ 멤버변수 표기 관련 ]------------------------------------------------------------------------------------------------------------------------
1. 명시하지 않아도 기본적으로 private로 선언이 되기는 하나 항상 private 같이 기재하기(팀원간의 코드 명시성 ↑)
ex) bool m_b_name(X) / private bool m_b_name(O)
2. 헝가리안 표기법을 기반으로 변수 선언 - private/public, 자료형(소문자) , 변수이름
ex) private bool name -> private bool m_b_name;
public bool name -> public bool b_name;
2-1. GameObject, Rigidbody 같이 애매한건 그냥 앞글자 대문자로 땁시다
ex) private GameObject m_G_name;
3. 협업 중 무분별한 public 변수 이용시 코드가 엉킬수 있으므로, 인스펙터에서 조절할 수는 있지만
타 스크립트에서는 변수값에 접근하지 못하게 하고싶을때 private + 스크립트 직렬화(SerializeField) 사용하기
(유니티 공식에서도 특별한 상황이 아니면 public을 쓰기를 권장하고 회사에서도 그냥 보통 public 쓴다고 하지만 우리는 코린이니까 자신+서로를 위해!)
※ 직렬화 바로 밑의 변수 한 개에만 적용되기 때매 일일이 달아줘야되서 좀 귀찮기는 합니다ㅜ
ex) [SerializeField] private int m_i_bubbleMax = 13;
└→ 물속 물거품 개수를 인스펙터에서 변경할수는 있지만 타 스크립트에서 해당 변수에 접근할 수 없음
4. 변수 옆에 뭐하는 변수인지 주석 달아놓기 (+ 함수 위에도 기능 간단하게 꼭 주석달아놓기)
ex) private GameObject m_G_bubble; //버블 프리팹
ex2) //수중 물거품 랜덤 위치 생성
void makin_Bubble()
{ ~~; }
-[ 이동 관련 ]--------------------------------------------------------------------------------------------------------------------------------
ㆍFixedUpdate : rigidbody가 적용된 오브젝트 사용할 때 ex) 무기 투척
ㆍUpdate : 캐릭터 기본이동 및 회전
ㆍLateUpdate : 카메라 이동 및 회전 ex) 3인칭 카메라 코드로 직접 제어. 이 프로젝트에선 자주 쓰이진 않을 것 같음.
-[ 함수 관련 ]---------------------------------------------------------------------------------------------------------------------------------
사용되지 않는 함수들은 정리하기 (Start, Update 등 중요 함수 포함. 체감은 크지않지만 굳이 불필요한 연산은 줄이기)
GetComponent 보다는 Inspector 링크 지향하기. (마우스 드래그로 넣을수 있는것들. 꼭 필요하지 않는이상 GetComponent 쓰지않기. 불필요한 코드연산 줄이기)
-[ 코드 구조 관련 ]-----------------------------------------------------------------------------------------------------------------------------
1) 아이템 : 개별 Class + 상속 지향. 아이템 구별은 Enum 지향. (추후 확장성, 관리 용이성을 위해)
2) 싱글톤 있는 매니저들은 각자의 Start 나 Awake 를 넣을시 특정 상황에서 호출 순서가 꼬일 수 있으므로
첫 실행시 바로 진행되어야하는 것들은 Init() 함수에 넣고 한개의 매니저의 Start 나 Awake에 같이 때려박아넣어두기 (코드 호출 흐름도 안정화 때문)
3) 합칠수 있는 코드는 합쳐보기(각자가 만들어 둔 것들 중 중복되는 코드는 정리)
4) Instantiate 사용시 특정 부모폴더 밑에서 생성되게 코딩하기(나중에 생성할 오브젝트가 많아지면 하이어라키 엉망진창됨)
*/
/* 수중도시 씬
*/
/* 섬 씬
변경 사항
-- 2021.07.21-------------
플레이어 이동 및 애니메이션 구현 (육지)
플레이어 공격 애니메이션 구현 (육지)
상호작용 가능한 오브젝트에 마우스 올릴 시 Outline 활성화되도록 구현
└→ ⚠ Update문에서 계속 RayCast로 체크해주고 있으므로 좀 더 효율적인 방법 찾아볼 것
*/
/* 연구소 씬
변경 사항
-- 2021.07.23--------------
최종 아이템 방 추가 (SecretRoom)
문 열고 닫음 구현 X -> 2021.07.25 트리거 구현은 했으나 애니메이션 구현에 문제가 있는 듯함
-- 2021.07.25--------------
목적지 이펙트에 들어가면 아일랜드씬으로 변환 구현
-- 추가 사항---------------
1. 디렉셔널 라이트 0.3으로 하기
*/
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
namespace iCopy.Database
{
public class ApplicationRole : IdentityRole<int>
{
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool Active { get; set; }
public ICollection<ApplicationUserRole> UserRoles { get; set; }
}
}
|
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Forms.Plugin.CardForm.Droid;
using Forms.Plugin.CardForm.Platforms.Helpers;
using Forms.Plugin.CardForm.Controls;
using Forms.Plugin.CardForm.Shared.Helpers;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Card = Forms.Plugin.CardForm.Controls.CardEntry;
[assembly: ExportRenderer(typeof(Card), typeof(CardEntryRenderer))]
namespace Forms.Plugin.CardForm.Droid
{
public class CardEntryRenderer : EntryRenderer
{
Card element;
public CardEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
Control.InputType = Android.Text.InputTypes.ClassNumber;
}
protected override async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
try
{
base.OnElementPropertyChanged(sender, e);
element = (Card)Element;
var editText = Control;
if (element.Image != null)
{
switch (element.ImageAlignment)
{
case ImageAlignment.Left:
editText.SetCompoundDrawablesWithIntrinsicBounds(await GetDrawable(element.Image), null, null, null);
break;
case ImageAlignment.Right:
editText.SetCompoundDrawablesWithIntrinsicBounds(null, null, await GetDrawable(element.Image), null);
break;
}
}
editText.CompoundDrawablePadding = 25;
Control.Background.SetColorFilter(element.LineColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private async Task<BitmapDrawable> GetDrawable(ImageSource imageEntryImage)
{
Bitmap _bitmapImageconverted = await ImageHelper.GetBitmapFromImageSourceAsync(element.Image, Context);
return new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(_bitmapImageconverted, 50 * 2, 40 * 2, true));
}
}
}
|
using System.Collections;
using Castle.DynamicProxy;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NUnit.Framework;
namespace AdvancedIoCTechniques
{
public class AspectOrientedProgramming
{
[Test]
public void Redefine_The_Rules()
{
var hash = _windsor.Resolve<IDictionary>();
hash["hello"] = 123;
Assert.AreEqual(42, hash["hello"]);
}
#region setup
private IWindsorContainer _windsor;
[TestFixtureSetUp]
public void Setup()
{
_windsor = new WindsorContainer();
_windsor.Register(
Component.For<AlwaysReturns42Interceptor>(),
Component
.For<IDictionary>()
.ImplementedBy<Hashtable>()
.Interceptors<AlwaysReturns42Interceptor>());
}
public class AlwaysReturns42Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
invocation.ReturnValue = 42;
}
}
#endregion
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Game.Player.Scoring
{
public class Scoreinmenu : MonoBehaviour
{
/*private int Count = 10;
public GameObject[] TextPrefab;
public GameObject prefabForCreate;
public Transform ScoreParent;
void Start()
{
TextPrefab = new GameObject[10];
for (int Prefabs = 0; Prefabs <= Count; Prefabs++)
{
TextPrefab[Prefabs] = Instantiate(prefabForCreate,
ScoreParent.transform.localPosition,ScoreParent.transform.rotation);
TextPrefab[Prefabs].transform.SetParent(ScoreParent);
TextPrefab[Prefabs].transform.localScale = new Vector3(1,1,1);
TextPrefab[Prefabs].transform.localPosition = new Vector3
(TextPrefab[Prefabs].transform.position.x,TextPrefab[Prefabs].transform.position.y, -55);
if (PlayerPrefs.HasKey("Position" + Prefabs))
TextPrefab[Prefabs].GetComponent<Text>().text = PlayerPrefs.GetString("Position" + Prefabs);
}
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NUnit.RestServiceTest
{
public interface IRestClientMethods
{
void GETALLUSERS();
void GETONEUSER(string name);
List<string> ADDUSER(string name1, string name2);
List<string> DELETEUSER(string name);
void UPDATEUSER(string name1, string name2, string name3);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Zelo.Management.AppUtils;
using Zelo.Management.Models;
using Zelo.DBModel;
using Zelo.DBService;
namespace Zelo.Management.Controllers
{
public abstract class BaseController : ApiController
{
public BaseController()
{
}
public User CurrentUser
{
get;
set;
}
private Boolean _isAuthrized = false;
public Boolean IsAuthrized
{
get
{
return _isAuthrized;
}
set
{
_isAuthrized = value;
}
}
/// <summary>
/// token是否过期
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public Boolean IsTokenOutDate(String userID, String token)
{
return false;
//return userTokenDAL.IsTokenOutDate(userID,token);
}
/// <summary>
/// 检查modelstat,参数是否验证成功,且token是否正确,如果正确返回null;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="param"></param>
/// <returns></returns>
public Result<T> CheckModelState<T>(BaseParams param)
{
Result<T> result = ControllerUtils.getErrorResult<T>(ModelState, param);
if (result == null)
{
if (IsTokenOutDate(param.user_id, param.token))
{
User user = new User();
user.UserGID = param.user_id;
user.UserToken = param.token;
CurrentUser = user;
return Result<T>.CreateInstance(ResultCode.TokenOutDate, "token过期");
}
else
{
return null;
}
}
return result;
}
public Result<object> AuthFilterResult { get; set; }
/// <summary>
/// 获取最后结果
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public Result<T> GetAuthFilterResult<T>()
{
Result<T> temp = new Result<T>();
temp.code = AuthFilterResult.code;
temp.message = AuthFilterResult.message;
return temp;
}
public T GetService<T>() where T : BaseService
{
return ServiceFactory.GetService<T>(CurrentUser);
}
#region 一些特殊方法
/// <summary>
/// 一身模型转化
/// </summary>
/// <param name="doctor"></param>
/// <returns></returns>
protected DoctorInfo ConvertDoctorInfo(TDoctor doctor)
{
DoctorInfo info = new DoctorInfo();
info.avatar = ObjectUtils.GetValueOrEmpty(doctor.Avatar);
info.name = ObjectUtils.GetValueOrEmpty(doctor.DoctorName);
info.province = ObjectUtils.GetValueOrEmpty(doctor.ProvinceName);
info.sex = ObjectUtils.GetValueOrDefault<int>(doctor.Sex);
info.title = ObjectUtils.GetValueOrEmpty(doctor.DoctorTitle);
info.doctor_id = doctor.DocotorMID;
info.city = ObjectUtils.GetValueOrEmpty(doctor.CityName);
info.hospital = ObjectUtils.GetValueOrEmpty(doctor.HospitalName);
info.introduce = ObjectUtils.GetValueOrEmpty(doctor.Introduce);
info.user_id = ObjectUtils.GetValueOrEmpty(doctor.DoctorGID);
return (DoctorInfo)info;
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimatorParameterSetter : MonoBehaviour {
[SerializeField]
protected Animator _animator;
[SerializeField]
private string _parameterName;
[SerializeField]
private float _floatInitialValue;
[SerializeField]
private int _intInitialValue;
[SerializeField]
private bool _boolInitialValue;
public void SetTrigger()
{
_animator.SetTrigger(_parameterName);
}
public void SetTrigger(string triggerName)
{
_animator.SetTrigger(triggerName);
}
public void SetBool()
{
_animator.SetBool(_parameterName, _boolInitialValue);
}
public void SetInt()
{
_animator.SetInteger(_parameterName, _intInitialValue);
}
public void SetFloat()
{
_animator.SetFloat(_parameterName, _floatInitialValue);
}
public void SetParameter(string parameterName)
{
_animator.SetTrigger(parameterName);
}
public void SetParameter(string parameterName, bool value)
{
_animator.SetBool(parameterName, value);
}
public void SetParameter(string parameterName, int value)
{
_animator.SetInteger(parameterName, value);
}
public void SetParameter(string parameterName, float value)
{
_animator.SetFloat(parameterName, value);
}
}
|
//-----------------------------------------------------------------------
// <copyright file="RetrCommandHandler.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
// <author>Mark Junker</author>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using FubarDev.FtpServer.FileSystem;
namespace FubarDev.FtpServer.CommandHandlers
{
/// <summary>
/// Implements the <c>RETR</c> command.
/// </summary>
public class RetrCommandHandler : FtpCommandHandler
{
private const int BufferSize = 4096;
/// <summary>
/// Initializes a new instance of the <see cref="RetrCommandHandler"/> class.
/// </summary>
/// <param name="connectionAccessor">The accessor to get the connection that is active during the <see cref="Process"/> method execution.</param>
public RetrCommandHandler(IFtpConnectionAccessor connectionAccessor)
: base(connectionAccessor, "RETR")
{
}
/// <inheritdoc/>
public override bool IsAbortable => true;
/// <inheritdoc/>
public override async Task<FtpResponse> Process(FtpCommand command, CancellationToken cancellationToken)
{
var restartPosition = Data.RestartPosition;
Data.RestartPosition = null;
if (!Data.TransferMode.IsBinary && Data.TransferMode.FileType != FtpFileType.Ascii)
{
throw new NotSupportedException();
}
var fileName = command.Argument;
var currentPath = Data.Path.Clone();
var fileInfo = await Data.FileSystem.SearchFileAsync(currentPath, fileName, cancellationToken).ConfigureAwait(false);
if (fileInfo?.Entry == null)
{
return new FtpResponse(550, "File doesn't exist.");
}
using (var input = await Data.FileSystem.OpenReadAsync(fileInfo.Entry, restartPosition ?? 0, cancellationToken).ConfigureAwait(false))
{
await Connection.WriteAsync(new FtpResponse(150, "Opening connection for data transfer."), cancellationToken).ConfigureAwait(false);
// ReSharper disable once AccessToDisposedClosure
return await Connection.SendResponseAsync(
client => ExecuteSendAsync(client, input, cancellationToken))
.ConfigureAwait(false);
}
}
private async Task<FtpResponse> ExecuteSendAsync(
TcpClient responseSocket,
Stream input,
CancellationToken cancellationToken)
{
var writeStream = responseSocket.GetStream();
writeStream.WriteTimeout = 10000;
using (var stream = await Connection.CreateEncryptedStream(writeStream).ConfigureAwait(false))
{
var buffer = new byte[BufferSize];
int receivedBytes;
while ((receivedBytes = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken)
.ConfigureAwait(false)) != 0)
{
await stream.WriteAsync(buffer, 0, receivedBytes, cancellationToken)
.ConfigureAwait(false);
}
}
return new FtpResponse(226, "File download succeeded.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Areas22
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCuadrado_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Cuadrado(numCuadrado.Value);
lblCuadrado.Text = resultado + "";
}
private void btnRectangulo_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Rectangulo(numRectangulo.Value, numRectangulo1.Value);
lblRectangulo.Text = resultado + "";
}
private void btnTriangulo_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Triangulo(numTriangulo.Value, numTriangulo1.Value);
lblTriangulo.Text = resultado + "";
}
private void btnRombo_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Rombo(numRombo.Value, numRombo1.Value);
lblRombo.Text = resultado + "";
}
private void btnRomboide_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Romboide(numRomboide.Value, numRomboide1.Value);
lblRomboide.Text = resultado + "";
}
private void btnPoligono_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Poligono(numPoligono.Value, numPoligono1.Value);
lblPoligono.Text = resultado + "";
}
private void btnCirculo_Click(object sender, EventArgs e)
{
Areas a= new Areas();
decimal resultado = a.Circulo(numCirculo.Value);
lblCirculo.Text = resultado + "";
}
private void btnTrapecio_Click(object sender, EventArgs e)
{
Areas a = new Areas();
decimal resultado = a.Trapecio(numTrapecio.Value, numTrapecio1.Value, numtrapecio2.Value);
lblTrapecio.Text = resultado + "";
}
}
}
|
namespace Fairmas.PickupTracking.Shared.Models
{
/// <summary>
/// Represents the model for the figures that are delivered by the PickupTracking backend services.
/// </summary>
public class PickupFigures
{
/// <summary>
/// The appropriate figure from snapshot one. Figure will only be delivered if explicitely specified in the request.
/// </summary>
public decimal? SnapshotOneValue { get; set; }
/// <summary>
/// The appropriate figure from snapshot two. Figure will only be delivered if explicitely specified in the request.
/// </summary>
public decimal? SnapshotTwoValue { get; set; }
/// <summary>
/// The appropriate pickup figure (difference between figures from snapshot one and snapshot two).
/// Figure will only be delivered if explicitely specified in the request.
/// </summary>
public decimal? PickupValue { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using Nito.AsyncEx;
using TemporaryEmploymentCorp.DataAccess;
using TemporaryEmploymentCorp.DataAccess.EF;
using TemporaryEmploymentCorp.Helpers.ReportViewer;
using TemporaryEmploymentCorp.Models.Attendance;
using TemporaryEmploymentCorp.Models.Candidate;
using TemporaryEmploymentCorp.Models.Enrollees;
using TemporaryEmploymentCorp.Models.Qualification;
using TemporaryEmploymentCorp.Models.Session;
using TemporaryEmploymentCorp.Reports.Course;
using TemporaryEmploymentCorp.Reports.Session;
using TemporaryEmploymentCorp.Views.Session;
using TemporaryEmploymentCorp.Views.Session.Attendance;
using TemporaryEmploymentCorp.Views.Session.Enrollees;
namespace TemporaryEmploymentCorp.Modules
{
public class SessionModule : ObservableObject
{
private IRepository _repository;
private SessionModel _selectedSession;
private NewSessionModel _newSession;
public ObservableCollection<SessionModel> Sessions { get; } = new ObservableCollection<SessionModel>();
public SessionModule(IRepository repository)
{
_repository = repository;
SessionLoading = NotifyTaskCompletion.Create(LoadSessionAsync);
}
private async Task LoadSessionAsync()
{
var sessions = await _repository.Session.GetRangeAsync();
foreach (var session in sessions)
{
var course = _repository.Course.Get(c => c.CourseId == session.CourseId);
session.Course = course;
Sessions.Add(new SessionModel(session, _repository));
}
}
public INotifyTaskCompletion SessionLoading { get; private set; }
public SessionModel SelectedSession
{
get { return _selectedSession; }
set
{
_selectedSession?.CancelEditCommand.Execute(null);
_selectedSession = value;
if (value != null)
{
LoadSessionDetails();
_selectedSession.LoadRelatedInfo();
GetNumberOfEnrollees();
}
RaisePropertyChanged(nameof(SelectedSession));
}
}
private void LoadSessionDetails()
{
var course = _repository.Course.Get(c => c.CourseId == SelectedSession.Model.CourseId);
LoadedCourse = course;
}
public Course LoadedCourse
{
get { return _loadedCourse; }
set
{
_loadedCourse = value;
RaisePropertyChanged(nameof(LoadedCourse));
}
}
public NewSessionModel NewSession
{
get { return _newSession; }
set
{
_newSession = value;
RaisePropertyChanged(nameof(NewSession));
}
}
public EnrolleeModel SelectedEnrollee
{
get { return _selectedEnrollee; }
set
{
_selectedEnrollee = value;
RaisePropertyChanged(nameof(SelectedEnrollee));
}
}
public NewEnrollmentModel NewEnrollment
{
get { return _newEnrollment; }
set
{
_newEnrollment = value;
RaisePropertyChanged(nameof(NewEnrollment));
}
}
public ICommand AddEnrolleeCommand => new RelayCommand(AddEnrolleeProc);
public AddEnrolleesWindow _AddEnrolleesWindow;
private void AddEnrolleeProc()
{
NewEnrollment = new NewEnrollmentModel(new Enrollment(), _repository, SelectedSession);
_AddEnrolleesWindow = new AddEnrolleesWindow();
_AddEnrolleesWindow.Owner = Application.Current.MainWindow;
_AddEnrolleesWindow.ShowDialog();
}
public ICommand CancelEnrolleeCommand => new RelayCommand(CancelEnrolleeProc);
private void CancelEnrolleeProc()
{
NewEnrollment?.Dispose();
_AddEnrolleesWindow.Close();
}
public ICommand SaveEnrolleeCommand => new RelayCommand(SaveEnrolleeProc, SaveEnrolleeCondition);
public int NumberOfEnrollees
{
get { return _numberOfEnrollees; }
set
{
_numberOfEnrollees = value;
RaisePropertyChanged(nameof(NumberOfEnrollees));
}
}
private void GetNumberOfEnrollees()
{
var enrollments = _repository.Enrollment.GetRange(c => c.SessionCode == SelectedSession.Model.SessionId);
NumberOfEnrollees = enrollments.Count;
}
private bool SaveEnrolleeCondition()
{
return true;
}
private void SaveEnrolleeProc()
{
if (NewEnrollment == null) return;
try
{
NewEnrollment.ModelCopy.Balance = GetBalance(SelectedSession.Model.Fee);
NewEnrollment.ModelCopy.SessionCode = SelectedSession.Model.SessionId;
_repository.Enrollment.Add(NewEnrollment.ModelCopy);
_selectedSession.EnrolledCandidatesList.Add(new EnrolleeModel(NewEnrollment.ModelCopy, _repository));
}
catch (Exception e)
{
MessageBox.Show("Unable to save. Reason: " + e.Message);
throw;
}
// var selectedEnrollees = NewEnrollment.ToEnrollList.Where(c => c.IsSelected).ToList();
// foreach (var selectedEnrollee in selectedEnrollees)
// {
// try
// {
// NewEnrollment.ModelCopy.CandidateId = selectedEnrollee.Model.CandidateId;
// NewEnrollment.ModelCopy.SessionCode = SelectedSession.Model.SessionId;
//
// _selectedSession.EnrolledCandidatesList.Add(new EnrolleeModel(NewEnrollment.ModelCopy, _repository));
// _repository.Enrollment.Add(NewEnrollment.ModelCopy);
//
//
// }
// catch (Exception)
// {
// MessageBox.Show("An error occured during save", "Candidate");
// }
// }
SelectedSession = _selectedSession;
ViewModelLocatorStatic.Locator.CandidateModule.SelectedCandidate =
ViewModelLocatorStatic.Locator.CandidateModule.SelectedCandidate;
_AddEnrolleesWindow.Close();
}
public ICommand RemoveEnrolleeCommand => new RelayCommand(RemoveEnrolleeProc, RemoveEnrolleCondition);
private void RemoveEnrolleeProc()
{
var result = MessageBox.Show("Are you sure you want to delete selected enrollee?", "Enrollment",
MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
try
{
NotifyTaskCompletion.Create(RemoveEnrolleeCommandAsync);
}
catch (Exception e)
{
MessageBox.Show("Unable to delete opening");
}
}
}
private async Task RemoveEnrolleeCommandAsync()
{
await _repository.Enrollment.RemoveAsync(SelectedEnrollee.Model);
SelectedSession.EnrolledCandidatesList.Remove(SelectedEnrollee);
}
private bool RemoveEnrolleCondition()
{
if(SelectedEnrollee == null) return false;
return true;
}
private string GetBalance(string fee)
{
int zero = 0;
var newBalance = Convert.ToInt32(fee) - Convert.ToInt32(NewEnrollment.ModelCopy.Balance);
if (newBalance < 0)
{
return zero.ToString();
}
return newBalance.ToString();
}
public ICommand AddSessionCommand => new RelayCommand(AddSessionProc);
public ICommand RemoveSessionCommand => new RelayCommand(RemoveSessionProc, RemoveSessionCondition);
public ICommand RemoveAttendeeCommand => new RelayCommand(RemoveAttendeeProc, RemoveAttendeeCondition);
private void RemoveAttendeeProc()
{
try
{
_repository.Attendance.Remove(SelectedAttendance.Model);
SelectedSession.PresentCandidatesList.Remove(SelectedAttendance);
}
catch (Exception)
{
MessageBox.Show("Unable to Delete Attendee");
throw;
}
}
private bool RemoveAttendeeCondition()
{
if (SelectedAttendance == null) return false;
return true;
}
private void RemoveSessionProc()
{
var result = MessageBox.Show("Are you sure you want to delete selected session?", "Session",
MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
try
{
var enrollments =
_repository.Enrollment.GetRange(c => c.SessionCode == SelectedSession.Model.SessionId);
if (enrollments.Count > 0)
{
MessageBox.Show("Unable to delete sessions with enrollees");
}
else
{
NotifyTaskCompletion.Create(RemoveSessionAsync);
}
}
catch (Exception e)
{
MessageBox.Show("Unable to delete opening");
}
}
}
private async Task RemoveSessionAsync()
{
await _repository.Session.RemoveAsync(SelectedSession.Model);
Sessions.Remove(SelectedSession);
}
private bool RemoveSessionCondition()
{
if (SelectedSession == null) return false;
return true;
}
public AddSessionWindow _AddSessionWindow;
private EnrolleeModel _selectedEnrollee;
private NewEnrollmentModel _newEnrollment;
private AttendanceModel _selectedAttendance;
private NewAttendanceModel _newAttendance;
private void AddSessionProc()
{
NewSession = new NewSessionModel();
_AddSessionWindow = new AddSessionWindow();
_AddSessionWindow.Owner = Application.Current.MainWindow;
_AddSessionWindow.ShowDialog();
}
public ICommand CancelSessionCommand => new RelayCommand(CancelSessionProc);
private void CancelSessionProc()
{
NewSession?.Dispose();
_AddSessionWindow.Close();
}
public ICommand SaveSessionCommand => new RelayCommand(SaveSessionProc, SaveSessionCondition);
private bool SaveSessionCondition()
{
return true;
}
private void SaveSessionProc()
{
if (NewSession == null) return;
if (!NewSession.HasChanges) return;
try
{
_repository.Session.Add(NewSession.ModelCopy);
Sessions.Add(new SessionModel(NewSession.ModelCopy, _repository));
_AddSessionWindow.Close();
}
catch (Exception e)
{
MessageBox.Show("An error occured during save. Reason:" + e.Message, "Company");
}
SelectedSession = _selectedSession;
}
public AttendanceModel SelectedAttendance
{
get { return _selectedAttendance; }
set
{
_selectedAttendance = value;
RaisePropertyChanged(nameof(SelectedAttendance));
}
}
public NewAttendanceModel NewAttendance
{
get { return _newAttendance; }
set
{
_newAttendance = value;
RaisePropertyChanged(nameof(NewAttendance));
}
}
public ICommand AddAttendanceCommand => new RelayCommand(AddAttendanceProc);
public AddAttendanceWindow _AddAttendanceWindow;
private int _numberOfEnrollees;
private Course _loadedCourse;
private void AddAttendanceProc()
{
NewAttendance = new NewAttendanceModel(new Attendance(), _repository, SelectedSession);
_AddAttendanceWindow = new AddAttendanceWindow();
_AddAttendanceWindow.Owner = Application.Current.MainWindow;
_AddAttendanceWindow.ShowDialog();
}
public ICommand CancelAttendanceCommand => new RelayCommand(CancelAttendanceProc);
private void CancelAttendanceProc()
{
NewAttendance?.Dispose();
_AddAttendanceWindow.Close();
}
public ICommand SaveAttendanceCommand => new RelayCommand(SaveAttendanceProc, SaveAttendanceCondition);
private bool SaveAttendanceCondition()
{
return true;
}
private void SaveAttendanceProc()
{
if(NewAttendance == null) return;
var selectedPresentEnrollees = NewAttendance.ToCheckAttendance.Where(c => c.IsSelected).ToList();
foreach (var selectedStudent in selectedPresentEnrollees)
{
try
{
NewAttendance.ModelCopy.SessionId = SelectedSession.Model.SessionId;
NewAttendance.ModelCopy.CandidateId = selectedStudent.Model.CandidateId;
NewAttendance.ModelCopy.IsPresent = true;
_repository.Attendance.Add(NewAttendance.ModelCopy);
_selectedSession.PresentCandidatesList.Add(new AttendanceModel(NewAttendance.ModelCopy, _repository));
}
catch (Exception e)
{
MessageBox.Show("Unable to save. Reason: " + e.Message);
}
}
SelectedSession = _selectedSession;
_AddAttendanceWindow.Close();
}
public ICommand PrintAllSessionsCommand => new RelayCommand(PrintAllSessionsProc);
private SingleInstanceWindowViewer<AllSessionReportWindow> _allSessionWindow = new SingleInstanceWindowViewer<AllSessionReportWindow>();
private void PrintAllSessionsProc()
{
_allSessionWindow.Show();
}
public ICommand PrintAttendanceCommand => new RelayCommand(PrintAttendanceProc);
private SingleInstanceWindowViewer<AttendanceReportWindow> _printAttendanceWindow = new SingleInstanceWindowViewer<AttendanceReportWindow>();
private void PrintAttendanceProc()
{
_printAttendanceWindow.Show();
}
private string _searchSession;
public string SearchSession
{
get { return _searchSession; }
set
{
_searchSession = value;
RaisePropertyChanged(nameof(SearchSession));
var SessionList = CollectionViewSource.GetDefaultView(Sessions);
if (string.IsNullOrWhiteSpace(SearchSession))
{
SessionList.Filter = null;
}
else
{
SessionList.Filter = obj =>
{
var sessModel = obj as SessionModel;
var sc = SearchSession.ToLowerInvariant();
if (sessModel == null) return false;
return sessModel.Model.SessionId.ToLowerInvariant().Contains(sc) ||
sessModel.Model.Course.CourseName.ToLowerInvariant().Contains(sc);
};
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Studentum.Infrastructure.Caching;
using Studentum.Infrastructure.Repository;
namespace BreakAway.Domain
{
public class ActivityLoader : CachedEntityLoader<Activity, int>
{
public ActivityLoader() : base("BreakAway") { }
protected override IEnumerable<Activity> LoadAll()
{
IRepository<Activity> repository = RepositoryFactory.GetReadOnlyRepository<ActivityRepository>();
return repository.Items;
}
protected override Activity LoadItem(int key)
{
IRepository<Activity> repository = RepositoryFactory.GetReadOnlyRepository<ActivityRepository>();
Activity item = repository.Get(key);
return item;
}
}
public class ActivityStore : LocalStoreBase<Activity, int>
{
public ActivityStore(ILoader<Activity, int> loader) : base(loader, null) { }
}
}
|
using System;
using System.IO;
namespace CloudFile
{
public class RequestObjectForUpload : RequestObject
{
private Stream m_requestStream;
public Stream RequestStream
{
get
{
return this.m_requestStream;
}
set
{
this.m_requestStream = value;
}
}
public RequestObjectForUpload(int id) : base(id)
{
}
public override void Release()
{
base.Release();
if (this.m_requestStream != null)
{
this.m_requestStream.Close();
this.m_requestStream = null;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Eric : MonoBehaviour
{
void Awake()
{
EventSystem.instance.OnClick += DoIt;
}
public void DoIt(GameObject go)
{
if (go == gameObject)
print("I am doing it");
}
}
|
namespace KISSMp3MoverBefore.Contracts
{
public interface IFileSelectStrategy
{
bool CanBeSelected(string fileName);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class BallLauncher : MonoBehaviour
{
// public Slider slider1;
public GameObject ballprefab;
public float ballspeed = 1.0f;
private Vector3 throwSpeed = new Vector3(0, 26, 40);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
// for (ballspeed = 3; Input.anyKeyDown; ballspeed++) ;
ballspeed += Input.GetAxis("Mouse ScrollWheel");
ballspeed = Mathf.Clamp(ballspeed, 0, 10);
print("speed is" + ballspeed);
//slider1.value = ballspeed;
if (Input.GetMouseButtonUp(0))
{
// Instantiate(ballprefab);
GameObject instance = Instantiate(ballprefab);
instance.transform.position = transform.position;
Rigidbody rb = instance.GetComponent<Rigidbody>();
Camera camera = GetComponentInChildren<Camera>();
// throwSpeed.x = ballspeed/2;
throwSpeed.y = ballspeed / 2;
throwSpeed.z = (ballspeed);
rb.velocity = camera.transform.rotation * throwSpeed * ballspeed;
//ballspeed = 3.0f;
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
namespace Yasl
{
public class ArraySerializer : ISerializer
{
readonly Type _elementType;
//readonly int _arrayDimensions;
public ArraySerializer(Type elementType, int arrayDimensions)
{
_elementType = elementType;
//_arrayDimensions = arrayDimensions;
}
public void SerializeConstructor(ref object value, ISerializationWriter writer)
{
Array array = (Array)value;
int[] lengths = new int[array.Rank];
for (int i = 0; i < array.Rank; ++i)
{
lengths[i] = array.GetLength(i);
}
writer.WriteSet(typeof(int), "Length", lengths);
}
public void SerializeContents(ref object value, ISerializationWriter writer)
{
writer.WriteSet(_elementType, SerializationConstants.DefaultValueItemName, (Array)value);
}
public void SerializeBacklinks(ref object value, ISerializationWriter writer)
{
}
public void DeserializeConstructor(out object value, int version, ISerializationReader reader)
{
int[] lengths = reader.ReadSet<int>("Length").ToArray();
value = Array.CreateInstance(_elementType, lengths);
}
bool RecursiveAssignArray(IEnumerator valueEnumerator, Array array, int[] index, int depth)
{
if (depth == array.Rank)
{
if (valueEnumerator.MoveNext())
{
array.SetValue(valueEnumerator.Current, index);
}
else
{
return false;
}
}
else
{
for (index[depth] = 0; index[depth] < array.GetLength(depth); index[depth] += 1)
{
if (!RecursiveAssignArray(valueEnumerator, array, index, depth + 1))
{
return false;
}
}
}
return true;
}
public void DeserializeContents(ref object value, int version, ISerializationReader reader)
{
Array array = (Array)value;
var enumerator = reader.ReadSet(_elementType, SerializationConstants.DefaultValueItemName, false).GetEnumerator();
if (array.Rank == 1)
{
for (int i = 0; i < array.Length && enumerator.MoveNext(); ++i)
{
array.SetValue(enumerator.Current, i);
}
}
else
{
int[] index = new int[array.Rank];
RecursiveAssignArray(enumerator, array, index, 0);
}
while (enumerator.MoveNext())
{
// ensures all enumerated items are read
}
}
public void DeserializeBacklinks(ref object value, int version, ISerializationReader reader)
{
}
public void DeserializationComplete(ref object value, int version)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enums {
public enum FightCommands {
LightAttack,
Block, BrokenBlock, MoveRight, MoveLeft, Crouch, StandUp, Fake,
None, NUM_COMMANDS, NULL
}
public enum FighterControllerType { Player, AI, Dummy, Rail, None }
public enum GameMode { Mayhem, Strategy }
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace DataAccess.Operations
{
public class HERE_TrafficAnalytics
{
public string _fx_GetTrafficAnalyticsByDates(BusinessEntities.Entities.HERE_TrafficAnalyticsRequests.TrafficAnalyticsByDates trafficAnalyticsByDates, LoggingFramework.ILog iLog, string Usertag)
{
string Result = string.Empty;
try
{
using (SqlConnection sqlConnection = DataAccess.Admin.DataAccessManager._fx_GetSqlConnection(iLog, string.Empty))
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("_spt_GetTrafficAnalyticsByDates", sqlConnection);
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_TAFromDate", trafficAnalyticsByDates.FromDate);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_TAToDate", trafficAnalyticsByDates.ToDate);
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
Result = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);
}
}
}
catch (Exception exception)
{
iLog.WriteError(exception.ToString());
}
finally
{ }
return Result;
}
public static string _fx_GetToSpeedDataByLinkIds(BusinessEntities.Entities.HERE_TrafficAnalyticsRequests.ToSpeedDataByLinkIds toSpeedDataByLinkIds, LoggingFramework.ILog iLog, string Usertag)
{
string Result = string.Empty;
try
{
using (SqlConnection sqlConnection = DataAccess.Admin.DataAccessManager._fx_GetSqlConnection(iLog, string.Empty))
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("_spt_GetToSpeedDataByLinkIds", sqlConnection);
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_LINKIDs", toSpeedDataByLinkIds.LinkIds);
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
Result = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);
}
}
}
catch (Exception exception)
{
Result = exception.ToString();
iLog.WriteError(exception.ToString());
}
finally
{ }
return Result;
}
public static string _fx_GetCongestionFactorByLinkIds(BusinessEntities.Entities.HERE_TrafficAnalyticsRequests.CongestionFactorByLinkIds congestionFactorByLinkIds, LoggingFramework.ILog iLog, string Usertag)
{
string Result = string.Empty;
try
{
using (SqlConnection sqlConnection = DataAccess.Admin.DataAccessManager._fx_GetSqlConnection(iLog, string.Empty))
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("_spt_GetCongestionFactorByLinkIds", sqlConnection);
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_LinkIds", congestionFactorByLinkIds.LinkIds);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_TimePattern", congestionFactorByLinkIds.TimePattern);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_Direction", congestionFactorByLinkIds.Direction);
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
Result = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);
}
}
}
catch (Exception exception)
{
Result = exception.ToString();
iLog.WriteError(exception.ToString());
}
finally
{ }
return Result;
}
public static string _fx_GetCongestionFactorsByLinkIds(BusinessEntities.Entities.HERE_TrafficAnalyticsRequests.CongestionFactorsByLinkIds congestionFactorsByLinkIds, LoggingFramework.ILog iLog, string Usertag)
{
string Result = string.Empty;
try
{
using (SqlConnection sqlConnection = DataAccess.Admin.DataAccessManager._fx_GetSqlConnection(iLog, string.Empty))
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("_spt_GetCongestionFactorsByLinkIds", sqlConnection);
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_LinkIds", congestionFactorsByLinkIds.LinkIds);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@_param_TimePattern", congestionFactorsByLinkIds.TimePattern);
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
Result = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable);
}
}
}
catch (Exception exception)
{
Result = exception.ToString();
iLog.WriteError(exception.ToString());
}
finally
{ }
return Result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KT.ServiceInterfaces;
using KnowledgeTester.Helpers;
using KnowledgeTester.Models;
using KnowledgeTester.Ninject;
namespace KnowledgeTester.Controllers
{
public class QuestionController : BaseController
{
//
// GET: /Question/
private Guid _qId;
public ActionResult Index(Guid? id)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
// user rights
if (TempData["ModelInvalid"] != null)
{
ViewBag.Message = TempData["ModelInvalid"];
}
if (id == null)
{
ViewBag.Message = "Please select a valid question!";
return RedirectToAction("Index", "Subcategory", new { id = SessionWrapper.CurrentSubcategoryId });
}
var subCatName = ServicesFactory.GetService<IKtSubcategoriesService>().GetById(SessionWrapper.CurrentSubcategoryId).Name;
if (id.Value.Equals(Guid.Empty))
{
var m = new QuestionModel(subCatName);
return View(m);
}
var q = ServicesFactory.GetService<IKtQuestionsService>().GetById(id.Value);
if (q != null)
{
var m = new QuestionModel(q, subCatName);
_qId = m.Id;
ViewBag.IsExistingQuestion = true;
return View(m);
}
ViewBag.Message = "Question does not exists!";
return View();
}
[HttpPost]
public ActionResult Save(QuestionModel model)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
{
TempData["ModelInvalid"] = "The save was not performed. Please review the page fileds and save again.";
return RedirectToAction("Index", "Question", new { id = model.Id });
}
_qId = model.Id.Equals(Guid.Empty) ?
ServicesFactory.GetService<IKtQuestionsService>().Save(model.Text, SessionWrapper.CurrentSubcategoryId) :
ServicesFactory.GetService<IKtQuestionsService>().Save(model.Text,
SessionWrapper.CurrentSubcategoryId, model.Id, model.IsMultiple, model.CorrectArgument);
if (model.Answers != null)
{
foreach (var ans in model.Answers)
{
ServicesFactory.GetService<IKtAnswersService>().Save(ans.Id, _qId, ans.Text, ans.IsCorrect);
}
}
return RedirectToAction("Index", "Question", new { id = _qId });
}
[HttpPost]
public ActionResult AddNewAnswer(Guid id)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
ServicesFactory.GetService<IKtAnswersService>().AddEmpyFor(id);
return RedirectToAction("Index", "Question", new { id });
}
[HttpPost]
public ActionResult DeleteAnswer(Guid id, Guid questionId)
{
if (!AdminAllowed)
{
return RedirectToAction("Index", "Home");
}
ServicesFactory.GetService<IKtAnswersService>().Delete(id);
return RedirectToAction("Index", "Question", new { id = questionId });
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
private SpawnerController _spawnerController;
private ScoreManager _scoreManager;
[SerializeField]
private DeathScreen _deathMenu;
private LivesController _livesController;
private KidAnimatorParameterSetter _kidAnimatorSetter;
private ActiveObjectsTracker _tracker;
private Timer _timer;
public GameObject JustDiePanel;
[SerializeField]
private GameObject _advButtonEng;
[SerializeField]
private GameObject _advButtonRus;
[SerializeField]
private GameObject _pauseButton;
private bool _kidIsAlive = true;
private int _deathsCounter;
private SoundManager _soundManager;
void Start()
{
_deathsCounter = 0;
_timer = FindObjectOfType<Timer>();
_scoreManager = FindObjectOfType<ScoreManager>();
_livesController = FindObjectOfType<LivesController>();
_tracker = FindObjectOfType<ActiveObjectsTracker>();
_kidAnimatorSetter = FindObjectOfType<KidAnimatorParameterSetter>();
_spawnerController = FindObjectOfType<SpawnerController>();
_soundManager = FindObjectOfType<SoundManager>();
}
public void Die()
{
_deathsCounter++;
_spawnerController.DecreaseTastyPossibility(_deathsCounter);
_kidIsAlive = false;
Time.timeScale = 0;
_pauseButton.SetActive(false);
_timer.TimerOn();
//StartCoroutine(TestTimerCoroutine());
}
public void AfterTimer()
{
JustDiePanel.SetActive(false);
if (!_kidIsAlive)
{
_scoreManager.SaveScore();
_scoreManager.LoadScore();
_deathMenu.Launch();
}
}
IEnumerator TestTimerCoroutine()
{
_timer.TimerOn();
yield return new WaitForSecondsRealtime(0f);
_pauseButton.SetActive(true);
if (!_kidIsAlive)
{
_scoreManager.SaveScore();
_scoreManager.LoadScore();
_deathMenu.Launch();
_soundManager.StopGeneralMelody();
PlayerPrefs.SetInt("FullBodySkin", (int)CostumeType.Default);
}
}
public void RewardForAd(string placementID)
{
if (placementID.Length < 2)
{
Debug.LogError ("Placement ID is too short. Please recheck all your IDs.");
return;
}
if (placementID.Equals("DeathScreen"))
{
StartCoroutine(Revive());
}
else
if (placementID.Equals("ExtraSweets"))
{
AddExtraSweets();
}
}
private IEnumerator Revive()
{
_kidIsAlive = true;
_livesController.Revive();
_kidAnimatorSetter.SetTrigger("Revive");
_tracker.KillEachActiveObstacle();
_deathMenu.gameObject.SetActive(false);
JustDiePanel.SetActive(false);
yield return new WaitForSecondsRealtime(1f);
Time.timeScale = 1;
}
private void AddExtraSweets()
{
_scoreManager.AddAdvertizementSweets(100);
_scoreManager.LoadScore();
//Making Button less visiable
Color color = new Color(255, 255, 255, 0.2f);
_advButtonEng.gameObject.GetComponent<Image>().color = color;
_advButtonEng.gameObject.GetComponent<Button>().interactable = false;
_advButtonRus.gameObject.GetComponent<Image>().color = color;
_advButtonRus.gameObject.GetComponent<Button>().interactable = false;
}
// Intensity of the GameObj Color 100%
public void FullTransparency(GameObject Obj)
{
if (Obj.gameObject.GetComponent<Image>().color.a.Equals(0.5f))
{
Color color = new Color(255, 255, 255, 1f);
Obj.gameObject.GetComponent<Image>().color = color;
}
}
// Intensity of the GameObj Color 50%
public void HalfTransparency(GameObject Obj)
{
if (Obj.gameObject.GetComponent<Image>().color.a.Equals(1f))
{
Color color = new Color(255, 255, 255, 0.5f);
Obj.gameObject.GetComponent<Image>().color = color;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class panelShow : MonoBehaviour {
public GameObject Panel;
public void showPanel()
{
Panel.gameObject.SetActive (true);
}
} |
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SampleService
{
public class VersjonController : ApiController
{
[Route]
[HttpGet]
public HttpResponseMessage Versjon()
{
return Request.CreateResponse(HttpStatusCode.OK, FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion);
}
}
} |
// <copyright file="AppDbContext.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Library.Repositories
{
using Library.Models;
using Microsoft.EntityFrameworkCore;
/// <summary>
/// This class must inherit DbContext, a class EF Core uses to map your models to database tables.
/// </summary>
public class AppDbContext : DbContext
{
/// <summary>
/// These properties are sets (collections of unique objects) that map models to database tables.
/// </summary>
public DbSet<Reader> Readers { get; set; }
/// <summary>
/// These properties are sets (collections of unique objects) that map models to database tables.
/// </summary>
public DbSet<Book> Books { get; set; }
/// <summary>
/// The constructor we added to this class is responsible for passing the database configuration
/// to the base class through dependency injection.
/// </summary>
/// <param name="options"></param>
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
/// <summary>
/// This method is using the feature called Fluent API to specify the database mapping.
/// </summary>
/// <param name="builder"></param>
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Reader>().ToTable("Readers");
builder.Entity<Reader>().HasKey(p => p.Id);
builder.Entity<Reader>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Reader>().Property(p => p.Name).IsRequired().HasMaxLength(30);
builder.Entity<Reader>().Property(p => p.DOB).IsRequired();
builder.Entity<Reader>().HasMany(p => p.Books).WithOne(p => p.Reader).HasForeignKey(p => p.ReaderId);
// Seeding the data.
builder.Entity<Reader>().HasData
(
new Reader { Id = 10, Name = "John", DOB = new System.DateTime(1985, 12 ,24, 05, 30, 12) }, // Id set manually due to in-memory provider
new Reader { Id = 11, Name = "Christopher", DOB = new System.DateTime(1981, 01, 21, 12, 02, 00) }
);
builder.Entity<Book>().ToTable("Books");
builder.Entity<Book>().HasKey(p => p.Id);
builder.Entity<Book>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Book>().Property(p => p.Title).IsRequired().HasMaxLength(50);
builder.Entity<Book>().Property(p => p.ISBN).IsRequired();
builder.Entity<Book>().Property(p => p.CheckOutDate);
builder.Entity<Book>().Property(p => p.Lost);
// Seeding the data.
builder.Entity<Book>().HasData
(
new Book
{
Id = 10,
Title = "Computer Science Using Python",
ISBN = "1001",
CheckOutDate = new System.DateTime(2021,02,15,08,30,10),
ReaderId = 10,
Lost = false
},
new Book
{
Id = 11,
Title = "The Pragmatic Programmer",
ISBN = "1002",
CheckOutDate = new System.DateTime(2021, 03, 09, 08, 30, 10),
ReaderId = 10,
Lost = false
},
new Book
{
Id = 12,
Title = "Modern Operating Systems",
ISBN = "1003",
CheckOutDate = new System.DateTime(2021, 03, 09, 08, 30, 10),
ReaderId = 11,
Lost = false
},
new Book
{
Id = 13,
Title = "C# Programming",
ISBN = "1004",
CheckOutDate = new System.DateTime(2021, 04, 21, 08, 30, 10),
ReaderId = 11,
Lost = false
}
);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Tivo.Hme.Host.Services
{
/// <summary>
/// Indicates an application needs the host to handle http requests
/// beyond the standard hme protocol defined urls.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class UsesHostHttpServicesAttribute : Attribute
{
}
}
|
using Memorama_Client.JuegoBase;
using System;
using static Memorama_Client.Servicios;
namespace Memorama_Client.JuegoMulti.ViewModels
{
public enum SlideCategoriesM
{
Cartas,
Animals,
Cars,
Foods
}
public class GameViewModelM : ObservableObjectM
{
public SlideCollectionViewModelM Slides { get; private set; }
public GameInfoViewModelM GameInfo { get; private set; }
public TimerViewModelM Timer { get; private set; }
public SlideCategoriesM Category { get; private set; }
public ServiciosCallBack calbacpapa;
private int numero;
public bool turno;
public GameViewModelM(SlideCategoriesM category, int numero, ServiciosCallBack callBack)
{
this.numero = numero;
Category = category;
SetupGame(category);
this.calbacpapa=callBack;
}
public GameViewModelM() { }
private void SetupGame(SlideCategoriesM category)
{
Slides = new SlideCollectionViewModelM(numero);
Timer = new TimerViewModelM(new TimeSpan(0, 0, 1));
GameInfo = new GameInfoViewModelM();
GameInfo.ClearInfo();
Slides.CreateSlides("Assets/" + category.ToString());
Slides.Memorize();
Timer.Start();
OnPropertyChanged("Slides");
OnPropertyChanged("Timer");
OnPropertyChanged("GameInfo");
}
public void ClickedSlide(object slide)
{
if (Slides.canSelect)
{
var selected = slide as PictureViewModelM;
Slides.SelectSlide(selected);
}
if (!Slides.areSlidesActive)
{
if (Slides.CheckIfMatched())
GameInfo.Award(); //Correct match
else
{
if (turno)
{
CartaEquivocada(calbacpapa);
}
GameInfo.Penalize();//Incorrect match
}
}
GameStatus();
}
private void GameStatus()
{
if (GameInfo.MatchAttempts < 0)
{
GameInfo.GameStatus(false);
Slides.RevealUnmatched();
Timer.Stop();
}
if (Slides.AllSlidesMatched)
{
GameInfo.GameStatus(true);
Timer.Stop();
}
}
public void Restart()
{
ControladorDeAudio.PlayIncorrecto();
SetupGame(Category);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CalculatorAndGuessingGame
{
/// <summary>
/// Interaction logic for Cone.xaml
/// </summary>
public partial class Cone : Page
{
public Cone()
{
InitializeComponent();
}
//Checks input and calculates area
private void Button_Click(object sender, RoutedEventArgs e)
{
if (double.TryParse(HeightBox.Text, out double height) && double.TryParse(RadiusBox.Text, out double radius))
{
if (HeightBox.Text != "" || RadiusBox.Text != "")
{
AreaBox.Text = (Math.PI * (radius * radius)*(height/3)).ToString();
}
}
}
}
}
|
using UnityEngine;
using System;
public class TriggerElement : TriggerControl
{
protected Predicate<Collider> m_Conditions;
protected enum TriggerState { Deactive, Active };
protected TriggerState m_State;
protected TriggerState State
{
set
{
m_State = value;
if (value == TriggerState.Deactive)
{
if (DeactiveTrigger != null) DeactiveTrigger();
}
else if (value == TriggerState.Active)
{
if (ActiveTrigger != null) ActiveTrigger();
}
if (Activity != null) Activity(value != TriggerState.Deactive);
}
}
public event Action<bool> Activity;
public event Action ActiveTrigger, DeactiveTrigger;
public event Action Enter, Exit;
protected override bool CheckConditions(Collider cld)
{
return m_Conditions == null || m_Conditions(cld);
}
protected virtual void OnSetDefault() { }
protected virtual void Enable() { }
public void SetDefault()
{
Enter = Exit = null;
m_Conditions = null;
m_IgnoreTriggerEnter = false;
Clear();
StopAllCoroutines();
OnSetDefault();
bool active = enabled && gameObject.activeInHierarchy;
if (m_State == TriggerState.Active)
{
if (!active) m_State = TriggerState.Deactive;
}
else
{
if (active) m_State = TriggerState.Active;
}
}
protected override void Disable()
{
m_IgnoreTriggerEnter = false;
State = TriggerState.Deactive;
}
private void OnEnable()
{
State = TriggerState.Active;
Enable();
}
protected override void OnEnterToTrigger(Collider sender, bool condition)
{
if (condition)
{
m_IgnoreTriggerEnter = true;
if (Enter != null) Enter();
}
}
protected override void OnExitFromTrigger(Collider sender, bool condition)
{
if (condition)
{
m_IgnoreTriggerEnter = false;
if (Exit != null) Exit();
}
}
}
|
using System.Windows.Navigation;
namespace MediCalcToGo.View
{
public partial class MainView : StateSavingView
{
// Constructor
public MainView() : base()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
//DataContext = App.ViewModel;
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
/*
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
*/
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Test
{
public class Explosion : Sprite
{
public Explosion(Texture2D texture, Vector2 centerOfSprite, Rectangle bounds) : base(texture,centerOfSprite,bounds,5,5,60)
{
}
public bool IsDone()
{
return animationPlayedOnce;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Trettim.Framework.Utility;
using Trettim.Settings;
using Trettim.Sicredi.DocumentLibrary.Resources;
using Trettim.Sicredi.DocumentLibrary.Services;
using Entities = Trettim.Sicredi.DocumentLibrary.Entities;
using System.IO;
namespace Trettim.Sicredi.DocumentLibrary.Admin
{
public partial class NewsDetail : PageBase
{
#region [ Page Load ]
protected void Page_Load(object sender, EventArgs e)
{
ServiceFactory.ValidatePagePermission();
ScriptManager.GetCurrent(this).RegisterPostBackControl(btnSave);
if (!Page.IsPostBack)
{
this.BindLabels();
this.BindFields();
}
}
#endregion
#region [ Bind ]
private void BindFields()
{
List<Entities.News> entities;
Entities.News entity;
entities = ServiceFactory.CreateConfigurationService.SelectNews(base.GetInt32("ID"), null, null);
if (entities.Count == 1)
{
entity = entities[0];
this.txtNewsTitle.Text = entity.Title;
this.txtNewsText.Text = entity.Text;
this.chkUserIsEnabled.Checked = entity.IsEnabled;
switch (base.Operation)
{
case "I":
upload.Visible = true;
image.Visible = false;
break;
case "U":
upload.Visible = false;
image.Visible = true;
imgFile.ImageUrl = entity.FilePath;
break;
case "D":
base.SetDeleteButton(btnSave);
upload.Visible = false;
image.Visible = true;
imgFile.ImageUrl = entity.FilePath;
break;
}
}
}
private void BindLabels()
{
this.lblTitle.Text = ResourceLabels.NewsDetailTitle;
this.lblNewsTitle.Text = ResourceLabels.Title;
this.lblNewsText.Text = ResourceLabels.Text;
this.lblUserIsEnabled.Text = ResourceLabels.Enabled;
this.btnSave.Text = ResourceButtons.SaveButtonLabel;
this.btnBack.Text = ResourceButtons.BackButtonLabel;
}
#endregion
#region [ Private Methods ]
public Entities.News SaveFile()
{
if (FileUploadControl.HasFile)
{
Entities.News result = new Entities.News();
string extension = Path.GetExtension(FileUploadControl.FileName);
string filename = Path.GetFileName(FileUploadControl.FileName);
string aux = filename.Replace(extension, "");
try
{
string saveName = aux + DateTime.Now.ToString("_ddMMyyyy") + extension;
FileUploadControl.SaveAs(Server.MapPath(Param.NewsDocumentLibrary) + saveName);
result.FilePath = Param.NewsDocumentLibrary + saveName;
}
catch (Exception ex)
{
throw ex;
}
return result;
}
return null;
}
#endregion
#region [ Event Handlers ]
protected void btnSave_Click(object sender, EventArgs e)
{
Entities.News entity = new Entities.News();
try
{
entity.NewsID = base.GetInt32("ID");
entity.Title = txtNewsTitle.Text;
entity.Text = txtNewsText.Text;
entity.IsEnabled = chkUserIsEnabled.Checked;
switch (base.Operation)
{
case "I":
entity = SaveFile();
if (entity != null)
{
entity.Title = txtNewsTitle.Text;
entity.Text = txtNewsText.Text;
entity.IsEnabled = chkUserIsEnabled.Checked;
ServiceFactory.CreateConfigurationService.InsertNews(entity);
}
break;
case "U":
ServiceFactory.CreateConfigurationService.UpdateNews(entity);
break;
case "D":
ServiceFactory.CreateConfigurationService.DeleteNews(entity);
break;
}
Response.Redirect("NewsList.aspx", false);
}
catch
{
base.SetMessage(lblMessage, MessageType.Error, ResourceMessages.UnexpectedErrorMessage);
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("NewsList.aspx", false);
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager : MonoBehaviour
{
// Start is called before the first frame update
public DotANIM dot;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Application.platform == RuntimePlatform.Android)
{
if (Input.GetKeyUp(KeyCode.Escape))
{
dot.menuback();
return;
}
}
}
}
|
namespace Kraken.Controllers.Api
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.AspNet.Authorization;
using Kraken.Models;
using Kraken.Services;
using Octopus.Client.Model;
[Authorize]
[Produces("application/json")]
[Route("api/releasebatches")]
public class ReleaseBatchesController : Controller
{
public ReleaseBatchesController(ApplicationDbContext context, IOctopusProxy octopusProxy)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (octopusProxy == null) throw new ArgumentNullException(nameof(octopusProxy));
_context = context;
_octopusProxy = octopusProxy;
}
// GET: api/ReleaseBatches
[HttpGet]
public IEnumerable<ReleaseBatch> GetReleaseBatches()
{
return _context.ReleaseBatches;
}
// GET: api/ReleaseBatches/5
[HttpGet("{id}", Name = "GetReleaseBatch")]
public async Task<IActionResult> GetReleaseBatch([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var releaseBatch = await _context.ReleaseBatches.Include(e => e.Items).SingleAsync(m => m.Id == id);
if (releaseBatch == null)
{
return HttpNotFound();
}
return Ok(releaseBatch);
}
// PUT: api/ReleaseBatches/5
[HttpPut("{id}")]
public async Task<IActionResult> PutReleaseBatch([FromRoute] int id, [FromBody] ReleaseBatch releaseBatch)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != releaseBatch.Id)
{
return HttpBadRequest();
}
_context.Entry(releaseBatch).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReleaseBatchExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ReleaseBatches
[HttpPost]
public async Task<IActionResult> PostReleaseBatch([FromBody] ReleaseBatch releaseBatch)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
_context.ReleaseBatches.Add(releaseBatch);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ReleaseBatchExists(releaseBatch.Id))
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetReleaseBatch", new { id = releaseBatch.Id }, releaseBatch);
}
// DELETE: api/ReleaseBatches/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteReleaseBatch([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var releaseBatch = await _context.ReleaseBatches.SingleAsync(m => m.Id == id);
if (releaseBatch == null)
{
return HttpNotFound();
}
_context.ReleaseBatches.Remove(releaseBatch);
await _context.SaveChangesAsync();
return Ok(releaseBatch);
}
// PUT: api/ReleaseBatches/5/LinkProject
[HttpPut("{id}/LinkProject")]
public async Task<IActionResult> LinkProjectToReleaseBatch([FromRoute] int id, [FromBody] string projectIdOrSlugOrName)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var projectResource = _octopusProxy.GetProject(projectIdOrSlugOrName);
if (projectResource == null)
{
return HttpBadRequest("Project Not Found");
}
var releaseBatchItem = new ReleaseBatchItem
{
ReleaseBatchId = id,
ProjectId = projectResource.Id,
ProjectName = projectResource.Name
};
_context.ReleaseBatchItems.Add(releaseBatchItem);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReleaseBatchExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
//TODO: check for existence and throw bad request
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// PUT: api/ReleaseBatches/5/UnlinkProject
[HttpPut("{id}/UnlinkProject")]
public async Task<IActionResult> UnlinkProjectFromReleaseBatch([FromRoute] int id, [FromBody] string projectIdOrSlugOrName)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
var projectResource = _octopusProxy.GetProject(projectIdOrSlugOrName);
if (projectResource == null)
{
return HttpBadRequest("Project Not Found");
}
var releaseBatchItem = await _context.ReleaseBatchItems.SingleOrDefaultAsync(e => e.ReleaseBatchId == id && e.ProjectId == projectResource.Id);
if (releaseBatchItem != null)
{
_context.ReleaseBatchItems.Remove(releaseBatchItem);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReleaseBatchExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
}
else if (!ReleaseBatchExists(id))
{
return HttpNotFound();
}
else
{
return HttpBadRequest();
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// PUT: api/ReleaseBatches/5/Sync
[HttpPut("{id}/Sync")]
public async Task<IActionResult> SyncReleaseBatch([FromRoute] int id, [FromBody] string environmentIdOrName = null)
{
if (!ReleaseBatchExists(id))
{
return new HttpStatusCodeResult(StatusCodes.Status404NotFound);
}
var releaseBatch = await _context.ReleaseBatches.Include(e => e.Items).SingleAsync(m => m.Id == id);
if (releaseBatch.Items != null && releaseBatch.Items.Any())
{
EnvironmentResource environment = null;
if (!String.IsNullOrEmpty(environmentIdOrName))
{
environment = _octopusProxy.GetEnvironment(environmentIdOrName);
if (environment == null)
{
return HttpBadRequest("Environment Not Found");
}
}
foreach (var releaseBatchItem in releaseBatch.Items)
{
ReleaseResource releaseResource;
if (environment == null)
{
releaseResource = _octopusProxy.GetLastestRelease(releaseBatchItem.ProjectId);
}
else
{
releaseResource = _octopusProxy.GetLastDeployedRelease(releaseBatchItem.ProjectId, environment.Id);
}
releaseBatchItem.ReleaseId = releaseResource?.Id;
releaseBatchItem.ReleaseVersion = releaseResource?.Version;
}
_context.Entry(releaseBatch).State = EntityState.Modified;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReleaseBatchExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return Ok(releaseBatch);
}
// POST api/ReleaseBatches/5/Deploy
[HttpPost("{id}/Deploy")]
public async Task<IActionResult> DeployReleaseBatch([FromRoute] int id, [FromBody] string environmentIdOrName)
{
var releaseBatch = await _context.ReleaseBatches.Include(e => e.Items).SingleAsync(m => m.Id == id);
var deployments = new List<DeploymentResource>();
var environment = _octopusProxy.GetEnvironment(environmentIdOrName);
if (environment == null)
{
return HttpBadRequest("Environment Not Found");
}
if (releaseBatch.Items != null && releaseBatch.Items.Any())
{
foreach (var releaseBatchItem in releaseBatch.Items.Where(releaseBatchItem => !string.IsNullOrEmpty(releaseBatchItem.ReleaseId)))
{
deployments.Add(_octopusProxy.DeployRelease(releaseBatchItem.ReleaseId, environment.Id));
}
}
return Ok(deployments);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ReleaseBatchExists(int id)
{
return _context.ReleaseBatches.Count(e => e.Id == id) > 0;
}
private readonly ApplicationDbContext _context;
private readonly IOctopusProxy _octopusProxy;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DexTool
{
/// <summary>
/// 对Byte数据进行解析、格式转化
/// </summary>
public class Byter
{
public byte[] bytes; // byte数据
public string HexStr; // 16进制数据
public string BinStr; // 二进制数据
public string Str_UTF8; // 普通字符串形式
public long _long; // long值
public byte[] LEB128_bytes; // 从bytes按LEB128格式解析后的byte数据
public string LEB128_HexStr;// 从bytes按LEB128格式解析后的16进制数据
public string LEB128_BinStr;// 从bytes按LEB128格式解析后的二进制数据
public string LEB128_Str; // LEB128格式表示的字符串
public long LEB128_long; // LEB128格式表示的值
public Byter(byte[] bytes)
{
this.bytes = bytes;
HexStr = ToHexStr(bytes);
BinStr = ToBinStr(bytes);
Str_UTF8 = ToStr_UTF8(bytes);
_long = To_Long(bytes);
LEB128_bytes = To_LEB128_Bytes(bytes);
LEB128_HexStr = To_LEB128_HexStr(bytes);
LEB128_BinStr = To_LEB128_BinStr(bytes);
LEB128_Str = To_LEB128_Str(bytes);
LEB128_long = To_LEB128_Long(bytes);
}
public String ToString()
{
string Str = "";
Str += "HexStr:" + "\t" + HexStr + "\r\n";
Str += "BinStr:" + "\t" + BinStr + "\r\n";
Str += "_long:" + "\t" + _long + "\r\n";
Str += "Str_UTF8:" + "\t" + Str_UTF8.Replace("\0", "\\0") + "\r\n";
Str += "\r\n";
Str += "LEB128_HexStr:" + "\t" + LEB128_HexStr + "\r\n";
Str += "LEB128_BinStr:" + "\t" + LEB128_BinStr + "\r\n";
Str += "LEB128_long:" + "\t" + LEB128_long + "\r\n";
Str += "LEB128_Str:" + "\t" + LEB128_Str.Replace("\0", "\\0") + "\r\n";
return Str;
}
public String ToString2(bool native = false)
{
string Str = "";
Str += "HexStr:" + "\t" + HexStr + "\r\n";
Str += "BinStr:" + "\t" + BinStr + "\r\n";
Str += "_long:" + "\t" + _long + "\r\n";
Str += "Str_UTF8:" + "\t" + Str_UTF8 + "\r\n";
Str += "\r\n";
Str += "LEB128_HexStr:" + "\t" + LEB128_HexStr + "\r\n";
Str += "LEB128_BinStr:" + "\t" + LEB128_BinStr + "\r\n";
Str += "LEB128_long:" + "\t" + LEB128_long + "\r\n";
Str += "LEB128_Str:" + "\t" + LEB128_Str + "\r\n";
return Str;
}
#region byte转16进制串
/// <summary>
/// 转化为16进制串
/// </summary>
public static string ToHexStr(byte[] B)
{
StringBuilder Str = new StringBuilder();
foreach (byte b in B)
{
Str.Append(ToHexStr(b) + " ");
}
return Str.ToString();
}
private static string ToHexStr(byte b)
{
return "" + ToChar(b / 16) + ToChar(b % 16);
}
private static char ToChar(int n)
{
if (0 <= n && n <= 9) return (char)('0' + n);
else if (10 <= n && n <= 35) return (char)('a' + n - 10);
else return ' ';
}
#endregion
#region 16进制串转byte
/// <summary>
/// 解析字符串为Bytes数组
/// </summary>
public static byte[] HexToBytes(string data)
{
byte[] B = new byte[data.Length / 2];
char[] C = data.ToLower().ToCharArray();
for (int i = 0; i < C.Length; i += 2)
{
byte b = HexToByte(C[i], C[i + 1]);
B[i / 2] = b;
}
return B;
}
/// <summary>
/// 每两个字母还原为一个字节
/// </summary>
private static byte HexToByte(char a1, char a2)
{
return (byte)( HexCValue(a1) * 16 + HexCValue(a2) );
}
/// <summary>
/// 0-9a-z映射为对应值
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private static int HexCValue(char c)
{
if ('0' <= c && c <= '9') return c - '0';
else if ('a' <= c && c <= 'z') return c - 'a' + 10;
else return 0;
}
#endregion
#region byte转2进制串
/// <summary>
/// 转化为二进制串
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static string ToBinStr(byte[] B)
{
StringBuilder Str = new StringBuilder();
foreach (byte b in B)
{
Str.Append(ToBinStr(b) + " ");
}
return Str.ToString();
}
private static string ToBinStr(byte b)
{
String Str = "";
for (int i = 0; i < 8; i++)
{
Str = (b % 2 == 1 ? "1" : "0") + Str;
b = (byte)((int)b >> 1);
}
return Str;
}
#endregion
#region byte转String
public static string ToStr_UTF8(byte[] B)
{
string str = Encoding.UTF8.GetString(B);
return str;
}
#endregion
/// <summary>
/// 转换LEB128表示的数值
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static long To_Long(byte[] B)
{
long N = -1;
for (int i = B.Length - 1; i >= 0; i--)
//foreach (byte b in B_LE128)
{
byte b = B[i];
if (N == -1) N = b;
else
{
N = (N << 8) + b;
}
}
return N;
}
#region byte转LE128格式String
public static byte[] To_LEB128_Bytes(byte[] B)
{
List<byte> L = new List<byte>();
foreach (byte b in B)
{
if (((int)b & 0x80) != 0) // 若最高位为1,则移除最高位,继续读取下一个byte
{
L.Add((byte)((int)b & 0x7f));
}
else
{ // 若最高位为0,则不再读取下一个byte
L.Add(b);
break;
}
}
return L.ToArray<byte>();
}
/// <summary>
/// 转换LEB128表示的16进制字符串
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static string To_LEB128_HexStr(byte[] B)
{
byte[] B_LE128 = To_LEB128_Bytes(B);
string str = ToHexStr(B_LE128);
return str;
}
/// <summary>
/// 转换LEB128表示的2进制字符串
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static string To_LEB128_BinStr(byte[] B)
{
byte[] B_LE128 = To_LEB128_Bytes(B);
string str = ToBinStr(B_LE128);
return str;
}
# region LEB128有效数据还原
private static byte[] To_LEB128_Bytes_pre(byte[] B)
{
List<byte> pre = new List<byte>();
List<bool> byteTmp = new List<bool>();
byte[] B_LE128 = To_LEB128_Bytes(B);
foreach (byte b in B_LE128) // 读取数据中所有byte
{
List<bool> bit = To_LEB128_Bit(b); // 获取LEB128格式表示的有效位
foreach (bool bi in bit)
{
byteTmp.Add(bi); // 按位添加至byteTmp中
if (byteTmp.Count == 8)
{
byte preByte = To_byte(byteTmp); // 每8位还原为一个字节
pre.Add(preByte);
byteTmp.Clear();
}
}
}
if (byteTmp.Count > 0) // 所有字节读取完成,剩余位大于0不足8位
{
byte preByte = To_byte(byteTmp); // 还原为一个字节
if(preByte != 0) pre.Add(preByte); // 不足8为且为0时不添加
}
return pre.ToArray();
}
/// <summary>
/// 将byte转化为2进制形式
/// </summary>
private static List<bool> To_LEB128_Bit(byte b0)
{
int b = (int) b0;
List<bool> BitL = new List<bool>();
for (int i = 0; i < 7; i++)
{
if ((b & 1) != 0) BitL.Add(true);
else BitL.Add(false);
b = b >> 1;
}
return BitL;
}
/// <summary>
/// 将bit数据转化为byte,最高位在最后
/// </summary>
private static byte To_byte(List<bool> BitL)
{
int n = 0;
for(int i= BitL.Count-1; i>=0; i--)
{
n = (n << 1) | (BitL[i] ? 1 : 0);
}
return (byte)n;
}
#endregion
/// <summary>
/// 转换LEB128表示的字符串
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static string To_LEB128_Str(byte[] B)
{
byte[] B_pre = To_LEB128_Bytes_pre(B); // 还原LEB128编码为原数据
string str = Encoding.UTF8.GetString(B_pre); // 还原为字符串
return str;
}
/// <summary>
/// 转换LEB128表示的数值
/// </summary>
/// <param name="B"></param>
/// <returns></returns>
public static long To_LEB128_Long(byte[] B)
{
long N = -1;
byte[] B_pre = To_LEB128_Bytes_pre(B); // 还原LEB128编码为原数据
for (int i = B_pre.Length - 1; i >= 0; i--)
//foreach (byte b in B_LE128)
{
byte b = B_pre[i];
if (N == -1) N = b;
else
{
N = (N << 8) + b;
}
}
return N;
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Yarn.Unity;
public class yarnCommands : MonoBehaviour {
public GameObject ike;
private GameObject ike2;
public Canvas theCanvas;
public Text theText;
public GameObject laura;
private GameObject laura2;
public GameObject brad;
private GameObject brad2;
private Transform thepos;
private bool boy;
private bool girl;
// Use this for initialization
void Start () {
// thepos = new Vector2(-10.6f, 226.8501f)
}
// Update is called once per frame
void Update () {
}
[YarnCommand("sceneLoader")]
public void sceneLoader(string theScene)
{
SceneManager.LoadScene(theScene);
}
[YarnCommand("ikein")]
public void ikein()
{
ike2 = Instantiate(ike);
ike2.transform.position = new Vector2(-10.6f, 240.8501f);
if (brad2 != null)
{
Destroy(brad2);
}
if (laura2 != null)
{
Destroy(laura2);
}
ike2.transform.SetParent(theCanvas.transform, false);
}
[YarnCommand("ikeout")]
public void ikeout()
{
Destroy(ike2);
}
[YarnCommand("laurain")]
public void laurain()
{
if (brad2 != null)
{
Destroy(brad2);
}
if (ike2 != null)
{
Destroy(ike2);
}
laura2 = Instantiate(laura);
laura2.transform.position = new Vector2(-10.6f, 240.8501f);
laura2.transform.SetParent(theCanvas.transform, false);
}
[YarnCommand("lauraout")]
public void lauraout()
{
Destroy(laura2);
}
public void dotheQuit()
{
Application.Quit();
}
[YarnCommand("bradin")]
public void bradin()
{
if (laura2 != null)
{
Destroy(laura2);
}
if (ike2 != null)
{
Destroy(ike2);
}
brad2 = Instantiate(brad);
brad2.transform.position = new Vector2(-10.6f, 240.8501f);
brad2.transform.SetParent(theCanvas.transform, false);
}
[YarnCommand("bradout")]
public void bradout()
{
Destroy(brad2);
}
[YarnCommand("setboy")]
public void setboy()
{
boy = true;
girl = false;
}
[YarnCommand("setgirl")]
public void setgirl()
{
boy = false;
girl = true;
}
[YarnCommand("setnb")]
public void setnb()
{
boy = false;
girl = false;
}
[YarnCommand("getboy")]
public bool getboy()
{
return boy;
}
[YarnCommand("getgirl")]
public bool getgirl()
{
return girl;
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game.Mono;
[Attribute38("ConfigFile")]
public class ConfigFile : MonoClass
{
public ConfigFile(IntPtr address) : this(address, "ConfigFile")
{
}
public ConfigFile(IntPtr address, string className) : base(address, className)
{
}
public void Clear()
{
base.method_8("Clear", Array.Empty<object>());
}
public bool Delete(string key, bool removeEmptySections)
{
object[] objArray1 = new object[] { key, removeEmptySections };
return base.method_11<bool>("Delete", objArray1);
}
public Line FindEntry(string fullKey)
{
object[] objArray1 = new object[] { fullKey };
return base.method_14<Line>("FindEntry", objArray1);
}
public int FindEntryIndex(string fullKey)
{
object[] objArray1 = new object[] { fullKey };
return base.method_11<int>("FindEntryIndex", objArray1);
}
public int FindSectionIndex(string sectionName)
{
object[] objArray1 = new object[] { sectionName };
return base.method_11<int>("FindSectionIndex", objArray1);
}
public bool FullLoad(string path)
{
object[] objArray1 = new object[] { path };
return base.method_11<bool>("FullLoad", objArray1);
}
public string GenerateText()
{
return base.method_13("GenerateText", Array.Empty<object>());
}
public bool Get(string key, bool defaultVal)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { key, defaultVal };
return base.method_10<bool>("Get", enumArray1, objArray1);
}
public int Get(string key, int defaultVal)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.I4 };
object[] objArray1 = new object[] { key, defaultVal };
return base.method_10<int>("Get", enumArray1, objArray1);
}
public float Get(string key, float defaultVal)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.R4 };
object[] objArray1 = new object[] { key, defaultVal };
return base.method_10<float>("Get", enumArray1, objArray1);
}
public string Get(string key, string defaultVal)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.String };
object[] objArray1 = new object[] { key, defaultVal };
return base.method_12("Get", enumArray1, objArray1);
}
public List<Line> GetLines()
{
Class267<Line> class2 = base.method_14<Class267<Line>>("GetLines", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public string GetPath()
{
return base.method_13("GetPath", Array.Empty<object>());
}
public bool Has(string key)
{
object[] objArray1 = new object[] { key };
return base.method_11<bool>("Has", objArray1);
}
public bool LightLoad(string path)
{
object[] objArray1 = new object[] { path };
return base.method_11<bool>("LightLoad", objArray1);
}
public bool Load(string path, bool ignoreUselessLines)
{
object[] objArray1 = new object[] { path, ignoreUselessLines };
return base.method_11<bool>("Load", objArray1);
}
public Line RegisterEntry(string fullKey)
{
object[] objArray1 = new object[] { fullKey };
return base.method_14<Line>("RegisterEntry", objArray1);
}
public bool Save(string path)
{
object[] objArray1 = new object[] { path };
return base.method_11<bool>("Save", objArray1);
}
public bool Set(string key, bool val)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { key, val };
return base.method_10<bool>("Set", enumArray1, objArray1);
}
public bool Set(string key, object val)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Class };
object[] objArray1 = new object[] { key, val };
return base.method_10<bool>("Set", enumArray1, objArray1);
}
public bool Set(string key, string val)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.String };
object[] objArray1 = new object[] { key, val };
return base.method_10<bool>("Set", enumArray1, objArray1);
}
public List<Line> m_lines
{
get
{
Class267<Line> class2 = base.method_3<Class267<Line>>("m_lines");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public string m_path
{
get
{
return base.method_4("m_path");
}
}
[Attribute38("ConfigFile.Line")]
public class Line : MonoClass
{
public Line(IntPtr address) : this(address, "Line")
{
}
public Line(IntPtr address, string className) : base(address, className)
{
}
public string m_fullKey
{
get
{
return base.method_4("m_fullKey");
}
}
public string m_lineKey
{
get
{
return base.method_4("m_lineKey");
}
}
public bool m_quoteValue
{
get
{
return base.method_2<bool>("m_quoteValue");
}
}
public string m_raw
{
get
{
return base.method_4("m_raw");
}
}
public string m_sectionName
{
get
{
return base.method_4("m_sectionName");
}
}
public ConfigFile.LineType m_type
{
get
{
return base.method_2<ConfigFile.LineType>("m_type");
}
}
public string m_value
{
get
{
return base.method_4("m_value");
}
}
}
public enum LineType
{
UNKNOWN,
COMMENT,
SECTION,
ENTRY
}
}
}
|
using System;
using NUnit.Framework;
namespace TestsPayroll.Social
{
[TestFixture()]
public class SocialEmployeePaymentHappyTest
{
[Test()]
public void Employee_Insurance_Payment_For_2_000_CZK_Base_Is_X_CZK()
{
}
[Test()]
public void Employee_Insurance_Payment_For_10_000_CZK_Base_Is_X_CZK()
{
}
[Test()]
public void Employee_Insurance_Payment_For_0_CZK_Base_Is_0_CZK()
{
}
[Test()]
public void Employee_Insurance_Payment_For_Obligatory_Base_Is_X_CZK()
{
}
[Test()]
public void Employee_Insurance_Payment_For_Annual_Max_Base_Is_X_CZK()
{
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DivideAndConque;
namespace AlgTest
{
[TestClass]
public class DivConqueTest
{
[TestMethod]
public void TestPow()
{
Pow target = new Pow();
double actual = target.pow(2, 3);
Assert.AreEqual(8.0, actual);
}
[TestMethod]
public void TestMedianOf2Array()
{
MedianOf2Array target = new MedianOf2Array();
int[] a = new int[] { 1, 3, 5, 7, 9 };
int[] b = new int[] { 2, 4, 6, 8, 10 };
int actual = target.FindMedian(a, b);
Assert.AreEqual(5, actual);
}
[TestMethod]
public void TestTopKElement()
{
TopKElement target = new TopKElement();
int[] input = new[] { 1,9,3,10,2,6,5,8,7,4};
target.FindTopK(input, 3);
Assert.IsTrue(input[0] > 7);
Assert.IsTrue(input[1] > 7);
Assert.IsTrue(input[2] > 7);
input = new[] { 1, 9, 3, 10, 2, 6, 5, 8, 7, 4 };
target.FindTopK(input, 4);
Assert.IsTrue(input[0] > 6);
Assert.IsTrue(input[1] > 6);
Assert.IsTrue(input[2] > 6);
Assert.IsTrue(input[3] > 6);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demoUISpecTests.DataStructure
{
public class Formdata
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string NewPwd { get; set; }
public string ConfirmPwd { get; set; }
public string Dob { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
public string Number { get; set; }
public string RecoveryEmail { get; set; }
public string Location { get; set; }
}
}
|
using System;
using System.IO;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DairyFarmWebApp.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Courses",
columns: table => new
{
CategoryID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CategoryCode = table.Column<string>(nullable: true),
CategoryName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Courses", x => x.CategoryID);
});
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
CompanyID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CompanyName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.CompanyID);
});
migrationBuilder.CreateTable(
name: "StudentCourses",
columns: table => new
{
ProductID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductName = table.Column<string>(nullable: true),
Price = table.Column<int>(nullable: false),
CategoryID = table.Column<int>(nullable: false),
CompanyID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StudentCourses", x => x.ProductID);
table.ForeignKey(
name: "FK_StudentCourses_Courses_CategoryID",
column: x => x.CategoryID,
principalTable: "Courses",
principalColumn: "CategoryID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_StudentCourses_Students_CompanyID",
column: x => x.CompanyID,
principalTable: "Students",
principalColumn: "CompanyID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Branches",
columns: table => new
{
OrderID = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductID = table.Column<int>(nullable: false),
Quantity = table.Column<int>(nullable: false),
CustomerName = table.Column<string>(nullable: true),
ContactNo = table.Column<string>(nullable: true),
OrderDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Branches", x => x.OrderID);
table.ForeignKey(
name: "FK_Branches_StudentCourses_ProductID",
column: x => x.ProductID,
principalTable: "StudentCourses",
principalColumn: "ProductID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Branches_ProductID",
table: "Branches",
column: "ProductID");
migrationBuilder.CreateIndex(
name: "IX_StudentCourses_CategoryID",
table: "StudentCourses",
column: "CategoryID");
migrationBuilder.CreateIndex(
name: "IX_StudentCourses_CompanyID",
table: "StudentCourses",
column: "CompanyID");
var sqlFile = Path.Combine(".\\Data", @"dairyqueries.sql");
migrationBuilder.Sql(File.ReadAllText(sqlFile));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Branches");
migrationBuilder.DropTable(
name: "StudentCourses");
migrationBuilder.DropTable(
name: "Courses");
migrationBuilder.DropTable(
name: "Students");
}
}
}
|
using System;
using Models;
namespace Atividade_1
{
class Program
{
static void Main(string[] args)
{
ListaConvidados convidados = new ListaConvidados();
string resposta = "S";
Console.WriteLine ("Este é o programa para a confirmação de prensença da minha festa");
do{
string nome;
int idade;
string telefone;
Console.WriteLine ("Insira seu nome: ");
nome = Console.ReadLine ();
Console.WriteLine ("Insira sua idade: ");
idade = int.Parse (Console.ReadLine ());
Console.WriteLine ("Insira seu telefone: ");
telefone = Console.ReadLine ();
Convidado convidado = new Convidado (nome, idade, telefone);
if(convidados.addConvidado(convidado))
Console.WriteLine("Convidado incluido.");
else
Console.WriteLine("Convidado recusado.");
Console.WriteLine("Inserir outro convidado? (S/N) ");
resposta = Console.ReadLine();
Console.Clear();
}while(resposta.ToUpper () == "S");
convidados.mostraConvidados();
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Salad.cs" company="">
//
// </copyright>
// <summary>
// The salad.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace RestaurantManager.Models
{
using RestaurantManager.Interfaces;
/// <summary>
/// The salad.
/// </summary>
internal class Salad : Meal, ISalad
{
/// <summary>
/// The contains pasta.
/// </summary>
private readonly bool containsPasta;
/// <summary>
/// Initializes a new instance of the <see cref="Salad"/> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="price">
/// The price.
/// </param>
/// <param name="calories">
/// The calories.
/// </param>
/// <param name="quantity">
/// The quantity.
/// </param>
/// <param name="unit">
/// The unit.
/// </param>
/// <param name="time">
/// The time.
/// </param>
/// <param name="isVegan">
/// The is vegan.
/// </param>
/// <param name="containsPasta">
/// The contains pasta.
/// </param>
public Salad(
string name,
decimal price,
int calories,
int quantity,
int time,
bool isVegan,
bool containsPasta)
: base(name, price, calories, quantity, time, isVegan)
{
this.containsPasta = containsPasta;
}
/// <summary>
/// Gets a value indicating whether contains pasta.
/// </summary>
public bool ContainsPasta
{
get
{
return this.containsPasta;
}
}
}
} |
using System.Collections.Generic;
using Business.Generics;
using Core.Utilities.Results;
using Entities.Concrete;
using Microsoft.AspNetCore.Http;
namespace Business.Abstract
{
public interface IProductImagesService:IGenericImagesService<ProductsImage>
{
IResult AddAsync(List<IFormFile> file, ProductsImage productsImage);
IResult DeleteById(int id);
}
} |
using UnityEngine;
using System.Collections;
public class OppgraderForsvarselement : MonoBehaviour
{
// gameobject referanser
public GameObject detectionArea;
private int maxLevel = 4;
private int oppgraderingKostnad;
private Vector3 nyStorrelse;
//referanser til originalstørrelse
private float rangeScaleX;
private float rangeScalez;
// script referanser
private Forsvarselement forsvarselement;
void Start()
{
// cacher referanser
forsvarselement = GetComponent<Forsvarselement>();
}
public void oppgrader()
{
// finner oppgraderingkostnad basert på level
oppgraderingKostnad = forsvarselement.oppgraderingKostnad * forsvarselement.level;
// hvis level er mindre enn maxlevel og det er nok penger til å oppgradere
if (forsvarselement.level < maxLevel && oppgraderingKostnad <= GameManager.instance.antallPenger)
{
// øker level med 1
forsvarselement.level++;
// sjekker level og gjør ting basert på det
// lot det være en switch her tilfelle levels skal ha unike karakteristikker
switch (forsvarselement.level)
{
case 2:
//Henter nåværende størrelse;
Vector3 SwAndRange = detectionArea.transform.localScale;
// lager ny størrelse til skyterange-gameobjekt
SwAndRange.x = (detectionArea.transform.localScale.x *1.5f);
SwAndRange.z = (detectionArea.transform.localScale.z *1.1f);
detectionArea.transform.localScale = SwAndRange;
// sender med nye verdier til metode som oppgraderer verdiene
oppgraderVerdier(oppgraderingKostnad);
break;
case 3:
//Henter nåværende størrelse;
Vector3 SwAndRange2 = detectionArea.transform.localScale;
// lager ny størrelse til skyterange-gameobjekt
SwAndRange2.x = (detectionArea.transform.localScale.x *1.8f);
SwAndRange2.z = (detectionArea.transform.localScale.z *1.15f);
detectionArea.transform.localScale = SwAndRange2;
// sender med nye verdier til metode som oppgraderer verdiene
oppgraderVerdier(oppgraderingKostnad);
break;
case 4:
//Henter nåværende størrelse;
Vector3 SwAndRange3 = detectionArea.transform.localScale;
// lager ny størrelse til skyterange-gameobjekt
SwAndRange3.x = (detectionArea.transform.localScale.x *1.6f);
SwAndRange3.z = (detectionArea.transform.localScale.z *1.2f);
detectionArea.transform.localScale = SwAndRange3;
// sender med nye verdier til metode som oppgraderer verdiene
oppgraderVerdier(oppgraderingKostnad);
break;
}
}
else
{
// TODO gi feilmeldinger til spilleren
}
}
public void oppgraderVerdier(int oPris)
{
// øker statistikk verdier
forsvarselement.skade *= 1.5f;
forsvarselement.helse *= 1.5f;
// fjerner oppgraderingskostnad fra penger
GameManager.instance.penger.fjernPenger(oPris);
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
using BookShelf.Services;
using BookShelf.Models.BookViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using BookShelf.Models;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BookShelf.API
{
[Route("api/[controller]")]
[Authorize]
public class BooksController : Controller
{
private readonly IBookService _bookService;
private readonly UserManager<ApplicationUser> _userManager;
public BooksController(IBookService bookService, UserManager<ApplicationUser> userManager)
{
_bookService = bookService;
_userManager = userManager;
}
// POST api/books
[HttpPost]
public int Post(BookCreateModel model)
{
if (!ModelState.IsValid)
throw new Exception("Form is invalid.");
return _bookService.AddBook(model, _userManager.GetUserId(User));
}
// PUT api/books/5
[HttpPut("{id}")]
public void Put(int id, bool onLoan) => _bookService.UpdateLoanStatus(id, onLoan, _userManager.GetUserId(User));
// DELETE api/books/5
[HttpDelete("{id}")]
public void Delete(int id) => _bookService.Delete(id, _userManager.GetUserId(User));
}
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VwExtraPatientInformations
{
public int Id { get; set; }
public string Hl7Typ { get; set; }
public DateTime? Hl7Erstellungsdatum { get; set; }
public string PatientId { get; set; }
public string Fallnummer { get; set; }
public DateTime? Erfassungsdatum { get; set; }
public string Nachname { get; set; }
public string Vorname { get; set; }
public string Titel { get; set; }
public string Geburtsdatum { get; set; }
public string Geschlecht { get; set; }
public string Patientenstatus { get; set; }
public string Station { get; set; }
public string Fachbateilung { get; set; }
public string BehandelnderArzt { get; set; }
public string AufnahmeDatum { get; set; }
public string EntlassungsDatum { get; set; }
public string Hl7Message { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Dawnfall.Helper.Editor
{
public static class HelperEditor
{
public static List<T> LoadObjectsFromFolder<T>(string[] folders) where T : Object
{
string searchFilter = "t:" + typeof(T).ToString();
Debug.Log(searchFilter);
string[] guids = (folders == null) ? AssetDatabase.FindAssets(searchFilter) : AssetDatabase.FindAssets(searchFilter, folders);
Debug.Log("paths count: " + guids.Length);
if (guids.Length > 0)
Debug.Log(guids[0]);
List<T> result = new List<T>();
foreach (string id in guids)
{
T asset = AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(id));
if (asset != null)
result.Add(asset);
}
Debug.Log(result.Count);
return result;
}
}
} |
using System;
namespace Football.DAL.Entities
{
public class PlayerMatch:IEntityBase
{
public int MatchId { get; set; }
public Match Match { get; set; }
public int? PlayerId { get; set; }
public Player Player { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.