text
stringlengths
13
6.01M
namespace ClearBank.DeveloperTest.Types { public class MakePaymentResult { public bool Success { get; private set; } public MakePaymentResult() { Success = true; } public static MakePaymentResult OK() { return new MakePaymentResult(); } public static MakePaymentResult Fail() { return new MakePaymentResult(){ Success = false}; } } }
using UnityEngine; using System.Collections; public class lgc_indicator : MonoBehaviour { public longcaster myGun; public Rect myRect; public NetworkShipGUI nsg; void OnGUI () { if (myGun.firing) {GUI.DrawTexture(myRect,nsg.ind_white,ScaleMode.StretchToFill);} else { if (myGun.ready) {if (nsg.nsc.capacity>=myGun.eps) GUI.DrawTexture(myRect,nsg.ind_green); else GUI.DrawTexture(myRect,nsg.ind_red);} else {GUI.DrawTexture(myRect,nsg.ind_yellow,ScaleMode.StretchToFill);} } GUI.DrawTexture(myRect,nsg.module_icons[0],ScaleMode.StretchToFill); } }
using Microsoft.AspNetCore.Hosting; using System; using System.Collections.Generic; using System.IO; namespace WaterTrans.GlyphLoader.Demo { public interface ITypefaces { bool ContainsKey(string key); Typeface this[string key] { get; } string[] FontFiles { get; } } public class Typefaces : ITypefaces { private Dictionary<string, Typeface> _typefaces = new Dictionary<string, Typeface>(); public Typefaces() { foreach (string fontFile in FontFiles) { string fontPath = Path.Combine(AppContext.BaseDirectory, fontFile); using (var fontStream = File.OpenRead(fontPath)) { _typefaces[fontFile] = new Typeface(fontStream); } } } public Typeface this[string key] => _typefaces[key]; public string[] FontFiles => new string[] { "NotoSerifJP-Regular.otf", "NotoSansJP-Regular.otf", "Roboto-Regular.ttf", "RobotoMono-Regular.ttf", "Lora-VariableFont_wght.ttf", "Font Awesome 5 Free-Solid-900.otf", "Font Awesome 5 Free-Regular-400.otf", "Font Awesome 5 Brands-Regular-400.otf", "Roboto-Regular.woff2", "RobotoMono-Regular.woff2", }; public bool ContainsKey(string key) { return _typefaces.ContainsKey(key); } } }
using Puppeteer.Core; using System; using System.Threading.Tasks; using UnityEngine; public class ExplosionManager : SingletonMonoBehaviour<ExplosionManager> { private void Start() { foreach(var agent in PuppeteerManager.Instance.GetAgents()) { agent.AddOrUpdateWorkingMemory("IsInDanger", false); } } public float GetDangerRange() { return m_DangerRange; } public Vector3? GetLastExplosionPositionIfAny() { return m_LastExplosionPosition; } public float GetRandomHideDuration() { return UnityEngine.Random.Range(m_MinMaxHideDurationInSeconds.x, m_MinMaxHideDurationInSeconds.y); } private async void ClearLastExplosionPositionAfterWait() { await Task.Delay(TimeSpan.FromSeconds(0.5f)); m_LastExplosionPosition = null; } private async void DestroyExplosionInstanceAfterWait(GameObject _instance) { await Task.Delay(TimeSpan.FromSeconds(m_DestroyExplosionInstanceAfter)); if (Application.isEditor) { DestroyImmediate(_instance); } else { Destroy(_instance); } } private void Update() { if (!Input.GetMouseButtonDown(0)) { return; } if (m_ExplosionPrefab == null) { return; } var ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out var hit, 1000.0f, m_ExplosionRaycastMask)) { DestroyExplosionInstanceAfterWait(Instantiate(m_ExplosionPrefab, hit.point, Quaternion.identity)); m_LastExplosionPosition = hit.point; ClearLastExplosionPositionAfterWait(); } } #pragma warning disable CS0649 [SerializeField] private float m_DangerRange = 5.0f; [SerializeField] private float m_DestroyExplosionInstanceAfter = 1; [SerializeField] private GameObject m_ExplosionPrefab; [SerializeField] private LayerMask m_ExplosionRaycastMask; [SerializeField] private Vector2 m_MinMaxHideDurationInSeconds; #pragma warning restore CS0649 private Vector3? m_LastExplosionPosition = null; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; namespace WebConsole { class Program { static void Main(string[] args) { StartCrawlerAsync(); Console.Read(); } private static async Task StartCrawlerAsync() { var url = "http://www.automobile.tn/neuf/bmw.3/"; var httpClient = new HttpClient(); var html= await httpClient.GetStringAsync(url); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var divs = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("Class", "").Equals("article_new_car article_last_modele")).ToList(); var cars = new List<Car>(); foreach (var div in divs) { var car = new Car() { Model = div.Descendants("h2").FirstOrDefault().InnerText, Prix = div.Descendants("span").FirstOrDefault().InnerText, ImageUrl = div.Descendants("img").FirstOrDefault().ChildAttributes("src").FirstOrDefault().Value, Link= div.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value, }; cars.Add(car); } } } [DebuggerDisplay("{Model},{Prix}")] class Car { public string Model { get; set; } public string Prix { get; set; } public string ImageUrl { get; set; } public string Link { get; set; } } }
using Cinemachine; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Cameras { public class CameraConfineSensor : MonoBehaviour { [SerializeField] [HideInInspector] private CameraConfiner m_confiner; [SerializeField] private CinemachineVirtualCamera m_camera; [SerializeField] [MinValue(0.1f)] private float m_time; public void SetCameraConfiner(CameraConfiner confiner) { m_confiner = confiner; } private void OnTriggerEnter2D(Collider2D collision) { var player = collision.gameObject.GetComponentInParent<Player.Player>(); if (player) { PlayerCamera.TransistionToCamera(m_camera, m_time); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using FireSharp.Interfaces; using FireSharp.Config; using FireSharp.Response; using System.IO; namespace SMS { public partial class update : Form { int Id; string FName, Pone, gender, CuAddress, PeAddress, Dob; Bitmap imge; //, ImgString; IFirebaseClient client; private void btn_upload_Click(object sender, EventArgs e) { OpenFileDialog od = new OpenFileDialog(); od.Filter = "Image files(*.jpg,*.png,*.jpeg,*.bmp)| *.jpg;*.jpeg;*.bmp;*.png| All files (*.*)|*.*"; if (od.ShowDialog() == DialogResult.OK) { profilePic.Load(od.FileName); } } private void btn_clear_Click(object sender, EventArgs e) { this.Close(); } IFirebaseConfig config = new FirebaseConfig() { AuthSecret = "ZKLTdMy5kwia8gbOdBNMW0T59PN0rGP0eNbT7vCi", BasePath = "https://school-c893b-default-rtdb.firebaseio.com/" }; private void update_Load(object sender, EventArgs e) { try { client = new FireSharp.FirebaseClient(config); } catch { MessageBox.Show("Problem in Interet Connection!!"); } fName.Text = FName; dob.Text = Dob; pAddress.Text = PeAddress; cAddress.Text = CuAddress; if (gender == "Male") { btnMale.Checked = true; } if (gender == "Female") { btnFemale.Checked = true; } phone.Text = Pone; // MemoryStream ms = new MemoryStream(imge); // byte[] img = Convert.FromBase64String(imge); profilePic.Image = imge; } public update(int id, string FullName, string Phone, string Gender, string CurrentAddress, string PermanentAddress, string DOB, Bitmap ImgStr) { InitializeComponent(); Id = id; FName = FullName; Pone = Phone; gender = Gender; CuAddress = CurrentAddress; PeAddress = PermanentAddress; Dob = DOB; imge = ImgStr; // ImgString = ImgString; } private void btn_add_Click(object sender, EventArgs e) { var tch = new Teacher { // ID = (Convert.ToInt32(get.cnt) + 1).ToString(), ID = Id.ToString(), FullName = fName.Text, Phone = phone.Text, PermanentAddress = pAddress.Text, CurrentAddress = cAddress.Text, Gender = gender, DOB = dob.Text, ImgString = ImageIntoBase64String(profilePic) }; FirebaseResponse response = client.Update("TeacherList/" + Id.ToString(), tch); Teacher result = response.ResultAs<Teacher>(); MessageBox.Show("data updated successfully" + result.ID); fName.Text = string.Empty; phone.Text = string.Empty; pAddress.Text = string.Empty; cAddress.Text = string.Empty; gender = string.Empty; dob.Text = string.Empty; profilePic.Image = null; } public static string ImageIntoBase64String(PictureBox pbox) { MemoryStream ms = new MemoryStream(); pbox.Image.Save(ms, pbox.Image.RawFormat); return Convert.ToBase64String(ms.ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio15 { class Ordenacaomatrizes { static void Ordena(string[,] A, int Coluna) { for (int P = A.GetLength(0) - 1; P >= 1; P--) for (int Corrente = 0; Corrente <= P - 1; Corrente++) if (A[Corrente, Coluna].CompareTo(A[Corrente + 1, Coluna]) > 0) Troca(A, Corrente); } static void Troca(string[,] A, int Corrente) { string Temp; for (int J = 0; J <= A.GetLength(1) - 1; J++) { Temp = A[Corrente, J]; A[Corrente, J] = A[Corrente + 1, J]; A[Corrente + 1, J] = Temp; } } static void Escrita(string[,] A) { for (int I = 0; I <= A.GetLength(0) - 1; I++) { for (int J = 0; J <= A.GetLength(1) - 1; J++) Console.Write("{0, 10}", A[I, J].PadRight(10)); Console.WriteLine(); } } static void Main(string[] args) { { string[,] A = { { "60", "Rui", "Porto" }, { "20", "Joaquim", "Aveiro" }, { "30", "Adelino", "Porto" }, { "50", "Ricardo", "Coimbra" } }; Console.Write("Coluna (0,1,2) que é chave de ordenação "); int Coluna = Convert.ToInt16(Console.ReadLine()); Ordena(A, Coluna); Escrita(A); } } } }
using System; using System.Collections; using System.Collections.Generic; using com.Sconit.Entity.MD; using com.Sconit.Entity.ORD; using System.Linq; using Castle.Services.Transaction; using com.Sconit.Entity.ACC; using com.Sconit.Entity; namespace com.Sconit.Service.Impl { [Transactional] public class PartyMgrImpl : BaseMgr, IPartyMgr { public IGenericMgr genericMgr { get; set; } #region public methods public IList<Party> GetOrderFromParty(com.Sconit.CodeMaster.OrderType type) { return GetOrderParty(type, "From"); } public IList<Party> GetOrderToParty(com.Sconit.CodeMaster.OrderType type) { return GetOrderParty(type, "To"); } [Transaction(TransactionMode.Requires)] public void Create(Party party) { genericMgr.Create(party); #region 加权限 Permission permission = new Permission(); permission.Code = party.Code; permission.Description = party.CodeDescription; permission.PermissionCategory = party.GetType().Name; genericMgr.Create(permission); #endregion #region 加用户权限 UserPermission up = new UserPermission(); up.Permission = permission; up.User = SecurityContextHolder.Get(); genericMgr.Create(up); #endregion } [Transaction(TransactionMode.Requires)] public void AddPartyAddress(PartyAddress partyAddress) { if (partyAddress.IsPrimary) { this.genericMgr.Update("update from PartyAddress set IsPrimary = ? where Party = ?", new object[] { false, partyAddress.Party }); this.genericMgr.FlushSession(); } genericMgr.Create(partyAddress); } [Transaction(TransactionMode.Requires)] public void UpdatePartyAddress(PartyAddress partyAddress) { if (partyAddress.IsPrimary) { this.genericMgr.Update("update from PartyAddress set IsPrimary = ? where Party = ?", new object[] { false, partyAddress.Party }); this.genericMgr.FlushSession(); } genericMgr.Update(partyAddress); } #endregion #region private methods private IList<Party> GetOrderParty(com.Sconit.CodeMaster.OrderType type, string fromTo) { IList<Customer> customerList = genericMgr.FindAll<Customer>(); IList<Supplier> supplierList = genericMgr.FindAll<Supplier>(); IList<Region> regionList = genericMgr.FindAll<Region>(); IList<Party> partyList = new List<Party>(); if (fromTo == "From") { if (type == com.Sconit.CodeMaster.OrderType.Procurement) { partyList.Union<Party>(supplierList); partyList.Union<Party>(customerList); partyList.Union<Party>(regionList); } else if (type == com.Sconit.CodeMaster.OrderType.ScheduleLine) { partyList.Union<Party>(supplierList); partyList.Union<Party>(regionList); } else if (type == com.Sconit.CodeMaster.OrderType.Distribution) { partyList.Union<Party>(regionList); } else if (type == com.Sconit.CodeMaster.OrderType.Production) { partyList.Union<Party>(regionList); } } else if (fromTo == "To") { if (type == com.Sconit.CodeMaster.OrderType.Procurement) { partyList.Union<Party>(regionList); } else if (type == com.Sconit.CodeMaster.OrderType.ScheduleLine) { partyList.Union<Party>(regionList); } else if (type == com.Sconit.CodeMaster.OrderType.Distribution) { partyList.Union<Party>(customerList); } else if (type == com.Sconit.CodeMaster.OrderType.Production) { partyList.Union<Party>(regionList); } } return partyList; } #endregion } }
using UnityEngine; using UnityEngine.UI; using SimpleJSON; using System.Collections; public class Slot : MonoBehaviour { public string ItemId; public string ItemPlayerId; public string ItemNama; public string ItemType; public string ItemLevel; public string ItemAttack; public string ItemDefense; public string ItemStamina; public int slot,yslot; public bool isi; public Sprite defaultSprite; public GameObject equipments,selected; public Equipment eq; public GameObject RemoveItem,zoomselected; void Start () { } public void OnClick () { if (ItemId != null || ItemId != "" || ItemId != "null") { PlayerPrefs.SetInt ("xslot", slot); RemoveItem.SetActive (true); PlayerPrefs.SetString ("ItemID", ItemId); //StartCoroutine (lepasequipment ()); //if (eq.trans) { // clean_stats (); // eq.trans = false; //} } else { GetComponent<Button> ().interactable = false; } } // public IEnumerator lepasequipment(){ // Debug.Log (PlayerPrefs.GetString ("ItemID")); // string url = Link.url + "remove_item"; // WWWForm form = new WWWForm (); // form.AddField ("MY_ID", PlayerPrefs.GetString(Link.ID)); // form.AddField ("ITEMID", PlayerPrefs.GetString ("ItemID")); // form.AddField ("PlayerHantuID", PlayerPrefs.GetString ("hantuplayerid")); // // WWW www = new WWW(url,form); // yield return www; // if (www.error == null) { // Debug.Log (www.text); // // info.text = file; // // StartCoroutine (updateData ()); // clean_stats(); // } else { // //failed // } // // } public void Update(){ if (equipments.GetComponent<Equipment> ().trans) { if (slot == PlayerPrefs.GetInt ("xslot")) { if (slot == 1) { PlayerPrefs.SetString ("SLOTITEM1", ItemPlayerId); PlayerPrefs.SetInt("tukar1",1); eq.lepas=true; eq.selection1.GetComponent<EquipmentItem> ().slot = 0; //selected.SetActive (false); isi = false; } if (slot == 2) { PlayerPrefs.SetString ("SLOTITEM2", ItemPlayerId); PlayerPrefs.SetInt("tukar2",1); eq.lepas=true; isi = false; // selected.SetActive (false); eq.selection2.GetComponent<EquipmentItem> ().slot = 0; } if (slot == 3) { PlayerPrefs.SetString ("SLOTITEM3", ItemPlayerId); PlayerPrefs.SetInt("tukar3",1); eq.lepas=true; //selected.SetActive (false); isi = false; eq.selection3.GetComponent<EquipmentItem> ().slot = 0; } if (slot == 4) { PlayerPrefs.SetInt("tukar4",1); PlayerPrefs.SetString ("SLOTITEM4", ItemPlayerId); eq.lepas=true; // selected.SetActive (false); isi = false; eq.selection4.GetComponent<EquipmentItem> ().slot = 0; } clean_stats (); } } if (isi == false) { GetComponent<Button> ().interactable = false; } else{ GetComponent<Button> ().interactable = true; } } void clean_stats(){ eq.attackInt = eq.attackInt - int.Parse (ItemAttack); eq.defenseInt = eq.defenseInt - int.Parse (ItemDefense); eq.hpInt = eq.hpInt - int.Parse (ItemStamina); eq.attackText.text = eq.attack + " + <color=green>" + eq.attackInt.ToString()+"</color>"; eq.defenseText.text = eq.defense + " + <color=green>" + eq.defenseInt.ToString()+"</color>"; eq.staminaText.text = eq.hp + " + <color=green>" + eq.hpInt.ToString()+"</color>"; ItemId = ""; ItemNama = ""; ItemType = ""; ItemLevel = ""; ItemAttack = ""; ItemDefense = ""; ItemStamina = ""; ItemPlayerId = ""; //selected.SetActive (false); selected.GetComponent<EquipmentItem>().ItemStatus = "0"; transform.Find ("ImageFile").GetComponent<Image> ().sprite = defaultSprite; equipments.GetComponent<Equipment> ().trans = false; } }
using UnityEngine; [RequireComponent(typeof(Collider2D))] public class DialogueTrigger : MonoBehaviour { public int priority = 0; public bool hideOnExit = true; public bool once = true; public DialogueData[] onEnter; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { if (this.onEnter != null) { foreach (var dialogue in onEnter) { DialogueManager.instance.ShowDialogue(dialogue); } } if (this.once) { Destroy(this.gameObject); } } } private void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag("Player") && this.hideOnExit) { DialogueManager.instance.HideDialogue(this.priority); } } }
using LearningSystem.Models.ViewModels.Courses; namespace LearningSystem.Services.Interfaces { public interface ICourseService { CourseDetailsVm GetDetailsById(int id); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Deveres { public partial class SubjectCreate : Form { string subject; List<Subject> listOfSubjects = new List<Subject>(); SubjectsForm sbf; public SubjectCreate() { InitializeComponent(); } public SubjectCreate(string subjectrenamed,string nameBeforeChange) { InitializeComponent(); listOfSubjects.Remove(listOfSubjects.Find(x=>x.SubjectName==nameBeforeChange)); listOfSubjects.Add(new Subject(subjectrenamed)); dgvSubjects.Rows.Add(subjectrenamed); } public SubjectCreate(List<Subject> list) { InitializeComponent(); listOfSubjects = list; } private void btnAdd_Click(object sender, EventArgs e) { GetData(); if (tbxNameOfSubject.TextLength>0) { if (listOfSubjects.Exists(x=>x.SubjectName==subject)) { MessageBox.Show("materia ja existente"); } listOfSubjects.Add(new Subject(subject)); dgvSubjects.Rows.Add(subject); CleanData(); } else { MessageBox.Show("Preencha o campo"); } using (StreamWriter outputFile = new StreamWriter(@"C: \Users\Windows\Documents\Visual Studio 2015\Projects\Deveres\Deveres\bin\Debug\Notepads" + @"\Subjects.txt")) { foreach (Subject subjects in listOfSubjects) { outputFile.WriteLine(subjects.SubjectName + " @ " + subjects.Homework); } } } public void GetData() { subject = tbxNameOfSubject.Text; } public void CleanData() { tbxNameOfSubject.Text = ""; } private void pbxBack_Click(object sender, EventArgs e) { SubjectsForm sjf = new SubjectsForm(listOfSubjects); sjf.Show(); this.Close(); } private void pbxEdit_Click(object sender, EventArgs e) { if (dgvSubjects.SelectedCells.Count > 0) { Subject dsd = listOfSubjects.Find(x => x.SubjectName == dgvSubjects.CurrentRow.Cells[0].Value); // tbxNameOfSubject.Text = dsd.SubjectName; EditCreatedSubjectsForm scef = new EditCreatedSubjectsForm(dsd.SubjectName); scef.Show(); this.Hide(); } } private void pbxDelete_Click(object sender, EventArgs e) { if (dgvSubjects.SelectedCells.Count>0) { if (listOfSubjects.Exists(x => x.SubjectName == dgvSubjects.CurrentRow.Cells[0].Value.ToString())) { listOfSubjects.Remove(listOfSubjects.Find(x => x.SubjectName == dgvSubjects.CurrentRow.Cells[0].Value.ToString())); dgvSubjects.Rows.RemoveAt(dgvSubjects.CurrentRow.Cells[0].RowIndex); } } } private void SubjectCreate_Load(object sender, EventArgs e) { } } }
namespace IPTV_Checker_2.DTO { public class JsonChannel { public string Name { get; set; } public string Url { get; set; } public string Server { get; set; } public string Status { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { /// <summary> /// 基本上是神经元的集合,负责将Pulse()或ApplyLearning()命令传递给它的成员神经元。 /// 这是通过包装List <INeuron>并传递IList <INeuron>方法和属性来实现的 /// </summary> public class NeuralLayer : INeuralLayer { #region 构造函数 /// <summary> /// 基本上是神经元的集合,负责将Pulse()或ApplyLearning()命令传递给它的成员神经元。 /// </summary> public NeuralLayer() { m_neurons = new List<INeuron>(); } #endregion #region 成员变量 /// <summary> /// 神经元(neuron的复数形式) /// </summary> private List<INeuron> m_neurons; #endregion #region 属性 public int Count { get { return m_neurons.Count; } } public bool IsReadOnly { get { return false; } } #endregion #region 方法 public int IndexOf(INeuron item) { return m_neurons.IndexOf(item); } public void Insert(int index, INeuron item) { m_neurons.Insert(index, item); } public void RemoveAt(int index) { m_neurons.RemoveAt(index); } public INeuron this[int index] { get { return m_neurons[index]; } set { m_neurons[index] = value; } } public void Add(INeuron item) { m_neurons.Add(item); } public void Clear() { m_neurons.Clear(); } public bool Contains(INeuron item) { return m_neurons.Contains(item); } public void CopyTo(INeuron[] array, int arrayIndex) { m_neurons.CopyTo(array, arrayIndex); } public bool Remove(INeuron item) { return m_neurons.Remove(item); } public IEnumerator<INeuron> GetEnumerator() { return m_neurons.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Pulse(INeuralNet net) { foreach (INeuron n in m_neurons) n.Pulse(this); } public void ApplyLearning(INeuralNet net) { double learningRate = net.LearningRate; foreach (INeuron n in m_neurons) n.ApplyLearning(this, ref learningRate); } /// <summary> /// 将所有权重变化设置为零 /// </summary> /// <param name="net">神经网络</param> public void InitializeLearning(INeuralNet net) { foreach (INeuron n in m_neurons) n.InitializeLearning(this); } #endregion } }
using System; using System.Drawing; using System.Reflection; using System.Threading; using System.Timers; using System.Windows.Forms; using TtyRecDecoder; using Timer = System.Timers.Timer; namespace DisplayWindow { public partial class DCSSReplayWindow : Form { public static Thread m_Thread; public TtyRecKeyframeDecoder ttyrecDecoder = null; private delegate void SafeCallDelegate(Bitmap frame); private delegate void SafeCallDelegateTitle(string title); private delegate void SafeCallDelegateTitle2(string title, string title2); private delegate void SafeCallDelegateSeekBar(object obj, ElapsedEventArgs e); private delegate void SafeCallDelegateToggleControls(bool shouldShow); private Timer loopTimer; public bool run = true; public DCSSReplayWindow() { InitializeComponent(); PlayButton.Image = Image.FromFile(@"..\..\..\Extra\pause.png"); typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, SeekBar, new object[] { true }); loopTimer = new Timer(); loopTimer.Interval = 10; loopTimer.Enabled = false; loopTimer.Elapsed += loopTimerEvent; loopTimer.AutoReset = true; } public void UpdateTitle(string text) { try { if (run && InvokeRequired) { var d = new SafeCallDelegateTitle(UpdateTitle); IAsyncResult ar = this.BeginInvoke(d, new object[] { text }); ar.AsyncWaitHandle.WaitOne(); } else { Text = text; } } catch (System.Exception) { } } public void UpdateTime(string start, string end) { if (StartTimeLabel.InvokeRequired ) { var d = new SafeCallDelegateTitle2(UpdateTime); IAsyncResult ar2 = this.BeginInvoke(d, new object[] { start, end }); // ar2.AsyncWaitHandle.WaitOne(); } else { if (StartTimeLabel.Text != start) { StartTimeLabel.Text = start; EndTimeLabel.Text = end; SeekBar.Invalidate(); } } } public void ShowControls(bool shouldShow) { try { if (shouldShow != label1.Visible) { if (InvokeRequired) { var d = new SafeCallDelegateToggleControls(ShowControls); this.Invoke(d, new object[] { shouldShow }); } else { label1.Visible = shouldShow; } } } catch (System.Exception) { } } public void Update2(Bitmap frame) { if (frame == null && pictureBox2.Image == null) return; pictureBox2.Image = frame; } public void SeekBar_Paint(object sender, PaintEventArgs e) { var start = ttyrecDecoder == null ? new System.TimeSpan(0) : ttyrecDecoder.CurrentFrame.SinceStart; var end = ttyrecDecoder == null ? new System.TimeSpan(0) : ttyrecDecoder.Length; var progress = start.TotalMilliseconds / end.TotalMilliseconds; if(progress>0) { var rect = new Rectangle( e.ClipRectangle.Left, e.ClipRectangle.Top, (int)(SeekBar.Width * progress), SeekBar.Height ); e.Graphics.DrawRectangle(Pens.DarkBlue, rect); e.Graphics.FillRectangle(new SolidBrush(Color.DarkBlue), rect); } } private void SeekBar_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { loopTimer.Enabled = true; } } private void loopTimerEvent(Object source, ElapsedEventArgs e) { if (SeekBar.InvokeRequired) { var d = new SafeCallDelegateSeekBar(loopTimerEvent); this.Invoke(d, new object[] { source, e }); } else { var MouseCoordinates = SeekBar.PointToClient(Cursor.Position); double progress = (double)(MouseCoordinates.X) / SeekBar.Width; ttyrecDecoder.SeekTime = new TimeSpan((long)(ttyrecDecoder.Length.Ticks * progress)); } } private void SeekBar_MouseUp(object sender, MouseEventArgs e) { loopTimer.Enabled = false; } public readonly AutoResetEvent mWaitForThread = new AutoResetEvent(false); private void DCSSReplayWindow_FormClosing(object sender, FormClosingEventArgs e) { run = false; // mWaitForThread.WaitOne(); } public void PlayButton_Click(object sender, System.EventArgs e) { this.ActiveControl = null; if (ttyrecDecoder == null) return; if (ttyrecDecoder.PlaybackSpeed != 0) { PlayButton.Image = Image.FromFile(@"..\..\..\Extra\play.png"); ttyrecDecoder.Pause(); } else { PlayButton.Image = Image.FromFile(@"..\..\..\Extra\pause.png"); ttyrecDecoder.Unpause(); } } } }
using Terraria; using Terraria.ID; using Terraria.ModLoader; using Terraria.Graphics.Effects; using Microsoft.Xna.Framework; namespace ReducedGrinding.Items { public class Slime_Rain_Potion : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Slime Rain Potion"); Tooltip.SetDefault("Starts/stops slime rain"); } public override void SetDefaults() { item.width = 20; item.height = 30; item.maxStack = 30; item.rare = 2; item.useAnimation = 45; item.useTime = 45; item.useStyle = 4; item.value = Item.buyPrice(0, 0, 2, 30); item.UseSound = SoundID.Item3; item.consumable = true; } public override bool CanUseItem(Player player) { return true; } public override bool UseItem(Player player) { if (Main.slimeRain) StopSlimeRain(true); else StartSlimeRain(true); return true; } private static void StopSlimeRain(bool announce = true) { if (!Main.slimeRain) { return; } if (Main.netMode == 1) { Main.slimeRainTime = 0.0; Main.slimeRain = false; SkyManager.Instance.Deactivate("Slime", new object[0]); return; } int num = 86400 * 7; if (Main.hardMode) { num *= 2; } Main.slimeRainTime = (double)(-(double)Main.rand.Next(3024, 6048) * 100); Main.slimeRain = false; if (Main.netMode == NetmodeID.SinglePlayer) { if (announce) { Main.slimeWarningTime = Main.slimeWarningDelay; } SkyManager.Instance.Deactivate("Slime", new object[0]); return; } if (announce) { Main.slimeWarningTime = Main.slimeWarningDelay; NetMessage.SendData(7, -1, -1, null, 0, 0f, 0f, 0f, 0, 0, 0); } } public static void StartSlimeRain(bool announce = true) { if (Main.slimeRain) { return; } if (Main.netMode == 1) { Main.slimeRainTime = 54000.0; Main.slimeRain = true; SkyManager.Instance.Activate("Slime", default(Vector2), new object[0]); return; } if (Main.raining) { return; } Main.slimeRainTime = (double)Main.rand.Next(32400, 54000); Main.slimeRain = true; Main.slimeRainKillCount = 0; if (Main.netMode == NetmodeID.SinglePlayer) { SkyManager.Instance.Activate("Slime", default(Vector2), new object[0]); if (announce) { Main.slimeWarningTime = Main.slimeWarningDelay; return; } } else { if (announce) { Main.slimeWarningTime = Main.slimeWarningDelay; NetMessage.SendData(7, -1, -1, null, 0, 0f, 0f, 0f, 0, 0, 0); } } } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(mod.ItemType("Rain_Potion"), 1); recipe.AddIngredient(ItemID.Gel, 1); recipe.AddTile(TileID.Bottles); recipe.SetResult(this); recipe.AddRecipe(); } } }
// Animations for the shark, similar to "FishAnims" script using UnityEngine; using System.Collections; public class SharkAnims : MonoBehaviour { public enum anim {None, IdleLeft, EatLeft, IdleRight, EatRight} OTAnimatingSprite mySprite; anim currentAnim; public GameObject Shark; private Shark shark; // Use this for initialization void Start () { mySprite = GetComponent<OTAnimatingSprite>(); shark = this.gameObject.GetComponent<Shark>(); } // Update is called once per frame void Update () { // Turn Left if(shark.isLeft && shark.idle && !shark.swim && currentAnim != anim.IdleLeft) { currentAnim = anim.IdleLeft; mySprite.Play("idleleft"); } if(!shark.isLeft && shark.idle && !shark.swim && currentAnim != anim.IdleRight) { currentAnim = anim.IdleRight; mySprite.Play("idleright"); } if(shark.isLeft && !shark.idle && shark.swim && currentAnim != anim.EatLeft) { currentAnim = anim.EatLeft; mySprite.Play("eatleft"); } if(!shark.isLeft && !shark.idle && shark.swim && currentAnim != anim.EatRight) { currentAnim = anim.EatRight; mySprite.Play("eatright"); } } }
using System; using System.Collections.Generic; using System.Text; namespace gView.Framework.Geometry { public static class GeometryConst { public const double Epsilon = 1e-8; } }
using Exiled.API.Features; using Server = Exiled.Events.Handlers.Server; using Player = Exiled.Events.Handlers.Player; using System; namespace SCP106ContainRework { public class Main : Plugin<Config> { EventHandlers EventHandler; public override Version Version => new Version(1, 0, 1); public override Version RequiredExiledVersion => new Version(3, 0, 0); public override void OnEnabled() { EventHandler = new EventHandlers(); Server.RoundStarted += EventHandler.RoundStart; Player.Dying += EventHandler.SCP106Recontainment; Player.InteractingDoor += EventHandler.DoorInteract; base.OnEnabled(); } public override void OnDisabled() { EventHandler = null; Server.RoundStarted -= EventHandler.RoundStart; Player.Dying -= EventHandler.SCP106Recontainment; Player.InteractingDoor -= EventHandler.DoorInteract; base.OnDisabled(); } } }
using System; using System.Threading; using System.Web; namespace HTB.v2.intranetx { public abstract class Task { protected object _results; protected string _taskID; public Task(string taskID) { _taskID = taskID; } public abstract void Run(); public abstract void Run(object data); public object Results { get { return _results; } } } public class LengthyTask : Task { private int _seconds; public LengthyTask(string taskID) : base(taskID) { _seconds = 5; } public int Seconds { get { return _seconds; } set { _seconds = value; } } public override void Run() { for (int i = 1; i <= _seconds; i++) { TaskHelpers.UpdateStatus(_taskID, string.Format("Step {0} out of {1}", i, _seconds)); Thread.Sleep(1000); } Thread.Sleep(1000); _results = string.Format("Task completed at {0}", DateTime.Now); TaskHelpers.ClearStatus(_taskID); } public override void Run(object data) { for (int i = 1; i <= _seconds; i++) { TaskHelpers.UpdateStatus(_taskID, string.Format("Step {0} out of {1}", i, _seconds)); Thread.Sleep(1000); } Thread.Sleep(1000); _results = string.Format("Task completed at {0} : Data=‘{1}’", DateTime.Now, data); TaskHelpers.ClearStatus(_taskID); } } public class TaskHelpers { public static void UpdateStatus(string taskID, string info) { HttpContext context = HttpContext.Current; context.Cache[taskID] = info; } public static string GetStatus(string taskID) { HttpContext context = HttpContext.Current; object o = context.Cache[taskID]; if (o == null) return string.Empty; return (string)o; } public static void ClearStatus(string taskID) { HttpContext context = HttpContext.Current; context.Cache.Remove(taskID); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CuredZombie : MonoBehaviour { private SpriteRenderer Sprite; public ZombieDamageController zombieDamageController; // Start is called before the first frame update void Start() { Sprite = gameObject.GetComponent<SpriteRenderer>(); } //When cured, turns off the zombie sprite public void CuredZ() { Sprite.enabled = false; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace NA { public static class Utility { public static IEnumerator Lerp<T>( T begin, T end, float duration, AnimationCurve curve, Func<T, T, float, T> Lerp, Action<T> OnValueChanged, Action OnCompleted = null) { var beginTime = Time.time; var endTime = beginTime + duration; var t = 0f; OnValueChanged(begin); for (; ; ) { t = curve.Evaluate((Time.time - beginTime) / duration); OnValueChanged(Lerp(begin, end, t)); if (Time.time >= endTime) break; yield return null; } OnValueChanged(end); if (OnCompleted != null) OnCompleted(); } } }
using Puppeteer.UI.External.GraphVisualizer; using System; using UnityEditor; using UnityEngine; namespace Puppeteer.UI { internal class PuppeteerPlanGraphRenderer : DefaultGraphRenderer { public PuppeteerPlanGraphRenderer(Action<VisualiserBaseNode> _nodeClickedCallback) { OnNodeClicked += _node => _nodeClickedCallback(_node as VisualiserBaseNode); ColorUtility.TryParseHtmlString(EditorGUIUtility.isProSkin ? "#282828" : "#a5a5a5", out var colour); m_InspectorBackgroundColour = colour; } public void Draw(IGraphLayout _graphLayout, Rect _totalDrawingArea, GraphSettings _graphSettings, PuppeteerPlanVisualiser _visualiser) { var drawingArea = new Rect(_totalDrawingArea); if (_graphSettings.ShowInspector) { var inspectorArea = new Rect(_totalDrawingArea) { width = Mathf.Max(INSPECTOR_FIXED_WIDTH, drawingArea.width * 0.25f) + BORDER_SIZE * 2 }; inspectorArea.x = drawingArea.xMax - inspectorArea.width; drawingArea.width -= inspectorArea.width; DrawInspector(inspectorArea, _visualiser); } Draw(_graphLayout, drawingArea, _graphSettings); } private void DrawInspector(Rect _inspectorArea, PuppeteerPlanVisualiser _visualiser) { EditorGUI.DrawRect(_inspectorArea, m_InspectorBackgroundColour); _inspectorArea.Apply(ref m_BorderOffsetRect); GUILayout.BeginArea(_inspectorArea); GUILayout.BeginVertical(); if (m_SelectedNode != null) { using (var scrollView = new EditorGUILayout.ScrollViewScope(m_ScrollPosition)) { m_ScrollPosition = scrollView.scrollPosition; } (m_SelectedNode as VisualiserBaseNode)?.DrawInspector(_visualiser); } else { GUILayout.Label("Click on a node\nto display its details."); } GUILayout.FlexibleSpace(); GUILayout.EndVertical(); GUILayout.EndArea(); } private static readonly float BORDER_SIZE = 15; private static readonly float INSPECTOR_FIXED_WIDTH = 100; private static Rect m_BorderOffsetRect = new Rect(BORDER_SIZE, BORDER_SIZE, -(BORDER_SIZE * 2), - (BORDER_SIZE * 2)); private readonly Color m_InspectorBackgroundColour; private Vector2 m_ScrollPosition; } }
using System.Collections; using System.Windows; namespace Crystal.Plot2D.DataSources { /// <summary> /// This enumerator enumerates given enumerable object as sequence of points /// </summary> /// <typeparam name="T">Type parameter of source IEnumerable</typeparam> public sealed class EnumerablePointEnumerator<T> : IPointEnumerator { public EnumerableDataSource<T> DataSource { get; } public IEnumerator Enumerator { get; } public EnumerablePointEnumerator(EnumerableDataSource<T> _dataSource) { DataSource = _dataSource; Enumerator = _dataSource.Data.GetEnumerator(); } public bool MoveNext() => Enumerator.MoveNext(); public void GetCurrent(ref Point p) => DataSource.FillPoint((T)Enumerator.Current, ref p); public void ApplyMappings(DependencyObject target) => DataSource.ApplyMappings(target, (T)Enumerator.Current); public void Dispose() { //enumerator.Reset(); } } }
using RoboticMovementType.BaseMovementModel; using RoboticMovementType.Enums; using RoboticMovementType.Interface; using System; namespace RoboticMovementType { /// <summary> /// Rover can move with the command /// Rover also moves on the plateau on the planets /// </summary> public class RoboticRover : Rover { public IMatrix Plateau { get; set; } public RoboticRover(IPosition position, Direction direction, IMatrix plateau) : base(position, direction) { this.Plateau = plateau; if (!RoverInMatrix()) return; } /// <summary> /// Is Rover in the plateau /// </summary> /// <returns></returns> private bool RoverInMatrix() { return (Position.X >= 0) && (Position.X < Plateau.Matrixx) && (Position.Y >= 0) && (Position.Y < Plateau.Matrixy); } /// <summary> /// Command that allows the rover to move /// </summary> /// <param name="moveCommand"></param> /// <returns></returns> public override bool Move(string moveCommand) { char[] moveInputs = moveCommand.ToCharArray(); foreach (char movement in moveInputs) { switch (Enum.Parse(typeof(Movement), movement.ToString())) { case Movement.L: base.MoveLeft(); break; case Movement.R: base.MoveRight(); break; case Movement.M: this.MoveAhead(); break; default: throw new ArgumentException(string.Format("Incorrect input : {0}", movement)); } } return true; } /// <summary> /// Rover go ahead /// Rover also be carefull /// </summary> public override void MoveAhead() { base.MoveAhead(); if (this.Position.X < 0 || this.Position.Y < 0 || this.Position.X > this.Plateau.Matrixx || this.Position.Y > this.Plateau.Matrixy) throw new OperationCanceledException("Rover can not move, process canceled"); } } }
using System; using System.Collections.Generic; namespace _2018_08_11 { class Program { static void Main(string[] args) { Console.WriteLine("Please choose what to record:"); Console.WriteLine("1) Cat"); Console.WriteLine("2) Dog"); Console.WriteLine("3) Baby"); int selection = int.Parse(Console.ReadLine()); Console.WriteLine($"You chose {selection}."); List<INameable> nameables = new List<INameable>(); switch (selection) { case 1: var cat = new Cat(); nameables.Add(cat); break; case 2: var dog = new Dog(); nameables.Add(dog); break; case 3: var baby = new Baby(); nameables.Add(baby); break; default: throw new Exception(); } foreach (INameable named in nameables) { Console.WriteLine($"Hello, {named.GetName()}!"); } } } public interface INameable { string GetName(); } public interface IPet { } public interface IWalkable { void GoForWalk(); } public class Cat : IPet, INameable { public string LitterBoxLocation { get; set; } public string GetName() { return "Kitty"; } } public class Dog : IPet, IWalkable, INameable { public string GetName() { return "Mr. Barkers"; } public void GoForWalk() { Console.WriteLine("Woof woof! We're going on a walk! Yay!"); } } public class Baby : IWalkable, INameable { public void GoForWalk() { Console.WriteLine("Goo goo! Gaa gaa! I'm in a stroller!"); } public string GetName() { return "Elliot"; } } }
using UnityEngine; using UnityEditor; using Ardunity; [CustomEditor(typeof(ExplosionReactor))] public class ExplosionReactorEditor : ArdunityObjectEditor { private bool _useGizmo = true; SerializedProperty script; SerializedProperty effectRadius; SerializedProperty explosionForce; SerializedProperty oneShotOnly; SerializedProperty layerMask; void OnEnable() { script = serializedObject.FindProperty("m_Script"); effectRadius = serializedObject.FindProperty("effectRadius"); explosionForce = serializedObject.FindProperty("explosionForce"); oneShotOnly = serializedObject.FindProperty("oneShotOnly"); layerMask = serializedObject.FindProperty("layerMask"); } public override void OnInspectorGUI() { this.serializedObject.Update(); ExplosionReactor reactor = (ExplosionReactor)target; GUI.enabled = false; EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]); GUI.enabled = true; EditorGUILayout.PropertyField(effectRadius, new GUIContent("effectRadius")); EditorGUILayout.PropertyField(explosionForce, new GUIContent("explosionForce")); EditorGUILayout.PropertyField(oneShotOnly, new GUIContent("oneShotOnly")); EditorGUILayout.PropertyField(layerMask, new GUIContent("layerMask")); bool useGizmo = EditorGUILayout.Toggle("Use Gizmo", _useGizmo); if(useGizmo != _useGizmo) { _useGizmo = useGizmo; SceneView.RepaintAll(); } if(Application.isPlaying && reactor.oneShotOnly) { if(GUILayout.Button("Reset")) reactor.ResetOneShot(); } this.serializedObject.ApplyModifiedProperties(); } void OnSceneGUI() { if(!_useGizmo) return; ExplosionReactor reactor = (ExplosionReactor)target; Handles.color = Color.yellow; reactor.effectRadius = Handles.RadiusHandle(Quaternion.identity, reactor.transform.position, reactor.effectRadius); } static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func) { string menuName = "Unity/Add Reactor/Physics/ExplosionReactor"; if(Selection.activeGameObject != null) menu.AddItem(new GUIContent(menuName), false, func, typeof(ExplosionReactor)); else menu.AddDisabledItem(new GUIContent(menuName)); } }
using DChild.Gameplay.Player; using Sirenix.OdinInspector; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MagicRegen : MonoBehaviour { [SerializeField] [MinValue(0)] private int m_regen; private IMagicPoint m_playerMagicPoint; private IEnumerator Regen() { while (true) { m_playerMagicPoint.AddValue(m_regen); yield return new WaitForSeconds(1f); } } private void Awake() { m_playerMagicPoint = GetComponentInParent<IPlayer>().magicPoint; StartCoroutine(Regen()); } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Android.App; using Android.Content; using Android.Gms.Common.Apis; using Android.Gms.Location; using Android.Gms.Maps.Model; using Android.Runtime; using Android.Support.V7.App; using Android.Util; using Android.Views; using Android.Widget; using Android.OS; using Java.Interop; using Java.Lang; using Java.Util; using Exception = System.Exception; namespace Geofence { [Activity(Label = "Geofence", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/Theme.Base")] public class MainActivity : ActionBarActivity, IGoogleApiClientConnectionCallbacks, IGoogleApiClientOnConnectionFailedListener, IResultCallback { protected static string TAG = "creating-and-monitoring-geofences"; protected IGoogleApiClient mGoogleApiClient; protected IList<IGeofence> mGeofenceList; private bool mGeofencesAdded; private PendingIntent mGeofencePendingIntent; private ISharedPreferences mSharedPreferences; private Button mAddGeofencesButton; private Button mRemoveGeofencesButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); mAddGeofencesButton = (Button) FindViewById(Resource.Id.add_geofences_button); mRemoveGeofencesButton = (Button) FindViewById(Resource.Id.remove_geofences_button); mGeofenceList = new List<IGeofence>(); mGeofencePendingIntent = null; mSharedPreferences = GetSharedPreferences(Constants.SHARED_PREFERENCES_NAME, FileCreationMode.Private); mGeofencesAdded = mSharedPreferences.GetBoolean(Constants.GEOFENCES_ADDED_KEY, false); SetButtonsEnabledState(); PopulateGeofenceList(); BuildGoogleApiClient(); } [MethodImpl(MethodImplOptions.Synchronized)] protected void BuildGoogleApiClient() { mGoogleApiClient = new GoogleApiClientBuilder(this) .AddConnectionCallbacks(this) .AddOnConnectionFailedListener(this) .AddApi(LocationServices.API) .Build(); } protected override void OnStart() { base.OnStart(); mGoogleApiClient.Connect(); } protected override void OnStop() { base.OnStop(); mGoogleApiClient.Disconnect(); } public void OnResult(Java.Lang.Object rawStatus) { var status = Extensions.JavaCast<IResult>(rawStatus); if (status.Status.IsSuccess) { mGeofencesAdded = !mGeofencesAdded; ISharedPreferencesEditor editor = mSharedPreferences.Edit(); editor.PutBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded); editor.Commit(); SetButtonsEnabledState(); Toast.MakeText(this, GetString(mGeofencesAdded ? Resource.String.geofences_added : Resource.String.geofences_removed), ToastLength.Short).Show(); } else { string errorMessage = GeofenceErrorMessages.GetErrorString(this, status.Status.StatusCode); Log.Error(TAG, errorMessage); } } public void OnConnectionFailed(Android.Gms.Common.ConnectionResult result) { Log.Info(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.ErrorCode); } public void OnConnected(Bundle connectionHint) { Log.Info(TAG, "Connected to GoogleApiClient"); } public void OnConnectionSuspended(int cause) { Log.Info(TAG, "Connection suspended"); } private GeofencingRequest GetGeofencingRequest() { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.SetInitialTrigger(GeofencingRequest.InitialTriggerEnter); builder.AddGeofences(mGeofenceList); return builder.Build(); } [Export("AddGeofencesButtonHandler")] public void AddGeofencesButtonHandler(View view) { if (!mGoogleApiClient.IsConnected) { Toast.MakeText(this, GetString(Resource.String.not_connected), ToastLength.Short).Show(); return; } try { LocationServices.GeofencingApi.AddGeofences(mGoogleApiClient, GetGeofencingRequest(), GetGeofencePendingIntent()).SetResultCallback(this); } catch (SecurityException securityException) { LogSecurityException(securityException); } } [Export("RemoveGeofencesButtonHandler")] public void RemoveGeofencesButtonHandler(View view) { if (!mGoogleApiClient.IsConnected) { Toast.MakeText(this, GetString(Resource.String.not_connected), ToastLength.Short).Show(); return; } try { LocationServices.GeofencingApi.RemoveGeofences(mGoogleApiClient, GetGeofencePendingIntent()).SetResultCallback(this); } catch (SecurityException securityException) { LogSecurityException(securityException); } } private void LogSecurityException(SecurityException securityException) { Log.Error(TAG, "Invalid location permission. " + "You need to use ACCESS_FINE_LOCATION with geofences", securityException); } private PendingIntent GetGeofencePendingIntent() { if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } Intent intent = new Intent(this, typeof(GeofenceTransitionsIntentService)); return PendingIntent.GetService(this, 0, intent, PendingIntentFlags.UpdateCurrent); } public void PopulateGeofenceList() { foreach (var entry in Constants.BAY_AREA_LANDMARKS) { mGeofenceList.Add(new GeofenceBuilder() .SetRequestId(entry.Key) .SetCircularRegion(entry.Value.Latitude, entry.Value.Longitude, Constants.GEOFENCE_RADIUS_IN_METERS) .SetExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) .SetTransitionTypes(Android.Gms.Location.Geofence.GeofenceTransitionEnter | Android.Gms.Location.Geofence.GeofenceTransitionExit) .Build()); } } private void SetButtonsEnabledState() { if (mGeofencesAdded) { mAddGeofencesButton.Enabled = false; mRemoveGeofencesButton.Enabled = true; } else { mAddGeofencesButton.Enabled = true; mRemoveGeofencesButton.Enabled = false; } } } }
using System; using FrontDesk.Core.Aggregates; using PluralsightDdd.SharedKernel; using Xunit; namespace UnitTests.Core.AggregatesEntities.AppointmentTests { public class Appointment_UpdateTime { private readonly DateTime _startTime = new DateTime(2021, 01, 01, 10, 00, 00); private readonly DateTime _endTime = new DateTime(2021, 01, 01, 12, 00, 00); [Fact] public void UpdatesTimeRange() { var scheduleId = Guid.NewGuid(); const int clientId = 1; const int patientId = 2; const int roomId = 3; const int appointmentTypeId = 4; const int doctorId = 5; const string title = "Title Test"; var appointment = Appointment.Create(scheduleId, clientId, patientId, roomId, _startTime, _endTime, appointmentTypeId, doctorId, title); var newEndTime = new DateTime(2021, 01, 01, 11, 00, 00); var range = new DateTimeRange(_startTime, newEndTime); appointment.UpdateTime(range); Assert.Equal(range.DurationInMinutes(), appointment.TimeRange.DurationInMinutes()); } } }
using System; namespace Task_05 { class Program { static string Triangle(double AB, double BC, double CA) { string bad_result = "Треугольник не существует"; string result = AB + BC > CA ? (BC + CA > AB ? (CA + AB > BC ? "Треугольник существует" : bad_result) : bad_result) : bad_result; return AB > 0 && BC > 0 && CA > 0 ? result : bad_result; } static void Main(string[] args) { try { Console.WriteLine("Введите длины всех сторон треугольника через пробел"); string[] input = Console.ReadLine().Split(); double AB = Math.Round(double.Parse(input[0]), 3); double BC = Math.Round(double.Parse(input[1]), 3); double CA = Math.Round(double.Parse(input[2]), 3); Console.WriteLine(Triangle(AB, BC, CA)); Console.ReadLine(); } catch (Exception) { Console.WriteLine("Ошибка!"); } } } }
namespace Funding.Common.Constants { public class ProjectConst { public const string ProjectNameRequired = "Your project should have a name"; public const string ProjectDescriptionRequired = "Your project should have a clear description"; public const string ProjectImageUrlRequired = "Please verify that you are sending image link"; public const string StartDateMessage = "Start date should be greater than "; public const string EndDateMessage = "End date should be greater than Start Date"; public const string GoalRequired = "You need to have goal money"; public const string TagRequired = "You should have atleast on tag"; public const string GoalNegativeMessage = "Goal money cannot be negative"; public const string Success = "Succesfully added project"; public const string Failed = "Something went wrong try again"; public const string DoesntExist = "This project doesn't exist"; public const string ProjectAdded = "Your project was succesfully added.The admin should approve it before people can see it."; public const string Comment = "Comment cannot be empty"; public const string ProjectDeleted = "Project deleted"; public const string ProjectFunded = "Project {0} funded by {1}"; public const string DonateMessageRequired = "Please tell the creator why you liked his project"; public const string DonateAmountRequired = "Please enter valid number greater than 0.1"; public const string StartDateRequired = "Start Date need to be selected"; public const string EndDateRequired = "End Date need to be selected"; public const string ProjectApproved = "Your project was approved"; public const string ProjectNotApproved = "Your project was not approved"; public const string TempDataDeletedComment = "commentDelete"; public const string DeletedCommentSuccess = "Comment successfully deleted"; public const string DeletedCommentFailed = "You do not have permission to do that!"; public const string NoResults ="Sorry we couldn't find any match"; public const string SuccesfullyEdited = "Project succesfully edited"; public const string AlreadyDonated = "You've already donated for this project !"; public const string SuccessfullyDonated = "{0} euro succesfully donated!"; public const string ImageUrlDisplay = "Image URL"; public const string StartDateDisplay = "Project Start Date"; public const string EndDateDisplay = "Project End Date"; public const string Approved = "Approved"; public const string Deleted = "Deleted"; public const string Disabled = "disabled"; public const string TempDataUnauthorized = "unauthorized"; public const string TempDataDeleted = "deletedSuccess"; public const string TempDataSorry = "sorry"; public const string TempDataDonated = "message1"; public const string TempDataMessage = "message"; public const string TempDataAddedProject = "addedProject"; public const string TempDataNoResults = "noResult"; public const int MaxLenght = 2400; public const int ImageUrlMinLenght = 5; public const int MinimumGoal = 1; public const int NameMinLength = 2; public const int NameМaxLength = 100; public const int DescriptionMinLenght = 10; public const int DescriptionMaxLenght = 600; public const int CommentMinLength = 2; public const int CommentMaxLength = 250; public const double MinimumAmountToDonate = 0.01; public const string Jpeg = "jpeg"; public const string Jpg = "jpg"; public const string Png = "png"; public const string Gif = "gif"; } }
namespace Azure.Security.Tests { using System; using System.IO; using System.Runtime.Caching; using Interfaces; using Security; using Exceptions; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; [TestClass] [DeploymentItem(@"TestFiles\TestCertificate.pfx")] public class AzureCryptoTests { private const string TableName = "TestTableName"; private const string TestString = "This is some test value"; private static readonly Guid TestUserId = new Guid("e6f41e92-a89f-47ab-b511-224260f3bb55"); private readonly CloudStorageAccount acct = CloudStorageAccount.Parse("UseDevelopmentStorage=true"); private static IRsaHelper rsaHelper; private static ISymmetricKeyTableManager tableManager; public TestContext TestContext { get; set; } [TestInitialize] public void TestSetup() { var deploymentDirectory = TestContext.DeploymentDirectory; rsaHelper = new RsaHelper(Path.Combine(deploymentDirectory, "TestCertificate.pfx"), "test"); tableManager = new SymmetricKeyTableManager(TableName,acct); tableManager.CreateTableIfNotExists(); } [TestCleanup] public void TestTearDown() { tableManager.DeleteTableIfExists(); MemoryCache.Default.Dispose(); } [TestMethod] public void TestAzureTableCryptoInitializesSuccessfully() { //Create the master key if it doesn't exist var newKey = rsaHelper.CreateNewAesSymmetricKeyset(null); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, null); var c = new AzureCrypto(keyStore); Assert.IsNotNull(c); } [TestMethod] public void TestAzureTableCryptoThrowsTableNotFoundException() { // Delete table to simulate empty Azure storage tableManager.DeleteTableIfExists(); Action action = () => { var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, null); var c = new AzureCrypto(keyStore); c.GetEncryptor(); }; action.ShouldThrow<AzureCryptoException>(); } [TestMethod] public void TestAzureTableCryptoThrowsTableNotFoundExceptionWithUserId() { // Delete table to simulate empty Azure storage tableManager.DeleteTableIfExists(); Action action = () => { var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, TestUserId); var c = new AzureCrypto(keyStore); c.GetEncryptor(TestUserId); }; action.ShouldThrow<AzureCryptoException>(); } [TestMethod] public void TestAzureTableCryptoHasValidEncryptor() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, null); var c = new AzureCrypto(keyStore); c.Should().NotBeNull("At this stage the contstructor should have succeeded"); var encryptor = c.GetEncryptor(); encryptor.Should().NotBeNull("Because the keystore is initialized and there is a key"); } [TestMethod] public void TestAzureTableCryptoHasValidEncryptorWithUserId() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(TestUserId); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, TestUserId); var c = new AzureCrypto(keyStore); c.Should().NotBeNull("At this stage the contstructor should have succeeded"); var encryptor = c.GetEncryptor(TestUserId); encryptor.Should().NotBeNull("Because the keystore is initialized and there is a key"); } [TestMethod] public void EncryptionShouldWorkAsExpected() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, null); var c = new AzureCrypto(keyStore); var encryptedString = c.EncryptStringAndBase64(TestString); encryptedString.Should().NotBeNullOrEmpty("Because the encryption failed"); encryptedString.Should().NotMatch(TestString); } [TestMethod] public void EncryptionShouldWorkAsExpectedWithUserId() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(TestUserId); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, TestUserId); var c = new AzureCrypto(keyStore); var encryptedString = c.EncryptStringAndBase64(TestString, TestUserId); encryptedString.Should().NotBeNullOrEmpty("Because the encryption failed"); encryptedString.Should().NotMatch(TestString); } [TestMethod] public void DecryptionShouldReturnTheOriginalString() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(null); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, null); var c = new AzureCrypto(keyStore); var encryptedString = c.EncryptStringAndBase64(TestString); var decryptedString = c.DecryptStringFromBase64(encryptedString); decryptedString.ShouldBeEquivalentTo(TestString); } [TestMethod] public void DecryptionShouldReturnTheOriginalStringWithUserId() { var newKey = rsaHelper.CreateNewAesSymmetricKeyset(TestUserId); tableManager.AddSymmetricKey(newKey); var keyStore = new SymmetricKeyCache(rsaHelper, tableManager, TestUserId); var c = new AzureCrypto(keyStore); var encryptedString = c.EncryptStringAndBase64(TestString, TestUserId); var decryptedString = c.DecryptStringFromBase64(encryptedString, TestUserId); decryptedString.ShouldBeEquivalentTo(TestString); } } }
using ProjetoMVC.Ultis; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace ProjetoMVC.Models.Repositorios { public class FornecedorREP : Repositorio<Fornecedor, int> { ///<summary>Exclui um fornecedor pela entidade ///<param name="entity">Referência de Fornecedor que será excluída.</param> ///</summary> /// string tabela = "Fornecedores"; public override void Delete(Fornecedor entity) { TelefoneREP telefoneREP = new TelefoneREP(); List<Telefone> telefones = telefoneREP.GetByRef(entity.Id); foreach (var telefone in telefones) telefoneREP.Delete(telefone); using (var conn = new SqlConnection(StringConnection)) { string sql = "DELETE " + tabela + " Where Id=@Id"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Id", entity.Id); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } ///<summary>Exclui um fornecedor pelo ID ///<param name="id">Id do registro que será excluído.</param> ///</summary> public override void DeleteById(int id) { using (var conn = new SqlConnection(StringConnection)) { string sql = "DELETE " + tabela + " Where Id=@Id"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Id", id); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } ///<summary>Obtém todas os fornecedores ///<returns>Retorna os fornecedores cadastrados.</returns> ///</summary> public override List<Fornecedor> GetAll() { string sql = "Select " + " a.Id, " + " a.Nome, " + " a.CpfCnpj, " + " a.DataCadastro, " + " a.RG, " + " a.DataNascimento, " + " b.NomeFantasia as Empresa " + " FROM " + tabela + " a , Empresas b " + " where b.Id=a.Empresa " + " ORDER BY Nome"; using (var conn = new SqlConnection(StringConnection)) { var cmd = new SqlCommand(sql, conn); List<Fornecedor> list = new List<Fornecedor>(); try { conn.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { list.Add(PreencherDados(reader)); } } } catch (Exception e) { throw e; } return list; } } ///<summary>Preenche os dados de um fornecedor ///<param name="reader">Referencia da tupla obtida na consulta.</param> ///<returns>Retorna uma referência de Fornecedor preenchida com os dados obtidos.</returns> ///</summary> private Fornecedor PreencherDados(SqlDataReader reader) { int idade = Validador.CalcularIdade(Validador.converter(reader["DataNascimento"].ToString())); return new Fornecedor() { Id = (int)reader["Id"], Empresa = reader["Empresa"].ToString(), Nome = reader["Nome"].ToString(), CpfCnpj = reader["CpfCnpj"].ToString(), DataHoraCadastro = DateTime.Parse(reader["DataCadastro"].ToString()), RG = reader["RG"].ToString(), DataNascimento = Validador.converter(reader["DataNascimento"].ToString()), Idade = idade == 0 ? "" : idade.ToString() }; } ///<summary>Obtém um fornecedor pelo ID ///<param name="id">Id do registro que obtido.</param> ///<returns>Retorna uma referência de Fornecedor do registro encontrado ou null se ele não for encontrado.</returns> ///</summary> public override Fornecedor GetById(int id) { using (var conn = new SqlConnection(StringConnection)) { string sql = "Select " + " a.Id, " + " a.Nome, " + " a.CpfCnpj, " + " a.DataCadastro, " + " a.RG, " + " a.DataNascimento, " + " b.NomeFantasia as Empresa " + " FROM " + tabela + " a , Empresas b " + " WHERE a.Id=@Id " + " and a.Empresa=b.Id " + " ORDER BY a.Nome"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Id", id); try { conn.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (reader.HasRows) { if (reader.Read()) { return PreencherDados(reader); } } } } catch (Exception e) { throw e; } return null; } } ///<summary>Obtém um fornecedor pelo ID ///<param name="nome">Id do registro que obtido.</param> ///<returns>Retorna uma referência de Fornecedor do registro encontrado ou null se ele não for encontrado.</returns> ///</summary> public override Fornecedor GetByName(string nome) { using (var conn = new SqlConnection(StringConnection)) { string sql = "Select " + " a.Id, " + " a.Nome, " + " a.CpfCnpj, " + " a.DataCadastro, " + " a.RG, " + " a.DataNascimento, " + " b.NomeFantasia as Empresa " + " FROM " + tabela + " a , Empresas b " + " WHERE a.Nome=@Nome " + " and a.Empresa=b.Id " + " ORDER BY a.Nome "; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Nome", nome); try { conn.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (reader.HasRows) { if (reader.Read()) { return PreencherDados(reader); } } } } catch (Exception e) { throw e; } return null; } } public override List<Fornecedor> GetByRef(int id) { using (var conn = new SqlConnection(StringConnection)) { string sql = "Select a.Id, " + " a.Nome, " + " a.CpfCnpj, " + " a.DataCadastro, " + " a.RG, " + " a.DataNascimento, " + " b.NomeFantasia as Empresa " + " FROM " + tabela + " a , Empresas b " + " WHERE a.Empresa=@Empresa " + " and b.Id=@Empresa " + " ORDER BY a.Nome"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Empresa", id); List<Fornecedor> list = new List<Fornecedor>(); try { conn.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (reader.HasRows) { while (reader.Read()) { list.Add(PreencherDados(reader)); } } } } catch (Exception e) { throw e; } return list; } } ///<summary>Salva um fornecedor no banco ///<param name="entity">Referência de Fornecedor que será salva.</param> ///</summary> public override void Save(Fornecedor entity) { using (var conn = new SqlConnection(StringConnection)) { EmpresaREP empresaREP = new EmpresaREP(); Empresa empresa = empresaREP.GetByName(entity.Empresa); string sql = "INSERT INTO " + tabela + "(Empresa,Nome,CpfCnpj,DataCadastro,RG,DataNascimento ) " + "values(@Empresa," + "@Nome," + "@CpfCnpj," + "CONVERT(datetime, @DataCadastro, 103)," + "@RG," + "CONVERT(datetime, @DataNascimento, 103)" + ")"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@DataCadastro", DateTime.Now); cmd.Parameters.AddWithValue("@Empresa", empresa.Id); ComplementarParametros(ref cmd, entity); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } ///<summary>Atualiza um fornecedor no banco ///<param name="entity">Referência de Fornecedor que será atualizada.</param> ///</summary> public override void Update(Fornecedor entity) { using (var conn = new SqlConnection(StringConnection)) { string sql = "UPDATE " + tabela + "" + " SET " + " Nome=@Nome, " + " CpfCnpj=@CpfCnpj " + " Where Id=@Id "; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Id", entity.Id); ComplementarParametros(ref cmd, entity); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } ///<summary>Complementa os parametros para executar comandos no banco de dados ///<param name="cmd">Acesso direto ao objeto de que receberá os novos parametros.</param> ///<param name="entity">Referencia do objeto que possui as informações.</param> ///</summary> private void ComplementarParametros(ref SqlCommand cmd, Fornecedor entity) { cmd.Parameters.AddWithValue("@Nome", entity.Nome); cmd.Parameters.AddWithValue("@CpfCnpj", entity.CpfCnpj); cmd.Parameters.AddWithValue("@RG", entity.RG); cmd.Parameters.AddWithValue("@DataNascimento", entity.DataNascimento); } } }
using Comun.EntityFramework; using Datos.Interface; using Datos.Repositorio; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Datos.Fachada { public class UsuarioFachada { private readonly IUsuario interfaz; public UsuarioFachada() { interfaz = new UsuarioRepositroio(); } public object Guardar(object Parametro) { Usuarios usuario = (Usuarios)Parametro; if (usuario.Nombre.Length > 10) { return "Ingresaste más de 10 caracteres."; } return interfaz.Guardar(Parametro); } } }
using Sales.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace Sales.Services { public class ClientServices { ClientAccountServices caServ = new ClientAccountServices(); public void AddClient(Client client) { using (SalesDB db = new SalesDB()) { db.Clients.Add(client); db.SaveChanges(); } } public void DeleteClient(Client client) { using (SalesDB db = new SalesDB()) { db.Clients.Attach(client); db.Clients.Remove(client); db.SaveChanges(); } } public void UpdateClient(Client client) { using (SalesDB db = new SalesDB()) { db.Entry(client).State = EntityState.Modified; db.SaveChanges(); } } public int GetClientsNumer(string key) { using (SalesDB db = new SalesDB()) { return db.Clients.Include(i => i.ClientAccounts).Where(w => (w.Name + w.Address + w.Telephone).Contains(key)).Count(); } } public Client GetClient(int id) { using (SalesDB db = new SalesDB()) { return db.Clients.Include(i => i.ClientAccounts).SingleOrDefault(s => s.ID == id); } } public Client GetClient(string name) { using (SalesDB db = new SalesDB()) { return db.Clients.SingleOrDefault(s => s.Name == name); } } public List<string> GetNamesSuggetions() { using (SalesDB db = new SalesDB()) { List<string> newData = new List<string>(); var data = db.Clients.OrderBy(o => o.Name).Select(s => new { s.Name }).Distinct().ToList(); foreach (var item in data) { newData.Add(item.Name); } return newData; } } public List<string> GetAddressSuggetions() { using (SalesDB db = new SalesDB()) { List<string> newData = new List<string>(); var data = db.Clients.OrderBy(o => o.Telephone).Select(s => new { s.Telephone }).Distinct().ToList(); foreach (var item in data) { newData.Add(item.Telephone); } return newData; } } public List<Client> GetClients() { using (SalesDB db = new SalesDB()) { return db.Clients.OrderBy(o => o.Name).ToList(); } } public List<ClientVM> SearchClients(string key, int page) { using (SalesDB db = new SalesDB()) { return db.Clients.Include(i => i.ClientAccounts).Where(w => (w.Name + w.Address + w.Telephone) .Contains(key)).OrderBy(o => o.Name).Skip((page - 1) * 17).Take(17) .Select(s => new ClientVM { Address = s.Address, ID = s.ID, Name = s.Name, Telephone = s.Telephone, ClientAccounts = s.ClientAccounts.Count(), Account = s.AccountStart + ((db.ClientsAccounts.Where(w => w.ClientID == s.ID).Count()) > 0 ? db.ClientsAccounts.Where(w => w.ClientID == s.ID && !w.Statement.Contains("خصومات")).Sum(d => d.Credit) - db.ClientsAccounts.Where(w => w.ClientID == s.ID && !w.Statement.Contains("خصومات")).Sum(d => d.Debit) : 0 - (db.ClientsAccounts.Where(w => w.ClientID == s.ID && w.Statement.Contains("خصومات")).Count()) > 0 ? db.ClientsAccounts.Where(w => w.ClientID == s.ID && w.Statement.Contains("خصومات")).Sum(w => w.Credit) : 0) }).ToList(); } } } }
using System; namespace NewFeatures._7_0 { public class ReferenceDemo { public static void Run() { int[] numbers = {1, 2, 3}; ref int refToSecond = ref numbers[1]; // getting value -> copy to variable var valueOfSecond = refToSecond; // modify through a reference refToSecond = 123; // second value will be 123 Console.WriteLine(string.Join(", ", numbers)); // 1. references can not be rebind -> refToSecond = ref numbers[0] // 2. reference persist even if array has changed its size Array.Resize(ref numbers, 1); Console.WriteLine($"second = {refToSecond}, array size is {numbers.Length}"); refToSecond = 321; Console.WriteLine($"second = {refToSecond}, array size is {numbers.Length}"); int[] moreNumbers = {10, 20, 30}; //using function that returns reference ref int refToThirty = ref Find(moreNumbers, 30); refToThirty = 1000; // using Min function and getting ref to minimum value int a = 1, b = 2; ref int min = ref Min(ref a, ref b); } // getting reference using function static ref int Find(int[] numbers, int value) { for (int i = 0; i < numbers.Length; i++) { if (numbers[i] == value) return ref numbers[i]; } throw new ArgumentException("meh"); } static ref int Min(ref int x, ref int y) { if (x < y) return ref x; return ref y; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BenefitDeductionAPI.Models.EmployeeBenefitDeduction { public class BenefitDeductionDetailDto { public decimal AnnualTotalCostGross { get; set; } public decimal AnnualTotalCostNet { get; set; } public decimal AnnualSalaryAjustment { get; set; } public decimal PerPayPeriodTotalCostGross { get; set; } public decimal PerPayPeriodTotalCostNet { get; set; } public decimal PerPayPeriodSalaryAjustment { get; set; } public decimal PerPayPeriodBenefitAjustment { get; set; } public decimal EmployeeSalary { get; set; } public decimal EmployeeSalaryPerPayPeriod { get; set; } public List<BenefitDeductionItemDto> BenefitDeductionItems { get; set; } = new List<BenefitDeductionItemDto>(); } }
namespace BettingSystem.Application.Competitions.Leagues.Commands.Edit { using Common; using FluentValidation; public class EditLeagueCommandValidator : AbstractValidator<EditLeagueCommand> { public EditLeagueCommandValidator() => this.Include(new LeagueCommandValidator<EditLeagueCommand>()); } }
using AutoMapper; using FamilyAccounting.AutoMapper; using FamilyAccounting.BL.DTO; using FamilyAccounting.BL.Interfaces; using FamilyAccounting.BL.Services; using FamilyAccounting.DAL.Connection; using FamilyAccounting.DAL.Entities; using FamilyAccounting.DAL.Interfaces; using FamilyAccounting.DAL.Repositories; using FamilyAccounting.Web.Models; using Moq; using NUnit.Framework; using System; using System.Threading.Tasks; namespace FamilyAccounting.Tests.ServiceTests { public class CardServiceTests { [Test] public void CardService_CreateAnObject() { //Arrange DbConfig dbConfig = new DbConfig(); ICardRepository cardRepository = new CardRepository(dbConfig); var mock = new Mock<IMapper>(); string expected = "CardService"; //Act CardService cardService = new CardService(mock.Object, cardRepository); //Assert Assert.IsNotNull(cardService); Assert.AreEqual(expected, cardService.GetType().Name); } [Test] public void CreateCard_ShouldCallCreateInDalOnce() { //Arrange CardDTO cardDTO = new CardDTO { Description = "Description", }; var mockMapper = new Mock<IMapper>(); var mockRepository = new Mock<ICardRepository>(); ICardService service = new CardService(mockMapper.Object, mockRepository.Object); mockRepository.Setup(x => x.CreateAsync(It.IsAny<Card>())).ReturnsAsync(It.IsAny<Card>()); //Act service.Create(cardDTO); //Assert mockRepository.Verify(x => x.Create(It.IsAny<Card>()), Times.Once); } [Test] public async Task CreateCard_ShouldReturnCardDTO() { //Arrange CardDTO shouldBe = new CardDTO { Description = "Description", }; CardDTO cardDTO = new CardDTO { Description = "Description", }; var mock = new Mock<ICardService>(); mock.Setup(x => x.CreateAsync(cardDTO)).ReturnsAsync(cardDTO); //Act var result = await mock.Object.CreateAsync(cardDTO); //Assert Assert.IsNotNull(result); Assert.AreEqual(shouldBe.GetType().Name, result.GetType().Name); } [Test] public void CardService_UpdateCard_ShouldNotBeNull() { //Arrange CardDTO card = new CardDTO() { WalletId = 1, Description = "for shopping", }; var cardId = card.WalletId; var mock = new Mock<ICardService>(); //Act var result = mock.Setup(a => a.Update(cardId, card)); //Assert Assert.IsNotNull(result); } [Test] public void CardService_Verify_UpdateCardCalledOnce() { //Arrange CardDTO card = new CardDTO() { WalletId = 1, Description = "for shopping", }; var cardId = card.WalletId; var mock = new Mock<ICardService>(); //Act mock.Object.Update(cardId, card); //Assert mock.Verify(m => m.Update(cardId, card), Times.Once); } [Test] public void CardService_UpdateCard_ThrowsException() { //Arrange CardDTO card = new CardDTO() { WalletId = 1, Description = "for shopping", }; var cardId = card.WalletId; var mock = new Mock<ICardService>(); //Act mock.Setup(a => a.Update(cardId, card)).Throws(new Exception("Test Exception")); //Assert Assert.That(() => mock.Object.Update(cardId, card), Throws.Exception); } [Test] public void CardService_GetCard_ShouldNotBeNull() { //Arrange var serviceMock = new Mock<ICardService>(); int id = 1; //act var result = serviceMock.Setup(a => a.Get(id)); //assert Assert.IsNotNull(result); } [Test] public void CardService_GetCard_ThrowsException() { //Arrange var mock = new Mock<ICardService>(); int id = 0; //Act mock.Setup(a => a.Get(id)).Throws(new Exception("Test Exception")); //Assert Assert.That(() => mock.Object.Get(id), Throws.Exception); } [Test] public void CardtService_Verify_GetCardCalledOnce() { //Arrange var serviceMock = new Mock<ICardService>(); int id = 1; //Act serviceMock.Object.Get(id); //Assert serviceMock.Verify(m => m.Get(id), Times.Once); } [Test] public void DeleteShouldCallDeleteInDalOnce() { //Arrange var mockRepository = new Mock<ICardRepository>(); var mockMapper = new Mock<IMapper>(); ICardService service = new CardService(mockMapper.Object, mockRepository.Object); mockRepository.Setup(x => x.DeleteAsync(1)).ReturnsAsync(It.IsAny<int>); //Act service.Delete(1); //Assert mockRepository.Verify(x => x.Delete(1), Times.Once); } [Test] public void CardService_DeleteCard_ThrowsException() { //Arrange var mock = new Mock<ICardService>(); //Act mock.Setup(a => a.Delete(1)).Throws(new Exception("Test Exception")); //Assert Assert.That(() => mock.Object.Delete(1), Throws.Exception); } [Test] public void DeleteCard_Success_CallsRepositoryWithCorrectParameters() { //Arrenge int status = 1; var cardViewModel = new CardViewModel() { WalletId = 1 }; var cardRepoMock = new Mock<ICardRepository>(); cardRepoMock.Setup(r => r.DeleteAsync(It.IsAny<int>())).ReturnsAsync(status); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); var cardService = new CardService(mapper, cardRepoMock.Object); //Act var result = cardService.Delete(cardViewModel.WalletId); //Assert cardRepoMock.Verify(r => r.Delete(It.Is<int>(id => id == cardViewModel.WalletId)), Times.Once); } [Test] public void DeleteCard_IsNotNull() { //Arrenge int status = 1; var cardViewModel = new CardViewModel(); var cardRepoMock = new Mock<ICardRepository>(); cardRepoMock.Setup(r => r.DeleteAsync(It.IsAny<int>())).ReturnsAsync(status); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); var walletService = new CardService(mapper, cardRepoMock.Object); //Act var result = walletService.Delete(cardViewModel.WalletId); //Assert Assert.IsNotNull(result); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class gameover : MonoBehaviour { public float elapseTime; //setting the elapsed time for running public float endTime = 2.0f; //when reach end time it will go to another scene // Update is called once per frame void Update () { elapseTime += Time.deltaTime; if (elapseTime > endTime) { Menu_Manager.Instance.HighScore(); //after timer ends go to highscore } } }
using Euler_Logic.Helpers; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems { public class Problem152 : ProblemBase { public override string ProblemName { get { return "152: Writing 1/2 as a sum of inverse squares"; } } /* Whenever you add fractions, if you introduce a new prime factor, the lcm will undoubtedly be higher. You have to find another number with that same prime factor to reduce it. So I knew that any combination of distinct integers can't use more than a few prime factors, and those prime factors have to be small. So after much testing and trial/error, I narrowed it down to just 5 prime factors: 2, 3, 5, 7, and 13. My next method is to try all combinations of numbers that have at least one of those prime factors. You can reduce the variations to check by (1) stopping when the resulting fraction is greater than or equal to 1/2, and (2) not adding a new fraction if the difference between it and 1/2 is less than the smallest possible size fraction that we can make. Even despite these, the number of combinations is still too high. So instead of trying all combinations recursively, I precalculate all possible subsets of the highest 20 numbers. Then, when trying combinations, I stop just before the highest 20 and check if the the remainder to 1/2 exists in those subsets. That significantly reduces the number of combinations I have to check. Also, instead of using fractions, I simply calculate the lcm of all valid numbers. Because we are not using all numbers between 2 and 80, the lcm is within ulong range. */ private PrimeSieve _primes; private int _count; public override string GetAnswer() { int max = 80; int remove = 20; _primes = new PrimeSieve((ulong)max); FindNumsWithPrimeLimit(new List<ulong>() { 2, 3, 5, 7, 13 }, (ulong)max); int subsetMax = _validNums.Count - remove; InitializeBigInt(); ComputeBottomSubsets((int)subsetMax - 1, 0); _validNums.RemoveRange(subsetMax - 1, remove + 1); Recursive(1); return _count.ToString(); } private List<ulong> _validNums = new List<ulong>(); private void FindNumsWithPrimeLimit(List<ulong> primes, ulong max) { for (ulong num = 2; num <= max; num++) { var temp = num; foreach (var prime in primes) { while (temp % prime == 0) { temp /= prime; } } if (temp == 1) { _validNums.Add(num); } } } private Dictionary<ulong, ulong> _lcm = new Dictionary<ulong, ulong>(); private ulong _half; private ulong _max; private void InitializeBigInt() { ulong lcm = 1; foreach (var num in _validNums) { lcm = LCM.GetLCM(lcm, num * num); } foreach (var num in _validNums) { _lcm.Add(num, lcm / (num * num)); } _half = lcm / 2; _max = _lcm[_validNums.Last()]; _current = _lcm[2]; } private ulong _current; private void Recursive(int index) { if (index == _validNums.Count) { var remainder = _half - _current; if (_subsets.ContainsKey(remainder)) { _count += _subsets[remainder]; } } else { var tempCurrent = _current; var num = _validNums[index]; _current += _lcm[num]; if (_current < _half && _half - _current >= _max) { Recursive(index + 1); } _current = tempCurrent; Recursive(index + 1); } } private Dictionary<ulong, int> _subsets = new Dictionary<ulong, int>(); private void ComputeBottomSubsets(int index, ulong sum) { var num = _lcm[_validNums[index]]; var nextSum = sum + num; if (nextSum <= _half) { if (index < _validNums.Count - 1) { ComputeBottomSubsets(index + 1, nextSum); } else { if (!_subsets.ContainsKey(nextSum)) { _subsets.Add(nextSum, 1); } else { _subsets[nextSum]++; } } } if (index < _validNums.Count - 1) { ComputeBottomSubsets(index + 1, sum); } else { if (!_subsets.ContainsKey(sum)) { _subsets.Add(sum, 1); } else { _subsets[sum]++; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ControllerCamera : MonoBehaviour { public float speedMoveWinCamera = 1; public float speedLossVibrate = 10f; public GameObject EffectLoss; private bool gameIsFinish = false; private bool isLoss = false; private int Derection = 1; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Player.player.isLoss || Player.player.isWin && !gameIsFinish) { transform.parent = Player.player.transform.parent; gameIsFinish = true; if (EffectLoss) StartCoroutine(WaitAndSetActive(EffectLoss, 2, true)); if (Player.player.isLoss && !isLoss) { isLoss = true; StartCoroutine(waitAndchangeDerection(0.1f)); } } if (gameIsFinish) { transform.position += speedMoveWinCamera * Vector3.up * Time.deltaTime; } IsLoss(); } void IsLoss() { if (isLoss) { transform.position += speedLossVibrate * transform.right * Time.deltaTime * Derection; speedLossVibrate = Mathf.Clamp(speedLossVibrate - 1f, 0, speedLossVibrate); } } public IEnumerator WaitAndSetActive(GameObject Object, float TimeWaiting, bool value) { yield return new WaitForSeconds(TimeWaiting); Object.SetActive(value); } IEnumerator waitAndchangeDerection(float wait) { yield return new WaitForSeconds(wait); Derection = (Derection == -1) ? 1 : -1; StartCoroutine(waitAndchangeDerection(0.1f)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class DetectCollisions : MonoBehaviour { Player player; GameManager gameManager; void Start() { player = FindObjectOfType<Player>(); gameManager = FindObjectOfType<GameManager>(); } void Update() { } private void OnTriggerEnter(Collider other) { if (gameObject.CompareTag("Cow")) { gameManager.updateCowScore(); } else if (gameObject.CompareTag("Horse")) { gameManager.updateHorseScore(); } else if (gameObject.CompareTag("Dog")) { gameManager.updateDogScore(); } Destroy(gameObject); Destroy(other.gameObject); gameManager.updateBreadScore(); } }
using System.Runtime.Serialization; namespace com.Sconit.CodeMaster { public enum PermissionCategoryType { Menu = 0, Url = 1, Region = 2, Customer = 3, Supplier = 4, Terminal = 5, SI = 6, OrderType = 7, Carrier = 8 } public enum RoleType { Normal = 0, System = 1 } public enum UserType { Normal = 0, System = 1, Supplier = 2, } public enum BillType { /// <summary> /// 采购 /// </summary> Procurement = 0, /// <summary> /// 销售 /// </summary> Distribution = 1, /// <summary> /// 运输 /// </summary> Transport = 2, } public enum BillSubType { /// <summary> /// 采购 /// </summary> Normal = 0, /// <summary> /// 销售 /// </summary> Cancel = 1 } public enum InterfacePriceType { /// <summary> /// 采购 /// </summary> Purchase = 10, /// <summary> /// 委外 /// </summary> Subconctract = 20, /// <summary> /// 寄售价格 /// </summary> Consignment = 30, } public enum BillTransactionType { POPlanBill = 1, POPlanBillVoid = 2, SOPlanBill = 3, SOPlanBillVoid = 4, POSettle = 11, POSettleVoid = 12, SOSettle = 13, SOSettleVoid = 14, POBilled = 21, POBilledVoid = 22, SOBilled = 23, SOBilledVoid = 24, } public enum PriceListType { Procuement = 1, Distribution = 2 } public enum InspectType { Quantity = 1, Barcode = 2 } public enum InspectStatus { Submit = 0, InProcess = 1, Close = 2 } public enum JudgeResult { Qualified = 0, Rejected = 1 } public enum OrderType { Procurement = 1, Transfer = 2, Distribution = 3, Production = 4, SubContract = 5, CustomerGoods = 6, SubContractTransfer = 7, ScheduleLine = 8 } public enum OrderPriority { Normal = 0, Urgent = 1 } public enum LocationLevel { Donotcollect = 0,//不汇总 Factory = 3, //工厂 Region = 1, //区域 SinglePlant = 2 //分厂 } public enum SendStatus { NotSend = 0, Success = 1, Fail = 2 } public enum OrderStatus { Create = 0, Submit = 1, InProcess = 2, Complete = 3, Close = 4, Cancel = 5 } public enum ReceiveGapTo { AdjectLocFromInv = 0, //调整发货方库存 RecordIpGap = 1 //记录收货差异 } public enum CreateHuOption { //NoCreate = 0, //不创建 //Release = 1, //释放 //Start =2, //上线 //Ship = 3, //发货 //Receive = 4 //收货 None = 0, //不创建 //Submit = 1, //释放创建 //Start = 2, //上线创建 Ship = 3, //发货创建 Receive = 4 //收货创建 } public enum ReCalculatePriceOption { Manual = 0, //手工 Submit = 1, //释放 Start = 2, //上线 Ship = 3, //发货 Receive = 4 //收货 } public enum OrderBillTerm { NA = 0, //空 ReceivingSettlement = 1, //收货结算 AfterInspection = 2, //检验结算 OnlineBilling = 3, //上线结算 LinearClearing = 4, //下线结算 ConsignmentBilling = 5 //寄售结算 } public enum OrderSubType { Normal = 0,//SY01 Return = 1, //退货 采购、销售、移库、生产、客供、委外 Other = 40,//挤出废品报工 } public enum AddressType { ShipAddress = 0, BillAddress = 1 } public enum InventoryType { Quality = 0, //按数量 Barcode = 1 //按条码 } //public enum ItemType //{ // Purchase = 1, // Sales = 2, // Manufacture = 3, // SubContract = 4, // CustomerGoods = 5, // Virtual = 6, // Kit = 7 //} //public enum PartyType //{ // Region = 0, // Supplier = 1, // Customer = 2 //} public enum WorkingCalendarType { Work = 0, Rest = 1 } //public enum SpecialTimeType //{ // Work = 0, // Rest = 1 //} public enum RejectStatus { Create = 0, Submit = 1, InProcess = 2, Close = 3 } public enum QualityType //库存质量状态 { Qualified = 0, //正常 Inspect = 1, //待验 Reject = 2, //不合格品 } public enum OccupyType //库存质量状态 { None = 0, //Not Occupy Pick = 1, //拣货 Inspect = 2,//检验 Sequence = 3,//排序 MiscOrder = 4,//计划外出入库 //AutoPick = 5//系统拣货,只占用库存,没有拣货单 } public enum TimeUnit { NA = 0, Second = 1, Minute = 2, Hour = 3, Day = 4, Week = 5, Month = 6, Quarter = 7, Year = 8 } public enum WindowTimeType { FixedWindowTime = 0, CycledWindowTime = 1, } public enum StockTakeType { Part = 0, All = 1 } public enum StockTakeStatus { Create = 0, Submit = 1, InProcess = 2, Complete = 3, Close = 4, Cancel = 5 } public enum IssuePriority { Normal = 0, Urgent = 1 } public enum IssueStatus { Create = 0, Submit = 1, InProcess = 2, Complete = 3, Close = 4, Cancel = 5 } public enum IssueType { Issue = 0, Improvement = 1, Changepoint = 2 } /// <summary> /// 库存事务 /// </summary> public enum TransactionType { LOC_INI = 0, //库存初始化 //销售 ISS_SO = 101, //销售出库 ISS_SO_VOID = 102, //销售出库冲销 RCT_SO = 103, //销售退货入库 RCT_SO_VOID = 104, //销售退货入库冲销 //采购 RCT_PO = 201, //采购入库 RCT_PO_VOID = 202, //采购入库冲销 ISS_PO = 203, //采购退货 ISS_PO_VOID = 204, //采购退货冲销 RCT_SL = 205, //计划协议入库 RCT_SL_VOID = 206, //计划协议入库冲销 ISS_SL = 207, //计划协议退货 ISS_SL_VOID = 208, //计划协议退货冲销 //库内事务 ISS_TR = 301, //移库出库 ISS_TR_VOID = 302, //移库出库冲销 RCT_TR = 303, //移库入库 RCT_TR_VOID = 304, //移库入库冲销 ISS_TR_RTN = 311, //移库退货出库 ISS_TR_RTN_VOID = 312, //移库退货出库冲销 RCT_TR_RTN = 313, //移库退货入库 RCT_TR_RTN_VOID = 314, //移库退货入库冲销 ISS_STR = 305, //委外移库出库 ISS_STR_VOID = 306, //委外移库出库冲销 RCT_STR = 307, //委外移库入库 RCT_STR_VOID = 308, //委外移库入库冲销 ISS_STR_RTN = 315, //委外移库退货出库 ISS_STR_RTN_VOID = 316, //委外移库退货出库冲销 RCT_STR_RTN = 317, //委外移库退货入库 RCT_STR_RTN_VOID = 318, //委外移库退货入库冲销 ISS_REP = 351, //翻箱出库 RCT_REP = 352, //翻箱入库 ISS_PUT = 353, //上架出库 RCT_PUT = 354, //上架入库 ISS_PIK = 355, //下架出库 RCT_PIK = 356, //下架入库 ISS_IIC = 361, //库存物料替换出库 ISS_IIC_VOID = 362, //库存物料替换出库冲销 RCT_IIC = 363, //库存物料替换入库 RCT_IIC_VOID = 364, //库存物料替换入库冲销 //生产 ISS_WO = 401, //生产出库/原材料 ISS_WO_VOID = 402, //生产出库/原材料冲销 ISS_WO_BF = 403, //生产投料回冲出库/出生产线 ISS_WO_BF_VOID = 404, //生产投料回冲出库/出生产线冲销 RCT_WO = 405, //生产入库/成品 RCT_WO_VOID = 406, //生产入库/成品冲销 ISS_MIN = 407, //生产投料出库 ISS_MIN_RTN = 408, //生产投料退库出库 RCT_MIN = 409, //生产投料入库/入生产线 RCT_MIN_RTN = 410, //生产投料出库/出生产线 //委外 ISS_SWO = 411, //委外生产出库/原材料 ISS_SWO_VOID = 412, //委外生产出库/原材料冲销 ISS_SWO_BF = 413, //委外生产投料回冲出库/出生产线 ISS_SWO_BF_VOID = 414, //委外生产投料回冲出库/出生产线冲销 RCT_SWO = 415, //委外生产入库/成品 RCT_SWO_VOID = 416, //委外生产入库/成品冲销 ISS_SWO_RTN = 417, //委外收货退货出库 ISS_SWO_RTN_VOID = 418, //委外收货退货出库冲销 RCT_SWO_RTN = 419, //委外收货退货入库 RCT_SWO_RTN_VOID = 420, //委外收货退货入库冲销 ISS_WO_RTN = 421, //原材料回用收货出库 ISS_WO_RTN_VOID = 422, //原材料回用收货出库冲销 RCT_WO_RTN = 423, //原材料回用收货入库 RCT_WO_RTN_VOID = 424, //原材料回用收货入库冲销 //检验 ISS_INP = 501, //报验出库 RCT_INP = 502, //报验入库 ISS_ISL = 503, //隔离出库 RCT_ISL = 504, //隔离入库 ISS_INP_QDII = 505, //检验合格出库 RCT_INP_QDII = 506, //检验合格入库 ISS_INP_REJ = 507, //检验不合格出库 RCT_INP_REJ = 508, //检验不合格入库 ISS_INP_CCS = 509, //让步使用出库 RCT_INP_CCS = 510, //让步使用入库 //调整 CYC_CNT = 601, //盘点差异出库 CYC_CNT_VOID = 602, //盘点差异入库 ISS_UNP = 603, //计划外出库 ISS_UNP_VOID = 604, //计划外出库冲销 RCT_UNP = 605, //计划外入库 RCT_UNP_VOID = 606, //计划外入库冲销 //客户化 //ISS_AGE = 901, //老化出库 //ISS_AGE_VOID = 902, //老化出库冲销 //RCT_AGE = 903, //老化入库 //RCT_AGE_VOID = 904, //老化入库冲销 //ISS_FLT = 905, //过滤出库 //ISS_FLT_VOID = 906, //过滤出库冲销 //RCT_FLT = 907, //过滤入库 //RCT_FLT_VOID = 908, //过滤入库冲销 } public enum HandleResult { Qualify = 1, Scrap = 2, Return = 3,//退货 Rework = 4, Concession = 5, //让步 WorkersWaste = 6 //让步 } public enum BarCodeType { FLOW, ORDER, PICKLIST, ASN, INSPECTION, STOCKTAKE, LOCATION, BIN, CONTAINER, HU } public enum ModuleType { Client_Receive, Client_PickListOnline, Client_PickList, Client_PickListShip, Client_OrderShip, Client_SeqPack, Client_Transfer, Client_RePack, Client_Pack, Client_UnPack, Client_PutAway, Client_Pickup, Client_StockTaking, Client_HuStatus, Client_MiscIn, Client_MiscOut, Client_Inspect, Client_Qualify, Client_Reject, Client_AnDon, Client_ProductionOnline, //生产上线 Client_MaterialIn, //生产投料 Client_ProductionOffline, //生产下线 Client_ChassisOnline, //底盘上线 Client_CabOnline, //驾驶室上线 Client_AssemblyOnline, //总装上线 Client_MaterialReturn, //生产投料 //周转箱 Client_EmptyContainerShip,//空箱发货 Client_EmptyContainerReceive,//空箱收货 Client_FullContainerReceive,//满箱收货 M_Switch } public enum IpType { Normal = 0, SEQ = 1, KIT = 2, } public enum ItemExchangeType { ItemExchange = 0,//物料替换 Aging = 1,//老化 Filter = 2,//过滤 } public enum IpDetailType { Normal = 0, Gap = 1 } public enum IpStatus { Submit = 0, InProcess = 1, Close = 2, Cancel = 3 } public enum PickListStatus { //Create = 0, Submit = 0, InProcess = 1, Close = 2, Cancel = 3 } public enum BomStructureType { Normal = 0, //普通结构 Virtual = 1 //虚结构 } public enum FeedMethod { None = 0, //不投料 ProductionOrder = 1, //投料至工单成品 ProductionLine = 2 //投料至生产线 } public enum BackFlushMethod { GoodsReceive = 0, //收货回冲,按标准BOM线冲生产线在制品,不够冲线边 BackFlushOrder = 1, //只回冲工单在制品 WeightAverage = 2 //加权平均 } public enum BindType { Submit = 1, //提交 Start = 2 //上线 } public enum RoundUpOption { ToUp = 1, //向上圆整 None = 0, //不圆整 ToDown = 2 //向下圆整 } public enum MRPOption { OrderBeforePlan = 0, //订单优先 OrderOnly = 1, //只看订单 PlanAddOrder = 2, //订单计划一起考虑 PlanMinusOrder = 3, //订单减掉计划 PlanOnly = 4, //只看计划 SafeStockOnly = 5 //只看安全库存 } public enum FlowStrategy { NA = 0, Manual = 1, KB = 2, JIT = 3, SEQ = 4, KIT = 5, MRP = 6, ANDON = 7, JIT2 = 8, JIT_EX = 9, KB2 = 10 } //public enum SpecialValue //{ // BlankValue, // AllValue //} public enum DocumentsType { ORD_Procurement = 1001, ORD_Transfer = 1002, ORD_Distribution = 1003, ORD_Production = 1004, ORD_SubContract = 1005, ORD_CustomerGoods = 1006, ORD_SubContractTransfer = 1007, ORD_ScheduleLine = 1008, ASN_Procurement = 1101, ASN_Transfer = 1102, ASN_Distribution = 1103, ASN_SubContract = 1105, ASN_CustomerGoods = 1106, ASN_SubContractTransfer = 1107, ASN_ScheduleLine = 1108, REC_Procurement = 1201, REC_Transfer = 1202, REC_Distribution = 1203, REC_Production = 1204, REC_SubContract = 1205, REC_CustomerGoods = 1206, REC_SubContractTransfer = 1207, REC_ScheduleLine = 1208, PIK_Transfer = 1302, PIK_Distribution = 1303, PIK_SubContractTransfer = 1307, BIL_Procurement = 1401, BIL_Distribution = 1403, RED_Procurement = 1411, RED_Distribution = 1413, MIS_Out = 1501, MIS_In = 1502, //MIS_SY03 = 1531, //MIS_SY05 = 1551, INS = 1601, REJ = 1611, STT = 1701, SEQ = 1801, CON = 1901, INV_Hu = 2001, VEH = 2011, } public enum LikeMatchMode { Anywhere, Start, End, } public enum HuStatus { NA = 0, Location = 1, Ip = 2, } public enum CodeMasterType { System = 0, Editable = 1 } public enum PickOddOption { OddFirst = 0, //零头先发 NotPick = 1 //零头不发 } public enum ShipStrategy { FIFO = 0, //先进先出 LIFO = 1 //后进先出 } public enum CodeMaster { PermissionCategoryType, RoleType, UserType, BillType, BillTransactionType, PriceListType, InspectType, InspectStatus, JudgeResult, OrderType, OrderSubType, ReceiveGapTo, CreateHuOption, ReCalculatePriceOption, OrderPriority, OrderStatus, SendStatus, AddressType, InventoryType, //ItemType, WorkingCalendarType, RejectStatus, QualityType, OccupyType, TimeUnit, HandleResult, StockTakeType, StockTakeStatus, IssueType, IssuePriority, IssueStatus, IpType, IpDetailType, IpStatus, PickListStatus, BomStructureType, FeedMethod, BackFlushMethod, BindType, RoundUpOption, MRPOption, FlowStrategy, DocumentsType, HuStatus, LocationType, Language, LogLevel, DayOfWeek, HuTemplate, OrderTemplate, AsnTemplate, ReceiptTemplate, //FlowType, Strategy, InspectDefect, RoutingTimeUnit, BackFlushInShortHandle, SMSEventHeadler, SequenceStatus, ReceiptStatus, ConcessionStatus, MiscOrderType, MiscOrderStatus, PickOddOption, ShipStrategy, OrderBillTerm, CodeMasterType, MessageType, RePackType, JobRunStatus, TriggerStatus, MessagePriority, MessageStatus, EmailStatus, ScheduleType, TransactionIOType, TransactionType, IpGapAdjustOption, VehicleInFactoryStatus, LocationLevel, WindowTimeType, ApsPriorityType, ItemPriority, ResourceGroup, BillMasterStatus, PlanStatus, BomMrpOption, BillStatus, ItemOption, SubCategory, ShiftType, MachineType, QueryOrderType, Viscosity, HolidayType, ProductType, HuOption, PickListTemplate, SnapType, MrpSourceType, ItemExchangeType, ConsignmentStatus, FreezeStatus, InterfacePriceType, TaskPriority, TaskType, TaskStatus, TransportMode, TransportStatus, IOType, PickBy, TransportPricingMethod, FacilityStatus, FacilityTransType, MaintainPlanType, FacilityParamaterType, FacilityOrderType, FacilityOrderStatus, CheckListOrderStatus, LeadTimeOption, BarCodeMode, } public enum MessageType { Info = 0, Warning = 1, Error = 2 } public enum SequenceStatus { Submit = 0, Pack = 1, Ship = 2, Close = 3, Cancel = 4 } public enum ReceiptStatus { Close = 0, Cancel = 1 } public enum RePackType { In = 0, Out = 1 } public enum TransactionIOType { In = 0, Out = 1 } public enum IOType { In = 0, Out = 1 } //public enum DocumentTypeEnum //{ // ORD, // ASN, // PIK, // STT, // INS //} public enum ConcessionStatus { Create = 0, Submit = 1, Close = 2 } public enum JobRunStatus { InProcess = 0, Success = 1, Failure = 2, } public enum TriggerStatus { Open = 0, Close = 1, } public enum MessagePriority { Normal = 0, Low = 1, High = 2, } public enum MessageStatus { Open = 0, Close = 1 } public enum EmailStatus { Open = 0, Close = 1 } public enum MiscOrderType { GI = 0, GR = 1, } public enum MiscOrderSubType { COST = 0, SY03 = 30, /// <summary> /// 下线过程废品(包括在线待处理产品报废、线外挑选废品、后道退回来料废品) /// </summary> MES26 = 26, SY04 = 40, SY05 = 50, /// <summary> /// 后加工废品报废,不消耗库存 /// </summary> MES27 = 27, } public enum MiscOrderStatus { Create = 0, Close = 1, Cancel = 2 } public enum ScheduleType { Firm = 0, Forecast = 1, BackLog = 2, /// <summary> /// //挤出头子,包含在BOM废品率中 /// </summary> MES21 = 21, /// <summary> /// //挤出皮子料,包含在BOM废品率中 /// </summary> MES22 = 22, /// <summary> /// //挤出工艺损耗,包含在BOM废品率中 /// </summary> MES23 = 23, /// <summary> /// //挤出牵引废品,不包含在BOM废品率中,需废品报工 /// </summary> MES24 = 24, /// <summary> /// //在线过程废品,不包含在BOM废品率中,需废品报工 /// </summary> MES25 = 25, /// <summary> /// //下线过程废品(包括在线待处理产品报废、线外挑选废品、后道退回来料废品) /// </summary> MES26 = 26, MES27 = 27, MES28 = 28, MES29 = 29, SY01 = 101, SY02 = 102, SY03 = 103, SY04 = 104, SY05 = 105, SY41 = 141, SY42 = 142, SY43 = 143, } public enum IpGapAdjustOption { GI = 0, GR = 1 } public enum VehicleInFactoryStatus { Submit = 0, InProcess = 1, Close = 2 } public enum GridDisplayType { Summary = 0, Detail = 1 } public enum MQStatusEnum { Pending = 0, Success = 1, Fail = 2, Cancel = 3 } public enum PlanStatus { //Error = -1, Create = 0, Submit = 1, Close = 2, Cancle = 3 } public enum MrpSourceType { ExDay = 1, Order = 2, Plan = 3, StockLack = 4, StockOver = 5, Discontinue = 6, ShipGroupPlan = 7, //IndepentOrder = 8, MiShift = 10, ExShift = 20, FiShift = 30, } public enum ApsPriorityType { Normal = 5, //常用 Backup = 3, //备用 //Urgent = 1, //应急 } public enum BillStatus { Create = 0, Submit = 1, Close = 2, Cancel = 3, Void = 4 } public enum BillMasterStatus { Create = 0, Submit = 1, Close = 2, Cancel = 3 } public enum ResourceGroup { Other = 0, /// <summary> /// 炼胶 /// </summary> MI = 10, /// <summary> /// 挤出 /// </summary> EX = 20, /// <summary> /// 后加工 /// </summary> FI = 30, } public enum ItemPriority { /// <summary> /// 常规 /// </summary> Normal = 0,// /// <summary> /// 备件 /// </summary> Spare = 1, } public enum HuOption { /// <summary> /// 无需老化/过滤 /// </summary> NoNeed = 0,// /// <summary> /// 未老化 /// </summary> UnAging = 1, /// <summary> /// 已老化 /// </summary> Aged = 2, /// <summary> /// 未过滤 /// </summary> UnFilter = 3, /// <summary> /// 已过滤 /// </summary> Filtered = 4, } public enum BomMrpOption { All = 0, //Mrp和生产都要用到 ProductionOnly = 1, //只用于生产 MrpOnly = 2, //只用于Mrp } public enum MachineType { Kit = 1, //成套 Single = 2, //单件 } public enum ItemOption { NA = 0, NeedAging = 1,//需要老化 NeedFilter = 2,//需要过滤 } public enum SubCategory { ItemCategory = 0,//物料类型 //TypeOne = 1,//分类一 //TypeTwo = 2,//分类二 //TypeThree = 3,//分类三 //TypeFour = 4,//分类四 MaterialsGroup = 5,//物料组 } public enum ShiftType { TwoShiftPerDay = 2, //12小时/班 ThreeShiftPerDay = 3,//8小时/班 } public enum QueryOrderType { OrderNo = 0, ExternalOrderNo = 1, ReferenceOrderNo = 2, } //等级高中低 public enum Viscosity { High = 1, Inthe = 2, Low = 3, } public enum HolidayType { Holiday = 10, Trial = 20, Halt = 30 } /* public enum ProductType { A = 10,//A 批产01 SY01 B = 20,//B 工业化02 SY02 C = 30,//C 开发03 SY03 D = 40,//D 备模 E = 50,//E 工装 F = 60,//F 设备 G = 70,//G 材料 H = 80,//H 工艺 J = 100,//J 移线 K = 110,//K 攻关 L = 120,//L 改进 M = 130,//M 保养 N = 140,//N 能源 P = 160,//P 停产 Q = 170,//Q 工程更改 R = 180,//R 配件 S = 190,//S 塞芯 Z = 260,//Z 其他 } */ public enum SnapType { Rccp = 0, Mrp = 1 } public enum FreezeStatus { True = 1, False = 0 } public enum ConsignmentStatus { True = 1, False = 0 } public enum TaskPriority { Normal = 0, Urgent = 1, High = 2, Major = 3, Low = 4, } public enum TaskType { Audit = 0, Change = 1, Ecn = 2, General = 3, Improve = 4, Issue = 5, Plan = 6, Privacy = 7, PrjectIssue = 8, Project = 9, Response = 10, } public enum TaskStatus { Create = 0, Submit = 1, Cancel = 2, Assign = 3, InProcess = 4, Complete = 5, Close = 6, } public enum TransportMode { Land = 0, Sea = 1, Air = 2 } public enum TransportStatus { Create = 0, Submit = 1, InProcess = 2, Close = 3, Cancel = 4, } public enum TransportPricingMethod { Chartered = 0, Distance = 1, Weight = 2, Volume = 3, LadderVolume = 4 } public enum PickBy { LotNo = 0, Hu = 1 } public enum PickGroupType { Ship = 0, Pick = 1, Repack = 2 } /// <summary> /// 设施状态 /// </summary> public enum FacilityStatus { Create = 0, Idle = 1, InUse = 2, Maintaining = 3, Inspecting = 4, Failure = 5, Repairing = 6 } /// <summary> /// 设施事务类型 /// </summary> public enum FacilityTransType { Create = 101, Enable = 102, StartUse = 103, FinishUse = 104, StartMaintain = 105, FinishMaintain = 106, StartInspect = 107, FinishInspect = 108, StartRepair = 109, FinishRepair = 110, Envelop = 111, Lend = 112, Sell = 113, Lose = 114, Scrap = 115 } /// <summary> /// 预防策略类型 /// </summary> public enum MaintainPlanType { Once = 0, Year = 1, Month = 2, Week = 3, Day = 4, Hour = 5, Minute = 6, Second = 7, Times = 8 } /// <summary> /// 设备信息类型 /// </summary> public enum FacilityParamaterType { Scan = 0, Paramater = 1 } public enum FacilityOrderType { Maintain = 1, Fix = 2, Inspect = 3 } public enum FacilityOrderStatus { Create = 0, Submit = 1, InProcess = 2, Close = 3 } public enum CheckListOrderStatus { Create = 0, Submit = 1 } public enum LeadTimeOption { Strategy = 0, ShiftDetail = 1, } public enum BarCodeMode { //NoneBarCode = 0, //不启用条码 Box = 1, //按箱管理 Pallet = 2, //按托管理 LotNo = 3, //按批号管理 } }
using System; using System.IO; using System.Security.Cryptography; namespace DirectoryBackupService.Shared { public static class Files { public static byte[] SafelyReadFile(string filePath) { using (var s = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var ms = new MemoryStream()) { s.CopyTo(ms); return ms.ToArray(); } } public static string Hash(byte[] fileContent) { using (var md5 = MD5.Create()) { using (var stream = new MemoryStream(fileContent)) { var hash = md5.ComputeHash(stream); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using TinhLuongDataAdapter; namespace TinhLuongDAL { public class QuyLuongDAL { public DataTable GetListQuyLuong(decimal thang, decimal nam, string donviId) { SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@Thang", thang), new SqlParameter("@Nam",nam), new SqlParameter("@DonViID",donviId), }; try { DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "TinhLuong_LayQuyLuong", parm); return ds.Tables[0]; } catch { return new DataTable(); } } public DataTable GetListQuyLuongByDonVi(decimal thang, decimal nam, string donviId) { SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@Thang", thang), new SqlParameter("@Nam",nam), new SqlParameter("@DonViID",donviId), }; try { DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "Tuyen_TinhLuong_LayQuyLuong_ByDonViID", parm); return ds.Tables[0]; } catch { return new DataTable(); } } public bool XoaQuyLuong(decimal thang, decimal nam, string donviId) { SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@Thang",thang), new SqlParameter("@Nam",nam), new SqlParameter("@DonViID",donviId) }; try { SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.StoredProcedure, "TinhLuong_Xoa", parm); return true; } catch (Exception ex) { return false; } } public bool CapnhatQuyLuong(decimal thang, decimal nam, string donviId, decimal quygt, decimal quytt, decimal quythe, decimal chatluongthang, decimal htkh, decimal htcntt, decimal tylethe, decimal tylecuoc, decimal cstl, decimal stt, decimal quygt_kh, decimal quythe_kh) { //dbCmd.Parameters.Add(new SqlParameter("@Thang", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, thang)); //dbCmd.Parameters.Add(new SqlParameter("@Nam", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, nam)); //dbCmd.Parameters.Add(new SqlParameter("@DonViID", SqlDbType.NVarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, donviId )); //dbCmd.Parameters.Add(new SqlParameter("@QuyGT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, quygt)); //dbCmd.Parameters.Add(new SqlParameter("@QuyTT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, quytt)); //dbCmd.Parameters.Add(new SqlParameter("@ChatLuongThang", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, chatluongthang)); //dbCmd.Parameters.Add(new SqlParameter("@Tyle_HTKH", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, hethongkh)); //dbCmd.Parameters.Add(new SqlParameter("@Tyle_HTCNTT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, hethongcntt)); //dbCmd.Parameters.Add(new SqlParameter("@CSTL_LDDB", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, cstl)); //dbCmd.Parameters.Add(new SqlParameter("@STT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, stt)); SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@Thang", thang), new SqlParameter("@Nam", nam), new SqlParameter("@DonViID", donviId), new SqlParameter("@QuyGT", quygt), new SqlParameter("@QuyTT", quytt), new SqlParameter("@QuyThe", quythe), new SqlParameter("@ChatLuongThang", chatluongthang), new SqlParameter("@Tyle_HTKH", htkh), new SqlParameter("@Tyle_HTCNTT", htcntt), new SqlParameter("@Tyle_The", tylethe), new SqlParameter("@Tyle_Cuoc", tylecuoc), new SqlParameter("@CSTL_LDDB", cstl), new SqlParameter("@STT", stt), new SqlParameter("@QuyGT_KH", quygt_kh), new SqlParameter("@QuyThe_KH", quythe_kh), }; try { SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.StoredProcedure, "TinhLuong_Update", parm); return true; } catch (Exception ex) { return false; } } public bool ThemMoiQuyLuong(decimal thang, decimal nam, string donviId, decimal quygt, decimal quytt, decimal quythe, decimal chatluongthang, decimal htkh, decimal htcntt, decimal tylethe, decimal tylecuoc, decimal cstl, decimal stt, decimal quygt_kh, decimal quythe_kh) { //dbCmd.Parameters.Add(new SqlParameter("@Thang", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, thang)); //dbCmd.Parameters.Add(new SqlParameter("@Nam", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, nam)); //dbCmd.Parameters.Add(new SqlParameter("@DonViID", SqlDbType.NVarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, donviId )); //dbCmd.Parameters.Add(new SqlParameter("@QuyGT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, quygt)); //dbCmd.Parameters.Add(new SqlParameter("@QuyTT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, quytt)); //dbCmd.Parameters.Add(new SqlParameter("@ChatLuongThang", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, chatluongthang)); //dbCmd.Parameters.Add(new SqlParameter("@Tyle_HTKH", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, hethongkh)); //dbCmd.Parameters.Add(new SqlParameter("@Tyle_HTCNTT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, hethongcntt)); //dbCmd.Parameters.Add(new SqlParameter("@CSTL_LDDB", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, cstl)); //dbCmd.Parameters.Add(new SqlParameter("@STT", SqlDbType.Decimal, 17, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, stt)); SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@Thang", thang), new SqlParameter("@Nam", nam), new SqlParameter("@DonViID", donviId), new SqlParameter("@QuyGT", quygt), new SqlParameter("@QuyTT", quytt), new SqlParameter("@QuyThe", quythe), new SqlParameter("@ChatLuongThang", chatluongthang), new SqlParameter("@Tyle_HTKH", htkh), new SqlParameter("@Tyle_HTCNTT", htcntt), new SqlParameter("@Tyle_The", tylethe), new SqlParameter("@Tyle_Cuoc", tylecuoc), new SqlParameter("@CSTL_LDDB", cstl), new SqlParameter("@STT", stt), new SqlParameter("@QuyGT_KH", quygt_kh), new SqlParameter("@QuyThe_KH", quythe_kh), }; try { SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.StoredProcedure, "TinhLuong_Themmoi", parm); return true; } catch (Exception ex) { return false; } } } }
using SpotifyAPI.Web; using System.Collections.Generic; namespace Spotify_2._0.Classes { internal class Song { public string name { get; set; } public string album_name { get; set; } public string album_img { get; set; } public string[] album_artists { get; set; } public int duration { get; set; } public string preview_url { get; set; } public string name1 { get; } public string name2 { get; } public string url { get; } public List<SimpleArtist> Artists { get; } public int DurationMs { get; } public string PreviewUrl { get; } public string id { get; set; } public Song(string name, string album_name, string album_img, string[] album_artists, string id, int duration, string preview_url) { this.name = name; this.album_name = album_name; this.album_img = album_img; this.id = id; this.album_artists = album_artists; this.duration = duration; this.preview_url = preview_url; } public Song(string name1, string name2, string url, List<SimpleArtist> artists, string id, int durationMs, string previewUrl) { this.name = name1; this.album_name = name2; this.album_img = url; this.Artists = artists; this.id = id; this.duration = durationMs; this.preview_url = previewUrl; } public override string ToString() { return $"{name}\n{duration}\n{preview_url}"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace FolderBackup.Shared { public static class AuthenticationPrimitives { static public string hashPassword(string password, string salt, string token) { return Hash(Hash(Hash(password) + salt) + token); } static public string hashPassword(string password, string salt) { return Hash(Hash(password) + salt); } static private string Hash(string input) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { sb.Append(b.ToString("x2")); } return sb.ToString(); } } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `Quaternion`. Inherits from `AtomEventReferenceListener&lt;Quaternion, QuaternionEvent, QuaternionEventReference, QuaternionUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/Quaternion Event Reference Listener")] public sealed class QuaternionEventReferenceListener : AtomEventReferenceListener< Quaternion, QuaternionEvent, QuaternionEventReference, QuaternionUnityEvent> { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace WziumStars.Models { public class Podkategoria { [Key] public int Id { get; set; } [Required] [Display(Name = "Nazwa")] public string Name { get; set; } [Required] [Display(Name ="Kategoria")] public int CategoryId { get; set; } [ForeignKey("CategoryId")] public virtual Kategoria Kategoria { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace GucciBazaar.Models { public class ShoppingCartProduct : BaseModel { public long ShoppingCartId { get; set; } public long ProductId { get; set; } public int Quantity { get; set; } public double Price { get; set; } public virtual ShoppingCart ShoppingCart { get; set; } public virtual Product Product { get; set; } } }
namespace CarDealer.Services { using Data.Interfaces; public abstract class Service { protected Service(IDataProvidable data) { this.Data = data; } protected IDataProvidable Data { get; } } }
using BetterShippingBox.Menus; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using StardewValley.Menus; namespace BetterShippingBox { public class BetterShippingBox : Mod { /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { helper.Events.Display.MenuChanged += OnMenuChanged; } /// <summary>Raised after a game menu is opened, closed, or replaced.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnMenuChanged(object sender, MenuChangedEventArgs e) { if (e.NewMenu is ItemGrabMenu menu && menu.shippingBin) { Game1.activeClickableMenu = new BetterShippingMenu(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Tp3_Azure.Data.Context; using Tp3_Azure.Domain; using Tp3_Azure.Service.Helper; namespace Tp3_Azure.Client.Controllers { public class ProdutosController : Controller { private DataContext db = new DataContext(); // GET: Produtos public ActionResult Index() { List<Produto> produtos = new List<Produto>(); FilaHelper fila = new FilaHelper(); using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { foreach (var item in proxy.GetAll()) { produtos.Add(new Produto() { ProdutoId = item.ProdutoId, Nome=item.Nome, Categoria=item.Categoria, Preco = item.Preco, Quantidade = item.Quantidade }); } int? tamanho = fila.TamanhoDaFila(); Session["fila"] = tamanho; return View(produtos); } } public ActionResult ExecutarFila() { using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { proxy.ExecutarFila(); return RedirectToAction("Index"); } } // GET: Produtos/Details/5 public ActionResult Details(string nome) { Produto produto = new Produto(); using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { var item = proxy.Get(nome); produto = new Produto() { ProdutoId = item.ProdutoId, Nome = item.Nome, Categoria = item.Categoria, Preco = item.Preco, Quantidade = item.Quantidade }; return View(produto); } } // GET: Produtos/Create public ActionResult Create() { return View(); } // POST: Produtos/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ProdutoId,Nome,Categoria,Preco,Quantidade")] Produto produto) { if (ModelState.IsValid) { using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { proxy.Create(produto); } return RedirectToAction("Index"); } return View(produto); } // GET: Produtos/Edit/5 public ActionResult Edit(string nome) { Produto produto = new Produto(); using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { var item = proxy.Get(nome); produto = new Produto() { ProdutoId = item.ProdutoId, Nome = item.Nome, Categoria = item.Categoria, Preco = item.Preco, Quantidade = item.Quantidade }; return View(produto); } } // POST: Produtos/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ProdutoId,Nome,Categoria,Preco,Quantidade")] Produto produto) { if (ModelState.IsValid) { using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { proxy.Edit(produto.ProdutoId, produto); return RedirectToAction("Index"); } } return View(produto); } // GET: Produtos/Delete/5 public ActionResult Delete(string nome) { Produto produto = new Produto(); using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { var item = proxy.Get(nome); produto = new Produto() { ProdutoId = item.ProdutoId, Nome = item.Nome, Categoria = item.Categoria, Preco = item.Preco, Quantidade = item.Quantidade }; TempData["deleteid"] = produto.ProdutoId; TempData.Keep(); return View(produto); } } // POST: Produtos/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed() { Guid id = (Guid)TempData["deleteid"]; using (var proxy = new ServiceReference1.GerenciamentoDeProdutoServiceClient()) { proxy.Delete(id); } return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using DataAccess.Tables; using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace DataAccess.Dao { public class LanguageDao { private Entities db; public LanguageDao(Entities db) { this.db = db; } public IEnumerable<Language> GetLanguages() { return db.Languages.ToList(); } } }
using Xunit; namespace NStandard.Collections.Test { public class CounterTests { [Fact] public void ParseTest() { var counter = Counter.Parse("aba"); Assert.Equal(2, counter['a']); Assert.Equal(1, counter['b']); } [Fact] public void ElementTest() { var counter = Counter.Parse("aba"); Assert.Equal(new[] { 'a', 'a', 'b' }, counter.Elements()); } [Fact] public void AddingTest1() { var counter = Counter.Parse("aba") + Counter.Parse("babc"); Assert.Equal(3, counter['a']); Assert.Equal(3, counter['b']); Assert.Equal(1, counter['c']); } [Fact] public void AddingTest2() { var counter = Counter.Parse("babc") + Counter.Parse("aba"); Assert.Equal(3, counter['a']); Assert.Equal(3, counter['b']); Assert.Equal(1, counter['c']); } [Fact] public void SubtractTest1() { var counter = Counter.Parse("aba") - Counter.Parse("babc"); Assert.Equal(1, counter['a']); Assert.Equal(-1, counter['b']); Assert.Equal(-1, counter['c']); } [Fact] public void SubtractTest2() { var counter = Counter.Parse("babc") - Counter.Parse("aba"); Assert.Equal(-1, counter['a']); Assert.Equal(1, counter['b']); Assert.Equal(1, counter['c']); } [Fact] public void EqualTest() { var counter = Counter.Parse("abc"); var counter2 = Counter.Parse("bca"); Assert.Equal(counter, counter2); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Umbraco.Web.Mvc; using MySite.Models; using System.Net.Mail; using System.Configuration; namespace MySite.Controllers { public class ContactController : SurfaceController { public ActionResult RenderForm() { return PartialView("ContactForm", new Contact()); } public ActionResult RenderServices() { return PartialView("Services"); } public ActionResult FormPost(Contact post) { Contact contact = new Contact() { Name = post.Name, Email = post.Email, Message = post.Message }; contact.SendEmail(); return RedirectToCurrentUmbracoPage(); } } }
using System; using UnityEngine; using System.Collections.Generic; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainUITool : MonoBehaviour { #region 属性和字段 /// <summary> /// 静态实例 /// </summary> public static MainUITool Instance { get { return _instance; } } static MainUITool _instance; /// <summary> /// 界面预制体字典,保存界面复制体的引用 /// </summary> public Dictionary<WindowID, GameObject> Prefab_Dictionary { get { return _prefab_Dictionary; } } static Dictionary<WindowID, GameObject> _prefab_Dictionary;//存放界面预制体的字典 /// <summary> /// 存放当前显示界面的栈 /// </summary> public Stack<WindowID> TheActiveStack { get { if (SceneManager.GetActiveScene().name.Equals("UI")) { return _UI_Active_Stack; } else { return _game_Active_Stack; } } } static Stack<WindowID> _UI_Active_Stack; //存放UI场景当前显示界面的栈 static Stack<WindowID> _game_Active_Stack; //存放游戏场景当前显示界面的栈 #endregion void Awake() { if (_instance == null) { _instance = this; _UI_Active_Stack = new Stack<WindowID>(); DontDestroyOnLoad(transform.gameObject); } else { Destroy(gameObject); } _game_Active_Stack = new Stack<WindowID>(); _prefab_Dictionary = new Dictionary<WindowID, GameObject>(); } /// <summary> /// 设置界面显示 /// </summary> /// <param name="id">界面id</param> public void SetTheActive(WindowID id) { //显示界面 SetTheActive(id, ref _prefab_Dictionary, true); if (TheActiveStack.Count > 0) { WindowID current_ID = TheActiveStack.Peek(); //若打开界面与前一界面层级相同,关闭前一界面 if (UIResourceDefine.windowLayer[current_ID] == UIResourceDefine.windowLayer[id]) { if (current_ID != id) { SetTheActive(current_ID, ref _prefab_Dictionary, false); } } else { //层级不同,则开启遮罩层 SetTheActive(WindowID.WindowID_MyMask, ref _prefab_Dictionary, true); } } if (!TheActiveStack.Contains(id)) { //将显示界面加入栈中 TheActiveStack.Push(id); } } //设置界面的显示状态 void SetTheActive(WindowID id, ref Dictionary<WindowID,GameObject> prefab_Dictionary,bool active_Bool) { if (!prefab_Dictionary.ContainsKey(id)) { GameObject temp = Resources.Load(UIResourceDefine.MainUIPrefabPath + UIResourceDefine.windowPrefabName[id]) as GameObject; GameObject copy = Instantiate(temp); copy.transform.GetComponent<Canvas>().sortingOrder = UIResourceDefine.windowLayer[id]; prefab_Dictionary.Add(id, copy); } EffectManager.Instance.WindowEffect(active_Bool, prefab_Dictionary[id]); } /// <summary> /// 关闭当前界面,返回上一界面 /// </summary> public void ReturnPrevious() { if (SceneManager.GetActiveScene().name.Equals("UI")) { ReturnPrevious(ref _UI_Active_Stack, _prefab_Dictionary); } else { GameUITool.Instance.SetTheActive(GameUI.GameUI_Seconds); } } void ReturnPrevious(ref Stack<WindowID> active_Stack, Dictionary<WindowID, GameObject> prefab_Dictionary) { WindowID remove_ID = active_Stack.Pop(); SetTheActive(remove_ID, ref _prefab_Dictionary,false); //若返回界面是3级界面,直接跳过 if (UIResourceDefine.windowLayer[active_Stack.Peek()] == 3) { active_Stack.Pop(); } SetTheActive(active_Stack.Peek(), ref _prefab_Dictionary,true ); //遮罩层的关闭 if(prefab_Dictionary.ContainsKey(WindowID.WindowID_MyMask)&&prefab_Dictionary[WindowID.WindowID_MyMask].activeSelf == true) { SetTheActive(WindowID.WindowID_MyMask, ref _prefab_Dictionary, false); } if (active_Stack.Peek() == WindowID.WindowID_SelectHero) { _prefab_Dictionary[WindowID.WindowID_SelectHero].GetComponentInChildren<Window_ChooseHero>().ReturnUpdate(); } } //购买之后,实现购买键的变化 public void ItemsButton(GameObject button) { Transform tiao = button.transform.parent; Image[] images = tiao.GetComponentsInChildren<Image>(); foreach (var image in images) { image.raycastTarget = false; image.color = Color.gray; } Text[] texts = tiao.GetComponentsInChildren<Text>(); foreach (var text in texts) { text.raycastTarget = false; text.color = Color.gray; } //已生效显示正常 tiao.GetChild(0).GetChild(0).gameObject.SetActive(true); } /// <summary> /// 交易函数,0:购买钻石,1:购买金币,2:购买体力 /// </summary> /// <param name="x"></param> public void Business(int x) { switch (x) { case 0: break; case 1://使用钻石购买金币 if (MyKeys.Diamond_Value > 6) { MyKeys.Diamond_Value -= 6; MyKeys.Gold_Value += 60; } else { UIManager.ActiveWindow(WindowID.WindowID_ShopDiamond); } break; case 2://使用钻石购买体力 if (MyKeys.Diamond_Value >= MyKeys.BuyPhysicalPowerCost) { MyKeys.Diamond_Value -= MyKeys.BuyPhysicalPowerCost; MyKeys.Physical_Power_Value += 1; UMManager.Event(EventID.Buy_Power); } else { //UIManager.ActiveWindow(WindowID.WindowID_ShopZuanShi); MyAudio.PlayAudio(StaticParameter.s_No, false, StaticParameter.s_No_Volume); } break; default: Debug.Log("购买行为标记错误"); break; } } public void SetMapActive() { _UI_Active_Stack.Pop(); } }
using gView.Framework.Data; using gView.Framework.system; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; namespace gView.Plugins.Editor.Controls { internal partial class AttributeControl : UserControl, IErrorMessage { private Module _module = null; private IFeatureClass _fc = null; private string _errMsg = String.Empty; public AttributeControl() { InitializeComponent(); } public Module Module { get { return _module; } set { _module = value; } } private delegate void RefreshGUICallback(); async public void RefreshGUI() { if (this.InvokeRequired) { RefreshGUICallback d = new RefreshGUICallback(RefreshGUI); this.BeginInvoke(d); return; } if (_module == null || _module.FeatureClass == null) { //panelFieldNames.Controls.Clear(); //panelValues.Controls.Clear(); panelValues.Enabled = false; return; } if (_fc != _module.FeatureClass) { panelFieldNames.Controls.Clear(); panelValues.Controls.Clear(); _fc = _module.FeatureClass; IFeatureLayer layer = _module.GetFeatureClassLayer(_fc); if (layer == null || layer.Fields == null) { return; } List<IField> fields = new List<IField>(); foreach (IField f in layer.Fields.ToEnumerable()) { fields.Add(f); } int height = 20; foreach (IField field in ListOperations<IField>.Swap(fields)) { if (!field.IsEditable) { continue; } if (field.type == FieldType.Shape || field.type == FieldType.binary) { continue; } #region Label Panel p1 = new Panel(); p1.Height = height; p1.Dock = DockStyle.Top; TextBox tbLabel = new TextBox(); tbLabel.Text = field.aliasname + ":"; tbLabel.TextAlign = HorizontalAlignment.Right; tbLabel.ReadOnly = true; tbLabel.BackColor = Color.White; p1.Controls.Add(tbLabel); tbLabel.Dock = DockStyle.Fill; //Label label = new Label(); //label.Text = field.name + ":"; //label.TextAlign = ContentAlignment.MiddleRight; //p1.Controls.Add(label); //label.Dock = DockStyle.Fill; panelFieldNames.Controls.Add(p1); #endregion #region ValueControl Panel p2 = new Panel(); p2.Height = height; p2.Dock = DockStyle.Top; Control ctrl = null; if (field.Domain is IValuesFieldDomain) { ctrl = new ComboControl(_module.Feature, field, await ((IValuesFieldDomain)field.Domain).ValuesAsync()); } else { switch (field.type) { case FieldType.smallinteger: case FieldType.integer: case FieldType.biginteger: ctrl = new MaskedTextBox(_module.Feature, field); ((MaskedTextBox)ctrl).DigitOnly = true; break; case FieldType.Float: case FieldType.Double: //ctrl = new NumberControl(_module.Feature, field); ctrl = new MaskedTextBox(_module.Feature, field); ((MaskedTextBox)ctrl).DecimalOnly = true; break; default: ctrl = new TextControl(_module.Feature, field); break; } } p2.Controls.Add(ctrl); ctrl.Dock = DockStyle.Fill; panelValues.Controls.Add(p2); #endregion } panel1.Height = panelFieldNames.Controls.Count * height + 1; } else { SetFeatureValues(panelValues); } panelValues.Enabled = panelFieldNames.Enabled = (_module.Feature != null); } public bool CommitValues() { _errMsg = String.Empty; return CommitValues(panelValues); } private bool CommitValues(Control parent) { if (parent == null) { return false; } foreach (Control child in parent.Controls) { if (child == null) { continue; } if (child is IFieldControl) { if (!((IFieldControl)child).Commit()) { _errMsg = ((IFieldControl)child).LastErrorMessage; child.Focus(); return false; } } else if (!CommitValues(child)) { return false; } } return true; } private void SetFeatureValues(Control parent) { if (parent == null) { return; } foreach (Control child in parent.Controls) { if (child == null) { continue; } if (child is IFieldControl) { ((IFieldControl)child).Feature = _module.Feature; } else { SetFeatureValues(child); } } } #region ControlClasses private interface IFieldControl : IErrorMessage { IFeature Feature { get; set; } bool Commit(); } private class TextControl : TextBox, IFieldControl { protected IFeature _feature = null; protected IField _field; private String _origValue = null, _errMsg = String.Empty; public TextControl(IFeature feature, IField field) { _field = field; this.Feature = feature; AddEventHandlers(); SetBackColor(); } private void AddEventHandlers() { base.TextChanged += new EventHandler(TextControl_TextChanged); } private void RemoveEventHandlers() { base.TextChanged -= new EventHandler(TextControl_TextChanged); } void TextControl_TextChanged(object sender, EventArgs e) { Commit(); } #region IFieldControl Member public IFeature Feature { get { return _feature; } set { if (_feature != value) { //base.BackColor = Color.White; SetBackColor(); _feature = value; if (_feature != null) { _origValue = (_feature[_field.name] != null) ? _feature[_field.name].ToString() : String.Empty; base.Text = _origValue; base.Enabled = (_field.type != FieldType.ID && _field.type != FieldType.replicationID); } else { _origValue = null; base.Text = String.Empty; base.Enabled = false; } } } } virtual public bool Commit() { _errMsg = String.Empty; if (_feature != null) { Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, this.Text); SetBackColor(); if (_field.IsRequired && String.IsNullOrEmpty(this.Text)) { _errMsg = "Value '" + _field.name + "' is required..."; return false; } } else { base.Enabled = false; } return true; } private void SetBackColor() { if (_feature != null) { if (_origValue != null) { if (_origValue.Equals(this.Text)) { base.BackColor = Color.White; } else { base.BackColor = Color.Yellow; } } else { if (_feature[_field.name] == null) { base.BackColor = Color.White; } else { base.BackColor = Color.Yellow; } } if (_field.IsRequired && String.IsNullOrEmpty(this.Text)) { base.BackColor = Color.Red; } } else { if (_field != null && _field.IsRequired && String.IsNullOrEmpty(this.Text)) { base.BackColor = Color.Red; } else { base.BackColor = Color.White; } } } #endregion #region IErrorMessage Member public string LastErrorMessage { get { return _errMsg; } set { _errMsg = value; } } #endregion } private class NumberControl : NumericUpDown, IFieldControl { private IFeature _feature = null; private IField _field; private object _origValue = null; private string _errMsg = String.Empty; public NumberControl(IFeature feature, IField field) { _field = field; switch (field.type) { case FieldType.smallinteger: base.Minimum = short.MinValue; base.Maximum = short.MaxValue; base.DecimalPlaces = 0; break; case FieldType.integer: base.Minimum = int.MinValue; base.Maximum = int.MaxValue; base.DecimalPlaces = 0; break; case FieldType.biginteger: base.Minimum = long.MinValue; base.Maximum = long.MaxValue; base.DecimalPlaces = 0; break; case FieldType.Float: base.Minimum = decimal.MinValue; base.Maximum = decimal.MaxValue; base.DecimalPlaces = 7; break; case FieldType.Double: base.Minimum = decimal.MinValue; base.Maximum = decimal.MaxValue; base.DecimalPlaces = 16; break; } this.Feature = feature; base.ValueChanged += new EventHandler(NumberControl_ValueChanged); base.Leave += new EventHandler(NumberControl_ValueChanged); base.KeyPress += new KeyPressEventHandler(NumberControl_KeyPress); } void NumberControl_KeyPress(object sender, KeyPressEventArgs e) { NumberControl_ValueChanged(sender, new EventArgs()); } void NumberControl_ValueChanged(object sender, EventArgs e) { Commit(); } #region IFieldControl Member public IFeature Feature { get { return _feature; } set { if (_feature != value) { base.BackColor = Color.White; _feature = value; if (_feature != null) { _origValue = _feature[_field.name]; base.Value = (_origValue != null && _origValue != DBNull.Value) ? Convert.ToDecimal(_origValue) : (decimal)0.0; base.Enabled = true; } else { _origValue = null; base.Value = (decimal)0.0; base.Enabled = false; } } } } public bool Commit() { if (_feature == null) { return false; } switch (_field.type) { case FieldType.smallinteger: Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, (short)base.Value); break; case FieldType.integer: Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, (int)base.Value); break; case FieldType.biginteger: Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, (long)base.Value); break; case FieldType.Float: Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, (float)base.Value); break; case FieldType.Double: Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, (double)base.Value); break; } if (_origValue != null) { if (CompareValues(_origValue, _feature[_field.name])) { base.BackColor = Color.White; } else { base.BackColor = Color.Yellow; } } else { if (_feature[_field.name] == null) { base.BackColor = Color.White; } else { base.BackColor = Color.Yellow; } } return true; } #endregion private bool CompareValues(object var1, object var2) { if (var1 == null && var2 == null) { return true; } if (var1 != null && var1.Equals(var2)) { return true; } try { double v1 = Convert.ToDouble(var1); double v2 = Convert.ToDouble(var2); return v1 == v2; } catch { } return false; } #region IErrorMessage Member public string LastErrorMessage { get { return _errMsg; } set { _errMsg = value; } } #endregion } private class ComboControl : ComboBox, IFieldControl { private IFeature _feature = null; private IField _field; private object _origValue = null; private string _errMsg = String.Empty; public ComboControl(IFeature feature, IField field, object[] values) { this.DropDownStyle = ComboBoxStyle.DropDownList; if (values == null) { return; } foreach (object v in values) { if (v == null) { continue; } this.Items.Add(v); } _field = field; this.Feature = feature; base.DrawMode = DrawMode.OwnerDrawFixed; base.DrawItem += new DrawItemEventHandler(ComboControl_DrawItem); base.SelectedIndexChanged += new EventHandler(ComboControl_SelectedIndexChanged); } void ComboControl_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == -1) { return; } object item = base.Items[e.Index]; if (item == null) { return; } RectangleF rect = new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height); if (Bit.Has(e.State, DrawItemState.ComboBoxEdit) && _field != null && _field.IsRequired && (base.SelectedItem == null || String.IsNullOrEmpty(base.SelectedItem.ToString()))) { e.Graphics.FillRectangle(Brushes.Red, rect); } else { e.Graphics.FillRectangle( CompareValues(item, _origValue) ? Brushes.White : Brushes.Yellow, rect); } e.Graphics.DrawString( item.ToString(), e.Font, Brushes.Black, rect); e.DrawFocusRectangle(); //switch (e.State) //{ // case DrawItemState.Selected: // e.Graphics.DrawString( // item.ToString(), // e.Font, // Brushes.Blue, // rect); // break; // default: // break; //} } void ComboControl_SelectedIndexChanged(object sender, EventArgs e) { if (CompareValues(base.SelectedItem, _origValue)) { base.BackColor = Color.White; } else { base.BackColor = Color.Yellow; } } private bool CompareValues(object var1, object var2) { if (var1 == null && var2 == null) { return true; } if (var1 != null && var2 != null && var1.ToString() == var2.ToString()) { return true; } if (var1 != null) { return var1.Equals(var2); } return false; } #region IFieldControl Member public IFeature Feature { get { return _feature; } set { if (_feature != value) { base.BackColor = Color.White; _feature = value; if (_feature != null) { _origValue = _feature[_field.name]; if (_origValue == null) { base.SelectedIndex = -1; } else { base.SelectedItem = _origValue.ToString(); } base.Enabled = true; } else { _origValue = null; base.SelectedIndex = -1; base.Enabled = false; } } } } public bool Commit() { _errMsg = String.Empty; if (_field.IsRequired && (this.SelectedItem == null || String.IsNullOrEmpty(this.SelectedItem.ToString()))) { _errMsg = "Value '" + _field.name + "' is required..."; return false; } if (this.SelectedItem != null && _feature != null && _field != null) { Module.SetValueOrAppendFieldValueIfNotExist( _feature, _field.name, this.SelectedItem); } return true; } #endregion #region IErrorMessage Member public string LastErrorMessage { get { return _errMsg; } set { _errMsg = value; } } #endregion } private class MaskedTextBox : TextControl { private char _decimalSeperator = '.'; private bool m_dateOnly; private bool m_phoneOnly; private bool m_IPAddrOnly; private bool m_ssn; private bool m_decimalOnly; private bool m_digitOnly; private int digitPos = 0; private int DelimitNumber = 0; private System.Windows.Forms.ErrorProvider errorProvider1; private System.ComponentModel.Container components = null; public bool DecimalOnly { get { return m_decimalOnly; } set { m_decimalOnly = value; if (value) { try { _decimalSeperator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; } catch { _decimalSeperator = '.'; } } } } public bool PhoneWithAreaCode { get { return m_phoneOnly; } set { m_phoneOnly = value; } } public bool DateOnly { get { return m_dateOnly; } set { m_dateOnly = value; } } public bool SSNOnly { get { return m_ssn; } set { m_ssn = value; } } public bool IPAddrOnly { get { return m_IPAddrOnly; } set { m_IPAddrOnly = value; } } public bool DigitOnly { get { return m_digitOnly; } set { m_digitOnly = value; } } public MaskedTextBox(IFeature feature, IField field) : base(feature, field) { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitForm call } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.errorProvider1 = new System.Windows.Forms.ErrorProvider(); // // errorProvider1 // this.errorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink; // // MaskedTextBox // this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnKeyPress); } #endregion private void OnKeyPress(object sender, KeyPressEventArgs e) { MaskedTextBox sd = (MaskedTextBox)sender; if (sd.m_IPAddrOnly) { sd.MaskIpAddr(e); } if (sd.m_digitOnly) { sd.MaskDigit(e); } if (sd.m_ssn) { sd.MaskPhoneSSN(e, 3, 2); } if (sd.m_phoneOnly) { sd.MaskPhoneSSN(e, 3, 3); } if (sd.m_dateOnly) { sd.MaskDate(e); } if (sd.m_decimalOnly) { sd.MaskDecimal(e); } } private void MaskDigit(KeyPressEventArgs e) { if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '-' || e.KeyChar == '+') { string text = InsertKeyToText(e); try { switch (_field.type) { case FieldType.smallinteger: short.Parse(text); break; case FieldType.integer: int.Parse(text); break; case FieldType.biginteger: long.Parse(text); break; } } catch (Exception ex) { e.Handled = true; errorProvider1.SetError(this, ex.Message); return; } errorProvider1.SetError(this, ""); e.Handled = false; } else { e.Handled = true; errorProvider1.SetError(this, "Only valid for Digit"); } } private void MaskDecimal(KeyPressEventArgs e) { if (Char.IsDigit(e.KeyChar) || e.KeyChar == _decimalSeperator || e.KeyChar == 8 || e.KeyChar == '-' || e.KeyChar == '+') { string text = InsertKeyToText(e); try { switch (_field.type) { case FieldType.Float: float.Parse(text); break; case FieldType.Double: double.Parse(text); break; } } catch (Exception ex) { e.Handled = true; errorProvider1.SetError(this, ex.Message); return; } e.Handled = false; errorProvider1.SetError(this, ""); } else { e.Handled = true; errorProvider1.SetError(this, "Only valid for Digit and dot"); } } private void MaskDate(KeyPressEventArgs e) { int len = this.Text.Length; int indx = this.Text.LastIndexOf("/"); // if test is highlighted reset vars if (this.SelectedText == this.Text) { indx = -1; digitPos = 0; DelimitNumber = 0; this.Text = null; } if (Char.IsDigit(e.KeyChar) || e.KeyChar == '/' || e.KeyChar == 8) { string tmp = this.Text; if (e.KeyChar != 8) { if (e.KeyChar != '/') { if (indx > 0) { digitPos = len - indx; } else { digitPos++; } if (digitPos == 3 && DelimitNumber < 2) { if (e.KeyChar != '/') { DelimitNumber++; this.AppendText("/"); } } errorProvider1.SetError(this, ""); if ((digitPos == 2 || (Int32.Parse(e.KeyChar.ToString()) > 1 && DelimitNumber == 0))) { string tmp2; if (indx == -1) { tmp2 = e.KeyChar.ToString(); } else { tmp2 = this.Text.Substring(indx + 1) + e.KeyChar.ToString(); } if (DelimitNumber < 2) { if (digitPos == 1) { this.AppendText("0"); } this.AppendText(e.KeyChar.ToString()); if (indx < 0) { if (Int32.Parse(this.Text) > 12) // check validation { string str; str = this.Text.Insert(0, "0"); if (Int32.Parse(this.Text) > 13) { this.Text = str.Insert(2, "/0"); DelimitNumber++; this.AppendText("/"); } else { this.Text = str.Insert(2, "/"); this.AppendText(""); } DelimitNumber++; } else { this.AppendText("/"); DelimitNumber++; } e.Handled = true; } else { if (DelimitNumber == 1) { int m = Int32.Parse(this.Text.Substring(0, indx)); if (!CheckDayOfMonth(m, Int32.Parse(tmp2))) { errorProvider1.SetError(this, "Make sure this month have the day"); } else { this.AppendText("/"); DelimitNumber++; e.Handled = true; } } } } } else if (digitPos == 1 && Int32.Parse(e.KeyChar.ToString()) > 3 && DelimitNumber < 2) { if (digitPos == 1) { this.AppendText("0"); } this.AppendText(e.KeyChar.ToString()); this.AppendText("/"); DelimitNumber++; e.Handled = true; } else { if (digitPos == 1 && DelimitNumber == 2 && e.KeyChar > '2') { errorProvider1.SetError(this, "The year should start with 1 or 2"); } } } else { DelimitNumber++; string tmp3; if (indx == -1) { tmp3 = this.Text.Substring(indx + 1); } else { tmp3 = this.Text; } if (digitPos == 1) { this.Text = tmp3.Insert(indx + 1, "0"); ; this.AppendText("/"); e.Handled = true; } } } else { e.Handled = false; if ((len - indx) == 1) { DelimitNumber--; if (indx > -1) { digitPos = 2; } else { digitPos--; } } else { if (indx > -1) { digitPos = len - indx - 1; } else { digitPos = len - 1; } } } } else { e.Handled = true; errorProvider1.SetError(this, "Only valid for Digit and /"); } } private void MaskPhoneSSN(KeyPressEventArgs e, int pos, int pos2) { int len = this.Text.Length; int indx = this.Text.LastIndexOf("-"); // if test is highlighted reset vars if (this.SelectedText == this.Text) { indx = -1; digitPos = 0; DelimitNumber = 0; } if (Char.IsDigit(e.KeyChar) || e.KeyChar == '-' || e.KeyChar == 8) { // only digit, Backspace and - are accepted string tmp = this.Text; if (e.KeyChar != 8) { errorProvider1.SetError(this, ""); if (e.KeyChar != '-') { if (indx > 0) { digitPos = len - indx; } else { digitPos++; } } if (indx > -1 && digitPos == pos2 && DelimitNumber == 1) { if (e.KeyChar != '-') { this.AppendText(e.KeyChar.ToString()); this.AppendText("-"); e.Handled = true; DelimitNumber++; } } else if (digitPos == pos && DelimitNumber == 0) { if (e.KeyChar != '-') { this.AppendText(e.KeyChar.ToString()); this.AppendText("-"); e.Handled = true; DelimitNumber++; } } } else { e.Handled = false; if ((len - indx) == 1) { DelimitNumber--; if ((indx) > -1) { digitPos = len - indx; } else { digitPos--; } } else { if (indx > -1) { digitPos = len - indx - 1; } else { digitPos = len - 1; } } } } else { e.Handled = true; errorProvider1.SetError(this, "Only valid for Digit and -"); } } private void MaskIpAddr(KeyPressEventArgs e) { int len = this.Text.Length; int indx = this.Text.LastIndexOf("."); // if test is highlighted reset vars if (this.SelectedText == this.Text) { indx = -1; digitPos = 0; DelimitNumber = 0; } if (Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == 8) { // only digit, Backspace and dot are accepted string tmp = this.Text; errorProvider1.SetError(this, ""); if (e.KeyChar != 8) { if (e.KeyChar != '.') { if (indx > 0) { digitPos = len - indx; } else { digitPos++; } } if (digitPos == 3 && e.KeyChar != '.') { string tmp2 = this.Text.Substring(indx + 1) + e.KeyChar; if (Int32.Parse(tmp2) > 255) // check validation { errorProvider1.SetError(this, "The number can't be bigger than 255"); } else { if (DelimitNumber < 3) { this.AppendText(e.KeyChar.ToString()); this.AppendText("."); DelimitNumber++; e.Handled = true; } } } else if (digitPos == 4 && DelimitNumber < 3) { this.AppendText("."); } } else { e.Handled = false; if ((len - indx) == 1) { DelimitNumber--; if (indx > -1) { digitPos = len - indx; } else { digitPos--; } } else { if (indx > -1) { digitPos = len - indx - 1; } else { digitPos = len - 1; } } } } else { e.Handled = true; errorProvider1.SetError(this, "Only valid for Digit abd dot"); } } private bool CheckDayOfMonth(int mon, int day) { bool ret = true; if (day == 0) { ret = false; } switch (mon) { case 1: if (day > 31) { ret = false; } break; case 2: if (day > 28) { ret = false; } break; case 3: if (day > 31) { ret = false; } break; case 4: if (day > 30) { ret = false; } break; case 5: if (day > 31) { ret = false; } break; case 6: if (day > 30) { ret = false; } break; case 7: if (day > 31) { ret = false; } break; case 8: if (day > 31) { ret = false; } break; case 9: if (day > 30) { ret = false; } break; case 10: if (day > 31) { ret = false; } break; case 11: if (day > 30) { ret = false; } break; case 12: if (day > 31) { ret = false; } break; default: ret = false; break; } return ret; } private string InsertKeyToText(KeyPressEventArgs e) { string text = base.Text; if (base.SelectionStart == text.Length) { if (e.KeyChar == 8) // BackSpace { return text.Substring(0, text.Length - 1); } return text + e.KeyChar; } else { string t1 = text.Substring(0, base.SelectionStart); string t2 = text.Substring(base.SelectionStart + base.SelectionLength, text.Length - base.SelectionStart - base.SelectionLength); if (e.KeyChar == 8) { if (base.SelectionLength == 0) { return t1 + t2; } else { return t1.Substring(0, t1.Length - 1) + t2; } } return t1 + e.KeyChar + t2; } } public override bool Commit() { if (!base.Commit()) { return false; } if (String.IsNullOrEmpty(base.Text) && _field.IsRequired == false) { Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, System.DBNull.Value); return true; } try { switch (_field.type) { case FieldType.smallinteger: Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, Convert.ToInt16(base.Text)); break; case FieldType.integer: Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, Convert.ToInt32(base.Text)); break; case FieldType.biginteger: Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, Convert.ToInt64(base.Text)); break; case FieldType.Float: Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, Convert.ToSingle(base.Text)); break; case FieldType.Double: Module.SetValueOrAppendFieldValueIfNotExist(Feature, _field.name, Convert.ToDouble(base.Text)); break; } } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } return true; } } //[Designer(typeof(NumberTextBox.NumberTextBoxDesigner))] private class NumberTextBox : TextControl { public const int WM_PASTE = 0x0302; public const int WM_CHAR = 0x0102; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool MessageBeep(uint UType); public NumberTextBox(IFeature feature, IField field) : base(feature, field) { } protected override bool ProcessKeyEventArgs(ref Message m) { int nKey = m.WParam.ToInt32(); if ((nKey >= (char)48 && nKey <= (char)57) || nKey == (char)8 || nKey == (char)45 || nKey == (char)46) { return base.ProcessKeyPreview(ref m); } else { if (m.Msg == 256 && nKey == 46) { return base.ProcessKeyPreview(ref m); } if (m.Msg == 258) { MessageBeep(0); } } return true; } protected override void WndProc(ref Message m) { if (m.Msg == WM_CHAR) { int keyChar = m.WParam.ToInt32(); bool charOk = (keyChar > 47 && keyChar < 58) || keyChar == 8 || keyChar == 3 || keyChar == 22 || keyChar == 24; if (!charOk) { return; } } if (m.Msg == WM_PASTE) { IDataObject iData = Clipboard.GetDataObject(); if (iData.GetDataPresent(DataFormats.Text)) { string str; str = (String)iData.GetData(DataFormats.Text); if (!System.Text.RegularExpressions.Regex.IsMatch(str, @"^(\d{1,})$")) { return; } } } base.WndProc(ref m); } } private class NumberControl3 : TextControl { public NumberControl3(IFeature feature, IField field) : base(feature, field) { this.CausesValidation = true; this.Validating += new CancelEventHandler(NumberControl_Validating); } void NumberControl_Validating(object sender, CancelEventArgs e) { try { switch (_field.type) { case FieldType.smallinteger: short.Parse(this.Text); break; case FieldType.integer: int.Parse(this.Text); break; case FieldType.biginteger: long.Parse(this.Text); break; case FieldType.Float: float.Parse(this.Text); break; case FieldType.Double: double.Parse(this.Text); break; } } catch (Exception /*ex*/) { e.Cancel = true; //MessageBox.Show("Insert valid " + _field.type.ToString() + "-Number!"); } } } #endregion #region IErrorMessage Member public string LastErrorMessage { get { return _errMsg; } set { _errMsg = value; } } #endregion } }
using LHRLA.Model; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LHRLA.DAL.Model { [MetadataType(typeof(tbl_Case_TypesMetaData))] public partial class tbl_Case_Types { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fix_Emails { class Program { static void Main(string[] args) { var emailsDict = new Dictionary<string, string>(); while (true) { string input = Console.ReadLine(); if (input == "stop") { break; } string email = Console.ReadLine(); string domain = email.Substring(email.Length - 2); if (domain == "uk" || domain == "us") { continue; } else { emailsDict.Add(input, email); } } foreach (var email in emailsDict) { Console.WriteLine($"{email.Key} -> {email.Value}"); } } } }
using System; namespace Tast1_2 { class Program { static void Main(string[] args) { int[] numbers = {34, 5, 67, 1, 99, 34, 44, 78, 34, 0}; int total = 0; for(int i = 0; i < numbers.Length; i++) { total = total + numbers[i]; } Console.WriteLine(total); } } }
using System.ComponentModel.DataAnnotations; using Tomelt.DisplayManagement.Shapes; namespace Tomelt.MediaLibrary.MediaFileName { public class MediaFileNameEditorViewModel : Shape { [Required] public string FileName { get; set; } } }
using AzureAI.CallCenterTalksAnalysis.Core.Services; using AzureAI.CallCenterTalksAnalysis.Core.Services.Interfaces; using Microsoft.Extensions.DependencyInjection; namespace AzureAI.CallCenterTalksAnalysis.FunctionApps.Core.DependencyInjection { public static class FileFormatValidationServiceExtensions { public static IServiceCollection AddFileFormatValidationServices(this IServiceCollection services) { services.AddSingleton<IFileFormatValidationService, FileFormatValidationService>(); return services; } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ExamOnline.BaseClass; namespace ExamOnline.Admin { public partial class ExaminationInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["AdminName"] == null) { Response.Redirect("../Login.aspx"); } if (!IsPostBack) { string strsql = "select * from F_Test order by ID desc"; BaseClass.BaseClass.BindDG(gvExaminationInfo, "ID", strsql, "ExaminationInfo"); DalAdmin dal = new DalAdmin(); var sdr = dal.GetSdrInformation("select * from F_Lession"); this.ddlEkm.DataSource = sdr; this.ddlEkm.DataTextField = "Lession_Name"; this.ddlEkm.DataValueField = "Lession_ID"; this.ddlEkm.DataBind(); this.ddlEkm.SelectedIndex = 0; } } public string Getstatus(string zt) { if (zt == "0") return "否"; else return "是"; } protected void btnSerch_Click(object sender, EventArgs e) { string strsql = "select * from F_Test where TestCourse='" + ddlEkm.SelectedItem.Text + "'"; BaseClass.BaseClass.BindDG(gvExaminationInfo, "ID", strsql, "Result"); lbltype.Text = ddlEkm.SelectedItem.Text; } protected void gvExaminationInfo_RowDeleting(object sender, GridViewDeleteEventArgs e) { int id = (int)gvExaminationInfo.DataKeys[e.RowIndex].Value; string sql = "delete from F_Test where ID=" + id; BaseClass.BaseClass.OperateData(sql); string strsql = "select * from F_Test order by ID desc"; BaseClass.BaseClass.BindDG(gvExaminationInfo, "ID", strsql, "ExaminationInfo"); } protected void gvExaminationInfo_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvExaminationInfo.PageIndex = e.NewPageIndex; string strsql = "select * from F_Test order by ID desc"; BaseClass.BaseClass.BindDG(gvExaminationInfo, "ID", strsql, "ExaminationInfo"); } } }
using UnityEngine; using System; using System.Collections; [Serializable] public class ActionObject { public GameObject actionObject;//要操作的对象 public Vector3 startPosition;//开始位置,用于置放实体零部件 public Vector3 endPosition;//结束位置,用于指定运动路线及高亮提示所在的位置 public Vector3 startRotation;//开始角度 public Vector3 endRotation;//结束角度 }
#region MIT License /* * Copyright (c) 2009 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen. */ using Buttons = Silk.NET.Input.ButtonName; namespace Jypeli { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public enum Button { DPadUp = Buttons.DPadUp, DPadDown = Buttons.DPadDown, DPadLeft = Buttons.DPadLeft, DPadRight = Buttons.DPadRight, /// <summary> /// Start. /// </summary> Start = Buttons.Start, /// <summary> /// Back. /// </summary> Back = Buttons.Back, /// <summary> /// Oikea tikku. /// </summary> LeftStick = Buttons.LeftStick, /// <summary> /// Vasen tikku. /// </summary> RightStick = Buttons.RightStick, /// <summary> /// Vasen olkanappi. /// </summary> LeftShoulder = Buttons.LeftBumper, /// <summary> /// Oikea olkanappi. /// </summary> RightShoulder = Buttons.RightBumper, BigButton = Buttons.Home, A = Buttons.A, B = Buttons.B, X = Buttons.X, Y = Buttons.Y, /// <summary> /// Oikea liipasin. /// </summary> RightTrigger = 15, /// <summary> /// Vasen liipasin. /// </summary> LeftTrigger = 16 } }
using Microsoft.VisualStudio.DebuggerVisualizers; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; namespace IEnumerableVisualizerDotNetStandard { /// <summary> /// debugee side /// </summary> public class IEnumerableVisualizerObjectSource : VisualizerObjectSource { private int _serializeIndex = 0; public const int SERIALIZE_COUNT = 50; public override void GetData(object target, Stream outgoingData) { DataTable results; if (target is Array array) { results = Serialize(array.Cast<object>()); } else if (target is ArrayList arrayList) { results = Serialize(arrayList.Cast<object>()); } else if (target is BitArray bitArray) { results = Serialize(bitArray.Cast<object>()); } else if (target is BindingList<object> bindingList) { results = Serialize(bindingList); } else if (target is BlockingCollection<object> blockingCollection) { results = Serialize(blockingCollection); } else if (target is CollectionBase collectionBase) { results = Serialize(collectionBase.Cast<object>()); } else if (target is ConcurrentBag<object> concurrentBag) { results = Serialize(concurrentBag); } else if (target is ConcurrentDictionary<object, object> concurrentDictionary) { results = Serialize(concurrentDictionary); } else if (target is ConcurrentQueue<object> concurrentQueue) { results = Serialize(concurrentQueue); } else if (target is ConcurrentStack<object> concurrentStack) { results = Serialize(concurrentStack); } else if (target is DataRow dataRow && dataRow.Table != null) { results = dataRow.Table.Clone(); results.Rows.Add(dataRow.ItemArray); } else if (target is DataRowCollection dataRowCollection && dataRowCollection.Count > 0 && dataRowCollection[0].Table != null) { results = dataRowCollection[0].Table.Clone(); dataRowCollection.Cast<DataRow>().ToList().ForEach(x => results.Rows.Add(x.ItemArray)); } else if (target is Dictionary<object, object> dictionary1) { results = Serialize(dictionary1); } else if (target is Dictionary<object, object>.ValueCollection valueCollection) { results = Serialize(valueCollection); } else if (target is DictionaryBase dictionaryBase) { results = Serialize(dictionaryBase); } else if (target is LinkedList<object> linkedList) { results = Serialize(linkedList); } else if (target is List<object> list) { results = Serialize(list); } else if (target is ReadOnlyCollectionBase readOnlyCollectionBase) { results = Serialize(readOnlyCollectionBase.Cast<object>()); } else if (target is SortedList<object, object> sortedList1) { results = Serialize(sortedList1); } else if (target is SortedList sortedList2) { results = Serialize(sortedList2); } else if (target is Stack<object> stack1) { results = Serialize(stack1); } else if (target is Stack stack2) { results = Serialize(stack2.Cast<object>()); } else if (target is SortedSet<object> sortedSet) { results = Serialize(sortedSet); } else if (target is Queue<object> queue1) { results = Serialize(queue1); } else if (target is Queue queue2) { results = Serialize(queue2.Cast<object>()); } else if (target is IDictionary dictionary2) { results = Serialize(dictionary2); } else if (target is IList<object> iList1) { results = Serialize(iList1); } else if (target is IList iList2) { results = Serialize(iList2.Cast<object>()); } else if (target is ICollection<object> iCollection1) { results = Serialize(iCollection1); } else if (target is ICollection iCollection2) { results = Serialize(iCollection2.Cast<object>()); } else if (target is IQueryable<object> iQueryable1) { results = Serialize(iQueryable1); } else if (target is IQueryable iQueryable2) { results = Serialize(iQueryable2.Cast<object>()); } else if (target is IEnumerable<object> iEnumerable1) { results = Serialize(iEnumerable1); } else if (target is IEnumerable iEnumerable2) { results = Serialize(iEnumerable2.Cast<object>()); } else { results = new DataTable(); } results.Namespace = target.GetType().ToString(); base.GetData(results, outgoingData); } private DataTable Serialize(IEnumerable<object> objects) { var results = default(DataTable); if (objects != null) { results = Serialize(objects.ToArray()); _serializeIndex++; } return results; } private DataTable Serialize(IDictionary dictionary) { var results = default(DataTable); if (dictionary != null) { var dataTable1 = Serialize(dictionary.Keys.Cast<object>().ToArray()); var dataTable2 = Serialize(dictionary.Values.Cast<object>().ToArray()); _serializeIndex++; results = new DataTable(); foreach (DataColumn column in dataTable1.Columns) { AddColumn(results, string.Format("[{0}]", column.ColumnName), column.DataType); } foreach (DataColumn column in dataTable2.Columns) { AddColumn(results, column.ColumnName, column.DataType); } var dataTable1Count = dataTable1.Rows.Count; var dataTable2Count = dataTable2.Rows.Count; if (dataTable1Count == dataTable2Count) { for (int i = 0; i < dataTable1Count; i++) { var values = dataTable1.Rows[i].ItemArray.ToList(); values.AddRange(dataTable2.Rows[i].ItemArray); results.Rows.Add(values.ToArray()); } } else if (dataTable1Count > 0) { results.Rows.Add(dataTable1.Rows); } else if (dataTable2Count > 0) { results.Rows.Add(dataTable2.Rows); } } return results; } public DataTable Serialize(object[] objects) { var results = new DataTable(); var isHeterogeneous = objects.Select(x => x.GetType()).Distinct().Count() > 1; if (isHeterogeneous) { AddColumn(results, typeof(object).Name, typeof(string)); for (int i = 0; i < objects.Length; i++) { results.Rows.Add(objects[i]?.ToString()); } } else { objects = objects.Skip(_serializeIndex * SERIALIZE_COUNT).Take(SERIALIZE_COUNT).ToArray(); var first = objects.FirstOrDefault(); if (first != null) { var type = first.GetType(); if (type != null) { var propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) .Where(x => x.CanRead && !x.GetIndexParameters().Any()).ToArray(); var propertyInfosLength = propertyInfos.Length; var fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var fieldInfosLength = fieldInfos.Length; if (type.IsPrimitive || type.IsValueType || type == typeof(string) || type == typeof(IntPtr)) { AddColumn(results, type.ToString(), GetColumnType(type)); } else { for (int j = 0; j < fieldInfosLength; j++) { var fieldType = fieldInfos[j].FieldType; AddColumn(results, fieldInfos[j].Name, GetColumnType(fieldType)); } for (int j = 0; j < propertyInfosLength; j++) { var propertyType = propertyInfos[j].PropertyType; AddColumn(results, propertyInfos[j].Name, GetColumnType(propertyType)); } } for (int i = 0; i < objects.Length; i++) { var values = new List<object>(); if (type.IsPrimitive || type.IsValueType || type == typeof(string)) { var value = default(object); try { value = GetValue(type, objects[i]); } catch (Exception ex) { value = ex.Message; } values.Add(value); } else { for (int j = 0; j < fieldInfosLength; j++) { var value = default(object); try { value = GetValue(results.Columns[values.Count].DataType, fieldInfos[j].GetValue(objects[i])); } catch (Exception ex) { value = ex.Message; } values.Add(value); } for (int j = 0; j < propertyInfosLength; j++) { var value = default(object); try { value = GetValue(results.Columns[values.Count].DataType, propertyInfos[j].GetValue(objects[i])); } catch (Exception ex) { value = ex.Message; } values.Add(value); } } for (int j = 0; j < values.Count(); j++) { if (values[j] is string && results.Columns[j].DataType != typeof(string)) { results.Columns[j].DataType = typeof(string); } } results.Rows.Add(values.ToArray()); } } } } return results; } private void AddColumn(DataTable result, string columnName, Type type) { if (result != null && result.Columns != null) { var columnNameTemplate = columnName + " ({0})"; int i = 0; while (result.Columns.Contains(columnName) && i < int.MaxValue) { columnName = string.Format(columnNameTemplate, i); i++; } result.Columns.Add(columnName, GetColumnType(type)); } } private object GetValue(Type type, object value) { object result; if (IsSerializable(type)) { result = value; } else { result = value?.ToString(); } return result; } private bool IsSerializable(Type type) { var result = false; if ((type is IXmlSerializable || type.IsPrimitive) && type != typeof(IntPtr)) { result = true; } return result; } private Type GetColumnType(Type type) { var result = typeof(string); if (IsSerializable(type)) { result = type; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2.LettersAndDigits { class LettersDigits { static void Main() { Console.WriteLine("Enter six elements long text: "); string text = Console.ReadLine(); byte digits = 0; byte small = 0; byte big = 0; byte rest = 0; foreach (var item in text) { bool isDigit = char.IsDigit(item); if (isDigit) { digits++; } bool isLower = char.IsLower(item); if (isLower) { small++; } bool isUpper = char.IsUpper(item); if (isUpper) { big++; } bool isSymbol = char.IsSymbol(item); if (isSymbol) { rest++; } } Console.WriteLine("{0} {1} {2} {3}", digits, small, big, rest); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InoDrive.Domain.Models.InputModels { public class InputManageBidModel { public String UserId { get; set; } public Int32 TripId { get; set; } public Int32 BidId { get; set; } public String UserOwnerId { get; set; } public String UserClaimedId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Platform : Programmable { // Lowest position relative to the platform's original position public float MinElevation = 0.0f; // Highest position relative to the platform's original position public float MaxElevation = 1000.0f; }
using System.Globalization; using Autofac; using Tests.Pages.ActionID; using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Oberon; using Tests.Pages.Oberon.CodeManagement; using Tests.Pages.Oberon.Contact; using Tests.Pages.Oberon.Event; namespace Tests.Projects.Oberon.Event { public class AutomaticLinkingDisbursementReceivedFromEvent : BaseTest { private Driver Driver {get { return Scope.Resolve<Driver>(); }} private ActionIdLogIn ActionLogIn { get { return Scope.Resolve<ActionIdLogIn>(); } } /// <summary> /// Test: /// Scenario: Create events with source code, create contact and contribution and link contribution to event /// Steps: 1. Create Source Codes. 2. Create Event with source code. 3. Create contact and contribution using source code /// 4. Link contribution to event. 5. Verify data. /// </summary> [Test] //[Ignore] [Category("oberon"), Category("oberon_disbursements"), Category("oberon_event"), Category("oberon_smoketest"), Category("oberon_codes")] public void AutomaticLinkingDisbursementReceivedFromEventTest() { ActionLogIn.LogInTenant(); // create a source code string eCode = FakeData.RandomLetterString(10); string dCode = FakeData.RandomLetterString(10); var codesPage = Scope.Resolve<CodeManagementHome>(); codesPage.AddNewCode("source", eCode); codesPage.AddNewCode("source", dCode); // create an event var newEvent = Scope.Resolve<TestEvent>().GetTestEvent(); var create = Scope.Resolve<EventCreate>(); string eventId = create.CreateEvent(eCode, newEvent); // create contact var contact = Scope.Resolve<ContactCreate>(); var testContact = new TestContact { FirstName = "Event", LastName = "WithDisbursements" }; testContact.Id = contact.CreateContact(testContact); // create disbursement 1 var detail = Scope.Resolve<ContactDetail>(); string disbursementId1 = detail.AddNewDisbursement(eCode); // create disbursement 2 string disbursementId2 = detail.AddNewDisbursement(dCode); //compare event details page var eventDetail = Scope.Resolve<EventDetail>(); eventDetail.GoToEventDetail(eventId); Assert.AreEqual(newEvent.Name, eventDetail.EventName.Text); Assert.AreEqual(newEvent.Description, eventDetail.Description.Text); //Assert.AreEqual(newEvent.IsFundraisingEvent, eventDetail.FundraisingEvent); Assert.AreEqual("$" + newEvent.TargetAmountToRaise + ".00", eventDetail.TargetAmountToRaise.Text); Assert.AreEqual(newEvent.TargetGuestCount, eventDetail.TargetGuestCount.Text); string startDate = newEvent.StartDate + " " + newEvent.StartDateHour + ":" + newEvent.StartDateMinute + ":00 " + newEvent.StartDateMeridian; Assert.AreEqual(startDate, eventDetail.StartDateTime.Text); string endDate = newEvent.EndDate + " " + newEvent.EndDateHour + ":" + newEvent.EndDateMinute + ":00 " + newEvent.EndDateMeridian; Assert.AreEqual(endDate, eventDetail.EndDateTime.Text); Assert.AreEqual(newEvent.LocationName, eventDetail.LocationName.Text); //Assert.AreEqual(eCode, eventDetail.SourceCode.Text); Assert.IsTrue(eventDetail.Address.Text.Contains(newEvent.StateProvince)); Assert.IsTrue(eventDetail.Address.Text.Contains(newEvent.PostalCode)); // view disbursement eventDetail.ClickViewDisbursement(); // verify only one disbursement displays var eventList = Scope.Resolve<EventListDisbursement>(); Assert.AreEqual(Driver.GetRowCountInTable(eventList.EventDisbursementListTable).ToString(CultureInfo.InvariantCulture), "1", "there is more or less then 1 disbursement displayed"); // delete contact //var contactDetail = new ContactDetail(_driver); //contactDetail.GoToContactDetail(testContact.Id); //contactDetail.ClickDeleteLink(); //todo need to delete linked items first } } }
using Application.Common; using Domain.Extensions; using Infrastructure.Persistent; using Microsoft.AspNetCore.Mvc.Testing; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection.Extensions; using Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; namespace WebApi.IntegrationTests { public class IntegrationTest { protected readonly HttpClient TestClient; protected IntegrationTest() { var appFactory = new WebApplicationFactory<Startup>().WithWebHostBuilder(builder => { builder.ConfigureServices(services => { services.RemoveAll(typeof(IDbContext)); services.AddDbContext<IDbContext, ApplicationDbContext>(options => options.UseInMemoryDatabase("testDB")); }); }); using (var scope = appFactory.Services.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService<IDbContext>(); SeedSampleData(db); } TestClient = appFactory.CreateClient(); } private void SeedSampleData(IDbContext context) { if (!context.Users.Any()) { context.Users.Add(new Domain.Entities.User { Name = "John Doe", PasswordHash = "demopass".Hash("demouser"), Username = "demouser" }); context.SaveChanges(); } } protected void Authenticate() { TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetBasicAuth()); } private string GetBasicAuth() { return Convert.ToBase64String(Encoding.UTF8.GetBytes("demouser:demopass")); } } }
using INOTE.Core.Domain; using INOTE.View.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace INOTE.View { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static Frame Frame; private static ToolBarTray Toolbar; private static TextBlock Username; private static TextBlock Email; public MainWindow() { InitializeComponent(); Frame = MainWindowFrame; Toolbar = MainToolbar; Username = UsernameTb; Email = EmailTb; MainWindowFrame.Navigate(new LoginPage()); } public static void SetMainToolbarVisibility(bool isVisible, User user = null) { if(isVisible) { Toolbar.Visibility = Visibility.Visible; Username.Text = user.Username; Email.Text = user.Email; } else { Toolbar.Visibility = Visibility.Hidden; } } } }
using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class EditorsController : DemoController { public ActionResult LargeDataComboBox() { return DemoView("LargeDataComboBox"); } public ActionResult LargeDataComboBoxPartial() { return PartialView(); } } }
 namespace Mio.TileMaster { [System.Serializable] public class ScoreItemModel { public int highestScore; public int highestStar; public int highestCrown; public string itemName; } }
namespace KartSystem.Common { public class UserControlRelation { public UserControlRelation(object keyName, string userControlClassName) { KeyName = keyName; ClassName = userControlClassName; } public object KeyName { get; set; } public string ClassName { get; set; } } }
using GDS.BLL; using GDS.Comon; using GDS.Entity; using GDS.Entity.Constant; using GDS.Entity.Result; using GDS.Query; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using GDS.WebApi.Models; namespace GDS.WebApi.Controllers { public class IndexController : BaseController { public ActionResult Index() { return View(); } /* 系统权限应分为管理员,超级用户及一般用户。 管理员:系统最大权限,能对系统所有内容进行操作。 超级用户:不能对用户权限进行设置,但能查看所有项目(非自己参与的也能查看),能创建项目模板创建项目和维护管理基础信息。 项目经理:可创建项目和管理项目,审核项目内容 普通用户:项目参与者,可对参与的项目进行查阅,上传文档和填写表单 */ [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetIndex() { if (CurrenUserInfo == null) { return Json(new ResponseEntity<dynamic>(-2, "无权限", null), JsonRequestBehavior.AllowGet); } var result = new ProjectBLL().GetIndex(CurrenUserInfo.LoginName); var response = new ResponseEntity<object>(true, ConstantDefine.TipQuerySuccess, result); return Json(response, JsonRequestBehavior.AllowGet); } } }
namespace CODE.Framework.Wpf.Mvvm { /// <summary> /// Provides information about a launched view /// </summary> public interface IViewInformation { /// <summary> /// Location this view was originally loaded from /// </summary> string OriginalViewLoadLocation { get; set; } } }
using System; using System.Linq; using Upgrader.Infrastructure; namespace Upgrader.SqlServer { public class SqlServerDatabase : Database { private static readonly Lazy<ConnectionFactory> ConnectionFactory = new Lazy<ConnectionFactory>(() => new ConnectionFactory(new AdoProvider("Microsoft.Data.SqlClient.dll", "Microsoft.Data.SqlClient.SqlConnection"), new AdoProvider("System.Data.SqlClient.dll", "System.Data.SqlClient.SqlConnection"), new AdoProvider("System.Data.dll", "System.Data.SqlClient.SqlConnection"))); private readonly string connectionString; /// <summary> /// Initializes a new instance of the <see cref="SqlServerDatabase"/> class. /// </summary> /// <param name="connectionString">Connection string.</param> public SqlServerDatabase(string connectionString) : base(ConnectionFactory.Value.CreateConnection(connectionString), GetMasterConnectionString(connectionString, "Initial Catalog", "master")) { this.connectionString = connectionString; TypeMappings.Add<bool>("bit"); TypeMappings.Add<byte>("tinyint"); TypeMappings.Add<char>("nchar(1)"); TypeMappings.Add<DateTime>("datetime"); TypeMappings.Add<decimal>("decimal(19,5)"); TypeMappings.Add<double>("float"); TypeMappings.Add<float>("real"); TypeMappings.Add<Guid>("uniqueidentifier"); TypeMappings.Add<int>("int"); TypeMappings.Add<long>("bigint"); TypeMappings.Add<short>("smallint"); TypeMappings.Add<string>("nvarchar(50)"); } public override bool Exists { get { UseMainDatabase(); var exists = Dapper.ExecuteScalar<bool>( "SELECT COUNT(*) FROM sysdatabases WHERE name = @databaseName", new { databaseName = DatabaseName }); UseConnectedDatabase(); return exists; } } internal override string[] GeneratedTypes => new[] { "timestamp" }; internal override string AutoIncrementStatement => "IDENTITY"; internal override int MaxIdentifierLength => 128; internal override string GetSchema(string tableName) { if (tableName == null || tableName.Contains('.') == false) { return Dapper.ExecuteScalar<string>("SELECT SCHEMA_NAME()"); } return tableName.Split('.').Last(); } internal override string GetColumnDataType(string tableName, string columnName) { return InformationSchema.GetColumnDataType(tableName, columnName, "decimal", "nvarchar", "nchar", "varchar", "char", "time"); } internal override string GetCreateComputedStatement(string dataType, bool nullable, string expression, bool persisted) { var persistedStatement = persisted ? " PERSISTED" : ""; return $"AS ({expression}){persistedStatement}"; } internal override void RenameColumn(string tableName, string columnName, string newColumnName) { Dapper.Execute($"sp_RENAME '{tableName}.{columnName}', '{newColumnName}', 'COLUMN'"); } internal override void RenameTable(string tableName, string newTableName) { Dapper.Execute($"sp_RENAME '{tableName}', '{newTableName}'"); } internal override bool GetColumnAutoIncrement(string tableName, string columnName) { return Dapper.ExecuteScalar<bool>( @" SELECT is_identity FROM sys.columns WHERE object_id = OBJECT_ID(@tableName) AND name = @columnName ", new { tableName, columnName }); } internal override string EscapeIdentifier(string identifier) { return "[" + identifier.Replace("]", "]]") + "]"; } internal override string[] GetIndexNames(string tableName) { return Dapper.Query<string>( @" SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(@tableName) AND [type] = 2 ", new { tableName }).ToArray(); } internal override bool GetIndexType(string tableName, string indexName) { return Dapper.ExecuteScalar<bool>( @" SELECT is_unique FROM sys.indexes WHERE name = @indexName AND object_id = OBJECT_ID(@tableName) AND [type] = 2 ", new { indexName, tableName }); } internal override string[] GetIndexColumnNames(string tableName, string indexName) { return Dapper.Query<string>( @" SELECT sys.columns.Name FROM sys.indexes INNER JOIN sys.index_columns ON sys.index_columns .object_id = sys.indexes.object_id AND sys.index_columns .index_id = sys.indexes.index_id INNER JOIN sys.columns ON sys.columns.object_id = sys.index_columns .object_id AND sys.columns.column_id = sys.index_columns .column_id WHERE sys.columns.object_id = OBJECT_ID(@tableName) AND sys.indexes.name = @indexName AND sys.indexes.[type] = 2 ", new { indexName, tableName }).ToArray(); } internal override void RemoveIndex(string tableName, string indexName) { var escapedTableName = EscapeIdentifier(tableName); var escapedIndexName = EscapeIdentifier(indexName); Dapper.Execute($"DROP INDEX {escapedTableName}.{escapedIndexName}"); } internal override string GetLastInsertedAutoIncrementedPrimaryKeyIdentity(string columnName) { return "SELECT SCOPE_IDENTITY()"; } internal override Database Clone() { return new SqlServerDatabase(connectionString); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02.Float_or_Double { class Program { static void Main(string[] args) { //double: 34.567839023, 12.345, 8923.1234857, 3456.091? float fNum0 = 12.345f; float fNum1 = 3456.091f; Console.WriteLine("{0}-{1}",fNum0,fNum1); } } }
using System; namespace GraphicalEditorServer.DTO.EventSourcingDTO { public class FloorChangeEventDTO { public String Username { get; set; } public int BuildingNumber { get; set; } public int Floor { get; set; } public FloorChangeEventDTO() { } public FloorChangeEventDTO(string username, int buildingNumber, int floor) { Username = username; BuildingNumber = buildingNumber; Floor = floor; } } }
 namespace CC.Mobile.Routing { public interface INavigationPage{ int Screen{ get;} IViewModel NavModel{get;} } }
using System; using System.Collections.Generic; namespace DemoEF.Domain.Models { public partial class TbOrderCompleted { public long Id { get; set; } public long? OrderFlowId { get; set; } public long? DecoratorFlowId { get; set; } public DateTime? AddTime { get; set; } public long? OptUser { get; set; } public string OptUsername { get; set; } public string EventType { get; set; } public DateTime? CompletedStartWorktime { get; set; } public DateTime? CompletedFinishWorktime { get; set; } public string CompletedPictureurl { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EntityFrameworkCoreDemo.Models { public class School : BaseObject { public string Name { get; set; } public List<Course> Courses { get; set; } public School(string name) : base() { Name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Core.DAL; using Core.BIZ; using System.Globalization; using PagedList; namespace WebForm.Areas.Admin.Controllers { public class PhieuXuatController : BaseController { #region Private Properties private static PhieuXuat _phieu; private static int? _currentPhieu; private CultureInfo _cultureInfo; // Thông tin văn hóa #endregion #region Public Properties public CultureInfo CultureInfo { get { if (_cultureInfo == null) { _cultureInfo = CultureInfo.GetCultureInfo("vi-VN"); } return _cultureInfo; } } #endregion #region Actions // GET: PhieuNhap public ActionResult All(int page = 1, int pageSize = 10, string search = null) { List<PhieuXuat> DMPhieu = null; ViewBag.cultureInfo = CultureInfo; if (!String.IsNullOrEmpty(search)) { DMPhieu = PhieuXuatManager.filter(search); ViewBag.SearchKey = search; } else { DMPhieu = PhieuXuatManager.getAll(); } ViewBag.tongTien = DMPhieu.Sum(ph => ph.TongTien); var models = DMPhieu.ToPagedList(page, pageSize); setAlertMessage(); return View(models); } // GET: PhieuNhap/Details/5 public ActionResult Details(int? id) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } var model = PhieuXuatManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } setAlertMessage(); return View(model); } // GET: PhieuNhap/Create public ActionResult Create() { ViewBag.cultureInfo = CultureInfo; ViewBag.DMSach = new SelectList(SachManager.getAllAlive() .Where(s => s.Soluong > 0).ToList(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); ViewBag.DMDaiLy = new SelectList(DaiLyManager.getAllAlive(), nameof(DaiLyManager.Properties.MaSoDaiLy), nameof(DaiLyManager.Properties.TenDaiLy), ""); if (_phieu == null) { _phieu = new PhieuXuat(); } _phieu.NgayLap = DateTime.Now; setAlertMessage(); return View(_phieu); } // POST: PhieuNhap/Create [HttpPost] public ActionResult Create(PhieuXuat model, FormCollection collection) { try { // TODO: Add insert logic here if (ModelState.IsValid) { var result = PhieuXuatManager.add(model); if (result != 0) { _phieu = null; putSuccessMessage("Thêm thành công"); return RedirectToAction("Details", new { id = result }); } else { putErrorMessage("Thêm không thành công"); } } else { putModelStateFailErrors(ModelState); } //ViewBag.cultureInfo = CultureInfo; //ViewBag.DMSach = new SelectList(SachManager.getAllAlive() // .Where(s => s.Soluong > 0).ToList(), // nameof(SachManager.Properties.MaSoSach), // nameof(SachManager.Properties.TenSach), ""); //ViewBag.DMDaiLy = new SelectList(DaiLyManager.getAllAlive(), // nameof(DaiLyManager.Properties.MaSoDaiLy), // nameof(DaiLyManager.Properties.TenDaiLy), ""); //_phieu.NgayLap = DateTime.Now; //return View(_phieu); return RedirectToAction("Create"); } catch(Exception ex) { putErrorMessage(ex.Message); return View(); } } // GET: PhieuNhap/Edit/5 public ActionResult Edit(int? id ) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } if (_currentPhieu == null || _currentPhieu != id) { _currentPhieu = id; _phieu = PhieuXuatManager.find((int)id); if (_phieu == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (_phieu.TrangThai == 1) { //Nếu đã duyệt thì không cho sửa, chuyển sang trang chi tiết _currentPhieu = null; putErrorMessage("Phiếu đã duyệt"); return RedirectToAction("Details", new { id = id }); } } ViewBag.cultureInfo = CultureInfo; ViewBag.DMSach = new SelectList(SachManager.getAllAlive() .Where(s => s.Soluong > 0).ToList(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); ViewBag.DMDaiLy = new SelectList(DaiLyManager.getAllAlive(), nameof(DaiLyManager.Properties.MaSoDaiLy), nameof(DaiLyManager.Properties.TenDaiLy), ""); setAlertMessage(); return View(_phieu); } // POST: PhieuNhap/Edit/5 [HttpPost] public ActionResult Edit(PhieuXuat model, FormCollection collection) { try { if (ModelState.IsValid) { if (PhieuXuatManager.edit(model)) { _currentPhieu = null; putSuccessMessage("Cập nhật thành công"); return RedirectToAction("Details", new { id = model.MaSoPhieuXuat }); } else { putErrorMessage("Cập nhật không thành công"); } } else { putModelStateFailErrors(ModelState); return RedirectToAction("Edit", new { id = model.MaSoPhieuXuat}); } //// TODO: Add update logic here //_phieu = model; //ViewBag.DMSach = new SelectList(SachManager.getAllAlive() // .Where(s => s.Soluong > 0).ToList(), // nameof(SachManager.Properties.MaSoSach), // nameof(SachManager.Properties.TenSach), ""); //ViewBag.DMDaiLy = new SelectList(DaiLyManager.getAllAlive(), // nameof(DaiLyManager.Properties.MaSoDaiLy), // nameof(DaiLyManager.Properties.TenDaiLy), ""); //return View(_phieu); return RedirectToAction("Edit", new { id = model.MaSoPhieuXuat }); } catch(Exception ex) { putErrorMessage(ex.Message); return RedirectToAction("Edit", new { id = model.MaSoPhieuXuat }); } } // GET: PhieuNhap/Delete/5 public ActionResult Delete(int? id) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } var model = PhieuXuatManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (model.TrangThai == 1) { putErrorMessage("Phiếu đã duyệt"); return RedirectToAction("Details", new { id = model.MaSoPhieuXuat }); } setAlertMessage(); return View(model); } // POST: PhieuNhap/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { if (PhieuXuatManager.delete((int)id)) { putSuccessMessage("Xóa thành công"); return RedirectToAction("All"); } else { putErrorMessage("Xóa không thành công"); return RedirectToAction("Delete", new { id }); } } catch(Exception ex) { putErrorMessage(ex.Message); return RedirectToAction("Delete", new { id }); } } //Duyệt phiếu public ActionResult Accept(int? id) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } var model = PhieuXuatManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (model.TrangThai == 1) { putErrorMessage("Phiếu đã duyệt"); return RedirectToAction("Details", new { id = id }); } var result = model.accept(); switch (result) { case PhieuXuat.AcceptStatus.Success: putSuccessMessage("Đã duyệt thành công"); return RedirectToAction("Details", new { id = id }); case PhieuXuat.AcceptStatus.Error: putErrorMessage("Sách tồn không đủ để duyệt! Phiếu xuất yêu cầu được hủy!"); return RedirectToAction("Edit", new { id }); case PhieuXuat.AcceptStatus.Limited: putErrorMessage("Tiền nợ đã vượt quá mức cho phép, vui lòng thanh toán trước khi đặt tiếp"); return RedirectToAction("Edit", new { id }); default: putErrorMessage("Duyệt không thành công"); return RedirectToAction("Edit", new { id }); } } #endregion #region JSON REQUEST public JsonResult GetProperties(string request) { List<string> results = new List<string>(); foreach (string pro in PhieuXuat.searchKeys()) { results.Add(request + pro); } return Json(results, JsonRequestBehavior.AllowGet); } #endregion #region REQUEST public ViewResult BlankEditorRow() { var chitiet = new ChiTietPhieuXuat(); var founded = false; foreach (Sach s in SachManager.getAllAlive().Where(s => s.Soluong > 0).ToList()) { chitiet.MaSoSach = s.MaSoSach; if (_phieu.ChiTiet.Contains(chitiet)) { continue; } founded = true; break; } if (!founded) { return null; } ViewBag.cultureInfo = CultureInfo; ViewBag.DMSach = new SelectList(SachManager.getAllAlive() .Where(s => s.Soluong > 0).ToList(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); chitiet.SoLuong = 1; chitiet.DonGia = chitiet.Sach.GiaBan; _phieu.addDetail(chitiet); return View("ChiTietEditorRow", chitiet); } public ViewResult DeleteDetailRow(int masosach) { _phieu.deleteDetail(masosach); return null; } public ViewResult ChangeDetailRow(int masosach, int? masosach_new, int? soluong) { foreach(ChiTietPhieuXuat ct in _phieu.ChiTiet) { if (ct.MaSoSach.Equals(masosach)) { if(masosach_new != null) { ct.MaSoSach = (int)masosach_new; ct.Sach = SachManager.find(ct.MaSoSach); ct.DonGia = ct.Sach.GiaBan; ct.SoLuong = 1; } if(soluong != null) { ct.SoLuong = (int)soluong; } break; } } return null; } public JsonResult isDetailExisted(string masosach) { var key = Int32.Parse(masosach); var chitiet = new ChiTietPhieuXuat(); chitiet.MaSoSach = key; if (_phieu.isDetailExisted(chitiet)) { return Json(true,JsonRequestBehavior.AllowGet); } else { return Json(false, JsonRequestBehavior.AllowGet); } } #endregion } }
using System; using Xunit; using Xunit.Abstractions; using ClearBank.DemoFramework.Services; using ClearBank.DemoFramework.Types; namespace ClearBank.DemoFramework.Tests.Services { public sealed class PaymentServiceShould : IDisposable { private DataStoreService _ds; private AccountService _as; private PaymentService _ps; private MakePaymentRequest _req; private MakePaymentResult _res; private ITestOutputHelper _output; public PaymentServiceShould(ITestOutputHelper output) { // Helper service objects _ds = new DataStoreService(); _as = new AccountService(_ds); _ps = new PaymentService(_as); // Helper objects _req = new MakePaymentRequest(); _output = output; _output.WriteLine("Creating payment service..."); } [Fact(Skip = "Only for prototype. This is not needed and safe to remove.") ] public void _StubTestCase() { _output.WriteLine("Running StubTestCase..."); _res = _ps.MakePayment(_req); Assert.False(_res.Success); } [Fact] public void MakePaymentAccountMissingRequestReturnsFalse() { _res = _ps.MakePayment(null); Assert.False(_res.Success); } [Fact] public void MakePaymentBacsRequestProcessReturnsTrue() { var reqPay = new MakePaymentRequest { PaymentScheme = PaymentScheme.Bacs }; _res = _ps.MakePayment(reqPay); Assert.True(_res.Success); } [Fact] public void MakePaymentChapsRequestProcessReturnsTrue() { var reqPay = new MakePaymentRequest { PaymentScheme = PaymentScheme.Chaps }; _res = _ps.MakePayment(reqPay); Assert.True(_res.Success); } [Fact] public void MakePaymentFasterPaymentRequestProcessReturnsTrue() { var reqPay = new MakePaymentRequest { PaymentScheme = PaymentScheme.FasterPayments }; _res = _ps.MakePayment(reqPay); Assert.True(_res.Success); } //[Fact] //public void MakePaymentSuccessUpdateAccountReturnsTrue() //{ // var reqPay = new MakePaymentRequest { PaymentScheme = PaymentScheme.Bacs }; // _res = _ps.MakePayment(reqPay); // Assert.True(_res.Success); //} public void Dispose() { _output.WriteLine("Disposing payment service!"); } } }
using System.Collections.Generic; using IrsMonkeyApi.Models.DB; namespace IrsMonkeyApi.Models.Dto { public class FormQuestionDto { public int? Ordering { get; set; } public string Label { get; set; } public string ControlId { get; set; } public string Image { get; set; } public bool? Required { get; set; } public string CssClass { get; set; } public string Icon { get; set; } public string HtmlControlId { get; set; } public string HtmlControlName { get; set; } public List<FormQuestionAnswerDto> Answers { get; set; } public int FormQuestionId { get; set; } public int FormId { get; set; } public int? WizardStepId { get; set; } public string Function { get; set; } public int? ControlType { get; set; } } }
using System; using System.Collections.Generic; using Uintra.Core.Member.Models; namespace Uintra.Features.UserList.Models { public class MembersRowsViewModel { public IEnumerable<ProfileColumnModel> SelectedColumns { get; set; } public IEnumerable<MemberModel> Members { get; set; } public bool IsLastRequest { get; set; } public MemberViewModel CurrentMember { get; set; } public bool IsCurrentMemberGroupAdmin { get; set; } public Guid? GroupId { get; set; } public bool IsInvite { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.ApplicationModel.Core; using Windows.Storage; using Windows.System.Threading; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace GUI.Models { /// <summary> /// This class operates in background and manages the IRP fetching operations. /// Upon receiving new IRPs it'll push them to the IrpRepository. /// </summary> public class IrpDumper { public const double IrpDumperDefaultProbeValue = 1.0; // seconds public const string IrpDumperTaskName = "IrpDumperBackgroundTask"; public const string IrpDumperPollDelayKey = "BackgroundTaskPollDelay"; private ApplicationTrigger _trigger = null; private BackgroundTaskRegistration _task; IBackgroundTaskInstance _taskInstance = null; BackgroundTaskDeferral _deferral = null; ThreadPoolTimer _periodicTimer = null; BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort; volatile bool _cancelRequested = false; string _cancelReasonExtra = ""; public IrpDumper() { ResetBackgroundTask(); } private void ResetBackgroundTask() { // unregister in case the app wasn't shut down properly UnregisterBackgroundTask(); _trigger = new ApplicationTrigger(); var requestTask = BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = IrpDumperTaskName; builder.SetTrigger(_trigger); _task = builder.Register(); ApplicationData.Current.LocalSettings.Values.Remove(IrpDumperTaskName); ApplicationData.Current.LocalSettings.Values.Remove(IrpDumperPollDelayKey); } public async void Trigger() => await _trigger.RequestAsync(); public void SetInstance(IBackgroundTaskInstance taskInstance) { _taskInstance = taskInstance; _deferral = taskInstance.GetDeferral(); _taskInstance.Canceled += OnCanceled; } private bool _enabled = false; public bool Enabled { get => _enabled; set { bool success = false; if (value) success = StartFetcher(); else success = StopFetcher(); if (success) _enabled = value; } } private bool StartFetcher() { Debug.WriteLine($"Starting in-process background instance '{_task.Name}'..."); var delay = (double) (ApplicationData.Current.LocalSettings.Values[IrpDumperPollDelayKey] ?? IrpDumperDefaultProbeValue); _cancelRequested = false; _cancelReasonExtra = ""; _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer( new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(delay) ); return true; } private bool StopFetcher() { Debug.WriteLine($"Stopping in-process background instance '{_task.Name}'..."); _periodicTimer.Cancel(); _cancelRequested = true; _cancelReasonExtra = "UserRequest"; return true; } private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { _cancelRequested = true; _cancelReason = reason; Debug.WriteLine($"Canceled background instance '{sender.Task.Name}'"); _deferral.Complete(); } private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) { Debug.WriteLine($"OnProgress('{task.Name}')"); } private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) { Debug.WriteLine($"OnCompleted('{task.Name}')"); } // // Periodic callback for the task: this is where we actually do the job of fetching new IRPs // private async void PeriodicTimerCallback(ThreadPoolTimer timer) { // is there a pending cancellation request if (_cancelRequested) { _periodicTimer.Cancel(); var msg = $"Cancelling background task {_task.Name }, reason: {_cancelReason.ToString()}"; if (_cancelReasonExtra.Length > 0) msg += _cancelReasonExtra; Debug.WriteLine(msg); _deferral.Complete(); return; } try { // // collect the irps from the broker // List<Irp> NewIrps = new List<Irp>(); var NbIrps = await FetchAllIrps(NewIrps); _taskInstance.Progress += (uint)NewIrps.Count; if(NewIrps.Count > 0) { Debug.WriteLine($"Received {NewIrps.Count:d} new irps"); // // push them to the db // foreach (var irp in NewIrps) { await App.Irps.Insert(irp); } App.ViewModel.UpdateUi(); } } catch (Exception e) { _cancelRequested = true; _cancelReason = BackgroundTaskCancellationReason.ConditionLoss; _cancelReasonExtra = e.Message; StopFetcher(); } } // // Fetch new IRPs // private async Task<List<Irp>> FetchIrps() { var msg = await App.BrokerSession.GetInterceptedIrps(); if (msg.header.is_success) return msg.body.intercepted_irps.irps; throw new Exception($"GetInterceptedIrps() request returned FALSE, GLE=0x{msg.header.gle}"); } // // Fetch all IRPs from Broker queue until it's empty // private async Task<uint> FetchAllIrps(List<Irp> Irps) { // don't allow more that number of items per request uint ForceFlushLimit = 512; uint Count = 0; while(Count < ForceFlushLimit) { var irps = await FetchIrps(); if (irps.Count == 0) break; foreach (var irp in irps) Irps.Add(irp); Count += (uint)irps.Count; } return Count; } // // Unregister the background task // private static bool UnregisterBackgroundTask() { foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == IrpDumperTaskName) { cur.Value.Unregister(true); return true; } } return false; } } }
using SimpleRESTChat.DAL.Context; using SimpleRESTChat.DAL.Repository.Interfaces; using SimpleRESTChat.Entities; namespace SimpleRESTChat.DAL.Repository { public class UserRepository : RepositoryBase<User>, IUserRepository { public UserRepository(SimpleRestChatDbContext dbContext) : base(dbContext) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PasswordCreator22 { public abstract class LetterFactory //AllLetterとNonMarkLetterどちらを使うか選ぶためのもの { public abstract Letter Create(Random random, int i); //抽象メソッドにするためのなので処理は書かない } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Bunq.Sdk.Context; using Bunq.Sdk.Model.Generated.Endpoint; using Bunq.Sdk.Model.Generated.Object; namespace BunqAggregation { public class Program { public static void Main(string[] args) { JObject config = Settings.LoadConfig(); if (!(File.Exists(@"bunq.conf"))) { string apiKey = Environment.GetEnvironmentVariable("BUNQ_API_KEY").ToString(); var apiContextSetup = ApiContext.Create(ApiEnvironmentType.PRODUCTION, apiKey, "BunqAggregation"); apiContextSetup.Save(); } var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Laoziwubo.Model.Common { public class GenericM { public string TableName { get; set; } public string Identity { get; set; } public Dictionary<string, object> Fields { get; set; } } }
using System; using System.Web; namespace Honeybadger.ErrorReporter { public class HoneybadgerErrorRegistrationModule : IHttpModule { public void Init(HttpApplication httpApplication) { httpApplication.AuthenticateRequest += AuthenticateRequest; httpApplication.Error += ContextError; } static void AuthenticateRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var honeybadgerErrorTestMessage = app.Request.QueryString["HoneybadgerErrorTest"]; if (string.IsNullOrEmpty(honeybadgerErrorTestMessage) == false) { var honeybadgerService = new HoneybadgerService(); string honeybadgerResponse; honeybadgerService.ReportException(new Exception(honeybadgerErrorTestMessage), out honeybadgerResponse); } } static void ContextError(object sender, EventArgs e) { var httpApplication = sender as HttpApplication; if (httpApplication != null) { var context = httpApplication.Context; if (context != null) { var exception = context.Server.GetLastError(); string honeybadgerResponse; var honeybadgerService = new HoneybadgerService(); honeybadgerService.ReportException(exception, out honeybadgerResponse); } } } public void Dispose() { } } }
using AbstractFactoryPattern.AbstractEntity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractFactoryPattern.ConcreteEntity { public class RegularScooter : IScooter { public string Name() { return "Regular Scooter"; } } }
namespace FirstMvcApp.Models { public class QuickSearchModel { public string Name { get; set; } public int Amount { get; set; } } }
using System; using System.IO; using Aspose.Slides; using Aspose.Slides.Export; namespace Profiling2.Infrastructure.Aspose.Loader { public class PresentationLoader : BaseAsposeLoader { protected Presentation Presentation { get; set; } public PresentationLoader(Stream stream, string password) : base(stream) { try { LoadOptions loadOptions = new LoadOptions(LoadFormat.Auto); loadOptions.Password = password; this.Presentation = new Presentation(stream, loadOptions); this.Presentation.ProtectionManager.RemoveEncryption(); try { if (this.Presentation.ProtectionManager.IsWriteProtected) this.Presentation.ProtectionManager.RemoveWriteProtection(); } catch (Exception e) { this.Exception = e; } this.IsPasswordCorrect = true; } catch (Exception e) { this.Exception = e; } } public override Stream GetUnprotectedStream(Stream destination) { if (this.IsPasswordCorrect && this.Presentation != null) { this.Presentation.Save(destination, SaveFormat.Pptx); return destination; } return null; } public override Stream GetHtml(Stream destination) { if (this.Presentation != null) { this.Presentation.Save(destination, SaveFormat.Html); return destination; } throw new LoadSourceException(this.Exception.Message, this.Exception.InnerException); } } }