text stringlengths 13 6.01M |
|---|
using Globalization;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Framework.Extensions
{
public static class ModelStateExtensions
{
public static IDictionary<string, string[]> GetErrors(this ModelStateDictionary modelState)
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState), $"{nameof(modelState)} {ApplicationResources.CannotBeNull}");
}
var errors = modelState.Where(entry => entry.Value.Errors.Any()).ToDictionary(entry => entry.Key, entry => entry.Value.Errors.Select(x => x.ErrorMessage).Distinct().ToArray());
return errors;
}
}
}
|
using System;
namespace Facade
{
class Program
{
static void Main(string[] args)
{
var blobService = new BlobService();
blobService.Save("https://oneFrive/abc/", "ProjectDocuments", "NewDocument1");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesAndEvents
{
public delegate int DExc05();
internal class Exc05
{
public static void MainExc05()
{
int a = -1;
int b = 1;
DExc05 Fib = () =>
{
int c = a + b;
a = b;
b = c;
if (c == 0)
{
a = 0;
b = 1;
return 1;
}
return c;
};
for(int i = 0; i < 10; i++)
{
Console.WriteLine(Fib());
}
}
}
}
|
using System;
using IMP.Core;
using Imp.Core.Domain.Users;
namespace Imp.Core.Domain.Files
{
/// <summary>
/// file
/// </summary>
public class File : BaseEntity
{
/// <summary>
/// file name
/// </summary>
public string Name { get; set; }
/// <summary>
/// owner user id
/// </summary>
public string OwnerId { get; set; }
/// <summary>
/// create date
/// </summary>
public DateTime CreateDate { get; set; }
/// <summary>
/// last modified date
/// </summary>
public DateTime? LastModifyDate { get; set; }
/// <summary>
/// directory id
/// </summary>
public string DirectoryId { get; set; }
/// <summary>
/// is deleted
/// </summary>
public bool Deleted { get; set; }
/// <summary>
/// owner entity
/// </summary>
public virtual User Owner { get; set; }
/// <summary>
/// directory entity
/// </summary>
public virtual Directory Directory { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CourseHunter_61_Static
{
public class Calculator
{
public static double CalcTriangleArea(double sizeSideAB, double sizeSideBC, double sizeSideCA)
{
//Semiperimeter
double semiperimeter = (sizeSideAB + sizeSideBC + sizeSideCA) / 2;
//Area formula gerona
//double square = Math.Sqrt(semiperimeter * (semiperimeter - sizeSideAB) * (semiperimeter - sizeSideBC) * (semiperimeter - sizeSideCA));
//return square;
//Не обязательно новая переменная.
return Math.Sqrt(semiperimeter * (semiperimeter - sizeSideAB) * (semiperimeter - sizeSideBC) * (semiperimeter - sizeSideCA));
}
public double CalcTriangleArea(double sizeH, double sizeSemihypotenuse)
{
return ((sizeSemihypotenuse / 2) * sizeH);
}
public double CalcTriangleArea(double sizeSideAB, double sizeSideBC, int alpfa)
{
double rads = alpfa * Math.PI * 180;
return 0.5 * sizeSideAB * sizeSideBC * Math.Sin(rads);
}
public double Average(int[] numbers)
{
double summ = 0;
foreach (var item in numbers)
{
summ += item;
}
return summ / numbers.Length;
}
public static double Average2(params int[] numbers)
{
double summ = 0;
foreach (var item in numbers)
{
summ += item;
}
return summ / numbers.Length;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_1
{
class uppercheck
{
public void solution()
{
int flag = 0;
string word;
Console.WriteLine("Enter the word to check");
word = Console.ReadLine();
string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
for (int i = 0; i < word.Length; i++)
{
if (Char.IsUpper(word[i]) == true)
{
continue;
}
if (Char.IsDigit(word[i]))
{
flag = 1;
break;
}
foreach (var item in specialChar)
{
if (word.Contains(item))
{
flag = 1;
break;
}
}
}
if (flag == 1)
{
Console.WriteLine("False");
}
else
{
Console.WriteLine("True");
}
}
}
}
|
using UnityEngine;
using System.Collections;
using Frederick.ProjectAircraft;
public enum NPC_STATE
{
DI_MIAN_NPC,
FEI_XING_NPC,
ZAI_TI_NPC,
SHUI_QIANG_NPC,
BOSS_NPC,
DaEYu_ZXiong_NPC
}
public enum AudioNpcState
{
NULL,
Xiong,
ShiZi,
LaoHu,
ChangJingLu
}
public class NpcMoveCtrl : MonoBehaviour {
public AudioNpcState AudioState = AudioNpcState.NULL;
AudioSource AudioSourceNpc;
public NPC_STATE NPC_Type = NPC_STATE.DI_MIAN_NPC;
public bool IsDanCheLvNpc;
public bool IsDonotAimPlayerFire;
public GameObject BuWaWaObj;
public GameObject ExplodeObj;
public GameObject NpcSimpleBulletObj;
public GameObject NpcSimpleBulletObjFire_2;
public Transform SpawnBulletTran;
public Transform SpawnBulletTranFire_2;
public ZaiTiNpcCtrl []ZaiTiScript;
[Range(-5f, 5f)] public float HighOffset;
public bool IsTeShuZiDanHaiDao = false;
public bool IsTeShuZiDanShuiQiang = false;
[Range(1f, 10000f)] public float BuWaWaPowerVal = 500f;
public GameObject AudioHitNpcObj;
public GameObject AudioNpcFireObj_1;
public GameObject AudioNpcFireObj_2;
public AudioClip AudioHitNpc;
public AudioClip AudioNpcFire_1;
public AudioClip AudioNpcFire_2;
public GameObject SpawnPointObj;
float ShuiQiangNpcFlyTime = 2.5f;
bool IsFireNpc;
bool IsMoveNpc;
int NextMarker;
float MoveSpeed = 1f;
float OldMoveSpeed = 1f;
public static float MinDistance = 0.5f;
float FireDistance = 10f;
Animator AnimatorNpc;
Transform NpcPathTran;
Transform WaterwheelPlayer;
bool IsDoRootAction;
bool IsPlayRun_3;
bool IsDeadNpc;
float RootTimeVal;
float RunAniSpeed;
NpcMark MarkScripte;
NpcRunState RunStateVal;
Transform ZhangAiTranAimVal;
Transform ZhangAiTranObjVal;
int PreMarker;
bool IsLoopMovePath;
bool IsBackStartPoint;
bool IsGetMarkPos;
Vector3 AimMarkPos;
bool IsDoFireAction;
bool IsMoveFlyNpcToCam;
bool IsStartMoveFlyNpcToCam;
float RandVal_x;
float RandVal_y;
float RandVal_z;
Transform AimCuBeTranFly;
bool IsMoveByITween;
bool IsNiXingAiPath;
bool IsMoveToAiPath;
const float LerpForwardVal = 5f;
Transform NpcAiMarkTran;
Transform NpcAiPathTran;
Transform NpcTran;
int ZaiTiNpcDeadNum;
float SpawnTime;
const int MaxZaiTiZhengXing = 5;
const int MaxZaiTiNiXing = 5;
public static GameObject [] ZaiTiZhengXingObj;
public static GameObject [] ZaiTiNiXingObj;
bool IsCheckPlayerPos = true;
bool IsHandleNpc;
NetworkView netView;
Vector3 PositionCur;
Quaternion RotationCur;
bool IsMakeEYuMvToplayer;
public static Transform TranCamera;
AudioSource AudioSourceBoss;
Rigidbody RigObj;
bool IsDiLeiNpc;
bool IsMoveLeft;
bool IsMoveRight;
bool IsPlayerKillNpc;
bool IsMoveToEndPoint;
float TimeZaiTiPos;
Vector3 ZaiTiOldPos;
float BoxColSizeYVal = 2f;
bool IsPlayerFireNpc;
bool IsMoveZaiTiNpcItween;
public static bool CheckIsSpawnZhengXingZaiTiNpc()
{
int objNum = 0;
if (ZaiTiZhengXingObj == null) {
ZaiTiZhengXingObj = new GameObject[MaxZaiTiZhengXing];
}
int max = ZaiTiZhengXingObj.Length;
for (int i = 0; i < max; i++) {
if(ZaiTiZhengXingObj[i] != null)
{
objNum++;
}
}
if(objNum < MaxZaiTiZhengXing)
{
return true;
}
return false;
}
void FillZaiTiZhengXingObj()
{
int max = ZaiTiZhengXingObj.Length;
for (int i = 0; i < max; i++) {
if(ZaiTiZhengXingObj[i] == null)
{
ZaiTiZhengXingObj[i] = gameObject;
return;
}
}
}
public static bool CheckIsSpawnNiXingZaiTiNpc()
{
int objNum = 0;
if (ZaiTiNiXingObj == null) {
ZaiTiNiXingObj = new GameObject[MaxZaiTiNiXing];
}
int max = ZaiTiNiXingObj.Length;
for (int i = 0; i < max; i++) {
if(ZaiTiNiXingObj[i] != null)
{
objNum++;
}
}
if(objNum < MaxZaiTiNiXing)
{
return true;
}
return false;
}
void FillZaiTiNiXingObj()
{
int max = ZaiTiNiXingObj.Length;
for (int i = 0; i < max; i++) {
if(ZaiTiNiXingObj[i] == null)
{
ZaiTiNiXingObj[i] = gameObject;
return;
}
}
}
void Awake()
{
SetIsShuiLeiNpc();
if (TranCamera == null) {
TranCamera = Camera.main.transform;
}
SpawnTime = Time.time;
if (GlobalData.GetInstance().gameMode == GameMode.OnlineMode) {
netView = GetComponent<NetworkView>();
netView.stateSynchronization = NetworkStateSynchronization.Off;
}
RigObj = rigidbody;
if(ZaiTiZhengXingObj == null)
{
ZaiTiZhengXingObj = new GameObject[MaxZaiTiZhengXing];
}
if(ZaiTiNiXingObj == null)
{
ZaiTiNiXingObj = new GameObject[MaxZaiTiNiXing];
}
if(NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC)
{
if (Random.Range(0, 100) % 2 == 0) {
IsMoveLeft = true;
}
else {
IsMoveRight = true;
}
CreateAudioSourceBoss();
NPC_Type = NPC_STATE.ZAI_TI_NPC;
BuWaWaObj = null;
BoxCollider[] boxColArray = GetComponents<BoxCollider>();
for (int i = 0; i < boxColArray.Length; i++) {
Vector3 centerPos = boxColArray[i].center;
centerPos.y = -HighOffset + 0.2f;
boxColArray[i].center = centerPos;
}
}
else {
BoxColSizeYVal = GetComponent<BoxCollider>().size.y;
}
NpcTran = transform;
NpcTran.parent = GameCtrlXK.MissionCleanup;
if(BuWaWaObj != null)
{
BuWaWaObj.SetActive(false);
Rigidbody rigObj = BuWaWaObj.GetComponent<Rigidbody> ();
if (rigObj == null) {
rigObj.name = "null";
}
}
CreateAudioSourceNpc();
if (SpawnBulletTran == null && NPC_Type != NPC_STATE.ZAI_TI_NPC) {
Debug.LogError("SpawnBulletTran is null");
SpawnBulletTran.name = "null";
}
AnimatorNpc = GetComponent<Animator>();
ResetActionInfo();
if (IsDanCheLvNpc) {
IsDonotAimPlayerFire = true;
}
if (IsTeShuZiDanShuiQiang) {
NpcSimpleBulletObj.SetActive(false);
}
}
void OnTriggerEnter(Collider other)
{
if (!IsHandleNpc){
return;
}
HandleHitShootedPlayer(other.gameObject, 0);
}
void CheckNpcDownHit()
{
if (NPC_Type != NPC_STATE.ZAI_TI_NPC) {
return;
}
RaycastHit hitInfo;
Vector3 startPos = NpcTran.position + Vector3.up * 10f;
Physics.Raycast(startPos, Vector3.down, out hitInfo, 10f, GameCtrlXK.GetInstance().WaterLayerMask);
if (hitInfo.collider != null
&& !hitInfo.collider.isTrigger
&& hitInfo.collider.GetComponent<BoxCollider>() != null){
Vector3 posTmp = hitInfo.point + new Vector3(0f, HighOffset, 0f) + new Vector3(0f, 0.1f, 0f);
NpcTran.position = posTmp;
}
}
// Update is called once per frame
void Update()
{
CheckDistancePlayerCross();
if (!StartBtCtrl.GetInstanceP1().CheckIsActivePlayer()) {
return;
}
if (!IsHandleNpc) {
return;
}
if (FinishPanelCtrl.GetInstance().CheckIsActiveFinish()) {
RemoveNpcObj(false);
return;
}
if (IsPlayerKillNpc) {
CheckNpcDisCamera();
return;
}
CheckNpcDownHit();
if (IsDeadNpc) {
CheckNpcDisCamera();
CheckIsFireNpcAction();
if (IsMoveToAiPath) {
HandleMoveToAiPathNpc();
CheckPlayerPos();
}
return;
}
if (Time.time >= SpawnTime + 30f) {
//Debug.Log("*****************Do root");
IsDeadNpc = true;
if (NPC_Type != NPC_STATE.ZAI_TI_NPC) {
if (!IsDoFireAction) {
RandomDoRootAction();
}
}
else {
if (IsDanCheLvNpc) {
for (int i = 0; i < ZaiTiScript.Length; i++) {
ZaiTiScript[i].CloseRootAction();
}
}
}
return;
}
if (NPC_Type == NPC_STATE.FEI_XING_NPC) {
HandleMoveFlyNpc();
return;
}
if (!IsMoveNpc) {
if (IsFireNpc && NPC_Type != NPC_STATE.ZAI_TI_NPC && !IsDonotAimPlayerFire) {
NpcTran.LookAt(WaterwheelPlayer.position);
}
if(IsFireNpc && !IsDoFireAction && IsMoveToEndPoint)
{
float disPlayer = Vector3.Distance(NpcTran.position, WaterwheelPlayer.position);
if(disPlayer <= FireDistance)
{
if (NPC_Type == NPC_STATE.DaEYu_ZXiong_NPC) {
MakeNpcMoveToPlayer();
}
else {
PlayFireAction();
}
}
}
return;
}
if (IsMoveByITween) {
return;
}
if (IsFireNpc) {
float disPlayer = Vector3.Distance(transform.position, WaterwheelPlayer.position);
if (disPlayer <= FireDistance) {
if (NPC_Type == NPC_STATE.DaEYu_ZXiong_NPC) {
MakeNpcMoveToPlayer();
}
else {
PlayFireAction();
}
if(NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC)
{
}
else
{
return;
}
}
}
if (IsLoopMovePath) {
HandleLoopMoveNPC();
return;
}
if (IsDoRootAction) {
RootTimeVal += Time.deltaTime;
if (RootTimeVal < MarkScripte.RootAniTime) {
return;
}
IsDoRootAction = false;
RootTimeVal = 0f;
if (AnimatorNpc != null) {
AnimatorNpc.speed = RunAniSpeed;
CloseRootAction();
}
RandPlayRunAction();
}
Vector3 markPos = Vector3.zero;
if (!IsMoveToAiPath) {
markPos = GetAimMarkPos( NpcPathTran.GetChild(NextMarker) );
}
Vector3 vecA = NpcTran.position;
Vector3 vecB = markPos;
vecA.y = vecB.y = 0f;
float dis = Vector3.Distance(vecA, vecB);
if (IsMoveToAiPath) {
if (IsDanCheLvNpc && !IsDoFireAction) {
return;
}
HandleMoveToAiPathNpc();
CheckPlayerPos();
return;
}
if (dis < (MinDistance + 1f) && NextMarker < NpcPathTran.childCount) {
Transform markTran = NpcPathTran.GetChild(NextMarker);
ResetIsGetMarkPos();
NextMarker++;
MarkScripte = markTran.GetComponent<NpcMark>();
if(NextMarker < NpcPathTran.childCount && NPC_Type == NPC_STATE.SHUI_QIANG_NPC)
{
Transform nextMarkTmp = NpcPathTran.GetChild(NextMarker);
NpcMark nextMarkScript = nextMarkTmp != null ? nextMarkTmp.GetComponent<NpcMark>() : null;
if(nextMarkScript.GetFlyNodes().Count > 0)
{
IsMoveByITween = true;
MoveNpcByITween( nextMarkTmp );
PlayActionRun_2();
return;
}
}
if (MarkScripte.IsDoRoot) {
IsDoRootAction = true;
if (AnimatorNpc) {
AnimatorNpc.speed = 1f;
RandomDoRootAction();
}
}
else
{
RandPlayRunAction();
}
}
if (NextMarker >= NpcPathTran.childCount) {
if (NpcAiMarkTran != null) {
AiMark aiMarkScript = NpcAiMarkTran.GetComponent<AiMark>();
NextMarker = aiMarkScript.getMarkCount();
PreMarker = NextMarker;
IsMoveToAiPath = true;
if (IsDanCheLvNpc) {
MakeDanCheLvNpcDoRootAction();
}
}
else
{
IsMoveNpc = false;
IsMoveToEndPoint = true;
if (AnimatorNpc != null) {
AnimatorNpc.speed = 1f;
RandomDoRootAction();
}
}
}
else if (!IsDoRootAction) {
Vector3 mv = markPos - NpcTran.position;
mv.y = 0f;
NpcTran.forward = Vector3.Lerp(NpcTran.forward, mv, MoveSpeed * Time.deltaTime);
mv = mv.normalized * MoveSpeed * Time.deltaTime;
NpcTran.Translate(mv.x, 0f, mv.z, Space.World);
ApplyGravity();
}
if (Camera.main != null
&& Camera.main.enabled
&& GlobalData.GetInstance().gameMode == GameMode.OnlineMode
&& Network.peerType != NetworkPeerType.Disconnected) {
if (PositionCur != NpcTran.position) {
PositionCur = NpcTran.position;
netView.RPC("SendNpcPosToOther", RPCMode.OthersBuffered, PositionCur);
}
if (RotationCur != NpcTran.rotation) {
RotationCur = NpcTran.rotation;
netView.RPC("SendNpcRotToOther", RPCMode.OthersBuffered, RotationCur);
}
}
}
void MakeDanCheLvNpcDoRootAction()
{
if (!IsDanCheLvNpc) {
return;
}
if (!RigObj.isKinematic) {
RigObj.isKinematic = true;
}
for (int i = 0; i < ZaiTiScript.Length; i++) {
ZaiTiScript[i].RandomDoRootAction();
}
}
void OnBecameInvisible()
{
if (!IsDeadNpc) {
return;
}
if (NPC_Type != NPC_STATE.ZAI_TI_NPC) {
return;
}
if (NPC_Type == NPC_STATE.ZAI_TI_NPC) {
int max = ZaiTiScript.Length;
for(int i = 0; i < max; i++)
{
if(ZaiTiScript[i] != null)
{
Destroy(ZaiTiScript[i].gameObject);
}
}
}
HiddenNpcObj();
}
void DelayActiveNpcSimpleBulletObj()
{
NpcSimpleBulletObj.SetActive(true);
}
void OnMouseFireActive()
{
if (NPC_Type == NPC_STATE.DaEYu_ZXiong_NPC || IsTeShuZiDanShuiQiang) {
if (AnimatorNpc.GetBool("IsFire_1")) {
PlayNpcAudio(AudioNpcFireObj_1);
}
else {
PlayNpcAudio(AudioNpcFireObj_2);
}
return;
}
Vector3 vecA = Camera.main.transform.position - NpcTran.position;
Vector3 vecB = Camera.main.transform.forward;
vecA.y = vecB.y = 0f;
if (Vector3.Dot(vecA, vecB) > 0f) {
return;
}
Vector3 startPos = SpawnBulletTran.position;
Vector3 endPos = Camera.main.transform.position;
vecA = NpcTran.position - WaterwheelPlayer.position;
vecA.y = vecB.y = 0f;
if(Random.Range(0, 100) > 50 || Vector3.Dot(vecA, vecB) < 0.866f) {
endPos = WaterwheelPlayer.position + Vector3.up * 1.5f;
}
float distance = Vector3.Distance(startPos, endPos);
Vector3 forwardVec = endPos - startPos;
forwardVec = forwardVec.normalized;
RaycastHit hitInfo;
Physics.Raycast(startPos, forwardVec, out hitInfo, distance, GameCtrlXK.GetInstance().NpcAmmoHitLayer.value);
if (hitInfo.collider != null && hitInfo.collider.gameObject != gameObject){
endPos = hitInfo.point;
}
GameObject ammo = null;
if (AnimatorNpc.GetBool("IsFire_1")) {
ammo = (GameObject)Instantiate(NpcSimpleBulletObj);
PlayNpcAudio(AudioNpcFireObj_1);
}
else {
ammo = (GameObject)Instantiate(NpcSimpleBulletObjFire_2);
PlayNpcAudio(AudioNpcFireObj_2);
}
Transform ammoTran = ammo.transform;
ammoTran.parent = GameCtrlXK.MissionCleanup;
ammoTran.position = startPos;
ammoTran.forward = forwardVec;
NpcSimpleBullet bulletScript = ammo.GetComponent<NpcSimpleBullet>();
bulletScript.dist = Vector3.Distance(startPos, endPos);
}
void MakeNpcMoveToPlayer()
{
if (IsMakeEYuMvToplayer) {
return;
}
IsMakeEYuMvToplayer = true;
IsMoveByITween = true;
AnimatorNpc.speed = 1.0f;
CloseRootAction();
CloseRunAction(); //kongZhongJingZhenAction
RandomDoFireAction();
Vector3 [] nodesArray = new Vector3[3];
nodesArray[0] = NpcTran.position;
Transform attackTran = WaterwheelPlayerCtrl.GetInstance().EYuXiongAttackTran;
Vector3 offset = Vector3.zero;
offset.x = (Random.Range(0, 10000) % 3 - 1) * 0.4f * attackTran.localScale.x;
offset.y = (Random.Range(0, 10000) % 3 - 1) * 0.4f * attackTran.localScale.y;
offset.z = 0f;
nodesArray[1] = attackTran.position + offset.x * attackTran.right + offset.z * attackTran.forward
+ offset.y * attackTran.up;
Vector3 forVec = nodesArray[1] - nodesArray[0];
forVec.y = 0f;
offset = nodesArray[1] + forVec.normalized * Random.Range(2f, 3.5f);
offset.y -= Random.Range(3f, 4.5f);
nodesArray[2] = offset;
iTween.MoveTo(gameObject, iTween.Hash("path", nodesArray,
"time", 0.8f,
"orienttopath", true,
"looktime", 0.3f,
"easeType", iTween.EaseType.linear,
"oncomplete", "EYuNpcOnCompelteITween"));
}
void EYuNpcOnCompelteITween()
{
HiddenNpcObj();
}
void ApplyGravity ()
{
if (NPC_Type == NPC_STATE.FEI_XING_NPC) {
return;
}
if (NPC_Type == NPC_STATE.ZAI_TI_NPC) {
RaycastHit hitInfo;
Vector3 startPos = NpcTran.position + Vector3.up * 2f;
Vector3 forwardVal = Vector3.down;
Physics.Raycast(startPos, forwardVal, out hitInfo, 200f, GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
Vector3 posTmp = hitInfo.point;
GameObject objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer)) {
posTmp = hitInfo.point + new Vector3(0f, HighOffset, 0f) + new Vector3(0f, 0.1f, 0f); //Hit water
if (Vector3.Distance(NpcTran.position, posTmp) > 0.001f) {
NpcTran.position = posTmp;
}
}
}
}
else {
RaycastHit hitInfo;
Vector3 startPos = NpcTran.position + Vector3.up * 5f;
Vector3 forwardVal = Vector3.down;
Physics.Raycast(startPos, forwardVal, out hitInfo, 30f, GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
Vector3 posTmp = hitInfo.point;
GameObject objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer) && NPC_Type != NPC_STATE.SHUI_QIANG_NPC) {
posTmp = hitInfo.point + new Vector3(0f, HighOffset, 0f); //Hit water
}
if (Vector3.Distance(NpcTran.position, posTmp) > 0.001f) {
NpcTran.position = posTmp;
}
}
}
}
/// <summary>
/// Sets the npc animator action. if val == 0 is false, else is true.
/// </summary>
/// <param name="action">Action.</param>
/// <param name="val">Value.</param>
/// <param name="speedAction">Speed action.</param>
void SetNpcAnimatorAction(string action, int val, float speedAction)
{
bool isPlay = val == 0 ? false : true;
if (AnimatorNpc.GetBool(action) == isPlay) {
return;
}
AnimatorNpc.speed = speedAction;
AnimatorNpc.SetBool(action, isPlay);
if (Network.peerType != NetworkPeerType.Disconnected) {
netView.RPC("SendSetNpcAnimatorAction", RPCMode.OthersBuffered, action, val, speedAction);
}
}
[RPC]
void SendSetNpcAnimatorAction(string action, int val, float speedAction)
{
bool isPlay = val == 0 ? false : true;
AnimatorNpc.speed = speedAction;
AnimatorNpc.SetBool(action, isPlay);
}
public void SetIsHandleNpc()
{
IsHandleNpc = true;
}
[RPC]
void SendNpcRotToOther(Quaternion rot)
{
if (NpcTran != null) {
NpcTran.rotation = rot;
}
else {
NpcTran = transform;
NpcTran.rotation = rot;
}
}
[RPC]
void SendNpcPosToOther(Vector3 pos)
{
if (NpcTran != null) {
NpcTran.position = pos;
}
else {
NpcTran = transform;
NpcTran.position = pos;
}
}
public void ShootedByPlayer()
{
HandleHitShootedPlayer(WaterwheelPlayer.gameObject, 1);
}
///<summary>
/// npc hit player key -> 0, player shooting obj key -> 1
///</summary>
void HandleHitShootedPlayer(GameObject obj, int key)
{
switch(obj.tag)
{
case "NpcPlayer":
if (key == 1) {
return;
}
NpcMoveCtrl npcScript = obj.GetComponent<NpcMoveCtrl>();
if (npcScript == null) {
return;
}
if (npcScript.NPC_Type != NPC_STATE.ZAI_TI_NPC || NPC_Type != NPC_STATE.ZAI_TI_NPC) {
return;
}
CheckZaiTiNpcPos(obj, 0);
break;
case "Player":
if (!XingXingCtrl.IsPlayerCanHitNPC && 0 == key) {
return;
}
if (0 == key) {
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioShipHit_2);
if (PlayerAutoFire.PlayerMvSpeed > GameCtrlXK.NpcHitPlayerShakeSpeed
&& NPC_Type == NPC_STATE.ZAI_TI_NPC
&& Random.Range(0, 1000) % GameCtrlXK.NpcShakeCamVal == 0) {
CameraShake.GetInstance().SetCameraShakeImpulseValue();
}
}
if(NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC)
{
if (0 == key && !IsPlayerKillNpc) {
Vector3 vecA = WaterwheelPlayer.forward;
Vector3 vecB = WaterwheelPlayer.position - NpcTran.position;
vecA.y = vecB.y = 0f;
if (Vector3.Dot(vecA, vecB) < 0f) {
if (PlayerAutoFire.PlayerMvSpeed > 1f || !RigObj.isKinematic) {
IsDeadNpc = true;
IsPlayerKillNpc = true;
StopAudioSourceBoss();
for (int i = 0; i < ZaiTiScript.Length; i++) {
if (ZaiTiScript[i] != null) {
ZaiTiScript[i].ShootedByPlayer(1);
}
}
}
}
if (IsDanCheLvNpc || IsDiLeiNpc) {
Invoke("HiddenNpcObj", 2f);
}
}
return;
}
if(IsPlayerKillNpc)
{
return;
}
if(IsFireNpc)
{
WaterwheelPlayerCtrl.GetInstance().AddKillFireNpcNum();
}
PlayNpcAudio(AudioHitNpcObj);
if (1 == key || (key == 0 && !StartBtCtrl.GetInstanceP2().CheckIsActivePlayer())) {
WaterwheelCameraCtrl.GetInstance().SpawnPlayerNengLiangLiZi(NpcTran.position);
}
OnHitWaterwheelPlayer();
IsDeadNpc = true;
IsPlayerKillNpc = true;
break;
}
}
public void SetFlyNpcAimCubeTran()
{
if(IsFireNpc)
{
AimCuBeTranFly = WaterwheelPlayerCtrl.GetInstance().FlyNpcAimCube_1.transform;
}
else
{
AimCuBeTranFly = WaterwheelPlayerCtrl.GetInstance().FlyNpcAimCube_2.transform;
}
}
void EnableIsStartMoveFlyNpcToCam()
{
IsStartMoveFlyNpcToCam = true;
}
void MoveFlyNpcToCam()
{
if (!IsMoveFlyNpcToCam || !IsStartMoveFlyNpcToCam) {
return;
}
Vector3 AimPos = GetAimMarkPos(Camera.main.transform);
float dis = Vector3.Distance(AimPos, transform.position);
if (dis < MinDistance) {
Destroy(gameObject);
return;
}
NpcTran.forward = Vector3.Lerp(NpcTran.forward, AimPos - transform.position, LerpForwardVal * MoveSpeed * Time.deltaTime);
NpcTran.Translate(Vector3.forward * Time.deltaTime * MoveSpeed);
}
void HandleMoveFlyNpc()
{
if (!IsMoveNpc) {
return;
}
if (IsMoveFlyNpcToCam) {
MoveFlyNpcToCam();
return;
}
Vector3 AimPos = GetAimMarkPos(AimCuBeTranFly);
float dis = Vector3.Distance(AimPos, NpcTran.position);
if (dis < (MinDistance + 3f)) {
ResetIsGetMarkPos();
IsMoveFlyNpcToCam = true;
if (IsFireNpc && !IsDoFireAction) {
EnableIsStartMoveFlyNpcToCam();
IsDoFireAction = true;
AnimatorNpc.speed = 1.0f;
CloseRunAction();
RandomDoFireAction();
}
else
{
EnableIsStartMoveFlyNpcToCam();
}
return;
}
NpcTran.forward = Vector3.Lerp(NpcTran.forward, AimPos - transform.position, LerpForwardVal * MoveSpeed * Time.deltaTime);
NpcTran.Translate(Vector3.forward * Time.deltaTime * MoveSpeed);
}
void HandleNiXingAiPathNpc()
{
Vector3 markPos = GetAimMarkPos( NpcAiPathTran.GetChild(PreMarker) );
Vector3 posA = NpcTran.position;
Vector3 posB = markPos;
posA.y = posB.y = 0f;
float dis = Vector3.Distance(posA, posB);
if (dis < (MinDistance + 1f) && PreMarker > -1) {
ResetIsGetMarkPos();
PreMarker--;
RandPlayRunAction();
}
if (PreMarker <= -1) {
AiPathCtrl aiPathScript = NpcAiPathTran.GetComponent<AiPathCtrl>();
int preNum = aiPathScript.GetPrePathNum();
if (preNum <= 0) {
RemoveNpcObj(false);
return;
}
NpcAiPathTran = aiPathScript.GetPrePathTran(1) != null ? aiPathScript.GetPrePathTran(1) : null;
if(NpcAiPathTran == null)
{
NpcAiPathTran = aiPathScript.GetPrePathTran(2) != null ? aiPathScript.GetPrePathTran(2) : null;
}
if(NpcAiPathTran == null)
{
NpcAiPathTran = aiPathScript.GetPrePathTran(3) != null ? aiPathScript.GetPrePathTran(3) : null;
}
PreMarker = NpcAiPathTran.childCount - 1;
}
else
{
posB = WaterwheelPlayer.position;
posA.y = posB.y = 0f;
if (RigObj.isKinematic) {
RigObj.isKinematic = false;
}
Vector3 forwardVal = markPos - NpcTran.position;
forwardVal.y = 0f;
float disVal = Vector3.Distance(forwardVal, Vector3.zero);
forwardVal = forwardVal.normalized;
//Debug.DrawLine(NpcTran.position, markPos, Color.red);
if (Vector3.Dot(forwardVal, NpcTran.forward) < 0.998f && disVal > 2f) {
NpcTran.forward = Vector3.Lerp(NpcTran.forward, forwardVal, MoveSpeed * Time.deltaTime);
}
ApplyGravity();
forwardVal = NpcTran.forward;
forwardVal.y = 0f;
RigObj.velocity = Vector3.Lerp(RigObj.velocity, forwardVal * MoveSpeed, Time.deltaTime * 10f);
}
}
void HandleMoveToAiPathNpc()
{
if (NextMarker >= NpcAiPathTran.childCount) {
return;
}
if(IsNiXingAiPath)
{
HandleNiXingAiPathNpc();
return;
}
Vector3 markPos = GetAimMarkPos( NpcAiPathTran.GetChild(NextMarker) );
Vector3 posA = NpcTran.position;
Vector3 posB = markPos;
posA.y = posB.y = 0f;
float dis = Vector3.Distance(posA, posB);
if(dis < (MinDistance + 1f) && NextMarker < NpcAiPathTran.childCount)
{
ResetIsGetMarkPos();
NextMarker++;
RandPlayRunAction();
}
if (NextMarker >= NpcAiPathTran.childCount)
{
AiPathCtrl aiPathScript = NpcAiPathTran.GetComponent<AiPathCtrl>();
if(aiPathScript.mNextPath1 == null && aiPathScript.mNextPath2 == null && aiPathScript.mNextPath3 == null)
{
//RemoveNpcObj();
IsDeadNpc = true;
StopAudioSourceBoss();
return;
}
else
{
NpcAiPathTran = aiPathScript.mNextPath1 != null ? aiPathScript.mNextPath1 : null;
if(NpcAiPathTran == null)
{
NpcAiPathTran = aiPathScript.mNextPath2 != null ? aiPathScript.mNextPath2 : null;
}
if(NpcAiPathTran == null)
{
NpcAiPathTran = aiPathScript.mNextPath3 != null ? aiPathScript.mNextPath3 : null;
}
NextMarker = 0;
}
}
else
{
if (IsMoveZaiTiNpcItween) {
return;
}
if (RigObj.isKinematic) {
RigObj.isKinematic = false;
}
Vector3 forwardVal = markPos - NpcTran.position;
float dy = Mathf.Abs( forwardVal.y );
if (dy < 30f) {
Vector3 offsetVal = NpcTran.forward * 2.5f;
offsetVal.y = 0f;
posA = NpcTran.position + Vector3.up * (1f + Mathf.Abs(HighOffset)) + offsetVal;
posB = NpcTran.position + Vector3.up * (1f + Mathf.Abs(HighOffset));
RaycastHit hitInfo;
Vector3 startPos = posA;
Physics.Raycast(startPos, Vector3.down, out hitInfo, 10f, GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
GameObject objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer)) {
posA = hitInfo.point;
//Debug.DrawLine(startPos, posA, Color.red);
startPos = posB;
Physics.Raycast(startPos, Vector3.down, out hitInfo, 10f,
GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer)) {
posB = hitInfo.point;
//Debug.DrawLine(startPos, posB, Color.blue);
Vector3 vecTmp = posA - posB;
float disVal = Vector3.Distance(forwardVal, Vector3.zero);
forwardVal = forwardVal.normalized;
forwardVal.y = vecTmp.normalized.y;
forwardVal = forwardVal.normalized;
if (Vector3.Dot(forwardVal, NpcTran.forward) < 0.998f && disVal > 2f) {
NpcTran.forward = Vector3.Lerp(NpcTran.forward, forwardVal, MoveSpeed * Time.deltaTime);
}
}
}
}
}
}
else {
//NpcTran.position = markPos;
MakeZaiTiNpcMoveByItween();
return;
}
Vector3 mv = NpcTran.forward * 1.5f * Time.deltaTime;
mv.y = 0f;
NpcTran.Translate(mv.x, mv.y, mv.z, Space.World);
CheckZaiTiNpcPos();
ApplyGravity();
forwardVal = NpcTran.forward;
forwardVal.y = 0f;
RigObj.velocity = Vector3.Lerp(RigObj.velocity, forwardVal * MoveSpeed, Time.deltaTime * 10f);
}
}
void MakeZaiTiNpcMoveByItween()
{
if (IsMoveZaiTiNpcItween) {
return;
}
IsMoveZaiTiNpcItween = true;
RigObj.isKinematic = true;
Vector3 [] nodesArray = new Vector3[2];
nodesArray[0] = NpcTran.position;
Vector3 markPos = GetAimMarkPos( NpcAiPathTran.GetChild(NextMarker) );
markPos.y += 1.5f;
nodesArray[1] = markPos;
iTween.MoveTo(gameObject, iTween.Hash("path", nodesArray,
"time", Random.Range(2f, 5f),
"orienttopath", true,
"looktime", 1.5f,
"easeType", iTween.EaseType.linear,
"oncomplete", "EYuNpcOnCompelteITween"));
}
void ZaiTiNpcOnCompelteITween()
{
IsMoveZaiTiNpcItween = false;
}
void CheckZaiTiNpcPos()
{
if (Time.realtimeSinceStartup - TimeZaiTiPos < 2f) {
return;
}
Vector3 posA = ZaiTiOldPos;
Vector3 posB = NpcTran.position;
if (Vector3.Distance(posA, posB) < 3f) {
NpcTran.position = posB + new Vector3(0f, 0.3f, 0f);
}
TimeZaiTiPos = Time.realtimeSinceStartup;
ZaiTiOldPos = NpcTran.position;
posA = WaterwheelPlayer.position;
if (Vector3.Distance(posA, posB) > 350f) {
//Debug.Log("CheckZaiTiNpcPos ************** delete " + gameObject.name);
if (!IsDeadNpc) {
return;
}
if (NPC_Type != NPC_STATE.ZAI_TI_NPC) {
return;
}
if (NPC_Type == NPC_STATE.ZAI_TI_NPC) {
int max = ZaiTiScript.Length;
for (int i = 0; i < max; i++) {
if (ZaiTiScript[i] != null) {
Destroy(ZaiTiScript[i].gameObject);
}
}
}
HiddenNpcObj();
}
}
Vector3 GetAimMarkPos(Transform tranVal)
{
if(IsGetMarkPos)
{
if(NPC_Type == NPC_STATE.FEI_XING_NPC)
{
AimMarkPos = tranVal.position + RandVal_x * tranVal.right + RandVal_z * tranVal.forward
+ RandVal_y * tranVal.up;
}
return AimMarkPos;
}
IsGetMarkPos = true;
float perDis = Random.Range(0f, 40f) / 100f;
RandVal_x = (Random.Range(0, 10000) % 3 - 1) * perDis * tranVal.localScale.x;
RandVal_y = 0f;
RandVal_z = (Random.Range(0, 10000) % 3 - 1) * perDis * tranVal.localScale.z;
switch (NPC_Type) {
case NPC_STATE.ZAI_TI_NPC:
if(IsMoveLeft)
{
RandVal_x = (Random.Range(0, 10000) % 2 - 1) * perDis * tranVal.localScale.x;
RandVal_y = 0f;
RandVal_z = 0f;
}
else if (IsMoveRight)
{
RandVal_x = (Random.Range(0, 10000) % 2) * perDis * tranVal.localScale.x;
RandVal_y = 0f;
RandVal_z = 0f;
}
break;
case NPC_STATE.FEI_XING_NPC:
if(IsMoveFlyNpcToCam)
{
RandVal_x = (Random.Range(0, 10000) % 3 - 1) * perDis;
RandVal_y = 25f;
RandVal_z = -40f;
}
else
{
RandVal_y = (Random.Range(0, 10000) % 3 - 1) * perDis * tranVal.localScale.y;
RandVal_z = 0f;
}
break;
}
AimMarkPos = tranVal.position + RandVal_x * tranVal.right + RandVal_z * tranVal.forward
+ RandVal_y * tranVal.up;
return AimMarkPos;
}
void ResetIsGetMarkPos()
{
IsGetMarkPos = false;
}
void RandomDoRootAction()
{
CloseRunAction();
if (Random.Range(0, 100) % 2 == 0) {
SetNpcAnimatorAction("IsRoot_2", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRoot_1", 1, AnimatorNpc.speed);
}
else {
SetNpcAnimatorAction("IsRoot_1", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRoot_2", 1, AnimatorNpc.speed);
}
PlayNpcRootAudio();
if (NPC_Type == NPC_STATE.SHUI_QIANG_NPC) {
RaycastHit hitInfo;
Vector3 startPos = NpcTran.position + Vector3.up * 5f;
Vector3 forwardVal = Vector3.down;
Physics.Raycast(startPos, forwardVal, out hitInfo, 30f, GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
Vector3 posTmp = hitInfo.point;
GameObject objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer)) {
posTmp = hitInfo.point + new Vector3(0f, HighOffset, 0f); //Hit water
}
NpcTran.position = posTmp;
}
}
}
void CloseRootAction()
{
SetNpcAnimatorAction("IsRoot_1", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRoot_2", 0, AnimatorNpc.speed);
StopNpcRootAudio();
}
void MoveNpcToEndPoint()
{
Vector3 markPos = NpcPathTran.GetChild(NextMarker).position;
markPos = GetAimMarkPos( NpcPathTran.GetChild(NextMarker) );
Vector3 vecA = NpcTran.position;
Vector3 vecB = markPos;
vecA.y = vecB.y = 0f;
float dis = Vector3.Distance(vecA, vecB);
if(dis < MinDistance && NextMarker < NpcPathTran.childCount)
{
Transform markTran = NpcPathTran.GetChild(NextMarker);
ResetIsGetMarkPos();
NextMarker++;
MarkScripte = markTran.GetComponent<NpcMark>();
if(MarkScripte.IsDoRoot)
{
IsDoRootAction = true;
AnimatorNpc.speed = 1f;
//SetNpcAnimatorAction("IsRun_2", 0, AnimatorNpc.speed);
RandomDoRootAction();
}
else
{
RandPlayRunAction();
}
}
if(NextMarker >= NpcPathTran.childCount)
{
IsBackStartPoint = true;
PreMarker = NextMarker - 2;
NextMarker = 1;
}
else
{
if(IsDoRootAction)
{
return;
}
Vector3 mv = markPos - NpcTran.position;
mv.y = 0f;
NpcTran.forward = Vector3.Lerp(NpcTran.forward, mv, MoveSpeed * Time.deltaTime);
mv = mv.normalized * MoveSpeed * Time.deltaTime;
NpcTran.Translate(mv.x, 0f, mv.z, Space.World);
ApplyGravity();
}
}
void MoveNpcToStartPoint()
{
Vector3 markPos = NpcPathTran.GetChild(PreMarker).position;
markPos = GetAimMarkPos( NpcPathTran.GetChild(PreMarker) );
Vector3 vecA = NpcTran.position;
Vector3 vecB = markPos;
vecA.y = vecB.y = 0f;
float dis = Vector3.Distance(vecA, vecB);
if(dis < MinDistance && PreMarker > -1)
{
Transform markTran = NpcPathTran.GetChild(PreMarker);
ResetIsGetMarkPos();
PreMarker--;
MarkScripte = markTran.GetComponent<NpcMark>();
if(MarkScripte.IsDoRoot)
{
IsDoRootAction = true;
AnimatorNpc.speed = 1f;
//SetNpcAnimatorAction("IsRun_2", 0, AnimatorNpc.speed);
RandomDoRootAction();
}
else
{
RandPlayRunAction();
}
}
if(PreMarker <= -1)
{
IsBackStartPoint = false;
PreMarker = 0;
}
else
{
if(IsDoRootAction)
{
return;
}
Vector3 mv = markPos - NpcTran.position;
mv.y = 0f;
NpcTran.forward = Vector3.Lerp(NpcTran.forward, mv, MoveSpeed * Time.deltaTime);
mv = mv.normalized * MoveSpeed * Time.deltaTime;
NpcTran.Translate(mv.x, 0f, mv.z, Space.World);
ApplyGravity();
}
}
void HandleLoopMoveNPC()
{
if(!IsLoopMovePath)
{
return;
}
if(IsDoRootAction)
{
RootTimeVal += Time.deltaTime;
if(RootTimeVal < MarkScripte.RootAniTime)
{
return;
}
IsDoRootAction = false;
RootTimeVal = 0f;
AnimatorNpc.speed = RunAniSpeed;
CloseRootAction();
RandPlayRunAction();
}
if(!IsBackStartPoint)
{
MoveNpcToEndPoint();
}
else
{
MoveNpcToStartPoint();
}
}
public void RemoveNpcObj(bool isSpawnNpcPoint)
{
if(NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC)
{
if(NpcTran != null)
{
if (isSpawnNpcPoint) {
IsDeadNpc = true;
}
else {
int max = ZaiTiScript.Length;
for(int i = 0; i < max; i++)
{
if(ZaiTiScript[i] != null)
{
Destroy(ZaiTiScript[i].gameObject);
}
}
Destroy(gameObject);
}
}
}
else
{
HiddenNpcObj();
}
}
void HiddenNpcObj()
{
if (gameObject == null) {
return;
}
if (GlobalData.GetInstance().gameMode == GameMode.SoloMode) {
Destroy(gameObject);
}
else {
if (Network.peerType != NetworkPeerType.Disconnected) {
netView.RPC("SendHiddenNetNpcObj", RPCMode.OthersBuffered);
}
gameObject.SetActive(false);
}
}
[RPC]
void SendHiddenNetNpcObj()
{
gameObject.SetActive(false);
}
void CheckHitZhangAiObj()
{
if(NPC_Type != NPC_STATE.ZAI_TI_NPC)
{
return;
}
RaycastHit hit;
Vector3 startPos = NpcTran.position + (Vector3.up * NpcTran.localScale.y * 0.4f) + (NpcTran.forward * NpcTran.localScale.z * 0.55f);
startPos += NpcTran.right * NpcTran.localScale.x * (Random.Range(-0.5f, 0.5f));
if (Physics.Raycast(startPos, NpcTran.forward, out hit, 20.0f))
{
Transform colTran = hit.collider.transform;
switch (hit.collider.tag) {
case "NpcPlayer":
NpcMoveCtrl npcScript = colTran.GetComponent<NpcMoveCtrl>();
if(npcScript == null)
{
return;
}
if(npcScript.NPC_Type != NPC_STATE.ZAI_TI_NPC)
{
return;
}
return;
}
}
}
void ActiveBuWaWa()
{
if(BuWaWaObj == null || BuWaWaObj.activeSelf || AnimatorNpc == null || !AnimatorNpc.enabled)
{
return;
}
AnimatorNpc.enabled = false;
if (IsMoveByITween && NpcTran.GetComponent<iTween>() != null) {
//Debug.LogError("***************test " + NpcTran.name);
Vector3 [] nodesArray = new Vector3[2];
nodesArray[0] = NpcTran.position;
Transform attackTran = WaterwheelPlayer;
Vector3 offset = Vector3.zero;
offset.x = Random.Range(-3f, 3f);
offset.y = Random.Range(0.5f, 1.5f);
offset.z = Random.Range(17f, 26f);
nodesArray[1] = attackTran.position + offset.x * attackTran.right + offset.z * attackTran.forward
+ offset.y * attackTran.up;
if (!IsInvoking("DelayActiveBuWaWa")) {
Invoke("DelayActiveBuWaWa", 0.1f);
}
iTween.MoveTo(gameObject, iTween.Hash("path", nodesArray,
"time", 0.6f,
"orienttopath", false,
"easeType", iTween.EaseType.linear));
}
else {
if (!IsInvoking("DelayActiveBuWaWa")) {
Invoke("DelayActiveBuWaWa", 0.1f);
}
Vector3 [] nodesArray = new Vector3[2];
nodesArray[0] = NpcTran.position;
nodesArray[1] = NpcTran.position + Vector3.up * 0.5f;
iTween.MoveTo(gameObject, iTween.Hash("path", nodesArray,
"time", 0.3f,
"orienttopath", false,
"easeType", iTween.EaseType.linear));
}
}
void DelayActiveBuWaWa()
{
BuWaWaObj.SetActive(true);
Rigidbody rigObj = BuWaWaObj.GetComponent<Rigidbody>();
Vector3 vecDir = Vector3.Lerp(-NpcTran.forward, Vector3.up, GameCtrlXK.GetInstance().NpcBuWaWaVal);
if (GameCtrlXK.PlayerTran != null) {
Vector3 vecA = NpcTran.position - GameCtrlXK.PlayerTran.position;
vecA.y = 0f;
vecDir = Vector3.Lerp(vecA.normalized, Vector3.up, GameCtrlXK.GetInstance().NpcBuWaWaVal);
}
rigObj.AddForce(vecDir * BuWaWaPowerVal, ForceMode.Impulse);
}
void PlayActionRun_2()
{
if (NPC_Type != NPC_STATE.SHUI_QIANG_NPC) {
return;
}
CloseRootAction();
SetNpcAnimatorAction("IsRun_3", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRun_2", 1, AnimatorNpc.speed);
}
void PlayActionRun_3()
{
if (NPC_Type != NPC_STATE.SHUI_QIANG_NPC) {
return;
}
CloseRootAction();
CloseRunAction();
IsPlayRun_3 = true;
SetNpcAnimatorAction("IsRun_3", 1, AnimatorNpc.speed);
}
void CloseRunAction()
{
if (NPC_Type == NPC_STATE.SHUI_QIANG_NPC) {
SetNpcAnimatorAction("IsRun_3", 0, AnimatorNpc.speed);
}
SetNpcAnimatorAction("IsRun_2", 0, AnimatorNpc.speed);
}
void RandPlayRunAction()
{
if(AnimatorNpc == null)
{
return;
}
if (IsPlayRun_3 && NPC_Type == NPC_STATE.SHUI_QIANG_NPC) {
PlayActionRun_3();
return;
}
if(Random.Range(0, 10000) % 2 == 0)
{
CloseRunAction();
}
else
{
SetNpcAnimatorAction("IsRun_2", 1, AnimatorNpc.speed);
}
}
public void SetShuiQiangNpcFlyTime(float val)
{
ShuiQiangNpcFlyTime = val;
}
public void SetNpcPathTran(Transform tranNpcPathVal, float speedVal, bool isLoop, float fireDisVal,
NpcRunState runStateVal, GameObject objAiMarkVal, bool isNiXingVal)
{
SetIsShuiLeiNpc();
if(tranNpcPathVal == null && NPC_Type == NPC_STATE.DI_MIAN_NPC)
{
return;
}
if (speedVal < 1f) {
speedVal = 1f;
}
if(NPC_Type == NPC_STATE.SHUI_QIANG_NPC)
{
runStateVal = NpcRunState.RUN_1;
objAiMarkVal = null;
isNiXingVal = false;
isLoop = false;
}
MoveSpeed = speedVal;
NpcPathTran = tranNpcPathVal;
NpcAiMarkTran = objAiMarkVal != null ? objAiMarkVal.transform : null;
NpcAiPathTran = NpcAiMarkTran != null ? NpcAiMarkTran.parent : null;
IsNiXingAiPath = isNiXingVal;
if(AnimatorNpc)
{
RunAniSpeed = 1f;
AnimatorNpc.speed = 1f;
switch(runStateVal)
{
case NpcRunState.RUN_1:
CloseRunAction();
break;
case NpcRunState.RUN_2:
SetNpcAnimatorAction("IsRun_2", 1, AnimatorNpc.speed);
break;
default:
RandPlayRunAction();
break;
}
}
if (GlobalData.GetInstance().gameMode == GameMode.SoloMode) {
WaterwheelPlayer = WaterwheelPlayerCtrl.GetInstance().transform;
}
else {
WaterwheelPlayer = WaterwheelPlayerNetCtrl.GetInstance().transform;
}
FireDistance = fireDisVal;
if (fireDisVal > 0f) {
IsFireNpc = true;
}
if(NPC_Type == NPC_STATE.FEI_XING_NPC)
{
SetFlyNpcAimCubeTran();
isLoop = false;
}
else if (NPC_Type == NPC_STATE.ZAI_TI_NPC)
{
isLoop = false;
if (NpcPathTran == null) {
IsMoveToAiPath = true;
AiMark aiMarkScript = NpcAiMarkTran.GetComponent<AiMark>();
NextMarker = aiMarkScript.getMarkCount();
PreMarker = NextMarker;
if (IsDanCheLvNpc) {
MakeDanCheLvNpcDoRootAction();
}
}
if (IsFireNpc)
{
int max = ZaiTiScript.Length;
for (int i = 0; i < max; i++) {
if (ZaiTiScript[i] != null) {
ZaiTiScript[i].SetIsFireNpc();
}
}
}
if (!IsNiXingAiPath) {
if (!IsDiLeiNpc && !IsDanCheLvNpc) {
MoveSpeed = Random.Range(WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.3f, WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.5f);
}
FillZaiTiZhengXingObj();
}
else {
FillZaiTiNiXingObj();
}
}
IsLoopMovePath = isLoop;
IsMoveNpc = true;
}
void PlayFireAction()
{
if(NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC)
{
if (NpcAiPathTran != null) {
IsMoveNpc = true;
}
if(!IsDoFireAction)
{
int max = ZaiTiScript.Length;
for(int i = 0; i < max; i++)
{
if(ZaiTiScript[i] != null)
{
ZaiTiScript[i].PlayZaiNpcFireAction();
}
}
}
IsDoFireAction = true;
return;
}
else
{
IsDoFireAction = true;
IsMoveNpc = false;
}
if (!IsDonotAimPlayerFire) {
transform.LookAt(WaterwheelPlayer);
}
AnimatorNpc.speed = 1f;
CloseRunAction();
CloseRootAction();
RandomDoFireAction();
}
void RandomDoFireAction()
{
if (Random.Range(0, 100) % 2 == 0) {
SetNpcAnimatorAction("IsFire_2", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsFire_1", 1, AnimatorNpc.speed);
}
else {
SetNpcAnimatorAction("IsFire_1", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsFire_2", 1, AnimatorNpc.speed);
}
if (IsTeShuZiDanShuiQiang) {
NpcSimpleBulletObj.SetActive(true);
}
if (NPC_Type == NPC_STATE.SHUI_QIANG_NPC) {
RaycastHit hitInfo;
Vector3 startPos = NpcTran.position + Vector3.up * 5f;
Vector3 forwardVal = Vector3.down;
Physics.Raycast(startPos, forwardVal, out hitInfo, 30f, GameCtrlXK.GetInstance().NpcVertHitLayer.value);
if (hitInfo.collider != null){
Vector3 posTmp = hitInfo.point;
GameObject objHit = hitInfo.collider.gameObject;
if (objHit.layer == LayerMask.NameToLayer(GameCtrlXK.WaterLayer)) {
posTmp = hitInfo.point + new Vector3(0f, HighOffset, 0f); //Hit water
}
NpcTran.position = posTmp;
}
}
}
public void OnHitWaterwheelPlayer()
{
IsMoveNpc = false;
ActiveBuWaWa();
Invoke("DelaySpawnExplode", GameCtrlXK.GetInstance().TimeNpcSpawnExplode);
}
void DelaySpawnExplode()
{
Transform tran = BuWaWaObj.transform;
Instantiate(ExplodeObj, tran.position, tran.rotation);
Destroy(gameObject, 0.1f);
}
public void MoveNpcByITween(Transform npcMarkTranVal)
{
if (npcMarkTranVal == null) {
return;
}
NpcMark markScript = npcMarkTranVal.GetComponent<NpcMark>();
if (markScript == null) {
return;
}
iTween.MoveTo(gameObject, iTween.Hash("path", markScript.GetFlyNodes().ToArray(),
"time", ShuiQiangNpcFlyTime,
"orienttopath", true,
"looktime", 0.6f,
"easeType", iTween.EaseType.linear,
"oncomplete", "ShuiQiangNpcOnCompelteITween"));
}
void ShuiQiangNpcOnCompelteITween()
{
NextMarker++;
PlayActionRun_3();
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioShuiQiangIntoWater);
IsMoveByITween = false;
}
public void OnZaiTiNpcDead()
{
int max = ZaiTiScript.Length;
ZaiTiNpcDeadNum++;
if (ZaiTiNpcDeadNum >= max) {
IsDeadNpc = true;
}
else
{
int numTmp = 0;
for (int i = 0; i < max; i++) {
if (ZaiTiScript[i] != null) {
numTmp++;
}
}
if (numTmp <= 1) {
IsDeadNpc = true;
}
}
if (IsDeadNpc) {
StopAudioSourceBoss();
if (IsDanCheLvNpc || IsDiLeiNpc) {
Invoke("HiddenNpcObj", 2f);
}
}
}
void CheckZaiTiNpcPos(GameObject colObj, int key)
{
if (key != 0) {
return;
}
NpcMoveCtrl colObjScript = colObj.GetComponent<NpcMoveCtrl>();
if (!colObjScript.GetIsCheckPlayerPos() || !IsCheckPlayerPos) {
return;
}
if (Random.Range(0, 100) % 2 == 0) {
CloseCheckPlayerPos();
}
else {
colObjScript.CloseCheckPlayerPos();
}
}
public bool GetIsCheckPlayerPos()
{
return IsCheckPlayerPos;
}
void CloseCheckPlayerPos()
{
if (!IsCheckPlayerPos) {
return;
}
//Debug.Log("CloseCheckPlayerPos*********");
IsCheckPlayerPos = false;
OldMoveSpeed = MoveSpeed;
MoveSpeed = 0f;
Invoke("OpenCheckPlayerPos", 1f);
}
void OpenCheckPlayerPos()
{
IsCheckPlayerPos = true;
MoveSpeed = OldMoveSpeed;
}
void SetIsShuiLeiNpc()
{
if (NPC_Type == NPC_STATE.ZAI_TI_NPC || NPC_Type == NPC_STATE.BOSS_NPC) {
for (int i = 0; i < ZaiTiScript.Length; i++) {
if (ZaiTiScript[i].IsDiLeiNpc || IsDanCheLvNpc) {
if (IsDanCheLvNpc) {
ZaiTiScript[i].SetIsDanCheLvNpc();
}
IsDiLeiNpc = true;
break;
}
}
}
}
void CheckPlayerPos()
{
if (NPC_Type != NPC_STATE.ZAI_TI_NPC
|| IsDanCheLvNpc
|| IsDiLeiNpc) {
return;
}
if (IsNiXingAiPath || !IsMoveToAiPath) {
return;
}
if (!IsCheckPlayerPos) {
return;
}
if (IsDeadNpc) {
MoveSpeed = Random.Range(WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.2f, WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.5f);
return;
}
if (NextMarker >= NpcAiPathTran.childCount) {
return;
}
if (CameraShake.GetInstance().GetIsActiveHuanYingFu()
|| IntoPuBuCtrl.IsIntoPuBu) {
if (MoveSpeed >= 20f) {
MoveSpeed = Random.Range(WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.2f, WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.5f);
}
return;
}
Transform npcAimMark = NpcAiPathTran.GetChild(NextMarker);
Transform playerAimMark = WaterwheelPlayerCtrl.GetInstance().GetAimMarkTran();
if (playerAimMark == null) {
return;
}
AiPathCtrl npcAiPathScript = NpcAiPathTran.GetComponent<AiPathCtrl>();
AiPathCtrl playerAiPathScript = playerAimMark.parent.GetComponent<AiPathCtrl>();
int npcPathKey = npcAiPathScript.KeyState;
int playerPathKey = playerAiPathScript.KeyState;
int AiPathIdP = playerAimMark.parent.GetInstanceID();
int pathId = npcAimMark.parent.GetInstanceID();
if (AiPathIdP == pathId) {
AiMark markScript = npcAimMark.GetComponent<AiMark>();
AiMark markScriptP = playerAimMark.GetComponent<AiMark>();
int markCount = markScript.getMarkCount();
int markCountP = markScriptP.getMarkCount();
if (markCount <= markCountP) {
//Npc should add speed
ChangeNpcMoveSpeed(true);
return;
}
else if (markCount > markCountP) {
ChangeNpcMoveSpeed(false);
return;
}
}
else
{
if (npcPathKey <= playerPathKey) {
//Npc should add speed
ChangeNpcMoveSpeed(true);
return;
}
else if (npcPathKey > playerPathKey) {
ChangeNpcMoveSpeed(false);
return;
}
}
}
public float GetMoveSpeed()
{
return MoveSpeed;
}
void ChangeNpcMoveSpeed(bool isAddSpeed)
{
float playerSpeed = PlayerAutoFire.PlayerMvSpeed;
if (isAddSpeed) {
if (MoveSpeed <= playerSpeed) {
if (playerSpeed > 5) {
MoveSpeed = Random.Range(WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.5f, WaterwheelPlayerCtrl.mMaxVelocityFootMS * 1.3f);
}
else
{
MoveSpeed = WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.3f;
}
//Debug.Log("ChangeNpcMoveSpeed: isAddSpeed " + isAddSpeed + ", MoveSpeed " + MoveSpeed);
}
}
else
{
if (MoveSpeed >= playerSpeed) {
MoveSpeed = Random.Range(WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.2f, WaterwheelPlayerCtrl.mMaxVelocityFootMS * 0.5f);
//Debug.Log("ChangeNpcMoveSpeed: isAddSpeed " + isAddSpeed + ", MoveSpeed " + MoveSpeed);
}
}
}
void CheckNpcDisCamera()
{
Vector3 posA = TranCamera.position;
Vector3 posB = NpcTran.position;
posA.y = 0f;
posB.y = 0f;
if (Vector3.Distance(posA, posB) < 5f) {
return;
}
Vector3 vecA = TranCamera.forward;
Vector3 vecB = posB - posA;
vecA.y = 0f;
vecB.y = 0f;
if (Vector3.Dot(vecA, vecB) < 0f) {
//Debug.Log("CheckNpcDisCamera ***** " + gameObject.name);
if (NPC_Type == NPC_STATE.ZAI_TI_NPC) {
OnBecameInvisible();
}
else {
HiddenNpcObj();
}
}
}
void CreateAudioSourceNpc()
{
if (AudioState == AudioNpcState.NULL) {
return;
}
AudioSourceNpc = gameObject.AddComponent<AudioSource>();
AudioSourceNpc.loop = false;
AudioSourceNpc.playOnAwake = false;
AudioSourceNpc.Stop();
switch (AudioState) {
case AudioNpcState.Xiong:
AudioSourceNpc.clip = AudioListCtrl.GetInstance().AudioXiong;
break;
case AudioNpcState.ShiZi:
AudioSourceNpc.clip = AudioListCtrl.GetInstance().AudioShiZi;
break;
case AudioNpcState.LaoHu:
AudioSourceNpc.clip = AudioListCtrl.GetInstance().AudioLaoHu;
break;
case AudioNpcState.ChangJingLu:
AudioSourceNpc.clip = AudioListCtrl.GetInstance().AudioChangJingLu;
break;
}
}
void PlayNpcRootAudio()
{
if (AudioState == AudioNpcState.NULL) {
return;
}
if (!AudioSourceNpc.isPlaying) {
AudioSourceNpc.Play();
}
}
void StopNpcRootAudio()
{
if (AudioState == AudioNpcState.NULL) {
return;
}
if (AudioSourceNpc.isPlaying) {
AudioSourceNpc.Stop();
}
}
void CreateAudioSourceBoss()
{
if (NPC_Type != NPC_STATE.BOSS_NPC) {
return;
}
AudioSourceBoss = gameObject.AddComponent<AudioSource>();
AudioSourceBoss.clip = AudioListCtrl.GetInstance().AudioBossShip;
AudioSourceBoss.loop = true;
AudioSourceBoss.Play();
}
void StopAudioSourceBoss()
{
if (RigObj.isKinematic) {
RigObj.isKinematic = false;
}
if (AudioSourceBoss == null) {
return;
}
AudioSourceBoss.Stop();
}
void CheckIsFireNpcAction()
{
if (!IsMoveNpc) {
if (IsFireNpc && NPC_Type != NPC_STATE.ZAI_TI_NPC && !IsDonotAimPlayerFire) {
transform.LookAt(WaterwheelPlayer.position);
}
return;
}
if (IsMoveByITween) {
return;
}
if (IsFireNpc) {
float disPlayer = Vector3.Distance(transform.position, WaterwheelPlayer.position);
if(disPlayer <= FireDistance)
{
if (NPC_Type == NPC_STATE.DaEYu_ZXiong_NPC) {
MakeNpcMoveToPlayer();
}
else {
PlayFireAction();
}
}
}
}
void ResetActionInfo()
{
if (AnimatorNpc == null) {
return;
}
SetNpcAnimatorAction("IsRoot_1", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRoot_2", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsRun_2", 0, AnimatorNpc.speed);
if (NPC_Type == NPC_STATE.SHUI_QIANG_NPC) {
SetNpcAnimatorAction("IsRun_3", 0, AnimatorNpc.speed);
}
SetNpcAnimatorAction("IsFire_1", 0, AnimatorNpc.speed);
SetNpcAnimatorAction("IsFire_2", 0, AnimatorNpc.speed);
}
void CheckDistancePlayerCross()
{
if (!PlayerAutoFire.IsPlayerFire) {
return;
}
if (IsPlayerFireNpc) {
return;
}
Vector3 startPos = NpcTran.position;
Vector3 endPos = Camera.main.transform.position;
Vector3 forVal = endPos - startPos;
forVal= forVal.normalized;
startPos += forVal * 2f;
startPos.y += 1.2f;
float disVal = Vector3.Distance(startPos, endPos);
if (GlobalData.GetInstance().IsActiveJuLiFu) {
if (disVal > 90f) {
return;
}
}
else {
if (disVal > 50f) {
return;
}
}
//Debug.DrawLine(startPos, endPos, Color.red); //test
RaycastHit hitInfo;
Physics.Raycast(startPos, forVal, out hitInfo, disVal, GameCtrlXK.GetInstance().NpcAmmoHitLayer.value);
if (hitInfo.collider != null
&& hitInfo.collider.gameObject != WaterwheelPlayer.gameObject
&& hitInfo.collider.gameObject != gameObject){
//Debug.DrawLine(startPos, hitInfo.point, Color.blue); //test
return;
}
Vector3 vecA = Camera.main.transform.forward;
Vector3 vecB = NpcTran.position - Camera.main.transform.position;
vecA.y = vecB.y = 0f;
if (Vector3.Dot(vecA, vecB) < 0f) {
return;
}
Vector3 posTmp = NpcTran.position;
Vector3 posA = pcvr.CrossPosition;
posTmp += 0.6f * NpcTran.up * BoxColSizeYVal;
Vector3 posB = Camera.main.WorldToScreenPoint(posTmp);
posB.y = 768f - posB.y;
posB.z = 0f;
posA.y = 768f - posA.y;
float dx = Mathf.Abs(posA.x - posB.x);
float dy = Mathf.Abs(posA.y - posB.y);
if (GlobalData.GetInstance().IsActiveJuLiFu) {
float crossY = 198f;
if (dx < (0.7f * crossY) && dy < crossY) {
IsPlayerFireNpc = true;
HandleHitShootedPlayer(WaterwheelPlayer.gameObject, 1);
}
}
else {
float crossY = 98f;
if (dx < (0.7f * crossY) && dy < crossY) {
IsPlayerFireNpc = true;
HandleHitShootedPlayer(WaterwheelPlayer.gameObject, 1);
}
}
}
void PlayNpcAudio(GameObject audioObj)
{
if (audioObj == null) {
return;
}
if (!audioObj.activeSelf) {
audioObj.SetActive(true);
}
AudioSource ad = audioObj.GetComponent<AudioSource>();
ad.Play();
}
} |
using Backend.Model.PerformingExamination;
using System.Collections.Generic;
namespace Backend.Service.ExaminationAndPatientCard
{
public interface IEquipmentInExaminationService
{
EquipmentInExamination AddEquipmentInExamination(EquipmentInExamination equipmentInExamination);
List<EquipmentInExamination> GetEquipmentInExaminationFromExaminationID(int examinationID);
}
}
|
using Sentry.Extensibility;
namespace Sentry.Internal.DiagnosticSource;
/// <summary>
/// Class that subscribes to specific listeners from DiagnosticListener.
/// </summary>
internal class SentryDiagnosticSubscriber : IObserver<DiagnosticListener>
{
// We intentionally do not dispose subscriptions, so that we can get as much information as possible.
// Also, the <see cref="OnNext"/> method may fire more than once with the same listener name.
// We need to subscribe each time it does. However, we only need one instance of each of our listeners.
// Thus, we will create the instances lazily.
private readonly Lazy<SentryEFCoreListener> _efListener;
private readonly Lazy<SentrySqlListener> _sqlListener;
public SentryDiagnosticSubscriber(IHub hub, SentryOptions options)
{
_efListener = new Lazy<SentryEFCoreListener>(() =>
{
options.Log(SentryLevel.Debug, "Registering EF Core integration");
return new SentryEFCoreListener(hub, options);
});
_sqlListener = new Lazy<SentrySqlListener>(() =>
{
options.Log(SentryLevel.Debug, "Registering SQL Client integration.");
return new SentrySqlListener(hub, options);
});
}
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(DiagnosticListener listener)
{
switch (listener.Name)
{
case "Microsoft.EntityFrameworkCore":
{
listener.Subscribe(_efListener.Value);
break;
}
case "SqlClientDiagnosticListener":
{
listener.Subscribe(_sqlListener.Value);
break;
}
}
// By default, the EF listener will duplicate spans already given by the SQL Client listener.
// Thus, we should disable those parts of the EF listener when they are both registered.
if (_efListener.IsValueCreated && _sqlListener.IsValueCreated)
{
var efListener = _efListener.Value;
efListener.DisableConnectionSpan();
efListener.DisableQuerySpan();
}
}
}
|
using RRExpress.AppCommon;
using RRExpress.AppCommon.Attributes;
using System;
using System.Collections.Generic;
namespace RRExpress.Seller.ViewModels {
[Regist(InstanceMode.PreRequest)]
public class ChannelViewModel : BaseVM {
public event EventHandler SelectedChanged;
public override string Title {
get {
return "产品所属频道";
}
}
public IEnumerable<string> Datas {
get;
} = new List<string>() { "自营超市", "家乡农村", "身边商店" };
private string _selected;
public string Selected {
get {
return this._selected;
}
set {
this._selected = value;
this.NotifyOfPropertyChange(() => this.Selected);
}
}
}
}
|
/*
* Grading ID: M5477
* Lab: 9
* Due Date: April 21 2019
* Course Section: 01
* Description: A simple demonstration of using an external class
*/
using System;
using System.Windows.Forms;
namespace dates
{
public partial class DateForm : Form
{
private Date dateClass = new Date(1, 1, 2000);
public DateForm()
{
InitializeComponent();
}
private void DateForm_Load(object sender, EventArgs e)
{
dateBox.Text = dateClass.ToString();
}
private void monthButton_Click(object sender, EventArgs e)
{
bool validInput;
int month;
validInput = int.TryParse(monthBox.Text, out month);
if (validInput)
{
dateClass.Month = month;
monthBox.Text = null;
dateBox.Text = dateClass.ToString();
}
else
{
MessageBox.Show("Please update your input to contain whole numbers only.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dayButton_Click(object sender, EventArgs e)
{
bool validInput;
int day;
validInput = int.TryParse(dayBox.Text, out day);
if (validInput)
{
dateClass.Day = day;
dayBox.Text = null;
dateBox.Text = dateClass.ToString();
}
else
{
MessageBox.Show("Please update your input to contain whole numbers only.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void yearButton_Click(object sender, EventArgs e)
{
bool validInput;
int year;
validInput = int.TryParse(yearBox.Text, out year);
if (validInput)
{
dateClass.Year = year;
yearBox.Text = null;
dateBox.Text = dateClass.ToString();
}
else
{
MessageBox.Show("Please update your input to contain whole numbers only.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
namespace gView.Framework.IO
{
public interface IXmlString
{
string ToXmlString();
void FromXmlString(string xml);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using System.Threading;
namespace ClientPortal
{
public class ClientPortal_LoginPageElements
{
public static string url = "messages/Account/Login?ReturnUrl=%2Fmessages";
public IWebElement user_name = Driver.Instance.FindElement(By.Id("UserName"));
public IWebElement pass = Driver.Instance.FindElement(By.Id("Password"));
public IWebElement login_button = Driver.Instance.FindElement(By.Id("btnLogin"));
}
}
|
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Voluntariat.Data.Repositories;
using Voluntariat.Models;
namespace Voluntariat.Services
{
public interface IVolunteerService
{
List<ApplicationUser> GetVolunteersInRangeForBeneficiary(ApplicationUser beneficiary, int radiusInKm);
void NotifyUnaffiliatedVolunteers();
void DeleteUnaffiliatedVolunteers();
}
public class VolunteerService : IVolunteerService
{
private readonly IVolunteerRepository _volunteerRepository;
private readonly IVolunteerMatchingService _volunteerMatchingService;
private readonly IEmailSender _emailSender;
public VolunteerService(IVolunteerRepository volunteerRepository, IVolunteerMatchingService volunteerMatchingService, IEmailSender emailSender)
{
_volunteerRepository = volunteerRepository;
_volunteerMatchingService = volunteerMatchingService;
_emailSender = emailSender;
}
public List<ApplicationUser> GetVolunteersInRangeForBeneficiary(ApplicationUser beneficiary, int radiusInKm)
{
IQueryable<ApplicationUser> volunteers = _volunteerRepository.GetVolunteers();
return _volunteerMatchingService.GetVolunteersInRange(volunteers, beneficiary, radiusInKm).ToList();
}
public void NotifyUnaffiliatedVolunteers()
{
var volunteerUsers = _volunteerRepository.GetVolunteers();
var volunteers = _volunteerRepository.GetUnaffiliatedVolunteers();
var availableForNotificationVolunteerIds = volunteers
.Where(v => v.UnaffiliationStartTime.Value.Date.AddMonths(1) < DateTime.UtcNow.Date)
.Select(v => v.ID.ToString())
.ToList();
var availableForNotificationVolunteers = volunteerUsers.Where(u => availableForNotificationVolunteerIds.Contains(u.Id));
foreach (var volunteer in availableForNotificationVolunteers)
{
_emailSender.SendEmailAsync(volunteer.Email, "Unaffiliation notification",
$"Dear {volunteer.UserName}, <br/> Your account will be deleted due to unaffiliation in 48 hours.");
}
}
public void DeleteUnaffiliatedVolunteers()
{
var volunteers = _volunteerRepository.GetUnaffiliatedVolunteers();
var toBeRemovedVolunteerIds = volunteers
.Where(v => v.UnaffiliationStartTime.Value.Date.AddMonths(1).AddDays(2) < DateTime.UtcNow.Date)
.AsNoTracking()
.Select(v => v.ID)
.ToArray();
_volunteerRepository.RemoveVolunteers(toBeRemovedVolunteerIds);
}
}
}
|
using KingNetwork.Shared;
using System;
using System.Net;
using System.Net.Sockets;
namespace KingNetwork.Client.Listeners
{
/// <summary>
/// This class is responsible for managing the network tcp listener.
/// </summary>
public class TcpNetworkListener : NetworkListener
{
#region properties
/// <inheritdoc/>
public override bool HasConnected => _tcpListener != null ? _tcpListener.Connected : false;
#endregion
#region constructors
/// <summary>
/// Creates a new instance of a <see cref="TcpNetworkListener"/>.
/// </summary>
/// <param name="messageReceivedHandler">The callback of message received handler implementation.</param>
/// <param name="disconnectedHandler">The callback of client disconnected handler implementation.</param>
public TcpNetworkListener(MessageReceivedHandler messageReceivedHandler, DisconnectedHandler disconnectedHandler)
: base(messageReceivedHandler, disconnectedHandler) { }
#endregion
#region public methods implementation
/// <inheritdoc/>
public override void StartClient(string ip, int port, ushort maxMessageBuffer)
{
_tcpRemoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
_tcpListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_tcpListener.ReceiveBufferSize = maxMessageBuffer;
_tcpListener.SendBufferSize = maxMessageBuffer;
_tcpListener.Connect(_tcpRemoteEndPoint);
_tcpBuffer = new byte[maxMessageBuffer];
_stream = new NetworkStream(_tcpListener);
_stream.BeginRead(_tcpBuffer, 0, _tcpListener.ReceiveBufferSize, ReceiveDataCallback, null);
}
/// <inheritdoc/>
public override void SendMessage(KingBufferWriter writer)
{
_stream.BeginWrite(writer.BufferData, 0, writer.Length, null, null);
}
#endregion
#region private methods implementation
/// <summary>
/// The callback from received message from connected server.
/// </summary>
/// <param name="asyncResult">The async result from a received message from connected server.</param>
private void ReceiveDataCallback(IAsyncResult asyncResult)
{
try
{
if (_tcpListener.Connected)
{
var endRead = _stream.EndRead(asyncResult);
if (endRead != 0)
{
var tempArray = new byte[endRead];
Buffer.BlockCopy(_tcpBuffer, 0, tempArray, 0, endRead);
_stream.BeginRead(_tcpBuffer, 0, _tcpListener.ReceiveBufferSize, ReceiveDataCallback, null);
var buffer = KingBufferReader.Create(tempArray);
_messageReceivedHandler(buffer);
return;
}
}
_stream.Close();
_disconnectedHandler();
}
catch (Exception ex)
{
_stream.Close();
_disconnectedHandler();
throw ex;
}
}
#endregion
}
}
|
/*
* Created by SharpDevelop.
* User: Admin
* Date: 5/6/2019
* Time: 6:36 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace proyeto_poo
{
/// <summary>
/// Description of Room.
/// </summary>
public class Room : Functions
{
public Room()
{
}
public int NumberRoom{get;set;}
public int PriceRoom{get;set;}
bool _ReservationStatus = false;
public bool ReservationStatus{
get{
return _ReservationStatus;
}
set{
_ReservationStatus = value;
}
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EventManager : MonoBehaviour
{
private Dictionary<System.Type, UnityEventBase> eventDictionary;
private static EventManager eventManager;
public static EventManager instance
{
get
{
if (!eventManager)
{
eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError("There needs to be one active EventManager script on a GameObject in your scene.");
}
else
{
eventManager.Init();
}
}
return eventManager;
}
}
void Init()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<System.Type, UnityEventBase>();
}
}
public static void StartListening<Tbase>(UnityAction listener) where Tbase : UnityEvent, new()
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.AddListener(listener);
else
Debug.LogError("EventManager.StartListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
else
{
Tbase e = new Tbase();
e.AddListener(listener);
instance.eventDictionary.Add(typeof(Tbase), e);
}
}
public static void StartListening<Tbase, T0>(UnityAction<T0> listener) where Tbase : UnityEvent<T0>, new()
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.AddListener(listener);
else
Debug.LogError("EventManager.StartListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
else
{
Tbase e = new Tbase();
e.AddListener(listener);
instance.eventDictionary.Add(typeof(Tbase), e);
}
}
public static void StartListening<Tbase, T0, T1>(UnityAction<T0, T1> listener) where Tbase : UnityEvent<T0, T1>, new()
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.AddListener(listener);
else
Debug.LogError("EventManager.StartListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
else
{
Tbase e = new Tbase();
e.AddListener(listener);
instance.eventDictionary.Add(typeof(Tbase), e);
}
}
public static void StartListening<Tbase, T0, T1, T2>(UnityAction<T0, T1, T2> listener) where Tbase : UnityEvent<T0, T1, T2>, new()
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.AddListener(listener);
else
Debug.LogError("EventManager.StartListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
else
{
Tbase e = new Tbase();
e.AddListener(listener);
instance.eventDictionary.Add(typeof(Tbase), e);
}
}
public static void StartListening<Tbase, T0, T1, T2, T3>(UnityAction<T0, T1, T2, T3> listener) where Tbase : UnityEvent<T0, T1, T2, T3>, new()
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.AddListener(listener);
else
Debug.LogError("EventManager.StartListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
else
{
Tbase e = new Tbase();
e.AddListener(listener);
instance.eventDictionary.Add(typeof(Tbase), e);
}
}
public static void StopListening<Tbase>(UnityAction listener) where Tbase : UnityEvent
{
if (eventManager == null)
return;
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.RemoveListener(listener);
else
Debug.LogError("EventManager.StopListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void StopListening<Tbase, T0>(UnityAction<T0> listener) where Tbase : UnityEvent<T0>
{
if (eventManager == null)
return;
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.RemoveListener(listener);
else
Debug.LogError("EventManager.StopListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void StopListening<Tbase, T0, T1>(UnityAction<T0, T1> listener) where Tbase : UnityEvent<T0, T1>
{
if (eventManager == null)
return;
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.RemoveListener(listener);
else
Debug.LogError("EventManager.StopListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void StopListening<Tbase, T0, T1, T2>(UnityAction<T0, T1, T2> listener) where Tbase : UnityEvent<T0, T1, T2>
{
if (eventManager == null)
return;
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.RemoveListener(listener);
else
Debug.LogError("EventManager.StopListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void StopListening<Tbase, T0, T1, T2, T3>(UnityAction<T0, T1, T2, T3> listener) where Tbase : UnityEvent<T0, T1, T2, T3>
{
if (eventManager == null)
return;
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.RemoveListener(listener);
else
Debug.LogError("EventManager.StopListening() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void TriggerEvent<Tbase>() where Tbase : UnityEvent
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.Invoke();
else
Debug.LogError("EventManager.TriggerEvent() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void TriggerEvent<Tbase, T0>(T0 t0_obj) where Tbase : UnityEvent<T0>
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.Invoke(t0_obj);
else
Debug.LogError("EventManager.TriggerEvent() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void TriggerEvent<Tbase, T0, T1>(T0 t0_obj, T1 t1_obj) where Tbase : UnityEvent<T0, T1>
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.Invoke(t0_obj, t1_obj);
else
Debug.LogError("EventManager.TriggerEvent() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void TriggerEvent<Tbase, T0, T1, T2>(T0 t0_obj, T1 t1_obj, T2 t2_obj) where Tbase : UnityEvent<T0, T1, T2>
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.Invoke(t0_obj, t1_obj, t2_obj);
else
Debug.LogError("EventManager.TriggerEvent() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
public static void TriggerEvent<Tbase, T0, T1, T2, T3>(T0 t0_obj, T1 t1_obj, T2 t2_obj, T3 t3_obj) where Tbase : UnityEvent<T0, T1, T2, T3>
{
UnityEventBase thisEvent = null;
if (instance.eventDictionary.TryGetValue(typeof(Tbase), out thisEvent))
{
Tbase e = thisEvent as Tbase;
if (e != null)
e.Invoke(t0_obj, t1_obj, t2_obj, t3_obj);
else
Debug.LogError("EventManager.TriggerEvent() FAILED! Event type " + typeof(Tbase).ToString() + " could not be accessed for some strange reason.");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using BusinessDomainObject;
using BusinessLogic;
namespace ServiceInterfaceLayer
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class
//name "Service1" in both code and config file together.
public class ProductService : IProductService
{
ProductLogic productLogic = new ProductLogic();
public Product GetProduct(int id)
{
ProductBDO productBDO = null;
try
{
productBDO = productLogic.GetProduct(id);
}
catch (Exception e)
{
string msg = e.Message;
string reason = "GetProduct Exception";
throw new FaultException<ProductFault>(new ProductFault(msg), reason);
}
if (productBDO == null)
{
string msg = string.Format("No product found for id {0}", id);
string reason = "GetProduct Empty Product";
throw new FaultException<ProductFault>(new ProductFault(msg), reason);
}
Product product = new Product();
TranslateProductBDOToProductDTO(productBDO, product);
return product;
}
public bool UpdateProduct(ref Product product, ref string message)
{
bool result = true;
if (product.UnitPrice <= 0)
{
message = "Price cannot be <=0";
result = false;
}
else if (string.IsNullOrEmpty(product.ProductName))
{
message = "Product name cannot be empty";
result = false;
}
else if (string.IsNullOrEmpty(product.QuantityPerUnit))
{
message = "Quantity cannot be empty";
result = false;
}
else
{
try
{
ProductBDO productBDO = null;
TranslateProductDTOToProductBDO(product, productBDO);
result = productLogic.UpdatedProduct(ref productBDO, ref message);
}
catch (Exception e)
{
string msg = e.Message;
throw new FaultException<ProductFault>
(new ProductFault(msg), msg);
}
}
return result;
}
private void TranslateProductBDOToProductDTO(ProductBDO productBDO, Product
product)
{
product.ProductID = productBDO.Product_ID;
product.ProductName = productBDO.Product_Name;
product.QuantityPerUnit = productBDO.Quantity_Per_Unit;
product.UnitPrice = productBDO.Unit_Price;
product.Discontinued = productBDO.Discontinued;
}
private void TranslateProductDTOToProductBDO(Product product, ProductBDO
productBDO)
{
productBDO.Product_ID = product.ProductID;
productBDO.Product_Name = product.ProductName;
productBDO.Quantity_Per_Unit = product.QuantityPerUnit;
productBDO.Unit_Price = product.UnitPrice;
productBDO.Discontinued = product.Discontinued;
}
}
} |
using i18n;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SQLServerBackupTool.Web.Lib.Mvc
{
public partial class ApplicationController : ILocalizing
{
private static readonly ILocalizingService LocaleService = new LocalizingService();
public string __(string text)
{
if (Request == null || Request.UserLanguages == null || !Request.UserLanguages.Any())
{
return text;
}
// // Prefer a stored value to browser-supplied preferences
// var stored = LanguageSession.GetLanguageFromSession(ControllerContext.HttpContext);
// if (stored != null)
// {
// return _service.GetText(text, new[] { stored });
// }
// Find the most appropriate fit from the user's browser settings
return LocaleService.GetText(text, Request.UserLanguages);
}
public IHtmlString _(string text)
{
return new MvcHtmlString(__(text));
}
}
} |
using Photon.Pun;
using Source.Code.Environment;
using System.Collections;
using UnityEngine;
namespace Source.Code.Units.Components
{
public class AnimationComponent : MonoBehaviour
{
[SerializeField] private float bodyGetDownAfter = 3f;
[SerializeField] private float bodyGetDownSpeed = 2f;
[SerializeField] private float bodyDestroyDelay = 2f;
private Unit unit;
private Animator animator;
private int takeDamageLayerIndex, fullBodyLayerIndex;
private float takeDamageDuration = 0.667f;
private WaitForSeconds waitForTakeDamage;
private Coroutine takeDamageCoroutine;
private Transform deathAnimationModel;
public Transform Transform { get; private set; }
public void Initialize(Unit unit)
{
this.unit = unit;
animator = GetComponentInChildren<Animator>();
if (!animator) Debug.LogError("Can't find animator", transform);
Transform = transform;
takeDamageLayerIndex = animator.GetLayerIndex("TakeDamageLayer");
fullBodyLayerIndex = animator.GetLayerIndex("FullBody");
waitForTakeDamage = new WaitForSeconds(takeDamageDuration);
unit.HealthComponent.TakedDamage += OnTakeDamage;
InitializeDeathAnimationModel();
}
public void OnDisable()
{
if (deathAnimationModel == null) return;
deathAnimationModel.transform.position = unit.Transform.position;
deathAnimationModel.transform.rotation = unit.Model.rotation;
deathAnimationModel.gameObject.SetActive(true);
var modelCopyAnimator = deathAnimationModel.GetComponentInChildren<Animator>();
modelCopyAnimator.SetLayerWeight(fullBodyLayerIndex, 1);
modelCopyAnimator.CrossFade("Die", 0.1f);
deathAnimationModel.gameObject.AddComponent<Destroyer>().DestroyAfterFallingUnderground(bodyGetDownAfter, bodyGetDownSpeed, bodyDestroyDelay);
}
public void SpeedObserver()
{
}
public void SetLegsAnimation()
{
Vector3 offsetDirFromLastFrame = (unit.Transform.position - unit.LastFramePosition).normalized;
var angle = Vector2.SignedAngle(Vector2.up, new Vector2(Transform.forward.x, Transform.forward.z));
Vector3 rot = Quaternion.Euler(0, angle, 0) * new Vector3(offsetDirFromLastFrame.x, 0, offsetDirFromLastFrame.z);
animator.SetFloat("MoveDeltaX", rot.x);
animator.SetFloat("MoveDeltaY", rot.z);
}
public void PlayAnimation(string name)
{
animator.CrossFade(name, 0.1f);
}
public void PlayRollAnimation()
{
animator.SetLayerWeight(fullBodyLayerIndex, 1);
PlayAnimation("Roll");
}
public void EndRollAnimation()
{
animator.SetLayerWeight(fullBodyLayerIndex, 0);
PlayAnimation("Idle");
}
private void OnTakeDamage(Vector3 fromPoint, Unit fromUnit)
{
if (takeDamageCoroutine != null) StopCoroutine(takeDamageCoroutine);
if (unit.HealthComponent.IsAlive) takeDamageCoroutine = StartCoroutine(TakeDamageCoroutine(fromPoint, fromUnit));
}
private IEnumerator TakeDamageCoroutine(Vector3 fromPoint, Unit fromUnit)
{
animator.SetLayerWeight(takeDamageLayerIndex, 1);
float angle = Vector3.SignedAngle(unit.Model.right, (fromPoint - unit.Transform.position), Vector3.up);
string animName = angle <= 0 ? "TakeDamageBackward" : "TakeDamageForward";
animator.Play(animName);
yield return waitForTakeDamage;
animator.SetLayerWeight(takeDamageLayerIndex, 0);
}
private void InitializeDeathAnimationModel()
{
deathAnimationModel = Instantiate(unit.Model.gameObject).transform;
deathAnimationModel.gameObject.name = unit.OwnerNickName + " death animation model";
deathAnimationModel.gameObject.SetActive(false);
var trView = deathAnimationModel.GetComponent<PhotonTransformView>();
if (trView != null) Destroy(trView);
}
}
} |
using BP12.Collections;
using BP12.Events;
using DChild.Gameplay.Combat;
using DChild.Gameplay.Environment.Obstacles;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaterGeyser : IntervalObstacle
{
[SerializeField]
[AttackType(AttackType.Physical)]
private AttackDamage m_damage;
[SerializeField]
private CountdownTimer m_intervalTimer;
[SerializeField]
private float m_maxDistance;
protected override AttackInfo attackInfo => new AttackInfo(m_damage, 0, null, null);
protected override DamageFXType damageFXType => DamageFXType.None;
protected override EventActionArgs OnActiveEnd(object sender, EventActionArgs eventArgs)
{
throw new System.NotImplementedException();
}
protected override EventActionArgs OnInactiveEnd(object sender, EventActionArgs eventArgs)
{
throw new System.NotImplementedException();
}
}
|
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.system;
using System.Collections.Generic;
namespace gView.Framework.Carto
{
//public delegate void DatasetAddedEvent(IMap sender,IDataset dataset);
public delegate void LayerAddedEvent(IMap sender, ILayer layer);
public delegate void LayerRemovedEvent(IMap sender, ILayer layer);
public delegate void NewBitmapEvent(GraphicsEngine.Abstraction.IBitmap bitmap);
public delegate void DoRefreshMapViewEvent();
public delegate void StartRefreshMapEvent(IMap sender);
public delegate void DrawingLayerEvent(string layerName);
public delegate void TOCChangedEvent(IMap sender);
public delegate void NewExtentRenderedEvent(IMap sender, IEnvelope extent);
public delegate void DrawingLayerFinishedEvent(IMap sender, ITimeEvent timeEvent);
public delegate void UserIntefaceEvent(IMap sender, bool lockUI);
/*
public interface IDataView
{
string Name { get; set; }
IMap Map { get; set; }
}
*/
//public delegate bool LayerIsVisibleHook(string layername,bool defaultValue);
public delegate void BeforeRenderLayersEvent(IServiceMap sender, List<ILayer> layers);
public delegate void MapScaleChangedEvent(IDisplay sender);
public delegate void RenderOverlayImageEvent(GraphicsEngine.Abstraction.IBitmap bitmap, bool clearOld);
// Projective > 0
// Geographic < 0
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Trees.TreeHelper
{
class BinaryTreeNodeWithParent<T>
{
public BinaryTreeNodeWithParent<T> Left { get; set; }
public BinaryTreeNodeWithParent<T> Right { get; set; }
public BinaryTreeNodeWithParent<T> Parent { get; set; }
public T Data { get; set; }
public BinaryTreeNodeWithParent(T data)
{
Data = data;
}
}
class BinaryTreeWithParent<T> where T:IComparable
{
public BinaryTreeNodeWithParent<T> Head { get; set; }
private Queue<BinaryTreeNodeWithParent<T>> BtQueue { get; set; }
/// <summary>
/// Creates a complete binary tree with the array of tree data provided
/// </summary>
/// <param name="dataForTree">array of tree data provided</param>
public BinaryTreeWithParent(T[] dataForTree, bool IsCompleteTree)
{
if (IsCompleteTree)
{
BtQueue = new Queue<BinaryTreeNodeWithParent<T>>();
for (int index = 0; index < dataForTree.Length; index++)
{
InsertToCreateCompleteBT(dataForTree[index]);
}
}
else
{
for (int index = 0; index < dataForTree.Length; index++)
{
InsertSkewed(dataForTree[index]);
}
}
}
public void InsertToCreateCompleteBT(T data)
{
if (Head == null)
{
Head = new BinaryTreeNodeWithParent<T>(data);
BtQueue.Enqueue(Head);
}
else
{
BinaryTreeNodeWithParent<T> nodeToAdd = new BinaryTreeNodeWithParent<T>(data);
BinaryTreeNodeWithParent<T> nodeFromQueue = BtQueue.Peek();
if (nodeFromQueue.Left == null)
{
// add the new node to the left if the left node is not present on the nodeFromQueue
nodeFromQueue.Left = nodeToAdd;
nodeToAdd.Parent = nodeFromQueue;
}
else if (nodeFromQueue.Right == null)
{
// add the new node to the right if the right node is not present on the nodeFromQueue
nodeFromQueue.Right = nodeToAdd;
nodeToAdd.Parent = nodeFromQueue;
// Now both the left and right nodes of the nodeFromQueue is full, so we can dequeue it
BtQueue.Dequeue();
}
else
{
// we should never hit this condition, as we are dequeueing the Binary Tree node in the condition before
throw new Exception("The node with both left and right nodes notqual to null is present in the queue");
}
BtQueue.Enqueue(nodeToAdd);
}
}
public void InsertSkewed(T data)
{
if (Head == null)
{
Head = new BinaryTreeNodeWithParent<T>(data);
}
else
{
BinaryTreeNodeWithParent<T> currentNode = Head;
while (currentNode.Left != null)
{
currentNode = currentNode.Left;
}
BinaryTreeNodeWithParent<T> nodeToAdd = new BinaryTreeNodeWithParent<T>(data);
currentNode.Left = nodeToAdd;
nodeToAdd.Parent = currentNode;
}
}
public BinaryTreeNodeWithParent<T> Search(T data)
{
Queue<BinaryTreeNodeWithParent<T>> queueForTreeNodes = new Queue<BinaryTreeNodeWithParent<T>>();
queueForTreeNodes.Enqueue(Head);
while(queueForTreeNodes.Count!=0)
{
BinaryTreeNodeWithParent<T> currentNode = queueForTreeNodes.Dequeue();
if(currentNode.Data.CompareTo(data) == 0)
{
// Found the node
return currentNode;
}
if(currentNode.Left!=null)
{
queueForTreeNodes.Enqueue(currentNode.Left);
}
if(currentNode.Right!=null)
{
queueForTreeNodes.Enqueue(currentNode.Right);
}
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GSVM.Components;
namespace GSVM.Devices
{
public class DiskDrive : GenericDeviceBus<DiskDriveRequest>
{
public const byte LEN = 6;
public const byte PING = 7;
public const byte REPLY = 8;
protected IMemory memory;
public bool ReadOnly { get; private set; }
private DiskDrive(bool isReadOnly = false)
{
ReadOnly = isReadOnly;
deviceType = 2;
GenerateID();
}
public DiskDrive(uint size, bool isReadOnly = false) : this(isReadOnly)
{
memory = new Memory(size);
}
public DiskDrive(IMemory memory, bool isReadOnly = false) : this(isReadOnly)
{
this.memory = memory;
}
public override void ClockTick()
{
if (readData == null)
readData = new DiskDriveRequest();
if (ReadyToWrite)
{
readData.length = 0;
readData.diskData = new byte[0];
readData.data = 0;
readData.control = 0;
switch (WriteData.control)
{
// READ
case READ:
readData.control = ACK;
readData.data = writeData.data;
readData.length = writeData.length;
try
{
readData.diskData = memory.Read(writeData.data, writeData.length);
}
catch
{
// error
readData.control = ERROR;
readData.data = 0;
}
break;
case WRITE:
if (ReadOnly)
{
readData.control = ERROR;
readData.data = 1; // cannot overwrite read-only memory
}
else
{
readData.control = ACK;
readData.data = WriteData.data;
readData.length = WriteData.length;
try
{
memory.Write(writeData.data, writeData.diskData);
}
catch
{
readData.control = ERROR; // error
readData.data = 0; // Unknown
}
}
break;
case LEN:
readData.control = ACK; // ack
readData.data = memory.Length;
break;
case PING:
readData.control = REPLY; // reply
break;
}
}
base.ClockTick();
}
protected override bool InterruptChannelOk(uint channel)
{
return true;
}
}
}
|
using System.Web;
using System.Web.Optimization;
namespace WebsiteQuanLyPhatHanhSach
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/JavaScript").Include(
"~/Content/bower_components/jquery/dist/jquery.min.js",
"~/Content/bower_components/bootstrap/dist/js/bootstrap.min.js",
"~/Content/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
"~/Content/bower_components/fastclick/lib/fastclick.js",
"~/Content/bower_components/select2/dist/js/select2.full.min.js",
"~/Content/dist/js/adminlte.min.js",
"~/Content/dist/js/demo.js"));
bundles.Add(new StyleBundle("~/CSS").Include(
"~/Content/bower_components/bootstrap/dist/css/bootstrap.min.css",
"~/Content/bower_components/font-awesome/css/font-awesome.min.css",
"~/Content/bower_components/Ionicons/css/ionicons.min.css",
"~/Content/plugins/iCheck/all.css",
"~/Content/dist/css/AdminLTE.min.css",
"~/Content/bower_components/select2/dist/css/select2.min.css",
"~/Content/dist/css/skins/_all-skins.min.css"));
BundleTable.EnableOptimizations = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRAP.Global;
namespace BatchSystemMNGNT_Asimco.Entities
{
public class TEntityXMLINVA01 : IXMLNodeObject
{
public string AgencyLeaf { get; set; }
public string SysLogID { get; set; }
public string StationID { get; set; }
public string RoleLeaf { get; set; }
public string CommunityID { get; set; }
public string UserCode { get; set; }
public string ExCode { get; set; }
public string UserID { get; set; }
public string PassWord { get; set; }
public string ItemNumber { get; set; }
public string Stockroom { get; set; }
public string Bin { get; set; }
public string InventoryCategory { get; set; }
public string DocumentNumber { get; set; }
public string ActionCode { get; set; }
public string AdjustQuantity { get; set; }
public string Reason { get; set; }
public string InventoryOffsetMasterAccountNumber { get; set; }
public string LotIdentifier { get; set; }
public string LotNumber { get; set; }
public string VendorLotNumber { get; set; }
public string GetXMLString()
{
return IRAPXMLUtils.ObjectToXMLString(this, "Parameters", "Param");
}
}
}
|
using AutoMapper;
using WebApi.Dto;
using WebApi.Entities;
namespace WebApi.Profiles{
public class PresentsProfile: Profile{
public PresentsProfile()
{
//Source=>target
CreateMap<Present,PresentReadDto>();
CreateMap<PresentCreateDto,Present>();
//CreateMap<PresentUpdateDto,PresentItem>();
//CreateMap<Present,PresentUpdateDto>();
}
}
} |
using System.Collections.Generic;
namespace StolenTests
{
public interface INumberHelper
{
/// <summary>
/// Find a node that satisfy a given predicate and return it.
/// </summary>
/// <param name="needle">Number that is searched for</param>
/// <param name="haystack">Collection of numbers that are searched through</param>
/// <param name="n">The amount of numbers close to needle that should be returned</param>
/// <returns>A collection with the n numbers in haystack closest to needle</returns>
IEnumerable<int> FindClosestNumbers(int needle, IEnumerable<int> haystack, int n);
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BillsPaymentModels
{
public class User
{
public User()
{
this.BillingDetails = new HashSet<BillingDetail>();
}
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public ICollection<BillingDetail> BillingDetails { get; set; }
}
}
|
namespace BettingSystem.Domain.Games.Models.Matches
{
using System;
using Bogus;
using Common.Models;
using FakeItEasy;
using Teams;
public class MatchFakes
{
public class MatchDummyFactory : IDummyFactory
{
public bool CanCreate(Type type) => type == typeof(Match);
public object? Create(Type type)
=> new Faker<Match>()
.CustomInstantiator(_ => new Match(
DateTime.UtcNow,
A.Dummy<Team>(),
A.Dummy<Team>(),
A.Dummy<Stadium>(),
A.Dummy<Statistics>(),
Status.FirstHalf))
.Generate()
.SetId(1);
public Priority Priority => Priority.Default;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TricareManagementSystem.Model;
namespace TricareManagementSystem.DataAccess.User
{
public class AddNewRegulation
{
public RegulationDTO Regulation { get; set; }
public bool Add()
{
SqlParameter[] _parameters =
{
new SqlParameter("@RegulationName",Regulation.RegulationName),
new SqlParameter("@Description",Regulation.Description),
new SqlParameter("@DateOfCreation",Regulation.DateOfCreation),
new SqlParameter(" @DateOfModification",Regulation.DateOfModification)
};
DataBaseHelper dbHelper = new DataBaseHelper(StoredProcedure.ADD_REGULATION);
dbHelper.Parameters = _parameters;
return dbHelper.ExcecuteNonQuery();
}
}
}
|
namespace _2X2SquareInMatrix
{
using System;
public class Startup
{
public static void Main(string[] args)
{
Console.WriteLine(Execute());
}
private static int Execute()
{
var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var n = int.Parse(args[0]);
var m = int.Parse(args[1]);
var matrix = new char[n, m];
for (int i = 0; i < n; i++)
{
args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < m; j++)
{
matrix[i, j] = args[j][0];
}
}
var res = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m - 1; j++)
{
var first = matrix[i, j];
var isEqualSquare = true;
for (int k = i; k < i + 2 && k < n; k++)
{
for (int p = j; p < j + 2 && p < m; p++)
{
if (matrix[k, p] != matrix[i, j])
{
isEqualSquare = false;
break;
}
}
if (!isEqualSquare) break;
}
if (isEqualSquare) res++;
}
}
return res;
}
}
} |
using System.Collections.Generic;
using dgPower.KMS.Roles.Dto;
namespace dgPower.KMS.Web.Models.Roles
{
public class RoleListViewModel
{
public IReadOnlyList<PermissionDto> Permissions { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using POSServices.Models;
using POSServices.WebAPIModel;
namespace POSServices.Controllers
{
[Route("api/ChangePasswordAPI")]
[ApiController]
public class ChangePasswordAPIController : Controller
{
private readonly DB_BIENSI_POSContext _context;
public ChangePasswordAPIController(DB_BIENSI_POSContext context)
{
_context = context;
}
[HttpPost]
public async Task<IActionResult> changepass([FromBody]ChangePasswordModel change)
{
var employeecode = await _context.Employee.Where(c => c.EmployeeCode == change.username).Select(c => c.Id).FirstOrDefaultAsync();
var login = await _context.UserLogin.FirstOrDefaultAsync(x => x.UserId == employeecode);
if (login == null)
{
return StatusCode(404, new
{
status = "404",
error = true,
message = "Username Not found"
});
}
if (!VerifyPasswordHash(change.currentpassword, login.PasswordHash, login.PasswordSalt))
{
return StatusCode(404, new
{
status = "404",
error = true,
message = "Incorrect Current Password"
});
}
byte[] passwordHash, passwordSalt;
CreatePasswordHash(change.newpassword, out passwordHash, out passwordSalt);
login.PasswordHash = passwordHash;
login.PasswordSalt = passwordSalt;
login.OldPassword = change.newpassword;
_context.UserLogin.Update(login);
_context.SaveChanges();
return StatusCode(200, new
{
status = "200",
error = false,
message = "Change password success!"
});
}
private bool VerifyPasswordHash(string currentpassword, byte[] passwordHash, byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(currentpassword));
for (int i = 0; i < computedHash.Length; i++)
{
if (computedHash[i] != passwordHash[i]) return false;
}
}
return true;
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetGun : MonoBehaviour {
GameObject player;
public static int isGetgun=0;
public static int isaim=0;
public static int name=0;
public int tem=0;
void Awake(){
player = GameObject.FindGameObjectWithTag("Player");
Debug.Log (player);
}
void OnTriggerStay(Collider other){
if (other.gameObject == player) {
if(Input.GetKey("f")){
Destroy (gameObject,0f);
isGetgun= 1;
isaim = 1;
name = tem;
}
}
}
}
|
using PizzaBox.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace PizzaBox.Domain.Interfaces
{
public interface ICustomer : IRepository<Customer>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PInvoke.WindowsResolution;
using System.Threading;// Thread.Sleep, for the exit sleep timer...
using System.Configuration;//ConfigurationManager
//log4net should use config from app
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace setDisplayRes
{
/// <summary>
/// Yes, this is the easiest way to set the display resolution (19.06.2017).
/// Windows ;-(
/// https://msdn.microsoft.com/en-us/library/aa719104(v=vs.71).aspx
/// </summary>
class Program
{
// Create a logger for use in this class
static log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
Console.WriteLine(" ------------------------------------------------------ ");
Console.WriteLine(" ------------ set Display Resolution ------------- ");
Console.WriteLine(" ------------------------------------------------------ ");
//Console.WriteLine("Welcome to the extra complicated windows display resolution setter.");
Console.WriteLine(" Possible Arguments: ");
Console.WriteLine(" -set : sets the Resolutions defined in the config. ");
Console.WriteLine(" -list : lists all Displays ");
Console.WriteLine(" -listmodes : lists modes of a Displays ");
Console.WriteLine();
bool bSet = false;
bool bListDisplays = false;
bool bListDisplayModes = false;
string strArguments = "";
foreach (string arg in args)
{
if (strArguments != "")
{
strArguments += " ";
}
strArguments += arg;
string strLowerArg = arg.ToLower();
Console.WriteLine("check Arguments: " + strLowerArg);
if (strLowerArg == "-list")
{
bListDisplays = true;
}else if (strLowerArg == "-listmodes")
{
bListDisplayModes = true;
}
else if (strLowerArg == "-set")
{
bSet = true;
}
else
{
string strWrongArgMsg = " UNKNOWN ARGUMENT: " + arg;
Console.WriteLine(strWrongArgMsg);
_log.Error(strWrongArgMsg);
//exit delay animation
ExitWithDelay(3000);
return; //exit
}
}//foreach arg
_log.Debug("Program Start, Arguments: " + strArguments);
_log.Debug("User: '" + Environment.UserName + "'.");
_log.Debug("UserInteractive: '" + Environment.UserInteractive.ToString() + "'.");
_log.Debug("CurrentDirectory: '" + Environment.CurrentDirectory + "'.");
_log.Debug("CommandLine: '" + Environment.CommandLine + "'.");
_log.Debug("UserDomainName: '" + Environment.UserDomainName + "'.");
_log.Debug("SystemDirectory: '" + Environment.SystemDirectory + "'.");
if (bListDisplays)
{
_log.Debug("list displays");
//get all Displays
Display display = new Display();
List<DISPLAY_DEVICE> displays = display.GetDisplayList();
Console.WriteLine();
foreach (DISPLAY_DEVICE dev in displays)
{
String strDevice = "Name: '" + dev.DeviceName + "' String: '" + dev.DeviceString + "' Id: '" + dev.DeviceID + "'.";
Console.WriteLine("Device Found: " + strDevice);
}
}
else if (bListDisplayModes)
{
_log.Debug("list modes of a display");
Console.WriteLine("Enter a DeviceName to process:");
string strDeviceName = Console.ReadLine();
//get all Modes
Display display = new Display();
List<DevMode> modes = display.GetDisplaySettings(strDeviceName);
foreach (DevMode mode in modes)
{
String strMode = "Width: '" + mode.dmPelsWidth + "' Height: '" + mode.dmPelsHeight + "' Frequency: '" + mode.dmDisplayFrequency.ToString() + "'.";
Console.WriteLine(strMode);
}
}
else if (bSet)
{
_log.Info("Set DisplayModus to Extend");
//okay, first we set the display to extende to change both/all displays
NativeMethods.SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, ChangeDisplayConfigFlags.SDC_TOPOLOGY_EXTEND | ChangeDisplayConfigFlags.SDC_APPLY);
_log.Debug("adjust resolutions");
changeDisplaySettings();
bool bDuplicateMode = System.Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("setWindowModeDuplicated"));
bool bDuplicateModeSetRes = System.Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("setWindowModeDuplicatedChangeRes"));
if (bDuplicateMode)
{
//now we set the resolution again, but in clone modus.
_log.Info("Set DisplayModus to Duplicate");
NativeMethods.SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, ChangeDisplayConfigFlags.SDC_TOPOLOGY_CLONE | ChangeDisplayConfigFlags.SDC_APPLY);
if (bDuplicateModeSetRes)
{
_log.Debug("adjust resolution");
changeDisplaySettings(false);
}
}
}
else
{
//nothing to do.
}
_log.Debug("Program End");
//exit delay animation
ExitWithDelay(6000);
}//main()
/// <summary>
/// Dont set primary when in Duplicate Modus. Any Monitor (so usualy the wrong one) can be Primary after.
/// Best to set Prmiary it in Extend Modus only.
/// </summary>
/// <param name="bUsePrimarySettings"></param>
static private void changeDisplaySettings(bool bUsePrimarySettings = true)
{
//get Config (fails when config is wrong)
_log.Debug("read config, Start - fails when config is wrong");
//get MkDirServers from config file (fails when config is wrong)
DisplayConfig config = (DisplayConfig)ConfigurationManager.GetSection("DisplaySettings");
if (config != null)
{
_log.Debug("DisplaySettings loaded.");
}
else
{
String strError = "Worker, failed to load DisplaySettings section. -> check config file.";
_log.Fatal(strError);
throw new Exception(strError);
}
List<DisplayElement> configdisplays = config.GetAllDisplays();
foreach (DisplayElement displ in configdisplays)
{
_log.Debug("setting found: " + displ.ToString());
}
_log.Debug("read config, End");
//get all Displays from Windows
Display display = new Display();
List<DISPLAY_DEVICE> windowsdisplays = display.GetDisplayList();
//all windows installed displays
foreach (DISPLAY_DEVICE dev in windowsdisplays)
{
//display defined in configuration
foreach (DisplayElement configDisplay in configdisplays)
{
//check name or devicestring
bool bMatchingName = false;
if (configDisplay.name != "")
{
//use device name
if (configDisplay.name == "*" || configDisplay.name.ToLower() == dev.DeviceName.ToLower())
{
bMatchingName = true;
}
}
else if (configDisplay.devicestring != "")
{
//use device string (usualy the real name)
if (configDisplay.devicestring.ToLower() == dev.DeviceString.ToLower())
{
bMatchingName = true;
}
}
else if (configDisplay.deviceid != "")
{
//use device string (usualy the real name)
if (dev.DeviceID.ToLower().Contains(configDisplay.deviceid.ToLower()))
{
bMatchingName = true;
}
}
else
{
throw new Exception("must define name, devicestring or deviceid");
}
//found?
if (bMatchingName)
{
//found
_log.Debug("matching device found, name: '" + dev.DeviceName + "' string: '" + dev.DeviceString + "'.");
//get resolutions
List<DevMode> settings = display.GetDisplaySettings(dev.DeviceName);
bool bResFound = false;
DevMode selectedMode = new DevMode();
foreach (DevMode mode in settings)
{
if (mode.dmPelsHeight == configDisplay.height && mode.dmPelsWidth == configDisplay.width)
{
_log.Debug("matching resolution found: " + dev.DeviceName);
//optional
if (configDisplay.freqhz > 0)
{
if (mode.dmDisplayFrequency == configDisplay.freqhz)
{
_log.Debug("matching frequency found: " + dev.DeviceName);
//bingo
bResFound = true;
selectedMode = mode;
break;
}
}
else
{
//ignore freq
//bingo
bResFound = true;
selectedMode = mode;
break;
}
}
}//foreach mode of this display
if (bResFound)
{
_log.Debug("settings found for device" + dev.DeviceName);
//set resolution
if (bResFound)
{
bool bSetAsPrimary = false;
if(bUsePrimarySettings)
{
bSetAsPrimary = configDisplay.primary;
}
_log.Info("Change Settings, name: '" + dev.DeviceName + "', id: '" + dev.DeviceID + "'. primary: '" + bSetAsPrimary.ToString() + "' Res: " + selectedMode.dmPelsWidth.ToString() + "x" + selectedMode.dmPelsHeight.ToString() + " " + selectedMode.dmDisplayFrequency + "Hz");
string strError = display.ChangeSettings(dev, selectedMode, bSetAsPrimary);
if (strError == "")
{
_log.Debug("Changed Settings successful.");
}
else
{
_log.Error("Changed Settings with Error: " + strError);
}
}
else
{
Console.WriteLine("could not find the Resolution in the possible Modes.");
}
}
else
{
_log.Debug("no matching settings found for device, name: '" + dev.DeviceName + "', id: '" + dev.DeviceID + "'.");
}
}//if match
}//foreach config entry
}//foreach windows device
}
static private void ExitWithDelay(long a_lDelayMs)
{
//exit delay animation
if (a_lDelayMs > 1000)
{
Console.WriteLine("");
// chose one of the exit animations...
//AnimateTheDotsLine(a_lDelayMs); //shit
AnimateTheSecondsCounter(a_lDelayMs, "Exit in: '"); // okay
// coming soon in this theater: multiline animations ! ;-)
}
}
static private void AnimateTheSecondsCounter(long a_lDelayMs, string a_strText)
{
// Close the Application with delay
Console.Write(a_strText);
// Countdown...
for (int i = System.Convert.ToInt32(a_lDelayMs / 1000); i > 0; i--)
{
String strText = i.ToString() + "'.";
Console.Write(strText);
Thread.Sleep(1000);
Console.Write(new string('\b', strText.Length));
}
}//AnimateTheCounter
}//class
}//ns
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class FinaleDayController : MonoBehaviour {
[SerializeField]
private Text[] averages;
[SerializeField]
private Text message;
[SerializeField]
private GameController gameController;
[SerializeField]
private GameObject ScreenFinale;
private float time;
private int atualnumber;
private int progress;
public float mFinale;
void Start () {
progress = 1;
}
void Update ()
{
if(gameController.FinaleDay)
{
if (mFinale.Equals(0)) mFinale = (gameController.props.x + gameController.props.y + gameController.props.z) / 3;
ScreenFinale.SetActive(true);
SumToMedia(int.Parse(gameController.props.x.ToString()), int.Parse(gameController.props.y.ToString()), int.Parse(gameController.props.z.ToString()), int.Parse(Mathf.Floor(mFinale).ToString()));
}
}
void SumToMedia(int mHospital, int mSchool, int mPolice, int mFinale)
{
if (atualnumber < mHospital && atualnumber / (mHospital * (mHospital + 1 - atualnumber) - atualnumber) <= Time.fixedTime - time && progress.Equals(1))
{
time = Time.fixedTime;
atualnumber++;
averages[0].text = "Media Hospital:" + atualnumber.ToString() + "%";
}
else if(progress.Equals(1))
{
progress = 2;
time = 0;
atualnumber = 0;
}
if (atualnumber < mSchool && atualnumber / (mSchool * (mSchool + 1 - atualnumber) - atualnumber) <= Time.fixedTime - time && progress.Equals(2))
{
time = Time.fixedTime;
atualnumber++;
averages[1].text = "Media Escola:" + atualnumber.ToString() + "%";
}
else if(progress.Equals(2))
{
progress = 3;
time = 0;
atualnumber = 0;
}
if (atualnumber < mPolice && atualnumber / (mPolice * (mPolice + 1 - atualnumber) - atualnumber) <= Time.fixedTime - time && progress.Equals(3))
{
time = Time.fixedTime;
atualnumber++;
averages[2].text = "Media Policia:" + atualnumber.ToString() + "%";
}
else if (progress.Equals(3))
{
progress = 4;
time = 0;
atualnumber = 0;
}
if (atualnumber < mFinale && atualnumber / (mFinale * (mFinale + 1 - atualnumber) - atualnumber) <= Time.fixedTime - time && progress.Equals(4))
{
time = Time.fixedTime;
atualnumber++;
averages[3].text = "Media Final:" + atualnumber.ToString() + "%";
}
else if (progress.Equals(4))
{
progress = 5;
time = 0;
atualnumber = 0;
MessageFeedBack(mFinale);
}
}
void MessageFeedBack(float mFinale)
{
if (mFinale > 80)
{
message.text = "Perfect Media !";
}
else if (mFinale < 80 && mFinale > 60)
{
message.text = "Very Good Media !";
}
else if (mFinale < 60 && mFinale > 55)
{
message.text = " Good Media !";
}
else if (mFinale < 55)
{
message.text = " Bad Media !";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.PrintModel.INV;
namespace com.Sconit.Utility.Report.Operator
{
public class RepStockTakingOperator : RepTemplate2
{
public RepStockTakingOperator()
{
//明细部分的行数
this.pageDetailRowCount = 8;
//列数 1起始
this.columnCount = 4;
this.rowCount = 8;
//报表头的行数 1起始
this.leftColumnHeadCount = 0;
//报表尾的行数 1起始
this.bottomRowCount = 0;
this.headRowCount = 0;
}
/**
* 需要拷贝的数据与合并单元格操作
*
* Param pageIndex 页号
*/
public override void CopyPageValues(int pageIndex)
{
//this.SetMergedRegionColumn(pageIndex, 0, 1, 0, 3);
//this.SetMergedRegionColumn(pageIndex, 1, 0, 2, 0);
//this.SetMergedRegionColumn(pageIndex, 5, 1, 5, 3);
////this.SetMergedRegionColumn(pageIndex, 6, 1, 6, 3);
//this.SetMergedRegionColumn(pageIndex, 6, 0, 6, 3);
//this.SetMergedRegionColumn(pageIndex, 7, 0, 7, 3);
//this.CopyCellColumn(pageIndex, 0, 0, "A1");
//this.CopyCellColumn(pageIndex, 1, 0, "A2");
//this.CopyCellColumn(pageIndex, 3, 0, "A4");
//this.CopyCellColumn(pageIndex, 4, 0, "A5");
//this.CopyCellColumn(pageIndex, 5, 0, "A6");
//this.CopyCellColumn(pageIndex, 1, 2, "C2");
//this.CopyCellColumn(pageIndex, 2, 2, "C3");
//this.CopyCellColumn(pageIndex, 3, 2, "C4");
//this.CopyCellColumn(pageIndex, 4, 2, "C5");
}
/**
* 填充报表
*
* Param list [0]huDetailList
*/
protected override bool FillValuesImpl(String templateFileName, IList<object> data)
{
try
{
PrintStockTakeMaster printStockTakeMaster = (PrintStockTakeMaster)data[0];
if (printStockTakeMaster == null)
{
return false;
}
this.sheet.DisplayGridlines = false;
this.sheet.IsPrintGridlines = false;
this.barCodeFontName = this.GetBarcodeFontName(0, 0);
int pageIndex = 1;
string barCode = Utility.BarcodeHelper.GetBarcodeStr(printStockTakeMaster.StNo, this.barCodeFontName);
this.SetColumnCell(pageIndex, 0, 0, barCode);
this.SetColumnCell(pageIndex, 1, 0, printStockTakeMaster.StNo);
this.SetColumnCell(pageIndex, 2, 2, printStockTakeMaster.Region);
this.SetColumnCell(pageIndex, 3, 2, printStockTakeMaster.Type == 0 ? "抽盘" : "全盘");
this.SetColumnCell(pageIndex, 4, 2, printStockTakeMaster.EffectiveDate.HasValue ? printStockTakeMaster.EffectiveDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty);
this.SetColumnCell(pageIndex, 5, 2, printStockTakeMaster.IsScanHu ? "√" : "×");
this.SetColumnCell(pageIndex, 6, 2, printStockTakeMaster.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
this.SetColumnCell(pageIndex, 7, 2, printStockTakeMaster.CreateUserName);
}
catch (Exception e)
{
return false;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSConsoleRL.Enums;
using CSConsoleRL.Entities;
using CSConsoleRL.Helpers;
namespace CSConsoleRL.Events
{
public class NotifyChangeGameStateEvent : IGameEvent
{
public string EventName { get { return "NotifyChangeGameState"; } }
public List<object> EventParams { get; set; }
public NotifyChangeGameStateEvent(EnumGameState enumGameState)
{
EventParams = new List<object>() { };
EventParams.Add(enumGameState);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Calder1
{
public partial class RenameForm : Form
{
public RenameForm()
{
InitializeComponent();
}
public void SetFileName(string fileName)
{
textBox1.Text = fileName;
}
public string GetFileName()
{
return textBox1.Text;
}
}
}
|
using UnityEngine;
using UnityEngine.Events;
using System.Collections.Generic;
namespace Ardunity
{
public class DragData
{
public bool isDrag;
public float delta;
public float force;
public DragData()
{
isDrag = false;
delta = 0f;
force = 0f;
}
public DragData(DragData source)
{
isDrag = source.isDrag;
delta = source.delta;
force = source.force;
}
}
[AddComponentMenu("ARDUnity/Bridge/Input/DragInput")]
[HelpURL("https://sites.google.com/site/ardunitydoc/references/bridge/draginput")]
public class DragInput : ArdunityBridge, IWireInput<DragData>, IWireInput<float>
{
[Range(0f, 1f)]
public float minValue = 0.1f;
[Range(0f, 1f)]
public float maxValue = 0.9f;
public bool invert = false;
public float deltaMultiplier = 1f;
public float forceMultiplier = 1f;
public UnityEvent OnDragStart;
public UnityEvent OnDragEnd;
private AnalogInput _analogInput;
private DragData _dragData = new DragData();
private float _startValue;
private float _value;
private float _time;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(_analogInput != null)
{
if(_analogInput.connected)
{
float value = _analogInput.Value;
_time += Time.deltaTime;
if(value > minValue && value < maxValue)
{
if(!_dragData.isDrag)
{
_dragData.isDrag = true;
_dragData.delta = 0f;
_dragData.force = 0f;
_startValue = value;
_value = value;
_time = 0f;
if(_OnDragDataChanged != null)
_OnDragDataChanged(new DragData(_dragData));
OnDragStart.Invoke();
}
else
{
if(_value != value)
{
_dragData.delta = (_value - value) * deltaMultiplier;
if(invert)
_dragData.delta = -_dragData.delta;
_value = value;
if(_OnDragDataChanged != null)
_OnDragDataChanged(new DragData(_dragData));
if(_OnValueChanged != null)
_OnValueChanged(_value);
}
}
}
else
{
if(_dragData.isDrag)
{
_dragData.isDrag = false;
_dragData.delta = 0f;
_dragData.force = ((_startValue - _value) / _time) * forceMultiplier;
if(_OnDragDataChanged != null)
_OnDragDataChanged(new DragData(_dragData));
OnDragEnd.Invoke();
}
}
}
else
_value = _analogInput.Value;
}
}
public DragData dragData
{
get
{
return new DragData(_dragData);
}
}
public float Value
{
get
{
return _value;
}
}
#region Wire Editor
event WireEventHandler<DragData> _OnDragDataChanged;
event WireEventHandler<DragData> IWireInput<DragData>.OnWireInputChanged
{
add
{
_OnDragDataChanged += value;
}
remove
{
_OnDragDataChanged -= value;
}
}
DragData IWireInput<DragData>.input
{
get
{
return dragData;
}
}
event WireEventHandler<float> _OnValueChanged;
event WireEventHandler<float> IWireInput<float>.OnWireInputChanged
{
add
{
_OnValueChanged += value;
}
remove
{
_OnValueChanged -= value;
}
}
float IWireInput<float>.input
{
get
{
return Value;
}
}
protected override void AddNode(List<Node> nodes)
{
base.AddNode(nodes);
nodes.Add(new Node("analogInput", "AnalogInput", typeof(AnalogInput), NodeType.WireFrom, "AnalogInput"));
nodes.Add(new Node("dragData", "DragData", typeof(IWireInput<DragData>), NodeType.WireTo, "Input<DragData>"));
nodes.Add(new Node("Value", "Value", typeof(IWireInput<float>), NodeType.WireTo, "Input<float>"));
}
protected override void UpdateNode(Node node)
{
if(node.name.Equals("analogInput"))
{
node.updated = true;
if(node.objectTarget == null && _analogInput == null)
return;
if(node.objectTarget != null)
{
if(node.objectTarget.Equals(_analogInput))
return;
}
_analogInput = node.objectTarget as AnalogInput;
if(_analogInput == null)
node.objectTarget = null;
return;
}
else if(node.name.Equals("dragData"))
{
node.updated = true;
return;
}
else if(node.name.Equals("Value"))
{
node.updated = true;
return;
}
base.UpdateNode(node);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OE.Service
{
public class ServiceException : Exception
{
public int Code { get; private set; }
public ServiceException(string msg)
: base(msg)
{
Code = -1;
}
public ServiceException(int code, string msg)
: base(msg)
{
Code = code;
}
public ServiceException(int code, Exception innerex)
: base(innerex.Message, innerex)
{
Code = code;
}
public ServiceException(ServiceErrorCode code, string msg)
: base(msg)
{
Code = (int)code;
}
public ServiceException(ServiceErrorCode code, Exception innerex)
: base(innerex.Message, innerex)
{
Code = (int)code;
}
}
public enum ServiceErrorCode
{
Error = -5000,
Warning = -4000,
Infor = -1
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartObjects
{
/// <summary>
/// Связь CashDocument - ZReport
/// </summary>
public class CashDocument_ZReport : Entity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get
{
return "Связь CashDocument - ZReport";
}
}
/// <summary>
/// Наименование
/// </summary>
public string POSNAME { get; set; }
/// <summary>
/// Дата
/// </summary>
public DateTime DATETIME { get; set; }
/// <summary>
/// Суточный отчет с гашением
/// </summary>
public int NUMBER { get; set; }
/// <summary>
/// Счетчик на конец смены
/// </summary>
public double INCCOUNTEREND { get; set; }
/// <summary>
/// Итого продажи
/// </summary>
public decimal FISCALSALE { get; set; }
/// <summary>
/// Возврат продажи
/// </summary>
public decimal FISCALRETURN { get; set; }
/// <summary>
/// Выручка
/// </summary>
public decimal FISCALRES { get; set; }
/// <summary>
/// Внесений
/// </summary>
public decimal INCASH { get; set; }
/// <summary>
/// Выплат
/// </summary>
public decimal OUTCASH { get; set; }
/// <summary>
/// Остаток в кассе
/// </summary>
public decimal BalanceInCash { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem68 : ProblemBase {
private List<List<int>> _nodePaths = new List<List<int>>();
private int[] _nodes;
private int _maxNum;
private List<string> _permutations = new List<string>();
private int _lowestNodePath;
private int _maxKeyLength;
public override string ProblemName {
get { return "68: Magic 5-gon ring"; }
}
public override string GetAnswer() {
GenerateNodePaths();
BuildPermutations();
return GetMaxSet();
}
private string GetMaxSet() {
string best = "";
foreach (string permutation in _permutations) {
for (int index = 0; index < permutation.Length; index++) {
_nodes[index] = Convert.ToInt32(permutation.Substring(index, 1));
}
if (IsGood()) {
string key = GetPathString();
if (key.Length <= _maxKeyLength && string.Compare(key, best) > 0) {
best = key;
}
}
}
return best;
}
private string GetPathString() {
int path = _lowestNodePath;
StringBuilder key = new StringBuilder();
do {
foreach (int node in _nodePaths[path]) {
key.Append((_nodes[node] + 1).ToString());
}
path++;
if (path == _nodePaths.Count) {
path = 0;
}
} while (path != _lowestNodePath);
return key.ToString();
}
private bool IsGood() {
int lastPath = -1;
int lowestNodeValue = 0;
int pathIndex = 0;
foreach (List<int> path in _nodePaths) {
int sum = 0;
foreach (int node in path) {
sum += _nodes[node];
}
if (lastPath == -1) {
lastPath = sum;
lowestNodeValue = _nodes[path[0]];
_lowestNodePath = 0;
} else {
if (lastPath != sum) {
return false;
}
if (_nodes[path[0]] < lowestNodeValue) {
_lowestNodePath = pathIndex;
lowestNodeValue = _nodes[path[0]];
}
}
pathIndex++;
}
return true;
}
private void BuildPermutations() {
_permutations.Add("0");
for (int a = 1; a < _maxNum; a++) {
List<string> tempPerms = new List<string>();
for (int b = 0; b < _permutations.Count; b++) {
for (int c = 0; c <= _permutations[b].Length; c++) {
tempPerms.Add(_permutations[b].Insert(c, a.ToString()));
}
}
_permutations = tempPerms;
}
}
private void GenerateNodePathsTest() {
_maxNum = 6;
_nodes = new int[6];
_maxKeyLength = 9;
_nodePaths = new List<List<int>>();
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(0);
_nodePaths[_nodePaths.Count - 1].Add(1);
_nodePaths[_nodePaths.Count - 1].Add(2);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(3);
_nodePaths[_nodePaths.Count - 1].Add(2);
_nodePaths[_nodePaths.Count - 1].Add(4);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(5);
_nodePaths[_nodePaths.Count - 1].Add(4);
_nodePaths[_nodePaths.Count - 1].Add(1);
}
private void GenerateNodePaths() {
_maxNum = 10;
_nodes = new int[10];
_maxKeyLength = 16;
_nodePaths = new List<List<int>>();
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(0);
_nodePaths[_nodePaths.Count - 1].Add(1);
_nodePaths[_nodePaths.Count - 1].Add(2);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(3);
_nodePaths[_nodePaths.Count - 1].Add(2);
_nodePaths[_nodePaths.Count - 1].Add(4);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(5);
_nodePaths[_nodePaths.Count - 1].Add(4);
_nodePaths[_nodePaths.Count - 1].Add(6);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(7);
_nodePaths[_nodePaths.Count - 1].Add(6);
_nodePaths[_nodePaths.Count - 1].Add(8);
_nodePaths.Add(new List<int>());
_nodePaths[_nodePaths.Count - 1].Add(9);
_nodePaths[_nodePaths.Count - 1].Add(8);
_nodePaths[_nodePaths.Count - 1].Add(1);
}
}
}
|
using CaveGeneration.Models;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Linq;
using System;
using CaveGeneration.Content_Generation.Goal_Placement;
using CaveGeneration.Content_Generation.Astar;
using System.Collections.Generic;
using CaveGeneration.Models.Characters;
using CaveGeneration.Content_Generation.Enemy_Placement;
namespace CaveGeneration.System
{
class Updater
{
public void UpdateEndOfGame(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Enter))
{
gameState = GameState.MainMenu;
}
}
public void UpdateGameplay(GameTime gameTime)
{
playerPosition = player.Position;
playerRectangle.X = (int)playerPosition.X;
playerRectangle.Y = (int)playerPosition.Y;
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (goal.BoundingRectangle.Intersects(new Rectangle((int)player.Position.X, (int)player.Position.Y, player.Texture.Width, player.Texture.Height)))
{
GameOverMessage = "You Win!";
gameState = GameState.GameOver;
}
// TODO: Add your update logic here
player.Update(gameTime);
camera.Update(gameTime, this);
foreach (var enemy in allEnemies)
{
enemy.Update(gameTime);
if (playerRectangle.Intersects(new Rectangle((int)enemy.Position.X, (int)enemy.Position.Y, enemy.Texture.Width, enemy.Texture.Height)))
{
if (!player.hurt)
{
player.dealDamage();
}
if (!player.isAlive())
{
GameOverMessage = "You Lose!";
gameState = GameState.GameOver;
}
}
}
}
public void UpdateMainMenu(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Enter))
{
CreateMap(mapWidth, mapHeight, useCopyOfMap: useCopy);
gameState = GameState.Playing;
}
}
}
}
|
/*
* Company:
* Motto: Talk more to loved ones!
* Assignment: A book shelf application
* Deadline: 2012-01-02
* Programmer: Baran Topal
* Solution name: .BookShelfWeb
* Folder name: .Factory
* Project name: .BookShelfWeb.Factory
* File name: DALFactory.cs
* Status: Finished
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookShelfWeb.IDAL;
namespace BookShelfWeb.Factory
{
/// <summary>
/// DAL factory to produce DAL objects
/// </summary>
public class DALFactory : FactoryTemplate<DALFactory>
{
#region constructors
/// <summary>
/// constructor, you can change AppSetting key name here
/// </summary>
public DALFactory()
{
_lowerLayerBinaryPath = "DAL";
_lowerLayerBinaryPathCacheName = "DALName";
}
#endregion constructors
#region Retrieve User Interface
/// <summary>
/// Factory method to get IBookShelfUserDAL Interface
/// </summary>
/// <typeparam name="T">implement of IBookShelfUserDAL.Constructor with various parameter(s) is required</typeparam>
/// <returns>IBookShelfUserDAL</returns>
public static IBookShelfUserDAL GetUserInterface<T>(int userId, string fullName, string password)
{
return CreateInstance<IBookShelfUserDAL, T>(new object[] { userId, fullName, password }, false);
}
public static IBookShelfUserDAL GetUserInterface<T>(int userId)
{
return CreateInstance<IBookShelfUserDAL, T>(new object[] { userId }, false);
}
public static IBookShelfUserDAL GetUserInterface<T>(string fullName)
{
return CreateInstance<IBookShelfUserDAL, T>(new object[] { fullName }, false);
}
public static IBookShelfUserDAL GetUserInterface<T>()
{
return CreateInstance<IBookShelfUserDAL, T>(new object[] { }, false);
}
#endregion Retrieve User Interface
#region Retrieve Book Interface
/// <summary>
/// Factory method to get IBookShelfModelMembershipDAL Interface
/// </summary>
/// <typeparam name="T">implement of IBookShelfModelMembershipDAL.Constructor with two parameter(int,int) is required</typeparam>
/// <returns>IBookShelfModelMembershipDAL</returns>
public static IBookShelfBookDAL GetBookInterface<T>(int bookID, string isbn, string bookName, string authorName)
{
return CreateInstance<IBookShelfBookDAL, T>(new object[] { bookID, isbn, bookName, authorName }, false);
}
public static IBookShelfBookDAL GetBookInterface<T>(int bookID)
{
return CreateInstance<IBookShelfBookDAL, T>(new object[] { bookID }, false);
}
public static IBookShelfBookDAL GetBookInterface<T>()
{
return CreateInstance<IBookShelfBookDAL, T>(new object[] { }, false);
}
#endregion Retrieve Book Interface
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
//MessageBox.Show(cmbAngilal.SelectedItem.ToString());
Car myCar = new Car(txtZagvar.Text.Trim(), txtAralDugaar.Text.Trim(), txtUngu.Text.Trim(), Convert.ToInt32(maskOn.Text.Trim()), Convert.ToChar(cmbAngilal.SelectedItem.ToString()), maskUlsDugaar.Text.Trim());
lblInfo.Text = myCar.Mashinii_medeelel_avah();
}
}
}
|
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay
{
[System.Serializable]
public struct MoveConfiguration
{
[SerializeField]
[MinValue(1)]
private float m_maxSpeed;
[SerializeField]
[MinValue(0.1)]
private float m_acceleration;
[SerializeField]
[MinValue(1)]
private float m_decceleration;
public float maxSpeed => m_maxSpeed;
public float acceleration => m_acceleration;
public float decceleration => m_decceleration;
}
} |
using System;
namespace Max_Number
{
class Program
{
static void Main(string[] args)
{
int numberOfInputs = int.Parse(Console.ReadLine());
int minNumber = int.MaxValue;
int input;
while (numberOfInputs != 0)
{
input = int.Parse(Console.ReadLine());
numberOfInputs--;
if (input < minNumber)
{
minNumber = input;
}
}
Console.WriteLine(minNumber);
}
}
}
|
using Pe.Stracon.Politicas.Aplicacion.Core.Base;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using System;
using System.Collections.Generic;
namespace Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract
{
/// <summary>
/// Definición de servicios para Trabajador
/// </summary>
/// <remarks>
/// Creación: GMD 20150327 <br />
/// Modificación: <br />
/// </remarks>
public interface ITrabajadorService : IGenericService
{
/// <summary>
/// Búsqueda de Trabajador
/// </summary>
/// <param name="filtro">Trabajador Request</param>
/// <returns>Lista con registros</returns>
ProcessResult<List<TrabajadorResponse>> BuscarTrabajador(TrabajadorRequest filtro);
/// <summary>
/// Lista registros de trabajadores a partir de códigos.
/// </summary>
/// <param name="listaCodigos">Lista de códigos de trabajadores</param>
/// <returns>Listas de trabajadores</returns>
ProcessResult<List<TrabajadorResponse>> ListarTrabajadores(List<Guid?> listaCodigos);
/// <summary>
/// Registrar Trabajador
/// </summary>
/// <param name="data">Trabajador Response</param>
/// <returns>Identificador con resultado</returns>
ProcessResult<TrabajadorRequest> RegistrarTrabajador(TrabajadorRequest data);
/// <summary>
/// Eliminar el registro de trabajadores.
/// </summary>
/// <param name="listaTrabajadores">Lista de trabajadores</param>
/// <returns>Resultado de la operación</returns>
/// <returns>Identificador con resultado</returns>
ProcessResult<TrabajadorRequest> EliminarTrabajador(List<TrabajadorRequest> listaTrabajadores);
/// <summary>
/// Búsqueda de Trabajador
/// </summary>
/// <param name="filtro">Trabajador Request</param>
/// <returns>Lista con registros</returns>
ProcessResult<List<TrabajadorDatoMinimoResponse>> BuscarTrabajadorDatoMinimo(TrabajadorRequest filtro);
/// <summary>
/// Búsqueda de la firma de un Trabajador.
/// </summary>
/// <param name="trabajador">Trabajador Request</param>
/// <returns>Lista con Firma Trabajador</returns>
ProcessResult<TrabajadorResponse> BuscarFirmaTrabajador(TrabajadorRequest trabajador);
/// <summary>
/// Registrar la firma de un Trabajador.
/// </summary>
/// <param name="trabajador">Trabajador Request</param>
/// <returns>Identificador con resultado</returns>
ProcessResult<TrabajadorResponse> RegistrarFirmaTrabajador(TrabajadorRequest trabajador);
/// <summary>
/// Notificar inicios y cierres de periodo.
/// </summary>
/// <param name="listaTrabajadores">Lista de trabajaores</param>
/// <param name="CodigoNotificar">tipo de notificacion</param>
/// <param name="AnioPeriodo">Anio de Periodo</param>
/// <param name="MesPeriodo"> Mes del Periodo </param>
/// <param name="codigoSistema">Código del sistema</param>
/// <param name="profileCorreo">Perfil de la cuenta que ejecuta la notificación.</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<object> NotificaParticipanteCalendarizacion(List<Guid?> listaTrabajadores, string CodigoNotificar, string AnioPeriodo,
string MesPeriodo, string NombreActividad, Guid codigoSistema, string profileCorreo);
/// <summary>
/// Registrar TrabajadorUnidadOperativa
/// </summary>
/// <param name="data">Trabajador Response</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<TrabajadorRequest> RegistrarTrabajadorUnidadOperativa(TrabajadorRequest data);
/// <summary>
/// Lista los proyectos asociados a un trabajador.
/// </summary>
/// <param name="codigoTrabajador">Código de trabajador</param>
/// <returns>Lista de proyectos asociados</returns>
ProcessResult<List<TrabajadorUnidadOperativaResponse>> ListarTrabajadorUnidadOperativa(TrabajadorUnidadOperativaRequest filtro);
/// <summary>
/// Lista los proyectos SAP asociados a un trabajador.
/// </summary>
/// <param name="codigoTrabajador">Código de trabajador</param>
/// <returns>Lista de proyectos asociados</returns>
ProcessResult<List<TrabajadorUnidadOperativaResponse>> ListarTrabajadorUnidadOperativaSAP(TrabajadorUnidadOperativaRequest filtro);
/// <summary>
/// Eliminar trabajador unidad operativa
/// </summary>
/// <param name="codigoTrabajadorUnidadOperativa">CodigoTrabajadorUnidadOperativa</param>
/// <returns>Resultado del registro</returns>
ProcessResult<TrabajadorUnidadOperativaRequest> EliminarTrabajadorUnidadOperativa(Guid codigoTrabajadorUnidadOperativa);
/// <summary>
/// Búsqueda de TrabajadorSuplente
/// </summary>
/// <param name="filtro">Trabajador Request</param>
/// <returns>Lista con resultados de busqueda</returns>
ProcessResult<List<TrabajadorSuplenteResponse>> BuscarTrabajadorSuplente(TrabajadorRequest filtro);
/// <summary>
/// Registrar Trabajador Suplente
/// </summary>
/// <param name="data">TrabajadorSuplente Response</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<TrabajadorSuplenteRequest> RegistrarTrabajadorSuplente(TrabajadorSuplenteRequest data);
/// <summary>
/// Actualiza el reemplazo al trabajador original
/// </summary>
/// <param name="codigoTrabajador">Codigo de trabajador</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<string> EnviarNotificacionFinReemplazo(Guid codigoTrabajador, Guid codigoSuplente);
}
}
|
namespace CryptoReaper.Simulation.CryptFeatures
{
class Undefined : Crypt.Feature
{
public Undefined() : base(null)
{
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Tomelt.Environment.Extensions.Models;
using Tomelt.Packaging.Models;
namespace Tomelt.Packaging.ViewModels {
public class PackagingHarvestViewModel {
public IEnumerable<PackagingSource> Sources { get; set; }
public IEnumerable<ExtensionDescriptor> Extensions { get; set; }
[Required]
public string ExtensionName { get; set; }
public string FeedUrl { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InventoryManager.Service.ViewModels
{
public class ClothesViewModels
{
public string Name { get; set; }
public string Type { get; set; }
public string Qunatity { get; set; }
public string SinglePrice { get; set; }
}
}
|
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using GatewayEDI.Logging.Configuration;
using GatewayEDI.Logging.Factories;
namespace GatewayEDI.Logging.Resolver
{
/// <summary> Resolves factories to be used for log instantiation based on settings taken from the application's default configuration file (<c> App.config </c> or <c> Web.config </c>). </summary>
public class AppConfigFactoryResolver : NamedFactoryResolver
{
/// <summary> The name of the configuration section </summary>
private const string configSectionName = "gatewayedi.logging";
public AppConfigFactoryResolver()
{
Load();
}
/// <summary> A log used to log problems with the underlying configuration of logs and factories. Per default, a <see cref="DebugLog" /> is used. </summary>
protected ILog DiagnosticLog
{
get { return LogManager.GetDiagnosticLog(GetType().FullName); }
}
/// <summary> Loads the resolver configuration from the log.config file or the applications App.config file. </summary>
public virtual void Load()
{
LogConfigurationSection config = ParseConfiguration();
LoadConfiguration(config);
}
/// <summary> Parses the application configuration to locate and extract the configuration section </summary>
private LogConfigurationSection ParseConfiguration()
{
string configFileName = "log.config";
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
string appFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
configFileName = Path.Combine(appFolder, configFileName);
}
//This code is a base for loading from a separate configuration file instead of app.config.
FileInfo configFile = new FileInfo(configFileName);
if (configFile.Exists)
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFileName;
try
{
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
return (LogConfigurationSection) config.GetSection(configSectionName);
}
catch (ConfigurationErrorsException ex)
{
DiagnosticLog.Info(ex);
return (LogConfigurationSection) ConfigurationManager.GetSection(configSectionName);
}
}
else
{
return (LogConfigurationSection) ConfigurationManager.GetSection(configSectionName);
}
}
/// <summary> Prepares the internal dictionaries and caches for factory requests, but without already creating the factory instances. </summary>
/// <param name="configuration"> An configuration section that provides configuration settings about factories and loggers. </param>
protected void LoadConfiguration(LogConfigurationSection configuration)
{
// construct the named factories.
var factories = new Dictionary<string, ILogFactory>();
if (configuration != null && configuration.Factories != null)
{
foreach (FactoryConfigurationElement factoryConfiguration in configuration.Factories)
{
ILogFactory factory = CreateFactoryInstance(factoryConfiguration);
if (factories.ContainsKey(factoryConfiguration.Name))
{
DiagnosticLog.Warn("There are duplicate factories with the name [{0}]", factoryConfiguration.Name);
}
else
{
factories.Add(factoryConfiguration.Name, factory);
}
}
}
//if there is no default factory, create an implicit entry that resolves to a NullLogFactory
if (!factories.ContainsKey(LogManager.DefaultLogName))
{
factories.Add(LogManager.DefaultLogName, NullLogFactory.Instance);
}
//process log configurations
List<LogConfigurationElement> logConfigurationList = new List<LogConfigurationElement>();
if (configuration != null && configuration.Logs != null)
{
foreach (LogConfigurationElement logConfiguration in configuration.Logs)
{
logConfigurationList.Add(logConfiguration);
//make sure a correct factory name is referenced
string factoryName = logConfiguration.FactoryName;
if (!factories.ContainsKey(factoryName))
{
const string message = "Declared log configuration '{0}' refers to undeclared log factory '{1}'";
DiagnosticLog.Error(message, logConfiguration.LogName, factoryName);
// associate with a null logger factory
base.RegisterFactory(logConfiguration.LogName, NullLogFactory.Instance);
}
else
{
ILogFactory factory = factories[factoryName];
base.RegisterFactory(logConfiguration.LogName, factory);
}
}
}
// if there is no default log declaration, create one that links to the default factory
if (logConfigurationList.Find(el => el.LogName == LogManager.DefaultLogName) == null)
{
base.RegisterFactory(LogManager.DefaultLogName, factories[LogManager.DefaultLogName]);
}
}
/// <summary> Creates a factory based on a given configuration. If the factory provides invalid information, an error is logged through the internal log, and a <see cref="NullLogFactory" /> returned. </summary>
/// <param name="factoryConfiguration"> The configuration that provides type information for the <see cref="ILogFactory" /> that is being created. </param>
/// <returns> Factory instance. </returns>
private ILogFactory CreateFactoryInstance(FactoryConfigurationElement factoryConfiguration)
{
ILogFactory factory = ActivatorHelper.Instantiate<ILogFactory>(factoryConfiguration.Type, DiagnosticLog);
//if the factory is configurable, invoke its Init method
IConfigurableLogFactory cf = factory as IConfigurableLogFactory;
if (cf != null)
{
cf.Init(factoryConfiguration.FactoryData);
}
if (factory == null)
{
factory = NullLogFactory.Instance;
}
return factory;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public GameObject[] pickups;
public GameObject[] enemies;
public GameObject santa;
public Vector2 santaPos = new Vector2(10.28385f, 12.21354f);
public int[] enemyCounts;
public GameObject mapBounds;
public GameObject deathsplosion;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SpawnEnemies() {
GameObject player = GameObject.FindGameObjectWithTag("Player");
Debug.Log("player: " + player.tag);
for(int i = 0; i < enemies.Length; i++) {
for(int j = 0; j < enemyCounts[i]; j++) {
GameObject enemyClone = Instantiate(enemies[i], GetSpawnPos(), Quaternion.identity) as GameObject;
enemyClone.GetComponent<chasePlayer>().Init(gameObject, player);
GetComponent<GameManager>().enemyCount++;
}
}
}
public void SpawnSanta() {
GameObject player = GameObject.FindGameObjectWithTag("Player");
GameObject enemyClone = Instantiate(santa, santaPos, Quaternion.identity) as GameObject;
//Debug.Log("S:LDKFJL:SKDJF?");
enemyClone.GetComponent<chasePlayer>().Init(gameObject, player);
}
Vector2 GetSpawnPos() {
Bounds b = mapBounds.GetComponent<PolygonCollider2D>().bounds;
Vector2 spawnPos = new Vector2(Random.Range(b.min.y, b.max.y), Random.Range(b.min.y, b.max.y));
while(!mapBounds.GetComponent<PolygonCollider2D>().OverlapPoint(spawnPos) || mapBounds.GetComponent<CircleCollider2D>().OverlapPoint(spawnPos)) {
spawnPos = new Vector2(Random.Range(b.min.y, b.max.y), Random.Range(b.min.y, b.max.y));
}
Debug.Log(spawnPos);
return spawnPos;
}
public void explode(Vector2 pos)
{
Instantiate(deathsplosion, pos, Quaternion.identity);
}
public void SpawnPickup(Vector3 pos) {
int randNum = Random.Range(0, 100);
GameObject toSpawn;
if (randNum <= 50)
{
if (randNum <= 5)
{
toSpawn = pickups[0];
}
else if (randNum > 5 && randNum <= 15)
{
toSpawn = pickups[1];
}
else if (randNum > 15 && randNum <= 25)
{
toSpawn = pickups[2];
}
else
{
toSpawn = pickups[3];
}
Instantiate(toSpawn, pos, Quaternion.identity);
}
}
}
|
using Tomelt.ContentManagement;
using Tomelt.ContentManagement.Handlers;
using Tomelt.Data;
using Tomelt.Widgets.Models;
namespace Tomelt.Widgets.Handlers {
public class LayerPartHandler : ContentHandler {
public LayerPartHandler(IRepository<LayerPartRecord> layersRepository) {
Filters.Add(StorageFilter.For(layersRepository));
}
protected override void GetItemMetadata(GetContentItemMetadataContext context) {
var part = context.ContentItem.As<LayerPart>();
if (part != null) {
context.Metadata.Identity.Add("Layer.LayerName", part.Name);
}
}
}
} |
using Xamarin.Forms;
namespace RRExpress.Express.Views {
public partial class MyOrderStatusView : ContentView {
public MyOrderStatusView() {
InitializeComponent();
}
}
}
|
using CYJ.DingDing.Api.IApiService;
using CYJ.DingDing.Application.IAppService;
using CYJ.DingDing.Dto.Dto;
namespace CYJ.DingDing.Api.ApiService
{
public class UserApiService : IUserApiService
{
private readonly IUserAppService userAppService;
public UserApiService(IUserAppService userAppService)
{
this.userAppService = userAppService;
}
public UserListResponse GetList(UserListRequest request)
{
return userAppService.GetList(request);
}
public UserDetailResponse GetModel(int id)
{
return userAppService.GetModel(id);
}
public UserCreateResponse Create(UserCreateRequest request)
{
return userAppService.Create(request);
}
public UserUpdateResponse Update(UserUpdateRequest request)
{
return userAppService.Update(request);
}
public UserDeleteResponse Delete(int id)
{
return userAppService.Delete(id);
}
}
} |
namespace _07._SumBigNumbers
{
using System;
using System.Collections.Generic;
using System.Text;
public class Startup
{
public static void Main()
{
Stack<char> firstNumber = new Stack<char>(Console.ReadLine());
Stack<char> secondNumber = new Stack<char>(Console.ReadLine());
StringBuilder resultNumber = new StringBuilder();
int sum = 0;
while (firstNumber.Count != 0 || secondNumber.Count != 0)
{
sum /= 10;
if (firstNumber.Count != 0)
{
sum += int.Parse(firstNumber.Pop().ToString());
}
if (secondNumber.Count != 0)
{
sum += int.Parse(secondNumber.Pop().ToString());
}
int digit = sum % 10;
resultNumber.Insert(0, digit);
}
resultNumber.Insert(0, sum / 10);
Console.WriteLine(resultNumber.ToString().TrimStart('0'));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TripNetCore.Models;
namespace TripNetCore.Models
{
public class ReferenceData
{
public LookupItem[] transTypes { get; set; }
}
}
|
using System.Runtime.Serialization;
namespace mssngrrr
{
[DataContract]
public class AjaxResult
{
[DataMember(Name = "name", EmitDefaultValue = false)] public string Name;
[DataMember(Name = "length", EmitDefaultValue = false)] public int Length;
[DataMember(Name = "message", EmitDefaultValue = false)] public string Message;
[DataMember(Name = "error", EmitDefaultValue = false)] public string Error;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace EasySave.View
{
/// <summary>
/// MainWindow.xaml quick save logic.
/// </summary>
public partial class MainWindow
{
/// <summary>
/// Execute a quick save, get info from the different input box.
/// </summary>
/// <param name="sender">ExecuteQuickSave</param>
/// <param name="e">Cancel the event</param>
private void ExecuteQuickSave_Click(object sender, RoutedEventArgs e)
{
Dictionary<string, string> options = new Dictionary<string, string>
{
{ "encrypt", (QuickSaveEncrypt.IsChecked == true)? "yes" : "no" },
{ "name", QuickName.Text},
{ "source", QuickSourcePath.Text},
{ "target", QuickTargetPath.Text}
};
if (RadioMirrorSave.IsChecked == true)
QuickSaveEvent(QuickSaveAction.MIRROR, options);
if (RadioDifferentialSave.IsChecked == true)
QuickSaveEvent(QuickSaveAction.DIFFERENTIAL, options);
}
/// <summary>
/// Open folder context window : <see cref="GetFolderPath(System.Windows.Controls.TextBox)"/>
/// </summary>
/// <param name="sender">BtnQuickSourcePath</param>
/// <param name="e">Cancel the event</param>
private void BtnQuickSourcePath_Click(object sender, RoutedEventArgs e)
{
GetFolderPath(QuickSourcePath);
}
/// <summary>
/// Open folder context window : <see cref="GetFolderPath(System.Windows.Controls.TextBox)"/>
/// </summary>
/// <param name="sender">BtnQuickTargetPath</param>
/// <param name="e">Cancel the event</param>
private void BtnQuickTargetPath_Click(object sender, RoutedEventArgs e)
{
GetFolderPath(QuickTargetPath);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DataManager : MonoBehaviour {
public static void SaveData () {
string isBoughtData = "";
string isUsed = "";
foreach (ShipDefinition ship in GameManager.instance.ships) {
isBoughtData += ship.isBought ? "1" : "0";
if (ship.isUsed) {
isUsed = ship.shipName;
}
}
PlayerPrefs.SetString ("isBoughtShips", isBoughtData);
PlayerPrefs.SetString ("isUsedShip", isUsed);
foreach (TrailDefinition trail in GameManager.instance.trails) {
isBoughtData += trail.isBought ? "1" : "0";
if (trail.isUsed) {
isUsed = trail.trailName;
}
}
PlayerPrefs.SetString ("isBoughtTrails", isBoughtData);
PlayerPrefs.SetString ("isUsedTrail", isUsed);
}
public static void LoadData () {
string isBoughtData = PlayerPrefs.GetString ("isBoughtShips");
string isUsed = PlayerPrefs.GetString ("isUsedShip");
int iterator = 0;
foreach (ShipDefinition ship in GameManager.instance.ships) {
ship.isBought = isBoughtData[iterator] == '1' ? true : false;
if (isUsed == ship.shipName) {
ship.isUsed = true;
} else {
ship.isUsed = false;
}
iterator++;
}
FindObjectOfType<ShopUI> ().RebuildShipUI ();
isBoughtData = PlayerPrefs.GetString ("isBoughtTrails");
isUsed = PlayerPrefs.GetString ("isUsedTrail");
iterator = 0;
foreach (TrailDefinition trail in GameManager.instance.trails) {
trail.isBought = isBoughtData[iterator] == '1' ? true : false;
if (isUsed == trail.trailName) {
trail.isUsed = true;
} else {
trail.isUsed = false;
}
iterator++;
}
FindObjectOfType<ShopUI> ().RebuildTrailUI ();
}
public static void SaveDistanceAndCredits () {
PlayerPrefs.SetFloat ("distance", GameManager.instance.totalDistance);
PlayerPrefs.SetFloat ("recordDistance", GameManager.instance.recordDistance);
PlayerPrefs.SetFloat ("credits", GameManager.instance.credits);
}
public static void LoadDistanceAndCredits () {
GameManager.instance.totalDistance = PlayerPrefs.GetFloat ("distance");
GameManager.instance.recordDistance = PlayerPrefs.GetFloat ("recordDistance");
GameManager.instance.credits = PlayerPrefs.GetFloat ("credits");
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MOTHER3;
using Extensions;
namespace MOTHER3Funland
{
public partial class frmMainTextViewer : M3Form
{
public static Bitmap formIcon = Properties.Resources.sparrow;
bool loading = false;
bool loading2 = false;
// Text cache
string[] mapnames = new string[TextMapNames.Entries];
public frmMainTextViewer()
{
InitializeComponent();
Helpers.CheckFont(cboRoom);
Helpers.CheckFont(lstLines);
Helpers.CheckFont(txtLine);
cboRoom.JapaneseSearch = M3Rom.Version == RomVersion.Japanese;
// Load the map names
loading = true;
for (int i = 0; i < mapnames.Length; i++)
{
mapnames[i] = TextMapNames.GetName(i);
cboRoom.Items.Add("[" + i.ToString("X3") + "] " +
mapnames[i].Replace(Environment.NewLine, " "));
}
loading = false;
cboRoom.SelectedIndex = 0;
}
private void cboRoom_SelectedIndexChanged(object sender, EventArgs e)
{
if (loading) return;
lstLines.Items.Clear();
txtLine.Text = "";
int room = cboRoom.SelectedIndex;
int lines = TextMain.GetNumLines(room);
loading2 = true;
for (int i = 0; i < lines; i++)
{
string str = "[" + i.ToString("X3") + "] " + TextMain.GetLine(room, i).Replace(Environment.NewLine, "");
if (str.Length > 500)
lstLines.Items.Add(str.Substring(0, 500) + " [...]");
else
lstLines.Items.Add(str);
}
loading2 = false;
if (lines > 0)
lstLines.SelectedIndex = 0;
}
private void lstLines_SelectedIndexChanged(object sender, EventArgs e)
{
if (loading2) return;
txtLine.Text = TextMain.GetLine(cboRoom.SelectedIndex, lstLines.SelectedIndex);
}
public override void SelectIndex(int[] index)
{
cboRoom.SelectedIndex = index[0];
lstLines.SelectedIndex = index[1];
}
public override int[] GetIndex()
{
return new int[] { cboRoom.SelectedIndex, lstLines.SelectedIndex };
}
}
}
|
using LR.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LR.Data.Providers
{
public class QuestionProvider : MainProvider
{
public List<Question> GetQuestionForCategory(Guid categoryId, bool withVariants, bool randomize = false)
{
List<Question> result = null;
result = Context.Questions.Where(q => q.Category.Id == categoryId).ToList();
if (withVariants)
{
result.ForEach(q => q.Variants = GetRandomTopVariantsForQuestion(q.Id, 5));
}
result.ForEach(q => q.RightVariant = Context.Variants.FirstOrDefault(v => v.Question.Id == q.Id && v.IsCorrect));
if (randomize)
{
result = result.OrderBy(v => Guid.NewGuid()).ToList();
}
return result;
}
public void AddQuestion(Question question, List<Variant> variants, Guid categoryId)
{
try
{
question.Category = Context.Category.First(c => c.Id == categoryId);
Context.Questions.Add(question);
Context.SaveChanges();
variants.ForEach(v => v.Question = question);
variants.ForEach(v => Context.Variants.Add(v));
Context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
StringBuilder sb = new StringBuilder();
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
sb.Append(string.Format("Property: {0} Error: {1}",
validationError.PropertyName, validationError.ErrorMessage));
}
}
throw new Exception(sb.ToString());
}
}
public Question GetQuestionById(Guid id)
{
Question result = Context.Questions.FirstOrDefault(q => q.Id == id);
result.Variants = GetVariantsForQuestion(id);
result.RightVariant = result.Variants.FirstOrDefault(v => v.IsCorrect);
return result;
}
public List<Question> GetRandomQuestions(Guid categoryId, int questionCount)
{
List<Question> result = null;
result = Context.Questions.Where(q => q.Category.Id == categoryId).AsEnumerable().OrderBy(v => Guid.NewGuid()).Take(questionCount).ToList();
return result;
}
public void EditQuestion(Question question, List<Variant> variants, Guid categoryId)
{
Question questionToEdit = GetQuestionById(question.Id);
questionToEdit.QuestionText = question.QuestionText;
questionToEdit.Category = Context.Category.First(c => c.Id == categoryId);
Context.Variants.Where(v => v.Question.Id == question.Id).ToList().ForEach(v=>UpdateVariant(variants, v));
variants.ForEach(v => v.Question = questionToEdit);
variants.ForEach(v => Context.Variants.Add(v));
Context.SaveChanges();
}
public void DeleteQuestion(Guid questionId)
{
Context.Questions.Remove(GetQuestionById(questionId));
Context.SaveChanges();
}
public List<Variant> GetVariantsForQuestion(Guid questionId)
{
List<Variant> result = Context.Variants.Where(v=>v.Question.Id == questionId).ToList();
return result;
}
public List<Variant> GetRandomTopVariantsForQuestion(Guid questionId, int variantCount)
{
Variant rightVariant = Context.Variants.First(v => v.Question.Id == questionId && v.IsCorrect);
List<Variant> result = Context.Variants.Where(v => v.Question.Id == questionId && !v.IsCorrect).AsEnumerable().OrderBy(v => Guid.NewGuid()).
Take(variantCount).ToList();
result.Add(rightVariant);
result = result.AsEnumerable().OrderBy(v => Guid.NewGuid()).ToList();
return result;
}
public Variant GetVariantById(Guid id)
{
Variant result = Context.Variants.First(v => v.Id == id);
return result;
}
public void AddVariant(Variant variant)
{
Context.Variants.Add(variant);
Context.SaveChanges();
}
public void EditVariant(Variant variant)
{
Variant variantToEdit = GetVariantById(variant.Id);
variantToEdit.Value = variant.Value;
variantToEdit.Question = variant.Question;
Context.SaveChanges();
}
public void DeleteVariant(Guid variantId)
{
Context.Variants.Remove(GetVariantById(variantId));
Context.SaveChanges();
}
#region private_methods
private void UpdateVariant(List<Variant> newVariants, Variant oldVariant)
{
Variant newVariant = newVariants.FirstOrDefault(v => v.Value == oldVariant.Value);
if (newVariant == null)
{
Context.Variants.Remove(oldVariant);
}
else
{
oldVariant.IsCorrect = newVariant.IsCorrect;
newVariants.Remove(newVariant);
}
}
#endregion
}
}
|
using System;
using ELearning.Model;
namespace ELearning.BAL
{
public interface IUserBAL
{
UserModel UserAuthentication(UserModel objuser);
UserModel RegisterStudent(UserModel objModel, out int result);
UserModel Forgotpassword(string email, out bool result);
}
}
|
using Abstract1;
using Concrete1;
using Microsoft.Extensions.DependencyInjection;
namespace App1
{
class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IService, Service>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var service = serviceProvider.GetRequiredService<IService>();
service.Execute();
}
}
}
|
using CommonInterface;
using System.Threading.Tasks;
namespace Demo.Service
{
/// <summary>
/// 演示
/// </summary>
public interface IDemoService: AutoInject
{
string GetStrTest();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Euchre.AI
{
class EuchreAI
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleSpawn : MonoBehaviour
{
private const float spawnPointX = 100;
private const float yRange = 10;
private const float spawnPointZ = 10;
private const float spawnPointZ2 = 30;
private const float spawnPointZ3 = 50;
public GameObject[] Obstacles;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnObstacles", 1.0f, 2.5f);
}
// Update is called once per frame
void Update()
{
}
void SpawnObstacles()
{
int randomSpawn = Random.Range(0, Obstacles.Length);
Instantiate(Obstacles[randomSpawn], new Vector3(spawnPointX, Random.Range(-yRange, yRange), spawnPointZ), Obstacles[randomSpawn].transform.rotation);
for(int rocketCount = 0; rocketCount < 2; rocketCount++)
{
Instantiate(Obstacles[randomSpawn], new Vector3(spawnPointX, Random.Range(-yRange, yRange), spawnPointZ2), Obstacles[randomSpawn].transform.rotation);
}
for(int rocketCount = 0; rocketCount < 3; rocketCount++)
{
Instantiate(Obstacles[randomSpawn], new Vector3(spawnPointX, Random.Range(-yRange, yRange), spawnPointZ3), Obstacles[randomSpawn].transform.rotation);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
class Solution
{
// Complete the isValid function below.
static string IsValid(string s)
{
var frequencies = new Dictionary<char, int>();
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (frequencies.ContainsKey(ch))
{
frequencies[ch]++;
}
else
{
frequencies.Add(ch, 1);
}
}
var mostCommonFrequency = frequencies
.GroupBy(f => f.Value)
.Select(g => new { Frequency = g.Key, Count = g.Count() })
.OrderByDescending(c => c.Count)
.FirstOrDefault()
.Frequency;
var isValid = true;
var hasSingleDifference = false;
foreach (var frequency in frequencies)
{
if (frequency.Value != mostCommonFrequency)
{
if (hasSingleDifference || frequency.Value > mostCommonFrequency + 1)
{
isValid = false;
break;
}
hasSingleDifference = true;
}
}
return isValid ? "YES" : "NO";
}
static void Main(string[] args)
{
string s = Console.ReadLine();
string result = IsValid(s);
Console.WriteLine(result);
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.HR
{
public class OrganizationEntity
{
public OrganizationEntity(SPListItem item)
{
if (item != null)
{
Title = item["Title"] + "";
Name = item["Filed_Organization_Name"] + "";
Type = item["Filed_Organization_Type"] + "";
Code = item["Filed_Organization_Code"] + "";
ParentCode = item["Filed_Organization_ParentCode"] + "";
Location = item["Filed_Organization_Location"] + "";
ManagerAD = item["Filed_Organization_ManagerAD"] + "";
Remark = item["Filed_Organization_Remark"] + "";
}
}
public OrganizationEntity()
{
// TODO: Complete member initialization
}
/// <summary>
/// 标题
/// </summary>
[DataMember]
public string Title;
/// <summary>
///名称
/// </summary>
[DataMember]
public string Name;
/// <summary>
/// 类型
/// </summary>
[DataMember]
public string Type;
/// <summary>
///编码
/// </summary>
[DataMember]
public string Code;
/// <summary>
/// 地址
/// </summary>
[DataMember]
public string Location;
/// <summary>
/// 经理
/// </summary>
[DataMember]
public string ManagerAD;
/// <summary>
/// 备注
/// </summary>
[DataMember]
public string Remark;
/// <summary>
/// 父组织编码
/// </summary>
[DataMember]
public string ParentCode;
}
}
|
namespace ApiTemplate.Common.Markers.DependencyRegistrar
{
public interface ITransientDependency
{
}
} |
namespace Jypeli
{
public partial class GameObject
{
private ILayout _layout = null;
private Sizing _horizontalSizing = Sizing.FixedSize;
private Sizing _verticalSizing = Sizing.FixedSize;
private Vector _preferredSize = new Vector(50, 50);
private bool _sizeByLayout = true;
private bool _layoutNeedsRefreshing = false;
/// <summary>
/// Koon asettaminen vaakasuunnassa, kun olio on
/// asettelijan sisällä.
/// </summary>
public virtual Sizing HorizontalSizing
{
get
{
if (SizingByLayout && (Layout != null))
return Layout.HorizontalSizing;
return _horizontalSizing;
}
set
{
_horizontalSizing = value;
NotifyParentAboutChangedSizingAttributes();
}
}
/// <summary>
/// Koon asettaminen pystysuunnassa, kun olio on
/// asettelijan sisällä.
/// </summary>
public virtual Sizing VerticalSizing
{
get
{
if (SizingByLayout && (Layout != null))
return Layout.VerticalSizing;
return _verticalSizing;
}
set
{
_verticalSizing = value;
NotifyParentAboutChangedSizingAttributes();
}
}
/// <summary>
/// Koko, jota oliolla tulisi olla asettelijan sisällä. Todellinen koko voi olla
/// pienempi, jos tilaa ei ole tarpeeksi.
/// </summary>
public virtual Vector PreferredSize
{
get
{
if (Layout != null)
return Layout.PreferredSize;
return _preferredSize;
}
set
{
_preferredSize = value;
NotifyParentAboutChangedSizingAttributes();
}
}
/// <summary>
/// Onko olion koko asettelijan muokkaama
/// </summary>
public bool SizingByLayout
{
get { return _sizeByLayout; }
set { _sizeByLayout = value; }
}
/// <summary>
/// Should be called whenever properties that might affect layouts
/// are changed.
/// </summary>
internal protected void NotifyParentAboutChangedSizingAttributes()
{
if (Parent == null)
{
_layoutNeedsRefreshing = true;
}
else if (Parent is GameObject)
{
((GameObject)Parent).NotifyParentAboutChangedSizingAttributes();
}
}
/// <summary>
/// Asettelija lapsiolioille. Asettaa lapsiolioiden koon sekä paikan.
/// </summary>
public ILayout Layout
{
get { return _layout; }
set
{
if (_layout != null)
{
ILayout old = _layout;
_layout = null;
old.Parent = null;
}
InitChildren();
_layout = value;
_layout.Parent = this;
NotifyParentAboutChangedSizingAttributes();
}
}
/// <summary>
/// Alustaa asettelijan käyttöön
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public void InitLayout(double width, double height)
{
autoResizeChildObjects = false;
this.PreferredSize = new Vector(width, height);
}
/// <summary>
/// Alustaa asettelijan käyttöön
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="layout"></param>
public void InitLayout(double width, double height, ILayout layout)
{
this.Layout = layout;
InitLayout(width, height);
}
/// <summary>
/// Päivittää lapsiolioiden paikat ja koot, jos widgetille on asetettu asettelija.
/// Tätä metodia EI yleensä tarvitse kutsua itse, sillä asettelija
/// päivitetään automaattisesti jokaisella framella. Tämä metodi on
/// tarpeellinen esim. silloin, kun widgetille on lisätty lapsiolioita
/// (tai muutettu niiden ominaisuuksia) ja niiden paikat tarvitsee päivittää
/// välittömästi lisäyksen jälkeen. Silloinkin tätä tarvitsee kutsua vain kerran,
/// viimeisimmän muutoksen jälkeen.
/// </summary>
public void RefreshLayout()
{
if (Layout != null)
{
_childObjects.UpdateChanges();
// First, lets ask how big the child objects need to be.
UpdateSizeHints();
// Then, lets set the size accordingly, if we are allowed to do so.
if (SizingByLayout)
{
Vector newSize = Layout.PreferredSize;
Vector maxSize = this.GetMaximumSize();
if (newSize.X > maxSize.X)
newSize.X = maxSize.X;
if (newSize.Y > maxSize.Y)
newSize.Y = maxSize.Y;
_size = newSize;
}
// Finally, lets position the child objects into the space we have available
// for them.
UpdateLayout(_size);
}
}
/// <summary>
/// Recursively updates the preferred sizes (and other parameters that
/// affect the layout) of the object and its child objects.
/// </summary>
private void UpdateSizeHints()
{
if (_childObjects == null)
return;
foreach (var child in _childObjects)
{
child.UpdateSizeHints();
}
if (Layout != null)
Layout.UpdateSizeHints(_childObjects.items);
}
/// <summary>
/// Recursively updates the layouts of the object and
/// its child objects. <c>UpdateSizeHints()</c> must have
/// been called before this, because the layout needs to
/// know how big the objects need to be.
/// </summary>
/// <param name="maximumSize">The actual size that is allocated for the layout.</param>
private void UpdateLayout(Vector maximumSize)
{
if (Layout != null)
Layout.Update(Objects.items, maximumSize);
if (_childObjects != null)
{
foreach (var child in _childObjects)
{
child.UpdateLayout(child.Size);
}
}
}
/// <summary>
/// Antaa widgetin maksimikoon siinä tapauksessa, että kokoa ei
/// ole annettu rakentajassa (tai tarkemmin sanoen muuttujan <c>SizingByLayout</c>
/// arvo on <c>true</c>). Olio ei siis automaattisesti kasva tätä isommaksi.
/// </summary>
/// <returns></returns>
protected virtual Vector GetMaximumSize()
{
return new Vector(double.PositiveInfinity, double.PositiveInfinity);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ApiWrapper
{
class Api
{
[DllImport("user32.dll")]
public static extern void SendClickMessage(IntPtr m, int x, int y);
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
public static extern void mouse_event(MouseClickType flags, int dx, int dy, uint data, UIntPtr extraInfo);
[DllImport("user32.dll", EntryPoint = "keybd_event")]
public static extern void keybd_event(int bVk, byte bScan, KeyEventFlag dwFlags, int dwExtraInfo);
public enum KeyEventFlag : int
{
KEYEVENTF_KEYUP = 0x2,
KEYEVENTF_KEYDOWN = 0x00
}
[DllImport("User32.dll", EntryPoint = "FindWindow")]
public extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern int GetPixel(IntPtr hdc, int nXPos, int nYPos);
[DllImport("gdi32.dll")]
public static extern int SetPixel(IntPtr hdc, int nXPos, int nYPos, int color);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetLastError();
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll")]
public static extern int ResetDC(IntPtr hWnd, ref int hDC);
[DllImportAttribute("gdi32.dll")]
public static extern bool BitBlt(IntPtr hdcDest, //目的上下文设备的句柄
int nXDest, //目的图形的左上角的x坐标
int nYDest, //目的图形的左上角的y坐标
int nWidth, //目的图形的矩形宽度
int nHeight, //目的图形的矩形高度
IntPtr hdcSrc, //源上下文设备的句柄
int nXSrc, //源图形的左上角的x坐标
int nYSrc, //源图形的左上角的x坐标
System.Int32 dwRop //光栅操作代码
);
[DllImport("user32.dll")]
public static extern int GetWindowRect(IntPtr hWnd, out Rectangle lpRect);
[DllImport("user32.dll", EntryPoint = "SetWindowPos", SetLastError = true)]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
[DllImport("user32.dll", EntryPoint = "MoveWindow")]
public static extern IntPtr MoveWindow(IntPtr win, int x, int y, int width, int height, bool repaint);
[DllImport("user32.dll", EntryPoint = "BringWindowToTop", SetLastError = true)]
public static extern bool BringWindowToTop(IntPtr m_hWnd);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr parentHWnd, IntPtr childAfterHWnd, string className, string windowTitle);
}
}
|
using SuperMarket.DAO;
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 SuperMarket
{
public partial class BanHangForm : Form
{
public BanHangForm()
{
InitializeComponent();
LoadSP();
LoadTenSP();
Bang();
textBox8.Text = " Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year;
TienThua();
}
void TienThua()
{
int s;
if (textBox10.Text == "")
{
textBox9.Text = "";
}
else
{
if (textBox7.Text == "")
{
textBox9.Text = "";
}
else
{
s = int.Parse(textBox10.Text) - int.Parse(textBox7.Text);
textBox9.Text = s.ToString();
}
}
}
BindingSource SanPham = new BindingSource();
void LoadSP() // Danh sach san pham
{
string query = "select Ma as[Mã SP],Ten,DonVi as[Đơn vị],Gia as[Giá],SoLuong as[SL trong kho] from SanPham";
SanPham.DataSource = DataProvider.Instance.ExecuteQuery(query);
}
void LoadTenSP()
{
dataGridView1.DataSource = SanPham;
textBox1.DataBindings.Add(new Binding("text", dataGridView1.DataSource, "Ten", true, DataSourceUpdateMode.Never));
}
DataTable dt = new DataTable();
int TongTien = 0;
private void button2_Click(object sender, EventArgs e)
{
ThemSP();
dataGridView2.DataSource = dt;
}
void Bang()
{
dt.Columns.Add("Ma");
dt.Columns.Add("Ten");
dt.Columns.Add("Gia");
dt.Columns.Add("SoLuong");
}
int MaKH()
{
string query = "SELECT MAX(Ma) FROM dbo.KhachHang";
return int.Parse(DataProvider.Instance.DuLieu(query));
}
int MaHD()
{
string query = "SELECT MAX(Ma) FROM dbo.HoaDon";
return int.Parse(DataProvider.Instance.DuLieu(query));
}
private void button4_Click(object sender, EventArgs e)
{
string Ten = textBox3.Text;
string DiaChi = textBox4.Text;
string Sdt = textBox5.Text;
int ThanhTien = int.Parse(textBox7.Text);
int ngay = DateTime.Now.Day;
int thang = DateTime.Now.Month;
int nam = DateTime.Now.Year;
int SLmatHang = dataGridView2.Rows.Count - 1;
string ThoiGian = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
if (textBox3.Text != "" && textBox4.Text != "" && textBox5.Text != "")
{
if (BanHangDAO.Instance.InsertKH(Ten, DiaChi, Sdt))
{
}
else
{
MessageBox.Show("Không thành công");
}
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox7.Clear();
dt.Rows.Clear();
dataGridView2.DataSource = dt;
TongTien = 0;
}
else
{
MessageBox.Show("Nhập đầy đủ thông tin khách hàng");
}
}
public void LoadSearch(string TenSP)
{
string query = "SELECT * FROM dbo.SanPham WHERE Ten LIKE N'%" + TenSP + "%'";
dataGridView1.DataSource = DataProvider.Instance.ExecuteQuery(query);
}
private void button1_Click(object sender, EventArgs e)
{
string TenSP = textBox6.Text;
if (BanHangDAO.Instance.SearchSP(TenSP))
{
LoadSearch(TenSP);
}
else
{
MessageBox.Show("Không tìm thấy sản phẩm");
}
}
private void button5_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = SanPham;
LoadSP();
}
private void xoáToolStripMenuItem_Click(object sender, EventArgs e)
{
string Ten1;
int row = dataGridView2.CurrentCell.RowIndex;
int a = int.Parse(dataGridView2.Rows[row].Cells[2].Value.ToString());
int b = int.Parse(dataGridView2.Rows[row].Cells[3].Value.ToString());
string Ten2 = dataGridView2.Rows[row].Cells[1].Value.ToString();
int slSPtrongKho;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
Ten1 = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (string.Compare(Ten1, Ten2) == 0)
{
slSPtrongKho = int.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString());
if (BanHangDAO.Instance.UpdateSanPham2(slSPtrongKho, b, Ten1))
{
LoadSP();
}
}
}
TongTien -= a * b;
textBox7.Text = TongTien.ToString();
dt.Rows.RemoveAt(row);
dt.AcceptChanges();
dataGridView2.DataSource = dt;
}
void ThemSP()
{
int a, b;
string Ma = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string Ten = dataGridView1.CurrentRow.Cells[1].Value.ToString();
string GhiChu = dataGridView1.CurrentRow.Cells[2].Value.ToString();
string Gia = dataGridView1.CurrentRow.Cells[3].Value.ToString();
string SoLuong = textBox2.Text;
if (SoLuong != "")
{
int slTrongKho = int.Parse(dataGridView1.CurrentRow.Cells[4].Value.ToString());
int slBan = int.Parse(SoLuong);
if (slTrongKho >= slBan)
{
DataRow dr = dt.NewRow();
dr["Ma"] = Ma;
dr["Ten"] = Ten;
dr["Gia"] = Gia;
dr["SoLuong"] = SoLuong;
dt.Rows.Add(dr);
a = int.Parse(dataGridView1.CurrentRow.Cells[3].Value.ToString());
b = int.Parse(SoLuong);
TongTien += a * b;
textBox2.Clear();
if (BanHangDAO.Instance.UpdateSanPham(slTrongKho, slBan, Ten))
{
LoadSP();
}
}
else
{
MessageBox.Show("Số lượng sản phẩm không đủ");
}
}
else
{
MessageBox.Show("Nhập số lượng sản phẩm");
}
textBox7.Text = TongTien.ToString();
//textBox10.Text = (dt.Rows.Count).ToString();
}
//------------------------------------------------KhachHang-------------------------------------------------------------------
public void LoadSearchKH(string TenKH) // timkiem
{
string query = "SELECT hd.NgayBan AS[Ngày Bán],kh.Ma AS[Mã KH],kh.Ten AS[Tên],kh.DiaChi AS[Địa Chỉ],kh.SDT as[SĐT],hd.Ma AS[Mã HĐ],hd.ThanhTien AS[Tổng tiền] FROM dbo.KhachHang kh, dbo.HoaDon hd WHERE kh.Ma = hd.MaKH AND kh.Ten LIKE N'%" + TenKH + "%'";
dataGridView3.DataSource = DataProvider.Instance.ExecuteQuery(query);
}
private void button3_Click(object sender, EventArgs e)
{
string TenKH = textBox11.Text;
if (BanHangDAO.Instance.SearchKH(TenKH))
{
LoadSearchKH(TenKH);
}
else
{
MessageBox.Show("Không tìm thấy khách hàng");
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace IModelRepository
{
public interface ITestContext
{
ITest GetTest(int id);
IEnumerable<IUserTest> GetTestsProfile(int id);
void CheckTest(ITestResult test);
void AddTest(ITest test);
}
}
|
using System.Web.Mvc;
namespace CarDealerApp.Controllers
{
using System.Net;
using CarDealer.Data;
using CarDealer.Data.Repositories;
using CarDealer.Models;
using CarDealer.Services;
using Filters;
[RoutePrefix("customers")]
public class CustomersController : Controller
{
private readonly CustomersService customerService;
public CustomersController()
{
this.customerService = new CustomersService(new EfGenericRepository<Customer>(Data.Context()));
}
// GET: Customers
public ActionResult All(string order)
{
var customersVm = this.customerService.Customers(order);
return this.View(customersVm);
}
public ActionResult TotalSalesByCustomer(int id)
{
var totalSalesVm = this.customerService.GetCustomerTotalSales(id);
return this.View(totalSalesVm);
}
// GET: Create customer
[Route("create")]
public ActionResult Create()
{
return this.View();
}
[HttpPost]
[Route("create")]
public ActionResult Create([Bind(Include = "Name,BirthDate")] Customer customer)
{
if (ModelState.IsValid)
{
this.customerService.AddCustomer(customer);
return RedirectToAction("All");
}
return View(customer);
}
[Route("edit")]
public ActionResult Edit(int id)
{
var customer = this.customerService.GetCustomerVmById(id);
if (customer == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
return this.View(customer);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("edit")]
[Log]
public ActionResult Edit([Bind(Include = "Id,Name,BirthDate")] Customer customer)
{
if (this.ModelState.IsValid)
{
this.customerService.EditCustomer(customer);
}
return this.RedirectToAction("All", "Customers");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
namespace Anywhere2Go.Library
{
public class SendMail
{
private SmtpClient SmtpMail;
private String SendTo;
private String strSubject;
private String strMessage;
private String MailForm;
private Boolean ToHTML;
private MailAddressCollection SendToMany;
private String senderName;
private String replyTo;
public SendMail()
{
SmtpMail = new SmtpClient();
SmtpMail.Host = "mail.one2car.co.th";
MailForm = "info@imagineering-service.com";
}
public SendMail(string host,string mailfrom)
{
SmtpMail = new SmtpClient();
SmtpMail.Host = host;
MailForm = mailfrom;
}
public SendMail(string host, string user, string pass, int port, bool SSL)
{
SmtpMail = new SmtpClient(host, port);
SmtpMail.Credentials = new System.Net.NetworkCredential(user, pass);
SmtpMail.EnableSsl = SSL;
}
public string SmtpServer
{
get { return SmtpMail.Host; }
set { SmtpMail.Host = value; }
}
public string ToUser
{
get { return SendTo; }
set { SendTo = value; }
}
public MailAddressCollection ToUsers
{
get { return SendToMany; }
set { SendToMany = value; }
}
public string Subject
{
get { return strSubject; }
set { strSubject = value; }
}
public string Body
{
get { return strMessage; }
set { strMessage = value; }
}
public bool MailToHTML
{
get { return ToHTML; }
set { ToHTML = value; }
}
public string mailSendFrom
{
set { MailForm = value; }
}
public string SenderName
{
set { senderName = value; }
}
public string ReplyTo
{
set { replyTo = value; }
}
public Boolean Sending()
{
try {
MailMessage message = new MailMessage();
message.From = (!string.IsNullOrEmpty(senderName)) ? new MailAddress(MailForm.Trim(), senderName.Trim()) : new MailAddress(MailForm.Trim());
message.To.Add(new MailAddress(SendTo));
message.BodyEncoding = System.Text.Encoding.GetEncoding(874);
message.Subject = strSubject.Trim();
message.Body = strMessage.Trim();
message.Priority = MailPriority.Normal;
message.IsBodyHtml = ToHTML;
SmtpMail.Send(message);
return true;
} catch {
return false;
}finally {
SmtpMail = null;
}
}
public void SendingManyReceives(string toCCs = "",Attachment attachment = null)
{
MailMessage message = new MailMessage();
try
{
message.From = (!string.IsNullOrEmpty(senderName)) ? new MailAddress(MailForm.Trim(), senderName.Trim()) : new MailAddress(MailForm.Trim());
SendToMany.ToList().ForEach(m => message.To.Add(m.Address));
if (!string.IsNullOrEmpty(replyTo))
{
message.ReplyToList.Add(new MailAddress(replyTo, "Aplus Support"));
}
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = strSubject.Trim();
message.Body = strMessage.Trim().Replace("\n", "<br>");
message.Priority = MailPriority.Normal;
message.IsBodyHtml = ToHTML;
if (attachment != null)
{
message.Attachments.Add(attachment);
}
if (!string.IsNullOrEmpty(toCCs))
{
if (toCCs.Trim() != "")
{
string[] CCId = toCCs.Split(',');
foreach (string CCEmail in CCId)
{
if (!string.IsNullOrEmpty(CCEmail))
{
message.CC.Add(new MailAddress(CCEmail.Trim()));
}
}
}
}
SmtpMail.Port = 587;
SmtpMail.EnableSsl = true;
SmtpMail.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
throw ex;
//for (int i = 0; i < ex.InnerExceptions.Length; i++)
//{
// SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
// if (status == SmtpStatusCode.MailboxBusy ||
// status == SmtpStatusCode.MailboxUnavailable)
// {
// // Console.WriteLine("Delivery failed - retrying in 5 seconds.");
// System.Threading.Thread.Sleep(5000);
// SmtpMail.Send(message);
// }
// else
// {
// // ex.Data = ex.InnerExceptions[i].FailedRecipient;
// }
//}
}
catch (Exception ex)
{
throw ex;
}
finally
{
SmtpMail = null;
}
}
}
}
|
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DataAccesLayer.Repositories
{
public class KategoriRepository : IKategoriRepository<Kategori>
{
CategoryDataManager categoryDataManager;
List<Kategori> kategoriList;
public KategoriRepository()
{
kategoriList = new List<Kategori>();
categoryDataManager = new CategoryDataManager();
kategoriList = GetAll();
}
//Skapar ny katgori och sparar ändringarna
public void New(Kategori kategori)
{
kategoriList.Add(kategori);
SaveAllChanges();
}
//Sparar kategori ändringar
public void Save(int index, Kategori kategori)
{
try
{
if (index >= 0)
{
kategoriList[index] = kategori;
}
SaveAllChanges();
}
catch (System.ArgumentOutOfRangeException)
{
throw;
}
}
//Raderar kategori och sparar ändringarna
public void Delete(int index)
{
kategoriList.RemoveAt(index);
SaveAllChanges();
}
//Sparar alla ändringar och lägger in dem i ett lokalt xml dokument
public void SaveAllChanges()
{
categoryDataManager.Serialize(kategoriList);
}
//Hämtar alla kategorier från ett lokalt xml dokument
public List<Kategori> GetAll()
{
List<Kategori> kategoriListToBeReturned = new List<Kategori>();
try
{
kategoriListToBeReturned = categoryDataManager.Deserialize();
}
catch (Exception)
{
}
return kategoriListToBeReturned;
}
//Hämtar kategori via ett namn
public Kategori GetByNamn(string namn)
{
return GetAll().FirstOrDefault(p => p.Namn.Equals(namn));
}
//Hämtar kategori via ett index
public string GetName(int index)
{
return kategoriList[index].Namn;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Client.SubSystem;
using IRAP.Entity.SSO;
using IRAP.Entity.Kanban;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.MESPDC
{
public partial class frmUDFFormWithCOMScanner : IRAP.Client.Global.GUI.frmCustomFuncBase
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private MenuInfo menuInfo = null;
private UDFForm1Ex busUDFForm = new UDFForm1Ex();
private List<StationPortInfo> ports = new List<StationPortInfo>();
private List<ScannerForSerialPort> scanners = new List<ScannerForSerialPort>();
private List<SerialPortScannerUDFLog> logs = new List<SerialPortScannerUDFLog>();
private List<ScannerView> scannerViews = new List<ScannerView>();
public frmUDFFormWithCOMScanner()
{
InitializeComponent();
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
#region 从数据库中获取当前站点配置的串口扫描枪的信息列表
{
int errCode = 0;
string errText = "";
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
IRAPKBClient.Instance.ufn_GetKanban_Station_Ports(
IRAPUser.Instance.CommunityID,
IRAPUser.Instance.SysLogID,
0,
ref ports,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
#endregion
#region 根据上面获取到的串口扫描枪信息列表,创建串口扫描枪读取对象列表,并开始侦听
{
try
{
foreach (StationPortInfo port in ports)
{
if (port.IsComm)
{
ScannerForSerialPort scanner = new ScannerForSerialPort(lstBarCodes, port);
scanners.Add(scanner);
scannerViews.Add(
new ScannerView()
{
PortName = port.CommPort,
WorkUnitCode = port.WorkUnitCode,
WorkUnitName = port.WorkUnitName,
WorkUnitLeafID = port.WorkUnitLeaf,
});
}
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
}
#endregion
grdSerialPortScanners.DataSource = scannerViews;
grdBarCodeLogs.DataSource = logs;
grdvSerialPortScanners.BestFitColumns();
grdvBarCodeLogs.BestFitColumns();
}
private void WriteToScreenLog(
string mainBarCode,
string SerialPort,
string serialNumber,
int errCode,
string errText)
{
if (logs.Count >= 100)
{
logs.RemoveRange(99, logs.Count - 99);
}
logs.Insert(
0,
new SerialPortScannerUDFLog()
{
ProcessTime = DateTime.Now.ToString(),
MainBarCode = mainBarCode,
SerialPort = SerialPort,
SerialNumber = serialNumber,
ResultCode = errCode,
ResultMessage = errText,
});
grdvBarCodeLogs.BestFitColumns();
}
private void frmUDFFormWithCOMScanner_Shown(object sender, EventArgs e)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
if (this.Tag is MenuInfo)
{
menuInfo = this.Tag as MenuInfo;
}
else
{
WriteLog.Instance.Write("没有正确的传入菜单参数", strProcedureName);
WriteToScreenLog("", "", "", -1, "没有正确的传入菜单参数!");
return;
}
try
{
if (menuInfo.Parameters == "")
{
WriteToScreenLog("", "", "", -1, "菜单参数中没有正确配置万能表单的参数");
}
else
{
busUDFForm.SetCtrlParameter(menuInfo.Parameters);
busUDFForm.OpNode = menuInfo.OpNode;
frmUDFFormWithCOMScanner_Activated(this, null);
timer.Enabled = true;
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteToScreenLog("", "", "", -1, error.Message);
}
#if DEBUG
textEdit1.Visible = true;
#else
textEdit1.Visible = false;
#endif
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void frmUDFFormWithCOMScanner_Activated(object sender, EventArgs e)
{
Options.Visible = true;
}
private void frmUDFFormWithCOMScanner_FormClosed(object sender, FormClosedEventArgs e)
{
for (int i = scanners.Count - 1; i >= 0; i--)
{
scanners[i].Close();
}
}
private void timer_Tick(object sender, EventArgs e)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
timer.Enabled = false;
try
{
string barCode = "";
// 从条码池中获取一条待处理的在产品条码
lstBarCodes.Invoke(
new EventHandler(
delegate
{
if (lstBarCodes.Items.Count > 0)
{
object item = lstBarCodes.Items[0];
barCode = lstBarCodes.Items[0].ToString();
lstBarCodes.Items.Remove(item);
}
}));
string[] splitString = barCode.Split('|');
if (splitString.Length <= 1)
{
return;
}
foreach (ScannerView view in scannerViews)
{
if (view.PortName == splitString[0])
{
view.BarCode = splitString[1].TrimEnd('\0');
grdvSerialPortScanners.BestFitColumns();
if (Options.SelectStation == null ||
Options.SelectProduct == null)
{
WriteToScreenLog(
view.BarCode,
"",
"",
-1,
"当前站点没有配置产品流程和或工位");
return;
}
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
object tag = scannerViews;
#if DEBUG
XtraMessageBox.Show(
string.Format(
"PortName={0}|WorkUnitLeafID={1}|" +
"WorkUnitCode={2}|WorkUnitName={3}",
view.PortName,
view.WorkUnitLeafID,
view.WorkUnitCode,
view.WorkUnitName));
#endif
busUDFForm.SetStrParameterValue(view.BarCode, 1);
busUDFForm.SaveOLTPUDFFormData(
CurrentOptions.Instance.OptionTwo.T102LeafID,
view.WorkUnitLeafID,
null,
ref tag);
try
{
grdvSerialPortScanners.RefreshData();
grdvSerialPortScanners.BestFitColumns();
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("刷新界面表格数据的时候发生错误:{0}", error.Message),
strProcedureName);
}
WriteLog.Instance.Write(
string.Format(
"{0}.{1}",
busUDFForm.ErrorCode,
busUDFForm.ErrorMessage),
strProcedureName);
WriteToScreenLog(
view.BarCode,
splitString[0],
"",
busUDFForm.ErrorCode,
busUDFForm.ErrorMessage);
#region 调用完成后执行 Action
if (busUDFForm.ErrorCode == 0)
{
WriteLog.Instance.Write(
string.Format("Output={0}", busUDFForm.OutputStr),
strProcedureName);
if (busUDFForm.OutputStr != "")
{
try
{
Actions.UDFActions.DoActions(
busUDFForm.OutputStr,
null,
ref tag);
try
{
grdvSerialPortScanners.RefreshData();
grdvSerialPortScanners.BestFitColumns();
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("刷新界面表格数据的时候发生错误:{0}", error.Message),
strProcedureName);
}
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("错误信息:{0}。跟踪堆栈:{1}。",
error.Message,
error.StackTrace),
strProcedureName);
WriteToScreenLog(
view.BarCode,
splitString[0],
"",
-1,
string.Format(
"执行输出指令时发生错误:[{0}]",
error.Message));
}
}
}
#endregion
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteToScreenLog(
view.BarCode,
"",
"",
-1,
error.Message);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
}
finally
{
timer.Enabled = true;
}
}
private void textEdit1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode== Keys.Enter)
{
lstBarCodes.Items.Add(textEdit1.Text);
textEdit1.Text = "";
}
}
}
internal class SerialPortScannerUDFLog
{
public string ProcessTime { get; set; }
public string MainBarCode { get; set; }
public string SerialPort { get; set; }
public string SerialNumber { get; set; }
public int ResultCode { get; set; }
public string ResultMessage { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
using System.Linq;
[DisallowMultipleComponent]
[RequireComponent(typeof(LineRenderer))]
public class AIStateController : MonoBehaviour
{
private bool _isAIOn = true;
private bool _beingControlled = false;
public bool BeingControlled
{
get { return _beingControlled; }
set { _beingControlled = value; }
}
private bool _selectedForControl = false;
public bool IsSelectedForControl
{
get { return _selectedForControl; }
}
[SerializeField]
private GameData _gameData;
[SerializeField]
private CharacterStats _characterStats;
public CharacterStats CharacterStats
{
get { return _characterStats; }
}
[SerializeField]
private ZomzListAttribute _zomzActionsList;
[SerializeField]
private SelectedZombie _currentSelectedZombie;
private bool _isAlive = true;
public bool IsAlive
{
get { return _isAlive; }
}
public float _currentHealth;
[SerializeField]
private Transform _eyes;
public Transform Eyes
{
get { return _eyes; }
set { _eyes = value; }
}
[SerializeField]
private Image _zombieHealthBar;
[Header("Models")]
[SerializeField]
private GameObject _normalModeModel;
[SerializeField]
private GameObject _zomzModeModel;
[SerializeField]
private Material _normalModeMaterial;
[SerializeField]
private Material _zomzModeMaterial;
[SerializeField]
private GameObject _selectionQuad;
[SerializeField]
private float _lookRange = 10f;
public float LookRange
{
get { return _lookRange; }
set { _lookRange = value; }
}
[SerializeField]
private float _lookSphere = 10f;
public float LookSphere
{
get { return _lookSphere; }
set { _lookSphere = value; }
}
[SerializeField]
private float _attackRange = 1f;
public float AttackRange
{
get { return _attackRange; }
set { _attackRange = value; }
}
[SerializeField]
private float _attackRate = 1f;
public float AttackRate
{
get { return _attackRate; }
set { _attackRate = value; }
}
[Header("AI States")]
[SerializeField]
private State _initState;
public State InitState
{
get { return _initState; }
set { InitState = value; }
}
[SerializeField]
private State _currentState;
public State CurrentState
{
get { return _currentState; }
set { _currentState = value; }
}
[SerializeField]
private State _remainState;
public State RemainState
{
get { return _remainState; }
set { _remainState = value; }
}
[SerializeField]
private State _deadState;
public State DeadState
{
get { return _deadState; }
set { _deadState = value; }
}
[SerializeField]
private State _chaseState;
public State ChaseState
{
get { return _chaseState; }
set { _chaseState = value; }
}
[Header("FX")]
[SerializeField]
private GameObject _hurtFX;
private Animator _animator;
public Animator Animator
{
get { return _animator; }
}
[HideInInspector]
public NavMeshAgent navMeshAgent;
public Transform ChaseTarget;
[HideInInspector]
public float StateTimeElapsed = 0f;
[SerializeField]
private GameObject _wayPointsObj;
[HideInInspector]
public List<Transform> wayPoints;
private float period = float.MaxValue;
private CharacterControls _playerControls;
private GameObject _player;
private bool _zomzAttack = false;
private int _nextWayPoint;
public int NextWayPoint
{
get { return _nextWayPoint; }
set { _nextWayPoint = value; }
}
[Header("Mana Costs")]
[SerializeField]
private GameFloatAttribute _zomzManaAttribute;
[SerializeField]
private float _manaForUnitMovement = 2f;
[SerializeField]
private float _manaForAttack = 10f;
[SerializeField]
private float _zomzAttackCooldown = 10f;
private LineRenderer _lineRenderer;
private Queue<ZomzActionPoint> _zomzActionPoints = new Queue<ZomzActionPoint>();
public int NumActionPoints{
get { return _zomzActionPoints.Count; }
}
private List<Vector3> points = new List<Vector3>();
private int _groundLayerMask;
private int _enemyPlayerMask;
private ZomzActionSystem _zactionSystem;
private Renderer _renderer;
private bool _isExecutingActions = false;
private Coroutine _zomzAttackCoroutine;
private Coroutine _hurtPlayerCoroutine;
void Start()
{
_renderer = _normalModeModel.GetComponent<Renderer>();
_zactionSystem = _zomzModeModel.GetComponent<ZomzActionSystem>();
_groundLayerMask |= (1 << LayerMask.NameToLayer("Ground"));
_enemyPlayerMask = (1 << LayerMask.NameToLayer("Enemy")) | (1 << LayerMask.NameToLayer("Player"));
_lineRenderer = GetComponent<LineRenderer>();
_currentState = _initState;
_currentHealth = _characterStats.Health;
_player = GameObject.FindWithTag("Player");
_playerControls = _player.GetComponent<CharacterControls>();
//Get all waypoints
if (_wayPointsObj != null)
{
for (int i = 0; i < _wayPointsObj.transform.childCount; i++)
{
wayPoints.Add(_wayPointsObj.transform.GetChild(i));
}
}
//Get Navmesh Agent
navMeshAgent = GetComponent<NavMeshAgent>();
//Set Animator
_animator = GetComponent<Animator>();
_animator.SetTrigger(_currentState.AnimationTrigger);
}
public void SelectCurrentForControl()
{
_selectedForControl = true;
_currentSelectedZombie.CurrentSelectedZombie = this;
if (_selectionQuad)
_selectionQuad.SetActive(true);
}
public void ClearCurrentControl()
{
//_currentSelectedZombie.ResetSelection();
_selectedForControl = false;
if (_selectionQuad)
_selectionQuad.SetActive(false);
}
public void TakeControl()
{
_renderer.sharedMaterial = _zomzModeMaterial;
if (_zactionSystem)
_zactionSystem.enabled = true;
_beingControlled = true;
//_zomzActionsList.AllActionPoints.Clear ();
_zomzActionPoints.Enqueue(new ZomzActionPoint(_zomzModeModel.transform.position, ZomzAction.MOVE, null));
ToggleZomzAttackMode(false);
//_zomzActionsList.AllActionPoints.Add(new ZomzActionPoint(this,_zomzModeModel.transform.position, ZomzAction.MOVE, null));
points.Clear();
points.Add(_zomzModeModel.transform.position);
}
public void BeforeExecuting()
{
ClearCurrentControl();
_zomzModeModel.SetActive(false);
_zactionSystem.IsSelected = false;
_isExecutingActions = true;
_currentSelectedZombie.ResetSelection();
navMeshAgent.isStopped = true;
navMeshAgent.ResetPath();
//points.Clear();
//_lineRenderer.positionCount = points.Count;
//_lineRenderer.SetPositions(points.ToArray());
StartCoroutine(ExecuteActions());
EnableDisableColliders(false);
}
void EnableDisableColliders(bool pEnable)
{
Collider coll = GetComponent<Collider>();
Rigidbody rb = GetComponent<Rigidbody>();
if (coll != null)
coll.enabled = pEnable;
if (rb != null)
{
if (!pEnable)
rb.constraints = RigidbodyConstraints.FreezePosition;
else
{
rb.constraints = RigidbodyConstraints.None;
rb.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionY;
}
}
}
public IEnumerator ExecuteActions()
{
_animator.SetTrigger("walk");
if (_isExecutingActions)
{
while (_zomzActionPoints.Count > 0)
{
yield return StartCoroutine(UpdateZomzActions());
}
RelinquishControl();
if (ChaseTarget != null && !ChaseTarget.CompareTag("Player"))
{
Debug.Log(ChaseTarget);
//TransitionToState(_chaseState);
yield return new WaitForSeconds(_zomzAttackCooldown);
ChaseTarget = GameObject.FindWithTag("Player").transform;
}
//_animator.SetTrigger("idle");
}
yield return null;
}
IEnumerator UpdateZomzActions()
{
int i = 0;
if (navMeshAgent.remainingDistance<0.1f)// && _zomzAttackCoroutine==null)
{
ZomzActionPoint actionPoint = _zomzActionPoints.Dequeue();
//Move
if (actionPoint.ZomzAction == ZomzAction.MOVE)
{
navMeshAgent.SetDestination(actionPoint.Position);
navMeshAgent.speed = _characterStats.ZomzSpeed;
//Update Line Renderer
if(points.Count>0)
points.RemoveAt(i++);
_lineRenderer.positionCount = points.Count;
_lineRenderer.SetPositions(points.ToArray());
}
//Attack
else if (actionPoint.ZomzAction == ZomzAction.ATTACK)
{
points.Clear();
_lineRenderer.positionCount = points.Count;
_lineRenderer.SetPositions(points.ToArray());
ChaseTarget = actionPoint.ActionTarget;
_zomzActionPoints.Clear();
//if (actionPoint.ActionTarget != null)
//{
// transform.LookAt(actionPoint.ActionTarget);
// _animator.SetTrigger("attack");
// DealZomzDamage(actionPoint.ActionTarget);
// if (_zomzAttackCoroutine == null)
// _zomzAttackCoroutine = StartCoroutine(WaitToEndZomzAttack ());
//}
}
yield return null;
}
}
public void RelinquishControl()
{
_zomzModeModel.SetActive(false);
_isExecutingActions = false;
_renderer.sharedMaterial = _normalModeMaterial;
_beingControlled = false;
_zomzModeModel.transform.localPosition = Vector3.zero;
_zomzModeModel.transform.localRotation = Quaternion.identity;
_zomzActionPoints.Clear ();
points.Clear ();
navMeshAgent.speed = _characterStats.WalkSpeed;
EnableDisableColliders(true);
ToggleAI(true);
}
public void DealZomzDamage(Transform pTarget)
{
//if (pTarget.CompareTag ("Enemy"))
//{
// AIStateController otherZombie = pTarget.GetComponent<AIStateController> ();
// if (otherZombie != null)
// {
// otherZombie.TakeDamage (_characterStats.AttackStrength);
// TakeDamage(_characterStats.AttackDamageToSelf);
// }
//}
//if (pTarget.CompareTag ("Player"))
//{
// if (_playerControls)
// {
// _playerControls.StartCoroutine(_playerControls.Hurt(transform, _characterStats.AttackStrength));
// TakeDamage(_characterStats.AttackDamageToSelf);
// }
//}
}
IEnumerator WaitToEndZomzAttack()
{
yield return new WaitForSeconds (_characterStats.AttackRate);
_zomzAttackCoroutine = null;
_animator.SetTrigger ("walk");
}
void Update()
{
if(!_gameData.IsPaused)
{
if (_isAlive)
{
if (_isAIOn)
CurrentState.UpdateState(this);
if (_zomzManaAttribute.CurrentValue > 0)
{
//Under Zomz mode and selected by clicking
if (_beingControlled && _selectedForControl)
{
_zomzModeModel.SetActive(true);
_zactionSystem.IsSelected = true;
if (DistanceToLastPoint(_zomzModeModel.transform.position) > 0.5f)
{
if (_zomzManaAttribute)
_zomzManaAttribute.CurrentValue -= _manaForUnitMovement;
_zomzActionPoints.Enqueue (new ZomzActionPoint (_zomzModeModel.transform.position, ZomzAction.MOVE, null));
//_zomzActionsList.AllActionPoints.Add(new ZomzActionPoint(this, _zomzModeModel.transform.position, ZomzAction.MOVE, null));
ToggleZomzAttackMode(false);
points.Add(_zomzActionPoints.Last().Position);
_lineRenderer.positionCount = points.Count;
_lineRenderer.SetPositions(points.ToArray());
}
//Show attack sphere
if (Input.GetKeyDown(KeyCode.Alpha1))
{
ToggleZomzAttackMode(true);
//_zomzAttack = true;
}
if (_zomzAttack)
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity, _enemyPlayerMask))
{
if (hit.transform != null)
{
if (hit.collider.gameObject != this.gameObject)
{
if (_zomzManaAttribute.CurrentValue - _manaForAttack > 0)
{
if (_zomzManaAttribute)
_zomzManaAttribute.CurrentValue -= _manaForAttack;
_zomzActionPoints.Enqueue(new ZomzActionPoint(_zomzModeModel.transform.position, ZomzAction.ATTACK, hit.transform));
}
}
}
}
}
}
}
}
else
{
_zactionSystem.enabled = false;
}
//Released from zomz mode
if (!_beingControlled)
{
_zomzModeModel.SetActive(false);
_zactionSystem.IsSelected = false;
_zomzActionPoints.Clear();
points.Clear();
_lineRenderer.positionCount = points.Count;
_lineRenderer.SetPositions(points.ToArray());
_selectedForControl = false;
ToggleZomzAttackMode(false);
}
//Different Zombie Selected
if (!_selectedForControl)
{
_zactionSystem.IsSelected = false;
}
}
else{
CurrentState = null;
}
}
}
public void ToggleZomzAttackMode(bool pEnable)
{
_zomzAttack = pEnable;
}
private float DistanceToLastPoint(Vector3 pPoint)
{
if (!_zomzActionPoints.Any())
return float.MaxValue;
return Vector3.Distance (_zomzActionPoints.Last().Position, pPoint);
}
void ResetAI()
{
navMeshAgent.isStopped = true;
_currentState = null;
_animator.SetTrigger ("idle");
}
public void ToggleAI(bool pOnOff)
{
if (_isAlive && !_isExecutingActions)
{
_isAIOn = pOnOff;
if (!_isAIOn)
{
ResetAI ();
}
else
{
TransitionToState (InitState);
}
}
}
void OnDrawGizmos()
{
if (_currentState != null)
{
Gizmos.color = _currentState.SceneGizmoColor;
Gizmos.DrawWireSphere (transform.position, 2);
}
Gizmos.color = Color.white;
Gizmos.DrawWireSphere (transform.position, _characterStats.ZomzRange);
}
public void TakeDamage(float pDamage)
{
StartCoroutine (DamageCoroutine (pDamage));
}
IEnumerator DamageCoroutine(float pDamage)
{
if (_isAlive)
{
if (pDamage > 0)
{
if (_currentHealth - pDamage > 0)
{
_currentHealth -= pDamage;
}
else
_currentHealth = 0;
if (_currentHealth > 0)
{
yield return new WaitForSeconds(0.7f);
if (_hurtFX != null)
Instantiate(_hurtFX, _eyes.transform.position, Quaternion.identity);
//Update UI Element
if (_zombieHealthBar)
_zombieHealthBar.fillAmount = _currentHealth / 100;
}
else
{
yield return new WaitForSeconds(0.7f);
//Update UI Element
if (_zombieHealthBar)
_zombieHealthBar.fillAmount = 0;
TransitionToState(DeadState);
_isAlive = false;
//yield return new WaitForSeconds(2f);
//Destroy(gameObject);
}
}
}
}
public void Attack()
{
//if (!IsAlive)
//{
// StopCoroutine (_hurtPlayerCoroutine);
// _hurtPlayerCoroutine = null;
// return;
//}
//if (_characterStats)
//{
// if (period > _characterStats.AttackRate)
// {
// _animator.SetTrigger ("attack");
// if (ChaseTarget.CompareTag("Player"))
// {
// _playerControls.StartCoroutine (_playerControls.Hurt (transform, _characterStats.AttackStrength));
// }
// else if(ChaseTarget.CompareTag("Enemy"))
// {
// AIStateController enemyCtrl = ChaseTarget.GetComponent<AIStateController>();
// if(enemyCtrl!=null)
// {
// enemyCtrl.StartCoroutine(enemyCtrl.DamageCoroutine(_characterStats.AttackStrength));
// }
// }
// if (_characterStats.AttackDamageToSelf > 0)
// TakeDamage(_characterStats.AttackDamageToSelf);
// period = 0;
// }
// period += Time.deltaTime;
//}
}
public void TransitionToState(State pNextState)
{
if (pNextState != RemainState)
{
_currentState = pNextState;
_animator.SetTrigger (_currentState.AnimationTrigger);
OnExitState ();
}
}
public bool CheckIfCountDownElapsed(float duration)
{
StateTimeElapsed += Time.deltaTime;
return (StateTimeElapsed >= duration);
}
private void OnExitState()
{
StateTimeElapsed = 0;
}
}
|
using AutoMapper;
using ParrisConnection.DataLayer.DataAccess;
using ParrisConnection.DataLayer.Entities.Wall;
using ParrisConnection.ServiceLayer.Data;
using System.Collections.Generic;
namespace ParrisConnection.ServiceLayer.Services.Status.Save
{
public class StatusSaveService : IStatusSaveService
{
private readonly IDataAccess _dataAccess;
private readonly IMapper _mapper;
private readonly IMapper _commentMapper;
public StatusSaveService(IDataAccess dataAccess)
{
_dataAccess = dataAccess;
var commentConfig = new MapperConfiguration(m => m.CreateMap<Comment, CommentData>().ReverseMap());
_commentMapper = new Mapper(commentConfig);
var config = new MapperConfiguration(m => m.CreateMap<StatusData, DataLayer.Entities.Wall.Status>().ReverseMap().ForMember(u => u.Comments, d => d.MapFrom(s => _commentMapper.Map<IEnumerable<CommentData>>(s.Comments))));
_mapper = new Mapper(config);
}
public void SaveStatus(StatusData status)
{
_dataAccess.Statuses.Insert(_mapper.Map<DataLayer.Entities.Wall.Status>(status));
}
}
}
|
using CEMAPI.BAL;
using CEMAPI.DAL;
using CEMAPI.Models;
using Rotativa.Options;
using DMSUploadDownload;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Globalization;
namespace CEMAPI.Controllers
{
public class CancellationPDFController : Controller
{
TETechuvaDBContext context = new TETechuvaDBContext();
public ActionResult GenerateDOCPDF(int OfferId, int ProjectID, DateTime EffectiveDate, int CancellationId)
{
COOutputs result = new COOutputs();
SuccessInfo sinfo = new SuccessInfo();
string projtName = string.Empty;
var offerProjName = (from offer in context.TEOffers
join prj in context.TEProjects on offer.ProjectID equals prj.ProjectID
where offer.OfferID == OfferId
select new
{
prj.ProjectName
}).FirstOrDefault();
if (offerProjName != null)
{
projtName = offerProjName.ProjectName;
}
string Page = "0"; var ToPage = "0";
string customSwitches = string.Format("--footer-html \"{0}\" " +
"--header-html \"{1}\" ",
Url.Action("DOCFooter", "CancellationPDF", new { ProjectName = projtName, PageNumber = Page, TotalPage = ToPage }, "http"),
Url.Action("DOCHeader", "CancellationPDF", new { }, "http"));
var actionResult = new Rotativa.ActionAsPdf("DeedOfCancellationPDFView", new
{
OfferId = OfferId,
ProjectID = ProjectID,
EffectiveDate = EffectiveDate,
CancellationId = CancellationId
})
{
FileName = "DeedOfCancellation.pdf",
PageSize = Size.A4,
//PageMargins = { Left = 10, Right = 10, Top = 10, Bottom = 10 },
PageMargins = { Left = 15, Right = 15, Top = 20, Bottom = 35 },
CustomSwitches = customSwitches
};
string filePath = HostingEnvironment.MapPath("~/UploadDocs/");
string filename = string.Empty;
filename = DateTime.Now.ToString();
filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", "");
var byteArray = actionResult.BuildPdf(ControllerContext);
var fileStream = new FileStream(filePath + "\\DeedOfCancellation-" + filename + ".pdf", FileMode.Create, FileAccess.Write);
fileStream.Write(byteArray, 0, byteArray.Length);
fileStream.Close();
string base64String = string.Empty;
base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length);
string url = WebConfigurationManager.AppSettings["DMSDownloadedFiles"];
string downloadFilePath = url + "/" + "DeedOfCancellation-" + filename + ".pdf";
sinfo.errormessage = "Success";
sinfo.errorcode = 0;
result.info = sinfo;
result.Result = downloadFilePath;
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult DOCFooter(string ProjectName, string Page, string ToPage)
{
ViewBag.ProjectName = ProjectName;
ViewBag.Page = Page;
ViewBag.ToPage = ToPage;
return View();
}
public ActionResult DOCHeader()
{
return View();
}
public ActionResult DeedOfCancellationPDFView(int OfferId, int ProjectID, DateTime EffectiveDate, int CancellationId)
{
int projectTemplateid = (from t1 in context.TE_Doc_Prj_Templates
join t2 in context.TE_Ref_Document_Type on t1.RefDocumentTypeID equals t2.RefDocumentTypeID
where t1.ProjectID == ProjectID && t1.Status.Equals("Approved") && t2.Code.Equals("DC")
&& t1.isDeleted == false && t2.IsDeleted == false
select t1.ProjectTemplateID).FirstOrDefault();
string htmlContent = GetHtmlStringByProjectTemplateId(projectTemplateid);
var docDetails = (from offer in context.TEOffers
join prj in context.TEProjects on offer.ProjectID equals prj.ProjectID
join unt in context.TEUnits on offer.UnitID equals unt.UnitID
where offer.OfferID == OfferId
select new
{
unt.UnitNumber,
prj.ProjectName,
prj.ProjectColor,
offer.SAPCustomerID
}).FirstOrDefault();
string unitnumber = string.Empty, projectName = string.Empty, projectColour = string.Empty, sapCustomerId = string.Empty;
if (docDetails != null)
{
unitnumber = docDetails.UnitNumber;
projectName = docDetails.ProjectName;
projectColour = docDetails.ProjectColor;
sapCustomerId = docDetails.SAPCustomerID;
}
// Getting Effective Date Details
int dayInDate = EffectiveDate.Day;
string dayOrdinal = DateOrdinal(dayInDate);
string effectiveDateDay = string.Empty, effectiveDateMonth = string.Empty, effectiveDateYear = string.Empty,
formattedEffetiveDate = string.Empty, afsDate = string.Empty, caDate = string.Empty, icsDate = string.Empty, tsDate = string.Empty;
effectiveDateDay = dayOrdinal;
effectiveDateMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(EffectiveDate.Month);
effectiveDateYear = EffectiveDate.Year.ToString();
formattedEffetiveDate = EffectiveDate.ToString("dd.MM.yyyy");
//Getting AFS Date from Offer Events
var afsEventDate = (from evnt in context.TEOfferEventsDates
where (evnt.offerId == OfferId && evnt.OfferLifeCycleDateType == "SignedAFSDate")
select new { evnt.OfferLifeCycleDate }).FirstOrDefault();
if (afsEventDate != null)
{
afsDate = afsEventDate.OfferLifeCycleDate.Value.ToString("dd.MM.yyyy");
}
// Getting Customization submission Date
TECustomerBOQ custBoq = context.TECustomerBOQs.Where(a => a.CustomerID == sapCustomerId && a.isDeleted == false
&& a.Status == "Approved").FirstOrDefault();
if (custBoq != null && custBoq.CustomerBOQID > 0)
{
icsDate = custBoq.CustomizationSubmissionDate.Value.ToString("dd.MM.yyyy");
}
//Getting TS Date from Offer Events
var signedTSDate = (from evnt in context.TEOfferEventsDates
where (evnt.offerId == OfferId && evnt.OfferLifeCycleDateType == "SignedTermsheetDate")
select new { evnt.OfferLifeCycleDate }).FirstOrDefault();
if (signedTSDate != null)
{
tsDate = signedTSDate.OfferLifeCycleDate.Value.ToString("dd.MM.yyyy");
}
//Getting Refund Details
decimal totalCollections = new GenericDAL().GetSumOfReceiptsBySAPCustomerId(sapCustomerId);
//decimal totalTaxAmount = new GenericDAL().GetTotalInvoicedTaxAmount(sapCustomerId);
decimal totalTaxAmount = new GenericDAL().GetTotalMileStoneTypeInvoicedTaxAmount(sapCustomerId);
decimal totAmtCancelledAgreements = totalCollections - totalTaxAmount;
decimal totalNonRefundableTaxAmount = (decimal)new GenericDAL().GetTotalMileStoneTypeInvoicedNonRefundableTaxesBySAPCustomerId(sapCustomerId);
decimal totalRefundableTaxAmount = (decimal)new GenericDAL().GetTotalMileStoneTypeInvoicedRefundableTaxesBySAPCustomerId(sapCustomerId);
decimal deductions = 0;
TECancellation to = new TECancellation();
to = context.TECancellations.Where(a => a.CancellationsID == CancellationId && a.IsDeleted == false).FirstOrDefault();
if (to != null && to.CancellationsID > 0)
{
deductions = (decimal)to.CancellationFee;
}
decimal totRefAmtCancelledAgreements = totalCollections - totalRefundableTaxAmount;
decimal totRefTaxAmount = totalTaxAmount - totalNonRefundableTaxAmount;
decimal totRefundableAmount = totRefAmtCancelledAgreements + totRefTaxAmount;
/*Getting OFFER Special Conditions Details Block Starts*/
List<SplConditiondetails> specialConditions = GetSpecialConditionsByOfferId(OfferId);
if (specialConditions != null && specialConditions.Count > 0)
{
for (int i = 0; i < specialConditions.Count; i++)
{
if (specialConditions[i].SPConditionType.Equals("Credit"))
{
specialConditions[i].SpecialConditionName = specialConditions[i].SpecialConditionName.Replace("format("{0:N0}",%ConditionPrice%)", specialConditions[i].Value.ToString());
}
}
}
string speciealtandc = string.Empty;
if (specialConditions != null && specialConditions.Count > 0)
{
int tandcSPCounter = 1;
speciealtandc += "<table style='width: 100%;border:none;margin-top:5px;font-size:12pt;' cellpadding='3'>";
foreach (var data in specialConditions)
{
String PlainText = Regex.Replace(@data.SpecialConditionName, "<(.|\\n)*?>", string.Empty);
speciealtandc += "<tr>";
speciealtandc += "<td style='vertical-align:top;'><p style='font-size:12pt;text-align:justify;'>6." + tandcSPCounter + " <br>" + PlainText + "</p></td>";
speciealtandc += "</tr>";
tandcSPCounter++;
}
speciealtandc += "</table>";
}
else { speciealtandc += "<p style='font-size:12pt;text-align:justify;'>N.A.</p>"; }
/* Getting OFFER Special Conditions Block Ends*/
htmlContent = htmlContent.Replace("##DOC_EFFECTIVEDATEDAY##", effectiveDateDay);
htmlContent = htmlContent.Replace("##DOC_EFFECTIVEDATEMONTH##", effectiveDateMonth);
htmlContent = htmlContent.Replace("##DOC_EFFECTIVEDATEYEAR##", effectiveDateYear);
htmlContent = htmlContent.Replace("##DOC_EFFECTIVEDATE##", formattedEffetiveDate);
htmlContent = htmlContent.Replace("##DOC_UNITNUMBER##", unitnumber);
htmlContent = htmlContent.Replace("##DOC_PROJECTNAME##", projectName);
htmlContent = htmlContent.Replace("##DOC_PROJECTCOLOUR##", projectColour);
htmlContent = htmlContent.Replace("##DOC_AFSDATE##", afsDate);
htmlContent = htmlContent.Replace("##DOC_CADATE##", caDate);
htmlContent = htmlContent.Replace("##DOC_ICSADATE##", icsDate);
htmlContent = htmlContent.Replace("##DOC_TSDATE##", tsDate);
htmlContent = htmlContent.Replace("##DOC_TOTALAMOUNT##", string.Format("{0:0.00}", totalCollections));
htmlContent = htmlContent.Replace("##DOC_TACANCELLEDAGREEMENTS##", string.Format("{0:0.00}", totAmtCancelledAgreements));
htmlContent = htmlContent.Replace("##DOC_TATAXES", string.Format("{0:0.00}", totalTaxAmount));
htmlContent = htmlContent.Replace("##DOC_DEDUCTIONS", string.Format("{0:0.00}", deductions));
htmlContent = htmlContent.Replace("##DOC_REFUNDAMOUNT##", string.Format("{0:0.00}", totRefundableAmount));
htmlContent = htmlContent.Replace("##DOC_TRACANCELLEDAGREEMENTS##", string.Format("{0:0.00}", totRefAmtCancelledAgreements));
htmlContent = htmlContent.Replace("##DOC_TRATAXES##", string.Format("{0:0.00}", totRefTaxAmount));
htmlContent = htmlContent.Replace("##DOC_SPECIALTANDC##", speciealtandc);
string emptyLine = "<br>";
if (specialConditions != null && specialConditions.Count > 0)
emptyLine = string.Empty;
htmlContent = htmlContent.Replace("##DOC_EMPTYLINE##", emptyLine);
ViewBag.htmltext = htmlContent;
return View();
}
public string GetHtmlStringByProjectTemplateId(int projectTemplateID)
{
string htmlcontent = "";
var projTempl = context.TE_Doc_Prj_Templates.Where(a => a.ProjectTemplateID == projectTemplateID).FirstOrDefault();
if (projTempl != null)
{
string fileName = "";
string filePath = string.Empty;
var headers = Request.Headers;
fileName = projTempl.TemplateContent;
string assemblyFile = string.Empty;
assemblyFile = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
int index = assemblyFile.LastIndexOf("/bin/");
string PortFolioDocTemplates = WebConfigurationManager.AppSettings["PortFolioDocTemplates"];
string downloadFilePath = PortFolioDocTemplates + "/" + fileName;
if (System.IO.File.Exists(downloadFilePath))
{
htmlcontent = System.IO.File.ReadAllText(downloadFilePath);
}
}
return htmlcontent;
}
public ActionResult SaveCustomerDeedOfCancellation(int OfferID, int LastModifiedBy, DateTime EffectiveDate, string DocumentName, int CancellationId)
{
ResultInfo info = new ResultInfo();
SuccessInfo sinfo = new SuccessInfo();
TE_Customer_Templates tdt = new TE_Customer_Templates();
try
{
if (OfferID > 0)
{
var offerDetails = (from ofr in context.TEOffers
where ofr.OfferID == OfferID
select new
{ ofr.ProjectID, ofr.SAPCustomerID }).FirstOrDefault();
if (offerDetails != null && offerDetails.ProjectID > 0)
{
var templateDetails = (from t1 in context.TE_Doc_Prj_Templates
join t2 in context.TE_Ref_Document_Type on t1.RefDocumentTypeID equals t2.RefDocumentTypeID
where t1.ProjectID == offerDetails.ProjectID && t1.Status.Equals("Approved") && t2.Code.Equals("DC")
&& t1.isDeleted == false && t2.IsDeleted == false
select t1).FirstOrDefault();
var custTempl = context.TE_Customer_Templates.Where(a => a.SAPCustomerID == offerDetails.SAPCustomerID && a.IsDeleted == false
&& a.DocumentType == templateDetails.RefDocumentTypeID).ToList();
if (custTempl.Count > 0)
{
tdt.Version = custTempl.Count + 1;
}
else
{
tdt.Version = 1;
}
tdt.CreatedBy = LastModifiedBy;
tdt.CreatedOn = DateTime.Now;
tdt.DocumentName = DocumentName;
tdt.DocumentType = (int)templateDetails.RefDocumentTypeID;
tdt.IsDeleted = false;
tdt.LastModifiedBy = LastModifiedBy;
tdt.LastModifiedOn = DateTime.Now;
tdt.OfferId = OfferID;
tdt.SAPCustomerID = offerDetails.SAPCustomerID;
tdt.Status = "Unsigned";
tdt.RefProjectTemplateID = templateDetails.ProjectTemplateID;
context.TE_Customer_Templates.Add(tdt);
context.SaveChanges();
string documentName = "DeedOfCancellation";
string dmsDocumentType = "UnsignedDeedOfCancellation";
string metaDataContentType = "DeedOfCancellation";
int dmsId = GenerateUnSignedTemplate(OfferID, tdt.CustomerTemplateID, tdt.LastModifiedBy, documentName,
metaDataContentType, dmsDocumentType, offerDetails.ProjectID, EffectiveDate, CancellationId);
if (dmsId > 0)
{
TE_Customer_Templates custTempObj =
context.TE_Customer_Templates.Where(a => a.CustomerTemplateID == tdt.CustomerTemplateID).FirstOrDefault();
custTempObj.UnSignedDMSID = dmsId;
context.Entry(custTempObj).CurrentValues.SetValues(custTempObj);
context.SaveChanges();
TEDeedOfCancellationDate docDate = new TEDeedOfCancellationDate();
docDate.EffectiveDate = EffectiveDate;
docDate.IsDeleted = false;
docDate.LastModifiedById = LastModifiedBy;
docDate.LastModifiedOn = DateTime.Now;
docDate.OfferId = OfferID;
docDate.SAPCustomerID = offerDetails.SAPCustomerID;
docDate.Status = "Unsigned";
docDate.TECustomerTemplatesRef = custTempObj.CustomerTemplateID;
context.TEDeedOfCancellationDates.Add(docDate);
context.SaveChanges();
sinfo.errorcode = 0;
sinfo.errormessage = "DeedOfCancellation Successfully Saved.";
sinfo.errorcode = 0;
info.info = sinfo;
}
else
{
TE_Customer_Templates custTempObj =
context.TE_Customer_Templates.Where(a => a.CustomerTemplateID == tdt.CustomerTemplateID).FirstOrDefault();
context.TE_Customer_Templates.Remove(custTempObj);
context.SaveChanges();
sinfo.errorcode = 1;
sinfo.errormessage = "Fail to Save DeedOfCancellation";
info.info = sinfo;
}
}
else
{
sinfo.errorcode = 1;
sinfo.errormessage = "Fail to Save DeedOfCancellation. Offer details not available.";
info.info = sinfo;
}
}
else
{
sinfo.errorcode = 1;
sinfo.errormessage = "Fail to Save DeedOfCancellation. Invalid OfferId received.";
info.info = sinfo;
}
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
info.info.errorcode = 1;
info.info.errormessage = "Fail to Save DeedOfCancellation : " + ex.ToString();
}
return Json(info, JsonRequestBehavior.AllowGet);
}
public int GenerateUnSignedTemplate(int offerId, int customerTemplateId, int? lastModifiedBy, string docName,
string metaDataContentType, string dmsDocumentType, int? ProjectID, DateTime EffectiveDate, int CancellationId)
{
TEDMSDocument dmsDoc = new TEDMSDocument();
ResultDocumentDetails res = new ResultDocumentDetails();
string result = string.Empty;
int dmsID;
try
{
string pdfOfferId = offerId.ToString();
FileUploadAndDownload fileUploadDownload = new FileUploadAndDownload();
string DMSUserId = WebConfigurationManager.AppSettings["DMSUserId"];
string DMSPassword = WebConfigurationManager.AppSettings["DMSPassword"];
string DMSSiteUrl = WebConfigurationManager.AppSettings["DMSSiteUrl"];
string DMSLibrary = WebConfigurationManager.AppSettings["DMSLibrary"];
string filePath = HostingEnvironment.MapPath("~/UploadDocs/");
DOCPDFResult resultPDF = GenerateTemplatePDF(offerId, ProjectID, EffectiveDate, CancellationId);
var base64String = resultPDF.Base64String;
result = filePath + resultPDF.PathToFile + ".pdf";
string DOCFIlePath = filePath + resultPDF.PathToFile + ".pdf";
string[] arr = new string[] { result };
var custDtl = (from offer in context.TEOffers
join lead in context.TELeads on offer.LeadID equals lead.LeadID into l
from tmplead in l.DefaultIfEmpty()
join proj in context.TEProjects on offer.ProjectID equals proj.ProjectID into p
from tmpprjct in p.DefaultIfEmpty()
join unit in context.TEUnits on offer.UnitID equals unit.UnitID into u
from tmpunit in u.DefaultIfEmpty()
join usr in context.UserProfiles on offer.LastModifiedBy_Id equals usr.UserId into ur
from tmpusr in ur.DefaultIfEmpty()
where (offer.OfferID == offerId && offer.IsDeleted == false)
select new
{
ContextId = offer.OfferID,
SAPCustomerID = offer.SAPCustomerID,
CustomerName = offer.OfferCustomerName,
ProjectName = tmpprjct.ProjectName,
UnitNumber = tmpunit.UnitNumber,
lastmodifiedby = offer.LastModifiedBy_Id,
LastModifiedOn = offer.LastModifiedOn,
UserName = tmpusr.UserName,
Email = tmpusr.email,
LeadEmail = tmplead.Email
}).FirstOrDefault();
if (!string.IsNullOrEmpty(base64String))
{
string siteUrl = DMSSiteUrl;
string libraryName = DMSLibrary;
string userName = DMSUserId;
string passWord = DMSPassword;
string documentName = offerId + "-" + docName + "-" + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
string documentImageType = "pdf";
string baseformat = base64String;
bool overwrite = true;
CustLibMetadataInfo metainfo = new CustLibMetadataInfo();
metainfo.ContentType = metaDataContentType;
metainfo.ProjectName = custDtl.ProjectName;
metainfo.Customer = custDtl.CustomerName;
metainfo.Unit = custDtl.UnitNumber;
metainfo.IsPhysicalDocumentStored = "No";
metainfo.SigningStatus = "Unsigned";
metainfo.CustomerDocumentCategory = "Home Purchase Relationships";
metainfo.DocumentDate = DateTime.Today.ToShortDateString();
FileUploadAndDownload upload = new FileUploadAndDownload();
res = upload.UploadLargeDocumentToSharePointServer(siteUrl, libraryName, DOCFIlePath, userName, passWord, overwrite, metainfo);
if (res != null)
{
if (res.status == true)
{
dmsDoc.DMSID = res.documentID;
dmsDoc.DMSURL = res.documentURL;
dmsDoc.DocumentName = res.tiltle;
dmsDoc.DocumentType = dmsDocumentType;
dmsDoc.KeyID = customerTemplateId;
dmsDoc.FileType = "pdf";
dmsDoc.SAPCustomerID = custDtl.SAPCustomerID;
dmsDoc.UploadedBy = lastModifiedBy;
dmsDoc.UploadedOn = DateTime.Now;
dmsDoc.DMSDocumentID = res.ID;
dmsDoc.DMSDocumentUniqueID = res.uniqueID;
dmsDoc.IsDeleted = false;
context.TEDMSDocuments.Add(dmsDoc);
context.SaveChanges();
if (dmsDoc.UniqueID > 0)
dmsID = dmsDoc.UniqueID;
else
dmsID = 0;
}
else
{
dmsID = 0;
}
}
else
{
dmsID = 0;
}
}
else
{
dmsID = 0;
}
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
dmsID = 0;
}
return dmsID;
}
public DOCPDFResult GenerateTemplatePDF(int id, int? projectTemplateId, DateTime EffectiveDate, int CancellationId)
{
DOCPDFResult resultPDF = new DOCPDFResult();
try
{
resultPDF = GetDOCByOfferID(id, projectTemplateId, EffectiveDate, CancellationId);
return resultPDF;
// return Json(infoDetailsObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
return resultPDF;
}
}
public DOCPDFResult GetDOCByOfferID(int OfferId, int? ProjectID, DateTime EffectiveDate, int CancellationId)
{
string finalResult = string.Empty, projtName = string.Empty;
string Page = "0"; var ToPage = "0";
DOCPDFResult pdfResultdefaultoffer = new DOCPDFResult();
string customSwitches = string.Format("--footer-html \"{0}\" " +
"--header-html \"{1}\" ",
Url.Action("DOCFooter", "CancellationPDF", new { ProjectName = projtName, PageNumber = Page, TotalPage = ToPage }, "http"),
Url.Action("DOCHeader", "CancellationPDF", new { }, "http"));
try
{
var actionResult = new Rotativa.ActionAsPdf("DeedOfCancellationPDFView", new
{
OfferId = OfferId,
ProjectID = ProjectID,
EffectiveDate = EffectiveDate,
CancellationId = CancellationId
})
{
FileName = "DeedOfCancellation.pdf",
PageSize = Size.A4,
//PageMargins = { Left = 10, Right = 10, Top = 10, Bottom = 10 },
PageMargins = { Left = 15, Right = 15, Top = 20, Bottom = 35 },
CustomSwitches = customSwitches
};
string filePath = HostingEnvironment.MapPath("~/UploadDocs/");
string filename = string.Empty;
filename = DateTime.Now.ToString();
filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+\/]", "");
var byteArray = actionResult.BuildPdf(ControllerContext);
var fileStream = new FileStream(filePath + "\\DeedOfCancellation-" + filename + ".pdf", FileMode.Create, FileAccess.Write);
fileStream.Write(byteArray, 0, byteArray.Length);
fileStream.Close();
string base64String = string.Empty;
base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length);
pdfResultdefaultoffer.PathToFile = "DeedOfCancellation-" + filename;
pdfResultdefaultoffer.Base64String = base64String;
return pdfResultdefaultoffer;
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
return pdfResultdefaultoffer;
}
}
public string DateOrdinal(int number)
{
var ones = number % 10;
var tens = Math.Floor(number / 10f) % 10;
if (tens == 1)
{
return number + "th";
}
switch (ones)
{
case 1: return number + "st";
case 2: return number + "nd";
case 3: return number + "rd";
default: return number + "th";
}
}
public List<SplConditiondetails> GetSpecialConditionsByOfferId(int offerId)
{
List<SplConditiondetails> splcndtnlist = new List<SplConditiondetails>();
splcndtnlist = (from ofrsplcndtn in context.TEOfferSpecialConditions
where (ofrsplcndtn.OfferID == offerId && ofrsplcndtn.IsDeleted == false)
select new SplConditiondetails
{
OfferSpecialID = ofrsplcndtn.OfferSpecialID,
OfferID = ofrsplcndtn.OfferID,
SpecialConditionName = ofrsplcndtn.SpecialConditionName,
SPConditionCategory = ofrsplcndtn.SPConditionCategory,
Value = ofrsplcndtn.Value,
SPConditionType = ofrsplcndtn.SPConditionType
}).ToList();
if (splcndtnlist != null && splcndtnlist.Count > 0)
return splcndtnlist;
else
return null;
}
public class COOutputs
{
public SuccessInfo info { get; set; }
public string Result { get; set; }
}
public class ResultInfo
{
public SuccessInfo info { get; set; }
}
public class DOCPDFResult
{
public string PathToFile { get; set; }
public string Base64String { get; set; }
public string URLPath { get; set; }
}
//public class SpecialConditions
//{
// public string OfferSpecialID { get; set; }
// public string OfferID { get; set; }
// public string OfferTitleName { get; set; }
// public string OfferCustomerName { get; set; }
// public string SpecialConditionName { get; set; }
// public string SPConditionCategory { get; set; }
// public string Value { get; set; }
// public string SPConditionType { get; set; }
//}
public class SplConditiondetails
{
public int OfferSpecialID { get; set; }
public int? OfferID { get; set; }
public string Value { get; set; }
public string OfferTitleName { get; set; }
public string OfferCustomerName { get; set; }
public string SpecialConditionName { get; set; }
public string SPConditionCategory { get; set; }
public string SPConditionType { get; set; }
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CIPMSBC;
using CIPMSBC.Eligibility;
public partial class Step2_JCC_3 : Page
{
private CamperApplication CamperAppl;
private General objGeneral;
private Boolean bPerformUpdate;
private RadioButton RadioButtonQ7Option1; // Rajesh
private RadioButton RadioButtonQ7Option2;
protected void Page_Init(object sender, EventArgs e)
{
if (ConfigurationManager.AppSettings["DisableOnSummaryPageFederations"].Split(',').Any(id => id == ((int)FederationEnum.MountainChai).ToString()))
Response.Redirect("~/NLIntermediate.aspx");
btnChkEligibility.Click += new EventHandler(btnChkEligibility_Click);
btnPrevious.Click += new EventHandler(btnPrevious_Click);
btnSaveandExit.Click += new EventHandler(btnSaveandExit_Click);
btnReturnAdmin.Click+=new EventHandler(btnReturnAdmin_Click);
CusValComments.ServerValidate += new ServerValidateEventHandler(CusValComments_ServerValidate);
CusValComments1.ServerValidate += new ServerValidateEventHandler(CusValComments_ServerValidate);
//ddlCampSession.SelectedIndexChanged += new EventHandler(ddlCampSession_SelectedIndexChanged);
}
void btnReturnAdmin_Click(object sender, EventArgs e)
{
string strRedirURL;
try
{
if (Page.IsValid)
{
strRedirURL = ConfigurationManager.AppSettings["AdminRedirURL"].ToString();
InsertCamperAnswers();
//Session["FJCID"] = null;
//Session["ZIPCODE"] = null;
Response.Redirect(strRedirURL);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
CamperAppl = new CamperApplication();
objGeneral = new General();
RadioButtonQ7Option1 = (RadioButton)RegControls1.FindControl("RadioButtonQ7Option1"); // <!-- Rajesh -->
RadioButtonQ7Option2 = (RadioButton)RegControls1.FindControl("RadioButtonQ7Option2");
imgbtnCalStartDt.Attributes.Add("onclick", "return ShowCalendar('" + txtStartDate.ClientID + "');");
imgbtnCalEndDt.Attributes.Add("onclick", "return ShowCalendar('" + txtEndDate.ClientID + "');");
if (Session["STATUS"] != null)
{
if (Convert.ToInt32(Session["STATUS"].ToString()) == Convert.ToInt32(StatusInfo.SystemInEligible))
{
lblEligibility.Visible = false;
}
else
{
lblEligibility.Visible = true;
}
}
if (!(Page.IsPostBack))
{
getCamps("0", Master.CampYear); //to get all the camps and fill in
//to get the FJCID which is stored in session
if (Session["FJCID"] != null)
{
hdnFJCIDStep2_3.Value = (string)Session["FJCID"];
getCamperAnswers();
//Session["FJCID"] = null;
}
}
RadioButtonQ7Option1.Attributes.Add("onclick", "JavaScript:popupCall(this,'noCampRegistrationMsg','',true);");
RadioButtonQ7Option2.Attributes.Add("onclick", "JavaScript:popupCall(this,'noCampRegistrationMsg','',true);");
//RadioButtonQ7Option3.Attributes.Add("onclick", "windowBnaiopen(this,'PnlQ8','PnlQ9','PnlQ10');");
//RadioButtonQ7Option4.Attributes.Add("onclick", "windowBnaiopen(this,'PnlQ8','PnlQ9','PnlQ10');");
//to enable / disable the panel states based on the radio button selected
SetPanelStates();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
//page unload
protected void Page_Unload(object sender, EventArgs e)
{
CamperAppl = null;
objGeneral = null;
}
void btnSaveandExit_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
string strRedirURL;
//strRedirURL = ConfigurationManager.AppSettings["SaveExitRedirURL"].ToString();
strRedirURL = Master.SaveandExitURL;
if (!objGeneral.IsApplicationReadOnly(hdnFJCIDStep2_3.Value, Master.CamperUserId))
{
InsertCamperAnswers();
}
//Session["FJCID"] = null;
//Session["ZIPCODE"] = null;
//Session["STATUS"] = null;
// Session.Abandon();
// Response.Redirect(strRedirURL);
if (Master.IsCamperUser == "Yes")
{
General oGen = new General();
if (oGen.IsApplicationSubmitted(Session["FJCID"].ToString()))
{
Response.Redirect(strRedirURL);
}
else
{
string strScript = "<script language=javascript>openThis(); window.location='" + strRedirURL + "';</script>";
if (!ClientScript.IsStartupScriptRegistered("clientScript"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "clientScript", strScript);
}
}
}
else
{
Response.Redirect(strRedirURL);
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
void btnPrevious_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
if (!objGeneral.IsApplicationReadOnly(hdnFJCIDStep2_3.Value, Master.CamperUserId))
{
InsertCamperAnswers();
}
Session["FJCID"] = hdnFJCIDStep2_3.Value;
Session["STATUS"] = null;
Response.Redirect("Step2_2.aspx");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void ValidateDataInput(object source, ServerValidateEventArgs args)
{
if (!RadioButtonQ7Option1.Checked && !RadioButtonQ7Option2.Checked)
{
args.IsValid = false;
CusVal.ErrorMessage = "Please answer the question: Have you registered for camp yet?";
return;
}
if (ddlCamp.SelectedValue == "0")
{
args.IsValid = false;
CusVal.ErrorMessage = "Please choose a camp.";
return;
}
if (txtCampSession.Text.Trim() == "")
{
args.IsValid = false;
CusVal.ErrorMessage = "Please enter a session name.";
return;
}
if (!ValidationChecker.CheckSessionDate(txtStartDate.Text.Trim()))
{
args.IsValid = false;
CusVal.ErrorMessage = "Error in start session date. The accepted format is mm/dd/yyyy.";
return;
}
if (!ValidationChecker.CheckSessionDate(txtEndDate.Text.Trim()))
{
args.IsValid = false;
CusVal.ErrorMessage = "Error in end session date. The accepted format is mm/dd/yyyy.";
return;
}
DateTime startDate = DateTime.Parse(txtStartDate.Text.Trim());
DateTime endDate = DateTime.Parse(txtEndDate.Text.Trim());
int result = DateTime.Compare(startDate, endDate);
if (result >= 0)
{
args.IsValid = false;
CusVal.ErrorMessage = "Error in session dates. The start date must be prior to the end date.";
return;
}
int currentYear = Convert.ToInt32(Session["CampYear"]);
if (!ValidationChecker.CheckSessionRange(startDate, endDate, currentYear))
{
args.IsValid = false;
CusVal.ErrorMessage = String.Format("Error in session dates. The session range must be between 05/01/{0} and 09/30/{1}", currentYear, currentYear);
return;
}
args.IsValid = true;
}
void btnChkEligibility_Click(object sender, EventArgs e)
{
int iStatus, iCampId;
string strModifiedBy, strFJCID, strComments;
EligibilityBase objEligibility = EligibilityFactory.GetEligibility(FederationEnum.MountainChai);
try
{
if (Page.IsValid)
{
bool isReadOnly = objGeneral.IsApplicationReadOnly(hdnFJCIDStep2_3.Value, Master.CamperUserId);
//Modified by id taken from the Master Id
strModifiedBy = Master.UserId;
if (!isReadOnly)
{
InsertCamperAnswers();
}
iCampId = Convert.ToInt32(ddlCamp.SelectedValue);
strFJCID = hdnFJCIDStep2_3.Value;
//comments used only by the Admin user
strComments = txtComments.Text.Trim();
if (strFJCID != "" && strModifiedBy != "")
{
if (isReadOnly)
{
DataSet dsApp = CamperAppl.getCamperApplication(strFJCID);
iStatus = Convert.ToInt32(dsApp.Tables[0].Rows[0]["Status"]);
}
else
{
//to update the camp value to the database (to be used for search functionality)
CamperAppl.updateCamp(strFJCID, iCampId, strComments, Convert.ToInt32(Master.CamperUserId));
//to check whether the camper is eligible
objEligibility.checkEligibility(strFJCID, out iStatus);
}
var checkStatus = Convert.ToInt32(Session["STATUS"]);
if (checkStatus == (int)StatusInfo.SystemInEligible)
iStatus = checkStatus;
else
Session["STATUS"] = iStatus;
if (iStatus == Convert.ToInt32(StatusInfo.SystemInEligible))
{
string strRedirURL;
if (Master.UserId != Master.CamperUserId) //then the user is admin
strRedirURL = ConfigurationManager.AppSettings["AdminRedirURL"];
else //the user is Camper
strRedirURL = "../ThankYou.aspx";
//to update the status to the database
if (!isReadOnly)
{
CamperAppl.submitCamperApplication(strFJCID, strComments, Convert.ToInt32(strModifiedBy), iStatus);
}
Response.Redirect(strRedirURL, false);
}
else //if he/she is eligible
{
Session["FJCID"] = hdnFJCIDStep2_3.Value;
Response.Redirect("../Step2_1.aspx");
}
}
//Session["ZIPCODE"] = null;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
objEligibility = null;
}
}
//to insert the Camper Answers
protected void InsertCamperAnswers()
{
string strFJCID, strComments;
int RowsAffected;
string strModifiedBy, strCamperAnswers;
strFJCID = hdnFJCIDStep2_3.Value;
//Modified by id taken from the common.master
strModifiedBy = Master.UserId;
//comments (used only by the Admin user)
strComments = txtComments.Text.Trim();
strCamperAnswers = ConstructCamperAnswers();
if (strFJCID != "" && strCamperAnswers != "" && strModifiedBy != "" && bPerformUpdate)
RowsAffected = CamperAppl.InsertCamperAnswers(strFJCID, strCamperAnswers, strModifiedBy, strComments);
}
//to get the camper answers from the database
void getCamperAnswers()
{
string strFJCID;
DataSet dsAnswers;
int iCount;
DataView dv;
RadioButton rb;
string strFilter;
strFJCID = hdnFJCIDStep2_3.Value;
if (! strFJCID.Equals(string.Empty))
{
dsAnswers = CamperAppl.getCamperAnswers(strFJCID, "9", "12", "N");
if (dsAnswers.Tables[0].Rows.Count > 0) //if there are records for the current FJCID
{
dv = dsAnswers.Tables[0].DefaultView;
//to display answers for the QuestionId from 1001 - 1004 in Other info page
for (int i = 9; i <= 12; i++)
{
strFilter = "QuestionId = '" + i.ToString() + "'";
iCount = dsAnswers.Tables[0].Rows.Count;
switch (i)
{
case 9: //assigning the answer for question 9
foreach (DataRow dr in dv.Table.Select(strFilter))
{
if (!dr["OptionID"].Equals(DBNull.Value))
{
rb = (RadioButton)RegControls1.FindControl("RadioButtonQ7Option" + dr["OptionID"].ToString());
rb.Checked = true;
}
}
break;
case 10:// assigning the answer for question 10
foreach (DataRow dr in dv.Table.Select(strFilter))
{
if (!dr["OptionID"].Equals(DBNull.Value))
{
switch (dr["OptionID"].ToString())
{
case "2": //for camp
ddlCamp.SelectedValue = dr["Answer"].Equals(DBNull.Value) ? "" : dr["Answer"].ToString();
//if (ddlCamp.SelectedIndex > 0)
//{
// ddlCampSession.DataSource = objGeneral.GetCampSessionsForCamp(Int32.Parse(ddlCamp.SelectedValue)).Tables[0];
// ddlCampSession.DataTextField = "Name";
// ddlCampSession.DataValueField = "ID";
// ddlCampSession.DataBind();
// ddlCampSession.Items.Insert(0, new ListItem("--Select--", "0"));
//}
break;
}
}
}
break;
case 11:// assigning the answer for question 11
foreach (DataRow dr in dv.Table.Select(strFilter))
{
if (!dr["Answer"].Equals(DBNull.Value))
{
//ddlCampSession.SelectedValue = dr["Answer"].ToString();
txtCampSession.Text = dr["Answer"].ToString();
}
}
break;
case 12: // assigning the answer for question 12
foreach (DataRow dr in dv.Table.Select(strFilter))
{
if (!dr["OptionID"].Equals(DBNull.Value))
{
switch (dr["OptionID"].ToString())
{
case "1": //for Start Date
//lblStartDate.Text = dr["Answer"].Equals(DBNull.Value) ? "" : dr["Answer"].ToString();
txtStartDate.Text = dr["Answer"].Equals(DBNull.Value) ? "" : dr["Answer"].ToString();
break;
case "2": //for End Date
//lblEndDate.Text = dr["Answer"].Equals(DBNull.Value) ? "" : dr["Answer"].ToString();
txtEndDate.Text = dr["Answer"].Equals(DBNull.Value) ? "" : dr["Answer"].ToString();
break;
}
}
}
break;
}
}
}
} //end if for null check of fjcid
}
//to enable or disable the question panels based on the radio button selected
protected void SetPanelStates()
{
if (RadioButtonQ7Option1.Checked == true)
{
PnlQ8.Enabled = false;
PnlQ8_2_1.Enabled = false;
PnlQ8_2_2.Enabled = false;
ddlCamp.SelectedIndex = 0;
PnlQ9.Enabled = false;
//ddlCampSession.SelectedIndex = 0;
txtCampSession.Text = "";
PnlQ10.Enabled = false;
txtStartDate.Text = "";
txtEndDate.Text = "";
//lblStartDate.Text = "";
//lblEndDate.Text = "";
}
else
{
PnlQ8.Enabled = true;
PnlQ8_2_1.Enabled = true;
PnlQ8_2_2.Enabled = true;
PnlQ9.Enabled = true;
PnlQ10.Enabled = true;
}
}
//to get the camps based on the state selected
//if state is not selected then all the camps are populated
private void getCamps(string StateId,string CampYear)
{
DataSet dsCamps;
//if (StateId == "0")
// {
dsCamps = objGeneral.get_AllCamps(CampYear);
//}
//else
//{
// dsCamps = objGeneral.get_CampsForState(StateId);
//}
ddlCamp.DataSource = dsCamps;
ddlCamp.DataTextField = "Camp";
ddlCamp.DataValueField = "ID";
ddlCamp.DataBind();
ddlCamp.Items.Insert(0, new ListItem("-- Select --", "0"));
}
private string ConstructCamperAnswers()
{
string strQuestionId = "";
string strTablevalues = "";
string strFSeparator;
string strQSeparator;
string strRadioOption;
string strCamp, strCampSession, strStartDate, strEndDate; //-1 for Camper (User id will be passed for Admin user)
//to get the Question separator from Web.config
strQSeparator = ConfigurationManager.AppSettings["QuestionSeparator"].ToString();
//to get the Field separator from Web.config
strFSeparator = ConfigurationManager.AppSettings["FieldSeparator"].ToString();
//for question 7
strRadioOption = Convert.ToString(RadioButtonQ7Option1.Checked ? "1" : RadioButtonQ7Option2.Checked ? "2" : "");
strCamp = ddlCamp.SelectedValue;
//strCampSession = ddlCampSession.SelectedValue;
//strStartDate = lblStartDate.Text.Trim();
//strEndDate = lblEndDate.Text.Trim();
strCampSession = txtCampSession.Text.Trim();
strStartDate = txtStartDate.Text.Trim();
strEndDate = txtEndDate.Text.Trim();
strQuestionId = hdnQ7Id.Value;
strTablevalues += strQuestionId + strFSeparator + strRadioOption + strFSeparator + strQSeparator;
//for question 8
strQuestionId = hdnQ8Id.Value;
//value - 1 for state and 2 for Camp
strTablevalues += strQuestionId + strFSeparator + "2" + strFSeparator + strCamp + strQSeparator;
//for question 9
strQuestionId = hdnQ9Id.Value;
strTablevalues += strQuestionId + strFSeparator + strFSeparator + strCampSession + strQSeparator;
//for question 10
strQuestionId = hdnQ10Id.Value;
//value - 1 for start date and 2 for end date
strTablevalues += strQuestionId + strFSeparator + "1" + strFSeparator + strStartDate + strQSeparator;
strTablevalues += strQuestionId + strFSeparator + "2" + strFSeparator + strEndDate + strQSeparator;
//to remove the extra character at the end of the string, if any
char[] chartoRemove = { Convert.ToChar(strQSeparator) };
strTablevalues = strTablevalues.TrimEnd(chartoRemove);
return strTablevalues;
}
void CusValComments_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
string strCamperAnswers, strUserId, strCamperUserId, strComments, strFJCID;
Boolean bArgsValid, bPerform;
strUserId = Master.UserId;
strCamperUserId = Master.CamperUserId;
strComments = txtComments.Text.Trim();
strFJCID = hdnFJCIDStep2_3.Value;
strCamperAnswers = ConstructCamperAnswers();
CamperAppl.CamperAnswersServerValidation(strCamperAnswers, strComments, strFJCID, strUserId, (Convert.ToInt32(Redirection_Logic.PageNames.Step2_3)).ToString(), strCamperUserId, out bArgsValid, out bPerform);
args.IsValid = bArgsValid;
bPerformUpdate = bPerform;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
//protected void ddlCampSession_SelectedIndexChanged(object sender, EventArgs e)
//{
// if (ddlCampSession.SelectedIndex > -1)
// {
// if (ddlCampSession.SelectedValue != "0")
// {
// DataSet dsSessionDetails = objGeneral.GetCampSessionDetail(Int32.Parse(ddlCampSession.SelectedValue));
// if (dsSessionDetails.Tables[0].Rows.Count > 0)
// {
// DataRow dr = dsSessionDetails.Tables[0].Rows[0];
// lblStartDate.Text = DateTime.Parse(dr["StartDate"].ToString()).ToShortDateString();
// lblEndDate.Text = DateTime.Parse(dr["EndDate"].ToString()).ToShortDateString();
// }
// }
// else
// {
// lblStartDate.Text = lblEndDate.Text = string.Empty;
// }
// }
//}
protected void imgbtnCalStartDt_Click(object sender, ImageClickEventArgs e)
{
int iDisplayYear = 0;
int iDisplayMonth = 6;//June
pnlCalStartDt.Style.Add("position", "absolute");
pnlCalStartDt.Style.Add("top", "420px");
pnlCalStartDt.Style.Add("left", "400px");
pnlCalStartDt.Visible = true;
if (DateTime.Now.Month > iDisplayMonth) //if it is July
iDisplayYear = DateTime.Now.Year + 1;
else
iDisplayYear = DateTime.Now.Year;
calStartDt.VisibleDate = new DateTime(iDisplayYear, iDisplayMonth, 1);
}
protected void imgbtnCalEndDt_Click(object sender, ImageClickEventArgs e)
{
pnlCalEndDt.Style.Add("position", "absolute");
pnlCalEndDt.Style.Add("top", "420px");
pnlCalEndDt.Style.Add("left", "610px");
pnlCalEndDt.Visible = true;
}
protected void calStartDt_SelectionChanged(object sender, EventArgs e)
{
txtStartDate.Text = calStartDt.SelectedDate.ToString("MM/dd/yyyy");
pnlCalStartDt.Visible = false;
}
protected void calEndDt_SelectionChanged(object sender, EventArgs e)
{
txtEndDate.Text = calEndDt.SelectedDate.ToString("MM/dd/yyyy");
pnlCalEndDt.Visible = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace IModelRepository.Models
{
public interface IUser
{
int Id { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
string Phone { get; set; }
string Position { get; set; }
IDepartment Department { get; set; }
ILogin Login { get; set; }
IEnumerable<IUserTest> Tests { get; set; }
string Role { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PhotographyEvent.Events
{
// This page shows previous events list
public partial class PreviousEvents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
BindData();
}
// selects data and show them on the table
private void BindData()
{
string select = @"select ROW_NUMBER() over (order by a.eventid) as RowNo, a.EventId, a.EventName,
(a.StartDate + ' ~ ' + a.EndDate) as EventDate, c.FirstName as WinnerName,
COUNT(b.UserId) as UserCount
from Events as A
left outer join EventUserPhotos as B on a.EventId = b.EventId
left outer join Users as c on a.Winner = c.UserId
where a.IsClosed = 1
group by a.EventId, a.EventName, a.StartDate, a.EndDate, c.FirstName";
using (System.Data.DataSet ds = Libs.DbHandler.getResultAsDataSet(select, null))
{
gvPrevEvents.DataSource = ds;
gvPrevEvents.DataBind();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
#region Comments
//Is there like a namespace class. I just want to be able to say namespace.GetExecutingNamespace() then get all types in namespace
//Implement class like this below
//var poodle = Dog.Create("Poodle");
//poodle.Bark();
#endregion
namespace JobSite.Examples.ReplaceConstructorWithFactoryMethod
{
public abstract class Dog
{
public Dog() { }
public abstract void Bark();
public static string Namespace => typeof(Dog).Namespace;
public static Dog Create(string dogType)
{
var dog = Assembly.GetExecutingAssembly().GetTypes().
First(t => t.IsClass && t.Namespace == Namespace && t.Name == dogType);
return (Dog)Activator.CreateInstance(dog);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using LoginNavigation.Models;
using Xamarin.Forms;
namespace LoginNavigation
{
public partial class NewPassword : ContentPage
{
public NewPassword()
{
InitializeComponent();
}
public async void ChangePassword(object sender, EventArgs e)
{
if (IsValid())
{
//Changes the user's password in the database
User user = RegisteredUsers.registeredUsers.Find(a => a.Email.ToLower() == VerifyCode.sentTo.ToLower());
if (user != null) {
user.Password = passwordEntry.Text;
App.IsUserLoggedIn = true;
Navigation.InsertPageBefore(new MainPage(), Navigation.NavigationStack.First());
await Navigation.PopToRootAsync();
}
//There should be no reason for the code to enter this else branch.
//However, it's here just in case.
else
{
messageLabel.Text = "Unknown error. Contact developers.";
}
}
}
//This function is used to determine if the user has entered a valid password
public bool IsValid()
{
//This function will only return true if none of the below if statements are true
bool valid = false;
if (passwordEntry.Text.Length < 8)
messageLabel.Text = "Password must be at least 8 characters long";
else if (passwordEntry.Text != passwordRepeatEntry.Text)
messageLabel.Text = "Passwords do not match";
else
valid = true;
return valid;
}
}
}
|
using AxisPosCore;
//using AxisPosCore.Common;
using AxisPosCore.Common;
using KartLib;
using KartObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using KartObjects.Entities.Documents;
namespace KartSystem.Presenters
{
public class POSJobPresenter
{
const string OutboundDir = "Receipts";
public List<PointOfSale> getOfflinePosList()
{
return Loader.DbLoad<PointOfSale>("isOnline<=0", 0) ?? new List<PointOfSale>();
}
public int doExchange(List<PointOfSale> OfflinePos,string ExportDir)
{
var v = Loader.DataContext;
EPDataConnection epc = new EPDataConnection(Settings.AxiEpServer, Settings.AxiEpPort, Settings.AxiEPCompress, Settings.AxiEPCrypt);
Loader.DataContext = epc;
EPconnectionHandler connectionHandler = new EPconnectionHandler();
Exception err = null;
int ReceiptCounter = 0;
try
{
foreach (var item in OfflinePos)
{
//Прием чеков
string ReceiptsDirName = ExportDir + @"\POS" + item.Number + @"\receipts";
if (Directory.Exists(ReceiptsDirName))
{
DirectoryInfo di = new DirectoryInfo(ReceiptsDirName);
foreach (var file in di.GetFiles("*.xml").OrderBy(q => q.FullName))
{
using (StreamReader reader = new StreamReader(file.FullName))
{
try
{
//чек
if (file.Name[0] == 'r')
{
XmlSerializer receiptSerializer = new XmlSerializer(typeof(Receipt));
Receipt r = (Receipt)receiptSerializer.Deserialize(reader);
connectionHandler.SaveReceipt(r);
}
//Zreport
if (file.Name[0] == 'z')
{
XmlSerializer receiptSerializer = new XmlSerializer(typeof(ZReport));
ZReport r = (ZReport)receiptSerializer.Deserialize(reader);
connectionHandler.SaveZReport(r);
}
}
catch (Exception)
{
}
finally
{
reader.Close();
File.Delete(file.FullName);
}
}
ReceiptCounter++;
}
}
//Формирование AxiposData
string PacketsDirName = ExportDir + @"\POS" + item.Number + @"\packets";
DataDictionary dict = DataDictionary.LoadDataFromStream(Loader.DataContext.GetDataDictionary(item.Number));
if (!Directory.Exists(PacketsDirName))
Directory.CreateDirectory(PacketsDirName);
TextWriter writer = new StreamWriter(PacketsDirName + @"\axisposdata.xml");
XmlSerializer serializer = new XmlSerializer(dict.GetType());
serializer.Serialize(writer, dict);
writer.Close();
}
}
catch (Exception e)
{
err = e;
}
finally
{
Loader.DataContext = v;
}
if (err != null)
throw err;
return ReceiptCounter;
}
}
}
|
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace Phenix.Windows.Helper
{
/// <summary>
/// EditControl助手
/// </summary>
public static class EditControlHelper
{
#region 方法
/// <summary>
/// 搜索第一个匹配的控件,并定位焦点
/// </summary>
/// <param name="controls">控件队列</param>
/// <returns>被定位焦点的编辑控件</returns>
public static Control FocusControl(IList<Control> controls)
{
if (controls == null)
return null;
foreach (Control item in controls)
if (item.Enabled && item.Visible && item.CanFocus)
{
item.Focus();
return item;
}
return null;
}
/// <summary>
/// 搜索第一个匹配的控件,并定位焦点
/// </summary>
/// <param name="container">控件容器</param>
/// <param name="source">数据源</param>
/// <returns>被定位焦点的编辑控件</returns>
public static Control FocusControl(Control container, BindingSource source)
{
return FocusControl(Phenix.Core.Windows.ControlHelper.FindEditControls(container, source));
}
/// <summary>
/// 搜索第一个匹配的可编辑控件,并定位焦点
/// </summary>
/// <param name="controls">控件队列</param>
/// <returns>被定位焦点的编辑控件</returns>
public static Control FocusEditableControl(IList<Control> controls)
{
if (controls == null)
return null;
foreach (Control item in controls)
if (item.Enabled && item.Visible && item.CanFocus)
{
//for Developer Express .NET
BaseEdit edit = item as BaseEdit;
if (edit != null && edit.Properties.ReadOnly)
continue;
item.Focus();
return item;
}
return null;
}
/// <summary>
/// 搜索第一个匹配的可编辑控件,并定位焦点
/// </summary>
/// <param name="container">控件容器</param>
/// <param name="source">数据源</param>
/// <returns>被定位焦点的编辑控件</returns>
public static Control FocusEditableControl(Control container, BindingSource source)
{
return FocusEditableControl(Phenix.Core.Windows.ControlHelper.FindEditControls(container, source));
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
namespace OrgMan.DomainObjects.Common
{
public class MemberInformationDomainModel
{
public Guid UID { get; set; }
public DateTime EntryDate { get; set; }
public DateTime ExitDate { get; set; }
public List<MemberInformationToMembershipDomainModel> MemberInformationToMemberships { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace CalculatorServices.WebAPI.DTOs
{
public class QueryResponse
{
public List<OperationResponse> Operations { get; set; }
}
public class OperationResponse
{
public string OperationType { get; set; } = "";
public string Calculation { get; set; } = "";
public DateTime DateTime { get; set; }
public int TrackId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EBS.Query;
using EBS.Query.DTO;
using EBS.Admin.Services;
using Newtonsoft.Json;
using EBS.Application;
using EBS.Infrastructure.File;
namespace EBS.Admin.Controllers
{
[Permission]
public class SaleOrderController : Controller
{
ISaleOrderQuery _saleOrderQuery;
IContextService _context;
ICategoryQuery _categoryQuery;
ISaleReportFacade _saleReportFacade;
IExcel _excelService;
public SaleOrderController(IContextService contextService, ISaleOrderQuery saleQuery, ICategoryQuery categoryQuery, ISaleReportFacade saleReportFacade, IExcel excelService)
{
_saleOrderQuery = saleQuery;
this._context = contextService;
this._categoryQuery = categoryQuery;
_saleReportFacade = saleReportFacade;
this._excelService = excelService;
}
//
// GET: /SaleOrder/
public ActionResult Index()
{
ViewBag.today = DateTime.Now.ToString("yyyy-MM-dd");
SetUserAuthention();
return View();
}
public ActionResult Details(int id)
{
var model = _saleOrderQuery.GetById(id);
return View(model);
}
/// <summary>
/// 收银流水
/// </summary>
/// <returns></returns>
public ActionResult SaleOrderItems()
{
SetUserAuthention();
return View();
}
public JsonResult QuerySaleOrderItems(Pager page, SearchSaleOrder condition)
{
if (string.IsNullOrEmpty(condition.StoreId) || condition.StoreId == "0") { condition.StoreId = _context.CurrentAccount.CanViewStores; }
var rows = _saleOrderQuery.QuerySaleOrderItems(page, condition);
return Json(new { success = true, data = rows, total = page.Total, sum = page.SumColumns });
}
/// <summary>
/// 营业额汇总核对
/// </summary>
/// <returns></returns>
public ActionResult SaleSummary()
{
ViewBag.today = DateTime.Now.ToString("yyyy-MM-dd");
SetUserAuthention();
return View();
}
public JsonResult QuerySaleSummary(Pager page, SearchSaleOrder condition)
{
if (string.IsNullOrEmpty(condition.StoreId) || condition.StoreId == "0") { condition.StoreId = _context.CurrentAccount.CanViewStores; }
var rows = _saleOrderQuery.QuerySaleSummary(page, condition);
return Json(new { success = true, data = rows, total = page.Total, sum = page.SumColumns });
}
/// <summary>
/// 收银防损核对
/// </summary>
/// <returns></returns>
public ActionResult SaleCheck()
{
ViewBag.today = DateTime.Now.ToString("yyyy-MM-dd");
SetUserAuthention();
return View();
}
public JsonResult QuerySaleCheck(Pager page, SearchSaleOrder condition)
{
if (string.IsNullOrEmpty(condition.StoreId) || condition.StoreId == "0") { condition.StoreId = _context.CurrentAccount.CanViewStores; }
var rows = _saleOrderQuery.QuerySaleCheck(page, condition);
return Json(new { success = true, data = rows, total = page.Total });
}
public ActionResult SaleSync()
{
ViewBag.saleDate = DateTime.Now.ToString("yyyy-MM-dd");
SetUserAuthention();
return View();
}
public JsonResult QuerySaleSync(Pager page, DateTime saleDate,string storeId)
{
if (string.IsNullOrEmpty(storeId) || storeId == "0") { storeId = _context.CurrentAccount.CanViewStores; }
var rows = _saleOrderQuery.QuerySaleSync(page, saleDate,storeId);
return Json(new { success = true, data = rows, total = page.Total });
}
public ActionResult SaleList(int id, int status, int orderType)
{
ViewBag.workScheduleId = id;
ViewBag.status = status;
ViewBag.orderType = orderType;
return View();
}
public JsonResult QuerySaleOrder(Pager page,int workScheduleId, int status, int orderType)
{
var rows = _saleOrderQuery.QuerySaleOrder(page,workScheduleId, status, orderType);
return Json(new { success = true, data = rows, total = page.Total });
}
private void SetUserAuthention()
{
ViewBag.View = _context.CurrentAccount.ShowSelectStore() ? "true" : "false";
ViewBag.StoreId = _context.CurrentAccount.StoreId;
ViewBag.StoreName = _context.CurrentAccount.StoreName;
}
/// <summary>
/// 单品销售汇总:门店员工用
/// </summary>
/// <returns></returns>
public ActionResult SingleProductSale()
{
SetUserAuthention();
ViewBag.Today = DateTime.Now.ToString("yyyy-MM-dd");
return View();
}
public JsonResult QuerySingleProductSale(Pager page, SearchSingleProductSale condition)
{
var rows = _saleOrderQuery.QuerySingleProductSale(page, condition);
return Json(new { success = true, data = rows, total = page.Total });
}
public ActionResult SaleReport()
{
SetUserAuthention();
ViewBag.Today = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
LoadCategory();
ViewBag.IsAdmin = _context.CurrentAccount.RoleId == 1 || _context.CurrentAccount.RoleId == 2? "true" : "false";
return View();
}
private void LoadCategory()
{
var treeNodes = _categoryQuery.GetCategoryTree();
var tree = JsonConvert.SerializeObject(treeNodes);
ViewBag.Tree = tree;
}
public JsonResult QuerySaleReport(Pager page, SearchSaleReport condition)
{
var rows = _saleOrderQuery.QuerySaleReport(page, condition);
return Json(new { success = true, data = rows, total = page.Total,sum = page.SumColumns });
}
public JsonResult GenerateSaleReport(DateTime beginDate, DateTime endDate)
{
_saleReportFacade.Create(beginDate, endDate);
return Json(new { success = true });
}
public JsonResult Proofread(DateTime beginDate, DateTime endDate)
{
return Json(new { success = true });
}
#region 门店销售实时报表
public ActionResult RealTimeSaleReport()
{
SetUserAuthention();
ViewBag.Today = DateTime.Now.ToString("yyyy-MM-dd");
return View();
}
public ActionResult QueryRealTimeSaleReport(Pager page, SearchSaleReport condition)
{
var rows = _saleOrderQuery.QueryRealTimeSaleReport(page, condition);
if (page.toExcel)
{
var data = _excelService.WriteToExcelStream(rows.ToList(), ExcelVersion.Above2007, false, true).ToArray();
var fileName = string.Format("实时销售报表_{0}.xlsx", DateTime.Now.ToString("yyyyMMdd"));
return File(data, "application/ms-excel", fileName);
}
return Json(new { success = true, data = rows, total = page.Total, sum = page.SumColumns });
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PlayerWinLose : MonoBehaviour
{
int enemiesPetrified = 0;
public Text textCounter;
public Text textWin;
public Text textPoints;
public CanvasGroup diedText;
public Text gameOverText;
public Text statueText;
//public int defaultPoint = 100;
//public int proximityBonus = 50;
private int currentScore = 0;
private int statuesSold = 0;
public int statuesToSell = 2;
private bool isSelling;
private List<GameObject> statuesSelected;
private EnemyGenerator enemyGen;
private StatueManager statueManager;
private Animator medusaAnimator;
private Pathfinding pathfinding;
public bool isDead;
private GameObject selector;
private int positionInList = 0;
private Map map;
// Use this for initialization
void Start()
{
map = GameObject.Find("Map").GetComponent<Map>();
enemyGen = GameObject.FindObjectOfType<EnemyGenerator>();
medusaAnimator = GameObject.Find("Medusa").GetComponent<Animator>();
pathfinding = GameObject.Find("Medusa").GetComponent<Pathfinding>();
statueManager = GameObject.Find("Map").GetComponent<StatueManager>();
isSelling = false;
statuesSelected = new List<GameObject>();
isDead = false;
}
void Update()
{
if (isSelling)
{
if (Input.GetKeyDown("left"))
{
if (positionInList != 0)
{
selector.transform.position = statueManager.statues[positionInList - 1].transform.position;
positionInList = positionInList - 1;
}
else
{
selector.transform.position = statueManager.statues[statueManager.statues.Count - 1].transform.position;
positionInList = statueManager.statues.Count - 1;
}
}
if (Input.GetKeyDown("right"))
{
if (positionInList != statueManager.statues.Count - 1)
{
selector.transform.position = statueManager.statues[positionInList + 1].transform.position;
positionInList = positionInList + 1;
}
else
{
selector.transform.position = statueManager.statues[0].transform.position;
positionInList = 0;
}
}
if (Input.GetKeyDown("space"))
{
if (statueManager.statues[positionInList].GetComponent<Statue>().pIsSold)
{
statueManager.statues[positionInList].GetComponent<Statue>().pIsSold = false;
statuesSold -= 1;
statueManager.statues[positionInList].transform.Find("SelectionIndicator").gameObject.SetActive(false);
statuesSelected.Remove(statueManager.statues[positionInList]);
}
else if (!statueManager.statues[positionInList].GetComponent<Statue>().pIsSold)
{
if (statuesSold < 2)
{
statueManager.statues[positionInList].GetComponent<Statue>().pIsSold = true;
statuesSold += 1;
statueManager.statues[positionInList].transform.Find("SelectionIndicator").gameObject.SetActive(true);
statuesSelected.Add(statueManager.statues[positionInList]);
}
}
}
if (Input.GetKeyDown("return"))
{
if (statuesSold == 2)
{
foreach(GameObject statue in statuesSelected)
{
//TODO: Implement auction screen
currentScore += statue.GetComponent<Statue>().pPointsWorth;
map.removeStatue(statue.transform.position);
Destroy(statue);
}
Destroy(selector);
statuesSelected.Clear();
statuesSold = 0;
isSelling = false;
updateScore();
foreach (GameObject statue in statueManager.statues)
{
statue.GetComponent<Statue>().HideStars();
}
GameObject.Find("Medusa").GetComponent<Animator>().speed = 1;
StartCoroutine(NextWave());
}
}
}
}
public void Die(bool starved)
{
//Show Death UI and wait for a moment
if (!isDead)
{
StartCoroutine(DieDie(starved));
}
}
IEnumerator DieDie(bool starved)
{
isDead = true;
GameObject.Find("Medusa").GetComponent<PlayerMovement>().enabled = false;
GameObject.Find("Medusa").GetComponent<BoxCollider2D>().enabled = false;
medusaAnimator.SetBool("FacingUp", false);
medusaAnimator.SetBool("FacingDown", false);
medusaAnimator.SetBool("FacingRight", false);
medusaAnimator.SetBool("FacingLeft", false);
medusaAnimator.SetBool("IsDead", true);
yield return new WaitForSeconds(0.1f);
medusaAnimator.SetBool("IsDead", false);
yield return new WaitForSeconds(2);
if (starved)
{
gameOverText.text = "YOU STARVED\nFinal Score: " + currentScore;
}
else
{
gameOverText.text = "YOU DIED\nFinal Score: " + currentScore;
}
diedText.alpha = 1;
yield return new WaitForSeconds(2);
SceneManager.LoadScene("Level0");
}
IEnumerator Win()
{
GameObject.Find("Medusa").GetComponent<PlayerMovement>().enabled = false;
GameObject.Find("Medusa").GetComponent<AudioSource>().mute = true;
GameObject.Find("Medusa").GetComponent<Animator>().speed = 0;
statueText.enabled = true;
yield return new WaitForSeconds(2);
statueText.enabled = false;
selector = Instantiate(Resources.Load<GameObject>("Selector"));
selector.transform.position = statueManager.statues[positionInList].transform.position;
foreach (GameObject statue in statueManager.statues)
{
statue.GetComponent<Statue>().DisplayStars();
}
isSelling = true;
}
public void Petrified()
{
enemiesPetrified++;
updateScore();
//Debug.Log(distance);
if (enemiesPetrified >= enemyGen.numOfEnemiesToSpawn)
{
//Initiate scoring screen
StartCoroutine(Win());
}
else if (pathfinding.IsBlockedIn())
{
Die(true);
}
}
void updateScore()
{
textCounter.text = "HEROES LEFT: " + (enemyGen.numOfEnemiesToSpawn - enemiesPetrified);
textPoints.text = "DRACHMAE: " + (currentScore);
}
public void newWave()
{
enemyGen.numOfEnemiesToSpawn += enemyGen.howManyToAdd;
enemyGen.SpawnEnemies(enemyGen.numOfEnemiesToSpawn);
textCounter.text = "HEROES LEFT: " + (enemyGen.numOfEnemiesToSpawn);
enemiesPetrified = 0;
}
IEnumerator NextWave()
{
textWin.enabled = true;
yield return new WaitForSeconds(2.5f);
GameObject.Find("Medusa").GetComponent<PlayerMovement>().enabled = true;
textWin.enabled = false;
newWave();
}
} |
using UnityEngine;
namespace Grandma.PF
{
public class ChargingState : TimedState
{
public ChargingData Data { get; set; }
//TODO: requires fully charged?
}
}
|
using UnityEngine.Audio;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class ClipsContainer : MonoBehaviour
{
private AudioSource clipOutput;
public Audio[] clips;
private void Start()
{
clipOutput = GetComponent<AudioSource>();
}
public void PutClip(int index)
{
if (index >= clips.Length)
{
return;
}
Audio a = clips[index];
clipOutput.clip = a.clip;
clipOutput.volume = a.volume;
clipOutput.Play();
}
}
|
using EntityFrameworkCore.BootKit;
using Newtonsoft.Json.Linq;
using Quickflow.Core;
using Quickflow.Core.Entities;
using Quickflow.Core.Interfacess;
using RazorLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quickflow.ActivityRepository
{
public class DataMappingActivity : EssentialActivity, IWorkflowActivity
{
private static RazorLightEngine engine;
public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity)
{
var template = activity.GetOptionValue("Template");
if (engine == null)
{
engine = new RazorLightEngineBuilder()
.UseFilesystemProject(AppDomain.CurrentDomain.GetData("ContentRootPath").ToString() + "\\App_Data")
.UseMemoryCachingProvider()
.Build();
}
var model = CleanJObject(activity);
string result = "";
var cacheResult = engine.TemplateCache.RetrieveTemplate(template);
if (cacheResult.Success)
{
result = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model);
}
else
{
result = await engine.CompileRenderAsync(template, model);
}
activity.Output.Data = JObject.Parse(result);
}
private JObject CleanJObject(ActivityInWorkflow activity)
{
// convert illegal variable name
var jObject = JObject.FromObject(activity.Input.Data);
jObject.Properties().ToList().ForEach(p => {
char letter = p.Name[0];
int i = letter - '0';
if (i >= 0 && i <= 9)
{
jObject.Add('n' + p.Name, p.Value);
jObject.Remove(p.Name);
}
});
return jObject;
}
}
}
|
namespace CatchTheThief
{
using System;
public class StartUp
{
public static void Main()
{
string integerType = Console.ReadLine();
long countIDs = long.Parse(Console.ReadLine());
long thiefID = long.MinValue;
for (int i = 0; i < countIDs; i++)
{
long numberID = long.Parse(Console.ReadLine());
if (integerType == "sbyte")
{
if ((sbyte.MinValue <= numberID) && (numberID <= sbyte.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
if (integerType == "int")
{
if ((int.MinValue <= numberID) && (numberID <= int.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
if (integerType == "long")
{
if ((long.MinValue <= numberID) && (numberID <= long.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
}
Console.WriteLine(thiefID);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.