text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using ReadyGamerOne.Global; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace ReadyGamerOne.Script { public class Dragger : MonoBehaviour,IBeginDragHandler,IEndDragHandler,IDragHandler { public LayerMask testLayer; public bool dragOnce = true; //设置没有到达目的地会返回初始位置 public bool backToStart = true; private enum DragType { GameObject, Ui } #region 回调事件 public event Action eventOnDrag; public event Action eventOnBeginDrag; public event Action eventOnEndDrag; public event Action<GameObject> eventOnDrop; public event Action<GameObject> eventOnEnter; public Func<GameObject,bool> IsTarget; public event Action<GameObject> eventOnEndWithTarget; public event Action eventOnEndWithoutTarget; #endregion #region Private #region Field //判断是否拖拽过 private bool dragged = false; //是否正在拖拽 private bool draging = false; private GameObject lastGameObject_ui; private GameObject lastGameObject_obj; //保存开始时候的父物体和本地坐标 private Vector3 beginLocalPosition; private Transform beforeParent; private DragType _dragType; #endregion #region Properties //移动的时候把被拖物体设为不接受UI事件,拖拽结束取消设置,这个列表记录了被修改的UI组件 private List<Graphic> gcs=new List<Graphic>(); private bool Raycastable { set { if (value) { //把修改过的值恢复 foreach (var gc in gcs) gc.raycastTarget = true; gcs.Clear(); } else { //把物体本身及子物体所有接收UI输入的组件都改成不接受 var graphics = GetComponents<Graphic>(); foreach (var gc in graphics) { if (gc.raycastTarget) { gc.raycastTarget = false; gcs.Add(gc); } } graphics = GetComponentsInChildren<Graphic>(); foreach (var gc in graphics) { if (gc.raycastTarget) { gc.raycastTarget = false; gcs.Add(gc); } } } } } #endregion #region Methods private void BackToStart() { transform.SetParent(beforeParent); transform.localPosition = beginLocalPosition; } #endregion #endregion #region MonoBehavior private void Start() { eventOnEnter += this.OnEnter; if (this.gameObject.layer == LayerMask.NameToLayer("UI")) { this._dragType = DragType.Ui; } else this._dragType = DragType.GameObject; } void Update() { //如果鼠标按下 if (_dragType==DragType.GameObject && Input.GetMouseButtonDown(0)) { //获取碰撞信息 var hit = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero,testLayer); //如果点在某个物体上 if (hit.Length>=1) { //如果点击的物体是自己,可以开始拖拽! if(hit[0].transform ==this.transform && !draging) ToStartDrag(); } } lastGameObject_obj = GetCurrentTarget(); if (draging) { if (_dragType==DragType.GameObject && Input.GetMouseButtonUp(0)) { ToEndDrag(); } else { print("OnDraging: " + name); #region 判断是否进入某些物体 if (lastGameObject_obj) eventOnEnter?.Invoke(lastGameObject_obj); #endregion var pos = transform.position; var mouseToPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition); this.transform.position = new Vector3(mouseToPoint.x, mouseToPoint.y, pos.z); eventOnDrag?.Invoke(); } } } #endregion private GameObject GetCurrentTarget() { var hit = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero,testLayer); if (_dragType == DragType.GameObject && hit.Length>=2) { return hit[1].transform.gameObject; } if (_dragType == DragType.Ui && hit.Length >= 1) { return hit[0].transform.gameObject; } return null; } private void ToStartDrag() { print("ToStartDrag: "+transform.name); //如果之调用一次,并且调用过了,直接返回 if (dragOnce && dragged) return; //记录开始的父物体和位置 beforeParent = transform.parent; beginLocalPosition = transform.localPosition; if (_dragType == DragType.Ui) { //在UI最上层 transform.SetParent(GlobalVar.G_Canvas.transform); ; transform.SetAsLastSibling(); //设置拖拽物体不接受UI事件 Raycastable = false; } //修改标记 draging = true; //回调 eventOnBeginDrag?.Invoke(); } private void ToEndDrag() { Debug.Log("ToEndDrag: "+transform.name); //如果只拖拽一次并且已经拖拽过了,就不在执行,直接返回 if (dragOnce && dragged) return; //设置标记 draging = false; if (_dragType == DragType.Ui) { //恢复刚刚做得修改 Raycastable = true; } //回调 eventOnEndDrag?.Invoke(); //是否到达目的地 GameObject testTarget; if(_dragType==DragType.Ui) testTarget = lastGameObject_ui??lastGameObject_obj; else { testTarget = GetCurrentTarget(); } if (IsTarget !=null && testTarget && IsTarget(testTarget)) { //已经到达,那就设置标记——已经拖拽过了 dragged = true; eventOnEndWithTarget?.Invoke(testTarget); } else if(backToStart) { //没到达目的地并且设置了不到达返回起点,那么调用此函数 BackToStart(); eventOnEndWithoutTarget?.Invoke(); } else { //就算没到达目的地,位置上不返回起点,父物体也还是要该回去 transform.SetParent(beforeParent); eventOnEndWithoutTarget?.Invoke(); } } private void OnEnter(GameObject target) { print("Dragging " + name + "时,经过:" + target.name); } #region drag_Interface public virtual void OnBeginDrag(PointerEventData eventData) { if (draging) return; ToStartDrag(); } public virtual void OnEndDrag(PointerEventData eventData) { ToEndDrag(); } #endregion public void OnDrag(PointerEventData eventData) { if (eventData == null) this.lastGameObject_ui = null; else { this.lastGameObject_ui = eventData.pointerEnter; } if(eventData!=null && eventData.pointerEnter && eventData.pointerEnter!=gameObject) eventOnEnter?.Invoke(eventData.pointerEnter); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScoreScreenBehavior : Game { private Text m_txtScore; private Text m_txtMaxScore; // Use this for initialization void Start () { Game.Localization.InitLocalization(); m_txtScore = GameObject.Find("txt_score_nr").GetComponent<Text>(); m_txtScore.text = Game.State.CurrentScore.ToString(); m_txtMaxScore = GameObject.Find("scorescreen_subtitle_2").GetComponent<Text>(); m_txtMaxScore.text += Game.State.MaxScore.ToString(); Game.State.ResetCurrentScore(); Game.Rules.ResetMoveTime(); } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using Dalamud.Plugin; using Penumbra.Util; namespace Penumbra.Models { public class Deduplicator { private readonly DirectoryInfo _baseDir; private readonly ModMeta _mod; private SHA256? _hasher; private readonly Dictionary< long, List< FileInfo > > _filesBySize = new(); private SHA256 Sha() { _hasher ??= SHA256.Create(); return _hasher; } public Deduplicator( DirectoryInfo baseDir, ModMeta mod ) { _baseDir = baseDir; _mod = mod; BuildDict(); } private void BuildDict() { foreach( var file in _baseDir.EnumerateFiles( "*.*", SearchOption.AllDirectories ) ) { var fileLength = file.Length; if( _filesBySize.TryGetValue( fileLength, out var files ) ) { files.Add( file ); } else { _filesBySize[ fileLength ] = new List< FileInfo >() { file }; } } } public void Run() { foreach( var pair in _filesBySize.Where( pair => pair.Value.Count >= 2 ) ) { if( pair.Value.Count == 2 ) { if( CompareFilesDirectly( pair.Value[ 0 ], pair.Value[ 1 ] ) ) { ReplaceFile( pair.Value[ 0 ], pair.Value[ 1 ] ); } } else { var deleted = Enumerable.Repeat( false, pair.Value.Count ).ToArray(); var hashes = pair.Value.Select( ComputeHash ).ToArray(); for( var i = 0; i < pair.Value.Count; ++i ) { if( deleted[ i ] ) { continue; } for( var j = i + 1; j < pair.Value.Count; ++j ) { if( deleted[ j ] || !CompareHashes( hashes[ i ], hashes[ j ] ) ) { continue; } ReplaceFile( pair.Value[ i ], pair.Value[ j ] ); deleted[ j ] = true; } } } } ClearEmptySubDirectories( _baseDir ); } private void ReplaceFile( FileInfo f1, FileInfo f2 ) { RelPath relName1 = new( f1, _baseDir ); RelPath relName2 = new( f2, _baseDir ); var inOption = false; foreach( var group in _mod.Groups.Select( g => g.Value.Options ) ) { foreach( var option in group ) { if( option.OptionFiles.TryGetValue( relName2, out var values ) ) { inOption = true; foreach( var value in values ) { option.AddFile( relName1, value ); } option.OptionFiles.Remove( relName2 ); } } } if( !inOption ) { const string duplicates = "Duplicates"; if( !_mod.Groups.ContainsKey( duplicates ) ) { OptionGroup info = new() { GroupName = duplicates, SelectionType = SelectType.Single, Options = new List< Option >() { new() { OptionName = "Required", OptionDesc = "", OptionFiles = new Dictionary< RelPath, HashSet< GamePath > >() } } }; _mod.Groups.Add( duplicates, info ); } _mod.Groups[ duplicates ].Options[ 0 ].AddFile( relName1, new GamePath( relName2 ) ); _mod.Groups[ duplicates ].Options[ 0 ].AddFile( relName1, new GamePath( relName1 ) ); } PluginLog.Information( $"File {relName1} and {relName2} are identical. Deleting the second." ); f2.Delete(); } public static bool CompareFilesDirectly( FileInfo f1, FileInfo f2 ) => File.ReadAllBytes( f1.FullName ).SequenceEqual( File.ReadAllBytes( f2.FullName ) ); public static bool CompareHashes( byte[] f1, byte[] f2 ) => StructuralComparisons.StructuralEqualityComparer.Equals( f1, f2 ); public byte[] ComputeHash( FileInfo f ) { var stream = File.OpenRead( f.FullName ); var ret = Sha().ComputeHash( stream ); stream.Dispose(); return ret; } // Does not delete the base directory itself even if it is completely empty at the end. public static void ClearEmptySubDirectories( DirectoryInfo baseDir ) { foreach( var subDir in baseDir.GetDirectories() ) { ClearEmptySubDirectories( subDir ); if( subDir.GetFiles().Length == 0 && subDir.GetDirectories().Length == 0 ) { subDir.Delete(); } } } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using HPMS.DB; using HPMS.Util; using Tool; namespace HPMS { public partial class frmLogin : Office2007Muti { private string _softVersion; public User User; public frmLogin(string softVersion) { _softVersion = softVersion; EnableGlass = false; this.Icon = base.Icon; InitializeComponent(); } private void frmLogin_Load(object sender, EventArgs e) { } private void btnLogin_Click(object sender, EventArgs e) { //this.Close(); string userName = txtUser.Text; UserDao.DbMode = chkDBMode.Checked; List<User> userList = UserDao.Find(userName); if (userList.Count == 1) { User = userList[0]; if (User.Psw == txtPsw.Text) { if (User.UserStatus != RecordStatus.Enable) { Ui.MessageBoxMuti("账户已停用或被删除",this); } else { if (User.IsSuper) { Gloabal.GUser = User; this.Close(); } } } else { Ui.MessageBoxMuti("用户名或密码错误",this); } } else { Ui.MessageBoxMuti("用户名或密码错误"); } } private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } } }
using System.Collections.Generic; using Xamarin.Forms; namespace MKGo { public partial class MasterPage : ContentPage { public ListView ListView { get { return listView; } } public MasterPage() { InitializeComponent(); var masterPageItems = new List<MasterPageItem>(); masterPageItems.Add(new MasterPageItem { Title = "Karte", IconSource = "ic_map.png", TargetType = typeof(MapPage) }); masterPageItems.Add(new MasterPageItem { Title = "Meine Sammlung", IconSource = "ic_collections.png", TargetType = typeof(CollectionPage) }); masterPageItems.Add(new MasterPageItem { Title = "Impressum", IconSource = "ic_info.png", TargetType = typeof(AboutPage) }); listView.ItemsSource = masterPageItems; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mine : MonoBehaviour { public bool mobile;//set to true if the mine is mobile public GameObject explosion;//the explosion object/effect // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } //this function checks what object has collided with the mine and calls the explode function if needed //called when anything collides with this object //input is the object that has collided with this object private void OnTriggerEnter(Collider other) { if (!mobile) //if not mobile { if (other.transform.tag == "Enemy")//if hit by an enemy explode { explode(); } if (other.transform.tag == "Player")//if hit by a player explode { explode(); } } else//if mobile { if (other.transform.tag == "Player")//if hit by a player explode { explode(); } } } //function to create explosion and destroy this object public void explode() { Instantiate(explosion, transform.position, transform.rotation);//create the explosion Destroy(gameObject);//delete the mine } }
using Alword.Algoexpert.Tier1; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Alword.Algoexpert.Tests._1 { public class LongestPeakTest { [Fact] public void TestPeak() { var array = new int[] { 1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3 }; int expected = 6; Assert.Equal(expected, LongestPeakTask.LongestPeak(array)); } [Fact] public void EmptyTest() { var array = new int[] { }; int expected = 0; Assert.Equal(expected, LongestPeakTask.LongestPeak(array)); } [Fact] public void InlineTest() { var array = new int[] { 1, 3, 2 }; int expected = 3; Assert.Equal(expected, LongestPeakTask.LongestPeak(array)); } } }
using System; using System.Collections; namespace Aut.Lab.Lab12 { public class Basetwo { private string inputnum = ""; public Basetwo(string num) { inputnum = num; } private bool isBase2Valid(string baseTwoStr) { char[] arrch = baseTwoStr.ToCharArray(); for(int i = 0;i<arrch.Length;i++) { if(arrch[i] != '0' && arrch[i] != '1') { return false; } } return true; } public void ChangeBaseTwo() { char[] arrchar = inputnum.ToCharArray(); if (!isBase2Valid(inputnum)) { Console.WriteLine("Error !!"); return; } Int64 sum = 0; int len = arrchar.Length; for (int i = 1; i <= len; i++) { char ch = arrchar[i-1]; int x = Convert.ToInt32(ch.ToString()); sum = sum + (Int64) Math.Pow(2, len-i) * x; } Console.WriteLine("Output = {0}", sum); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestHelper { class RefOutTest { static void Print(string[] args) { a aa = new a(); Change1(aa); // val change Change2(aa); // val not change Change3(ref aa); // val change Change4(ref aa); // val change System.Console.ReadLine(); } public static void Change1(a aaa) { aaa.val = 10; } public static void Change2(a aa) { a aaaaa = new a(); aaaaa.val = 20; aa = aaaaa; } public static void Change3(ref a aaa) { aaa.val = 30; } public static void Change4(ref a aaa) { a aaaaa = new a(); aaaaa.val = 40; aaa = aaaaa; } } class a { public int val; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LockerAnimationScript : MonoBehaviour { public Animator animator; public AudioSource lockerSound; // Start is called before the first frame update void OnTriggerEnter(Collider other) { StartCoroutine(Text()); IEnumerator Text() { animator.SetBool("Open", true); Debug.Log("Open Door"); yield return new WaitForSeconds(0.5f); animator.SetBool("Open", false); lockerSound.Play(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using View.Game; using View.Interfaces; using View.Rendering; namespace View.Controllers { /// <summary> /// Контроллер игры /// </summary> public class GameController : IGame { private Player[] bots; private Player player; private Deck deck; private Thread[] botThreads; private IForm view; private object keyUpdate; private Render render; private Random rand; public GameController(IForm view, int wh, int ht) { rand = new Random(); this.view = view; render = new Render(wh, ht); view.UpdatePic(render.GetBackground()); player = new Player(); player.TypePlayer = TypePlayer.Player; player.Name = "Player"; InitBots(); botThreads = new Thread[3]; keyUpdate = new object(); } /// <summary> /// Создание ботов /// </summary> private void InitBots() { bots = new Player[3]; string[] names = new string[] { "Bob", "John", "Nancey", "Nicole", "Bettany", "Mark", "Justin", "Karl", "Andrew", "Rita", "Tayler" }; for (int i = 0; i < bots.Length; i++) { bots[i] = new Player(); bots[i].Name = names[rand.Next(0, names.Length)]; } bots[0].Name = "Казино"; bots[0].TypePlayer = TypePlayer.Dealer; } /// <summary> /// Новая игра /// </summary> public void NewGame() { deck = new Deck(); Turn(); } /// <summary> /// Имитация ставок ботов /// </summary> private void BetBots() { for (int i = 0; i < bots.Length; i++) { bots[i].Bet = rand.Next(10, bots[i].Money / 2); } } /// <summary> /// Очистка рук всех игроков /// </summary> /// <param name="bots"> Массив ботов </param> /// <param name="pl"> Класс игрока-человека </param> private void ClearHand(Player[] bots, Player pl) { for (int i = 0; i < bots.Length; i++) { bots[i].Hand = new Hand(); } pl.Hand = new Hand(); } /// <summary> /// Начало новой партии /// </summary> private void Turn() { ClearHand(bots, player); player.Bet = view.GetBet(player.Money); BetBots(); //UpdateThreads(); DefaultCards(bots, player); view.UpdatePoints(player.Hand.Point); StartBots(); } /// <summary> /// Запуск ботов /// </summary> private void StartBots() { for (int i = 0; i < botThreads.Length; i++) { int j = i; //magic botThreads[i] = new Thread(delegate() { BotTurn(bots[j]); }); botThreads[i].IsBackground = true; botThreads[i].Start(); } } /// <summary> /// Раздача карт в начале партии /// </summary> /// <param name="bots" >Массив ботов </param> /// <param name="pl"> Класс игрока-человека </param> private void DefaultCards(Player[] bots, Player pl) { view.EnabledButton = false; for (int i = 0; i < bots.Length; i++) { GiveCard(bots[i]); GiveCard(bots[i]); } GiveCard(pl); GiveCard(pl); view.EnabledButton = true; } /// <summary> /// Имитация логики ботов /// </summary> /// <param name="bot"></param> private void BotTurn(Player bot) { while (bot.Hand.Point < 17) { Thread.Sleep(rand.Next(500, 2500)); // бот думает GiveCard(bot); } } /// <summary> /// Выдача карты игроку /// </summary> /// <param name="pl">Класс игрока</param> private void GiveCard(Player pl) { pl.Hand.AddCard(deck.TakeCard()); Thread.Sleep(100); // задержка выдачи карт lock (keyUpdate) { view.UpdatePic(render.Draw(bots, player)); } } /// <summary> /// Ожидание завершения потоков ботов /// </summary> private void JoinBots() { for (int i = 0; i < botThreads.Length; i++) { if (botThreads[i].IsAlive) { botThreads[i].Join(); Thread.Sleep(500); } } } /// <summary> /// Конец партии, определение победителя /// </summary> private void EndOfGame() { view.UpdatePic(render.ShowCards(bots, player)); int indexWinner = WinnerOfBots(); if (player.Hand.Point <= 21 && player.Hand.Point > bots[indexWinner].Hand.Point) { player.Money += player.Bet; view.Winner(player.Name); PickUpBetBots(null); } else { player.Money -= player.Bet; view.Winner(bots[indexWinner].Name); PickUpBetBots(indexWinner); if (player.Money == 0) { view.UpdateMoney(0); view.GameOver(); return; } } //Новая партия deck.RandomDeck(); view.UpdateMoney(player.Money); Turn(); } /// <summary> /// Вычисление средcтв ботов /// </summary> /// <param name="winnerBot">индекс бота-победителя или при отсутствии победителя - null </param> private void PickUpBetBots(int? winnerBot) { for (int i = 0; i < bots.Length; i++) { bots[i].Money -= bots[i].Bet; } if (winnerBot != null) { int i = (int)winnerBot; bots[i].Money += 2 * bots[i].Bet; } } /// <summary> /// Определение победителя среди ботов /// </summary> /// <returns></returns> private int WinnerOfBots() { int max = 0; int index = 0; for (int i = 0; i < bots.Length; i++) { if (bots[i].Hand.Point <= 21 && bots[i].Hand.Point > max) { max = bots[i].Hand.Point; index = i; } } return index; } public void TakeCard() { GiveCard(player); view.UpdatePoints(player.Hand.Point); if (player.Hand.Point > 21) { Enough(); } } public void Enough() { view.EnabledButton = false; JoinBots(); EndOfGame(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SpiderCore { public interface IScheduler { /// <summary> /// 推送 /// </summary> bool Push(Request request); /// <summary> /// 弹出 /// </summary> Request Pop(); /// <summary> /// 切换网站 /// </summary> void Switch(); } }
using System.Collections.Generic; namespace CheckMySymptoms.Forms.View.Common { public class MultiSelectTemplateView { public string TemplateName { get; set; } public string PlaceHolderText { get; set; } public string TextField { get; set; } public string ValueField { get; set; } public DataRequestStateView State { get; set; } public RequestDetailsView RequestDetails { get; set; } public string ModelType { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; static class PathStorage { //Create a static class PathStorage with static methods to save and load paths from a text file. //Use a file format of your choice. public static void SavePath(Path path) { Console.WriteLine("Saving current path ..."); StreamWriter writer = new StreamWriter("save.txt"); List<Point3D> list = path.CurrentPath; using (writer) { for (int i = 0; i < list.Count; i++) { writer.Write(list[i].ToString() + ' '); } } Console.Write("Do you want to view the save file (y/n): "); char answer = char.Parse(Console.ReadLine()); if (answer == 'y') { Process.Start("save.txt"); } } public static Path LoadPath(string filePath) { //We asume correct input - not a phone number or something Console.WriteLine("Loading specified path ..."); StreamReader reader = new StreamReader(filePath); //Adding sperate points to a list List<Point3D> result = new List<Point3D>(); using (reader) { string coordiantes = reader.ReadToEnd(); //Since in the save method we have one extra ' ' at the end //here we need to use StringSplitOptions.RemoveEmptyEntries string[] points = coordiantes.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries); foreach (var point in points) { result.Add(new Point3D(point)); } } if (result.Count < 2) { throw new ArgumentException("This is not a valid path - you need at least 2 points"); } //Adding points to the final Path Path path = new Path(result[0], result[1]); for (int i = 2; i < result.Count; i++) { path.Add(result[i]); } return path; } }
using System; using System.Collections.Generic; namespace TeamElem.Security.Cryptography { [Serializable] public abstract class PublicKey : IEquatable<PublicKey> { public abstract bool Equals(PublicKey other); public override bool Equals(object obj) => Equals(obj as PublicKey); public override abstract int GetHashCode(); public static bool operator ==(PublicKey x, PublicKey y) => x?.Equals(y) ?? ((object)y == null); public static bool operator !=(PublicKey x, PublicKey y) => !(x == y); } }
namespace syscrawl.Game.Models.Levels { public enum SceneNodeType { Current, Previous, Active, FurtherAhead } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet; using System.Management.Automation; namespace NtObjectManager.Cmdlets.Object { /// <summary> /// <para type="synopsis">Deletes a registry key.</para> /// <para type="description">This cmdlet deletes a registry key.</para> /// </summary> /// <example> /// <code>Remove-NtKey \Registry\Machine\SOFTWARE\ABC</code> /// <para>Deletes the \Registry\Machine\SOFTWARE\ABC key.</para> /// </example> /// <example> /// <code>Remove-NtKey \Registry\Machine\SOFTWARE\ABC -OpenLink</code> /// <para>Deletes the \Registry\Machine\SOFTWARE\ABC symbolic link key.</para> /// </example> /// <example> /// <code>Remove-NtKey -Path ABC -Root $key</code> /// <para>Deletes the key ABC under root $key.</para> /// </example> /// <example> /// <code>Remove-NtKey $key</code> /// <para>Deletes the existing key $key.</para> /// </example> [Cmdlet(VerbsCommon.Remove, "NtKey")] public sealed class RemoveKeyCmdlet : PSCmdlet { /// <summary> /// <para type="description">The NT object manager path for the key to delete.</para> /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = "FromPath")] public string Path { get; set; } /// <summary> /// <para type="description">The root object for the key to delete. Ignored if a Win32Path.</para> /// </summary> [Parameter(ParameterSetName = "FromPath")] public NtObject Root { get; set; } /// <summary> /// <para type="description">Specify the path is a Win32 path.</para> /// </summary> [Parameter(ParameterSetName = "FromPath")] public SwitchParameter Win32Path { get; set; } /// <summary> /// <para type="description">Specify a transaction to delete the key under.</para> /// </summary> [Parameter(ParameterSetName = "FromPath")] public INtTransaction Transaction { get; set; } /// <summary> /// <para type="description">Specify that you want to remove a symbolic link.</para> /// </summary> [Parameter(ParameterSetName = "FromPath")] public SwitchParameter OpenLink { get; set; } /// <summary> /// <para type="description">An existing key to delete.</para> /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = "FromKey")] public NtKey Key { get; set; } private ObjectAttributes GetObjectAttributes() { AttributeFlags flags = AttributeFlags.CaseInsensitive; if (OpenLink) { flags |= AttributeFlags.OpenLink; } if (Win32Path) { return new ObjectAttributes(NtKeyUtils.Win32KeyNameToNt(Path), flags); } else { return new ObjectAttributes(Path, flags, Root); } } /// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case "FromKey": Key.Delete(); break; case "FromPath": using (var obja = GetObjectAttributes()) { using (var key = NtKey.Open(obja, KeyAccessRights.Delete, KeyCreateOptions.NonVolatile, Transaction)) { key.Delete(); } } break; } } } }
using Logs.Data.Contracts; using Logs.Factories; using Logs.Models; using Logs.Services.Contracts; using Moq; using NUnit.Framework; using System; namespace Logs.Services.Tests.MeasurementServiceTests { [TestFixture] public class ConstructorTests { [Test] public void TestConstructor_PassEverything_ShouldInitializeCorrectly() { // Arrange var mockedRepository = new Mock<IRepository<Measurement>>(); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var mockedMeasurementFactory = new Mock<IMeasurementFactory>(); // Act var service = new MeasurementService(mockedRepository.Object, mockedUnitOfWork.Object, mockedMeasurementFactory.Object); // Assert Assert.IsNotNull(service); } [Test] public void TestConstructor_PassRepositoryNull_ShouldThrowArgumentNullException() { // Arrange var mockedUnitOfWork = new Mock<IUnitOfWork>(); var mockedMeasurementFactory = new Mock<IMeasurementFactory>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementService(null, mockedUnitOfWork.Object, mockedMeasurementFactory.Object) ); } [Test] public void TestConstructor_PassUnitOfWorkNull_ShouldThrowArgumentNullException() { // Arrange var mockedRepository = new Mock<IRepository<Measurement>>(); var mockedMeasurementFactory = new Mock<IMeasurementFactory>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementService(mockedRepository.Object, null, mockedMeasurementFactory.Object) ); } [Test] public void TestConstructor_PassMeasurementFactoryNull_ShouldThrowArgumentNullException() { // Arrange var mockedRepository = new Mock<IRepository<Measurement>>(); var mockedUnitOfWork = new Mock<IUnitOfWork>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementService(mockedRepository.Object, mockedUnitOfWork.Object, null) ); } } }
using UnityEngine; using System.Collections; public class RoomProperties { // photon network provides sql match making. Using registers C0 .. C10 you can set your own properties public const string GameMode = "C0"; public const string Map = "C1"; public const string Score = "Sc"; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawner : MonoBehaviour { public static GameObject[] enemySpawnLocations; public GameObject[] enemies; public static int enemyCount; public int maxEnemyCount = 2; // Use this for initialization void Start () { enemySpawnLocations = GameObject.FindGameObjectsWithTag("EnemySpawn"); enemyCount = GameObject.FindGameObjectsWithTag("Enemy").Length; InvokeRepeating("SpawnEnemy", 5.0f, 6.0f); } void SpawnEnemy() { //If total enemy count is under the max count for the level spawn a new enemy if(enemyCount < maxEnemyCount) { GameObject spawningEnemy = enemies[Random.Range(0, enemies.Length)]; Vector3 spawningLocation = enemySpawnLocations[Random.Range(0, enemySpawnLocations.Length)].transform.position; //Check if object is already present at the randomly selected spawn location, if so return without spawning if (Physics2D.OverlapCircle((Vector2)spawningLocation, 0.5f) != null) { return; } //Spawning an enemy Instantiate(spawningEnemy, spawningLocation, Quaternion.identity); enemyCount += 1; } } }
using System; using FirstProject.Intefaces; namespace FirstProject.TiposDeConta { public abstract class Conta : IImposto { public static int QuantidadeDeContas; public double Saldo { get; protected set; } public string NomeProprietario { get; set; } public DateTime DataAbertura { get; set; } public int numero { get; set; } public Conta(){ QuantidadeDeContas++; } public Conta(double saldo, string nomeProprietario, DateTime dataAbertura){ this.Saldo = saldo; this.NomeProprietario = nomeProprietario; this.DataAbertura = dataAbertura; QuantidadeDeContas++; } public abstract void saque(double valor); public abstract void deposito(double valor); public abstract double calculaImposto(); public static int ProximaConta(){ return QuantidadeDeContas + 1; } public override string ToString() { return String.Format("{0}:[Numero da Conta = {1} | Titular = {2} | Data de Abertura = {3} | Saldo = {4}]", this.GetType().Name, this.numero, this.NomeProprietario, this.DataAbertura, this.Saldo); } public override bool Equals(object obj) { if(this.GetType() != obj.GetType() || obj == null) { return false; } Conta other = (Conta) obj; return this.DataAbertura.Equals(other.DataAbertura) && this.NomeProprietario.Equals(other.NomeProprietario) && this.numero.Equals(other.numero) && this.Saldo.Equals((other.Saldo)); } public override int GetHashCode() { var hashCode = 1; hashCode *= (this.numero == 0)? 31 : this.numero.GetHashCode() * 31; hashCode *= (this.DataAbertura == null)? 31 : this.DataAbertura.GetHashCode() * 31; hashCode *= (this.NomeProprietario == null)? 31 : this.DataAbertura.GetHashCode() * 31; hashCode *= (this.Saldo == 0)? 31 : this.Saldo.GetHashCode() * 31; return hashCode; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using TMPro; public class FinishLineController : MonoBehaviour { [SerializeField] private InputField input; [SerializeField] private Scene sceneToLoad; [SerializeField] private TextMeshProUGUI timeText; private string finalTime; private void Awake() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; //Setup InputField Restrictions //input = GameObject.Find("InputField").GetComponent<InputField>(); input.characterLimit = 3; input.ActivateInputField(); finalTime = PlayerPrefs.GetString("PlayerTimeString"); timeText.text = finalTime; } public void GetInput(string name) { name = input.text; name = name.ToUpper(); PlayerPrefs.SetString("PlayerName", name); Debug.Log("Saved Name: " + PlayerPrefs.GetString("PlayerName")); } public void LoadScene() { Debug.Log("Opening Scene: " + sceneToLoad.name); SceneManager.LoadScene(sceneToLoad.handle); PlayerPrefs.SetInt("AddEntry", 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClassLibrary1 { public class Class1 { private static string getPluginName() { return "ToLower"; } public static void ToLower(RichTextBox rich) { if (String.IsNullOrEmpty(rich.SelectedText)) { rich.Text = rich.Text.ToLower(); } else { rich.SelectedText = rich.SelectedText.ToLower(); } } } }
using ICSharpCode.SharpZipLib.Zip; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Windows.Forms; namespace Back_Pain_Test { public partial class BackPainFrm : Form { Dictionary<string, string> rs2073711_AA_pos = null; const int RESULT_PROB_TRUE = 2; const int RESULT_TRUE = 1; const int RESULT_FALSE = 0; const int RESULT_NA = -1; public BackPainFrm() { InitializeComponent(); } private void BackPainFrm_Load(object sender, EventArgs e) { rs2073711_AA_pos = new Dictionary<string, string>(); rs2073711_AA_pos.Add("rs28666660", "G"); rs2073711_AA_pos.Add("rs7175765", "G"); rs2073711_AA_pos.Add("rs563082", "T"); rs2073711_AA_pos.Add("rs514319", "A"); rs2073711_AA_pos.Add("rs12593770", "G"); rs2073711_AA_pos.Add("rs16953514", "T"); rs2073711_AA_pos.Add("rs640005", "A"); rs2073711_AA_pos.Add("rs16948024", "G"); rs2073711_AA_pos.Add("rs673931", "A"); rs2073711_AA_pos.Add("rs11071799", "C"); rs2073711_AA_pos.Add("rs2733386", "GA"); rs2073711_AA_pos.Add("rs16948046", "T"); rs2073711_AA_pos.Add("rs8036775", "G"); rs2073711_AA_pos.Add("rs547818", "A"); rs2073711_AA_pos.Add("rs633275", "G"); rs2073711_AA_pos.Add("rs16948101", "A"); rs2073711_AA_pos.Add("rs627101", "AC"); rs2073711_AA_pos.Add("rs16948108", "A"); rs2073711_AA_pos.Add("rs2593699", "C"); rs2073711_AA_pos.Add("rs4777488", "T"); rs2073711_AA_pos.Add("rs8029243", "G"); rs2073711_AA_pos.Add("rs10519272", "A"); rs2073711_AA_pos.Add("rs4777499", "T"); rs2073711_AA_pos.Add("rs11633399", "AC"); rs2073711_AA_pos.Add("rs11071803", "G"); rs2073711_AA_pos.Add("rs16948170", "C"); rs2073711_AA_pos.Add("rs11631564", "G"); rs2073711_AA_pos.Add("rs16948182", "T"); rs2073711_AA_pos.Add("rs3751534", "G"); rs2073711_AA_pos.Add("rs11858605", "C"); rs2073711_AA_pos.Add("rs7402386", "G"); rs2073711_AA_pos.Add("rs7173216", "C"); rs2073711_AA_pos.Add("rs10162671", "G"); rs2073711_AA_pos.Add("rs7402511", "C"); rs2073711_AA_pos.Add("rs7495961", "C"); rs2073711_AA_pos.Add("rs6494489", "CT"); rs2073711_AA_pos.Add("rs7403071", "A"); rs2073711_AA_pos.Add("rs10851739", "A"); rs2073711_AA_pos.Add("rs1008917", "C"); rs2073711_AA_pos.Add("rs7174486", "A"); rs2073711_AA_pos.Add("rs4777601", "T"); rs2073711_AA_pos.Add("rs4777602", "A"); rs2073711_AA_pos.Add("rs28704836", "G"); rs2073711_AA_pos.Add("rs17208301", "C"); rs2073711_AA_pos.Add("rs8036568", "T"); rs2073711_AA_pos.Add("rs1872592", "A"); rs2073711_AA_pos.Add("rs3743046", "C"); rs2073711_AA_pos.Add("rs4777615", "T"); rs2073711_AA_pos.Add("rs2414858", "A"); rs2073711_AA_pos.Add("rs1719288", "T"); rs2073711_AA_pos.Add("rs1522747", "T"); rs2073711_AA_pos.Add("rs1352093", "G"); rs2073711_AA_pos.Add("rs832882", "G"); rs2073711_AA_pos.Add("rs832884", "C"); rs2073711_AA_pos.Add("rs16948311", "G"); rs2073711_AA_pos.Add("rs832886", "C"); rs2073711_AA_pos.Add("rs2010875", "C"); rs2073711_AA_pos.Add("rs1043690", "A"); rs2073711_AA_pos.Add("rs1043697", "C"); rs2073711_AA_pos.Add("rs3183338", "T"); rs2073711_AA_pos.Add("rs1719271", "A"); rs2073711_AA_pos.Add("rs2200490", "C"); rs2073711_AA_pos.Add("rs1628955", "C"); rs2073711_AA_pos.Add("rs936867", "AG"); rs2073711_AA_pos.Add("rs1631677", "A"); rs2073711_AA_pos.Add("rs12437824", "AG"); rs2073711_AA_pos.Add("rs832878", "A"); rs2073711_AA_pos.Add("rs1471834", "A"); rs2073711_AA_pos.Add("rs2056497", "C"); rs2073711_AA_pos.Add("rs4287512", "CT"); rs2073711_AA_pos.Add("rs7168200", "TG"); rs2073711_AA_pos.Add("rs12438783", "G"); rs2073711_AA_pos.Add("rs12442603", "G"); rs2073711_AA_pos.Add("rs7178748", "C"); rs2073711_AA_pos.Add("rs28406502", "T"); rs2073711_AA_pos.Add("rs34988193", "A"); rs2073711_AA_pos.Add("rs2414865", "C"); rs2073711_AA_pos.Add("rs2277539", "C"); rs2073711_AA_pos.Add("rs6494503", "GA"); rs2073711_AA_pos.Add("rs4776654", "A"); rs2073711_AA_pos.Add("rs16948431", "T"); rs2073711_AA_pos.Add("rs1554524", "G"); rs2073711_AA_pos.Add("rs16948440", "T"); rs2073711_AA_pos.Add("rs7322", "TC"); rs2073711_AA_pos.Add("rs17229765", "GA"); rs2073711_AA_pos.Add("rs2280555", "GT"); rs2073711_AA_pos.Add("rs4346160", "CT"); rs2073711_AA_pos.Add("rs4316701", "G"); rs2073711_AA_pos.Add("rs11633597", "GA"); rs2073711_AA_pos.Add("rs8042506", "GA"); rs2073711_AA_pos.Add("rs16948457", "G"); rs2073711_AA_pos.Add("rs11635570", "GA"); rs2073711_AA_pos.Add("rs34636936", "C"); rs2073711_AA_pos.Add("rs4776660", "A"); rs2073711_AA_pos.Add("rs8035428", "TC"); rs2073711_AA_pos.Add("rs8024697", "TG"); rs2073711_AA_pos.Add("rs8029145", "A"); rs2073711_AA_pos.Add("rs2946662", "AC"); rs2073711_AA_pos.Add("rs4776661", "T"); rs2073711_AA_pos.Add("rs2946656", "C"); rs2073711_AA_pos.Add("rs7175761", "T"); rs2073711_AA_pos.Add("rs2946653", "T"); rs2073711_AA_pos.Add("rs8031050", "G"); rs2073711_AA_pos.Add("rs2919351", "T"); rs2073711_AA_pos.Add("rs2919352", "A"); rs2073711_AA_pos.Add("rs1046482", "T"); rs2073711_AA_pos.Add("rs2232762", "G"); rs2073711_AA_pos.Add("rs2232753", "A"); rs2073711_AA_pos.Add("rs2241858", "A"); rs2073711_AA_pos.Add("rs9630429", "A"); rs2073711_AA_pos.Add("rs4238400", "C"); rs2073711_AA_pos.Add("rs12440107", "A"); rs2073711_AA_pos.Add("rs12904843", "G"); rs2073711_AA_pos.Add("rs4776664", "A"); rs2073711_AA_pos.Add("rs2946650", "G"); rs2073711_AA_pos.Add("rs12916225", "C"); rs2073711_AA_pos.Add("rs11855621", "G"); rs2073711_AA_pos.Add("rs11852900", "A"); rs2073711_AA_pos.Add("rs17805328", "C"); rs2073711_AA_pos.Add("rs4776670", "C"); rs2073711_AA_pos.Add("rs7175110", "T"); rs2073711_AA_pos.Add("rs11071828", "C"); rs2073711_AA_pos.Add("rs2946672", "T"); rs2073711_AA_pos.Add("rs12595310", "C"); rs2073711_AA_pos.Add("rs2414878", "G"); rs2073711_AA_pos.Add("rs4776258", "G"); rs2073711_AA_pos.Add("rs12903989", "C"); rs2073711_AA_pos.Add("rs938951", "A"); rs2073711_AA_pos.Add("rs938952", "T"); rs2073711_AA_pos.Add("rs2679117", "C"); rs2073711_AA_pos.Add("rs34908405", "T"); rs2073711_AA_pos.Add("rs2679118", "C"); rs2073711_AA_pos.Add("rs756625", "G"); rs2073711_AA_pos.Add("rs11071829", "C"); rs2073711_AA_pos.Add("rs2073711", "A"); rs2073711_AA_pos.Add("rs11856834", "C"); rs2073711_AA_pos.Add("rs2585034", "C"); rs2073711_AA_pos.Add("rs2681038", "A"); rs2073711_AA_pos.Add("rs2585033", "C"); rs2073711_AA_pos.Add("rs2019185", "G"); rs2073711_AA_pos.Add("rs16948565", "T"); rs2073711_AA_pos.Add("rs1442795", "C"); rs2073711_AA_pos.Add("rs1561888", "G"); rs2073711_AA_pos.Add("rs8023487", "G"); rs2073711_AA_pos.Add("rs8023869", "C"); rs2073711_AA_pos.Add("rs17805775", "C"); rs2073711_AA_pos.Add("rs3759849", "C"); rs2073711_AA_pos.Add("rs11639264", "T"); rs2073711_AA_pos.Add("rs11071830", "T"); rs2073711_AA_pos.Add("rs920686", "G"); rs2073711_AA_pos.Add("rs755115", "C"); rs2073711_AA_pos.Add("rs11632307", "G"); rs2073711_AA_pos.Add("rs920688", "C"); rs2073711_AA_pos.Add("rs16948596", "G"); rs2073711_AA_pos.Add("rs4415968", "G"); rs2073711_AA_pos.Add("rs894494", "C"); rs2073711_AA_pos.Add("rs8024728", "G"); rs2073711_AA_pos.Add("rs11071835", "T"); rs2073711_AA_pos.Add("rs665287", "A"); rs2073711_AA_pos.Add("rs7175829", "C"); rs2073711_AA_pos.Add("rs556177", "C"); rs2073711_AA_pos.Add("rs680552", "T"); rs2073711_AA_pos.Add("rs681856", "A"); rs2073711_AA_pos.Add("rs11071838", "A"); rs2073711_AA_pos.Add("rs626163", "A"); rs2073711_AA_pos.Add("rs525514", "T"); rs2073711_AA_pos.Add("rs7162046", "A"); rs2073711_AA_pos.Add("rs639812", "G"); rs2073711_AA_pos.Add("rs11853777", "A"); rs2073711_AA_pos.Add("rs12907128", "A"); rs2073711_AA_pos.Add("rs894491", "A"); rs2073711_AA_pos.Add("rs581427", "T"); rs2073711_AA_pos.Add("rs603439", "A"); rs2073711_AA_pos.Add("rs8031618", "G"); rs2073711_AA_pos.Add("rs575749", "G"); rs2073711_AA_pos.Add("rs1442796", "T"); rs2073711_AA_pos.Add("rs678113", "T"); rs2073711_AA_pos.Add("rs578708", "C"); rs2073711_AA_pos.Add("rs602192", "C"); rs2073711_AA_pos.Add("rs6494518", "A"); rs2073711_AA_pos.Add("rs7182756", "G"); rs2073711_AA_pos.Add("rs2280345", "A"); rs2073711_AA_pos.Add("rs2292933", "T"); rs2073711_AA_pos.Add("rs11071841", "G"); rs2073711_AA_pos.Add("rs2277582", "A"); rs2073711_AA_pos.Add("rs1550027", "A"); rs2073711_AA_pos.Add("rs12442757", "T"); rs2073711_AA_pos.Add("rs668278", "A"); rs2073711_AA_pos.Add("rs588842", "G"); rs2073711_AA_pos.Add("rs736923", "A"); rs2073711_AA_pos.Add("rs591980", "AG"); rs2073711_AA_pos.Add("rs593647", "GA"); rs2073711_AA_pos.Add("rs612401", "G"); rs2073711_AA_pos.Add("rs7171289", "C"); rs2073711_AA_pos.Add("rs2289045", "G"); rs2073711_AA_pos.Add("rs652931", "CT"); rs2073711_AA_pos.Add("rs892650", "C"); rs2073711_AA_pos.Add("rs11009", "C"); rs2073711_AA_pos.Add("rs7163482", "TC"); rs2073711_AA_pos.Add("rs12595213", "C"); rs2073711_AA_pos.Add("rs3825891", "T"); rs2073711_AA_pos.Add("rs7174627", "G"); rs2073711_AA_pos.Add("rs352457", "G"); rs2073711_AA_pos.Add("rs409987", "G"); rs2073711_AA_pos.Add("rs1865421", "A"); rs2073711_AA_pos.Add("rs11071846", "GA"); rs2073711_AA_pos.Add("rs352480", "T"); rs2073711_AA_pos.Add("rs3784448", "C"); rs2073711_AA_pos.Add("rs9635366", "G"); rs2073711_AA_pos.Add("rs352476", "TC"); rs2073711_AA_pos.Add("rs8039978", "C"); rs2073711_AA_pos.Add("rs7164489", "A"); rs2073711_AA_pos.Add("rs430515", "G"); rs2073711_AA_pos.Add("rs2456015", "T"); rs2073711_AA_pos.Add("rs395300", "A"); rs2073711_AA_pos.Add("rs189518", "T"); rs2073711_AA_pos.Add("rs2456009", "CA"); rs2073711_AA_pos.Add("rs1003104", "G"); rs2073711_AA_pos.Add("rs7164255", "C"); rs2073711_AA_pos.Add("rs10519294", "A"); rs2073711_AA_pos.Add("rs16948825", "A"); rs2073711_AA_pos.Add("rs2279854", "A"); rs2073711_AA_pos.Add("rs12333", "C"); rs2073711_AA_pos.Add("rs3743168", "T"); rs2073711_AA_pos.Add("rs3743169", "G"); rs2073711_AA_pos.Add("rs11484", "G"); rs2073711_AA_pos.Add("rs11635626", "A"); rs2073711_AA_pos.Add("rs2899708", "G"); rs2073711_AA_pos.Add("rs16948867", "A"); rs2073711_AA_pos.Add("rs12906196", "CT"); rs2073711_AA_pos.Add("rs4366668", "AG"); rs2073711_AA_pos.Add("rs870022", "C"); rs2073711_AA_pos.Add("rs3743171", "A"); rs2073711_AA_pos.Add("rs34363823", "G"); rs2073711_AA_pos.Add("rs35984752", "G"); rs2073711_AA_pos.Add("rs12917564", "G"); rs2073711_AA_pos.Add("rs16948886", "C"); rs2073711_AA_pos.Add("rs16948889", "A"); rs2073711_AA_pos.Add("rs1211944", "C"); rs2073711_AA_pos.Add("rs12910810", "T"); rs2073711_AA_pos.Add("rs16948916", "T"); rs2073711_AA_pos.Add("rs8035639", "TC"); rs2073711_AA_pos.Add("rs905733", "T"); rs2073711_AA_pos.Add("rs16948924", "G"); rs2073711_AA_pos.Add("rs8027260", "T"); rs2073711_AA_pos.Add("rs8030562", "CT"); rs2073711_AA_pos.Add("rs11858075", "C"); rs2073711_AA_pos.Add("rs8028238", "C"); rs2073711_AA_pos.Add("rs1435125", "A"); rs2073711_AA_pos.Add("rs11071848", "T"); rs2073711_AA_pos.Add("rs17810074", "C"); rs2073711_AA_pos.Add("rs7162611", "T"); rs2073711_AA_pos.Add("rs934542", "G"); rs2073711_AA_pos.Add("rs10519303", "T"); rs2073711_AA_pos.Add("rs7180542", "C"); rs2073711_AA_pos.Add("rs6494537", "TC"); rs2073711_AA_pos.Add("rs2572217", "C"); rs2073711_AA_pos.Add("rs2727098", "T"); rs2073711_AA_pos.Add("rs721151", "C"); rs2073711_AA_pos.Add("rs2727102", "C"); rs2073711_AA_pos.Add("rs17816071", "T"); rs2073711_AA_pos.Add("rs2572209", "C"); rs2073711_AA_pos.Add("rs8035725", "G"); rs2073711_AA_pos.Add("rs16949046", "A"); rs2073711_AA_pos.Add("rs8027781", "CA"); rs2073711_AA_pos.Add("rs2727087", "C"); rs2073711_AA_pos.Add("rs2727089", "C"); rs2073711_AA_pos.Add("rs2660632", "T"); rs2073711_AA_pos.Add("rs2899713", "C"); rs2073711_AA_pos.Add("rs10851750", "G"); rs2073711_AA_pos.Add("rs9806220", "G"); rs2073711_AA_pos.Add("rs2660619", "G"); rs2073711_AA_pos.Add("rs11634367", "A"); rs2073711_AA_pos.Add("rs11071852", "T"); rs2073711_AA_pos.Add("rs12593305", "G"); rs2073711_AA_pos.Add("rs12594238", "T"); rs2073711_AA_pos.Add("rs2414891", "A"); rs2073711_AA_pos.Add("rs12904203", "A"); rs2073711_AA_pos.Add("rs4530073", "G"); rs2073711_AA_pos.Add("rs4514623", "T"); rs2073711_AA_pos.Add("rs11854887", "A"); rs2073711_AA_pos.Add("rs11634482", "A"); rs2073711_AA_pos.Add("rs11637538", "A"); rs2073711_AA_pos.Add("rs1063697", "T"); rs2073711_AA_pos.Add("rs16949087", "C"); rs2073711_AA_pos.Add("rs11071853", "C"); rs2073711_AA_pos.Add("rs11638122", "A"); rs2073711_AA_pos.Add("rs16949091", "A"); rs2073711_AA_pos.Add("rs333542", "A"); rs2073711_AA_pos.Add("rs3803414", "G"); rs2073711_AA_pos.Add("rs16949100", "T"); rs2073711_AA_pos.Add("rs11637551", "G"); rs2073711_AA_pos.Add("rs875948", "A"); rs2073711_AA_pos.Add("rs11635501", "C"); rs2073711_AA_pos.Add("rs10519311", "C"); rs2073711_AA_pos.Add("rs10400879", "G"); rs2073711_AA_pos.Add("rs16949128", "T"); } public byte[] Zip(byte[] bytes) { using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(mso, CompressionMode.Compress)) { //msi.CopyTo(gs); CopyTo(msi, gs); } return mso.ToArray(); } } public byte[] Unzip(byte[] bytes) { using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) { //gs.CopyTo(mso); CopyTo(gs, mso); } return mso.ToArray(); } } public void CopyTo(Stream src, Stream dest) { byte[] bytes = new byte[4096]; int cnt; while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) { dest.Write(bytes, 0, cnt); } } private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog(this) == DialogResult.OK) { int world_average_age=80; int user_avg_age = world_average_age; int avg_risk = checkIBD(dialog.FileName, rs2073711_AA_pos, "rs2073711", "15", "AA"); switch (avg_risk) { case RESULT_NA: MessageBox.Show("Insufficient data."); break; case RESULT_TRUE: MessageBox.Show("You have normal risk of lumbar disc disease."); break; case RESULT_PROB_TRUE: MessageBox.Show("You may have normal risk of lumbar disc disease."); break; case RESULT_FALSE: MessageBox.Show("You have high risk of lumbar disc disease."); break; } } } private int checkIBD(string file, Dictionary<string, string> ibd_gt_ref, string rsid, string chr, string target_gt) { List<string> match = new List<string>(); string text = getAutosomalText(file); StringReader reader = new StringReader(text); string line = null; string[] data=null; bool is_match = true; int error_count = 0; int allowed_errors = ibd_gt_ref.Count * 4 / 100; //StringBuilder stmp = new StringBuilder(); while((line=reader.ReadLine())!=null) { if (line.StartsWith("#") || line.StartsWith("RSID") || line.StartsWith("rsid")) continue; line = line.Replace("\"", "").Replace("\t",","); data=line.Split(new char[]{','}); if (data.Length == 5) data[3] = data[3] + data[4]; if(data[1]==chr) { //stmp.Append(line); //stmp.Append("\r\n"); if (data[0] == rsid) { if (data[3] == target_gt) return RESULT_TRUE; else return RESULT_FALSE; } if(ibd_gt_ref.ContainsKey(data[0])) { if (ibd_gt_ref[data[0]].Length == 1) { if (ibd_gt_ref[data[0]] == data[3][0].ToString() || ibd_gt_ref[data[0]] == data[3][1].ToString()) match.Add(data[0]); else { if (data[3].IndexOf("-") != -1 || data[3].IndexOf("0") != -1 || data[3].IndexOf("?") != -1) continue; error_count++; if (error_count >= allowed_errors) { is_match = false; break; } else match.Add(data[0]); } } else if (ibd_gt_ref[data[0]].Length == 2) { if (ibd_gt_ref[data[0]][0].ToString() == data[3][0].ToString() || ibd_gt_ref[data[0]][0].ToString() == data[3][1].ToString() || ibd_gt_ref[data[0]][1].ToString() == data[3][0].ToString() || ibd_gt_ref[data[0]][1].ToString() == data[3][1].ToString()) match.Add(data[0]); else { if (data[3].IndexOf("-") != -1 || data[3].IndexOf("0") != -1 || data[3].IndexOf("?") != -1) continue; error_count++; if (error_count >= allowed_errors) { is_match = false; break; } else match.Add(data[0]); } } else { if (data[3].IndexOf("-") != -1 || data[3].IndexOf("0") != -1 || data[3].IndexOf("?") != -1) continue; error_count++; if (error_count >= allowed_errors) { is_match = false; break; } else match.Add(data[0]); } } } } //File.WriteAllText(@"D:\Temp\" + Path.GetFileName(file) + ".7", stmp.ToString()); if (is_match) { if (match.Count >= ibd_gt_ref.Keys.Count*0.9) return RESULT_TRUE; else if (match.Count >= ibd_gt_ref.Keys.Count * 0.5) return RESULT_PROB_TRUE; else return RESULT_NA; } else { return RESULT_FALSE; } } private string getAutosomalText(string file) { string text = null; if (file.EndsWith(".gz")) { StringReader reader = new StringReader(Encoding.UTF8.GetString(Unzip(File.ReadAllBytes(file)))); text = reader.ReadToEnd(); reader.Close(); } else if (file.EndsWith(".zip")) { using (var fs = new MemoryStream(File.ReadAllBytes(file))) using (var zf = new ZipFile(fs)) { var ze = zf[0]; if (ze == null) { throw new ArgumentException("file not found in Zip"); } using (var s = zf.GetInputStream(ze)) { using (StreamReader sr = new StreamReader(s)) { text = sr.ReadToEnd(); } } } } else text = File.ReadAllText(file); return text; } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.y-str.org/"); } } }
namespace DTO { public class TEM_DTO { public int mstem; public string ngaybatdau; public string ngayketthuc; } }
using ExperianOfficeArrangement.Common; using ExperianOfficeArrangement.Factories; using ExperianOfficeArrangement.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExperianOfficeArrangement.ViewModels { public class LoadMapViewModel : NavigationViewModelBase { public LoadMapViewModel() : this(new RandomLayoutFactory(0)) { } public LoadMapViewModel(IInteriorLayoutFactory layoutFactory) { this.layoutFactory = layoutFactory; this.LoadMapCommand = new DelegateCommand(this.LoadLayout); } private string layoutIdentifier; public string LayoutIdentifier { get { return this.layoutIdentifier; } set { this.SetProperty(ref this.layoutIdentifier, value); } } public IInvalidatableCommand LoadMapCommand { get; private set; } public override IStateViewModel GetNextState() { return this.layout != null ? new ChooseBrandViewModel(this.layout) : null; } private void LoadLayout(object dummyParam) { this.layout = this.layoutFactory.GetLayout(); if (this.layout != null) { this.LayoutIdentifier = layoutFactory.LayoutIdentifier; this.CanTransition = this.layout != null; } } private InteriorField[,] layout; private IInteriorLayoutFactory layoutFactory; } }
using System; using System.Collections.Generic; using System.Web.Mvc; using Logs.Authentication.Contracts; using Logs.Common; using Logs.Services.Contracts; using Logs.Web.Areas.Administration.Models; using PagedList; namespace Logs.Web.Areas.Administration.Controllers { [Authorize(Roles = Common.Constants.AdministratorRoleName)] public class UserAdministrationController : Controller { private readonly IUserService userService; private readonly IAuthenticationProvider authenticationProvider; public UserAdministrationController(IUserService userService, IAuthenticationProvider authenticationProvider) { if (userService == null) { throw new ArgumentNullException(nameof(userService)); } if (authenticationProvider == null) { throw new ArgumentNullException(nameof(authenticationProvider)); } this.userService = userService; this.authenticationProvider = authenticationProvider; } public ActionResult Index(int page = 1, int count = Constants.AdminPageSize) { var users = this.userService.GetUsers(); var model = new List<UserViewModel>(); foreach (var user in users) { var isAdmin = this.authenticationProvider.IsInRole(user.Id, Constants.AdministratorRoleName); var viewModel = new UserViewModel(user, isAdmin); model.Add(viewModel); } return this.View(model.ToPagedList(page, count)); } public ActionResult Ban(string userId, int page) { this.authenticationProvider.BanUser(userId); return this.RedirectToAction("Index", new { page = page }); } public ActionResult Unban(string userId, int page) { this.authenticationProvider.UnbanUser(userId); return this.RedirectToAction("Index", new { page = page }); } public ActionResult RemoveAdmin(string userId, int page) { this.authenticationProvider.RemoveFromRole(userId, Common.Constants.AdministratorRoleName); return this.RedirectToAction("Index", new { page = page }); } public ActionResult AddAdmin(string userId, int page) { this.authenticationProvider.AddToRole(userId, Common.Constants.AdministratorRoleName); return this.RedirectToAction("Index", new { page = page }); } } }
namespace Core.Enums { public enum ProductType { Dress= 1, Veil = 2, Flowers = 3 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnowProCorp.DAL { [Flags] public enum ShipmentStatus { OrderReceived = 1, InPreparation = 2, PickepUp = 4, Delivered = 8, Lost = 16 } }
using System; using System.IO; using FluentAssertions; using NUnit.Framework; using VH.Core.Configuration.AKSKeyVaultFileProvider; namespace VH.Core.Configuration.UnitTests.AKSKeyVaultFileProvider.TheAksKeyVaultSecretFileProvider._Constructor { public class when_directory_does_not_exist { [Test] public void should_throw_DirectoryNotFoundException() { var rootFolder = TempFolderFactory.CreateNonExistingTempFolder(); var action = new Action(() => new AksKeyVaultSecretFileProvider(rootFolder)); action.Should().Throw<DirectoryNotFoundException>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.ViewModels { public class UserInterestViewModel { public String UserName { get; set; } public int IdInterest { get; set; } } }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using CloneDeploy_App.Controllers.Authorization; using CloneDeploy_Entities; using CloneDeploy_Entities.DTOs; using CloneDeploy_Services; namespace CloneDeploy_App.Controllers { public class ComputerLogController : ApiController { private readonly ComputerLogServices _computerLogServices; public ComputerLogController() { _computerLogServices = new ComputerLogServices(); } [CustomAuth(Permission = "ComputerSearch")] public ActionResultDTO Delete(int id) { var result = _computerLogServices.DeleteComputerLog(id); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } [CustomAuth(Permission = "ComputerSearch")] public ComputerLogEntity Get(int id) { var result = _computerLogServices.GetComputerLog(id); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } [CustomAuth(Permission = "AdminRead")] public IEnumerable<ComputerLogEntity> GetOnDemandLogs(int limit = 0) { return _computerLogServices.SearchOnDemand(limit); } [CustomAuth(Permission = "ComputerSearch")] public ActionResultDTO Post(ComputerLogEntity computerLog) { var result = _computerLogServices.AddComputerLog(computerLog); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } } }
using UnityEngine; [CreateAssetMenu(fileName = "MovePatternDual")] public class MovePatternDual : MovePattern { private bool doubleJump; public override void Invoke(CharacterController controller, Transform transform) { if (controller.isGrounded) { MoveTran(transform); doubleJump = true; } else { if (doubleJump) { MoveTran(transform); doubleJump = false; } } MoveCon(controller); } }
using ChatApp.Lib.Messaging.Model; using ChatApp.Lib.Messaging.Persistence; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; namespace ChatApp.Controllers.Api { /// <summary> /// Controller for providing <see cref="ChatMessage">chat messages</see> /// </summary> [Route("api/v1/messages")] public class MessageController : Controller { private readonly IChatMessageRepository _chatMessageRepository; //Limit for max messages to fetch private const int MaxMessages = 1000; public MessageController(IChatMessageRepository chatMessageRepository) { _chatMessageRepository = chatMessageRepository; } /// <summary> /// Get all <see cref="ChatMessage">chat messages</see> available in the provided repository /// TODO: Paging support /// </summary> /// <returns> /// <see cref="IEnumerable{ChatMessage}"/> containing all messages in repository (count capped by MaxMessages const). /// Enumerable is empty if no messages exist /// </returns> [HttpGet("all")] public async Task<IEnumerable<ChatMessage>> GetAllMessages() { return await _chatMessageRepository.GetMessages(MaxMessages); } } }
using App.Entity; namespace App.Data { /// <seealso cref="App.Data.BasicDAC{App.Entity.RolBE, App.Data.RolDAC}" /> public class RolDAC : BasicDAC<RolBE, RolDAC> { /// <summary> /// Initializes a new instance of the <see cref="RolDAC"/> class. /// </summary> public RolDAC() : base(ContextVariables.Source, "Rol") { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SSW.DataOnion.CodeGenerator.Exceptions; namespace SSW.DataOnion.CodeGenerator.Helpers { public class DbContextGenerator { /// <summary> /// /// </summary> /// <param name="dbContextName">Name of the DbContext class</param> /// <param name="entitiesNamespaces">Namespace used for entities</param> /// <param name="dataProjectNamespace">Namespace used for project where DbContext resides</param> /// <param name="entitiesDllPath">Path to entities dll</param> /// <param name="baseEntityClassName">Optional base class used by all entities</param> public void Generate( string dbContextName, string entitiesNamespaces, string dataProjectNamespace, string entitiesDllPath, string baseEntityClassName = null) { Guard.AgainstNullOrEmptyString(dbContextName, nameof(dbContextName)); Guard.AgainstNullOrEmptyString(entitiesNamespaces, nameof(entitiesNamespaces)); Guard.AgainstNullOrEmptyString(dataProjectNamespace, nameof(dataProjectNamespace)); Guard.AgainstNullOrEmptyString(entitiesDllPath, nameof(entitiesDllPath)); var entityTypes = AssemblyHelper.GetDomainTypes(entitiesNamespaces, entitiesDllPath, baseEntityClassName); var template = ResourceReader.GetResourceContents("DbContext.template"); var dbSets = GetDbSets(entityTypes); // replace all tokens template = template.Replace(TokenNames.DataProject, dataProjectNamespace) .Replace(TokenNames.DbContextName, dbContextName) .Replace(TokenNames.EntitiesProject, string.Join(Environment.NewLine + "\t\t", entitiesNamespaces.Split(',').Select(v => $"using {v};"))) .Replace(TokenNames.DbSets, string.Join(Environment.NewLine, dbSets)); // create file File.WriteAllText($"{dbContextName}.gen.cs", template); } private static IEnumerable<string> GetDbSets(ICollection<string> entityTypes) { var dbSets = entityTypes.Select( e => $"{TokenNames.DbSetTemplate.Replace(TokenNames.Entity, e).Replace(TokenNames.DbSet, e.Pluralize())}"); return dbSets; } } }
using EmployeeInfoAPI.DataAccess; using EmployeeInfoAPI.Model; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; namespace EmployeeInfoAPI.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { private readonly EmployeeDBContext _employeeDBContext; public EmployeeController(EmployeeDBContext employeeDBContext) { _employeeDBContext = employeeDBContext; } [HttpGet("GetEmployeeInfo")] public async Task<IActionResult> GetEmployeeInfo() { var employeeInfo = await _employeeDBContext.EmployeeInformation.ToListAsync(); return Ok(employeeInfo); } [HttpPost("CreateEmployee")] public async Task<IActionResult> CreateEmployeeInfo([FromBody] EmployeeInfo employeeInfo) { await _employeeDBContext.EmployeeInformation.AddAsync(employeeInfo); await _employeeDBContext.SaveChangesAsync(); return Ok(employeeInfo); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YzkSoftWare.DataModel { /// <summary> /// 定义数据模型字段过滤器的基类的特性 /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public abstract class DataModelFieldCustomFilterAttribute : Attribute { /// <summary> /// 判断指定的属性是否是数据库字段 /// </summary> /// <param name="pd">要判断的属性</param> /// <returns>如果pd是一个数据库字段则返回true,否则返回false</returns> public abstract bool IsDefineFeild(PropertyDescriptor pd); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Soko.Domain; using Soko.Report; using Bilten.Dao; using Soko.Exceptions; using NHibernate; using Soko.Data; using NHibernate.Context; using Soko.Misc; namespace Soko.UI { public partial class UplateClanarineForm : EntityListForm { private readonly string CLAN = "PrezimeImeBrojDatumRodj"; private readonly string IZNOS = "Iznos"; private readonly string DATUM_UPLATE = "DatumUplate"; private readonly string VREME_UPLATE = "VremeUplate"; private readonly string GRUPA = "SifraGrupeCrtaNazivGrupe"; private readonly string VAZI_OD = "VaziOd"; private readonly string NAPOMENA = "Napomena"; private readonly string KORISNIK = "Korisnik"; private List<Clan> clanovi; public UplateClanarineForm() { InitializeComponent(); initialize(typeof(UplataClanarine)); rbtClan.CheckedChanged += new System.EventHandler(rbtClan_CheckedChanged); rbtInterval.CheckedChanged += new System.EventHandler(rbtInterval_CheckedChanged); cmbClan.SelectedIndexChanged += new System.EventHandler(cmbClan_SelectedIndexChanged); //sortByDatumVreme(); } private List<Clan> loadClanovi() { List<Clan> result = new List<Clan>(DAOFactoryFactory.DAOFactory.GetClanDAO().FindAll()); Util.sortByPrezimeImeDatumRodjenja(result); return result; } private void setClanovi(List<Clan> clanovi) { cmbClan.DropDownStyle = ComboBoxStyle.DropDown; cmbClan.DataSource = clanovi; cmbClan.DisplayMember = "BrojPrezimeImeDatumRodjenja"; } private Clan SelectedClan { get { return cmbClan.SelectedItem as Clan; } set { cmbClan.SelectedItem = value; } } protected override DataGridView getDataGridView() { return dataGridView1; } protected override void initUI() { base.initUI(); this.Text = "Potvrda o uplati"; this.Size = new Size(Size.Width, 450); this.dtpOd.CustomFormat = "d.M.yyyy"; this.dtpOd.Format = DateTimePickerFormat.Custom; this.dtpDo.CustomFormat = "d.M.yyyy"; this.dtpDo.Format = DateTimePickerFormat.Custom; rbtInterval.Checked = true; cmbClan.Enabled = false; } private void sortByDatumVreme() { PropertyDescriptor propDescDatum = TypeDescriptor.GetProperties(typeof(UplataClanarine))["DatumUplate"]; PropertyDescriptor propDescVreme = TypeDescriptor.GetProperties(typeof(UplataClanarine))["VremeUplate"]; PropertyDescriptor[] propDesc = new PropertyDescriptor[2] { propDescDatum, propDescVreme }; ListSortDirection[] direction = new ListSortDirection[2] { ListSortDirection.Descending, ListSortDirection.Descending }; entities.Sort(new SortComparer<object>(propDesc, direction)); } protected override void addGridColumns() { AddColumn("Clan", CLAN, 180); AddColumn("Iznos", IZNOS, DataGridViewContentAlignment.MiddleRight, "{0:f2}"); AddColumn("Datum uplate", DATUM_UPLATE, DataGridViewContentAlignment.MiddleRight); AddColumn("Vreme uplate", VREME_UPLATE, DataGridViewContentAlignment.MiddleCenter, "{0:t}"); AddColumn("Grupa", GRUPA, 220); AddColumn("Za mesec", VAZI_OD, DataGridViewContentAlignment.MiddleRight, "{0:MMMM yyyy}"); AddColumn("Napomena", NAPOMENA, 150, DataGridViewContentAlignment.MiddleCenter); AddColumn("Korisnik", KORISNIK, DataGridViewContentAlignment.MiddleCenter); } protected override List<object> loadEntities() { clanovi = loadClanovi(); setClanovi(clanovi); if (clanovi.Count > 0) SelectedClan = clanovi[0]; else SelectedClan = null; if (rbtClan.Checked) return loadUplateForClan(SelectedClan); else return loadUplateForInterval(dtpOd.Value.Date, dtpDo.Value.Date); } private List<object> loadUplateForInterval(DateTime from, DateTime to) { UplataClanarineDAO uplataClanarineDAO = DAOFactoryFactory.DAOFactory.GetUplataClanarineDAO(); return new List<UplataClanarine>(uplataClanarineDAO.findUplate(from, to)).ConvertAll<object>( delegate(UplataClanarine u) { return u; }); } private List<object> loadUplateForClan(Clan c) { if (c == null) return new List<object>(); UplataClanarineDAO uplataClanarineDAO = DAOFactoryFactory.DAOFactory.GetUplataClanarineDAO(); return new List<UplataClanarine>(uplataClanarineDAO.findUplate(c)).ConvertAll<object>( delegate(UplataClanarine u) { return u; }); } private void cmbClan_SelectedIndexChanged(object sender, System.EventArgs e) { // TODO: Ne bi bilo lose da svi kreirani DAO objekti koji se koriste za realizaciju nekog juz-kejsa budu metodi // klase Form. Time se izbegava situacija gde se neki DAO dva puta kreira. updateGrid(); } private void showUplateForClan(Clan c) { setEntities(loadUplateForClan(c)); //sortByDatumVreme(); } private void updateGrid() { try { using (ISession session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); if (rbtClan.Checked) showUplateForClan(SelectedClan); else showUplateForInterval(dtpOd.Value.Date, dtpDo.Value.Date); } } catch (InfrastructureException ex) { MessageDialogs.showError(ex.Message, this.Text); Close(); return; } catch (Exception ex) { MessageDialogs.showError(ex.Message, this.Text); Close(); return; } finally { CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } } private void showUplateForInterval(DateTime from, DateTime to) { setEntities(loadUplateForInterval(from, to)); //sortByDatumVreme(); } private void rbtClan_CheckedChanged(object sender, System.EventArgs e) { if (rbtClan.Checked) { cmbClan.Enabled = true; dtpOd.Enabled = false; dtpDo.Enabled = false; lblOd.Enabled = false; lblDo.Enabled = false; updateGrid(); } } private void rbtInterval_CheckedChanged(object sender, System.EventArgs e) { if (rbtInterval.Checked) { cmbClan.Enabled = false; dtpOd.Enabled = true; dtpDo.Enabled = true; lblOd.Enabled = true; lblDo.Enabled = true; Cursor.Current = Cursors.WaitCursor; Cursor.Show(); updateGrid(); Cursor.Hide(); Cursor.Current = Cursors.Arrow; } } private void dtpOd_CloseUp(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; Cursor.Show(); updateGrid(); Cursor.Hide(); Cursor.Current = Cursors.Arrow; } private void dtpDo_CloseUp(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; Cursor.Show(); updateGrid(); Cursor.Hide(); Cursor.Current = Cursors.Arrow; } private void btnStampaj_Click(object sender, System.EventArgs e) { // TODO: Probaj da promenis i EntityListForm i EntityDetailForm tako da // rade za bilo koji objekt (da mogu da se koriste i za npr. DTO objekte) UplataClanarine uplata = (UplataClanarine)getSelectedEntity(); if (uplata == null) return; try { using (ISession session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); PreviewDialog p = new PreviewDialog(); List<int> idList = new List<int>(); idList.Add(uplata.Id); p.setIzvestaj(new PotvrdaIzvestaj(idList)); p.ShowDialog(); } } catch (InfrastructureException ex) { MessageDialogs.showError(ex.Message, this.Text); } catch (Exception ex) { MessageDialogs.showError(ex.Message, this.Text); } finally { CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } } private void btnZatvori_Click(object sender, System.EventArgs e) { Close(); } private void PotvrdaUplateForm_Shown(object sender, EventArgs e) { btnZatvori.Focus(); } private void btnPromeni_Click(object sender, EventArgs e) { editCommand(); } protected override EntityDetailForm createEntityDetailForm(Nullable<int> entityId) { return new UplataDialogAdmin(entityId); } } }
namespace HelperLibrary.Models.Interfaces { public interface ITable { int Id { get; set; } } }
using System.Threading.Tasks; using Archimedes.Library.Message.Dto; namespace Archimedes.Service.Ui.Hubs { public interface IMarketHub { Task Add(MarketDto value); Task Delete(MarketDto value); Task Update(MarketDto value); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraEditors; using PMQL.Bussiness; namespace PMQL { public partial class ThanhVien : DevExpress.XtraEditors.XtraForm { Bussinesslogic bs = new Bussinesslogic(); public ThanhVien() { InitializeComponent(); } private void BtnLocTV_CheckedChanged(object sender, EventArgs e) { } private void ThanhVien_Load(object sender, EventArgs e) { dataGridViewTV.DataSource = bs.getThanhVien(); } } }
using ComputerBuilderSystem.Contracts; namespace ComputerBuilderSystem.SystemComponents { public class Cpu32Bit : BaseCpu, ICentralProcessingUnit { private const int Bit32Size = 500; public Cpu32Bit(byte numberOfCores) : base(numberOfCores, Bit32Size) { } } }
// Decompiled with JetBrains decompiler // Type: System.Data.Linq.SqlClient.Strings // Assembly: System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 43A00CAE-A2D4-43EB-9464-93379DA02EC9 // Assembly location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Data.Linq.dll namespace System.Data.Linq.SqlClient { internal static class Strings { internal static string OwningTeam => SR.GetString(nameof(OwningTeam)); internal static string VbLikeDoesNotSupportMultipleCharacterRanges => SR.GetString(nameof(VbLikeDoesNotSupportMultipleCharacterRanges)); internal static string VbLikeUnclosedBracket => SR.GetString(nameof(VbLikeUnclosedBracket)); internal static string UnrecognizedProviderMode(object p0) => SR.GetString(nameof(UnrecognizedProviderMode), p0); internal static string CompiledQueryCannotReturnType(object p0) => SR.GetString(nameof(CompiledQueryCannotReturnType), p0); internal static string ArgumentEmpty(object p0) => SR.GetString(nameof(ArgumentEmpty), p0); internal static string ProviderCannotBeUsedAfterDispose => SR.GetString(nameof(ProviderCannotBeUsedAfterDispose)); internal static string ArgumentTypeMismatch(object p0) => SR.GetString(nameof(ArgumentTypeMismatch), p0); internal static string ContextNotInitialized => SR.GetString(nameof(ContextNotInitialized)); internal static string CouldNotDetermineSqlType(object p0) => SR.GetString(nameof(CouldNotDetermineSqlType), p0); internal static string CouldNotDetermineDbGeneratedSqlType(object p0) => SR.GetString(nameof(CouldNotDetermineDbGeneratedSqlType), p0); internal static string CouldNotDetermineCatalogName => SR.GetString(nameof(CouldNotDetermineCatalogName)); internal static string CreateDatabaseFailedBecauseOfClassWithNoMembers(object p0) => SR.GetString(nameof(CreateDatabaseFailedBecauseOfClassWithNoMembers), p0); internal static string CreateDatabaseFailedBecauseOfContextWithNoTables(object p0) => SR.GetString(nameof(CreateDatabaseFailedBecauseOfContextWithNoTables), p0); internal static string CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(object p0) => SR.GetString(nameof(CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists), p0); internal static string DistributedTransactionsAreNotAllowed => SR.GetString(nameof(DistributedTransactionsAreNotAllowed)); internal static string InvalidConnectionArgument(object p0) => SR.GetString(nameof(InvalidConnectionArgument), p0); internal static string CannotEnumerateResultsMoreThanOnce => SR.GetString(nameof(CannotEnumerateResultsMoreThanOnce)); internal static string IifReturnTypesMustBeEqual(object p0, object p1) => SR.GetString(nameof(IifReturnTypesMustBeEqual), p0, p1); internal static string MethodNotMappedToStoredProcedure(object p0) => SR.GetString(nameof(MethodNotMappedToStoredProcedure), p0); internal static string ResultTypeNotMappedToFunction(object p0, object p1) => SR.GetString(nameof(ResultTypeNotMappedToFunction), p0, p1); internal static string ToStringOnlySupportedForPrimitiveTypes => SR.GetString(nameof(ToStringOnlySupportedForPrimitiveTypes)); internal static string TransactionDoesNotMatchConnection => SR.GetString(nameof(TransactionDoesNotMatchConnection)); internal static string UnexpectedTypeCode(object p0) => SR.GetString(nameof(UnexpectedTypeCode), p0); internal static string UnsupportedDateTimeConstructorForm => SR.GetString(nameof(UnsupportedDateTimeConstructorForm)); internal static string UnsupportedDateTimeOffsetConstructorForm => SR.GetString(nameof(UnsupportedDateTimeOffsetConstructorForm)); internal static string UnsupportedStringConstructorForm => SR.GetString(nameof(UnsupportedStringConstructorForm)); internal static string UnsupportedTimeSpanConstructorForm => SR.GetString(nameof(UnsupportedTimeSpanConstructorForm)); internal static string UnsupportedTypeConstructorForm(object p0) => SR.GetString(nameof(UnsupportedTypeConstructorForm), p0); internal static string WrongNumberOfValuesInCollectionArgument(object p0, object p1, object p2) => SR.GetString(nameof(WrongNumberOfValuesInCollectionArgument), p0, p1, p2); internal static string LogGeneralInfoMessage(object p0, object p1) => SR.GetString(nameof(LogGeneralInfoMessage), p0, p1); internal static string LogAttemptingToDeleteDatabase(object p0) => SR.GetString(nameof(LogAttemptingToDeleteDatabase), p0); internal static string LogStoredProcedureExecution(object p0, object p1) => SR.GetString(nameof(LogStoredProcedureExecution), p0, p1); internal static string MemberCannotBeTranslated(object p0, object p1) => SR.GetString(nameof(MemberCannotBeTranslated), p0, p1); internal static string NonConstantExpressionsNotSupportedFor(object p0) => SR.GetString(nameof(NonConstantExpressionsNotSupportedFor), p0); internal static string MathRoundNotSupported => SR.GetString(nameof(MathRoundNotSupported)); internal static string SqlMethodOnlyForSql(object p0) => SR.GetString(nameof(SqlMethodOnlyForSql), p0); internal static string NonConstantExpressionsNotSupportedForRounding => SR.GetString(nameof(NonConstantExpressionsNotSupportedForRounding)); internal static string CompiledQueryAgainstMultipleShapesNotSupported => SR.GetString(nameof(CompiledQueryAgainstMultipleShapesNotSupported)); internal static string LenOfTextOrNTextNotSupported(object p0) => SR.GetString(nameof(LenOfTextOrNTextNotSupported), p0); internal static string TextNTextAndImageCannotOccurInDistinct(object p0) => SR.GetString(nameof(TextNTextAndImageCannotOccurInDistinct), p0); internal static string TextNTextAndImageCannotOccurInUnion(object p0) => SR.GetString(nameof(TextNTextAndImageCannotOccurInUnion), p0); internal static string MaxSizeNotSupported(object p0) => SR.GetString(nameof(MaxSizeNotSupported), p0); internal static string IndexOfWithStringComparisonArgNotSupported => SR.GetString(nameof(IndexOfWithStringComparisonArgNotSupported)); internal static string LastIndexOfWithStringComparisonArgNotSupported => SR.GetString(nameof(LastIndexOfWithStringComparisonArgNotSupported)); internal static string ConvertToCharFromBoolNotSupported => SR.GetString(nameof(ConvertToCharFromBoolNotSupported)); internal static string ConvertToDateTimeOnlyForDateTimeOrString => SR.GetString(nameof(ConvertToDateTimeOnlyForDateTimeOrString)); internal static string CannotTranslateExpressionToSql => SR.GetString(nameof(CannotTranslateExpressionToSql)); internal static string SkipIsValidOnlyOverOrderedQueries => SR.GetString(nameof(SkipIsValidOnlyOverOrderedQueries)); internal static string SkipRequiresSingleTableQueryWithPKs => SR.GetString(nameof(SkipRequiresSingleTableQueryWithPKs)); internal static string NoMethodInTypeMatchingArguments(object p0) => SR.GetString(nameof(NoMethodInTypeMatchingArguments), p0); internal static string CannotConvertToEntityRef(object p0) => SR.GetString(nameof(CannotConvertToEntityRef), p0); internal static string ExpressionNotDeferredQuerySource => SR.GetString(nameof(ExpressionNotDeferredQuerySource)); internal static string DeferredMemberWrongType => SR.GetString(nameof(DeferredMemberWrongType)); internal static string ArgumentWrongType(object p0, object p1, object p2) => SR.GetString(nameof(ArgumentWrongType), p0, p1, p2); internal static string ArgumentWrongValue(object p0) => SR.GetString(nameof(ArgumentWrongValue), p0); internal static string BadProjectionInSelect => SR.GetString(nameof(BadProjectionInSelect)); internal static string InvalidReturnFromSproc(object p0) => SR.GetString(nameof(InvalidReturnFromSproc), p0); internal static string WrongDataContext => SR.GetString(nameof(WrongDataContext)); internal static string BinaryOperatorNotRecognized(object p0) => SR.GetString(nameof(BinaryOperatorNotRecognized), p0); internal static string CannotAggregateType(object p0) => SR.GetString(nameof(CannotAggregateType), p0); internal static string CannotCompareItemsAssociatedWithDifferentTable => SR.GetString(nameof(CannotCompareItemsAssociatedWithDifferentTable)); internal static string CannotDeleteTypesOf(object p0) => SR.GetString(nameof(CannotDeleteTypesOf), p0); internal static string ClassLiteralsNotAllowed(object p0) => SR.GetString(nameof(ClassLiteralsNotAllowed), p0); internal static string ClientCaseShouldNotHold(object p0) => SR.GetString(nameof(ClientCaseShouldNotHold), p0); internal static string ClrBoolDoesNotAgreeWithSqlType(object p0) => SR.GetString(nameof(ClrBoolDoesNotAgreeWithSqlType), p0); internal static string ColumnCannotReferToItself => SR.GetString(nameof(ColumnCannotReferToItself)); internal static string ColumnClrTypeDoesNotAgreeWithExpressionsClrType => SR.GetString(nameof(ColumnClrTypeDoesNotAgreeWithExpressionsClrType)); internal static string ColumnIsDefinedInMultiplePlaces(object p0) => SR.GetString(nameof(ColumnIsDefinedInMultiplePlaces), p0); internal static string ColumnIsNotAccessibleThroughGroupBy(object p0) => SR.GetString(nameof(ColumnIsNotAccessibleThroughGroupBy), p0); internal static string ColumnIsNotAccessibleThroughDistinct(object p0) => SR.GetString(nameof(ColumnIsNotAccessibleThroughDistinct), p0); internal static string ColumnReferencedIsNotInScope(object p0) => SR.GetString(nameof(ColumnReferencedIsNotInScope), p0); internal static string ConstructedArraysNotSupported => SR.GetString(nameof(ConstructedArraysNotSupported)); internal static string ParametersCannotBeSequences => SR.GetString(nameof(ParametersCannotBeSequences)); internal static string CapturedValuesCannotBeSequences => SR.GetString(nameof(CapturedValuesCannotBeSequences)); internal static string IQueryableCannotReturnSelfReferencingConstantExpression => SR.GetString(nameof(IQueryableCannotReturnSelfReferencingConstantExpression)); internal static string CouldNotAssignSequence(object p0, object p1) => SR.GetString(nameof(CouldNotAssignSequence), p0, p1); internal static string CouldNotTranslateExpressionForReading(object p0) => SR.GetString(nameof(CouldNotTranslateExpressionForReading), p0); internal static string CouldNotGetClrType => SR.GetString(nameof(CouldNotGetClrType)); internal static string CouldNotGetSqlType => SR.GetString(nameof(CouldNotGetSqlType)); internal static string CouldNotHandleAliasRef(object p0) => SR.GetString(nameof(CouldNotHandleAliasRef), p0); internal static string DidNotExpectAs(object p0) => SR.GetString(nameof(DidNotExpectAs), p0); internal static string DidNotExpectTypeBinding => SR.GetString(nameof(DidNotExpectTypeBinding)); internal static string DidNotExpectTypeChange(object p0, object p1) => SR.GetString(nameof(DidNotExpectTypeChange), p0, p1); internal static string EmptyCaseNotSupported => SR.GetString(nameof(EmptyCaseNotSupported)); internal static string ExpectedNoObjectType => SR.GetString(nameof(ExpectedNoObjectType)); internal static string ExpectedBitFoundPredicate => SR.GetString(nameof(ExpectedBitFoundPredicate)); internal static string ExpectedClrTypesToAgree(object p0, object p1) => SR.GetString(nameof(ExpectedClrTypesToAgree), p0, p1); internal static string ExpectedPredicateFoundBit => SR.GetString(nameof(ExpectedPredicateFoundBit)); internal static string ExpectedQueryableArgument(object p0, object p1, object p2) => SR.GetString(nameof(ExpectedQueryableArgument), p0, p1, p2); internal static string InvalidGroupByExpressionType(object p0) => SR.GetString(nameof(InvalidGroupByExpressionType), p0); internal static string InvalidGroupByExpression => SR.GetString(nameof(InvalidGroupByExpression)); internal static string InvalidOrderByExpression(object p0) => SR.GetString(nameof(InvalidOrderByExpression), p0); internal static string Impossible => SR.GetString(nameof(Impossible)); internal static string InfiniteDescent => SR.GetString(nameof(InfiniteDescent)); internal static string InvalidFormatNode(object p0) => SR.GetString(nameof(InvalidFormatNode), p0); internal static string InvalidReferenceToRemovedAliasDuringDeflation => SR.GetString(nameof(InvalidReferenceToRemovedAliasDuringDeflation)); internal static string InvalidSequenceOperatorCall(object p0) => SR.GetString(nameof(InvalidSequenceOperatorCall), p0); internal static string ParameterNotInScope(object p0) => SR.GetString(nameof(ParameterNotInScope), p0); internal static string MemberAccessIllegal(object p0, object p1, object p2) => SR.GetString(nameof(MemberAccessIllegal), p0, p1, p2); internal static string MemberCouldNotBeTranslated(object p0, object p1) => SR.GetString(nameof(MemberCouldNotBeTranslated), p0, p1); internal static string MemberNotPartOfProjection(object p0, object p1) => SR.GetString(nameof(MemberNotPartOfProjection), p0, p1); internal static string MethodHasNoSupportConversionToSql(object p0) => SR.GetString(nameof(MethodHasNoSupportConversionToSql), p0); internal static string MethodFormHasNoSupportConversionToSql(object p0, object p1) => SR.GetString(nameof(MethodFormHasNoSupportConversionToSql), p0, p1); internal static string UnableToBindUnmappedMember(object p0, object p1, object p2) => SR.GetString(nameof(UnableToBindUnmappedMember), p0, p1, p2); internal static string QueryOperatorNotSupported(object p0) => SR.GetString(nameof(QueryOperatorNotSupported), p0); internal static string QueryOperatorOverloadNotSupported(object p0) => SR.GetString(nameof(QueryOperatorOverloadNotSupported), p0); internal static string ReaderUsedAfterDispose => SR.GetString(nameof(ReaderUsedAfterDispose)); internal static string RequiredColumnDoesNotExist(object p0) => SR.GetString(nameof(RequiredColumnDoesNotExist), p0); internal static string SimpleCaseShouldNotHold(object p0) => SR.GetString(nameof(SimpleCaseShouldNotHold), p0); internal static string TypeBinaryOperatorNotRecognized => SR.GetString(nameof(TypeBinaryOperatorNotRecognized)); internal static string UnexpectedNode(object p0) => SR.GetString(nameof(UnexpectedNode), p0); internal static string UnexpectedFloatingColumn => SR.GetString(nameof(UnexpectedFloatingColumn)); internal static string UnexpectedSharedExpression => SR.GetString(nameof(UnexpectedSharedExpression)); internal static string UnexpectedSharedExpressionReference => SR.GetString(nameof(UnexpectedSharedExpressionReference)); internal static string UnhandledBindingType(object p0) => SR.GetString(nameof(UnhandledBindingType), p0); internal static string UnhandledStringTypeComparison => SR.GetString(nameof(UnhandledStringTypeComparison)); internal static string UnhandledMemberAccess(object p0, object p1) => SR.GetString(nameof(UnhandledMemberAccess), p0, p1); internal static string UnmappedDataMember(object p0, object p1, object p2) => SR.GetString(nameof(UnmappedDataMember), p0, p1, p2); internal static string UnrecognizedExpressionNode(object p0) => SR.GetString(nameof(UnrecognizedExpressionNode), p0); internal static string ValueHasNoLiteralInSql(object p0) => SR.GetString(nameof(ValueHasNoLiteralInSql), p0); internal static string UnionIncompatibleConstruction => SR.GetString(nameof(UnionIncompatibleConstruction)); internal static string UnionDifferentMembers => SR.GetString(nameof(UnionDifferentMembers)); internal static string UnionDifferentMemberOrder => SR.GetString(nameof(UnionDifferentMemberOrder)); internal static string UnionOfIncompatibleDynamicTypes => SR.GetString(nameof(UnionOfIncompatibleDynamicTypes)); internal static string UnionWithHierarchy => SR.GetString(nameof(UnionWithHierarchy)); internal static string UnhandledExpressionType(object p0) => SR.GetString(nameof(UnhandledExpressionType), p0); internal static string IntersectNotSupportedForHierarchicalTypes => SR.GetString(nameof(IntersectNotSupportedForHierarchicalTypes)); internal static string ExceptNotSupportedForHierarchicalTypes => SR.GetString(nameof(ExceptNotSupportedForHierarchicalTypes)); internal static string NonCountAggregateFunctionsAreNotValidOnProjections(object p0) => SR.GetString(nameof(NonCountAggregateFunctionsAreNotValidOnProjections), p0); internal static string GroupingNotSupportedAsOrderCriterion => SR.GetString(nameof(GroupingNotSupportedAsOrderCriterion)); internal static string SourceExpressionAnnotation(object p0) => SR.GetString(nameof(SourceExpressionAnnotation), p0); internal static string SelectManyDoesNotSupportStrings => SR.GetString(nameof(SelectManyDoesNotSupportStrings)); internal static string SequenceOperatorsNotSupportedForType(object p0) => SR.GetString(nameof(SequenceOperatorsNotSupportedForType), p0); internal static string SkipNotSupportedForSequenceTypes => SR.GetString(nameof(SkipNotSupportedForSequenceTypes)); internal static string ComparisonNotSupportedForType(object p0) => SR.GetString(nameof(ComparisonNotSupportedForType), p0); internal static string QueryOnLocalCollectionNotSupported => SR.GetString(nameof(QueryOnLocalCollectionNotSupported)); internal static string UnsupportedNodeType(object p0) => SR.GetString(nameof(UnsupportedNodeType), p0); internal static string TypeColumnWithUnhandledSource => SR.GetString(nameof(TypeColumnWithUnhandledSource)); internal static string GeneralCollectionMaterializationNotSupported => SR.GetString(nameof(GeneralCollectionMaterializationNotSupported)); internal static string TypeCannotBeOrdered(object p0) => SR.GetString(nameof(TypeCannotBeOrdered), p0); internal static string InvalidMethodExecution(object p0) => SR.GetString(nameof(InvalidMethodExecution), p0); internal static string SprocsCannotBeComposed => SR.GetString(nameof(SprocsCannotBeComposed)); internal static string InsertItemMustBeConstant => SR.GetString(nameof(InsertItemMustBeConstant)); internal static string UpdateItemMustBeConstant => SR.GetString(nameof(UpdateItemMustBeConstant)); internal static string CouldNotConvertToPropertyOrField(object p0) => SR.GetString(nameof(CouldNotConvertToPropertyOrField), p0); internal static string BadParameterType(object p0) => SR.GetString(nameof(BadParameterType), p0); internal static string CannotAssignToMember(object p0) => SR.GetString(nameof(CannotAssignToMember), p0); internal static string MappedTypeMustHaveDefaultConstructor(object p0) => SR.GetString(nameof(MappedTypeMustHaveDefaultConstructor), p0); internal static string UnsafeStringConversion(object p0, object p1) => SR.GetString(nameof(UnsafeStringConversion), p0, p1); internal static string CannotAssignNull(object p0) => SR.GetString(nameof(CannotAssignNull), p0); internal static string ProviderNotInstalled(object p0, object p1) => SR.GetString(nameof(ProviderNotInstalled), p0, p1); internal static string InvalidProviderType(object p0) => SR.GetString(nameof(InvalidProviderType), p0); internal static string InvalidDbGeneratedType(object p0) => SR.GetString(nameof(InvalidDbGeneratedType), p0); internal static string DatabaseDeleteThroughContext => SR.GetString(nameof(DatabaseDeleteThroughContext)); internal static string CannotMaterializeEntityType(object p0) => SR.GetString(nameof(CannotMaterializeEntityType), p0); internal static string CannotMaterializeList(object p0) => SR.GetString(nameof(CannotMaterializeList), p0); internal static string CouldNotConvert(object p0, object p1) => SR.GetString(nameof(CouldNotConvert), p0, p1); } }
using BookStore.Core.Calculator; using BookStore.Core.Domain; using Moq; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace BookStore.Core.Tests.Calculator { public class OrderCalculatorTest { private readonly Order _order; private readonly Mock<IDiscount> _discountMock; private readonly OrderCalculator _calculator; public OrderCalculatorTest() { _order = new Order { Books = new List<Book> { new Book { BookName = "Unsolved Crimes", Category = BookCategory.Crime, TotalCost = 10.99m }, new Book { BookName = "A Little Love Story", Category = BookCategory.Romance, TotalCost = 2.40m }, new Book { BookName = "Heresy", Category = BookCategory.Fantasy, TotalCost = 6.80m } } }; _discountMock = new Mock<IDiscount>(); _calculator = new OrderCalculator(_order); } [Fact] public void ShouldReturnOrderTotalBeforeTax() { var total = _calculator.CalculateOrderTotal(); Assert.Equal(_order.Books.Sum(b => b.TotalCost), total); } [Fact] public void ShouldThrowExceptionIfOrderIsNull() { var exception = Assert.Throws<ArgumentNullException>(() => new OrderCalculator(null)); Assert.Equal("order", exception.ParamName); } [Theory] [InlineData(0.01)] [InlineData(0.025)] public void ShouldReturnOrderTotalBeforeTaxWithDiscountApplied(decimal discount) { Order orderWithDiscountApplied = null; _discountMock.Setup(x => x.Apply(It.IsAny<Order>())) .Returns((Order order) => { var originalValue = order.Books.First().TotalCost; order.Books.First().TotalCost = originalValue - (originalValue - discount); orderWithDiscountApplied = order; return order; }); var total = _calculator.CalculateOrderTotal(discount: _discountMock.Object); _discountMock.Verify(x => x.Apply(It.IsAny<Order>()), Times.Once); Assert.NotNull(orderWithDiscountApplied); Assert.Equal(orderWithDiscountApplied.Books.Sum(b => b.TotalCost), total); } [Theory] [InlineData(0.1)] [InlineData(0.15)] public void ShouldReturnOrderTotalAfterTax(decimal tax) { var orderTotal = _order.Books.Sum(b => b.TotalCost); var orderTotalWithTax = orderTotal + (orderTotal * tax); var total = _calculator.CalculateOrderTotal(tax); Assert.Equal(orderTotalWithTax, total); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; using ShareTradingModel; namespace Entities.Test { public class CompanyTest:EntityTest<Company> { } }
using UnityEngine; namespace CoreEngine { [ExecuteInEditMode] [RequireComponent(typeof(Renderer))] public class RendererSortingLayer : MonoBehaviour { [SortingLayer] public string m_Layer = "Default"; public int m_OrderInLayer = 0; Renderer m_Renderer; public void Awake() { m_Renderer = GetComponent<Renderer>(); } public void Start() { Update(); if ( Application.isEditor == false ) enabled = false; } public void Update() { m_Renderer.sortingLayerName = m_Layer; m_Renderer.sortingOrder = m_OrderInLayer; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CapaEntidades; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace CapaDatos { public class D_Detalle_Venta { //Metodo insertar detalle de ingreso public string InsertarDetalleVenta(E_Detalle_Venta DetalleVenta,ref SqlConnection Connection,ref SqlTransaction transaction) { string Rpta; try { SqlCommand SqlCmd = new SqlCommand("sp_insertar_detalle_venta", Connection) { CommandType = CommandType.StoredProcedure, Transaction=transaction }; SqlCmd.Parameters.AddWithValue("@id_venta", DetalleVenta.Id_venta); SqlCmd.Parameters.AddWithValue("@id_detalle_ingreso", DetalleVenta.Id_detalle_ingreso); SqlCmd.Parameters.AddWithValue("@cantidad", DetalleVenta.Cantidad); SqlCmd.Parameters.AddWithValue("@precio_venta", DetalleVenta.Precio_venta); SqlCmd.Parameters.AddWithValue("@descuento", DetalleVenta.Descuento); Rpta = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "No se puede ingresar el detalle de venta"; } catch (Exception ex) { Rpta = "ERROR " + ex.Message + ex.StackTrace; } return Rpta; } } }
using HackHW2018.Factories; using HackHW2018.Firebase; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Nez; using System.Collections.Generic; namespace HackHW2018.Scenes { public class MainScene : Scene { public int MapWidth = 0; float TimePassed = 0; public bool Paused = false; public FirebaseEventBus EventBus; public List<FirebasePlayerFormat> Players; public MainScene(List<FirebasePlayerFormat> list) { Players = list; addRenderer(new DefaultRenderer()); EventBus = new FirebaseEventBus(); } public override void Initialize() { samplerState = SamplerState.PointClamp; var background = BackgroundFactory.MakeBackground(this); var tiledMap = background.getComponent<TiledMapComponent>(); ScenePopulationFactory.PopulateScene(this, tiledMap.tiledMap.getObjectGroup("EntityLayer")); MapWidth = (int)tiledMap.width; var player1 = PlayerFactory.MakePlayer(this); //var player2 = PlayerFactory.MakePlayer(this); //var player3 = PlayerFactory.MakePlayer(this); //var player4 = PlayerFactory.MakePlayer(this); base.Initialize(); } public override void Update() { if (!Paused) { TimePassed += Time.deltaTime; Vector2 nextCameraPosition = new Vector2(camera.transform.position.X, camera.transform.position.Y); if (TimePassed >= 1.0f) { nextCameraPosition.X += 4; } if (nextCameraPosition.X + camera.bounds.width > MapWidth) { nextCameraPosition.X = MapWidth - camera.bounds.width; } camera.transform.setPosition(nextCameraPosition); base.Update(); } if (Input.isKeyPressed(Microsoft.Xna.Framework.Input.Keys.S)) Paused = !Paused; } } }
using amsdemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace amsdemo.DAL.Interface { public interface ILogin { IEnumerable<tblUser> Login(); } }
using UnityEngine; using System.Collections; using Infated.Tools; namespace Infated.CoreEngine { public class FireMagicInteractions : MonoBehaviour { public bool isFacingRight; public int damage = 0; // Start is called before the first frame update void Start() { Vector3 position = gameObject.transform.position; RaycastHit2D hit = Physics2D.Raycast(position, isFacingRight ? Vector2.right : Vector2.left); if(hit.collider != null){ Debug.Log("Raycast Start: " + hit.collider.tag); if(hit.collider.tag == "BurnableIvy"){ hit.transform.gameObject.GetComponent<Animator>().Play("IvyBurnDown"); } } } // Update is called once per frame void Update() { } void OnTriggerEnter2D(Collider2D other){ HitCheck(other); } void OnTriggerStay2D(Collider2D other){ HitCheck(other); } void HitCheck(Collider2D other){ Debug.Log("HitCheck"); if(other.tag == "Enemy"){ Health hp = other.GetComponent<Health>(); if(hp != null){ hp.Damage(damage, this.gameObject, 0.5f, 0.5f, true); Debug.Log("Dealt: " + damage + " fire damage"); } } } protected virtual void PlaySound(AudioClip sfx) { // we create a temporary game object to host our audio source GameObject temporaryAudioHost = new GameObject("TempAudio"); // we set the temp audio's position // we add an audio source to that host AudioSource audioSource = temporaryAudioHost.AddComponent<AudioSource>() as AudioSource; // we set that audio source clip to the one in paramaters audioSource.clip = sfx; // we set the audio source volume to the one in parameters audioSource.volume = 100; // we start playing the sound audioSource.Play(); Destroy(temporaryAudioHost, sfx.length); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; namespace LuckyGitlabStatWebAPI.DAO { public class ConnectDB { //数据库用户名 private static string userName = "cuichongyang"; //数据库密码 private static string password = "Lucky.2016"; //连接的服务器地址 private static string dataSource = "luckygitlabstat.database.windows.net"; //数据库名称 private static string sampleDatabaseName = "luckygitlabstat"; /// <summary> /// 公共代码,连接数据库 /// </summary> /// <returns></returns> public SqlConnectionStringBuilder ConnectDataBase() { SqlConnectionStringBuilder connString2Builder; connString2Builder = new SqlConnectionStringBuilder(); connString2Builder.DataSource = dataSource; connString2Builder.InitialCatalog = sampleDatabaseName; connString2Builder.Encrypt = true; connString2Builder.TrustServerCertificate = false; connString2Builder.UserID = userName; connString2Builder.Password = password; return connString2Builder; } } }
using Microsoft.Owin.Security; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace iTemplate.Web.Models { // Modified this from private to public and add the setter //public IAuthenticationManager AuthenticationManager //{ // get // { // if (_authnManager == null) // _authnManager = HttpContext.GetOwinContext().Authentication; // return _authnManager; // } // set { _authnManager = value; } //} }
using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Kuli.Rendering { public class FragmentExportService { private readonly ILogger<FragmentExportService> _logger; private readonly PublishDirectoryWriter _outputWriter; private readonly FragmentRenderer _renderer; private readonly SiteRenderingContext _siteRenderingContext; public FragmentExportService(ILogger<FragmentExportService> logger, FragmentRenderer renderer, SiteRenderingContext siteContext, PublishDirectoryWriter outputWriter) { _logger = logger; _renderer = renderer; _siteRenderingContext = siteContext; _outputWriter = outputWriter; } public async Task ExportFragmentsAsync(CancellationToken cancellationToken) { _logger.LogInformation("Rendering fragments..."); var sw = Stopwatch.StartNew(); foreach (var fragmentEntry in _siteRenderingContext.Fragments) { var fragment = fragmentEntry.Value; var result = await _renderer.RenderFragmentAsync(fragment); await _outputWriter.WriteTextFileAsync(fragment.Name, result, "html"); } sw.Stop(); _logger.LogInformation("Rendered {count} fragments in {time}ms", _siteRenderingContext.Fragments.Count, sw.ElapsedMilliseconds); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WishCardBtn : MonoBehaviour { //Button Image의 sprite를 변경해서 선택된 버튼의 색깔이 바뀌도록 한다. public Image m_image; public Sprite m_normalImg; public Sprite m_selectImg; //text값을 읽어와서 소원이 값인지 확인한다. public Text m_text; //선택됬는지 여부를 결정한다. public bool m_bisSelect = false; public void SelectBtn() { m_bisSelect = !m_bisSelect; if (m_bisSelect) { m_image.sprite = m_selectImg; GameManager.Instance.m_wishCardPopup.SetSelectedBtn(this); } else { m_image.sprite = m_normalImg; GameManager.Instance.m_wishCardPopup.UnselectBtn(); } } public void UnselectBtn() { m_bisSelect = false; m_image.sprite = m_normalImg; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assingment1 { class Program { static void Main(string[] args) { try { Console.WriteLine("Enter the Book ID "); int id = Int32.Parse(Console.ReadLine()); Console.WriteLine("Enter the Book Name"); string Bname = Console.ReadLine(); if (Bname.Length < 1) { throw new AutherException("Book Name is mandatory"); } Console.WriteLine("Enter the Author Name"); string Aname = Console.ReadLine(); if (Aname.Length < 1) { throw new AutherException("Author Name is mandatory"); } Console.WriteLine("Enter the Book Gener"); string Gener = Console.ReadLine(); Console.WriteLine("Enter the Book Price "); Double Bprice = double.Parse(Console.ReadLine()); Book b = new Book(id, Bname, Aname, Gener, Bprice); b.ToString(); // Book b2 = new Book(); //b2.Author = Console.ReadLine(); //b2.BookID = Console.Read(); } catch (AutherException ex) { Console.WriteLine(ex.Message); } catch (ArgumentOutOfRangeException outOfRange) { Console.WriteLine("Error: {0}", outOfRange.Message); } finally { Console.WriteLine("Program ended"); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SprintFour.Commands { public class CursorDownCommand : ICommand { public void Execute() { SprintFourGame.GetInstance().cursor.MoveCursorDown(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using InfoPole.Core.Entities; using InfoPole.Core.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace InfoPole.Controllers { [Produces("application/json")] [Route("Tag")] public class TagsController : Controller { private IEnumerable<Tag> _tags; public TagsController(IServerCacheService cache) { _tags = cache.GetList<Tag>(); } [HttpGet] public IActionResult Tag(long markupTagId) { var tags = _tags.Where(mt => mt.MarkupTagId == markupTagId).ToList(); return Ok(tags); } } }
using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace Sem { public static class SaveImage { public static void Save(IApplicationBuilder app) { app.Run(async context => { var id = context.Session.GetInt32("user_id"); if (id == null) { context.Response.Headers.Add("status", "not_registered"); return; } var files = Directory.GetFiles(@"wwwroot/Resources/UserImages/", id + ".*"); foreach (var x in files) File.Delete(x); //var filename = context.Request.Headers["filename"]; var file = context.Request.Form.Files.GetFile("image"); //var a = file.ContentType; var extension = Path.GetExtension(file.FileName); // var extension = "jpg";//context.Request.ContentType.Split('/')[1]; var fileStream = File.Open(@$"wwwroot\Resources\UserImages\{id}{extension}", FileMode.Create); await file.CopyToAsync(fileStream); //context.Request.Body.Close(); fileStream.Close(); }); } } }
using MediSutBackEnd.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using static System.Net.HttpStatusCode; namespace MediSutBackEnd.Controllers { //[RoutePrefix("Product")] public class ProductController : ApplicationController { //GET: api/Product public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Product/5 [HttpGet] [Route("api/Product/PerMonth")] public HttpResponseMessage PerMonth(string month) { Connection.Open(); using (SqlCommand cmd = new SqlCommand("SP_DISCOUNT_PERMOUNTH", Connection)) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MONTH", month); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { List<Discount> discounts = new List<Discount>(); while (reader.Read()) { discounts.Add(new Discount() { Id = reader.GetInt32(0), IdClient = reader.GetInt32(1), IdProduct = reader.GetInt32(2), DiscountRate = reader.GetDecimal(3), DiscountDate = reader.GetDateTime(4) }); } Connection.Close(); return new HttpResponseMessage(OK) { Content = new StringContent(JsonConvert.SerializeObject(discounts)) }; } else { Connection.Close(); return new HttpResponseMessage(HttpStatusCode.NotFound); } } } } // POST: api/Product public void Post([FromBody]string value) { } // PUT: api/Product/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Product/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Text; namespace FanIn_Fanout { public static class DownloadReporter { internal static void PrintResults(List<WebsiteDataModel> results) { Console.WriteLine(); foreach (var item in results) { //resultsWindow.Text += $"{ item.WebsiteUrl } downloaded: { item.WebsiteData.Length } characters long.{ Environment.NewLine }"; Console.WriteLine($"{ item.WebsiteUrl } downloaded: { item.WebsiteData.Length } characters long.{ Environment.NewLine }"); } } internal static void ReportWebSiteInfo(WebsiteDataModel dataModel) { Console.WriteLine($"{ dataModel.WebsiteUrl } downloaded: { dataModel.WebsiteData.Length } characters long.{ Environment.NewLine }"); } } }
using System; using System.Text.RegularExpressions; using TestCase.Basics; using TestCase.Contracts; using TestCase.Factory.Abstract; using TestCase.Factory.Concrete; using TestCase.Workspaces; namespace TestCase { class Program { //5x5 (0, 0) (1, 3) (4, 4) (4, 2) (4, 2) (0, 1) (3, 2) (2, 3) (4, 1) static void Main(string[] args) { try { WorkspaceFactory pizzaWorkspaceFactory = new PizzaWorkspaceFactory(); IRouteProccesor pizzaWorkspace; if (string.Join(" ", args) == "") { Console.WriteLine("Input size of map and delivery points: "); pizzaWorkspace = pizzaWorkspaceFactory.CreateWorkspace(Console.ReadLine()); } else { pizzaWorkspace = pizzaWorkspaceFactory.CreateWorkspace(string.Join(" ", args)); } pizzaWorkspace.ProccesRoute(); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC.Models; namespace MVC.Controllers { public class MyController : Controller { //Cannot be Accessed from outside string Get() => "1234"; //Cannot be Accessed from outside [NonAction] public string Get2() => "5678"; //Can be Accessed from outside with GET and POST (Default Behavior) public string Get3() => "9999"; //Can be Accessed from outside with GET [HttpGet] public string Get4() => "9999"; //Can be Accessed from outside with GET [AcceptVerbs(HttpVerbs.Get)] public string Get5() => "9999"; //Can be Accessed from outside with GET and POST [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] public string Get6() => "9999"; [HttpGet] public ActionResult GetView1() => View("View1"); [HttpGet] public ActionResult GetView2() { Class1 a = new Class1 { A = "A", B = "B" }; ViewBag.HelloBag = a; //ViewData.Add("Hello", a); return View("TestView"); } [HttpGet] public ActionResult GetView3() { Class1 a = new Class1 { A = "A", B = "B" }; return View("StrongView", a); } [HttpPost] public void PostByModelBinder(Class1 c) { bool isValid = ModelState.IsValid; if (!isValid) { var values = ModelState.Values; List<ModelErrorCollection> errors = new List<ModelErrorCollection>(); foreach(ModelState v in values) { errors.Add(v.Errors); } } else { } } [HttpPost] public void PostByModelBinder2(string A, string B) { bool isValid = ModelState.IsValid; if (!isValid) { var values = ModelState.Values; List<ModelErrorCollection> errors = new List<ModelErrorCollection>(); foreach (ModelState v in values) { errors.Add(v.Errors); } } Class1 c = new Class1 { A = A, B = B }; } [HttpPost] public void PostManual() { Class1 c = new Class1(); c.A = Request.Form["A"]; c.B = Request.Form["B"]; } [HttpGet] public string WriteHTML() { return @"<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </body> </html>"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; //using Google.Protobuf.Examples.MessageProtocol; namespace WcfService1 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract] public interface IService1{ [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllCustomer/")] string GetAllCustomer(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllOrder/")] string GetAllOrder(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllEmployee/")] string GetAllEmployee(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllCategory/")] string GetAllCategory(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllPurchase/")] string GetAllPurchase(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllSupplier/")] string GetAllSupplier(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomer/{msj}")] string Get_Customer(string msj); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostCustomer")] string PostCustomer(Customer str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWCustomer")] string PostNEWCustomer(Customer str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWCategory")] string PostNEWCategory(Category str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWEmployee")] string PostNEWEmployee(Employee str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWOrder")] string PostNEWOrder(Order_Check str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWProduct")] string PostNEWProduct(Product str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWPurchase")] string PostNEWPurchase(Purchase_Item str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostNEWSupplier")] string PostNEWSupplier(Supplier str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/UpdateCustomer")] string UpdateCustomer(Customer str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/UpdateProduct")] string PostUpdateProduct(Product str); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "DeleteCustomer/{msj}")] string DeleteCustomer(string msj); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "UpdateOrder?id={id}&status={status}")] string UpdateOrder(string id, string status); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "DeleteSupplier/{msj}")] string DeleteSupplier(string msj); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetOrders/{suc}")] string GetOrders(string suc); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostOrder")] string PostOrder(Order_Check str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostCategory")] string PostCategory(Category str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostLogin")] string PostLogin(LoginAuth str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostLoginEmployee")] string PostLoginEmployee(LoginEmployee str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostEmployee")] string PostEmployee(Employee str); /* [OperationContract] [WebGet(UriTemplate = "/GetCustomer/{}?params={paramList}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string GetCustomer(string paramList); */ //get method of Products [OperationContract] [WebGet(UriTemplate = "/GetProducts?params={paramList}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] String GetProducts(string paramList); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostProduct")] string PostProduct(Product str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostPurchaseItem")] string Post_Purchase_Item(Purchase_Item str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostSupplier")] string Post_Supplier(Supplier str); [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/PostShop")] string Post_Shop(GenericQuery str); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetOrder/{msj}")] string Get_Order(string msj); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetStadistics/{msj}")] string Get_Stadistics(string msj); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetBoffice/")] string GetBoffice(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "DeleteProduct/{idP}")] string DeleteProduct(string idP); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetSupplier/")] string GetSupplier(); [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "PostBoffice/{Name}")] string PostBoffice(string Name); /* [OperationContract] [WebGet(UriTemplate = "/prueba?param={id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string Product_Quantity(int id);*/ } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CRM.Model { public class Product:BaseEntity { public Product() { OfferItems = new HashSet<OfferItem>(); Customers = new HashSet<Customer>(); OrderItems = new HashSet<OrderItem>(); } [Display(Name="Ürün Adı")] public string Name { get; set; } [Display(Name = "Açıklama")] public string Description { get; set; } [Display(Name = "Seri Numarası")] public string SerialNumber { get; set; } [Display(Name = "Alış Fiyatı")] public decimal BuyingPrice { get; set; } [Display(Name="Stok")] public int Stock { get; set; } [Display(Name = "Kategori")] public Guid CategoryId { get; set; } public virtual Category Category { get; set; } public virtual ICollection<OrderItem> OrderItems { get; set; } public virtual ICollection<OfferItem> OfferItems { get; set; } public virtual ICollection<Customer> Customers { get; set; } } }
using ProConstructionsManagment.Desktop.Commands; using ProConstructionsManagment.Desktop.Managers; using ProConstructionsManagment.Desktop.Messages; using ProConstructionsManagment.Desktop.Models; using ProConstructionsManagment.Desktop.Services; using ProConstructionsManagment.Desktop.Views.Base; using Serilog; using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace ProConstructionsManagment.Desktop.Views.ProjectRecruitment { public class ProjectRecruitmentViewModel : ViewModelBase { private readonly IProjectsService _projectsService; private readonly IPositionsService _positionsService; private readonly IMessengerService _messengerService; private readonly IShellManager _shellManager; private string _projectId; private string _projectRecruitmentId; private string _positionId; private int _position; private int _requiredNumberOfEmployees; private ObservableCollection<Models.Position> _positions; public ProjectRecruitmentViewModel(IProjectsService projectsService, IPositionsService positionsService, IMessengerService messengerService, IShellManager shellManager) { _projectsService = projectsService; _messengerService = messengerService; _positionsService = positionsService; _shellManager = shellManager; messengerService.Register<ProjectIdMessage>(this, msg => ProjectId = msg.ProjectId); messengerService.Register<ProjectRecruitmentIdMessage>(this, msg => ProjectRecruitmentId = msg.ProjectRecruitmentId); } public string ProjectId { get => _projectId; set => Set(ref _projectId, value); } public string ProjectRecruitmentId { get => _projectRecruitmentId; set => Set(ref _projectRecruitmentId, value); } public string PositionId { get => _positionId; set => Set(ref _positionId, value); } public int Position { get => _position; set => Set(ref _position, value); } public int RequiredNumberOfEmployees { get => _requiredNumberOfEmployees; set => Set(ref _requiredNumberOfEmployees, value); } public ObservableCollection<Models.Position> Positions { get => _positions; set => Set(ref _positions, value); } private ValidationResult BuildValidation() { if (string.IsNullOrWhiteSpace(RequiredNumberOfEmployees.ToString()) || string.IsNullOrWhiteSpace(Position.ToString())) { return new ValidationResult(false); } return new ValidationResult(true); } public async Task Initialize() { try { _shellManager.SetLoadingData(true); Positions = await _positionsService.GetAllPositions(); var projectRecruitment = await _projectsService.GetProjectRecruitmentById(ProjectRecruitmentId); var position = await _positionsService.GetPositionById(projectRecruitment.PositionId); var positionIndex = Positions .ToList() .FindIndex(x => x.Id == position.Id); Position = positionIndex; RequiredNumberOfEmployees = projectRecruitment.RequiredNumberOfEmployees; } catch (Exception e) { Log.Error(e, "Failed loading project recruitment view"); MessageBox.Show("Coś poszło nie tak podczas pobierania danych"); } finally { _shellManager.SetLoadingData(false); } } public ICommand UpdateProjectRecruitmentCommand => new AsyncRelayCommand(UpdateProjectRecruitment); private async Task UpdateProjectRecruitment() { if (BuildValidation().IsSuccessful) { try { _shellManager.SetLoadingData(true); var data = new Models.ProjectRecruitment { Id = ProjectId, PositionId = PositionId, RequiredNumberOfEmployees = RequiredNumberOfEmployees, }; var result = await Task.Run(() => _projectsService.UpdateProjectRecruitment(data, ProjectId)); if (result.IsSuccessful) { Log.Information($"Successfully edited project recruitment ({data.Id})"); MessageBox.Show("Pomyślnie zapisano rekrutacje"); } } catch (Exception e) { Log.Error(e, "Failed editing project recruitment"); MessageBox.Show( "Coś poszło nie tak podczas dodawania projektu, proszę spróbować jeszcze raz. Jeśli problem nadal występuje, skontakuj się z administratorem oprogramowania"); } finally { _shellManager.SetLoadingData(false); } } else { MessageBox.Show("Uzupełnij wymagane pola"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Zelo.Common.CustomAttributes; namespace Zelo.DBModel { [Table(Name = "T_Medical_HisDetail")] public class TMedicHisDetailInfo:TMedicalHisDetail { public List<TMedicalHisDetailPic> PicList { set; get; } } }
 using System; using System.ComponentModel; using Abp.Application.Services.Dto; using Abp.AutoMapper; namespace MyCompanyName.AbpZeroTemplate.Card.Dtos { /// <summary> /// 财务明细列表Dto /// </summary> [AutoMapFrom(typeof(FinancialDetails))] public class FinancialDetailsListDto : EntityDto<long> { /// <summary> /// 0收入2支出 /// </summary> [DisplayName("0收入2支出")] public int Type { get; set; } /// <summary> /// 0系统 /// </summary> [DisplayName("0系统")] public int PayType { get; set; } /// <summary> /// 交易金额 /// </summary> [DisplayName("交易金额")] public int Money { get; set; } /// <summary> /// 当前余额 /// </summary> [DisplayName("当前余额")] public int NowMoney { get; set; } /// <summary> /// 创建时间 /// </summary> [DisplayName("创建时间")] public DateTime CreationTime { get; set; } public string Desc { get; set; } /// <summary> /// 备注 /// </summary> public string Mark { get; set; } /// <summary> /// 用户名称 /// </summary> public string UserUserName { get; set; } /// <summary> /// 操作人 /// </summary> public string OperUserName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace BoxDragXF { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); this.LayoutChanged += MainPage_LayoutChanged; } private void MainPage_LayoutChanged(object sender, EventArgs e) { button1.Clicked += delegate { var rc = box1.Bounds; rc.X = 50; rc.Y = 50; box1.LayoutTo(rc); }; buttonLeft.Clicked += delegate { var rc = box1.Bounds; rc.X -= 20; box1.LayoutTo(rc); }; buttonRight.Clicked += delegate { var rc = box1.Bounds; rc.X += 20; box1.LayoutTo(rc); }; buttonUp.Clicked += delegate { var rc = box1.Bounds; rc.Y -= 20; box1.LayoutTo(rc); }; buttonDown.Clicked += delegate { var rc = box1.Bounds; rc.Y += 20; box1.LayoutTo(rc); }; } } }
using System.Collections.Generic; namespace KataBowling { public class Partie { private readonly IList<int> _lancers = new List<int>(); public void NouveauLancer(int quilles) { _lancers.Add(quilles); } public int CalculeScore() { var score = 0; var indiceLancer = 0; for (var i = 0; i < 10; i++) { if (EstStrike(indiceLancer)) { score += 10 + BonusStrike(indiceLancer); indiceLancer++; } else if (EstSpare(indiceLancer)) { score += 10 + BonusSpare(indiceLancer); indiceLancer += 2; } else { score += _lancers[indiceLancer] + _lancers[indiceLancer + 1]; indiceLancer += 2; } } return score; } private bool EstStrike(int indiceLancer) { return _lancers[indiceLancer] == 10; } private int BonusStrike(int indiceLancer) { return _lancers[indiceLancer + 1] + _lancers[indiceLancer + 2]; } private bool EstSpare(int indiceLancer) { return _lancers[indiceLancer] + _lancers[indiceLancer + 1] == 10; } private int BonusSpare(int indiceLancer) { return _lancers[indiceLancer + 2]; } } }
using System; using System.Collections.Generic; using TestsGenerator.IO; namespace TestsGenerator.UsageExample { class Program { static void Main(string[] args) { TestsGeneratorConfig config = new TestsGeneratorConfig { ReadPaths = new List<string> { "../../SimpleTestFile.cs", "../../ExtendedTestFile.cs" }, Writer = new AsyncFileWriter() { Directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }, ReadThreadCount = 2, WriteThreadCount = 2 }; new TestsGenerator(config).Generate().Wait(); Console.WriteLine("Generation completed"); Console.ReadKey(); } } }
using ReadyGamerOne.Utility; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace ReadyGamerOne.ScriptableObjects { public class AnimationCurveAsset:ScriptableObject { #if UNITY_EDITOR [MenuItem("ReadyGamerOne/Create/AnimationCurveAsset")] public static void CreateAsset() { EditorUtil.CreateAsset<AnimationCurveAsset>("AnimationCurveAsset"); } #endif public AnimationCurve curve; } }
/* 04. Write a program that compares two text files line by line and prints the number of lines that are the same and the number of lines that are different. * Assume the files have equal number of lines. */ using System; using System.IO; using System.Collections.Generic; class CompareTextFiles { static void Main() { List<string> firstInput = new List<string>(); List<string> secondInput = new List<string>(); StreamReader firstReader = new StreamReader("../../first_input.txt"); using (firstReader) { string line = firstReader.ReadLine(); while (line != null) { firstInput.Add(line); line = firstReader.ReadLine(); } } StreamReader secondReader = new StreamReader("../../second_input.txt"); using (secondReader) { string line = secondReader.ReadLine(); while (line != null) { secondInput.Add(line); line = secondReader.ReadLine(); } } if (firstInput.Count != secondInput.Count) { Console.WriteLine("The files length must be equal!"); return; } else { int equalLines = 0; int differentLines = 0; for (int i = 0; i < firstInput.Count; i++) { if (firstInput[i] != secondInput[i]) { differentLines++; } else { equalLines++; } } Console.WriteLine("Number of equal lines: {0}", equalLines); Console.WriteLine("Number of different lines: {0}", differentLines); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dominio; using System.Data.SqlClient; namespace Negocio { public class ClienteNegocio { public List<Cliente> listar() { List<Cliente> lista = new List<Cliente>(); AccesoDatos accesoDatos = new AccesoDatos(); Cliente cliente; try { accesoDatos.SetearConsulta("select Id, DNI, Nombre, Apellido, Email, Direccion, Ciudad, CodigoPostal,FechaRegistro from clientes"); accesoDatos.AbrirConexion(); accesoDatos.ejecutarConsulta(); while (accesoDatos.Lector.Read()) { cliente = new Cliente(); cliente.Id = (Int64)accesoDatos.Lector["Id"]; cliente.DNI = (int)accesoDatos.Lector["DNI"]; cliente.Nombre = accesoDatos.Lector["Nombre"].ToString(); cliente.Apellido = accesoDatos.Lector["Apellido"].ToString(); cliente.Email = accesoDatos.Lector["Email"].ToString(); cliente.Direccion = accesoDatos.Lector["Direccion"].ToString(); cliente.Ciudad = accesoDatos.Lector["Ciudad"].ToString(); cliente.CP = accesoDatos.Lector["CodigoPostal"].ToString(); cliente.Fecha_registro = (DateTime)accesoDatos.Lector["FechaRegistro"]; } return lista; } catch (Exception ex) { throw ex; } finally { accesoDatos.cerrarConexion(); } } public Cliente traer(int dni) { AccesoDatos accesoDatos = new AccesoDatos(); Cliente cliente; try { cliente = new Cliente(); accesoDatos.SetearConsulta("Select Id, DNI, Nombre, Apellido, Email, Direccion, Ciudad, CodigoPostal,FechaRegistro from clientes where DNI=" + dni); accesoDatos.AbrirConexion(); accesoDatos.ejecutarConsulta(); while (accesoDatos.Lector.Read()) { cliente.DNI = (int)accesoDatos.Lector["dni"]; cliente.Nombre = accesoDatos.Lector["Nombre"].ToString(); cliente.Apellido = accesoDatos.Lector["Apellido"].ToString(); cliente.Email = accesoDatos.Lector["Email"].ToString(); cliente.Direccion = accesoDatos.Lector["direccion"].ToString(); cliente.Ciudad = accesoDatos.Lector["ciudad"].ToString(); cliente.CP = accesoDatos.Lector["CodigoPostal"].ToString(); } return cliente; } catch (Exception ex) { throw ex; } finally { accesoDatos.cerrarConexion(); } } } }
namespace XShare.Services.Data { using System; using System.Linq; using XShare.Data.Models; using XShare.Data.Repositories; using XShare.Services.Data.Contracts; public class AccidentService : IAccidentService { private readonly IRepository<Accident> accidents; public AccidentService(IRepository<Accident> accidents) { this.accidents = accidents; } public Accident AccidentById(int id) { object serachId = id; return this.accidents.GetById(id); } public void DeleteById(int id) { Accident itemToDelet = this.accidents.GetById(id); if (itemToDelet != null) { this.accidents.Delete(itemToDelet); this.accidents.SaveChanges(); } } public Accident GetById(int id) { return this.accidents.GetById(id); } public void UpadteAccident(Accident accidentToUpdate) { this.accidents.Update(accidentToUpdate); this.accidents.SaveChanges(); } public IQueryable<Accident> GetFiltered(int? id,string userName, string model, string carType, string location, string descriptipn) { var accidentsQuery = this.accidents.All(); if (id != null && id > 0) { accidentsQuery = accidentsQuery.Where(a => a.Id == id); } if (!string.IsNullOrEmpty(userName)) { accidentsQuery = accidentsQuery.Where(a => a.User.UserName.Contains(userName)); } if (!string.IsNullOrEmpty(model)) { accidentsQuery = accidentsQuery.Where(a => a.Car.Description.Contains(model)); } if (!string.IsNullOrEmpty(carType)) { accidentsQuery = accidentsQuery.Where(a => a.Car.CarType.ToString() == carType); } if (!string.IsNullOrEmpty(location)) { accidentsQuery = accidentsQuery.Where(a => a.Location.Contains(location)); } if (!string.IsNullOrEmpty(descriptipn)) { accidentsQuery = accidentsQuery.Where(a => a.Description.Contains(descriptipn)); } return accidentsQuery; } public IQueryable<Accident> AllAccident() { return this.accidents.All(); } public Accident CreateAccident(string location, string picture, string description, int carId, string userId) { var accidentToAdd = new Accident { Location = location, Picture = picture, Date = DateTime.UtcNow, Description = description, CarId = carId, UserId = userId }; this.accidents.Add(accidentToAdd); this.accidents.SaveChanges(); return accidentToAdd; } } }
using System; namespace DelegateChainApp { class Program { delegate void AllCalc(int x, int y); // 대리자 선언 static void Plus(int a, int b) { Console.WriteLine($"a + b = {a + b}"); } static void Minus(int a, int b) { Console.WriteLine($"a - b = {a - b}"); } static void Multiple(int a, int b) { Console.WriteLine($"a * b = {a * b}"); } static void Divide(int a, int b) { Console.WriteLine($"a / b = {a / b}"); } static void Main(string[] args) { Console.WriteLine("Hello World!"); AllCalc all = new AllCalc(Plus) + new AllCalc(Minus) + new AllCalc(Multiple) + new AllCalc(Divide); all(10, 2); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using Microsoft.Extensions.DependencyInjection; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Modules.Groups.Components; using DotNetNuke.Common; using DotNetNuke.Framework; using DotNetNuke.Abstractions; #endregion namespace DotNetNuke.Modules.Groups { /// ----------------------------------------------------------------------------- /// <summary> /// The ViewSocialGroups class displays the content /// </summary> /// ----------------------------------------------------------------------------- public partial class View : GroupsModuleBase { private readonly INavigationManager _navigationManager; public View() { _navigationManager = DependencyProvider.GetRequiredService<INavigationManager>(); } #region Event Handlers protected override void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { Load += Page_Load; } /// ----------------------------------------------------------------------------- /// <summary> /// Page_Load runs when the control is loaded /// </summary> /// ----------------------------------------------------------------------------- private void Page_Load(object sender, EventArgs e) { try { JavaScript.RequestRegistration(CommonJs.DnnPlugins); if (GroupId < 0) { if (TabId != GroupListTabId && !UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) { Response.Redirect(_navigationManager.NavigateURL(GroupListTabId)); } } GroupsModuleBase ctl = (GroupsModuleBase)LoadControl(ControlPath); ctl.ModuleConfiguration = this.ModuleConfiguration; plhContent.Controls.Clear(); plhContent.Controls.Add(ctl); } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } #endregion } }
using PlatformRacing3.Common.Customization; using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; namespace PlatformRacing3.Server.Game.Commands.Match; internal class RemoveHatsCommand : ICommand { private readonly CommandManager commandManager; public RemoveHatsCommand(CommandManager commandManager) { this.commandManager = commandManager; } public string Permission => "command.removehats.use"; public void OnCommand(ICommandExecutor executor, string label, ReadOnlySpan<string> args) { HashSet<Hat> hats = new HashSet<Hat>(); for (int i = 1; i < args.Length; i++) { Hat hat; if (uint.TryParse(args[i], out uint hatId)) { hat = (Hat)hatId; } else if (!Enum.TryParse(args[i], ignoreCase: true, out hat)) { executor.SendMessage($"Unable to find part with name {args[i]}"); return; } hats.Add(hat); } IEnumerable<ClientSession> targets; if (args.Length >= 1) { targets = this.commandManager.GetTargets(executor, args[0]); } else if (executor is ClientSession session) { targets = new ClientSession[] { session }; } else { executor.SendMessage("No target"); return; } int targetsMatched = 0; foreach (ClientSession target in targets) { if (target is { MultiplayerMatchSession.Match: { } match, MultiplayerMatchSession.MatchPlayer: { } matchPlayer }) { targetsMatched++; if (hats.Count == 0) { match.RemoveHatsFromPlayer(matchPlayer); } else { foreach (Hat hat in hats) { match.RemoveHatFromPlayer(matchPlayer, hat); } } } } executor.SendMessage($"Effected {targetsMatched} clients"); } }
 #region Usings using Zengo.WP8.FAS.Helpers; using Zengo.WP8.FAS.Models; using Zengo.WP8.FAS.Resources; using Zengo.WP8.FAS.WebApi.Responses; using Zengo.WP8.FAS.WepApi; using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; #endregion namespace Zengo.WP8.FAS.Controls { public class UpdateAccountStartingEventArgs : EventArgs { public int Count { get; set; } } public class UpdateAccountCompletedEventArgs : EventArgs { public bool Success { get; set; } public string Message { get; set; } } public partial class MyAccountControl : UserControl { public class ErrorAndControl { public FieldTitleAndError Error { get; set; } public UIElement Element { get; set; } } #region Events public event EventHandler<EventArgs> FirstFavouriteTeamPressed; public event EventHandler<EventArgs> SecondFavouriteTeamPressed; public event EventHandler<EventArgs> MyCountryPressed; public event EventHandler<UpdateAccountStartingEventArgs> UpdateAccountStarting; public event EventHandler<UpdateAccountCompletedEventArgs> UpdateAccountCompleted; #endregion #region Fields UserApi userApi; string firstnameWatermark = AppResources.FirstnameWatermark; string lastnameWatermark = AppResources.SurnameWatermark; string mobileWatermark = AppResources.MobileWatermark; List<ErrorAndControl> errors; #endregion #region Constructors public MyAccountControl() { InitializeComponent(); // Initialise an instance of the user api userApi = new UserApi(); userApi.UpdateCompleted += userApi_UpdateCompleted; // Subscribe to the pressed event of the team selectors FavouriteTeam1.TeamPressed += FavouriteTeam1_TeamPressed; FavouriteTeam2.TeamPressed += FavouriteTeam2_TeamPressed; MyCountry.CountryPressed += MyCountry_CountryPressed; // Put all of the error controls in a list errors = new List<ErrorAndControl>(); int index = 0; foreach (object control in LayoutRoot.Children) { index += 1; if (control is FieldTitleAndError) { ErrorAndControl errorAndControl = new ErrorAndControl() { Error = control as FieldTitleAndError, Element = LayoutRoot.Children[index] }; errors.Add(errorAndControl); } } // Set the titles ResetErrors(); } #endregion #region EventHandlers /// <summary> /// They have clicked on the favourite team control ("Please choose a favourite team") /// </summary> void FavouriteTeam1_TeamPressed(object sender, EventArgs e) { if (FirstFavouriteTeamPressed != null) { FirstFavouriteTeamPressed(this, new EventArgs()); } } void FavouriteTeam2_TeamPressed(object sender, EventArgs e) { if (SecondFavouriteTeamPressed != null) { SecondFavouriteTeamPressed(this, new EventArgs()); } } void MyCountry_CountryPressed(object sender, EventArgs e) { if (MyCountryPressed != null) { MyCountryPressed(this, new EventArgs()); } } void userApi_UpdateCompleted(object sender, UpdateEventArgs e) { if (e.ConnectionError == ApiConnectionResult.Good) { // Update the users details in the database App.ViewModel.DbViewModel.UpdateUser(e.ServerResponse.Details); // Raise message to containing page telling them we are completed a login if (UpdateAccountCompleted != null) { UpdateAccountCompleted(this, new UpdateAccountCompletedEventArgs() { Message = AppResources.UpdateAccountSuccess, Success = true }); } } else if (e.ConnectionError == ApiConnectionResult.Bad) { if (UpdateAccountCompleted != null) { UpdateAccountCompleted(this, new UpdateAccountCompletedEventArgs() { Message = e.FriendlyMessage, Success = false }); } } else { if (UpdateAccountCompleted != null) { UpdateAccountCompleted(this, new UpdateAccountCompletedEventArgs() { Message = e.FriendlyMessage, Success = false }); } } e.ShowDebugMessage(); } internal void SetFavouriteTeamFromHiddenId(ClubRecord team1, ClubRecord team2, CountryRecord myCountry) { FavouriteTeam1.Refresh(team1); FavouriteTeam2.Refresh(team2); MyCountry.Refresh(myCountry); } #endregion #region This Controls Event Handlers private void UserControl_Loaded(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(TextBoxFirstName.Text)) { TextBoxFirstName.Text = firstnameWatermark; TextBoxFirstName.Foreground = App.AppConstants.WatermarkTextColourBrush; } if (string.IsNullOrEmpty(TextBoxLastName.Text)) { TextBoxLastName.Text = lastnameWatermark; TextBoxLastName.Foreground = App.AppConstants.WatermarkTextColourBrush; } if (string.IsNullOrEmpty(TextBoxMobile.Text)) { TextBoxMobile.Text = mobileWatermark; TextBoxMobile.Foreground = App.AppConstants.WatermarkTextColourBrush; } //if (string.IsNullOrEmpty(TextBoxTeamName.Text)) //{ // TextBoxTeamName.Text = teamNameWatermark; // TextBoxTeamName.Foreground = App.AppConstants.WatermarkTextColourBrush; //} } #endregion #region First Name Focus Handlers private void TextBoxFirstName_GotFocus(object sender, RoutedEventArgs e) { App.AppConstants.SetTextBoxFocusColours(sender as TextBox); // if our watermark is set in the control if (TextBoxFirstName.Text == firstnameWatermark) { TextBoxFirstName.Text = string.Empty; TextBoxFirstName.Foreground = App.AppConstants.NormalTextColourBrush; } } private void TextBoxFirstName_LostFocus(object sender, RoutedEventArgs e) { // If nothing has been entered on leaving our textbox, then set our watermark again if (TextBoxFirstName.Text == string.Empty) { TextBoxFirstName.Text = firstnameWatermark; TextBoxFirstName.Foreground = App.AppConstants.WatermarkTextColourBrush; } } /// <summary> /// Also validate on a key up /// </summary> private void TextBoxFirstName_KeyUp(object sender, KeyEventArgs e) { // Reset the errors if a key has been pressed if (e.Key != Key.Unknown) { ResetErrors(); } // remove focus from the textbox when enter has been pressed and go to the next field if (e.Key == Key.Enter) { TextBoxLastName.Focus(); } } #endregion #region Last Name Focus Handlers private void TextBoxLastName_GotFocus(object sender, RoutedEventArgs e) { App.AppConstants.SetTextBoxFocusColours(sender as TextBox); // if our watermark is set in the control if (TextBoxLastName.Text == lastnameWatermark) { TextBoxLastName.Text = string.Empty; TextBoxLastName.Foreground = App.AppConstants.NormalTextColourBrush; } } private void TextBoxLastName_LostFocus(object sender, RoutedEventArgs e) { // If nothing has been entered on leaving our textbox, then set our watermark again if (TextBoxLastName.Text == string.Empty) { TextBoxLastName.Text = lastnameWatermark; TextBoxLastName.Foreground = App.AppConstants.WatermarkTextColourBrush; } } /// <summary> /// Also validate on a key up /// </summary> private void TextBoxLastName_KeyUp(object sender, KeyEventArgs e) { // Reset the errors if a key has been pressed if (e.Key != Key.Unknown) { ResetErrors(); } // remove focus from the textbox when enter has been pressed and go to the next field if (e.Key == Key.Enter) { TextBoxMobile.Focus(); } } #endregion #region Mobile Focus Handlers private void TextBoxMobile_GotFocus(object sender, RoutedEventArgs e) { App.AppConstants.SetTextBoxFocusColours(sender as TextBox); // if our watermark is set in the control if (TextBoxMobile.Text == mobileWatermark) { TextBoxMobile.Text = string.Empty; TextBoxMobile.Foreground = App.AppConstants.NormalTextColourBrush; } } private void TextBoxMobile_LostFocus(object sender, RoutedEventArgs e) { // If nothing has been entered on leaving our textbox, then set our watermark again if (TextBoxMobile.Text == string.Empty) { TextBoxMobile.Text = mobileWatermark; TextBoxMobile.Foreground = App.AppConstants.WatermarkTextColourBrush; } } /// <summary> /// Also validate on a key up /// </summary> private void TextBoxMobile_KeyUp(object sender, KeyEventArgs e) { // Reset the errors if a key has been pressed if (e.Key != Key.Unknown) { ResetErrors(); } // remove focus from the textbox when enter has been pressed and go to the next field if (e.Key == Key.Enter) { this.Focus(); } } #endregion #region Team Name Focus Handlers //private void TextBoxTeamName_GotFocus(object sender, RoutedEventArgs e) //{ // // if our watermark is set in the control // if (TextBoxTeamName.Text == teamNameWatermark) // { // TextBoxTeamName.Text = string.Empty; // TextBoxTeamName.Foreground = App.AppConstants.NormalTextColourBrush; // } //} //private void TextBoxTeamName_LostFocus(object sender, RoutedEventArgs e) //{ // // If nothing has been entered on leaving our textbox, then set our watermark again // if (TextBoxTeamName.Text == string.Empty) // { // TextBoxTeamName.Text = teamNameWatermark; // TextBoxTeamName.Foreground = App.AppConstants.WatermarkTextColourBrush; // } //} #endregion private void ResetErrors() { foreach (ErrorAndControl title in errors) { title.Error.ClearError(); } } /// <summary> /// Instruction from the containing page to save (update account) /// </summary> internal void Save(ScrollViewer scroller) { bool pageValid = false; int scrollerOffset = 0; ResetErrors(); // Do some validation if (Validation.ValidateExists(TitleFirstName, TextBoxFirstName, firstnameWatermark, AppResources.FirstnameWatermark)) { scrollerOffset = 90; if (Validation.ValidateExists(TitleLastName, TextBoxLastName, lastnameWatermark, AppResources.SurnameWatermark)) { scrollerOffset = 180; if (Validation.ValidateExists(TitleMobile, TextBoxMobile, mobileWatermark, AppResources.MobileWatermark)) { pageValid = true; } } } // This control is in a scroller - so put the user at teh correct place if there is an error if ( !pageValid ) { scroller.ScrollToVerticalOffset(scrollerOffset); } // If page is valid then call the api if (pageValid) { string firstname = TextBoxFirstName.Text == firstnameWatermark ? string.Empty : TextBoxFirstName.Text; string lastname = TextBoxLastName.Text == lastnameWatermark ? string.Empty : TextBoxLastName.Text; string mobile = TextBoxMobile.Text == mobileWatermark ? string.Empty : TextBoxMobile.Text; //string teamname = TextBoxTeamName.Text == teamNameWatermark ? string.Empty : TextBoxTeamName.Text; string fav1 = FavouriteTeam1.SelectedId(); string fav2 = FavouriteTeam2.SelectedId(); string country = MyCountry.SelectedId(); // Raise message to containing page telling them we are starting a login so they can display progress bar etc if (UpdateAccountStarting != null) { UpdateAccountStarting(this, new UpdateAccountStartingEventArgs() { Count = 1 }); } // Call the api userApi.UserUpdate(App.ViewModel.DbViewModel.CurrentUser.UserId, firstname, lastname, mobile, fav1, fav2, country); } } } }
namespace Frontend.Core.Logging { /// <summary> /// Used to differentiate between the source of a particular log entry. /// </summary> public enum LogEntrySource { /// <summary> /// The UI (Frontend) caused this log entry /// </summary> UI, /// <summary> /// The converter itself caused this log entry /// </summary> Converter } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NekoUchi.BLL; using NekoUchi.MVC.Model; using Microsoft.Extensions.Primitives; namespace NekoUchi.MVC.Controllers { public class LessonController : Controller { // GET: Lesson public ActionResult Index() { return View(); } // GET: Lesson/Details/5 public ActionResult Details(string token, string courseId, string lessonName) { string username = AuthLogic.CheckToken(token); if (username == "") { throw new Exception("NotAuthorized"); } ViewData["token"] = token; var course = Course.GetCourse(courseId); if (username == course.ModelCourse.Author) { ViewData["isAuthor"] = true; } else { ViewData["isAuthor"] = false; } var lessonView = new LessonView(); foreach(var courseLesson in course.ModelCourse.Lessons) { if (courseLesson.Name == lessonName) { lessonView = LessonView.CastFromLesson(courseLesson, courseId); break; } } if (lessonView.Words == null) { lessonView.Words = new List<WordView>(); } // For now there are only generic tests; later there might be lesson-specific tests, // so those will be included here as well...) var bllQuizzes = Quiz.GetAllGenericQuizzes(); lessonView.Quiz = QuizView.CastFromBllQuiz(bllQuizzes); return View(lessonView); } // GET: Lesson/Create public ActionResult Create(string courseId, string token) { if (AuthLogic.CheckToken(token) == "") { throw new Exception("NotAuthorized"); } ViewData["token"] = token; var lessonView = new GridLessonView(); lessonView.CourseIdentification = courseId; return View(lessonView); } // POST: Lesson/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(IFormCollection collection) { try { var name = new StringValues(); var description = new StringValues(); var courseIdentification = new StringValues(); var token = new StringValues(); if (collection.TryGetValue("Name", out name) && collection.TryGetValue("Description", out description) && collection.TryGetValue("token", out token) && collection.TryGetValue("CourseIdentification", out courseIdentification)) { var username = AuthLogic.CheckToken(token.ToString()); if (username == "") { throw new Exception("NotAuthorized"); } ViewData["token"] = token; // Add lesson to Course var lesson = new Lesson(); lesson.ModelLesson = new NekoUchi.Model.Lesson(); lesson.ModelLesson.Name = name.ToString(); lesson.ModelLesson.Description = description.ToString(); lesson.ModelLesson.Words = new List<NekoUchi.Model.Word>(); if (Course.AddLessonToCourse(courseIdentification.ToString(), lesson.ModelLesson)) { return RedirectToAction("Details", new { token = token.ToString(), courseId = courseIdentification.ToString(), lessonName = name.ToString() }); } } throw new Exception("Something happened..."); } catch { throw new Exception("Something happened..."); } } // GET: Lesson/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Lesson/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, IFormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Lesson/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Lesson/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } public ActionResult WordsForLesson(string courseId, string lessonName, string token, string filter = "", bool sByMeaning = true, bool ascending = true) { if (AuthLogic.CheckToken(token) == "") { throw new Exception("NotAuthorized"); } ViewData["token"] = token; ViewData["courseId"] = courseId; ViewData["lessonName"] = lessonName; // Za prvu ruku sve ide iz baze, poslije Šu uzimati samo one koji odgovaraju // zadanom filtru var allWords = Word.GetAllWords(); // filter ViewData["filter"] = filter; if (filter != null && filter != "") { allWords = allWords.Where(w => w.ModelWord.Meaning.ToLower().Contains(filter.ToLower()) || w.ModelWord.Kana.ToLower().Contains(filter.ToLower()) || w.ModelWord.Kanji.ToLower().Contains(filter.ToLower()) || w.ModelWord.Level.ToLower().Contains(filter.ToLower())).ToList(); } // sort ViewData["ascending"] = ascending; if (sByMeaning) { if (ascending) { allWords = allWords.OrderBy(w => w.ModelWord.Meaning).ToList(); } else { allWords = allWords.OrderByDescending(w => w.ModelWord.Meaning).ToList(); } } else { if (ascending) { allWords = allWords.OrderBy(w => w.ModelWord.Level).ToList(); } else { allWords = allWords.OrderByDescending(w => w.ModelWord.Level).ToList(); } } // paging var words = new List<WordView>(); words = WordView.CastFromBllWord(allWords); return View(words); } public void AddWordToLesson(string wordId, string token, string courseId, string lessonName) { if (AuthLogic.CheckToken(token) == "") { throw new Exception("NotAuthorized"); } Word word = Word.GetWord(wordId); if(!Lesson.AddWordToLesson(courseId, lessonName, word.ModelWord)) { throw new Exception("Something went wrong..."); } } } }
 using Xunit; namespace XRTTicket.Test { public class UnitTest1 { private readonly DAO.TicketDao _ticket; public UnitTest1() { _ticket = new DAO.TicketDao(); } [Fact] public void TestMethod1() { var result = _ticket.Next(); Assert.Equal( result, 1 ); } [Fact] public void TestMethod2() { var result = _ticket.Next(); Assert.NotEqual(result, 0); } } }
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Rinsen.IdentityProviderWeb { public static class ExtensionMethods { public static void AddModelErrorAndClearModelValue<TModel>(this ModelStateDictionary dictionary, Expression<Func<TModel, object>> expression, string errorMessage) { var key = ExpressionHelper.GetExpressionText(expression); ClearModelValue(dictionary, key); dictionary.AddModelError(key, errorMessage); } public static void ClearModelValue<TModel>(this ModelStateDictionary dictionary, Expression<Func<TModel, object>> expression) { var key = ExpressionHelper.GetExpressionText(expression); ClearModelValue(dictionary, key); } private static void ClearModelValue(ModelStateDictionary dictionary, string key) { ModelStateEntry modelState; if (!dictionary.TryGetValue(key, out modelState)) return; var type = modelState.RawValue.GetType(); var rawValue = type == typeof(string) ? string.Empty : Activator.CreateInstance(type); // TODO Is this close to correct? modelState.RawValue = rawValue; modelState.ValidationState = ModelValidationState.Valid; modelState.AttemptedValue = string.Empty; modelState.Errors.Clear(); } } }
using System; using Facebook; using NUnit.Framework; namespace FacebookScratch { [TestFixture] public class Program { public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override bool Equals(object obj) { var cast = obj as Person; if (cast == null) { return false; } return cast.FirstName.Equals(FirstName) && cast.LastName.Equals(LastName); } } public static void Main(string[] args) { } [Test] public void Test() { var p1 = new Person { FirstName = "Collin", LastName = "Sauve" }; var p2 = new Person { FirstName = "Collin", LastName = "Sauve2" }; Assert.AreEqual(p1, p2); } } }
using REQFINFO.Business; using REQFINFO.Repository; using REQFINFO.Domain; using REQFINFO.Repository.DataEntity; using REQFINFO.Utility; using ExpressMapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace REQFINFO.Business.Infrastructure { public class ExpressMapperBusinessProfile { public static void RegisterMapping() { #region business to entity Mapper.Register<UserModel, User>(); Mapper.Register<WorkFlowModel, RFI_GetUserWorkflow_Result>(); Mapper.Register<FunctionModel, Function>(); Mapper.Register<CustomLookupModel,CustomLookup>(); Mapper.Register<LifeCycleModel,LifeCycle>() .Member(dest => dest.IDLevel, src => src.IDLevel > 0 ? src.IDLevel : (int?)null) .Member(dest => dest.AssignedToID, src => src.AssignedToID > 0 ? src.AssignedToID : (int?)null); Mapper.Register<StatusModel, Tab>(); Mapper.Register<UserXProjectXWorkFlowUserGroupModel, UserXProjectXWorkFlowUserGroup>(); Mapper.Register<UDFInstanceModel, UDFInstance>(); Mapper.Register<WorkFlowUserGroupModel, WorkFlowUserGroup>(); Mapper.Register<GIGModel, GIG>() //.Member(dest => dest.Originator, src => src.GIGOriginator) // .Member(dest => dest.SendTo, src => src.SendTo > 0 ? src.SendTo : (int?)null) .Member(dest => dest.IDContractor, src => src.IDContractor > 0 ? src.IDContractor : (int?)null); #endregion #region entity to business Mapper.Register<User, UserModel>(); Mapper.Register<Tab, StatusModel>(); Mapper.Register<Function, FunctionModel>(); Mapper.Register<UDFInstance, UDFInstanceModel>(); Mapper.Register<RFI_GetUserWorkflow_Result, WorkFlowModel>(); Mapper.Register<RFI_GetActionsForLoggedInUser_Result, FunctionModel>(); Mapper.Register<GetLevelDetailNextOrPrevious_Result, LevelModel>(); Mapper.Register<RFI_GetSendto_Result, UserModel>(); Mapper.Register<RFI_GetUDFFieldsData_Result, CreateGigModel>(); Mapper.Register<CustomLookup, CustomLookupModel>(); Mapper.Register<WorkFlowUserGroup, WorkFlowUserGroupModel>(); Mapper.Register<LifeCycle, LifeCycleModel>(); Mapper.Register<GIG, GIGModel>() // .Member(dest => dest.GIGOriginator, src => src.Originator) // .Member(dest => dest.GIGOriginatorName, src => src.User.FirstName+' '+ src.User.LastName) //.Member(dest => dest.PreparedByName, src => src.User.FirstName + ' ' + src.User.LastName) .Member(dest => dest.ContractorName, src => src.Contractor.Name); Mapper.Register<UserXProjectXWorkFlowUserGroup, UserXProjectXWorkFlowUserGroupModel>() .Member(dest => dest.WorkflowName, src => src.WorkFlowUserGroup.Workflow.Name) .Member(dest => dest.ProjectName, src => src.Project.Name).Member(dest => dest.WorkflowDisplayName, src => src.WorkFlowUserGroup.Workflow.DisplayName) .Member(dest => dest.IDWorkFlow, src => src.WorkFlowUserGroup.Workflow.IDWorkflow) .Member(dest => dest.UserName, src => src.User.FirstName + ' ' + src.User.LastName); Mapper.Register<RFI_GetGIGCommunicationLog_Result, GIGModel>() .Member(dest => dest.GIGDirection, src => src.TriggerValue); #endregion } } }
using Microsoft.EntityFrameworkCore; namespace Phc_Common_Api.DatabaseContext { public class IBMD2Context: DbContext { public virtual DbSet<SUPPLIER_ORG> SUPPLIER_ORG { get; set; } public virtual DbSet<PARKER_DIV_XREF> PARKER_DIV_XREF { get; set; } public virtual DbSet<PARKER_LOC_XREF> PARKER_LOC_XREF { get; set; } public virtual DbSet<SUPP_PARKER_LOC> SUPP_PARKER_LOC { get; set; } public virtual DbSet<WEB_USER_SUPP_DIV> WEB_USER_SUPP_DIV { get; set; } public IBMD2Context(DbContextOptions<IBMD2Context> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<WEB_USER_SUPP_DIV>().HasKey(k => new { k.WEB_ID }); builder.Entity<SUPPLIER_ORG>().HasKey(k => new { k.SUPP_ORG_ID }); builder.Entity<PARKER_DIV_XREF>().HasKey(k => new { k.PARKER_DIV_ID }); builder.Entity<PARKER_LOC_XREF>().HasKey(k => new { k.PARKER_DIV_ID, k.SECURITY_LOC_CD }); builder.Entity<SUPP_PARKER_LOC>().HasKey(k => new { k.PARKER_DIV_ID, k.PARKER_LOC_CD, k.SUPP_ORG_ID }); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using TriodorArgeProject.Entities; using TriodorArgeProject.Entities.EntityClasses; using TriodorArgeProject.Service.Managers; namespace TriodorArgeProject.WebUI.Controllers { public class PersonnelController : Controller { private PersonnelManager personnelManager = new PersonnelManager(); private ProjectManager projectManager = new ProjectManager(); private PersonnelProjectManager personnelProjectManager = new PersonnelProjectManager(); private List<Personnels> personnelList = new List<Personnels>(); private List<PersonnelModels> personnelModelsList = new List<PersonnelModels>(); private UserManager userManager = new UserManager(); private PositionManager positionManager = new PositionManager(); private Personnels personnels; PersonnelModels personnelModels; // GET: Personnel public ActionResult GetPersonnelList() { personnelList = personnelManager.List(); foreach (var item in personnelList) { personnelModels = new PersonnelModels { ID = item.Id, Name = item.Name + " " + item.Surname }; personnelModelsList.Add(personnelModels); } return Json(new { result = true, veri = personnelModelsList }, JsonRequestBehavior.AllowGet); } public ActionResult PersonnelList() { return View(personnelManager.List()); } public ActionResult Create() { ViewBag.POSITION = positionManager.List(); return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(string firstname,string lastname,string registerno,string startdate,string leavedate,string position,string username,string password,string repassword) { if (firstname!=null && lastname !=null &&registerno!=null&&startdate!=null &&position!=null &&password!=null&&password==repassword) { personnels = new Personnels(); personnels.Name = firstname; personnels.Surname = lastname; personnels.RegisterNo = registerno; personnels.StartDate= DateTime.Parse(startdate); if (leavedate!="") { personnels.LeaveDate = DateTime.Parse(leavedate); personnels.IsActive = false; } else { personnels.IsActive = true; } personnels.PositionID=positionManager.Find(x => x.Position == position).ID; Users user = new Users(); user.Username = username; user.Password = password; user.RoleID = null; personnels.Users = user; var res = personnelManager.Insert(personnels); if (res>0) { TempData["personelmesaj"] = "Personel Başarılı Bir Şekilde Eklendi."; } return RedirectToAction("PersonnelList"); } else { TempData["personelmesaj"] = "Lütfen tüm alanları doldurunuz."; } return View(personnels); } public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Personnels personnel = personnelManager.Find(x => x.Id == id); if (personnel == null) { return HttpNotFound(); } return View(personnel); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Personnels personnels) { if (ModelState.IsValid) { var res = personnelManager.Update(personnels); if (res > 0) { TempData["mesaj"] = "Personel başarılı bir şekilde güncellendi."; } TempData["mesaj"] = "Personel güncellenirken hata ile karşılaşıldı."; return RedirectToAction("Index"); } return View(personnels); } public ActionResult Delete(int? id) { if (id==null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Personnels personnels = personnelManager.Find(x => x.Id == id); if (personnels==null) { return HttpNotFound(); } return View(personnels); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Personnels personnels = personnelManager.Find(x => x.Id == id); personnelManager.Delete(personnels); return RedirectToAction("PersonnelList"); } public ActionResult Detail(int? id ,string year="2010",int projectID=10) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } personnels = personnelManager.Find(x => x.Id == id); List<PersonnelProjectsTable> personnelProject = personnelProjectManager.List(x => x.PersonnelID == id && x.Year == year && x.ProjectID == projectID) ; List<string> monthList = new List<string>(); string projectName = projectManager.Find(x => x.ID == projectID).Name; List<int> workRate = new List<int>(); foreach (var item in personnelProject) { monthList.Add(item.Month); workRate.Add(Int32.Parse(item.WorkRate)); } if (personnels == null) { return HttpNotFound(); } ViewBag.WORKRATES = workRate; ViewBag.MONTHS = monthList; ViewBag.PROJECTNAME = projectName; return View(personnels); } public ActionResult GetAddEducation() { return PartialView("_PartialAddEducation"); } public ActionResult GetAddAbility() { return PartialView("_PartialAddAbility"); } public ActionResult GetAddWorkExperience() { return PartialView("_PartialAddWorkExperience"); } public ActionResult GetAddCertificate() { return PartialView("_PartialAddCertificate"); } public ActionResult GetEducationInfo(int id) { return PartialView("_PartialEducationInfo",personnelManager.Find(x=>x.Id==id).PersonnelEducations); } public ActionResult GetAbilityInfo(int id) { return PartialView("_PartialAbilityInfo", personnelManager.Find(x => x.Id == id).PersonnelAbility); } public ActionResult GetWorkExperienceInfo(int id) { return PartialView("_PartialWorkExperienceInfo", personnelManager.Find(x => x.Id == id).WorkExperiences); } public ActionResult GetCertificateInfo(int id) { return PartialView("_PartialCertificateInfo", personnelManager.Find(x => x.Id == id).PersonnelCertificates); } public ActionResult PersonnelInfo(int? id) { if (id==null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Personnels personnel = personnelManager.Find(x => x.Id == id); if (personnel==null) { return HttpNotFound(); } return View(personnel); } public ActionResult AddEducation(int? id) { if (id==null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult AddEducation(int? id,PersonnelEducations education) { if (id==null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return View(); } } }
using System; using System.Threading.Tasks; using System.Collections.Generic; namespace XamChat { public class FakeService:IWebServices { public int SleepDurtion{ get; set;} public FakeService() { SleepDurtion = 0; } private Task Sleep() { return Task.Delay (SleepDurtion); } public async Task<User> Register (User user) { await Sleep(); return user; } public async Task<User> Login(string username, string password) { await Sleep(); return new User { Id = 1, Username=username}; } public async Task<User[]> GetFriend(int userid) { await Sleep(); return new User[] { new User{Id=2,Username="o=bobama"}, new User{Id=3,Username="bobloblaw"} }; } public async Task<User> addFriend(int userid,string username) { await Sleep (); return new User{Id=4,Username=username}; } public async Task<Conversation[]> getConversation(int userid) { await Sleep(); List<Conversation> list = new List<Conversation> (); return new Conversation[] { new Conversation { Id = 1, UserId = 2,UserOwner=new User{Id=1},UserOwnerFriend=new User{Id=5,Username="Friend"} }, new Conversation { Id = 1, UserId = 3 ,UserOwner=new User{Id=1},UserOwnerFriend=new User{Id=6,Username="GF"}}, new Conversation { Id = 1, UserId = 4 ,UserOwner=new User{Id=1},UserOwnerFriend=new User{Id=7,Username="Anonymous"}}, }; } public async Task<MessageM[]> getMessage(int conversationId) { await Sleep (); return new[] { new MessageM { Id = 1, ConversationId = conversationId, UserId = 2, Text = "Hey", }, new MessageM { Id = 2, ConversationId = conversationId, UserId = 1, Text = "What's Up?", }, new MessageM { Id = 3, ConversationId = conversationId, UserId = 2, Text = "Have you seen that new movie?", }, new MessageM { Id = 4, ConversationId = conversationId, UserId = 1, Text = "It's great!", }, }; } public async Task<MessageM> sendMessage(MessageM message) { await Sleep(); return message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SynchWebService.Entity { [Serializable] public class AppHdr { public string User01 { get; set; } public string User02 { get; set; } public string User03 { get; set; } public string User04 { get; set; } public string User05 { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; namespace DataLayer { public class EventsDAL { public IList<Events> getAllEvents() { TEVEntityModel db = new TEVEntityModel(); return db.Events.ToList(); } public Events getEventById(Guid id) { TEVEntityModel db = new TEVEntityModel(); return db.Events.Find(id); } public void createEvent(Events events) { TEVEntityModel db = new TEVEntityModel(); db.Events.Add(events); db.SaveChanges(); } public void updateEvent(Events events) { TEVEntityModel db = new TEVEntityModel(); db.Entry<Events>(events).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } public void deleteEvent(Guid id) { TEVEntityModel db = new TEVEntityModel(); db.Events.Remove(db.Events.Find(id)); db.SaveChanges(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class keyPops : MonoBehaviour { public GameObject perfectStroke; Text text; // Start is called before the first frame update void Start() { SongManager.onHitEvent += showPopup; text = GetComponent<Text>(); text.enabled = false; } void showPopup(int trackNumber, SongManager.Rank rank) { if (rank == SongManager.Rank.PERFECT) { text.text = "PERFECT!"; text.enabled = true; } else if (rank == SongManager.Rank.GOOD) { text.text = "GOOD!"; text.enabled = true; } else if (rank == SongManager.Rank.OKAY) { text.text = "OKAY!"; text.enabled = true; } else if (rank == SongManager.Rank.MISS) { text.text = "MISS!"; text.enabled = true; } StartCoroutine(PopUpDelay()); } IEnumerator PopUpDelay() { yield return new WaitForSecondsRealtime(1); text.enabled = false; } void OnDestroy() { SongManager.onHitEvent -= showPopup; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; public class Wanikani_baseResponse { }
using FluentValidation; using System; namespace Carpark.Register.Application.ParkingRates.Queries.GetParkingRate { public class GetParkingRateQueryValidator : AbstractValidator<GetParkingRateQuery> { public GetParkingRateQueryValidator() { RuleFor(x => x.EntryDateTime) .Must(BeAValidDate).WithMessage("Entry date is required"); RuleFor(x => x.ExitDateTime) .Must(BeAValidDate).WithMessage("Exit date is required") .GreaterThan(x => x.EntryDateTime).WithMessage("Exit Date/Time must be after Entry Date/Time"); } private bool BeAValidDate(DateTime date) { return !date.Equals(default(DateTime)); } } }
using System; using Raven.Client.Documents.Session; using static LaYumba.Functional.F; namespace RavenExample.Infrastructure.Storage { public class RavenSessionHelper { public static TResult Open<TResult>(Func<IDocumentSession, TResult> func) { var store = DocumentStoreHolder.Store; using (var session = store.OpenSession()) { return func(session); } } public static void Do(Action<IDocumentSession> operation) => Open(session => { operation(session); return Unit(); }); } }
 using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using SFP.Persistencia.Dao; namespace SFP.SIT.SERV.Dao.TABADM { public class EstOrgDAO : BaseDao { public EstOrgDAO(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter) { } public Object dmlAgregarDetalle(EstOrgDetalle oDatos) { String sSQL = " INSERT INTO TCE_ADM_EstOrgDet( " + "EOCLAVE, EODCLAVE, ARACLAVE, EODOrden, EODReporta, " + "EODPLAZAS, EODPLAZASGPO, EODPRESUPUESTO, EODPRESUPUESTOGPO, EODCALIFICACION, " + "EODCALIFGPO )" + " VALUES ( " + "' ) "; //return EjecutaDML(sSQL, oDatos.EOD_EOId, oDatos.EOD_Id, oDatos.EOD_NivelId, oDatos.EOD_Orden, oDatos.EOD_Reporta, oDatos.EOD_ReportaOrg); return EjecutaOracleCommand(sSQL); } public int dmlEditar(EstOrgDetalle oDatos) { throw new NotImplementedException(); } public int dmlBorrar(EstOrgDetalle oDatos) { throw new NotImplementedException(); } public List<EstOrgDetalle> dmlSelectTabla() { String sSQL = " SELECT * FROM Area "; return CrearListaMDL<EstOrgDetalle>(ConsultaDML(sSQL) as DataTable); } /*INICIO*/ public List<EstOrgDetalle> dmlSelectByAreaYear(Dictionary<string, object> dicParametros) { String sqlQuery = "SELECT * FROM TCE_ADM_ESTORGDET WHERE EOCLAVE = "+dicParametros["date"]+" and araclave = "+dicParametros["araclave"]+""; Dictionary<string, object> dicParam = new Dictionary<string, object>(); DataTable dt = ConsultaDML(sqlQuery, dicParam); List<EstOrgDetalle> lstAdmUsuMdl = CrearListaMDL<EstOrgDetalle>(dt); return lstAdmUsuMdl; } /*FIN*/ } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Net.Sockets; using mysql_connection_driver; using System.Text; using System.Timers; using System.Data; using System.Data.Odbc; using System.Linq; public class CommunicationMaster : MonoBehaviour { // const int[] debug_id = new int[1]{8}; public TextAsset dbConfig; public static List<string> IATA_tags = new List<string>(); const int PORT_NUM = 9319; private Hashtable clients = new Hashtable(); private TcpListener listener; private Thread listenerThread; private Db db; const int EXCEL_PORT_NUM = 2000; private Hashtable excelClients = new Hashtable(); private TcpListener excelListener; private Thread excelListenerThread; System.Text.ASCIIEncoding encoding; private bool firstpass = true; Dictionary<string,int> plc_to_emu; ConveyorForward[] conveyer; bool[] conveyerstate; bool[] conveyerlaststate; int[] conveyerio; bool[] conveyer_excel_override; bool[] conveyer_excel_val; ConveyorTurn[] conveyer_turn_run; bool[] conveyer_turn_run_state; bool[] conveyer_turn_run_laststate; int[] conveyer_turn_run_io; bool[] conveyer_turn_run_excel_override; bool[] conveyer_turn_run_excel_val; MergeConveyor[] conveyer_merge_run; bool[] conveyer_merge_run_state; bool[] conveyer_merge_run_laststate; int[] conveyer_merge_run_io; bool[] conveyer_merge_run_excel_override; bool[] conveyer_merge_run_excel_val; ConveyorForward[] conveyer_disconnect; bool[] conveyer_disconnect_state; bool[] conveyer_disconnect_laststate; int[] conveyer_disconnect_io; ConveyorTurn[] conveyer_turn_disconnect; bool[] conveyer_turn_disconnect_state; bool[] conveyer_turn_disconnect_laststate; int[] conveyer_turn_disconnect_io; MergeConveyor[] conveyer_merge_disconnect; bool[] conveyer_merge_disconnect_state; bool[] conveyer_merge_disconnect_laststate; int[] conveyer_merge_disconnect_io; DiverterLeftC[] hsd_cycle; bool[] hsd_cycle_state; bool[] hsd_cycle_laststate; bool[] hsd_last_cycle_io; int[] hsd_cycle_io; DiverterLeftC[] hsd_extended_prox; bool[] hsd_extended_prox_state; bool[] hsd_extended_prox_laststate; int[] hsd_extended_prox_io; DiverterLeftC[] hsd_retracted_prox; bool[] hsd_retracted_prox_state; bool[] hsd_retracted_prox_laststate; int[] hsd_retracted_prox_io; VerticalDiverter[] vsu_cycle; bool[] vsu_cycle_state; bool[] vsu_cycle_laststate; bool[] vsu_last_cycle_io; int[] vsu_cycle_io; VerticalDiverter[] vsu_up_prox; bool[] vsu_up_prox_state; bool[] vsu_up_prox_laststate; int[] vsu_up_prox_io; VerticalDiverter[] vsu_down_prox; bool[] vsu_down_prox_state; bool[] vsu_down_prox_laststate; int[] vsu_down_prox_io; ControlStationButton[] cs_button_output;//lighting bool[] cs_button_output_state; bool[] cs_button_output_laststate; // allows for not updating unnecessarily int[] cs_button_output_io; ControlStationButton[] cs_button_input;//button pressing int[] cs_button_input_io; PhotoEye[] pe_assign_security_clear; //photoeyeassigns bool[] pe_assign_security_clear_state; bool[] pe_assign_security_clear_laststate; int[] pe_assign_security_clear_io; PhotoEye[] pe_assign_security_alarmed; bool[] pe_assign_security_alarmed_state; bool[] pe_assign_security_alarmed_laststate; int[] pe_assign_security_alarmed_io; PhotoEye[] pe_assign_security_pending; bool[] pe_assign_security_pending_state; bool[] pe_assign_security_pending_laststate; int[] pe_assign_security_pending_io; Dictionary<string,int> emu_to_plc; int max_emu_to_plc_io; PhotoEye[] photoeye; bool[] photoeyestate; int[] photoeyeIO; bool[] photoeye_excel_override; bool[] photoeye_excel_val; BmaInput[] bmas; int[] bma_OK_io; int[] bma_OOG_io; BitArray emu_to_plc_bits; private int lasttrigger =0; private bool loggingenabled = false; private bool debuglogenabled = false; private bool ready = false; private bool getnewinputs = false; // Use this for initialization void Start () { Logger.WriteLine("[INFO]","STARTUP","",true); IataTags.initIATATags(); object[] obj = GameObject.FindSceneObjectsOfType(typeof (GameObject)); encoding = new System.Text.ASCIIEncoding(); MySql_connection db = new MySql_connection(); db.setConnectionString(GetConnectionString()); try{ plc_to_emu = db.getPLCtoEMU(); emu_to_plc = db.getEMUtoPLC(); }catch(Exception e){ Logger.WriteLine("[ERROR]","Initialization","Unable to get IO data from mysqlconnection.dll. Check Database connectivity and dbConfig.txt ConnectionString.",true); } if(emu_to_plc == null) { Debug.Log("Unable to get IO data from mysqlconnection.dll. Check Database connectivity."); Logger.WriteLine("[ERROR]","Initialization","Unable to get IO data from mysqlconnection.dll. Check Database connectivity.",true); return; } else{ Logger.WriteLine("[INFO]","Initialization","Successfully retrieved config values from the database. Lengths: "+plc_to_emu.Count+", "+emu_to_plc.Count,true); Debug.Log("Successfully retrieved config values from the database. Lengths: "+plc_to_emu.Count+", "+emu_to_plc.Count); } ///////////// EMU to PLC max_emu_to_plc_io = 0; int photoeyecount = 0; int conveyer_disconnect_count =0; int conveyer_merge_disconnect_count =0; int conveyer_turn_disconnect_count = 0; int hsd_extended_prox_count = 0; int hsd_retracted_prox_count = 0; int vsu_up_prox_count = 0; int vsu_down_prox_count =0; int cs_button_input_count = 0; //pressed or not int bma_count = 0; foreach (object o in obj) { GameObject g = (GameObject) o; if(g.GetComponent<PhotoEye>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<PhotoEye>().IO_name_photoeye)) { if(emu_to_plc[g.GetComponent<PhotoEye>().IO_name_photoeye]>max_emu_to_plc_io){ max_emu_to_plc_io = emu_to_plc[g.GetComponent<PhotoEye>().IO_name_photoeye]; } photoeyecount++; } } else if(g.GetComponent<ConveyorForward>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<ConveyorForward>().IO_name_disconnect)) { conveyer_disconnect_count ++; } } else if(g.GetComponent<ConveyorTurn>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<ConveyorTurn>().IO_name_disconnect)) { conveyer_turn_disconnect_count ++; } } else if(g.GetComponent<MergeConveyor>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<MergeConveyor>().IO_name_disconnect)) { conveyer_merge_disconnect_count ++; } }else if(g.GetComponent<DiverterLeftC>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_extended_prox)) { hsd_extended_prox_count ++; } if(emu_to_plc.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_retracted_prox)) { hsd_retracted_prox_count ++; } }else if(g.GetComponent<VerticalDiverter>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_up_prox)) { vsu_up_prox_count ++; } if(emu_to_plc.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_dn_prox)) { vsu_down_prox_count ++; } }else if(g.GetComponent<ControlStationButton>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<ControlStationButton>().IO_input)) { cs_button_input_count ++; } }else if(g.GetComponent<BmaInput>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<BmaInput>().IO_name_BMA_OK)) { bma_count ++; } } } if(max_emu_to_plc_io%8!=0) { max_emu_to_plc_io = (int)(Math.Floor((double)max_emu_to_plc_io/8)+1)*8; } max_emu_to_plc_io = 1312; // make the response larger, fixed size. (temporary ? ) emu_to_plc_bits = new BitArray(max_emu_to_plc_io); photoeye = new PhotoEye[photoeyecount]; photoeyestate = new bool[photoeyecount]; photoeyeIO = new int[photoeyecount]; photoeye_excel_override = new bool[photoeyecount]; photoeye_excel_val = new bool[photoeyecount]; photoeyecount = 0; conveyer_disconnect = new ConveyorForward[conveyer_disconnect_count]; conveyer_disconnect_state = new bool[conveyer_disconnect_count]; conveyer_disconnect_laststate= new bool[conveyer_disconnect_count]; conveyer_disconnect_io = new int[conveyer_disconnect_count]; conveyer_disconnect_count =0; conveyer_turn_disconnect = new ConveyorTurn[conveyer_turn_disconnect_count]; conveyer_turn_disconnect_state = new bool[conveyer_turn_disconnect_count]; conveyer_turn_disconnect_laststate= new bool[conveyer_turn_disconnect_count]; conveyer_turn_disconnect_io = new int[conveyer_turn_disconnect_count]; conveyer_turn_disconnect_count =0; conveyer_merge_disconnect = new MergeConveyor[conveyer_merge_disconnect_count]; conveyer_merge_disconnect_state = new bool[conveyer_merge_disconnect_count]; conveyer_merge_disconnect_laststate= new bool[conveyer_merge_disconnect_count]; conveyer_merge_disconnect_io = new int[conveyer_merge_disconnect_count]; conveyer_merge_disconnect_count =0; hsd_extended_prox = new DiverterLeftC[hsd_extended_prox_count]; hsd_extended_prox_state = new bool[hsd_extended_prox_count]; hsd_extended_prox_laststate= new bool[hsd_extended_prox_count]; hsd_extended_prox_io = new int[hsd_extended_prox_count]; hsd_extended_prox_count =0; hsd_retracted_prox = new DiverterLeftC[hsd_retracted_prox_count]; hsd_retracted_prox_state = new bool[hsd_retracted_prox_count]; hsd_retracted_prox_laststate= new bool[hsd_retracted_prox_count]; hsd_retracted_prox_io = new int[hsd_retracted_prox_count]; hsd_retracted_prox_count =0; vsu_up_prox = new VerticalDiverter[vsu_up_prox_count]; vsu_up_prox_state = new bool[vsu_up_prox_count]; vsu_up_prox_laststate= new bool[vsu_up_prox_count]; vsu_up_prox_io = new int[vsu_up_prox_count]; vsu_up_prox_count =0; vsu_down_prox = new VerticalDiverter[vsu_down_prox_count]; vsu_down_prox_state = new bool[vsu_down_prox_count]; vsu_down_prox_laststate= new bool[vsu_down_prox_count]; vsu_down_prox_io = new int[vsu_down_prox_count]; vsu_down_prox_count =0; cs_button_input = new ControlStationButton[cs_button_input_count]; cs_button_input_io = new int[cs_button_input_count]; cs_button_input_count = 0; bmas = new BmaInput[bma_count]; bma_OK_io = new int[bma_count]; bma_OOG_io = new int[bma_count]; bma_count =0; foreach (object o in obj) { GameObject g = (GameObject) o; if(g.GetComponent<PhotoEye>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<PhotoEye>().IO_name_photoeye)) { photoeye[photoeyecount] = g.GetComponent<PhotoEye>(); photoeyestate[photoeyecount] = photoeye[photoeyecount].getState(); photoeyeIO[photoeyecount] = emu_to_plc[photoeye[photoeyecount].IO_name_photoeye]; photoeyecount ++; } } else if(g.GetComponent<ConveyorForward>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<ConveyorForward>().IO_name_disconnect)) { conveyer_disconnect[conveyer_disconnect_count] = g.GetComponent<ConveyorForward>(); conveyer_disconnect_state[conveyer_disconnect_count] = conveyer_disconnect[conveyer_disconnect_count].getState(); conveyer_disconnect_io[conveyer_disconnect_count] = emu_to_plc[conveyer_disconnect[conveyer_disconnect_count].IO_name_disconnect]; conveyer_disconnect_count ++; } } else if(g.GetComponent<ConveyorTurn>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<ConveyorTurn>().IO_name_disconnect)) { conveyer_turn_disconnect[conveyer_turn_disconnect_count] = g.GetComponent<ConveyorTurn>(); conveyer_turn_disconnect_state[conveyer_turn_disconnect_count] = conveyer_turn_disconnect[conveyer_turn_disconnect_count].getState(); conveyer_turn_disconnect_io[conveyer_turn_disconnect_count] = emu_to_plc[conveyer_turn_disconnect[conveyer_turn_disconnect_count].IO_name_disconnect]; conveyer_turn_disconnect_count ++; } } else if(g.GetComponent<MergeConveyor>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<MergeConveyor>().IO_name_disconnect)) { conveyer_merge_disconnect[conveyer_merge_disconnect_count] = g.GetComponent<MergeConveyor>(); conveyer_merge_disconnect_state[conveyer_merge_disconnect_count] = conveyer_merge_disconnect[conveyer_merge_disconnect_count].getState(); conveyer_merge_disconnect_io[conveyer_merge_disconnect_count] = emu_to_plc[conveyer_merge_disconnect[conveyer_merge_disconnect_count].IO_name_disconnect]; conveyer_merge_disconnect_count ++; } } else if(g.GetComponent<DiverterLeftC>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_extended_prox)) { hsd_extended_prox[hsd_extended_prox_count] = g.GetComponent<DiverterLeftC>(); hsd_extended_prox_state[hsd_extended_prox_count] = hsd_extended_prox[hsd_extended_prox_count].getState(); hsd_extended_prox_io[hsd_extended_prox_count] = emu_to_plc[hsd_extended_prox[hsd_extended_prox_count].IO_name_extended_prox]; hsd_extended_prox_count ++; } if(emu_to_plc.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_retracted_prox)) { hsd_retracted_prox[hsd_retracted_prox_count] = g.GetComponent<DiverterLeftC>(); hsd_retracted_prox_state[hsd_retracted_prox_count] = hsd_retracted_prox[hsd_retracted_prox_count].getState(); hsd_retracted_prox_io[hsd_retracted_prox_count] = emu_to_plc[hsd_retracted_prox[hsd_retracted_prox_count].IO_name_retracted_prox]; hsd_retracted_prox_count ++; } }else if(g.GetComponent<VerticalDiverter>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_up_prox)) { vsu_up_prox[vsu_up_prox_count] = g.GetComponent<VerticalDiverter>(); vsu_up_prox_state[vsu_up_prox_count] = vsu_up_prox[vsu_up_prox_count].getState(); vsu_up_prox_io[vsu_up_prox_count] = emu_to_plc[vsu_up_prox[vsu_up_prox_count].IO_name_up_prox]; vsu_up_prox_count ++; } if(emu_to_plc.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_dn_prox)) { vsu_down_prox[vsu_down_prox_count] = g.GetComponent<VerticalDiverter>(); vsu_down_prox_state[vsu_down_prox_count] = vsu_down_prox[vsu_down_prox_count].getState(); vsu_down_prox_io[vsu_down_prox_count] = emu_to_plc[vsu_down_prox[vsu_down_prox_count].IO_name_dn_prox]; vsu_down_prox_count ++; } } else if(g.GetComponent<ControlStationButton>()!=null) { if(emu_to_plc.ContainsKey(g.GetComponent<ControlStationButton>().IO_input)) { cs_button_input[cs_button_input_count] = g.GetComponent<ControlStationButton>(); cs_button_input_io[cs_button_input_count] = emu_to_plc[cs_button_input[cs_button_input_count].IO_input]; cs_button_input_count ++; } }else if(g.GetComponent<BmaInput>()!=null){ if(emu_to_plc.ContainsKey(g.GetComponent<BmaInput>().IO_name_BMA_OK)) { bmas[bma_count] = g.GetComponent<BmaInput>(); bma_OK_io[bma_count] = emu_to_plc[bmas[bma_count].IO_name_BMA_OK]; bma_OOG_io[bma_count] = emu_to_plc[bmas[bma_count].IO_name_BMA_OOG]; bma_count ++; } } } ///////////// PLC to EMU /// Builds up the arrays for the different devices int conveyercount =0; int conveyer_turn_run_count = 0; int conveyer_merge_run_count = 0; int hsd_cycle_count=0; int vsu_cycle_count = 0; int cs_button_output_count = 0; int pe_assign_security_clear_count= 0; int pe_assign_security_alarmed_count= 0; int pe_assign_security_pending_count= 0; foreach (object o in obj) { GameObject g = (GameObject) o; if(g.GetComponent<ConveyorForward>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ConveyorForward>().IO_name_motor_run)) { conveyercount++; } } else if(g.GetComponent<ConveyorTurn>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ConveyorTurn>().IO_name_motor_run)) { conveyer_turn_run_count++; } } else if(g.GetComponent<MergeConveyor>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<MergeConveyor>().IO_name_motor_run)) { conveyer_merge_run_count++; } } else if(g.GetComponent<DiverterLeftC>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_cycle_command)) { hsd_cycle_count++; } } else if(g.GetComponent<VerticalDiverter>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_cycle_cmd)) { vsu_cycle_count++; } }else if(g.GetComponent<ControlStationButton>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ControlStationButton>().IO_output)) { cs_button_output_count++; } } else if(g.GetComponent<PhotoEye>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_clear)) { pe_assign_security_clear_count++; } if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_alarmed)) { pe_assign_security_alarmed_count++; } if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_pending)) { pe_assign_security_pending_count++; } } } conveyer = new ConveyorForward[conveyercount]; conveyerstate = new bool[conveyercount]; conveyerlaststate = new bool[conveyercount]; conveyerio = new int[conveyercount]; conveyer_excel_override = new bool[conveyercount]; conveyer_excel_val = new bool[conveyercount]; conveyercount =0; conveyer_turn_run = new ConveyorTurn[conveyer_turn_run_count]; conveyer_turn_run_state = new bool[conveyer_turn_run_count]; conveyer_turn_run_laststate = new bool[conveyer_turn_run_count]; conveyer_turn_run_io = new int[conveyer_turn_run_count]; conveyer_turn_run_excel_override = new bool[conveyer_turn_run_count]; conveyer_turn_run_excel_val = new bool[conveyer_turn_run_count]; conveyer_turn_run_count =0; conveyer_merge_run = new MergeConveyor[conveyer_merge_run_count]; conveyer_merge_run_state = new bool[conveyer_merge_run_count]; conveyer_merge_run_laststate = new bool[conveyer_merge_run_count]; conveyer_merge_run_io = new int[conveyer_merge_run_count]; conveyer_merge_run_excel_override = new bool[conveyer_merge_run_count]; conveyer_merge_run_excel_val = new bool[conveyer_merge_run_count]; conveyer_merge_run_count =0; hsd_cycle = new DiverterLeftC[hsd_cycle_count]; hsd_cycle_state = new bool[hsd_cycle_count]; hsd_cycle_laststate = new bool[hsd_cycle_count]; hsd_last_cycle_io = new bool[hsd_cycle_count]; hsd_cycle_io = new int[hsd_cycle_count]; hsd_cycle_count =0; vsu_cycle = new VerticalDiverter[vsu_cycle_count]; vsu_cycle_state = new bool[vsu_cycle_count]; vsu_cycle_laststate = new bool[vsu_cycle_count]; vsu_last_cycle_io = new bool[vsu_cycle_count]; vsu_cycle_io = new int[vsu_cycle_count]; vsu_cycle_count =0; cs_button_output = new ControlStationButton[cs_button_output_count]; cs_button_output_io = new int[cs_button_output_count]; cs_button_output_state = new bool[cs_button_output_count]; cs_button_output_laststate = new bool[cs_button_output_count]; cs_button_output_count=0; pe_assign_security_clear = new PhotoEye[pe_assign_security_clear_count]; //photoeyeassigns pe_assign_security_clear_state = new bool[pe_assign_security_clear_count]; pe_assign_security_clear_laststate = new bool[pe_assign_security_clear_count]; pe_assign_security_clear_io = new int[pe_assign_security_clear_count]; pe_assign_security_clear_count = 0; pe_assign_security_alarmed = new PhotoEye[pe_assign_security_alarmed_count]; pe_assign_security_alarmed_state = new bool[pe_assign_security_alarmed_count]; pe_assign_security_alarmed_laststate = new bool[pe_assign_security_alarmed_count]; pe_assign_security_alarmed_io = new int[pe_assign_security_alarmed_count]; pe_assign_security_alarmed_count = 0; pe_assign_security_pending = new PhotoEye[pe_assign_security_pending_count]; pe_assign_security_pending_state = new bool[pe_assign_security_pending_count]; pe_assign_security_pending_laststate = new bool[pe_assign_security_pending_count]; pe_assign_security_pending_io = new int[pe_assign_security_pending_count]; pe_assign_security_pending_count = 0; foreach (object o in obj) { GameObject g = (GameObject) o; if(g.GetComponent<ConveyorForward>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ConveyorForward>().IO_name_motor_run)) { conveyer[conveyercount] = g.GetComponent<ConveyorForward>(); conveyerstate[conveyercount] = conveyer[conveyercount].getState(); conveyerio[conveyercount] = plc_to_emu[conveyer[conveyercount].IO_name_motor_run]; conveyercount ++; } } else if(g.GetComponent<ConveyorTurn>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ConveyorTurn>().IO_name_motor_run)) { conveyer_turn_run[conveyer_turn_run_count] = g.GetComponent<ConveyorTurn>(); conveyer_turn_run_state[conveyer_turn_run_count] = conveyer_turn_run[conveyer_turn_run_count].getState(); conveyer_turn_run_io[conveyer_turn_run_count] = plc_to_emu[conveyer_turn_run[conveyer_turn_run_count].IO_name_motor_run]; conveyer_turn_run_count ++; } } else if(g.GetComponent<MergeConveyor>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<MergeConveyor>().IO_name_motor_run)) { conveyer_merge_run[conveyer_merge_run_count] = g.GetComponent<MergeConveyor>(); conveyer_merge_run_state[conveyer_merge_run_count] = conveyer_merge_run[conveyer_merge_run_count].getState(); conveyer_merge_run_io[conveyer_merge_run_count] = plc_to_emu[conveyer_merge_run[conveyer_merge_run_count].IO_name_motor_run]; conveyer_merge_run_count ++; } } else if(g.GetComponent<DiverterLeftC>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<DiverterLeftC>().IO_name_cycle_command)) { hsd_cycle[hsd_cycle_count] = g.GetComponent<DiverterLeftC>(); hsd_cycle_state[hsd_cycle_count] = hsd_cycle[hsd_cycle_count].getState(); // <<== prolly not needed hsd_cycle_io[hsd_cycle_count] = plc_to_emu[hsd_cycle[hsd_cycle_count].IO_name_cycle_command]; hsd_cycle_count ++; } } else if(g.GetComponent<VerticalDiverter>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<VerticalDiverter>().IO_name_cycle_cmd)) { vsu_cycle[vsu_cycle_count] = g.GetComponent<VerticalDiverter>(); vsu_cycle_state[vsu_cycle_count] = vsu_cycle[vsu_cycle_count].getState(); // <<== prolly not needed vsu_cycle_io[vsu_cycle_count] = plc_to_emu[vsu_cycle[vsu_cycle_count].IO_name_cycle_cmd]; vsu_cycle_count ++; } }else if(g.GetComponent<ControlStationButton>()!=null) { if(plc_to_emu.ContainsKey(g.GetComponent<ControlStationButton>().IO_output)) { cs_button_output[cs_button_output_count] = g.GetComponent<ControlStationButton>(); cs_button_output_state[cs_button_output_count] = cs_button_output[cs_button_output_count].getState(); // <<== prolly not needed cs_button_output_io[cs_button_output_count] = plc_to_emu[cs_button_output[cs_button_output_count].IO_output]; cs_button_output_count ++; } }else if(g.GetComponent<PhotoEye>()!=null) // Assumes all states are false to start. { if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_clear)) { pe_assign_security_clear[pe_assign_security_clear_count] = g.GetComponent<PhotoEye>(); pe_assign_security_clear_io[pe_assign_security_clear_count] = plc_to_emu[pe_assign_security_clear[pe_assign_security_clear_count].IO_assign_bag_clear]; pe_assign_security_clear_count++; } if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_alarmed)) { pe_assign_security_alarmed[pe_assign_security_alarmed_count] = g.GetComponent<PhotoEye>(); pe_assign_security_alarmed_io[pe_assign_security_alarmed_count] = plc_to_emu[pe_assign_security_clear[pe_assign_security_alarmed_count].IO_assign_bag_alarmed]; pe_assign_security_alarmed_count++; } if(plc_to_emu.ContainsKey(g.GetComponent<PhotoEye>().IO_assign_bag_pending)) { pe_assign_security_pending[pe_assign_security_pending_count] = g.GetComponent<PhotoEye>(); pe_assign_security_pending_io[pe_assign_security_pending_count] = plc_to_emu[pe_assign_security_pending[pe_assign_security_pending_count].IO_assign_bag_pending]; pe_assign_security_pending_count++; } } } Debug.Log("IO points from database initialized successfully.\r\n"); Logger.WriteLine("[INFO]","IO initialized","IO points from database initialized successfully.\r\n",true); ready = true; listenerThread = new Thread(new ThreadStart(DoListen)); listenerThread.Start(); excelListenerThread = new Thread(new ThreadStart(DoExcelListen)); excelListenerThread.Start(); //responderThread = new Thread(new ThreadStart(DoResponder)); //responderThread.Start(); } void OnApplicationQuit() { if(listener !=null){ listener.Server.Close(); } if(listenerThread!=null) { listenerThread.Abort(); } if(excelListener !=null){ excelListener.Server.Close(); } if(excelListenerThread!=null) { excelListenerThread.Abort(); } } // This subroutine sends a message to all attached clients private void Broadcast(string strMessage) { UserConnection client; // All entries in the clients Hashtable are UserConnection so it is possible // to assign it safely. foreach(DictionaryEntry entry in clients) { client = (UserConnection) entry.Value; //client.SendData(strMessage); } } // This subroutine checks to see if username already exists in the clients // Hashtable. if it does, send a REFUSE message, otherwise confirm with a JOIN. private void ConnectUser(string userName, UserConnection sender) {; if (clients.Contains(userName)) { ReplyToSender("REFUSE", sender); } else { sender.Name = userName; // UpdateStatus(userName + " has joined the chat."); clients.Add(userName, sender); //lstPlayers.Items.Add(sender.Name); // Send a JOIN to sender, and notify all other clients that sender joined ReplyToSender("JOIN", sender); // SendToClients("CHAT|" + sender.Name + " has joined the chat.", sender); } } // This subroutine notifies other clients that sender left the chat, and removes // the name from the clients Hashtable private void DisconnectUser(UserConnection sender) { // UpdateStatus(sender.Name + " has left the chat."); // SendToClients("CHAT|" + sender.Name + " has left the chat.", sender); clients.Remove(sender.Name); //lstPlayers.Items.Remove(sender.Name); } // This subroutine is used a background listener thread to allow reading incoming // messages without lagging the user interface. private void DoListen() { try { // Listen for new connections. listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM); listener.Start(); do { // Create a new user connection using TcpClient returned by // TcpListener.AcceptTcpClient() UserConnection client = new UserConnection(listener.AcceptTcpClient()); // Create an event handler to allow the UserConnection to communicate // with the window. client.LineReceived += new LineReceive(OnLineReceived); //AddHandler client.LineReceived, AddressOf OnLineReceived; // UpdateStatus("new connection found: waiting for log-in"); }while(true); } catch(Exception ex){ //MessageBox.Show(ex.ToString()); } } private void DoExcelListen() { // Excel listener try { // Listen for new connections. excelListener = new TcpListener(System.Net.IPAddress.Any, EXCEL_PORT_NUM); excelListener.Start(); do { // Create a new user connection using TcpClient returned by // TcpListener.AcceptTcpClient() UserConnection excelClient = new UserConnection(excelListener.AcceptTcpClient()); // Create an event handler to allow the UserConnection to communicate // with the window. excelClient.LineReceived += new LineReceive(ExcelOnLineReceived); //AddHandler client.LineReceived, AddressOf OnLineReceived; // UpdateStatus("new connection found: waiting for log-in"); }while(true); } catch(Exception ex){ //MessageBox.Show(ex.ToString()); } } /// This is the Excel event handler /// /// private void ExcelOnLineReceived(UserConnection sender, byte[] data) { byte[] responsebytes = GetBytes("s"); byte[] iobytes = new byte[640];//data; for(int i=0;i<1280;i++) { if(i-2*(i/2)==1) { iobytes[i/2] += (byte)(data[i]*16); }else{ iobytes[i/2] = (byte)(data[i]); } } string excel_to_emu_bit_string = ""; for(var i=0; i<iobytes.Length;i++) { if(i==320) { excel_to_emu_bit_string += "\r\n Inputs:"; } excel_to_emu_bit_string += iobytes[i].ToString()+ " "; } Debug.Log("excel override: Outputs:" + excel_to_emu_bit_string + "\r\n Length:"+iobytes.Length.ToString()+"\r\n"); //sender.SendData(responsebytes); //return; //byte[] iobytes = data; byte[] byte_io_enabled = new byte[320]; byte[] byte_iovals = new byte[320]; for(var i=0;i<160;i++) // lower motor output bits { byte_iovals[i] = iobytes[i]; } for(var i=0;i<160;i++) { byte_io_enabled[i] = iobytes[i+160]; } for(var i=0;i<160;i++) // higher photoEye INPUT bits { byte_iovals[i+160] = iobytes[i+320]; } for(var i=0;i<160;i++) { byte_io_enabled[i+160] = iobytes[i+320+160]; } excel_to_emu_bit_string = ""; for(var i=0; i<byte_io_enabled.Length;i++) { excel_to_emu_bit_string += byte_io_enabled[i].ToString()+ " "; } //Debug.Log("byte_io_enabled:" + excel_to_emu_bit_string + "\r\n Length:"+byte_io_enabled.Length.ToString()+"\r\n"); BitArray io_enabled = new System.Collections.BitArray(byte_io_enabled); BitArray iovals = new System.Collections.BitArray(byte_iovals); for(var i=0;i<conveyer.Length;i++) { conveyer_excel_override[i] = (bool)io_enabled[conveyerio[i]]; conveyer_excel_val[i] = (bool)iovals[conveyerio[i]]; } /*for(var i=0;i<conveyer_turn_run.Length;i++) { Debug.Log(i.ToString()+" "+conveyer_turn_run_excel_override.Length.ToString()+" "+conveyer_turn_run_excel_val.Length.ToString()+" "+iovals.Length.ToString()+" "+io_enabled.Length.ToString()+" "+conveyer_turn_run_io[i].ToString()+"\r\n"); }*/ for(var i=0;i<conveyer_turn_run.Length;i++) { conveyer_turn_run_excel_override[i] = (bool)io_enabled[conveyer_turn_run_io[i]]; conveyer_turn_run_excel_val[i] = (bool)iovals[conveyer_turn_run_io[i]]; } for(var i=0;i<conveyer_merge_run.Length;i++) { conveyer_merge_run_excel_override[i] = (bool)io_enabled[conveyer_merge_run_io[i]]; conveyer_merge_run_excel_val[i] = (bool)iovals[conveyer_merge_run_io[i]]; } for(var i=0;i<photoeye.Length;i++) { photoeye_excel_override[i] = (bool)io_enabled[photoeyeIO[i]+(160*8)]; // gets it from shifted input photoeye_excel_val[i] = (bool)iovals[photoeyeIO[i]+(160*8)]; // gets it from shifted input } Loom.QueueOnMainThread(()=>{ for(var i=0;i<conveyer.Length;i++) { conveyer[i].setExcelOverride(conveyer_excel_override[i],conveyer_excel_val[i]); } for(var i=0;i<conveyer_turn_run.Length;i++) { conveyer_turn_run[i].setExcelOverride(conveyer_turn_run_excel_override[i],conveyer_turn_run_excel_val[i]); } for(var i=0;i<conveyer_merge_run.Length;i++) { conveyer_merge_run[i].setExcelOverride(conveyer_merge_run_excel_override[i],conveyer_merge_run_excel_val[i]); } for(var i=0;i<photoeye.Length;i++) { photoeye[i].setExcelOverride(photoeye_excel_override[i],photoeye_excel_val[i]); } }); // byte[] responsebytes = GetBytes("success"); sender.SendData(responsebytes); } private byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } // This is the event handler for the UserConnection when it receives a full line. // Parse the cammand and parameters and take appropriate action. private void OnLineReceived(UserConnection sender, byte[] data) { //Debug.Log("Received:\r\n"+data); byte[] iobytes = data; //encoding.GetBytes(data); int trigger = 0; if(iobytes.Length>=4){ trigger = Convert.ToInt32(iobytes[160])+(Convert.ToInt32(iobytes[161])*256)+(Convert.ToInt32(iobytes[162])*65536)+(Convert.ToInt32(iobytes[163])*16777216); } if(trigger == lasttrigger) { if(loggingenabled) { Debug.Log("Ignored Trigger " + trigger.ToString()); } return; } lasttrigger = trigger; BitArray iovals = new System.Collections.BitArray(iobytes); string plc_to_emu_bit_string_bits = ""; string plc_to_emu_bit_string = ""; for(var i=0; i<iobytes.Length;i++) { plc_to_emu_bit_string += iobytes[i].ToString()+ " "; } /* for(var i=0;i<iovals.Length;i++) { if(i%8==0) { plc_to_emu_bit_string_bits+=" |"; } if(i%4==0) { plc_to_emu_bit_string_bits+=" "; } if(iovals[i]==true){ plc_to_emu_bit_string_bits +=1; } else { plc_to_emu_bit_string_bits +=0; } }*/ /* string plc_to_emu_bit_string_bits = ""; string plc_to_emu_bit_string = ""; int tbyte = 0; int tbytecount = 7; for(var i=0;i<iovals.Length;i++) { if(i%8==0) { tbyte = 0; tbytecount =7; } //iovals[i] if(iovals[i]==true){ tbyte += (int) Math.Pow(2,tbytecount); //plc_to_emu_bit_string += "1"; plc_to_emu_bit_string_bits+="1"; }else{ //tbyte += (int)Math.Pow(2,tbytecount); //plc_to_emu_bit_string +="0"; plc_to_emu_bit_string_bits +="0"; } if(tbytecount==0) { plc_to_emu_bit_string += tbyte.ToString()+" "; } tbytecount--; }*/ if(loggingenabled) { Debug.Log("Received:\r\n"+plc_to_emu_bit_string); //Debug.Log("Received bits:\r\n"+plc_to_emu_bit_string_bits); } for(var i=0;i<conveyer.Length;i++) { if((bool)iovals[conveyerio[i]] != conveyerstate[i]) // The STATE HAS CHANGED!! { conveyerstate[i]=(bool)iovals[conveyerio[i]]; } } for(var i=0;i<conveyer_turn_run.Length;i++) { if((bool)iovals[conveyer_turn_run_io[i]] != conveyer_turn_run_state[i]) // The STATE HAS CHANGED!! { conveyer_turn_run_state[i]=(bool)iovals[conveyer_turn_run_io[i]]; } } for(var i=0;i<conveyer_merge_run.Length;i++) { if((bool)iovals[conveyer_merge_run_io[i]] != conveyer_merge_run_state[i]) // The STATE HAS CHANGED!! { conveyer_merge_run_state[i]=(bool)iovals[conveyer_merge_run_io[i]]; } } for(var i=0;i<hsd_cycle.Length;i++) { if((bool)iovals[hsd_cycle_io[i]] != hsd_last_cycle_io[i]) // The STATE HAS CHANGED!! { if(debuglogenabled) { Debug.Log("HSD "+ hsd_cycle_io[i]+ " cycle input changed to "+ ((bool)iovals[hsd_cycle_io[i]]).ToString()); } if((bool)iovals[hsd_cycle_io[i]]) // if rising edge. { if(debuglogenabled) { Debug.Log("HSD "+ hsd_cycle_io[i]+ " toggled to "+ (!hsd_cycle_state[i]).ToString()); } hsd_cycle_state[i]=!hsd_cycle_state[i]; // then toggle it. } hsd_last_cycle_io[i]=(bool)iovals[hsd_cycle_io[i]]; } } for(var i=0;i<vsu_cycle.Length;i++) { if((bool)iovals[vsu_cycle_io[i]] != vsu_last_cycle_io[i]) // The STATE HAS CHANGED!! { if((bool)iovals[vsu_cycle_io[i]]) // if rising edge. { vsu_cycle_state[i]=!vsu_cycle_state[i]; // then toggle it. } vsu_last_cycle_io[i]=(bool)iovals[vsu_cycle_io[i]]; } } for(var i=0;i<cs_button_output.Length;i++) { if((bool)iovals[cs_button_output_io[i]] != cs_button_output_state[i]) // The STATE HAS CHANGED!! { cs_button_output_state[i]=(bool)iovals[cs_button_output_io[i]]; } } for(var i=0;i<pe_assign_security_clear.Length;i++) { if((bool)iovals[pe_assign_security_clear_io[i]] != pe_assign_security_clear_state[i]) // The STATE HAS CHANGED!! { //Debug.Log ("changed Clear val"); pe_assign_security_clear_state[i]=(bool)iovals[pe_assign_security_clear_io[i]]; } } for(var i=0;i<pe_assign_security_alarmed.Length;i++) { if((bool)iovals[pe_assign_security_alarmed_io[i]] != pe_assign_security_alarmed_state[i]) // The STATE HAS CHANGED!! { pe_assign_security_alarmed_state[i]=(bool)iovals[pe_assign_security_alarmed_io[i]]; } } for(var i=0;i<pe_assign_security_pending.Length;i++) { if((bool)iovals[pe_assign_security_pending_io[i]] != pe_assign_security_pending_state[i]) // The STATE HAS CHANGED!! { pe_assign_security_pending_state[i]=(bool)iovals[pe_assign_security_pending_io[i]]; } } int heartlog = Logger.counter++; if(heartlog==100) { Logger.WriteLine("[INFO]","COM_SRV","Heartbeat",true); Logger.counter = 0; } // check if different. Loom.QueueOnMainThread(()=>{ for(var i=0;i<conveyer.Length;i++) { if(conveyerstate[i] !=conveyerlaststate[i]) { if(conveyer[i].GetType()!=System.Type.GetType("ConveyorForward")){ } else if(conveyer[i]==null){ Logger.WriteLine("[FATAL]","COM_SRV","NULL FOUND!!!! Somehow this reference has been lost!",true); //Debug.Log( } conveyer[i].setState(conveyerstate[i]); conveyerlaststate[i] = conveyerstate[i]; } } for(var i=0;i<conveyer_turn_run.Length;i++) { if(conveyer_turn_run_state[i] !=conveyer_turn_run_laststate[i]) { conveyer_turn_run[i].setState(conveyer_turn_run_state[i]); conveyer_turn_run_laststate[i] = conveyer_turn_run_state[i]; } } for(var i=0;i<conveyer_merge_run.Length;i++) { if(conveyer_merge_run_state[i] !=conveyer_merge_run_laststate[i]) { conveyer_merge_run[i].setState(conveyer_merge_run_state[i]); conveyer_merge_run_laststate[i] = conveyer_merge_run_state[i]; } } for(var i=0;i<hsd_cycle.Length;i++) { if(hsd_cycle_state[i] !=hsd_cycle_laststate[i]) { hsd_cycle[i].setState(hsd_cycle_state[i]); hsd_cycle_laststate[i] = hsd_cycle_state[i]; } } for(var i=0;i<vsu_cycle.Length;i++) { if(vsu_cycle_state[i] !=vsu_cycle_laststate[i]) { vsu_cycle[i].setState(vsu_cycle_state[i]); vsu_cycle_laststate[i] = vsu_cycle_state[i]; } } for(var i=0;i<cs_button_output.Length;i++) { if(cs_button_output_state[i] !=cs_button_output_laststate[i]) { cs_button_output[i].setState(cs_button_output_state[i]); cs_button_output_laststate[i] = cs_button_output_state[i]; } } for(var i=0;i<pe_assign_security_clear.Length;i++) { if(pe_assign_security_clear_state[i] !=pe_assign_security_clear_laststate[i]) { pe_assign_security_clear[i].setAssignClear(pe_assign_security_clear_state[i]); pe_assign_security_clear_laststate[i] = pe_assign_security_clear_state[i]; } } for(var i=0;i<pe_assign_security_alarmed.Length;i++) { if(pe_assign_security_alarmed_state[i] !=pe_assign_security_alarmed_laststate[i]) { pe_assign_security_alarmed[i].setAssignAlarmed(pe_assign_security_alarmed_state[i]); pe_assign_security_alarmed_laststate[i] = pe_assign_security_alarmed_state[i]; } } for(var i=0;i<pe_assign_security_pending.Length;i++) { if(pe_assign_security_pending_state[i] !=pe_assign_security_pending_laststate[i]) { pe_assign_security_pending[i].setAssignPending(pe_assign_security_pending_state[i]); pe_assign_security_pending_laststate[i] = pe_assign_security_pending_state[i]; } } }); // copy over last state //Loom.QueueOnMainThread(()=>{ // GameObject.Find("M_TC1_01").GetComponent<ConveyorForward>().setState(true); //}); //sender.SendData("Beltname:"+conveyern + " iopoint:" + iopointst + " previousstate:"+previousstate+" newstate:"+newstate + " input byte length:"+iovals.Length.ToString()); //return; /* byte[] overbyte = new byte[164]; for(var i=0;i<overbyte.Length;i++) { if(i%4==0) { overbyte[i] = (byte)(i/4+1); } } emu_to_plc_bits = new System.Collections.BitArray(overbyte); */ string triggerstring = ""; int triggerpointer = max_emu_to_plc_io-32; //index of start of 40th dint; int temptrigger = trigger; for(var i=0;i<32;i++){ int bit = (int)Math.Floor(trigger/Math.Pow(2,31-i)); triggerstring += trigger.ToString() + " "; if(bit ==1) { trigger = trigger - (int)Math.Pow (2,31-i); emu_to_plc_bits[triggerpointer+31-i] = true; } else { emu_to_plc_bits[triggerpointer+31-i] = false; //false; } } /*for(var i=0;i<emu_to_plc_bits.Length;i++) { emu_to_plc_bits[i]=i; }*/ if(!getnewinputs) { sendResponse(sender,emu_to_plc_bits,temptrigger.ToString()); return; } if(firstpass) { //firstpass = false; Loom.QueueOnMainThread(()=>{ for(var i=0;i<photoeye.Length;i++) { emu_to_plc_bits[photoeyeIO[i]] = photoeye[i].getState(); } for(var i=0;i<conveyer_disconnect.Length;i++) { emu_to_plc_bits[conveyer_disconnect_io[i]] = conveyer_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_turn_disconnect.Length;i++) { emu_to_plc_bits[conveyer_turn_disconnect_io[i]] = conveyer_turn_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_merge_disconnect.Length;i++) { emu_to_plc_bits[conveyer_merge_disconnect_io[i]] = conveyer_merge_disconnect[i].getDisconnect(); } for(var i=0;i<hsd_extended_prox.Length;i++) { emu_to_plc_bits[hsd_extended_prox_io[i]] = hsd_extended_prox[i].GetExtended(); } for(var i=0;i<hsd_retracted_prox.Length;i++) { emu_to_plc_bits[hsd_retracted_prox_io[i]] = hsd_retracted_prox[i].GetRetracted(); } for(var i=0;i<vsu_up_prox.Length;i++) { emu_to_plc_bits[vsu_up_prox_io[i]] = vsu_up_prox[i].GetExtended(); } for(var i=0;i<vsu_down_prox.Length;i++) { emu_to_plc_bits[vsu_down_prox_io[i]] = vsu_down_prox[i].GetRetracted(); } for(var i=0;i<cs_button_input.Length;i++) { emu_to_plc_bits[cs_button_input_io[i]] = cs_button_input[i].getState(); } for(var i=0;i<bmas.Length;i++) { emu_to_plc_bits[bma_OK_io[i]] = bmas[i].getBMA_OK(); emu_to_plc_bits[bma_OOG_io[i]] = bmas[i].getBMA_OOG(); } sendResponse(sender,emu_to_plc_bits,temptrigger.ToString()); }); } else{ Loom.QueueOnMainThread(()=>{ for(var i=0;i<photoeye.Length;i++) { emu_to_plc_bits[photoeyeIO[i]] = photoeye[i].getState(); } for(var i=0;i<conveyer_disconnect.Length;i++) { emu_to_plc_bits[conveyer_disconnect_io[i]] = conveyer_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_turn_disconnect.Length;i++) { emu_to_plc_bits[conveyer_turn_disconnect_io[i]] = conveyer_turn_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_merge_disconnect.Length;i++) { emu_to_plc_bits[conveyer_merge_disconnect_io[i]] = conveyer_merge_disconnect[i].getDisconnect(); } for(var i=0;i<hsd_extended_prox.Length;i++) { emu_to_plc_bits[hsd_extended_prox_io[i]] = hsd_extended_prox[i].GetExtended(); } for(var i=0;i<hsd_retracted_prox.Length;i++) { emu_to_plc_bits[hsd_retracted_prox_io[i]] = hsd_retracted_prox[i].GetRetracted(); } for(var i=0;i<vsu_up_prox.Length;i++) { emu_to_plc_bits[vsu_up_prox_io[i]] = vsu_up_prox[i].GetExtended(); } for(var i=0;i<vsu_down_prox.Length;i++) { emu_to_plc_bits[vsu_down_prox_io[i]] = vsu_down_prox[i].GetRetracted(); } for(var i=0;i<cs_button_input.Length;i++) { emu_to_plc_bits[cs_button_input_io[i]] = cs_button_input[i].getState(); } for(var i=0;i<bmas.Length;i++) { emu_to_plc_bits[bma_OK_io[i]] = bmas[i].getBMA_OK(); emu_to_plc_bits[bma_OOG_io[i]] = bmas[i].getBMA_OOG(); } }); sendResponse(sender,emu_to_plc_bits,temptrigger.ToString()); } //sender.SendData(Encoding.UTF8.GetString(BitArrayToByteArray(emu_to_plc_bits))); string[] dataArray; // Message parts are divided by "|" Break the string into an array accordingly. // Basically what happens here is that it is possible to get a flood of data during // the lock where we have combined commands and overflow // to simplify this proble, all I do is split the response by char 13 and then look // at the command, if the command is unknown, I consider it a junk message // and dump it, otherwise I act on it /* dataArray = data.Split((char) 13); dataArray = dataArray[0].Split((char) 124); // dataArray(0) is the command. switch( dataArray[0]) { case "CONNECT": ConnectUser(dataArray[1], sender); break; case "CHAT": SendChat(dataArray[1], sender); break; case "DISCONNECT": DisconnectUser(sender); break; default: // Message is junk do nothing with it. break; }*/ } private void Update() { if(getnewinputs) { return; } if(!ready) { return; } /// Go through and update all the output bits!! on EVERY frame! for(var i=0;i<photoeye.Length;i++) { emu_to_plc_bits[photoeyeIO[i]] = photoeye[i].getState(); } for(var i=0;i<conveyer_disconnect.Length;i++) { emu_to_plc_bits[conveyer_disconnect_io[i]] = conveyer_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_turn_disconnect.Length;i++) { emu_to_plc_bits[conveyer_turn_disconnect_io[i]] = conveyer_turn_disconnect[i].getDisconnect(); } for(var i=0;i<conveyer_merge_disconnect.Length;i++) { emu_to_plc_bits[conveyer_merge_disconnect_io[i]] = conveyer_merge_disconnect[i].getDisconnect(); } for(var i=0;i<hsd_extended_prox.Length;i++) { emu_to_plc_bits[hsd_extended_prox_io[i]] = hsd_extended_prox[i].GetExtended(); } for(var i=0;i<hsd_retracted_prox.Length;i++) { emu_to_plc_bits[hsd_retracted_prox_io[i]] = hsd_retracted_prox[i].GetRetracted(); } for(var i=0;i<vsu_up_prox.Length;i++) { emu_to_plc_bits[vsu_up_prox_io[i]] = vsu_up_prox[i].GetExtended(); } for(var i=0;i<vsu_down_prox.Length;i++) { emu_to_plc_bits[vsu_down_prox_io[i]] = vsu_down_prox[i].GetRetracted(); } // copy this here for(var i=0;i<cs_button_input.Length;i++) { emu_to_plc_bits[cs_button_input_io[i]] = cs_button_input[i].getState(); } for(var i=0;i<bmas.Length;i++) { emu_to_plc_bits[bma_OK_io[i]] = bmas[i].getBMA_OK(); emu_to_plc_bits[bma_OOG_io[i]] = bmas[i].getBMA_OOG(); } } private void sendResponse(UserConnection sender,BitArray emu_to_plc_bits,string temptrigger){ string bitstring = ""; /* //sender.SendData(emu_to_plc_bits.Length.ToString()); for(var i=0;i<emu_to_plc_bits.Length;i++) { if(i%8==0) { bitstring+=" |"; } if(i%4==0) { bitstring+=" "; } if(emu_to_plc_bits[i]==true){ bitstring += "1"; }else{ bitstring +="0"; } }*/ byte[] responsebytes = BitArrayToByteArray(emu_to_plc_bits); for(var i=0; i<responsebytes.Length;i++) { bitstring += responsebytes[i].ToString()+ " "; } sender.SendData(responsebytes); if(loggingenabled) { Debug.Log("Sent (trigger: "+ temptrigger +"):\r\n" + bitstring); } //sender.SendData("trigger:"+temptrigger + " output:" + bitstring);//Encoding.UTF8.GetString(BitArrayToByteArray(emu_to_plc_bits))); } // This subroutine sends a response to the sender. private void ReplyToSender(string strMessage, UserConnection sender) { // sender.SendData(strMessage); } // Send a chat message to all clients except sender. private void SendChat(string message, UserConnection sender) { // UpdateStatus(sender.Name + ": " + message); // SendToClients("CHAT|" + sender.Name + ": " + message, sender); } // Update is called once per frame //void Update () { //} // Use this for initialization /*void Awake() { DontDestroyOnLoad(this); GameObject M_TC1_01 = GameObject.Find("M_TC1_01"); GameObject M_TC1_2 = GameObject.Find("M_TC1_01"); }*/ private byte[] BitArrayToByteArray(BitArray bits) { byte[] ret = new byte[bits.Length / 8]; bits.CopyTo(ret, 0); return ret; } public string GetConnectionString () { String id = "connectionString"; ArrayList lines = new ArrayList(); string line; System.IO.StringReader textStream = new System.IO.StringReader(dbConfig.text); string lineID = "[" + id + "]"; bool match = false; while((line = textStream.ReadLine()) != null) { if (match) { if (line.StartsWith("[")) { break; } if (line.Length > 0) { lines.Add(line); } } else if (line.StartsWith(lineID)) { match = true; } } textStream.Close(); if (lines.Count > 0) { return (string)(((string[])lines.ToArray(typeof(string)))[0]); } return null; } }
using PDV.DAO.Atributos; using System; namespace PDV.DAO.GridViewModels { public class OrdemDeServicoGridViewModel { [CampoTabela(nameof(IDOrdemDeServico))] public decimal IDOrdemDeServico { get; set; } [CampoTabela(nameof(DataCadastro))] public DateTime DataCadastro { get; set; } [CampoTabela(nameof(DataFaturamento))] public DateTime? DataFaturamento { get; set; } [CampoTabela(nameof(ValorTotal))] public decimal ValorTotal { get; set; } [CampoTabela(nameof(Status))] public string Status { get; set; } [CampoTabela(nameof(Cliente))] public string Cliente { get; set; } } }
/** *┌──────────────────────────────────────────────────────────────┐ *│ 描 述: *│ 作 者:zhujun *│ 版 本:1.0 模板代码自动生成 *│ 创建时间:2019-05-23 16:43:42 *└──────────────────────────────────────────────────────────────┘ *┌──────────────────────────────────────────────────────────────┐ *│ 命名空间: EWF.Services *│ 接口名称: ISYS_BACKUSERRepository *└──────────────────────────────────────────────────────────────┘ */ using EWF.Entity; using EWF.Util; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace EWF.IServices { public interface ISYS_BACKUSERService: IDependency { /// <summary> /// 根据IP获取黑名单 /// </summary> /// <param name="ip"></param> /// <returns></returns> dynamic GetBackUser(string ip); /// <summary> /// 插记录 /// </summary> /// <param name="entity">实体</param> /// <returns></returns> string Insert(SYS_BACKUSER entity); } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; namespace TheMinepack.Items.Weapons { public class CactusYoyo : ModItem { public override bool Autoload(ref string name, ref string texture, IList<EquipType> equips) { texture = "TheMinepack/Items/Weapons/CactusYoyo"; return true; } public override void SetDefaults() { item.CloneDefaults(ItemID.WoodYoyo); // Clones Wooden Yoyo // Item Details item.name = "Cactus Yoyo"; item.rare = 0; item.value = Item.sellPrice(0, 0, 0, 30); // Item Animation & Sounds item.useTime = 26; item.useAnimation = 26; item.useStyle = 5; // Item Stats item.melee = true; item.damage = 12; item.knockBack = 2; // Item Functionality item.channel = true; item.autoReuse = false; item.shoot = mod.ProjectileType("CactusYoyoProjectile"); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.Cactus, 20); // 20 Cacti recipe.AddIngredient(ItemID.Cobweb, 10); // 10 Cobweb recipe.AddTile(TileID.WorkBenches); // Workbenches recipe.SetResult(this); recipe.AddRecipe(); } } }
using ShCore.Attributes; using System; namespace ShCore.Types { /// <summary> /// Chỉ định class là Convert cho kiểu dữ liệu nào /// </summary> public class ConverterOfAttribute : ClassInfoAttribute { /// <summary> /// Target => Kiểu dữ liệu mong muốn được thực hiện Convert /// </summary> public Type Target { set; get; } } }