text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace StudyManagement.Admin { public partial class ViewBookList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Page_PreRender(object sender, EventArgs e) { if (gvViewBook.SelectedRow==null) { dvViewBook.Visible = false; } else { dvViewBook.Visible = true; } } protected void dvViewBookList_ItemDeleted(object sender, DetailsViewDeletedEventArgs e) { gvViewBook.DataBind(); gvViewBook.SelectRow(-1); } protected void dvViewBookList_ItemInserted(object sender, DetailsViewInsertedEventArgs e) { gvViewBook.DataBind(); gvViewBook.SelectRow(-1); } protected void dvViewBookList_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e) { gvViewBook.DataBind(); gvViewBook.SelectRow(-1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class DefenceCubeLevel2 : DefenceCube { public override void CheckDestroy() { throw new System.NotImplementedException(); } }
using System.Collections.Generic; namespace Atc.Tests.XUnitTestData { internal static class TestMemberDataForExtensionsString { public static IEnumerable<object[]> IsCasingStyleValidData => new List<object[]> { // CamelCase new object[] { true, string.Empty, CasingStyle.CamelCase }, new object[] { true, "1", CasingStyle.CamelCase }, new object[] { true, "h", CasingStyle.CamelCase }, new object[] { false, "H", CasingStyle.CamelCase }, new object[] { true, "hallo", CasingStyle.CamelCase }, new object[] { false, "Hallo", CasingStyle.CamelCase }, new object[] { false, "HALLO", CasingStyle.CamelCase }, new object[] { false, "HAllo", CasingStyle.CamelCase }, new object[] { false, "haLLO", CasingStyle.CamelCase }, new object[] { false, "HaLlo", CasingStyle.CamelCase }, new object[] { false, "Hallo world", CasingStyle.CamelCase }, new object[] { false, "Hallo World", CasingStyle.CamelCase }, new object[] { false, "hallo world", CasingStyle.CamelCase }, new object[] { false, "hallo-world", CasingStyle.CamelCase }, new object[] { false, "hallo-World", CasingStyle.CamelCase }, new object[] { false, "hallo World", CasingStyle.CamelCase }, new object[] { false, "HalloWorld", CasingStyle.CamelCase }, new object[] { true, "halloWorld", CasingStyle.CamelCase }, new object[] { false, "hallo_world", CasingStyle.CamelCase }, new object[] { false, "hallo_World", CasingStyle.CamelCase }, // KebabCase new object[] { true, string.Empty, CasingStyle.KebabCase }, new object[] { true, "1", CasingStyle.KebabCase }, new object[] { true, "h", CasingStyle.KebabCase }, new object[] { false, "H", CasingStyle.KebabCase }, new object[] { true, "hallo", CasingStyle.KebabCase }, new object[] { false, "Hallo", CasingStyle.KebabCase }, new object[] { false, "HALLO", CasingStyle.KebabCase }, new object[] { false, "HAllo", CasingStyle.KebabCase }, new object[] { false, "haLLO", CasingStyle.KebabCase }, new object[] { false, "HaLlo", CasingStyle.KebabCase }, new object[] { false, "Hallo world", CasingStyle.KebabCase }, new object[] { false, "Hallo World", CasingStyle.KebabCase }, new object[] { false, "hallo world", CasingStyle.KebabCase }, new object[] { true, "hallo-world", CasingStyle.KebabCase }, new object[] { false, "hallo-World", CasingStyle.KebabCase }, new object[] { false, "hallo World", CasingStyle.KebabCase }, new object[] { false, "HalloWorld", CasingStyle.KebabCase }, new object[] { false, "halloWorld", CasingStyle.KebabCase }, new object[] { false, "hallo_world", CasingStyle.KebabCase }, new object[] { false, "hallo_World", CasingStyle.KebabCase }, // PascalCase new object[] { true, string.Empty, CasingStyle.PascalCase }, new object[] { true, "1", CasingStyle.PascalCase }, new object[] { false, "h", CasingStyle.PascalCase }, new object[] { true, "H", CasingStyle.PascalCase }, new object[] { false, "hallo", CasingStyle.PascalCase }, new object[] { true, "Hallo", CasingStyle.PascalCase }, new object[] { false, "HALLO", CasingStyle.PascalCase }, new object[] { false, "HAllo", CasingStyle.PascalCase }, new object[] { false, "haLLO", CasingStyle.PascalCase }, new object[] { true, "HaLlo", CasingStyle.PascalCase }, new object[] { false, "Hallo world", CasingStyle.PascalCase }, new object[] { false, "Hallo World", CasingStyle.PascalCase }, new object[] { false, "hallo world", CasingStyle.PascalCase }, new object[] { false, "hallo-world", CasingStyle.PascalCase }, new object[] { false, "hallo-World", CasingStyle.PascalCase }, new object[] { false, "hallo World", CasingStyle.PascalCase }, new object[] { true, "HalloWorld", CasingStyle.PascalCase }, new object[] { false, "halloWorld", CasingStyle.PascalCase }, new object[] { false, "hallo_world", CasingStyle.PascalCase }, new object[] { false, "hallo_World", CasingStyle.PascalCase }, // SnakeCase new object[] { true, string.Empty, CasingStyle.SnakeCase }, new object[] { true, "1", CasingStyle.SnakeCase }, new object[] { true, "h", CasingStyle.SnakeCase }, new object[] { false, "H", CasingStyle.SnakeCase }, new object[] { true, "hallo", CasingStyle.SnakeCase }, new object[] { false, "Hallo", CasingStyle.SnakeCase }, new object[] { false, "HALLO", CasingStyle.SnakeCase }, new object[] { false, "HAllo", CasingStyle.SnakeCase }, new object[] { false, "haLLO", CasingStyle.SnakeCase }, new object[] { false, "HaLlo", CasingStyle.SnakeCase }, new object[] { false, "Hallo world", CasingStyle.SnakeCase }, new object[] { false, "Hallo World", CasingStyle.SnakeCase }, new object[] { false, "hallo world", CasingStyle.SnakeCase }, new object[] { false, "hallo-world", CasingStyle.SnakeCase }, new object[] { false, "hallo-World", CasingStyle.SnakeCase }, new object[] { false, "hallo World", CasingStyle.SnakeCase }, new object[] { false, "HalloWorld", CasingStyle.SnakeCase }, new object[] { false, "halloWorld", CasingStyle.SnakeCase }, new object[] { true, "hallo_world", CasingStyle.SnakeCase }, new object[] { false, "hallo_World", CasingStyle.SnakeCase }, }; } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MusicAPI.Models { public class MusicBrainzModel : IMusicBrainzModel { public string Name { get; set; } [JsonProperty("release-groups")] public IEnumerable<MusicBrainzAlbum> Albums { get; set; } public IEnumerable<MusicBrainzWikiDataInfo> Relations { get; set; } public class MusicBrainzWikiDataInfo { public string Type { get; set; } [JsonProperty("type-id")] public string TypeId { get; set; } public Dictionary<string, string> Url { get; set; } public string Title { get; set; } } public class MusicBrainzAlbum { public string Id { get; set; } public string Title { get; set; } } public string GetWikiDataQNumber() { /*Här letas strängen fram bland modellens relationer och trimmas, eftersom MusicBrainz ger hela URLen och inte bara Q-numret vi är ute efter.*/ var wikidataRelation = Relations.Where(i => i.Type == "wikidata").FirstOrDefault(); string wikidataURL = wikidataRelation.Url["resource"]; int indexOfQ = wikidataURL.IndexOf('Q'); return wikidataURL.Substring(indexOfQ, wikidataURL.Length - indexOfQ); } public string GetWikiPediaTitle() { /*Metoden letar efter en wikipediatitle i modellens relationer vilket enligt specialfallet i uppgiftsbeskrivningen förekommer i enstaka fall*/ var wikiPedia = Relations.Where(i => i.Type == "wikipedia").FirstOrDefault(); if (wikiPedia != null) return wikiPedia.Title; else return null; } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; public class MyAudio : MonoBehaviour { private static GameObject _audio; private static AudioSource _audio_Source; private static readonly Dictionary<string, AudioClip> s_AudioClips_Dictionary = new Dictionary<string, AudioClip>(); void Awake() { //预加载所有音频 LoadAllAudio(); //保持本类对象只有一个 KeepOnlyOne(); } void KeepOnlyOne() { if (_audio == null) { _audio = gameObject; //游戏中唯一的声源组件,用来播放背景音乐 _audio_Source = _audio.GetComponent<AudioSource>(); DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } private void LoadAllAudio() { if(!StartGame.First_In) return; AudioClip[] temp = Resources.LoadAll<AudioClip>("Sound"); foreach (AudioClip clip in temp) { s_AudioClips_Dictionary[clip.name] = clip; } } public static void ChangeBGM() { try { if (SceneManager.GetActiveScene().name.Equals("UI")) { _audio_Source.clip = s_AudioClips_Dictionary[StaticParameter.s_UI_BGM]; } else { _audio_Source.clip = s_AudioClips_Dictionary[StaticParameter.s_Stage_BGM]; } _audio_Source.Play(); } catch (Exception) { Debug.Log("无法播放音频"); } } //音频播放方法 public static void PlayAudio(string name, bool loop, float volume) { try { AudioClip BGM = s_AudioClips_Dictionary[name]; _audio_Source.PlayOneShot(BGM, volume); } catch (Exception) { Debug.Log(name+"音频错误"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.U2D; public class ChunksTest : MonoBehaviour { SpriteShapeController spriteshape; private void Start() { spriteshape = GetComponentInChildren<SpriteShapeController>(); Debug.Log(spriteshape.cornerAngleThreshold); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using GodMorgon.Models; using GodMorgon.StateMachine; namespace GodMorgon.DeckBuilding.Draft { public class DraftPhase : MonoBehaviour { //Deck use to draw card for the draft [SerializeField] private DeckContent draftDeck = null; /** * link for the three card to choose during the draft */ [SerializeField] private List<CardDisplay> cardsOnDraft = null; /** * Number of draft to execute */ [SerializeField] private int nbDraftLeft = 5; /** * text indiquant le nombre de séquence de draft restante * ----Temporaire------ */ public Text nbDraftLeftText = null; /** * Start a draft sequence * choose 5 card randomly from draft deck and display them on screen */ public void StartDraftSequence() { if (nbDraftLeft > 0) { int rdmCardNb; for (int i = 0; i < cardsOnDraft.Count; i++) { rdmCardNb = Random.Range(0, draftDeck.cards.Count); cardsOnDraft[i].UpdateCard(draftDeck.cards[rdmCardNb]); } } //after pick all the card, we shuffle the deck and start the load of the game scene else { GameEngine.Instance.ShufleCompleteDeck(); GameEngine.Instance.SetState(StateMachine.StateMachine.STATE.LOAD); } //Debug.Log("Phase de draft Complete, Lancement de la scene de jeu avec le deck complet"); } /** * button function * Add the card choose durring the draft to the deck player. * And reload the draft sequence */ public void ChooseCard(CardDisplay cardChoosed) { DeckBuildingManager.Instance.AddCardToPlayerDeck(cardChoosed.card); nbDraftLeft -= 1; nbDraftLeftText.text = nbDraftLeft.ToString(); StartDraftSequence(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SharedLib { public partial class Department { public Department() { Employees = new HashSet<Employee>(); } public int DeptNo { get; set; } public string DeptName { get; set; } public string Location { get; set; } public virtual ICollection<Employee> Employees { get; set; } } public partial class Employee { [Required(ErrorMessage = "EmpNo is Must")] public int EmpNo { get; set; } [Required(ErrorMessage = "EmpName is Must")] public string EmpName { get; set; } [Required(ErrorMessage = "Designation is Must")] public string Designation { get; set; } [Required(ErrorMessage = "Salary is Must")] public int Salary { get; set; } [Required(ErrorMessage = "DeptNo is Must")] public int DeptNo { get; set; } public virtual Department DeptNoNavigation { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CourseVoiliers.Classes { public class Historique { } }
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using Simple.Wpf.Composition.Infrastructure; namespace Simple.Wpf.Composition.Workspaces { public sealed class Workspace : INotifyPropertyChanged { private readonly BaseController _controller; private readonly Action _dispose; private string _title; public Workspace(BaseController controller, Uri resources, Action dispose) { Resources = resources; _controller = controller; _dispose = dispose; } public BaseViewModel Content => _controller.ViewModel; public Type Type => _controller.Type; public Uri Resources { get; } public string Title { get => _title; set { _title = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; public void Dispose() { if (_dispose != null) { _controller.Dispose(); _dispose(); } } private void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Linq; using Terminal.Gui; using Xunit; // Alias Console to MockConsole so we don't accidentally use Console using Console = Terminal.Gui.FakeConsole; namespace Terminal.Gui.DriverTests { public class AttributeTests { [Fact] public void Constuctors_Constuct () { var driver = new FakeDriver (); Application.Init (driver); driver.Init (() => { }); // Test parameterless constructor var attr = new Attribute (); Assert.Equal (default (int), attr.Value); Assert.Equal (default (Color), attr.Foreground); Assert.Equal (default (Color), attr.Background); // Test value, foreground, background var value = 42; var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; attr = new Attribute (value, fg, bg); Assert.Equal (value, attr.Value); Assert.Equal (fg, attr.Foreground); Assert.Equal (bg, attr.Background); // value, foreground, background attr = new Attribute (fg, bg); Assert.Equal (fg, attr.Foreground); Assert.Equal (bg, attr.Background); attr = new Attribute (fg); Assert.Equal (fg, attr.Foreground); Assert.Equal (fg, attr.Background); attr = new Attribute (bg); Assert.Equal (bg, attr.Foreground); Assert.Equal (bg, attr.Background); driver.End (); Application.Shutdown (); } [Fact] public void Implicit_Assign () { var driver = new FakeDriver (); Application.Init (driver); driver.Init (() => { }); var attr = new Attribute (); var value = 42; var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; // Test conversion to int attr = new Attribute (value, fg, bg); int value_implicit = (int)attr.Value; Assert.Equal (value, value_implicit); // Test conversion from int attr = value; Assert.Equal (value, attr.Value); driver.End (); Application.Shutdown (); } [Fact] public void Implicit_Assign_NoDriver () { var attr = new Attribute (); var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; // Test conversion to int attr = new Attribute (fg, bg); int value_implicit = (int)attr.Value; Assert.False (attr.Initialized); Assert.Equal (-1, value_implicit); Assert.False (attr.Initialized); // Test conversion from int attr = -1; Assert.Equal (-1, attr.Value); Assert.False (attr.Initialized); } [Fact] public void Make_SetsNotInitialized_NoDriver () { var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; var a = Attribute.Make (fg, bg); Assert.False (a.Initialized); } [Fact] public void Make_Creates () { var driver = new FakeDriver (); Application.Init (driver); driver.Init (() => { }); var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; var attr = Attribute.Make (fg, bg); Assert.True (attr.Initialized); Assert.Equal (fg, attr.Foreground); Assert.Equal (bg, attr.Background); driver.End (); Application.Shutdown (); } [Fact] public void Make_Creates_NoDriver () { var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; var attr = Attribute.Make (fg, bg); Assert.False (attr.Initialized); Assert.Equal (fg, attr.Foreground); Assert.Equal (bg, attr.Background); } [Fact] public void Get_Asserts_NoDriver () { Assert.Throws<InvalidOperationException> (() => Attribute.Get ()); } [Fact] public void Get_Gets () { var driver = new FakeDriver (); Application.Init (driver); driver.Init (() => { }); var value = 42; var fg = new Color (); fg = Color.Red; var bg = new Color (); bg = Color.Blue; var attr = new Attribute (value, fg, bg); driver.SetAttribute (attr); var ret_attr = Attribute.Get (); Assert.Equal (value, ret_attr.Value); Assert.Equal (fg, ret_attr.Foreground); Assert.Equal (bg, ret_attr.Background); driver.End (); Application.Shutdown (); } [Fact] [AutoInitShutdown] public void GetColors_Based_On_Value () { var driver = Application.Driver; var attrValue = new Attribute (Color.Red, Color.Green).Value; driver.GetColors (attrValue, out Color fg, out Color bg); Assert.Equal (Color.Red, fg); Assert.Equal (Color.Green, bg); } [Fact] public void IsValid_Tests () { var attr = new Attribute (); Assert.True (attr.HasValidColors); attr = new Attribute (Color.Red, Color.Green); Assert.True (attr.HasValidColors); attr = new Attribute (Color.Red, (Color)(-1)); Assert.False (attr.HasValidColors); attr = new Attribute ((Color)(-1), Color.Green); Assert.False (attr.HasValidColors); attr = new Attribute ((Color)(-1), (Color)(-1)); Assert.False (attr.HasValidColors); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BusinessObjects; namespace DataAccess { class PostLikeDAO { private static PostLikeDAO instance = null; private static readonly object instanceLock = new object(); public static PostLikeDAO Instance { get { lock (instanceLock) { if (instance == null) { instance = new PostLikeDAO(); } return instance; } } } public PostLike GetPostLike(string username, int postId) { PostLike postLike = null; try { using var context = new PRN211_OnlyFunds_CopyContext(); postLike = context.PostLikes.SingleOrDefault(l => l.Username.Equals(username) && l.PostId == postId); } catch (Exception e) { Console.WriteLine(e); throw; } return postLike; } public void AddPostLike(PostLike like) { try { PostLike _like = GetPostLike(like.Username, like.PostId); if (_like == null) { using var context = new PRN211_OnlyFunds_CopyContext(); context.PostLikes.Add(like); context.SaveChanges(); } else { throw new Exception("Already Liked"); } } catch (Exception e) { Console.WriteLine(e); throw; } } public void DeleteLike(string username, int postId) { try { PostLike like = GetPostLike(username, postId); if (like != null) { using var context = new PRN211_OnlyFunds_CopyContext(); context.PostLikes.Remove(like); context.SaveChanges(); } } catch (Exception e) { Console.WriteLine(e); throw; } } public int CountPostLike(int postId) { try { using var context = new PRN211_OnlyFunds_CopyContext(); int count = context.PostLikes.Count(l => l.PostId == postId); return count; } catch (Exception e) { Console.WriteLine(e); throw; } } public PostLike CheckUserLike(string username, int postId) { try { using var context = new PRN211_OnlyFunds_CopyContext(); PostLike like = context.PostLikes.FirstOrDefault(l => l.Username.Equals(username) && l.PostId == postId); return like; } catch (Exception e) { Console.WriteLine(e); throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PhotographyEvent.Events { // Page for modification of user information: password, first name, last name, email address. public partial class AccountInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // When the page loads for the first time, shows user information stored in db BindData(); } } // Event when user tries to save altered data protected void btnSave_Click(object sender, EventArgs e) { // firstly, check email address validity. if (!Models.User.CheckEmail(txtEmail.Text.Trim(), User.Identity.Name)) { ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('Email addres you input is being used by other user. Please choose other email address.');", true); return; } // updates user information to the db string update = @"update Users set EmailAddress = @email, FirstName = @fName, LastName = @lName where UserId = @uid"; Dictionary<string, string> pList = new Dictionary<string, string>(); pList.Add("email", txtEmail.Text.Trim()); pList.Add("fName", txtFirstName.Text.Trim()); pList.Add("lName", txtLastName.Text.Trim()); pList.Add("uid", User.Identity.Name); // saves data and shows the result if (Libs.DbHandler.updateData(update, pList)) { ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('Saved successfully'); location.href='../Main.aspx';", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('Failed to save');", true); } } // Changes user's password protected void btnChngPass_Click(object sender, EventArgs e) { string update = @"update Users set password = @pword where UserId = @uid"; Dictionary<string, string> pList = new Dictionary<string, string>(); pList.Add("pword", txtPassword.Text); pList.Add("uid", User.Identity.Name); // updates password and shows result if (Libs.DbHandler.updateData(update, pList)) { ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('Changed successfully');", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('Failed to change password');", true); } } /// <summary> /// Retrieves and shows user information in text boxes /// </summary> private void BindData() { string select = @"Select Password, FirstName, LastName, EmailAddress From Users Where UserId = @uid and IsAdmin = 0"; Dictionary<string, string> pList = new Dictionary<string, string>(); pList.Add("uid", User.Identity.Name); using (System.Data.SqlClient.SqlDataReader reader = Libs.DbHandler.getResultAsDataReaderDicParam(select, pList)) { if (reader.Read()) { lblUserId.Text = User.Identity.Name; // User Id is fixed. txtPassword.Text = reader["Password"].ToString(); txtRetypePass.Text = reader["Password"].ToString(); txtEmail.Text = reader["EmailAddress"].ToString(); txtFirstName.Text = reader["FirstName"] == DBNull.Value ? string.Empty : reader["FirstName"].ToString(); txtLastName.Text = reader["LastName"] == DBNull.Value ? string.Empty : reader["LastName"].ToString(); } } } } }
namespace AGCompressedAir.Windows.Views { public sealed partial class ClientManageView { public ClientManageView() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using ArizaTakipYazılımSistemi.Model; namespace ArizaTakipYazılımSistemi.Controller { class YoneticiDB : DatabaseOperation { public YoneticiDB() { dataAdapter1.SelectCommand = SelectCommand1; SelectCommand1.Connection = connection; } public DataSet dataSet10 = new DataSet(); public DataTable datatable4 = new DataTable(); public DataTable datatable5 = new DataTable(); public DataTable datatable6 = new DataTable(); public DataTable datatable7 = new DataTable(); public DataTable atanmamisAriza() { datatable4.Clear(); dataAdapter1.SelectCommand.CommandText = "select tbl_ariza.ariza_id, tbl_ariza.baslik, tbl_ariza.konu, tbl_ariza.bildirim_saati, CONCAT(tbl_personel.adi, ' ', tbl_personel.soyadi) as 'adsoyad' from (tbl_ariza inner join tbl_personel on tbl_ariza.personel_Id = tbl_personel.personel_Id and tbl_personel.bolum_Id = " + Kullanici.personel.bolum_id + ") where atanma_saati is null"; dataAdapter1.Fill(datatable4); return datatable4; } public DataTable atanmisAriza() { datatable5.Clear(); dataAdapter1.SelectCommand.CommandText = "select tbl_ariza.ariza_id, tbl_ariza.baslik, tbl_ariza.konu, tbl_ariza.bildirim_saati,tbl_ariza.atanma_saati,tbl_ariza.tamamlanma_saati, CONCAT(tbl_personel.adi, ' ', tbl_personel.soyadi) as 'adsoyad' from(tbl_ariza inner join tbl_personel on tbl_ariza.personel_Id = tbl_personel.personel_Id and tbl_personel.bolum_Id = " + Kullanici.personel.bolum_id + ") where atanma_saati is not null "; dataAdapter1.Fill(datatable5); return datatable5; } public DataTable giderilmisAriza() { datatable6.Clear(); dataAdapter1.SelectCommand.CommandText = "select tbl_ariza.ariza_id, tbl_ariza.baslik, tbl_ariza.konu, tbl_ariza.mesaj, tbl_ariza.bildirim_saati,tbl_ariza.atanma_saati, tbl_ariza.tamamlanma_saati, CONCAT(tbl_personel.adi, ' ', tbl_personel.soyadi) as 'adsoyad' from(tbl_ariza inner join tbl_personel on tbl_ariza.personel_Id = tbl_personel.personel_Id and tbl_personel.bolum_Id = " + Kullanici.personel.bolum_id + ") where tamamlanma_saati is not null "; dataAdapter1.Fill(datatable6); return datatable6; } public void secilenPersonel(int id) { dataSet10.Clear(); open(); dataAdapter1.SelectCommand.CommandText = "Select * from tbl_personel where personel_Id = " + id + ""; dataAdapter1.Fill(dataSet10); close(); Personel personel = new Personel(); personel.personel_id = Convert.ToInt32(dataSet10.Tables[0].Rows[0][0]); personel.adi = dataSet10.Tables[0].Rows[0][1].ToString(); personel.soyadi = dataSet10.Tables[0].Rows[0][2].ToString(); personel.bolum_id = Convert.ToInt32(dataSet10.Tables[0].Rows[0][3]); personel.unvan_id = Convert.ToInt32(dataSet10.Tables[0].Rows[0][4]); personel.yetki = Convert.ToBoolean(dataSet10.Tables[0].Rows[0][5]); personel.username = dataSet10.Tables[0].Rows[0][6].ToString(); personel.password = dataSet10.Tables[0].Rows[0][7].ToString(); Degiskenler.Admin.personel = personel; } public DataTable bolum_kullanicilar() { datatable7.Clear(); open(); dataAdapter1.SelectCommand.CommandText = "select * from ((tbl_personel inner join tbl_bolum on tbl_personel.bolum_Id = tbl_bolum.bolum_Id) inner join tbl_unvan on tbl_personel.unvan_Id = tbl_unvan.unvan_Id) where tbl_personel.bolum_Id = "+ Kullanici.personel.bolum_id+""; dataAdapter1.Fill(datatable7); close(); return datatable7; } } }
using Alabo.Randoms; using Alabo.Web.Mvc.Attributes; using System; using System.Security.Cryptography; using System.Text; namespace Alabo.Helpers { public static class PasswordHelper { /// <summary> /// 获取指定数据的PBKDF2校验值 /// </summary> /// <param name="data"></param> /// <param name="slat">参与校验的随机数据,长度需要等于8</param> /// <param name="iterations">计算循环次数,越长强度越高但越耗费性能</param> /// <param name="hashLength">校验值长度</param> public static byte[] Pbkdf2Sum( byte[] data, byte[] slat, int iterations = 1024, int hashLength = 32) { var hash = new Rfc2898DeriveBytes(data, slat, iterations).GetBytes(hashLength); return hash; } /// <summary> /// 获取指定数据的Md5校验值 public static byte[] Md5Sum(byte[] data) { return MD5.Create().ComputeHash(data); } /// <summary> /// 获取指定数据的Sha1校验值 public static byte[] Sha1Sum(byte[] data) { return SHA1.Create().ComputeHash(data); } } /// <summary> /// 密码信息 /// </summary> public class PasswordInfo { /// <summary> /// 密码类型 /// </summary> public PasswordHashType Type { get; set; } = PasswordHashType.Pbkdf2; /// <summary> /// 参与校验的随机数据(base64) /// </summary> public string Slat { get; set; } /// <summary> /// 密码校验值(base64) /// </summary> public string Hash { get; set; } /// <summary> /// 检查密码,返回密码是否正确 /// </summary> /// <param name="password"></param> public bool Check(string password) { if (string.IsNullOrEmpty(password)) { return false; } var slat = Slat == null ? null : System.Convert.FromBase64String(Slat); var info = FromPassword(password, slat, Type); return Hash == info.Hash; } /// <summary> /// 从密码创建密码信息 /// </summary> /// <param name="password">密码</param> /// <param name="slat">参与校验的随机数据,不指定时使用默认值</param> /// <param name="type">密码类型</param> public static PasswordInfo FromPassword(string password, byte[] slat = null, PasswordHashType type = PasswordHashType.Pbkdf2) { if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password can't be empty"); } var info = new PasswordInfo { Type = type }; var passwordBytes = Encoding.UTF8.GetBytes(password); if (type == PasswordHashType.Pbkdf2) { slat = slat ?? RandomHelper.SystemRandomBytes(); info.Slat = System.Convert.ToBase64String(slat); info.Hash = System.Convert.ToBase64String(PasswordHelper.Pbkdf2Sum(passwordBytes, slat)); } else if (type == PasswordHashType.Md5) { info.Hash = System.Convert.ToBase64String(PasswordHelper.Md5Sum(passwordBytes)); } else if (type == PasswordHashType.Sha1) { info.Hash = System.Convert.ToBase64String(PasswordHelper.Sha1Sum(passwordBytes)); } return info; } } /// <summary> /// 密码类型 /// </summary> [ClassProperty(Name = "密码类型")] public enum PasswordHashType { /// <summary> /// 默认,等于PBKDF2 /// </summary> Default = Pbkdf2, /// <summary> /// PBKDF2 /// </summary> Pbkdf2 = 0, /// <summary> /// Md5 /// </summary> Md5 = 1, /// <summary> /// Sha1 /// </summary> Sha1 = 2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MerchantRPG.Simulation { [Flags()] public enum StatsFilter { Damage = 1 << 0, //Any damage type Accuracy = 1 << 1, CriticalRate = 1 << 2, Defense = 1 << 3, MagicDefense = 1 << 4, Hp = 1 << 5, Offensive = Damage | Accuracy | CriticalRate, Defenses = Defense | MagicDefense, All = Offensive | Defenses | Hp, MagicAttack = 1 << 6, } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class TimeManager : MonoBehaviour { public static float time; // The player's tim. public PlayerHealth playerHealth;// Reference to the player's health. Text timer; // Reference to the Text component. void Awake () { timer = GetComponent <Text> (); time = 0f; } void Update () { if(ScoreManager.score > 0 && playerHealth.currentHealth > 0){ time += Time.deltaTime; timer.text = "Time: " + (int)time; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public enum GraphicType { @Mesh, @Sprite } public class GraphicChanger : MonoBehaviour { Dictionary<GraphicType, Transform> GraphicObjects = new Dictionary<GraphicType, Transform>(); public static GraphicType GraphicType = GraphicType.Mesh; Texture2D texture; Sprite sprite; // Use this for initialization void Start () { GameManager.ChangeGraphicEvent += ChangeGraphicType; Transform[] children = GetComponentsInChildren<Transform>(true); GraphicObjects = new Dictionary<GraphicType, Transform>(); for (int i = 0; i < children.Length; i++) { if (children[i].name.ToLower().Contains(GraphicType.Mesh.ToString().ToLower())) { if (!GraphicObjects.ContainsKey(GraphicType.Mesh)) { GraphicObjects.Add(GraphicType.Mesh, children[i]); } else { GraphicObjects[GraphicType.Mesh] = children[i]; } texture = (Texture2D)children[i].GetComponent<Renderer>().material.mainTexture; if(!texture) { texture = new Texture2D(10, 10); } sprite = Sprite.Create( texture, new Rect(0, 0, texture.width ,texture.height), new Vector2(0.5f, 0.5f) ); } if (children[i].name.ToLower().Contains(GraphicType.Sprite.ToString().ToLower())) { if (!GraphicObjects.ContainsKey(GraphicType.Sprite)) { GraphicObjects.Add(GraphicType.Sprite, children[i]); } else { GraphicObjects[GraphicType.Sprite] = children[i]; } } } GraphicObjects[GraphicType.Sprite].GetComponent<SpriteRenderer>().sprite = sprite; ChangeGraphicType(GameManager.GraphicType); } void ChangeGraphicType(GraphicType type) { foreach (var item in GraphicObjects) { item.Value.transform.gameObject.SetActive(item.Key.ToString()==type.ToString()); } } void OnDestroy() { GameManager.ChangeGraphicEvent -= ChangeGraphicType; } }
using HRMoneyAPI.Models; using HRMoneyAPI.Services; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using MongoDB.Driver; using MongoDB; using HRMoneyAPI.Criptografia; namespace HRMoneyAPI.Controllers { [Route("api/[controller]")] [ApiController] public class UserController : Controller { private readonly UserService _userService; public UserController(UserService userService) { _userService = userService; } [HttpGet("{email}:{senha}", Name = "Buscar Usuario")] public ActionResult<User> Get(string email, string senha) { var user = _userService.Login(email, senha); if (user == null) return NotFound(); return user; } [HttpPost ("{email}:{senha}", Name = "Criar Conta")] public string Create(string email, string senha) { string retorno = _userService.Create(email, senha); return retorno; } [HttpPut("{token}:{senha}", Name = "Mudar Senha")] public ActionResult<User> Update(string token, string senha) { var user = _userService.GetUserByToken(token); if (user == null) return NotFound(); string senhaCriptografada = Criptografar.CriptografarSenha(senha); user.Senha = senhaCriptografada; _userService.Update(token, user); return user; } [HttpPut("{token}", Name = "Mudar Config")] public ActionResult<User> Update(string token, ConfigAlterar config) { if (config == null) return NotFound(); User result = _userService.UpdateConfig(token, config); if (result == null) return NotFound(); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization; namespace Starbucks { [Serializable] [DataContract] public class Store { [DataMember(IsRequired = true)] public int storeID { get; set; } [DataMember] public string storeNumber { get; set; } [DataMember] public string storeName { get; set; } [DataMember] public string storeAddress { get; set; } [DataMember] public string storeCity { get; set; } [DataMember] public string storeZip { get; set; } [DataMember] public string storeState { get; set; } [DataMember] public string storePhone { get; set; } [DataMember] public string storeManagerName { get; set; } [DataMember] public string storeEmailAddress { get; set; } [DataMember] public string storeOwnershipType { get; set; } [DataMember(IsRequired=true)] public bool PODRequired { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EmberMemory.Components.Collector { public interface ICollectorManager { public ValueTask StartCollectors(CancellationToken token = default); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; namespace electronicstore { public partial class AddCategory : Form { db d = new db(); public AddCategory() { InitializeComponent(); FormBorderStyle = FormBorderStyle.None; } private void AddCategory_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'furnitureshopDataSet.tbl_category' table. You can move, or remove it, as needed. this.tbl_categoryTableAdapter.Fill(this.furnitureshopDataSet.tbl_category); } private void button1_Click(object sender, EventArgs e) { bool isNameValid = Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"); if(textBox1.Text=="") { MessageBox.Show("Fields are Mandatory"); } else if(d.checkAvailablity("tbl_category","categoryname", textBox1.Text)) { MessageBox.Show("Category already exist ..."); } else if (!isNameValid) { MessageBox.Show("Invalid Category Name"); } else { d.insertData("insert into tbl_category values(" + d.latestId("tbl_category", "cat_id") + ",'" + textBox1.Text + "')"); AddCategory_Load(sender, e); MessageBox.Show("Category added successfully !!"); } } private void dataGridView1_UserDeletedRow(object sender, DataGridViewRowEventArgs e) { this.tbl_categoryTableAdapter.Update(this.furnitureshopDataSet.tbl_category); } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { this.tbl_categoryTableAdapter.Update(this.furnitureshopDataSet.tbl_category); } private void label2_Click(object sender, EventArgs e) { this.Close(); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { this.tbl_categoryTableAdapter.Update(this.furnitureshopDataSet.tbl_category); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Projet2Cpi { public class Notif { public string Type; public DateTime time; } }
using EducaClass.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Threading.Tasks; namespace EducaClass.Services { public class SQLService { public int EjecutarTransaccion(Contexto contexto, string script, Array parametros = null) { using (DbCommand comando = contexto.Database .GetDbConnection() .CreateCommand()) { comando.CommandText = script; comando.CommandType = CommandType.Text; if (parametros != null) { comando.Parameters.AddRange(parametros); } contexto.Database.OpenConnection(); return comando.ExecuteNonQuery(); } } public List<Tipo> EjecutarSQL<Tipo>(Contexto contexto, string sql, Func<DbDataReader, Tipo> leerRegistro, Array parametros = null) { using (DbCommand comando = contexto.Database .GetDbConnection() .CreateCommand()) { comando.CommandText = sql; comando.CommandType = CommandType.Text; if (parametros != null) { comando.Parameters.AddRange(parametros); } contexto.Database.OpenConnection(); using (DbDataReader dr = comando.ExecuteReader()) { List<Tipo> resultado = new List<Tipo>(); while (dr.Read()) { resultado.Add(leerRegistro(dr)); } return resultado; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using KartLib.Views; using KartObjects; using KartLib; namespace KartSystem { /// <summary> /// Представление роли кассира. Отображает список всех возможных ролей кассиров (вверху), /// а при выборе роли - перечень доступных ей действий (внизу). /// </summary> public partial class CashiersRoleView : KartUserControl,ICashierRoles { #region Поля /// <summary> /// Редактор роли кассира. Вызывается при создании новой роли и при изменении св-в уже существующей. /// </summary> CashierRoleEditor _cre; #endregion #region Свойства public IList<CashierRole> CashierRoles { get; set; } public override bool RecordSelected { get { return cashierRoleBindingSource.Current != null; } } public override bool IsEditable { get { return true; } } public override bool IsInsertable { get { return true; } } public override bool UseSubmenu { get { return false; } } public override bool IsDeletable { get { return true; } } public override bool IsPrintable { get { return false; } } #endregion #region Методы public override void RefreshView() { base.RefreshView(); cashierRoleBindingSource.DataSource = CashierRoles; if (CashierRoles == null || CashierRoles.Count == 0) pOSActionBindingSource.DataSource = null; } public override void EditorAction(bool addMode) { if (addMode) { CashierRole newUser = new CashierRole(); newUser.Name = string.Empty; Saver.SaveToDb<CashierRole>(newUser); _cre = new CashierRoleEditor(newUser); if (_cre.ShowDialog() == DialogResult.OK) { CashierRoles.Add(newUser); RefreshView(); ActiveEntity = newUser; } else { CashierRoles.Remove(newUser); Saver.DeleteFromDb<CashierRole>(newUser); } gridControl1.RefreshDataSource(); gridControl2.RefreshDataSource(); } else { if (cashierRoleBindingSource.Current == null) return; _cre = new CashierRoleEditor(cashierRoleBindingSource.Current as CashierRole); if (_cre.ShowDialog() == DialogResult.OK) { RefreshView(); gridControl1.RefreshDataSource(); gridControl2.RefreshDataSource(); UpdateCurrItem(); }; } } private void UpdateCurrItem() { CashierRole newVariable = cashierRoleBindingSource.Current as CashierRole; pOSActionBindingSource.DataSource = newVariable.RoleRights = Loader.DbLoad<CashierRolePOSAction>("IdRole=" + newVariable.Id) ?? new List<CashierRolePOSAction>(); } public override void DeleteItem(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { CashierRole gk = cashierRoleBindingSource.Current as CashierRole; if (gk != null) { if (MessageBox.Show(this, "Вы уверены что хотите удалить роль кассира " + gk.Name, "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { Saver.DeleteFromDb<CashierRole>(gk); foreach (CashierRolePOSAction currPOSAction in gk.RoleRights) { Saver.DeleteFromDb<CashierRolePOSAction>(currPOSAction); } CashierRoles.Remove(gk); gridControl1.RefreshDataSource(); gridControl2.RefreshDataSource(); } } } #endregion #region Конструкторы public CashiersRoleView() { InitializeComponent(); ViewObjectType = ObjectType.CasierRole; Preseneter = new CashiersPresenter(this); MainGridView = gridView1; } #endregion #region Инициализация public override void InitView() { base.InitView(); cashierRoleBindingSource.DataSource = CashierRoles; Dictionary<string, int> _POSDeviceTypesIdsByNames = new Dictionary<string, int>(); foreach (POSActionMnemonic currDT in Enum.GetValues(typeof(POSActionMnemonic))) { _POSDeviceTypesIdsByNames.Add(currDT.GetDescription(), (int)currDT); } repositoryItemLookUpEdit1.DataSource = new List<KeyValuePair<string, int>>(_POSDeviceTypesIdsByNames); repositoryItemLookUpEdit1.DisplayMember = "Key"; repositoryItemLookUpEdit1.ValueMember = "Value"; repositoryItemLookUpEdit1.Columns.Clear(); repositoryItemLookUpEdit1.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Key", " ")); } #endregion #region Обработчики private void gridControl1_DoubleClick(object sender, EventArgs e) { //EditorAction(false); EditAction(this, null); } private void cashierRoleBindingSource_PositionChanged(object sender, EventArgs e) { UpdateCurrItem(); } #endregion } }
using Terraria; using Terraria.ID; using Terraria.UI; using Terraria.ModLoader; using System; using System.IO; using ReLogic.Graphics; using Microsoft.Xna.Framework; namespace DuckingAround { public class DuckingAround : Mod { public static DuckingAround instance; public static DynamicSpriteFont exampleFont; internal UserInterface MomUserInterface; public static int Negativity(int someNum, int negativeChance) { if (Main.rand.Next(0, negativeChance) == 1) { return (someNum * -1); } else { return someNum; } } public override void Load() { DuckingAround.instance = this; } public static bool RandomBool(int EqualVal, int Upperbound) { if (Main.rand.Next(0, Upperbound) == EqualVal) { return true; } else { return false; } } public static void HandleNPC(int type, int syncID = 0, bool forceHandle = false, int whoAmI = 0) { if ((forceHandle ? 1 : (Main.netMode == NetmodeID.SinglePlayer ? 1 : 0)) != 0) DuckingAround.SpawnNPC(type, forceHandle, syncID, whoAmI); else DuckingAround.SyncNPC(type, syncID); } public static void SyncNPC(int type, int syncID = 0) { ModPacket packet = DuckingAround.instance.GetPacket(); packet.Write((byte)0); packet.Write(type); packet.Write(syncID); packet.Send(); } private static void SpawnNPC(int type, bool syncData = false, int syncID = 0, int whoAmI = 0) { Player player = syncData ? Main.player[whoAmI] : Main.LocalPlayer; int index; if (type == ModContent.NPCType<NPCs.Towns.EnemySpawnerNPC.EnemySpawnerNPC>()) { index = NPC.NewNPC((int)player.Bottom.X, (int)player.position.Y - 64, type); } else { index = NPC.NewNPC((int)Main.npc[NPC.FindFirstNPC(ModContent.NPCType<NPCs.Towns.EnemySpawnerNPC.EnemySpawnerNPC>())].position.X + DuckingAround.Negativity(800, 3), (int)player.Bottom.Y - 96, type); } if (syncID >= 0) { return; } Main.npc[index].SetDefaults(syncID); } public override void HandlePacket(BinaryReader reader, int whoAmI) { DuckingMessageType sheetMessageType = (DuckingMessageType)reader.ReadByte(); switch (sheetMessageType) { case DuckingMessageType.SpawnNPC: int type = reader.ReadInt32(); int num = reader.ReadInt32(); int syncID = num; int whoAmI1 = whoAmI; DuckingAround.HandleNPC(type, syncID, true, whoAmI1); break; default: this.Logger.Warn((object)("Unknown Message type: " + (object)sheetMessageType)); break; } } public static bool PlayerFromTile(Player player, int xPos, int yPos, int distance) { if (Math.Abs(((int)player.position.X / 16) - xPos) < distance && Math.Abs(((int)player.position.Y / 16) - yPos) < distance) { return true; } else { return false; } } public override void AddRecipeGroups() { RecipeGroup iron = new RecipeGroup(() => "Any Iron Bar", new int[] { ItemID.IronBar, ItemID.LeadBar }); RecipeGroup.RegisterGroup("DuckingAround:IronBars", iron); RecipeGroup gold = new RecipeGroup(() => "Any Gold Bar", new int[] { ItemID.PlatinumBar, ItemID.GoldBar }); RecipeGroup.RegisterGroup("DuckingAround:GoldBars", gold); RecipeGroup copper = new RecipeGroup(() => "Any Copper Bar", new int[] { ItemID.CopperBar, ItemID.TinBar }); RecipeGroup.RegisterGroup("DuckingAround:CopperBars", copper); RecipeGroup silver = new RecipeGroup(() => "Any Silver Bar", new int[] { ItemID.SilverBar, ItemID.TungstenBar }); RecipeGroup.RegisterGroup("DuckingAround:SilverBars", silver); } } class SpawnRateMultiplierGlobalNPC : GlobalNPC { public override void EditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns) { float chugJugMult = 20f; DuckingPlayer modPlayer = Main.LocalPlayer.GetModPlayer<DuckingPlayer>(); if(player.HasBuff(mod.BuffType("ChugJug"))) { modPlayer.timeCounter++; spawnRate = (int)(spawnRate / chugJugMult); maxSpawns = (int)(maxSpawns * chugJugMult); } } } }
using Alabo.Cloud.Shop.SecondBuy.Domain.Entities; using Alabo.Domains.Entities; using Alabo.Domains.Services; using MongoDB.Bson; using System.Collections.Generic; namespace Alabo.Cloud.Shop.SecondBuy.Domain.Services { public interface ISecondBuyOrderService : IService<SecondBuyOrder, ObjectId> { /// <summary> /// ¹ºÂò /// </summary> /// <param name="order"></param> /// <returns></returns> ServiceResult Buy(SecondBuyOrder order); /// <summary> /// ¹ºÂòÁбí /// </summary> /// <param name="productId"></param> /// <returns></returns> List<string> BuyList(long productId); /// <summary> /// ×î½ü¹ºÂò /// </summary> /// <param name="productId"></param> /// <returns></returns> List<string> BuyListRcently(long productId); } }
using System; using System.Collections.Generic; namespace CharacterCreation { public class Race { public string raceName { get; set; } public List<string> StatModifiers { get; set; } public List<string> Abilities { get; set; } public int MovementSpeedModifier { get; set; } public SubRace SubRace { get; set; } public string Size { get; set; } public string Description { get; set; } } public class SubRace { public bool hasSubRace { get; set; } public string subRaceName { get; set; } public List<string> statModifiers { get; set; } public List<string> abilities { get; set; } public int movementSpeedModifier { get; set; } public string size { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Safari; namespace SeleniumHarness { class Browser { public IWebDriver driver { get; set; } public string driverName { get; set; } public Browser(string browserName) { driverName = browserName; if (browserName == "Chrome") driver = new ChromeDriver(); if (browserName == "IE") driver = new InternetExplorerDriver(); if (browserName == "Safari") driver = new SafariDriver(); if (browserName == "Firefox") driver = new FirefoxDriver(); } } }
using Dapper.Contrib.Extensions; namespace IconCreator.Core.Domain.Models { [Table ("ArtikelIcons")] public class ArtikelIcon { [Key] public string ArtNr { get; set; } public string Ico1Path_1 { get; set; } public string Ico1Path_2 { get; set; } public string Ico1Path_3 { get; set; } public string Ico1Path_4 { get; set; } public string Ico1Omschr_1 { get; set; } public string Ico1Omschr_2 { get; set; } public string Ico1Omschr_3 { get; set; } public string Ico1Omschr_4 { get; set; } public string Ico2Path_1 { get; set; } public string Ico2Path_2 { get; set; } public string Ico2Path_3 { get; set; } public string Ico2Path_4 { get; set; } public string Ico2Omschr_1 { get; set; } public string Ico2Omschr_2 { get; set; } public string Ico2Omschr_3 { get; set; } public string Ico2Omschr_4 { get; set; } public string Ico3Path_1 { get; set; } public string Ico3Path_2 { get; set; } public string Ico3Path_3 { get; set; } public string Ico3Path_4 { get; set; } public string Ico3Omschr_1 { get; set; } public string Ico3Omschr_2 { get; set; } public string Ico3Omschr_3 { get; set; } public string Ico3Omschr_4 { get; set; } public bool UpdateFlag { get; set; } } }
using System.Collections.Generic; using Moq; using NBatch.Main.Readers.FileReader; using NUnit.Framework; namespace NBatch.Main.UnitTests.Readers.FileReaders { [TestFixture] class DefaultLineMapperTests { DefaultLineMapper<string> _lineMapper; Mock<ILineTokenizer> _lineTokenizer; Mock<IFieldSetMapper<string>> _mapper; [SetUp] public void BeforeEach() { _lineTokenizer = new Mock<ILineTokenizer>(); var headers = new List<string> {"NAME"}; var line = new List<string> {"Bob"}; _lineTokenizer.SetupGet(x => x.Headers).Returns(headers.ToArray); _lineTokenizer.Setup(x => x.Tokenize(It.IsAny<string>())).Returns(FieldSet.Create(headers, line)); _mapper = new Mock<IFieldSetMapper<string>>(); _lineMapper = new DefaultLineMapper<string>(_lineTokenizer.Object, _mapper.Object); } [Test] public void TokenizesTheDataBeforeMapping() { _lineMapper.MapToModel("line"); _lineTokenizer.Verify(x => x.Tokenize("line")); } [Test] public void MapperReceivesAProperlyFilledFieldSet() { _lineMapper.MapToModel("line"); _mapper.Verify(m => m.MapFieldSet(It.Is<FieldSet>(fs => fs.GetString("NAME") == "Bob"))); } } }
using System.Collections.Generic; using SciVacancies.ReadModel.Core; using SciVacancies.ReadModel.Pager; namespace SciVacancies.WebApp.ViewModels { public class SearchSubscriptionsInResearcherIndexViewModel { public PagedList<SearchSubscription> PagedItems { get; set; } } }
using Genesys.WebServicesClient.Components; 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.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Genesys.WebServicesClient.Sample.Agent.WPF { public partial class ToastWindow : Window { readonly GenesysCall call; public ToastWindow() { InitializeComponent(); var workArea = Screen.PrimaryScreen.WorkingArea; this.Left = workArea.Right - this.Width - 16; this.Top = workArea.Bottom - this.Height - 32; } public ToastWindow(GenesysCall call) : this() { this.call = call; this.DataContext = call; } void AnswerButton_Click(object sender, RoutedEventArgs e) { call.Answer(); } void CloseButton_Click(object sender, RoutedEventArgs e) { Close(); } } }
using System; using UnityEngine; using UnityEngine.UI; public class Coin : MonoBehaviour { void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Player")) { CoinController.CurrentCoin += 1; Destroy(gameObject); } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Magnet")) { CoinController.CurrentCoin += 1; Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Serialization; namespace GoogleHome.Models { public class PostLibrary { [XmlArray("Posts")] public List<Post> Posts { get; set; } public PostLibrary() { } } public class Post { public string Date { get; set; } public string Message { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Exercise_4 { class Program { static void Main(string[] args) { int students = int.Parse(Console.ReadLine()); List<Students> studentsList = new List<Students>(); for (int i = 0; i < students; i++) { studentsList.Add(new Students()); } List<Students> sortedStudents = studentsList.OrderByDescending(x => x.Grade).ToList(); Print(sortedStudents); } private static void Print(List<Students> articles) { for (int i = 0; i < articles.Count; i++) { Console.WriteLine(articles[i]); } } class Students { public string FirstName { get; set; } public string LastName { get; set; } public double Grade { get; set; } public Students() { List<string> command = Console.ReadLine().Split(' ').ToList(); this.FirstName = command[0]; this.LastName = command[1]; this.Grade = double.Parse(command[2]); } public override string ToString() { string newOverride = $"{FirstName} {LastName}: {Grade:f2}"; return newOverride; } } } }
namespace Pe.GyM.Security.Web.Base { /// <summary> /// /// </summary> public sealed class QueryStringParams { public const string ACTIONSSO = "ActionSSO"; public const string APP_KEY = "AppKey"; public const string REQUEST_ID = "RequestId"; public const string RETURN_URL = "ReturnUrl"; public const string RETURN_URL_DEBUG = "ReturnUrlDebug"; public const string TOKEN = "Token"; public const string LOGOUT = "Logout"; } }
using System.Linq; using NUnit.Framework; using Isop.Gui.ViewModels; using Isop.Gui; using Isop.Client.Transfer; using FakeItEasy; using Isop.Client; using Isop.Gui.Adapters; namespace Isop.Wpf.Tests { [TestFixture] public class RootViewModelTests { private IIsopClient _isopClient; private RootViewModel RootVmWithMethodSelected() { var mt = RootModelFromSource(); var treemodel = new RootViewModel(new JsonClient(_isopClient), mt); treemodel.CurrentMethod = treemodel.Controllers.Single() .Methods.Single(m => m.Name == "Action"); return treemodel; } private static Root RootModelFromSource() { return new Root { GlobalParameters = new[] { new Param { Name = "name", Type = typeof(string).FullName } }, Controllers = new[]{ new Controller { Name="My", Methods=new []{ new Method{Name="Action", Parameters=new []{new Param{Name="name", Type=typeof(string).FullName}}}, new Method{Name="AnotherAction", Parameters=new []{new Param{Name="name", Type=typeof(string).FullName}}} } } } }; } [SetUp] public void SetUp() { _isopClient = A.Fake<IIsopClient>(); } [Test] public void When_setting_value_on_global_parameter_will_set_value_on_method_parameter() { var treemodel = RootVmWithMethodSelected(); treemodel.GlobalParameters.First().Value = "new value"; Assert.That(treemodel.CurrentMethod.Parameters.Single().Value, Is.EqualTo("new value")); } [Test] public void When_setting_value_on_method_parameter_will_set_value_on_global_parameter() { var treemodel = RootVmWithMethodSelected(); treemodel.CurrentMethod.Parameters.Single().Value = "new value"; Assert.That(treemodel.GlobalParameters.First().Value, Is.EqualTo("new value")); } [Test] public void When_selecting_another_action_will_deregister_event_handlers() { var treemodel = RootVmWithMethodSelected(); var param1 = treemodel.CurrentMethod.Parameters.Single(); param1.Value = "new value"; treemodel.CurrentMethod = treemodel.Controllers.Single().Methods.Single(m => m.Name == "AnotherAction"); treemodel.CurrentMethod.Parameters.Single().Value = "another value"; Assert.That(treemodel.GlobalParameters.First().Value, Is.EqualTo("another value")); Assert.That(param1.Value, Is.EqualTo("new value")); } /// <summary> /// The parameters might be regenerated when using Select/Where /// </summary> [Test] public void Parameters_does_not_change() { var treemodel = RootVmWithMethodSelected(); var param1 = treemodel.CurrentMethod.Parameters.Single(); treemodel.CurrentMethod = treemodel.Controllers.Single().Methods.Single(m => m.Name == "AnotherAction"); Assert.That(treemodel.Controllers.Single() .Methods.Single(m => m.Name == "Action").Parameters.Single(), Is.EqualTo(param1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Kendo.Mvc.UI; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace RazorPageGridTest.Pages.Customer { public class IndexModel : PageModel { public List<RazorPageGridTest.Customer> Data { get; set; } public void OnGet() { Data = new List<RazorPageGridTest.Customer>(); for (int i = 1; i <= 100; i++) { Data.Add(new RazorPageGridTest.Customer() { CustomerId = i, Name = "Name " + i.ToString(), Address = "Address " + i.ToString(), ClockOut = DateTime.Now.AddDays(i) }); } } public JsonResult OnPostReadRecords() { List<RazorPageGridTest.Customer> data = new List<RazorPageGridTest.Customer>(); for (int i = 1; i <= 100; i++) { data.Add(new RazorPageGridTest.Customer() { CustomerId = i, Name = "Name "+ i.ToString(), Address = "Address " + i.ToString(), ClockOut = DateTime.Now.AddHours(i) }); } return new JsonResult(data); } public JsonResult OnPostUpdateRecord([DataSourceRequest] DataSourceRequest request, RazorPageGridTest.Customer customer) { System.Diagnostics.Debug.WriteLine("Updating"); return new JsonResult(customer); } } }
using CommonDomain.Core; using SciVacancies.Domain.Core; using SciVacancies.Domain.DataModels; using SciVacancies.Domain.Enums; using SciVacancies.Domain.Events; using System; using System.Collections.Generic; namespace SciVacancies.Domain.Aggregates { public class Vacancy : AggregateBase { public Guid OrganizationGuid { get; private set; } private VacancyDataModel Data { get; set; } public VacancyStatus Status { get; private set; } /// <summary> /// Дато окончания приёма заявок и начала работы комиссии /// </summary> public DateTime InCommitteeStartDate { get; private set; } /// <summary> /// Дата окончания работы комиссии (далее даётся Х дней на оглашение результатов, статус при этом остаётся "на комиссии". /// Дата может сдвигаться соответсующей командой /// </summary> public DateTime InCommitteeEndDate { get; private set; } /// <summary> /// Причина, почему продлили комиссию /// </summary> public string ProlongingInCommitteeReason { get; private set; } /// <summary> /// Заключение комиссии (помимо этого ещё файл "протокол комиссии" в attachments) /// </summary> public string CommitteeResolution { get; private set; } public Guid WinnerResearcherGuid { get; private set; } public Guid WinnerVacancyApplicationGuid { get; private set; } /// <summary> /// Если null, значит победитель ещё не принял решение или ему не отсылалось уведомление /// </summary> public bool? IsWinnerAccept { get; private set; } /// <summary> /// Обоснование выбора этой заявки в качестве победителя /// </summary> public Guid PretenderResearcherGuid { get; private set; } public Guid PretenderVacancyApplicationGuid { get; private set; } /// <summary> /// Если null, значит претендент ещё не принял решение или ему не отсылалось уведомление /// </summary> public bool? IsPretenderAccept { get; private set; } public string CancelReason { get; private set; } public Vacancy() { } public Vacancy(Guid guid, Guid organizationGuid, VacancyDataModel data) { if (guid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(guid)); if (organizationGuid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(organizationGuid)); if (data == null) throw new ArgumentNullException(nameof(data)); RaiseEvent(new VacancyCreated { VacancyGuid = guid, OrganizationGuid = organizationGuid, Data = data }); } #region Methods public void Update(VacancyDataModel data) { if (data == null) throw new ArgumentNullException(nameof(data)); if (Status != VacancyStatus.InProcess) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyUpdated { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, Data = data }); } public void Remove() { if (Status != VacancyStatus.InProcess) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyRemoved { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void Publish(DateTime inCommitteeStartDate, DateTime inCommitteeEndDate) { if (inCommitteeStartDate > inCommitteeEndDate) throw new ArgumentException("inCommitteeStartDate is bigger than inCommitteeEndDate"); if (Status != VacancyStatus.InProcess) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyPublished { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, InCommitteeStartDate = inCommitteeStartDate, InCommitteeEndDate = inCommitteeEndDate }); } public void VacancyToCommittee() { if (Status != VacancyStatus.Published) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyInCommittee { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void ProlongInCommittee(string reason, DateTime inCommitteeEndDate) { if (string.IsNullOrEmpty(reason)) throw new ArgumentNullException(nameof(reason)); if (InCommitteeEndDate >= inCommitteeEndDate) throw new ArgumentException("new inCommitteeEndDate is equals or before the current InCommitteeEndDate value"); if (Status != VacancyStatus.InCommittee) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyProlongedInCommittee { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, Reason = reason, InCommitteeEndDate = inCommitteeEndDate }); } public void SetCommitteeResolution(string resolution, List<VacancyAttachment> attachments) { if (string.IsNullOrEmpty(resolution)) throw new ArgumentNullException(nameof(resolution)); //по приказу не требуется, на данный момент, обязательно добавлять файл. //todo: Vacancy -> SetCommitteeResolution -> нужно ли требовать //if (attachments == null || attachments.Count == 0) throw new ArgumentNullException("attachments is null or empty"); if ( (attachments == null || attachments.Count == 0) && string.IsNullOrWhiteSpace(resolution)) throw new ArgumentNullException($"{nameof(attachments)} or {nameof(resolution)} should be added"); if (Status != VacancyStatus.InCommittee) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyCommitteeResolutionSet { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, Resolution = resolution, Attachments = attachments }); } public void SetWinner(Guid winnerGuid, Guid winnerVacancyApplicationGuid) { if (winnerGuid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(winnerGuid)); if (winnerVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(winnerVacancyApplicationGuid)); if (Status != VacancyStatus.InCommittee) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyWinnerSet { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, WinnerReasearcherGuid = winnerGuid, WinnerVacancyApplicationGuid = winnerVacancyApplicationGuid }); } public void SetPretender(Guid pretenderGuid, Guid pretenderVacancyApplicationGuid) { if (pretenderGuid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(pretenderGuid)); if (pretenderVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException(nameof(pretenderVacancyApplicationGuid)); if (Status != VacancyStatus.InCommittee) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyPretenderSet { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, PretenderReasearcherGuid = pretenderGuid, PretenderVacancyApplicationGuid = pretenderVacancyApplicationGuid }); } public void VacancyToResponseAwaitingFromWinner() { if (Status != VacancyStatus.InCommittee) throw new InvalidOperationException("vacancy state is invalid"); if (WinnerResearcherGuid == Guid.Empty || WinnerVacancyApplicationGuid == Guid.Empty) throw new ArgumentNullException("WinnerGuid or WinnerVacancyApplicationGuid is empty"); RaiseEvent(new VacancyInOfferResponseAwaitingFromWinner { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void WinnerAcceptOffer() { if (WinnerResearcherGuid.Equals(Guid.Empty)) throw new ArgumentNullException($"{nameof(WinnerResearcherGuid)} is empty"); if (WinnerVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException($"{nameof(WinnerVacancyApplicationGuid)} is empty"); if (Status != VacancyStatus.OfferResponseAwaitingFromWinner) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyOfferAcceptedByWinner { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void WinnerRejectOffer() { if (WinnerResearcherGuid.Equals(Guid.Empty)) throw new ArgumentNullException($"{nameof(WinnerResearcherGuid)} is empty"); if (WinnerVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException($"{nameof(WinnerVacancyApplicationGuid)} is empty"); if (Status != VacancyStatus.OfferResponseAwaitingFromWinner) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyOfferRejectedByWinner { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void VacancyToResponseAwaitingFromPretender() { if (!(Status==VacancyStatus.OfferAcceptedByWinner|| Status == VacancyStatus.OfferRejectedByWinner)) throw new InvalidOperationException("vacancy state is invalid"); if (PretenderResearcherGuid == Guid.Empty || PretenderVacancyApplicationGuid == Guid.Empty) throw new ArgumentNullException("WinnerGuid or WinnerVacancyApplicationGuid is empty"); RaiseEvent(new VacancyInOfferResponseAwaitingFromPretender { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void PretenderAcceptOffer() { if (PretenderResearcherGuid.Equals(Guid.Empty)) throw new ArgumentNullException("PretenderResearcherGuid is empty"); if (PretenderVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException("PretenderVacancyApplicationGuid is empty"); if (!IsWinnerAccept.HasValue) throw new InvalidOperationException("IsWinnerAccept is invalid"); if (Status != VacancyStatus.OfferResponseAwaitingFromPretender) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyOfferAcceptedByPretender { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void PretenderRejectOffer() { if (PretenderResearcherGuid.Equals(Guid.Empty)) throw new ArgumentNullException("PretenderResearcherGuid is empty"); if (PretenderVacancyApplicationGuid.Equals(Guid.Empty)) throw new ArgumentNullException("PretenderVacancyApplicationGuid is empty"); if (!IsWinnerAccept.HasValue) throw new InvalidOperationException("IsWinnerAccept is invalid"); if (Status != VacancyStatus.OfferResponseAwaitingFromPretender) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyOfferRejectedByPretender { VacancyGuid = Id, OrganizationGuid = OrganizationGuid }); } public void Close() { if (!(Status == VacancyStatus.OfferAcceptedByWinner || Status == VacancyStatus.OfferAcceptedByPretender)) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyClosed { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, WinnerResearcherGuid = WinnerResearcherGuid, WinnerVacancyApplicationGuid = WinnerVacancyApplicationGuid, IsWinnerAccept = IsWinnerAccept.Value, PretenderResearcherGuid = PretenderResearcherGuid, PretenderVacancyApplicationGuid = PretenderVacancyApplicationGuid, IsPretenderAccept = IsPretenderAccept }); } public void Cancel(string reason) { if (string.IsNullOrEmpty(reason)) throw new ArgumentNullException(nameof(reason)); if (!(Status == VacancyStatus.Published || Status == VacancyStatus.InCommittee || Status == VacancyStatus.OfferAcceptedByWinner || Status == VacancyStatus.OfferRejectedByWinner || Status == VacancyStatus.OfferAcceptedByPretender || Status == VacancyStatus.OfferRejectedByPretender)) throw new InvalidOperationException("vacancy state is invalid"); RaiseEvent(new VacancyCancelled { VacancyGuid = Id, OrganizationGuid = OrganizationGuid, Reason = reason }); } #endregion #region Apply-Handlers public void Apply(VacancyCreated @event) { Id = @event.VacancyGuid; OrganizationGuid = @event.OrganizationGuid; Data = @event.Data; } public void Apply(VacancyUpdated @event) { Data = @event.Data; } public void Apply(VacancyRemoved @event) { Status = VacancyStatus.Removed; } public void Apply(VacancyPublished @event) { InCommitteeStartDate = @event.InCommitteeStartDate; InCommitteeEndDate = @event.InCommitteeEndDate; Status = VacancyStatus.Published; } public void Apply(VacancyInCommittee @event) { Status = VacancyStatus.InCommittee; } public void Apply(VacancyProlongedInCommittee @event) { ProlongingInCommitteeReason = @event.Reason; InCommitteeEndDate = @event.InCommitteeEndDate; } public void Apply(VacancyCommitteeResolutionSet @event) { CommitteeResolution = @event.Resolution; Data.Attachments.AddRange(@event.Attachments); } public void Apply(VacancyWinnerSet @event) { WinnerResearcherGuid = @event.WinnerReasearcherGuid; WinnerVacancyApplicationGuid = @event.WinnerVacancyApplicationGuid; } public void Apply(VacancyPretenderSet @event) { PretenderResearcherGuid = @event.PretenderReasearcherGuid; PretenderVacancyApplicationGuid = @event.PretenderVacancyApplicationGuid; } public void Apply(VacancyInOfferResponseAwaitingFromWinner @event) { Status = VacancyStatus.OfferResponseAwaitingFromWinner; } public void Apply(VacancyOfferAcceptedByWinner @event) { IsWinnerAccept = true; Status = VacancyStatus.OfferAcceptedByWinner; } public void Apply(VacancyOfferRejectedByWinner @event) { IsWinnerAccept = false; Status = VacancyStatus.OfferRejectedByWinner; } public void Apply(VacancyInOfferResponseAwaitingFromPretender @event) { Status = VacancyStatus.OfferResponseAwaitingFromPretender; } public void Apply(VacancyOfferAcceptedByPretender @event) { IsPretenderAccept = true; Status = VacancyStatus.OfferAcceptedByPretender; } public void Apply(VacancyOfferRejectedByPretender @event) { IsPretenderAccept = false; Status = VacancyStatus.OfferRejectedByPretender; } public void Apply(VacancyClosed @event) { Status = VacancyStatus.Closed; } public void Apply(VacancyCancelled @event) { CancelReason = @event.Reason; Status = VacancyStatus.Cancelled; } #endregion } }
using System; using UnityEngine; using UnityEngine.UI; public class Slot : MonoBehaviour { public Text numText; public int num; public bool isCombine; public int _x; public int _y; float _xPos, _yPos; public bool move, _combine; void Start() { isCombine = false; num = Convert.ToInt32(gameObject.name); numText.text = num.ToString(); _xPos = GameObject.Find("Game").GetComponent<Game>().xPos; _yPos = GameObject.Find("Game").GetComponent<Game>().yPos; } // Update is called once per frame void Update() { if(move) { Move(_x, _y, _combine); } } public void Move(int x, int y, bool combine) { move = true; _x = x; _y = y; _combine = combine; Vector3 target = new Vector3((320 * x) - _xPos, (320 * y) - _yPos, 0); transform.localPosition = Vector3.MoveTowards(transform.localPosition, target, 100); if (transform.localPosition == target) { move = false; if (combine == true) { _combine = false; Destroy(gameObject); } } } }
using System; namespace DelftTools.Utils { public interface IEditableObject { /// <summary> /// True if object is being edited (potentially in invalid state). /// </summary> bool IsEditing { get; } /// <summary> /// Is set to true if the last edit action was cancelled. /// </summary> bool EditWasCancelled { get; } /// <summary> /// Current edit action. /// </summary> IEditAction CurrentEditAction { get; } /// <summary> /// Start editing object with the named action. Object must assign <see cref="action"/> to <see cref="CurrentEditActionName"/> before <see cref="IsEditing"/> is changed. /// </summary> /// <param name="action"></param> void BeginEdit(IEditAction action); /// <summary> /// Submit changes to the datasource. /// </summary> void EndEdit(); /// <summary> /// Revert the changes. /// </summary> void CancelEdit(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AmmoTooltip : MonoBehaviour { public Text text; public Weapon weapon; Transform playerHead; float sizeNormal = 1f; float sizeLarge = 1.75f; void Start () { text = GetComponent<Text>(); weapon = transform.parent.parent.GetComponent<Weapon>(); playerHead = GameObject.Find("Camera (both) (eye)").transform; if (weapon) { weapon.eventAdjustAmmo += AdjustText; text.text = weapon.ammoCurrent.ToString(); } } void AdjustText () { text.text = weapon.ammoCurrent.ToString(); transform.localScale = new Vector3(sizeLarge, sizeLarge, sizeLarge); } void Update () { float distanceFactor = Mathf.Clamp(-Vector3.Distance(transform.position, playerHead.position) + 3, 0, 1); float angleFactor = Mathf.Clamp(75 - (Vector3.Angle(transform.forward, playerHead.transform.forward) + 10), 0, 75) / 75; float factorTimeLastFired = Mathf.Clamp(((weapon.timeLastTriggered * 4) - (Time.timeSinceLevelLoad * 4)) + 4f, 0, 1); float factorTimeLastGrabbed = Mathf.Clamp01((weapon.timeLastGrabbed * 4) - (Time.timeSinceLevelLoad * 4) + 5f); text.color = new Color(text.color.r, text.color.g, text.color.b, Mathf.Clamp01(distanceFactor * angleFactor * (factorTimeLastFired + factorTimeLastGrabbed))); transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(sizeNormal, sizeNormal, sizeNormal), 10 * Time.deltaTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using com.Sconit.Entity.ORD; namespace com.Sconit.Web.Models.SearchModels.ORD { public class OrderBomDetailSearchModel : SearchModelBase { public int? Operation { get; set; } public string Item { get; set; } public string Location { get; set; } public string OpReference { get; set; } public int OrderDetailId { get; set; } public int OrderStatus { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BSTree; using NUnit.Framework; namespace TestsLcaForBSTree { public class TestSetNeighbour { public Node Node; public Node NodesNeighbour; public TestSetNeighbour(Node node, Node neighbour) { this.Node = node; this.NodesNeighbour = neighbour; } } [TestFixture] class RightNeibourTests { static Dictionary<string, TestSetNeighbour> testSetNeighbour = new Dictionary<string, TestSetNeighbour>(); static KeyValuePair<Node,int> nodeToStart; [TestFixtureSetUp] public void Init() { /* a / \ b c / \ \ d e f */ Node root1 = new Node("A", null); Node bNode = new Node("B", root1); Node cNode = new Node("C", root1); Node dNode = new Node("D", bNode); Node eNode = new Node("E", bNode); Node fNode = new Node("F", cNode); root1.Left = bNode; root1.Right = cNode; bNode.Left = dNode; bNode.Right = eNode; cNode.Right = fNode; Node.SetNodesRightNeighbour(root1, 0); testSetNeighbour.Add("test1",new TestSetNeighbour(root1,null)); testSetNeighbour.Add("test2",new TestSetNeighbour(cNode,null)); testSetNeighbour.Add("test3",new TestSetNeighbour(bNode,cNode)); testSetNeighbour.Add("test4",new TestSetNeighbour(eNode,fNode)); testSetNeighbour.Add("test5",new TestSetNeighbour(dNode,eNode)); } [Test] [TestCase("test1")] [TestCase("test2")] [TestCase("test3")] [TestCase("test4")] [TestCase("test5")] public void Test(string setName) { var node = testSetNeighbour[setName].Node; var expectedNeighbour = testSetNeighbour[setName].NodesNeighbour; var actualNeighbour = Node.GetNodeNeighbour(node); Assert.AreEqual(expectedNeighbour,actualNeighbour); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.SYS; //TODO: Add other using statements here namespace com.Sconit.Entity.PRD { [Serializable] public partial class SmallSparePartChk : EntityBase, IAuditable { #region O/R Mapping Properties public Int32 Id { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 10)] [Display(Name = "SmallSparePartChk_Huid", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public string Huid { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 20)] [Display(Name = "SmallSparePartChk_HuItem", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public string HuItem { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 30)] [Display(Name = "SmallSparePartChk_HuQty", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public decimal HuQty { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 40)] [Display(Name = "SmallSparePartChk_HuItemDesc", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public string HuItemDesc { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 50)] [Display(Name = "SmallSparePartChk_SpareItem", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public string SpareItem { get; set; } [Export(ExportName = "SmallMatchSparePartCheck", ExportSeq = 60)] [Display(Name = "SmallSparePartChk_SpareItemDesc", ResourceType = typeof(Resources.PRD.SmallSparePartChk))] public string SpareItemDesc { get; set; } public Int32 CreateUserId { get; set; } [Display(Name = "IpMaster_CreateUserName", ResourceType = typeof(Resources.ORD.IpMaster))] public string CreateUserName { get; set; } [Display(Name = "IpMaster_CreateDate", ResourceType = typeof(Resources.ORD.IpMaster))] public DateTime CreateDate { get; set; } public Int32 LastModifyUserId { get; set; } public string LastModifyUserName { get; set; } public DateTime LastModifyDate { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { SmallSparePartChk another = obj as SmallSparePartChk; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.ComponentModel.DataAnnotations; namespace OrgMan.DataModel { [MetadataType(typeof(CountryMetaData))] public partial class Country { public IEnumerable<Guid> MandatorUIDs { get { return null; } set { throw new DataException("Cannot set MandatorUIDs on Table Country. The Column does not exists."); } } } public class CountryMetaData { [MaxLength(10)] [Required] public string Code { get; set; } [MaxLength(30)] [Required] public string Title { get; set; } } [MetadataType(typeof(LoginMetaData))] public partial class Login { public IEnumerable<Guid> MandatorUIDs { get { if (this.Person != null && this.Person.PersonToMandators != null && this.Person.PersonToMandators.Any()) { return this.Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Login. The Column does not exists."); } } } public class LoginMetaData { } [MetadataType(typeof(MandatorMetaData))] public partial class Mandator { public IEnumerable<Guid> MandatorUIDs { get { var uids = new List<Guid>(); uids.Add(this.UID); return uids.AsEnumerable(); } set { throw new DataException("Cannot set MandatorUIDs on Table Mandator. The Column does not exists."); } } } public class MandatorMetaData { } [MetadataType(typeof(MemberinformationMetaData))] public partial class MemberInformation { public IEnumerable<Guid> MandatorUIDs { get { if (this.IndividualPersons != null && this.IndividualPersons.Any() && this.IndividualPersons.FirstOrDefault().Person != null && this.IndividualPersons.FirstOrDefault().Person.PersonToMandators != null && this.IndividualPersons.FirstOrDefault().Person.PersonToMandators.Any()) { return this.IndividualPersons.FirstOrDefault().Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table MemberInformation. The Column does not exists."); } } } public class MemberinformationMetaData { } [MetadataType(typeof(MemberInformationToMembershipMetaData))] public partial class MemberInformationToMembership { public IEnumerable<Guid> MandatorUIDs { get { if (this.Membership != null) { var uids = new List<Guid>(); uids.Add(this.Membership.MandatorUID); return uids.AsEnumerable(); }else { if(this.MemberInformation != null && this.MemberInformation.IndividualPersons != null && this.MemberInformation.IndividualPersons.Any() && this.MemberInformation.IndividualPersons.First().MandatorUIDs != null) { return this.MemberInformation.IndividualPersons.First().MandatorUIDs; } } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table MemberInformationToMembership. The Column does not exists."); } } public static implicit operator List<object>(MemberInformationToMembership v) { throw new NotImplementedException(); } } public class MemberInformationToMembershipMetaData { } [MetadataType(typeof(SaluatationMetaData))] public partial class Salutation { public IEnumerable<Guid> MandatorUIDs { get { return null; } set { throw new DataException("Cannot set MandatorUIDs on Table Saluation. The Column does not exists."); } } } public class SaluatationMetaData { } [MetadataType(typeof(AdressMetaData))] public partial class Adress { public IEnumerable<Guid> MandatorUIDs { get { if (this.IndividualPersons != null && this.IndividualPersons.Any() && this.IndividualPersons.FirstOrDefault().Person != null && this.IndividualPersons.FirstOrDefault().Person.PersonToMandators != null && this.IndividualPersons.FirstOrDefault().Person.PersonToMandators.Any()) { return this.IndividualPersons.FirstOrDefault().Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Adress. The Column does not exists."); } } } public class AdressMetaData { [MaxLength(50)] [Required] public string Street { get; set; } [MaxLength(10)] [Required] public string HouseNumber { get; set; } [MaxLength(100)] [Required] public string Additional { get; set; } [MaxLength(50)] public string City { get; set; } [MaxLength(10)] [Required] public string PostCode { get; set; } } [MetadataType(typeof(CommunicationTypeMetaData))] public partial class CommunicationType { public IEnumerable<Guid> MandatorUIDs { get { return null; } set { throw new DataException("Cannot set MandatorUIDs on Table CommunicationType. The Column does not exists."); } } } public class CommunicationTypeMetaData { } [MetadataType(typeof(EmailMetaData))] public partial class Email { public IEnumerable<Guid> MandatorUIDs { get { if (this.IndividualPerson != null && this.IndividualPerson.Person != null && this.IndividualPerson.Person.PersonToMandators != null && this.IndividualPerson.Person.PersonToMandators.Any()) { return this.IndividualPerson.Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Email. The Column does not exists."); } } } public class EmailMetaData { [MaxLength(100)] [MinLength(5)] [Required] public string EmailAdress { get; set; } [Required] public bool IsMain { get; set; } } [MetadataType(typeof(PhoneMetaData))] public partial class Phone { public IEnumerable<Guid> MandatorUIDs { get { if (this.IndividualPerson != null && this.IndividualPerson.Person != null && this.IndividualPerson.Person.PersonToMandators != null && this.IndividualPerson.Person.PersonToMandators.Any()) { return this.IndividualPerson.Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Phone. The Column does not exists."); } } } public class PhoneMetaData { [MaxLength(20)] [MinLength(5)] [Required] public string Phone { get; set; } [Required] public bool IsMain { get; set; } } [MetadataType(typeof(IndividualPersonMetaData))] public partial class IndividualPerson { public IEnumerable<Guid> MandatorUIDs { get { if(this.Person != null && this.Person.PersonToMandators != null && this.Person.PersonToMandators.Any()) { return this.Person.PersonToMandators.Select(p => p.MandatorUID); } return null; } set { throw new DataException("Cannot set MandatorUIDs on Table IndividualPerson. The Column does not exists."); } } } public class IndividualPersonMetaData { [MaxLength(100)] [Required] public string Company { get; set; } [MaxLength(2000)] public bool Comment { get; set; } } [MetadataType(typeof(SystemPersonMetaData))] public partial class SystemPerson { public IEnumerable<Guid> MandatorUIDs { get { if (this.Person != null && this.Person.PersonToMandators != null && this.Person.PersonToMandators.Any()) { return this.Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table SysPerson. The Column does not exists."); } } } public class SystemPersonMetaData { } [MetadataType(typeof(PersonMetaData))] public partial class Person { public IEnumerable<Guid> MandatorUIDs { get { if (this.PersonToMandators != null && this.PersonToMandators.Any()) { return this.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Person. The Column does not exists."); } } } public class PersonMetaData { [MaxLength(50)] [Required] public string Firstname { get; set; } [MaxLength(50)] [Required] public string lastname { get; set; } } [MetadataType(typeof(SessionMetaData))] public partial class Session { public IEnumerable<Guid> MandatorUIDs { get { if(this.Login != null && this.Login.Person != null && this.Login.Person.PersonToMandators != null && this.Login.Person.PersonToMandators.Any()) { return this.Login.Person.PersonToMandators.Select(p => p.MandatorUID); } throw new DataException("Could not load MandatorUIDs"); } set { throw new DataException("Cannot set MandatorUIDs on Table Session. The Column does not exists."); } } } public class SessionMetaData { } [MetadataType(typeof(MembershipMetaData))] public partial class Membership { public IEnumerable<Guid> MandatorUIDs { get { var uids = new List<Guid>(); uids.Add(this.MandatorUID); return uids.AsEnumerable(); } set { this.MandatorUID = value.First(); //throw new DataException("Cannot set MandatorUIDs on Table Membership. The Column does not exists."); } } } public class MembershipMetaData { [MaxLength(10)] [Required] public string Code { get; set; } [MaxLength(30)] [Required] public string Title { get; set; } } [MetadataType(typeof(PersonToMandatorMetaData))] public partial class PersonToMandator { public IEnumerable<Guid> MandatorUIDs { get { var uids = new List<Guid>(); uids.Add(this.MandatorUID); return uids.AsEnumerable(); } set { throw new DataException("Cannot set MandatorUIDs on Table Session. The Column does not exists."); } } } public class PersonToMandatorMetaData { } [MetadataType(typeof(MeetingMetaData))] public partial class Meeting { public IEnumerable<Guid> MandatorUIDs { get { var uids = new List<Guid>(); uids.Add(this.MandatorUID); return uids.AsEnumerable(); } set { throw new DataException("Cannot set MandatorUIDs on Table Session. The Column does not exists."); } } } public class MeetingMetaData { [MaxLength(50)] [Required] public string Title { get; set; } [MaxLength(50)] [Required] public string Location { get; set; } [MaxLength(500)] [Required] public string Description { get; set; } } }
namespace Infrastructure.Translations { public interface ITranslationService { dynamic Translate { get; } } }
using System; namespace PhotonInMaze.Common.Flow { internal class WhenAny : IThenAny, IInvoke, IBuild { private Action action; private Func<bool> predicate; public WhenAny() { this.predicate = () => true; } public WhenAny(Func<bool> predicate) { this.predicate = predicate; } public IInvoke Build() { return this; } public void Invoke(State currentState = State.GenerateMaze) { if(predicate.Invoke()) { action?.Invoke(); } } public IBuild ThenDo(Action action) { this.action = action; return this; } } public interface IWhenAny { IThenAny WhenIsAny(); IThenAny WhenIsAnyAnd(Func<bool> predicate); } public interface IThenAny { IBuild ThenDo(Action action); } public interface IBuild { IInvoke Build(); } }
using Profiling2.Domain.Contracts.Queries; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries { public class LocationMergeQuery : NHibernateQuery, ILocationMergeQuery { public void MergeLocations(int toKeepId, int toDeleteId) { string sql = @" UPDATE PRF_Event SET LocationID = :toKeepId WHERE LocationID = :toDeleteId "; Session.CreateSQLQuery(sql).SetInt32("toKeepId", toKeepId).SetInt32("toDeleteId", toDeleteId).ExecuteUpdate(); sql = @" UPDATE PRF_Career SET LocationID = :toKeepId WHERE LocationID = :toDeleteId "; Session.CreateSQLQuery(sql).SetInt32("toKeepId", toKeepId).SetInt32("toDeleteId", toDeleteId).ExecuteUpdate(); sql = @" UPDATE PRF_UnitLocation SET LocationID = :toKeepId WHERE LocationID = :toDeleteId "; Session.CreateSQLQuery(sql).SetInt32("toKeepId", toKeepId).SetInt32("toDeleteId", toDeleteId).ExecuteUpdate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Core31DemoProject.Controllers { /// <summary> /// [ApiController]属性将推理规则应用于操作参数的默认数据源。借助这些规则,无需将属性应用于操作参数来手动识别绑定源。绑定源的推理规则的行为如下: /// 1 [FromBody]针对复杂类型的参数进行推断.[FromBody]不适用于具有特殊含义的任何复杂的内置类型,如IFormCollection、CancellationToken /// 2 [FromForm]针对IFormFile、IFormFileCollection类型的参数进行推断。该特性不针对任何简单类型或用户自定义的类型进行推断 /// 3 [FromRoute]针对与路由模板中的参数相匹配的任何参数名称进行推断。当多个路由与一个操作参数匹配时,任何路由值都是为[FromRoute] /// 4 [FromQuery]针对任何其他操作参数进行推断 /// /// 所以ApiController主要是做 参数 数据源推理,有一套自己的推理规则,规则如上 /// </summary> [Route("api/[controller]/[action]"),ApiController] public class ApiBaseController : ControllerBase { } }
using Brambillator.CulturedMedia.Domain.Views; using Brambillator.CulturedMedia.Service; using Brambillator.Historiarum.Domain.Lookups; using Brambillator.Historiarum.Domain.Model; using Brambillator.Historiarum.Domain.UnitOfWork; using System.Collections.Generic; namespace Brambillator.Historiarum.Service { public class MomentumService { private IHistoriarumUnitOfWork _unitOfWork { get; set; } private IResourceService _resourceService { get; set; } /// <summary> /// Constructs a new instance of <see cref="MomentumService"/> with given repository. /// </summary> /// <param name="unitOfWork"></param> public MomentumService(IHistoriarumUnitOfWork unitOfWorkForMomentum, IResourceService resourceService) { _unitOfWork = unitOfWorkForMomentum; _resourceService = resourceService; } public void CreateMomentum(string cultureName, SourceType sourceType, MomentumType momentumType, ExtendedDate tempus, string[] resourceKeys) { Momentum newMomentum = new Momentum(); newMomentum.SourceType = sourceType; newMomentum.Tempus = tempus; newMomentum.Type = momentumType; //newMomentum.Resources = resources; List<MomentumResource> resourceList = new List<MomentumResource>(); foreach (string key in resourceKeys) { //_resourceService.CreateOrUpdate() resourceList.Add(new MomentumResource() { CulturedMediaKey = key }); } newMomentum.Resources = resourceList; //newMomentum.State = Infrastructure.Domain.Models.EntityState.Added; _unitOfWork.MomentumRepository.Add(newMomentum); _unitOfWork.Commit(); } } }
namespace TryHardForum.ViewModels.Forum { public class ForumDeleteModel { public int ForumId { get; set; } public string ForumName { get; set; } public string UserId { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Dominio; using Repositorios; namespace TableroComando.Formularios { public partial class Form_Empresa : Form { Empresa _empresa = EmpresaRepository.Instance.FindById(1); public Form_Empresa() { InitializeComponent(); } private void Form_Empresa_Load(object sender, EventArgs e) { CargarEmpresa(); } private void CargarEmpresa() { txtDenominacion.Text = _empresa.Denominacion; txtCuit.Text = _empresa.Cuit; txtDireccion.Text = _empresa.Direccion; txtTelefono.Text = _empresa.Telefono; txtAutoridades.Text = _empresa.Autoridades; txtMision.Text = _empresa.Mision; txtVision.Text = _empresa.Vision; txtValores.Text = _empresa.Valores; } private void CrearDatosEmpresa() { _empresa.Denominacion = txtDenominacion.Text; _empresa.Cuit = txtCuit.Text; _empresa.Direccion = txtDireccion.Text; _empresa.Telefono = txtTelefono.Text; _empresa.Autoridades = txtAutoridades.Text; _empresa.Mision = txtMision.Text; _empresa.Vision = txtVision.Text; _empresa.Valores = txtValores.Text; } private void btnGuardar_Click(object sender, EventArgs e) { CrearDatosEmpresa(); EmpresaRepository.Instance.Save(_empresa); MessageBox.Show("Los datos de su empresa se guardaron correctamente","Exito",MessageBoxButtons.OK,MessageBoxIcon.Information); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InoDrive.Domain.Entities { public class WayPoint { public Int32 WayPointId { get; set; } public Int32 WayPointIndex { get; set; } public Int32 TripId { get; set; } public String PlaceId { get; set; } public virtual Place Place { get; set; } public virtual Trip Trip { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using XH.Domain.Exceptions; namespace XH.Infrastructure.Web.Filters { public class ExceptionResult { public static ExceptionResult Create(Exception exception) { var domainException = exception as DomainException; var message = exception.Message; if (domainException != null) { message = domainException.Message; } return new ExceptionResult(HttpStatusCode.InternalServerError, message); } public ExceptionResult(HttpStatusCode statusCode, IEnumerable<string> errorMessages) { StatusCode = statusCode; Code = (int)statusCode; Errors = errorMessages; } public ExceptionResult(string errorMessage) : this(HttpStatusCode.InternalServerError, errorMessage) { } public ExceptionResult(IEnumerable<string> errorMessages) : this(HttpStatusCode.InternalServerError, errorMessages) { } public ExceptionResult(HttpStatusCode statusCode, string errorMessage) : this(statusCode, new List<string> { errorMessage }) { } [JsonIgnore] public HttpStatusCode StatusCode { get; private set; } [JsonProperty("StatusCode")] public int Code { get; set; } public IEnumerable<string> Errors { get; private set; } } }
namespace BattleEngine.Records { public class BattleNPCRecord { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Calculstor { public partial class Calculator : Form { // Creation of variables to hold user values,opertor and answer Double num1, num2, answer; String operators = ""; public Calculator() { InitializeComponent(); } //Event Handler for number clicked by user private void numClick(object sender, EventArgs e) { Button b = (Button)sender; txtEntry.Text = txtEntry.Text + b.Text; } //Event handler to clear values enterted by user private void btnClear_Click(object sender, EventArgs e) { txtEntry.Clear(); } //Event handler to clear data once first value entered //Event handler also sets first value to user entry private void operations_click(object sender, EventArgs e) { Button O = (Button)sender; operators = O.Text; num1 = Double.Parse(txtEntry.Text); if (btnAdd.Enabled || btnDivide.Enabled || btnMultiply.Enabled || btnSubtract.Enabled == true) { txtEntry.Clear(); } } //Event handler to determine mathematical opertations to perform based on user click //Event handler also displays answer of operations private void btnEqual_Click(object sender, EventArgs e) { num2 = Double.Parse(txtEntry.Text); switch (operators) { case "+": answer = num1 + num2; break; case "-": answer = num1 - num2; break; case "*": answer = num1 * num2; break; case "/": answer = num1 / num2; break; } txtEntry.Text = ""+answer; } } }
 using System.Collections.Generic; using System.Linq; namespace SoftUniParking { public class Parking { private readonly List<Car> cars; private readonly int capacity; public Parking(int capacity) { this.capacity = capacity; this.cars = new List<Car>(capacity); } public int Count => this.cars.Count; public string AddCar(Car car) { if (cars.Any(c => c.RegistrationNumber == car.RegistrationNumber)) { return "Car with that registration number, already exists!"; } else if (cars.Count >= capacity) { return "Parking is full!"; } else { cars.Add(car); return $"Successfully added new car {car.Make} {car.RegistrationNumber}"; } } public string RemoveCar(string regNumber) { if (cars.All(c => c.RegistrationNumber != regNumber)) { return "Car with that registration number, doesn't exist!"; } else { cars.Remove(cars.FirstOrDefault(c => c.RegistrationNumber == regNumber)); return $"Successfully removed {regNumber}"; } } public Car GetCar(string regNumber) { return cars.FirstOrDefault(c => c.RegistrationNumber == regNumber); } public void RemoveSetOfRegistrationNumber(List<string> RegistrationNumbers) { foreach (var regNumber in RegistrationNumbers) { cars.Remove(cars.FirstOrDefault(c => c.RegistrationNumber == regNumber)); } } } }
using System; using System.Collections.Generic; using MinistryPlatform.Translation.Models.DTO; namespace MinistryPlatform.Translation.Repositories.Interfaces { public interface IChildSigninRepository { MpHouseholdParticipantsDto GetChildrenByPhoneNumber(string phoneNumber, bool includeOtherHousehold = true); [Obsolete("This should not be used, and should eventually be removed. It has been replaced by GetChildrenByPhoneNumber.")] List<MpParticipantDto> GetChildrenByHouseholdId(int? householdId, int eventId); List<MpEventParticipantDto> CreateEventParticipants(List<MpEventParticipantDto> mpEventParticipantDtos); [Obsolete("This should not be used, and should eventually be removed. It was only needed when calling GetChildrenByHouseholdId, which is Obsolete.")] int? GetHouseholdIdByPhoneNumber(string phoneNumber); MpHouseholdParticipantsDto GetChildrenByPhoneNumberAndGroupIds(string phoneNumber, List<int> groupIds, bool includeOtherHousehold = true); } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event of type `float`. Inherits from `AtomEvent&lt;float&gt;`. /// </summary> [EditorIcon("atom-icon-cherry")] [CreateAssetMenu(menuName = "Unity Atoms/Events/Float", fileName = "FloatEvent")] public sealed class FloatEvent : AtomEvent<float> { } }
 using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class FSCollisionFocus : MonoBehaviour { public GameObject triggerObject; void Start () { } void Update () { } private void OnCollisionEnter2D (Collision2D other) { if (IsTarget (other.collider) & this.enabled) FS_Manager.AddFocus (gameObject); } private void OnCollisionExit2D (Collision2D other) { if (IsTarget (other.collider) & this.enabled) FS_Manager.RemoveFocus (gameObject); } private void OnCollisionStay2D (Collision2D other) { // if (IsTarget (other.collider) & this.enabled) onCollision.stay.Invoke (); } private void OnTriggerEnter2D (Collider2D other) { // if (IsTarget (other) & this.enabled) FSInputSender.AddFocus (gameObject); } private void OnTriggerExit2D (Collider2D other) { // if (IsTarget (other) & this.enabled) FSInputSender.RemoveFocus (gameObject); } private void OnTriggerStay2D (Collider2D other) { // if (IsTarget (other) & this.enabled) onTrigger.stay.Invoke (); } private bool IsTarget (Collider2D other) { return other.gameObject == triggerObject; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace clinic_project.userinterface { public partial class Deldoctor : UserControl { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\USERS\20102\Clinic_DB.MDF;Integrated Security=True;Connect Timeout=30"); public Deldoctor() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { if (textBox7.Text == "") { MessageBox.Show("Please Enter Doctor's ID"); } else { try { con.Open(); SqlDataAdapter checkdel = new SqlDataAdapter("Select Count(*) From Doctor1 where idDoctor= '" + textBox7.Text + "'", con); DataTable checkdoct = new DataTable(); checkdel.Fill(checkdoct); if (checkdoct.Rows[0][0].ToString() == "1") { SqlDataAdapter ad = new SqlDataAdapter("DELETE FROM Doctor1 WHERE idDoctor= '" + textBox7.Text + "' ", con); ad.SelectCommand.ExecuteNonQuery(); MessageBox.Show("DELETED"); } else { MessageBox.Show("Doctor is not found"); } con.Close(); } catch (Exception ex) { MessageBox.Show("Invalid input"); con.Close(); } } } private void Button2_Click(object sender, EventArgs e) { this.Visible = false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; namespace AsyncClasses.EventArgs { public class GetListCompletedEventArgs : AsyncCompletedEventArgs { #region Public Properties /// <summary> /// Gets the serialized data to be displayed in the grid. /// </summary> public readonly List<object> Data; /// <summary> /// Gets the current instance. /// </summary> public readonly int Instance; #endregion #region Constructors /// <summary> /// Creates a new instance of GetListCompletedEventArgs. /// </summary> /// <param name="data">The data to send.</param> /// <param name="instance">The current instance.</param> /// <param name="e">Exceptions, if any, that occurred during processing.</param> /// <param name="cancelled">Flag indicating whether the operation was cancelled.</param> /// <param name="userState">The user state.</param> public GetListCompletedEventArgs(List<object> data, int instance, Exception e, bool cancelled, object userState) : base(e, cancelled, userState) { Data = data; Instance = instance; //Only throw the exception if we are not cancelling. if (!cancelled) RaiseExceptionIfNecessary(); } #endregion } }
using FeedbackAndSurveyService.CustomException; using FeedbackAndSurveyService.SurveyService.DTO; using FeedbackAndSurveyService.SurveyService.Model.Memento; using System.Collections.Generic; using System.Linq; namespace FeedbackAndSurveyService.SurveyService.Model { public class SurveyResponder : IOriginator<SurveyResponderMemento> { private Jmbg Jmbg { get; } private ICollection<SurveyPermission> Permissions { get; } private ICollection<SurveyResponse> Responses { get; } public SurveyResponder(string jmbg, ICollection<SurveyPermission> permissions) { Jmbg = new Jmbg(jmbg); if (permissions != null) Permissions = permissions; else Permissions = new List<SurveyPermission>(); Responses = new List<SurveyResponse>(); } public void RespondToSurvey(int permissionId, SurveyResponseDTO surveyResponse) { SurveyPermission surveyPermission = Permissions.FirstOrDefault(p => p.Id == permissionId); if (surveyPermission is null) throw new ActionNotPermittedException("Permission id is not valid."); Permissions.Remove(surveyPermission); Responses.Add(new SurveyResponse(surveyPermission, surveyResponse)); } public SurveyResponderMemento GetMemento() { return new SurveyResponderMemento() { Jmbg = Jmbg.Value, Permissions = Permissions, Responses = Responses }; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace com.Sconit.PrintModel.BILL { [Serializable] public partial class PrintBillDetail : PrintBase { #region O/R Mapping Properties [DataMember] public Int32 Id { get; set; } [DataMember] public string BillNo { get; set; } [DataMember] public Int32 ActingBillId { get; set; } [DataMember] public string Item { get; set; } [DataMember] public string ItemDescription { get; set; } [DataMember] public string Uom { get; set; } [DataMember] public Decimal UnitCount { get; set; } [DataMember] public Decimal Qty { get; set; } [DataMember] public string PriceList { get; set; } [DataMember] public Decimal Amount { get; set; } [DataMember] public Decimal UnitPrice { get; set; } [DataMember] public string OrderNo { get; set; } [DataMember] public string IpNo { get; set; } [DataMember] public string ExternalIpNo { get; set; } [DataMember] public string ReceiptNo { get; set; } [DataMember] public string ExternalReceiptNo { get; set; } [DataMember] public Int32 CreateUserId { get; set; } [DataMember] public string CreateUserName { get; set; } [DataMember] public DateTime CreateDate { get; set; } [DataMember] public Int32 LastModifyUserId { get; set; } [DataMember] public string LastModifyUserName { get; set; } [DataMember] public DateTime LastModifyDate { get; set; } [DataMember] public Int32 Version { get; set; } [DataMember] public string Flow { get; set; } [DataMember] public string Currency { get; set; } [DataMember] public bool IsIncludeTax { get; set; } [DataMember] public string Tax { get; set; } [DataMember] public string ReferenceItemCode { get; set; } [DataMember] public string Party { get; set; } [DataMember] public string PartyName { get; set; } [DataMember] public Int16 Type { get; set; } [DataMember] public string LocationFrom { get; set; } [DataMember] public bool IsProvisionalEstimate { get; set; } [DataMember] public DateTime EffectiveDate { get; set; } #endregion } }
using System.Linq; using System.Web.Mvc; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using KendoLanguage.Models; namespace KendoLanguage.Controllers { public class GridController : Controller { public ActionResult Orders_Read([DataSourceRequest] DataSourceRequest request) { var result = Enumerable.Range(0, 50).Select(i => new OrderViewModel { Name = "a" + i, Surname = "b" + i }); return new JsonResult { Data = result.ToDataSourceResult(request), JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = int.MaxValue };;// Json(result, JsonRequestBehavior.AllowGet); } } }
using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Sources { /// <summary> /// Links two Sources. Mainly useful for tracking JHRO cases exported from LotusNotes in a hierarchical tree structure. /// </summary> public class SourceRelationship : Entity { public virtual string ParentSourcePath { get; set; } public virtual Source ParentSource { get; set; } public virtual Source ChildSource { get; set; } public SourceRelationship() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GoToCharaSettingScene : MonoBehaviour { // Start is called before the first frame update void Start() { GetComponent<Button>().onClick.AddListener(() => { //Debug.Log("a"); SceneLoadSvc.GetInstance().LoadSceneWithFX("CharaSetting", () => { CharaSettingSys.instance.Init(); //Debug.Log(CharaSettingSys.instance.equipmentList.Count); }); }); } // Update is called once per frame void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DiscardPile : MonoBehaviour { Stack<CardInfo> _currentDiscardPile; public Stack<CardInfo> CurrentDiscardPile { get { return _currentDiscardPile; } set { _currentDiscardPile = value; } } private void Awake() { _currentDiscardPile = new Stack<CardInfo>(); } public void AddToDiscardPile(CardInfo card) { _currentDiscardPile.Push(card); } public CardInfo TakeFromDiscardPile() { return _currentDiscardPile.Pop(); } public List<CardInfo> TakeAllCardsFromDiscardPile() { List<CardInfo> result = new List<CardInfo>(); int count = _currentDiscardPile.Count; for(int i = 0; i < count; ++i) { result.Add(_currentDiscardPile.Pop()); } return result; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Whathecode.System.Reflection; namespace Whathecode.System { /// <summary> /// A generic helper class to do common <see cref="Enum">Enum</see> operations. /// </summary> /// <typeparam name = "T">The type of the enum.</typeparam> public static class EnumHelper<T> { /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated constants (seperated by comma) /// to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. /// </summary> /// <param name = "value">A string containing the name or value to convert.</param> /// <param name = "ignoreCase">True to ignore case; false to regard case.</param> public static T Parse( string value, bool ignoreCase = false ) { return (T)Enum.Parse( typeof( T ), value, ignoreCase ); } /// <summary> /// Retrieves an enumerator of the constants in a specified enumeration. /// </summary> /// <returns>Enumerable which can be used to enumerate over all constants in the specified enumeration.</returns> public static IEnumerable<T> GetValues() { return from object value in Enum.GetValues( typeof( T ) ) select (T)value; } /// <summary> /// Retrieves an enumerator of all the flagged values in a flags enum. /// </summary> /// <param name = "flags">The value specifying the flags.</param> /// <returns>Enumerable which can be used to enumerate over all flagged values of the passed enum value.</returns> public static IEnumerable<T> GetFlaggedValues( T flags ) { if ( !typeof( T ).GetTypeInfo().IsFlagsEnum() ) { throw new ArgumentException( "The passed enum is not a flags enum.", nameof( flags ) ); } if ( flags == null ) { throw new ArgumentNullException( nameof( flags ) ); } // ReSharper disable PossibleNullReferenceException return from Enum value in Enum.GetValues( typeof( T ) ) where (flags as Enum).HasFlag( value ) select (T)(object)value; // ReSharper restore PossibleNullReferenceException } /// <summary> /// Converts an enum of one type to an enum of another type, using a mapping between both. /// TODO: Support flags enums? /// </summary> /// <typeparam name = "TTargetEnum">The target enum type.</typeparam> /// <param name = "value">The value to map to the other enum type.</param> /// <param name = "conversionMapping">Dictionary which is used to map values from one enum type to the other.</param> /// <returns>The passed value, mapped to the desired target enum type.</returns> public static TTargetEnum Convert<TTargetEnum>( T value, IDictionary<T, TTargetEnum> conversionMapping ) { if ( !typeof( T ).GetTypeInfo().IsEnum || !typeof( TTargetEnum ).GetTypeInfo().IsEnum ) { throw new ArgumentException( "The passed value and target type should be enum types." ); } // ReSharper disable PossibleNullReferenceException // ReSharper disable AssignNullToNotNullAttribute return conversionMapping.First( pair => (value as Enum).HasFlag( pair.Key as Enum ) ).Value; // ReSharper restore AssignNullToNotNullAttribute // ReSharper restore PossibleNullReferenceException } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Inventor; using Autodesk.DesignScript.Geometry; using Autodesk.DesignScript.Interfaces; using Autodesk.DesignScript.Runtime; using Dynamo.Models; using Dynamo.Utilities; using InventorLibrary.GeometryConversion; using InventorServices.Persistence; namespace InventorLibrary.API { [IsVisibleInDynamoLibrary(false)] public class InvEnvironmentManager { #region Internal properties internal Inventor.EnvironmentManager InternalEnvironmentManager { get; set; } //internal InvApplication InternalApplication //{ // get { return InvApplication.ByInvApplication(EnvironmentManagerInstance.Application); } //} //internal InvEnvironment InternalBaseEnvironment //{ // get { return InvEnvironment.ByInvEnvironment(EnvironmentManagerInstance.BaseEnvironment); } //} //internal InvEnvironment InternalEditObjectEnvironment //{ // get { return InvEnvironment.ByInvEnvironment(EnvironmentManagerInstance.EditObjectEnvironment); } //} //internal Inv_Document InternalParent //{ // get { return Inv_Document.ByInv_Document(EnvironmentManagerInstance.Parent); } //} internal InvObjectTypeEnum InternalType { get { return EnvironmentManagerInstance.Type.As<InvObjectTypeEnum>(); } } //Need to add Inventor.Environment //internal Environment InternalOverrideEnvironment { get; set; } #endregion #region Private constructors private InvEnvironmentManager(InvEnvironmentManager invEnvironmentManager) { InternalEnvironmentManager = invEnvironmentManager.InternalEnvironmentManager; } private InvEnvironmentManager(Inventor.EnvironmentManager invEnvironmentManager) { InternalEnvironmentManager = invEnvironmentManager; } #endregion #region Private methods private void InternalGetCurrentEnvironment(out Inventor.Environment environment, out string editTargetId) { EnvironmentManagerInstance.GetCurrentEnvironment(out environment, out editTargetId); } private void InternalSetCurrentEnvironment(Inventor.Environment environment, string editObjectId) { EnvironmentManagerInstance.SetCurrentEnvironment( environment, editObjectId); } #endregion #region Public properties public Inventor.EnvironmentManager EnvironmentManagerInstance { get { return InternalEnvironmentManager; } set { InternalEnvironmentManager = value; } } //public InvApplication Application //{ // get { return InternalApplication; } //} //public InvEnvironment BaseEnvironment //{ // get { return InternalBaseEnvironment; } //} //public InvEnvironment EditObjectEnvironment //{ // get { return InternalEditObjectEnvironment; } //} //public Inv_Document Parent //{ // get { return InternalParent; } //} public InvObjectTypeEnum Type { get { return InternalType; } } //public InvEnvironment OverrideEnvironment //{ // get { return InternalOverrideEnvironment; } // set { InternalOverrideEnvironment = value; } //} #endregion #region Public static constructors public static InvEnvironmentManager ByInvEnvironmentManager(InvEnvironmentManager invEnvironmentManager) { return new InvEnvironmentManager(invEnvironmentManager); } public static InvEnvironmentManager ByInvEnvironmentManager(Inventor.EnvironmentManager invEnvironmentManager) { return new InvEnvironmentManager(invEnvironmentManager); } #endregion #region Public methods public void GetCurrentEnvironment(out Inventor.Environment environment, out string editTargetId) { InternalGetCurrentEnvironment(out environment, out editTargetId); } public void SetCurrentEnvironment(Inventor.Environment environment, string editObjectId) { InternalSetCurrentEnvironment( environment, editObjectId); } #endregion } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Marten.Schema; using Marten.Schema.Sequences; using Marten.Services; using Shouldly; using StructureMap; using Xunit; namespace Marten.Testing.Schema.Sequences { public class HiloSequenceTests { private readonly IContainer _container = Container.For<DevelopmentModeRegistry>(); private readonly HiloSequence theSequence; private IConnectionFactory _connectionFactory; public HiloSequenceTests() { _container.GetInstance<DocumentCleaner>().CompletelyRemoveAll(); var sql = SchemaBuilder.GetText("mt_hilo"); _connectionFactory = _container.GetInstance<IConnectionFactory>(); _connectionFactory.RunSql(sql); theSequence = new HiloSequence(_connectionFactory, "foo", new HiloSettings()); } [Fact] public void default_values() { theSequence.CurrentHi.ShouldBe(-1); theSequence.Increment.ShouldBe(1); theSequence.MaxLo.ShouldBe(1000); } [Fact] public void should_advance_initial_case() { theSequence.ShouldAdvanceHi().ShouldBeTrue(); } [Fact] public void advance_to_next_hi_from_initial_state() { theSequence.AdvanceToNextHi(); theSequence.CurrentLo.ShouldBe(1); theSequence.CurrentHi.ShouldBe(0); } [Fact] public void advance_to_next_hi_several_times() { theSequence.AdvanceToNextHi(); theSequence.AdvanceToNextHi(); theSequence.CurrentHi.ShouldBe(1); theSequence.AdvanceToNextHi(); theSequence.CurrentHi.ShouldBe(2); theSequence.AdvanceToNextHi(); theSequence.CurrentHi.ShouldBe(3); } [Fact] public void advance_value_from_initial_state() { // Gotta do this at least once theSequence.AdvanceToNextHi(); theSequence.AdvanceValue().ShouldBe(1); theSequence.AdvanceValue().ShouldBe(2); theSequence.AdvanceValue().ShouldBe(3); theSequence.AdvanceValue().ShouldBe(4); theSequence.AdvanceValue().ShouldBe(5); } [Fact] public void read_from_a_single_thread_from_0_to_5000() { for (var i = 0; i < 5000; i++) { theSequence.NextLong().ShouldBe(i + 1); } } private Task<List<int>> startThread() { return Task.Factory.StartNew(() => { var list = new List<int>(); for (int i = 0; i < 1000; i++) { list.Add(theSequence.NextInt()); } return list; }); } [Fact] public void is_thread_safe() { var tasks = new Task<List<int>>[] {startThread(), startThread(), startThread(), startThread(), startThread(), startThread()}; Task.WaitAll(tasks); var all = tasks.SelectMany(x => x.Result).ToArray(); all.GroupBy(x => x).Any(x => x.Count() > 1).ShouldBeFalse(); all.Distinct().Count().ShouldBe(tasks.Length * 1000); } } }
namespace BashSoft { using BashSoft.IO; public class BashSoftProgram { public static void Main(string[] args) { //IOManager.TraverseDirectory(@"D:\Vsichki Programi\Softuni\C# Advanced 2\BashSoft\StoryMode\BashSoft"); // StudentsRepository.InitializeData(); // StudentsRepository.GetAllStudentsFromCourse("Unity"); //StudentsRepository.GetStudentsScoresFromCourse("Unity", "Ivan"); //Tester.CompareContent // (@"D:\Vsichki Programi\Softuni\C# Advanced 2\BashSoft\StoryMode\BashSoft\Files\test2.txt", // @"D:\Vsichki Programi\Softuni\C# Advanced 2\BashSoft\StoryMode\BashSoft\Files\test3.txt"); //IOManager.CreateDirectoryInCurrentFolder("pesho"); //IOManager.TraverseDirectory(2); //IOManager.ChangeCurrentDirectoryAbsolute(@"C:\Windows"); //IOManager.TraverseDirectory(1); //IOManager.TraverseDirectory(20); //Tester.CompareContent(@"D:\Vsichki Programi\Softuni\C# Advanced 2\BashSoft\StoryMode\BashSoft\Files\actual.txt", // @"D:\Vsichki Programi\Softuni\C# Advanced 2\BashSoft\StoryMode\BashSoft\Files\expected.txt"); //IOManager.CreateDirectoryInCurrentFolder("*2"); for (int i = 0; i < 2; i++) { IOManager.ChangeCurrentDirectoryRelative(".."); } InputReader.StartReadingCommands(); } } }
using Microsoft.EntityFrameworkCore; using RecipesFinal.Data.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Migrations; using RecipesFinal.Controllers; namespace RecipesFinal.Data.Context { public class RecipeDatacontext : DbContext { public RecipeDatacontext(DbContextOptions<RecipeDatacontext> options) : base(options) { } //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) //{ // optionsBuilder.ReplaceService<IMigrationCommandExecutor, myExecutor>(); //} //protected override void OnModelCreating(ModelBuilder modelBuilder) //{ // modelBuilder.Entity<Ingredient>().se //} public DbSet<Recipe> recipes { get; set; } public DbSet<Ingredient> Ingredients { get; set; } public DbSet<Customer> customers { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<Zone> Zones { get; set; } public DbSet<Woreda> Woredas { get; set; } public DbSet<Kebele> kebeles { get; set; } public DbSet<Nationality> Nationality { get; set; } public DbSet<CustomerDetail> customerDetails { get; set; } } }
using BLL; using Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinFormUI { public partial class TaskForm : MetroFramework.Forms.MetroForm { WorkBusiness _workBLL; ProjectBusiness _proBLL; StateBusiness _stateBLL; EmployeeBusiness _empBLL; public TaskForm() { InitializeComponent(); _workBLL = new WorkBusiness(LoginForm.EmployeeId()); _proBLL = new ProjectBusiness(LoginForm.EmployeeId()); _stateBLL = new StateBusiness(LoginForm.EmployeeId()); _empBLL = new EmployeeBusiness(LoginForm.EmployeeId()); } private void TaskForm_Load(object sender, EventArgs e) { try { // DataGridView ' e liste yükleniyor. // dgvTaskList.DataSource = _workBLL.GetAll(); // Comboboxlara listeler yükleniyor. //cmbProjectName.DataSource = _proBLL.GetAll() // .Where(o => o.Employees.Any(t => t.ID == LoginForm.EmployeeId().ID)).ToList(); //cmbProjectName.DisplayMember = "Name"; //cmbProjectName.ValueMember = "ID"; //cmbProjectName.DataSource = _proBLL.GetAll().ToList(); cmbState.DataSource = (from s in _stateBLL.GetAll() select s).ToList(); cmbState.DisplayMember = "StateName"; cmbState.ValueMember = "ID"; var r =(from p in _proBLL.GetAll() .Where(o => o.Employees.Any( t => t.ID == LoginForm.EmployeeId().ID)) select p).ToList(); cmbProjectName.DisplayMember = "Name"; cmbProjectName.ValueMember = "ID"; cmbJobAnalyst.DataSource = (from em in _empBLL.GetAll() where em.RoleID == 3 select em).ToList(); cmbJobAnalyst.DisplayMember = "FullName"; cmbJobAnalyst.ValueMember = "ID"; cmbSoftwareDeveloper.DataSource = (from em in _empBLL.GetAll() where em.RoleID == 4 select em).ToList(); cmbSoftwareDeveloper.DisplayMember = "FullName"; cmbSoftwareDeveloper.ValueMember = "ID"; cmbTester.DataSource = (from em in _empBLL.GetAll() where em.RoleID == 5 select em).ToList(); cmbTester.DisplayMember = "FullName"; cmbTester.ValueMember = "ID"; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnAddJobAnalist_Click(object sender, EventArgs e) { lstEmployee.Items.Add(_empBLL.Get((int)cmbJobAnalyst.SelectedValue)); } private void btnAddSoftwareDevelepor_Click(object sender, EventArgs e) { lstEmployee.Items.Add(_empBLL.Get((int)cmbSoftwareDeveloper.SelectedValue)); } private void btnAddTester_Click(object sender, EventArgs e) { lstEmployee.Items.Add(_empBLL.Get((int)cmbTester.SelectedValue)); } private void btnDeleteEmployee_Click(object sender, EventArgs e) { lstEmployee.Items.RemoveAt(lstEmployee.SelectedIndex); } private void btnSave_Click(object sender, EventArgs e) { Work work = new Work(); work.Name = txtTaskName.Text; work.Description = txtDescription.Text; work.StartDate = Convert.ToDateTime(dtpStartDate.Text); work.EndDate = Convert.ToDateTime(dtpEndDate.Text); work.ProjectID = Convert.ToInt32(cmbProjectName.SelectedValue); work.StateID = Convert.ToInt32(cmbProjectName.SelectedValue); work.Employees = ((List<Employee>)lstEmployee.DataSource); _workBLL.Add(work); } private void btnUpdate_Click(object sender, EventArgs e) { _workBLL = new WorkBusiness(LoginForm.EmployeeId()); } } }
using System.Reflection; using System.Web.Compilation; using System.Web.Mvc; using SimpleInjector; using SimpleInjector.Integration.Web; using SimpleInjector.Integration.Web.Mvc; using Timeclock.Services; using TimeClock.Data; using TimeClock.Web.Services; namespace TimeClock.Web { internal static class SimpleInject { internal static void Application_Start() { // Create the container as usual. var container = new Container(); container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); // Register your types, for instance: container.Register<TimeClockContext, TimeClockContext>(Lifestyle.Scoped); container.Register<IEmployeeService, EmployeeService>(Lifestyle.Scoped); container.Register<ITimeService, TimeService>(Lifestyle.Scoped); container.Register<IReportService, ReportService>(Lifestyle.Scoped); // This is an extension method from the integration package. container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); // This is an extension method from the integration package as well. container.RegisterMvcIntegratedFilterProvider(); container.Verify(); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParallelSerializer { public class TaskTreeNode { public object SyncRoot { get; } = new object(); public List<TaskTreeNode> Children { get; set; } public ISerializationTask Task { get; set; } public TaskTreeNode NextSibling { get; set; } public TaskTreeNode Parent { get; set; } public TaskTreeNode() { Children = new List<TaskTreeNode>(); } public int GetLength() { int result = Task.SerializationResult?.Length ?? 0; foreach (var taskTreeNode in Children) { result += taskTreeNode.GetLength(); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using System.Text; using System.Threading.Tasks; namespace HW7_PlaneShooting { class CBoss // { public Point pt = new Point(0, 0); public Rectangle rec; public int dirX = 0; public int dirY = 10; Bitmap bmp; public bool isLive = true; Image im; public int life = 1000; public CBoss(Image img, int seed, int a, int b) //建構子 { Random rd = new Random(seed); bmp = new Bitmap(img); bmp.MakeTransparent(Color.White); this.pt.X = rd.Next(img.Width, 400-img.Width); this.pt.Y = 0; rec = new Rectangle(pt.X, pt.Y ,img.Width, img.Height); this.dirX = b; this.dirY = 0; im = img; life = a; } public void Draw(Graphics g) //畫圖 { if (isLive) { Graphics dc = Graphics.FromImage(bmp); g.DrawImage(bmp, pt); dc.Dispose(); } } public void Move() //左右移動 { pt.X += dirX; rec.X = pt.X; rec.Y = pt.Y; if (pt.X > 400-im.Width) { dirX = -dirX; pt.X = 400 - im.Width; rec.X = pt.X; rec.Y = pt.Y; } else if (pt.X < im.Width-100) { dirX = -dirX; pt.X = im.Width-100; rec.X = pt.X; rec.Y = pt.Y; } } public bool Checkdie(CBullet bm) //檢查是否被射死 { if (rec.IntersectsWith(bm.rec)) { life -= bm.damage; //生命減子彈的攻擊數 if (life <= 0) { bm.isLive = false; isLive = false; return true; } bm.isLive = false; } return false; } } }
using System.Collections.Generic; using NHibernate; using NHibernate.Criterion; using Profiling2.Domain.Contracts.Queries; using Profiling2.Domain.Contracts.Queries.Search; using Profiling2.Domain.Prf.Persons; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries { public class PersonRelationshipTypeNameQuery : NHibernateQuery, IPersonRelationshipTypeNameQuery { public IList<PersonRelationshipType> GetResults(string term) { //var qo = Session.QueryOver<PersonRelationshipType>(); //if (!string.IsNullOrEmpty(term)) // return qo.Where(Restrictions.On<PersonRelationshipType>(x => x.PersonRelationshipTypeName).IsLike("%" + term + "%")) // .Take(50) // .List<PersonRelationshipType>(); //else // return new List<PersonRelationshipType>(); if (!string.IsNullOrEmpty(term)) return Session.CreateCriteria<PersonRelationshipType>() .Add(Expression.Sql("PersonRelationshipTypeName LIKE ? COLLATE Latin1_general_CI_AI", "%" + term + "%", NHibernateUtil.String)) .AddOrder(Order.Asc("PersonRelationshipTypeName")) .SetMaxResults(50) .List<PersonRelationshipType>(); else return new List<PersonRelationshipType>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace WebAutomationFramework.Pages { public class TestBases { public IWebDriver driver; String url = "https://easyjet.com/en/"; [SetUp] public void Setup() { var options = new ChromeOptions(); options.AddArguments("--test-type"); options.AddArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling --disable-infobars --enable-automation --start-maximized"); options.AddUserProfilePreference("credentials_enable_service", false); options.AddUserProfilePreference("profile.password_manager_enabled", false); driver = new ChromeDriver(options); driver.Navigate().GoToUrl(url); } //[OneTimeTearDown] //public void TestTearDown() //{ // driver.Quit(); //} } }
namespace rm.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class User { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public User() { Ridges = new HashSet<Ridge>(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int idUser { get; set; } [StringLength(45)] public string Name { get; set; } [StringLength(45)] public string Surname { get; set; } [StringLength(45)] public string Mail { get; set; } [StringLength(45)] public string Login { get; set; } [StringLength(45)] public string Password { get; set; } public int Role { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Ridge> Ridges { get; set; } public virtual Role Role1 { get; set; } } }
using System; using System.Collections; using System.Net.Sockets; using System.Reflection; using Phenix.Business; using Phenix.Core.Cache; using Phenix.Core.Log; using Phenix.Core.Mapping; using Phenix.Core.Net; using Phenix.Core.SyncCollections; using Phenix.Services.Contract; namespace Phenix.Services.Client.Library { internal class DataPortalProxy : Csla.DataPortalClient.IDataPortalProxy { #region 属性 private Csla.Server.IDataPortalServer _service; private Csla.Server.IDataPortalServer Service { get { if (_service == null) { if (NetConfig.ProxyType == ProxyType.Embedded) { _service = new Csla.Server.DataPortal(); return _service; } RemotingHelper.RegisterClientChannel(); _service = (Csla.Server.IDataPortalServer)RemotingHelper.CreateRemoteObjectProxy( typeof(Csla.Server.IDataPortalServer), ServicesInfo.DATA_PORTAL_URI); } return _service; } } private readonly SynchronizedDictionary<string, Csla.Server.IDataPortalServer> _serviceCluster = new SynchronizedDictionary<string, Csla.Server.IDataPortalServer>(StringComparer.Ordinal); #region IDataPortalProxy 成员 public bool IsServerRemote { get { return NetConfig.ProxyType != ProxyType.Embedded; } } #endregion #endregion #region 方法 private void InvalidateCache() { _service = null; _serviceCluster.Clear(); } private Csla.Server.IDataPortalServer GetService(Type objectType, object criteria) { if (NetConfig.ProxyType == ProxyType.Embedded) return Service; Type rootType = objectType; ICriterions criterions = criteria as ICriterions; if (criterions != null) { IBusinessObject masterBusiness = criterions.Master as IBusinessObject; if (masterBusiness != null && masterBusiness.Root != null) rootType = masterBusiness.Root.GetType(); } ServicesClusterAttribute clusterAttribute = ServicesClusterAttribute.Fetch(rootType); string servicesClusterAddress = NetConfig.GetServicesClusterAddress(clusterAttribute); if (String.IsNullOrEmpty(servicesClusterAddress)) return Service; return _serviceCluster.GetValue(clusterAttribute.Key, () => { RemotingHelper.RegisterClientChannel(); return (Csla.Server.IDataPortalServer)RemotingHelper.CreateRemoteObjectProxy( typeof(Csla.Server.IDataPortalServer), servicesClusterAddress, ServicesInfo.DATA_PORTAL_URI); }, true); } #region IDataPortalProxy 成员 public Csla.Server.DataPortalResult Create(Type objectType, object criteria, Csla.Server.DataPortalContext context) { NetConfig.InitializeSwitch(); do { try { return GetService(objectType, criteria).Create(objectType, criteria, context); } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public Csla.Server.DataPortalResult Fetch(Type objectType, object criteria, Csla.Server.DataPortalContext context) { if (objectType == null) throw new ArgumentNullException("objectType"); DateTime dt = DateTime.Now; Csla.Server.DataPortalResult result; DateTime? actionTime; object obj = ObjectCache.Find(objectType, criteria, out actionTime); if (obj != null) result = new Csla.Server.DataPortalResult(obj); else { NetConfig.InitializeSwitch(); do { try { result = GetService(objectType, criteria).Fetch(objectType, criteria, context); break; } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); if (actionTime != null) ObjectCache.Add(criteria, result.ReturnObject, actionTime.Value); } //跟踪日志 if (EventLog.MustSaveLog) { ICriterions criterions = criteria as ICriterions; EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + objectType.FullName + (criterions != null && criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) + " take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString() + " millisecond," + " count = " + (result.ReturnObject is IList ? ((IList)result.ReturnObject).Count.ToString() : result.ReturnObject is IBusinessObject ? ((IBusinessObject)result.ReturnObject).SelfFetched ? "1" : "0" : result.ReturnObject != null ? "1" : "0")); } return result; } public Csla.Server.DataPortalResult Update(object obj, Csla.Server.DataPortalContext context) { NetConfig.InitializeSwitch(); do { try { return GetService(obj.GetType(), null).Update(obj, context); } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public Csla.Server.DataPortalResult Delete(Type objectType, object criteria, Csla.Server.DataPortalContext context) { NetConfig.InitializeSwitch(); do { try { return GetService(objectType, criteria).Delete(objectType, criteria, context); } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace UI { class MyFormL5 : Form { public MyFormL5(string[,] data,string title,string path) : base() { Text = title; Size = new Size(600, 400); StartPosition = FormStartPosition.CenterScreen; FormBorderStyle = FormBorderStyle.FixedSingle; MaximizeBox = false; Font = new Font("Times New Roman", 11, FontStyle.Italic | FontStyle.Bold); Label pict = new Label(); pict.SetBounds(5, 5, 400, 300); pict.BorderStyle = BorderStyle.FixedSingle; Controls.Add(pict); ListBox lists = new ListBox(); lists.Size = new Size(110, 80); lists.Left = pict.Right + 5; lists.Top = pict.Top; for(int k = 0; k < data.GetLength(1); k++) { lists.Items.Add(data[0, k]); } lists.SelectedIndexChanged += (x, y) => { int index = lists.SelectedIndex; pict.Image = Image.FromFile(path + data[1, index]); }; Controls.Add(lists); Button button = new Button(); button.Text = "OK"; button.Left = lists.Left; button.Top = lists.Bottom -button.Height; button.Width = lists.Width; button.Height = 25; button.Font = lists.Font; button.Click += (x, y) => { Application.Exit(); }; Controls.Add(button); lists.SetSelected(lists.Items.Count - 1, true); } } class Listing5 { [STAThread] public static void ListingMain05() { string[,] data = {{ "Wolf", "Fox", "Bear", "Raccoon" }, { "Wolf.jpg", "Fox.jpg", "Bear.jpg", "Raccoon.jpg" } }; string title = "Discovery"; string path = "D:/Programming/GitHubProject/Studying/UI/"; MyFormL5 window = new MyFormL5(data, title, path); Application.Run(window); } } }
using Alabo.Cloud.Contracts.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.Contracts.Domain.Repositories { public class ContractRepository : RepositoryMongo<Contract, ObjectId>, IContractRepository { public ContractRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
namespace ServiceQuotes.Application.Filters { public class GetCustomerAddressFilter : SearchStringFilter { public string City { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using EQS.AccessControl.Domain.Entities; using EQS.AccessControl.Domain.Interfaces.Repository.Base; namespace EQS.AccessControl.Domain.Interfaces.Repository { public interface IRoleRepository : IBaseRepository<Role>, IDisposable { List<Person> GetPeopleAssociatedToRoleId(int id); } }
using ApiTemplate.Core.Entities.Users; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace ApiTemplate.Data.Configurations.Users { public class AppUserLoginConfiguration :IEntityTypeConfiguration<AppUserLogin> { public void Configure(EntityTypeBuilder<AppUserLogin> builder) { } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Hermana : MonoBehaviour { public Camera cameraHer; public static int conteoH; public GameObject globoH, PuertaHermana; public Text TexHermana; private bool visibleH; private string actual; private bool esperando; void start() { conteoH= 0; visibleH = true; actual = "!!!!! "; esperando = true; } // Update is called once per frame void Update () { switch (conteoH) { case 1: { actual = "!!!!!"; } break; case 2: { actual = " ¿Que qué pasa? "; } break; case 3: { actual = "El problema es que hoy me prometieron ir al parque de diversiones,"; } break; case 4: { actual = "pero mi hermano tiene que ir al banco y además quiere comprar unos audífonos, y mi mamá quiere arreglarse el cabello…"; } break; case 5: { actual = "Ya no me van a llevar a nada..."; Mensajes.visible = false; Mensajes.conteo = 8; } break; case 6: { visibleH = true; actual = "¡Bien Jugador! Es una buena idea. Le contaré a mamá."; GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("hermanita"); } break; } } void FixedUpdate() { Vector3 mouse = Input.mousePosition; if (Input.GetMouseButtonDown(0) && (HizoClick(mouse)))//Lee si se hizo click { esperando = true; if (conteoH == 0 && esperando) { conteoH = 1; esperando = false; } if (conteoH == 1 && esperando) { if (!visibleH) visibleH = true; conteoH = 2; esperando = false; } if (conteoH == 2 && esperando) { conteoH = 3; esperando = false; } if (conteoH == 3 && esperando) { conteoH = 4; esperando = false; } if (conteoH == 4 && esperando) { conteoH = 5; Mensajes.conteo = 7; esperando = false; } if (conteoH == 5 && esperando) { conteoH = 1; esperando = false; visibleH = false; } } if (visibleH) { globoH.GetComponent<SpriteRenderer>().enabled = true; TexHermana.gameObject.GetComponent<Text>().text = actual; } else { globoH.GetComponent<SpriteRenderer>().enabled = false; TexHermana.gameObject.GetComponent<Text>().text = ""; } } bool HizoClick(Vector3 mouse) { if ((cameraHer.ScreenToWorldPoint(mouse).x > (this.GetComponent<Renderer>().bounds.min.x)) && (cameraHer.ScreenToWorldPoint(mouse).x < (this.GetComponent<Renderer>().bounds.max.x)) && (cameraHer.ScreenToWorldPoint(mouse).y > (this.GetComponent<Renderer>().bounds.min.y)) && (cameraHer.ScreenToWorldPoint(mouse).y < (this.GetComponent<Renderer>().bounds.max.y))) return true; else return false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class DeathScript : MonoBehaviour { public GameObject EnnemyAudio; public AudioClip DeathSound; public int Hp = 100; private bool dying = false; private Animator animator; // Use this for initialization void Start () { animator = GetComponent<Animator> (); } // Update is called once per frame void Update () { if (dying) { float x, y; x = GetComponent<CapsuleCollider> ().center.x; y = GetComponent<CapsuleCollider> ().center.y; GetComponent<CapsuleCollider>().center = new Vector3(x, y, animator.GetFloat("ColCurve")); } } public void Death(int damages) { Debug.Log ("HIT"); if (Hp <= 0) { Debug.Log ("KILL"); Die (); } else { Debug.Log("Damage"); Hp -= damages; EnnemyAudio.GetComponent<AudioSource> ().PlayOneShot (DeathSound); } } public void Die() { dying = true; GetComponent<Rigidbody> ().isKinematic = false; EnnemyAudio.GetComponent<AudioSource> ().Stop (); EnnemyAudio.GetComponent<AudioSource> ().PlayOneShot (DeathSound); animator.SetTrigger ("dead"); animator.SetBool ("attack", false); GetComponent<IAParasite> ().enabled = false; GetComponent<NavMeshAgent> ().enabled = false; //GetComponent<CapsuleCollider> ().enabled = false; Destroy (gameObject, 10f); } public bool IsDying() { return this.dying; } public void ActivationIsKinematic() { GetComponent<Rigidbody> ().isKinematic = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreehouseDefense { interface IMappable { MapLocation Location { get; } //properties in an interface don't have implementation but have to determine whether getter or setter is part of the interface } interface IMovavable { void Move(); // } interface IInvader : IMappable, IMovavable //an interface defines what public members a class should have. have to also see what public members an invader should have. Took all public members from invader and pasted in IInvader. Interfaces don't have constructors so removed constructor from iinvader { //interfaces only define public members so don't have to have public access modifier stated. Also don't have to have virtual or abstract modifiers stated bool HasScored { get; } //invader has scored if the path to the is equal to the path's length int Health { get; }//allows different types of invaders to have different levels of initial health //making health property abstract means that healthproperty must be overriden in subclasses. abstract properties canthave implementation bool IsNeutralized { get; } bool IsActive { get; } void DecreaseHealth(int factor); //virtual is polymorphic. tell c# that this is just one possible implementation of the decreased health method } }
using RusticiSoftware.HostedEngine.Client; using System.Xml; namespace HackerFerret.ScormHelper.Model { public class RegistrationResult { public RegistrationResult() { } public string Title { get; set; } public string Complete { get; set; } public string Success { get; set; } public string Score { get; set; } public string Attempts { get; set; } public string ViewTime { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Animator))] public class TreasureChest : Interactable { public Item contents; public Signal raiseItem; public Inventory playerInventory; private Animator anim; public override void DialogInteract() { if (CanInteract()) { OpenChest(); } else { UnloadChest(); } base.DialogInteract(); } public override void AnimationInteract() { base.AnimationInteract(); anim.SetBool("open", true); contextClue.Raise(); SetPlayerMove(false); } void Start() { anim = GetComponent<Animator>(); } void OpenChest() { // Add the item dialog dialog = contents.itemDescription; // Set player state player.SetState(PlayerState.interact); // Add contents to player inventory and as current item playerInventory.AddItem(contents); playerInventory.currentItem = contents; // Raise signal to animate player raiseItem.Raise(); // Raise sign to close context clue contextClue.Raise(); // Set chest to opened SetHasBeenAnimated(true); } void UnloadChest() { // Turn off player animation player.SetAnimatorBool("receive_item", false); // Set player state player.SetState(PlayerState.idle); // Set current item to empty playerInventory.currentItem = null; // Raise signal to player to nullify item sprite raiseItem.Raise(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public Vector3 touchPosition; public Vector3 pixelTouchPosition; public Camera camera; public GameManager gm; public GameObject gemEffect, blueGemEffect; public GameObject[] skins; public int gemsCollected; public bool frozen; public ObstacleSpawner obstacleSpawner; public GameObject frozenScreenEffect; public ParticleSystem snow; // Use this for initialization void Start () { Instantiate(skins[PlayerPrefs.GetInt("skin")],GetComponent<Transform>()); } // Update is called once per frame void Update () { if (gm.isStarted) { //brackeysMove(); debugMove(); } } public void brackeysMove(){ if(Input.touchCount>0){ Touch touch = Input.GetTouch(0); touchPosition = camera.ScreenToWorldPoint(touch.position); pixelTouchPosition = touch.position; touchPosition.z = 0f; transform.position = Vector2.Lerp(transform.position, touchPosition, 0.5f); ; } } public void debugMove(){ if (Input.GetMouseButton(0)) { touchPosition = camera.ScreenToWorldPoint(Input.mousePosition); touchPosition.z = 0f; transform.position = Vector2.Lerp(transform.position, touchPosition, 0.5f); ; } } void OnCollisionEnter2D(Collision2D collision) { //Debug.Log("found collision"); if(collision.gameObject.CompareTag("block")){ //Debug.Log("collision is a block"); gm.endGame(); } } public IEnumerator freezeTime(float dur){ snow.Play(); frozenScreenEffect.SetActive(true); frozenScreenEffect.GetComponent<FrozenTimeCanvas>().startTime = Time.time; obstacleSpawner.gameObject.SetActive(false); GameObject[] obstacles = GameObject.FindGameObjectsWithTag("block"); foreach (GameObject obstacle in obstacles){ if (obstacle != null) { if (obstacle.gameObject.GetComponent<Obstacle>() != null) { obstacle.gameObject.GetComponent<Obstacle>().frozen = true; } //if (obstacle.gameObject.GetComponent<Animator>() != null) //{ // obstacle.gameObject.GetComponent<Animator>().enabled = false; //} //if (obstacle.gameObject.GetComponent<Rotate>() != null) //{ // obstacle.gameObject.GetComponent<Rotate>().enabled = false; //} else { Debug.Log("There is no animator on " + obstacle.name); } } } yield return new WaitForSeconds(dur); foreach (GameObject obstacle in obstacles) { if (obstacle != null) { if (obstacle.gameObject.GetComponent<Obstacle>() != null) { obstacle.gameObject.GetComponent<Obstacle>().frozen = false; } //if (obstacle.gameObject.GetComponent<Animator>() != null) //{ // obstacle.gameObject.GetComponent<Animator>().enabled = true; //} //if (obstacle.gameObject.GetComponent<Rotate>() != null) //{ // obstacle.gameObject.GetComponent<Rotate>().enabled = true; //} } } obstacleSpawner.gameObject.SetActive(true); frozenScreenEffect.SetActive(false); snow.Stop(); } public void clearFrozen(){ frozenScreenEffect.SetActive(false); snow.Stop(); } void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Crystal")) { //Debug.Log("collision is a block"); Destroy(collision.gameObject); gemsCollected++; if (PlayerPrefs.GetInt("isVibrate") < 1) { Vibration.Vibrate(20); } Instantiate(gemEffect, transform.position, Quaternion.identity); } if (collision.gameObject.CompareTag("BlueCrystal")) { Destroy(collision.gameObject); gemsCollected+=10; if (PlayerPrefs.GetInt("isVibrate") < 1) { Vibration.Vibrate(20); } Instantiate(blueGemEffect, transform.position, Quaternion.identity); } if (collision.gameObject.CompareTag("block")) { gm.endGame(); } if(collision.gameObject.CompareTag("freezeTime")){ foreach (GameObject i in GameObject.FindGameObjectsWithTag("freezeTime")) { Destroy(i);//this makes sure you don't bump into two freeze times } StartCoroutine(freezeTime(10)); obstacleSpawner.timeToSpawn += 10; } } }
using System; namespace Game { /// <summary> /// Handles menu inputs and outputs /// </summary> public class Menu { /// <summary> /// Property that contains instance of game /// </summary> public Game game; /// <summary> /// Property that contains instance of highscores /// </summary> public HighScore highScore; /// <summary> /// Create menu /// </summary> /// <param name="rows"></param> /// <param name="columns"></param> public Menu(int rows, int columns) { UseMenu(rows, columns); } /// <summary> /// Print menu and handle inputs for menu /// </summary> /// <param name="rows"></param> /// <param name="columns"></param> public void UseMenu(int rows, int columns) { //Variables to handle the input bool isValidInput = false; string inputStr; //Main menu Console.Clear(); Console.WriteLine("1. New game"); Console.WriteLine("2. High scores"); Console.WriteLine("3. Instructions"); Console.WriteLine("4. Credits"); Console.WriteLine("5. Quit"); //While the player does not give a valid input while(!isValidInput) { //Ask for input inputStr = Console.ReadLine(); ConsoleKeyInfo input; //Validate and choose input of player switch (inputStr) { case "1" : game = new Game(rows,columns); isValidInput = true; break; case "2" : Console.Clear(); highScore = new HighScore(rows, columns, 0, 1); input = Console.ReadKey(); UseMenu(rows, columns); break; case "3" : Console.Clear(); Console.Write("The rules are:\n"); Console.Write("You can move using 'WASD' or the " + "directional keys(▲, ►, ▼, ◄). "); Console.Write("Each time you move, you lose 1 hp.\n"); Console.Write("There are walls(█) you must dodge so " + "you can go to your objective\n"); Console.Write("Enemies move towards you, they move " + "after you moved twice. "); Console.Write("Minions(☼) deal 5 damage, " + "and bosses(☺) deal 10 damage.\n"); Console.Write("There are also powerups that heal you," + " small ones(♠) heal you by 4 hp, "); Console.Write("medium ones(♣) heal you by 8 hp and " + "big ones(♥) heal you by 16 hp. \n"); Console.Write("To pass each level you must reach" + " de exit(֍).\n"); Console.Write("Your objective is simple go as far" + " as you can! By the way this is you (☻)\n"); input = Console.ReadKey(); UseMenu(rows, columns); break; case "4" : Console.Clear(); Console.Write("Game done by:\n"); Console.Write("Pedro Coutinho 21905323\n"); Console.Write("Nelson Salvador 21904295\n"); Console.Write("Miguel Martinho 21901530\n"); input = Console.ReadKey(); UseMenu(rows, columns); break; case "5" : System.Environment.Exit(0); isValidInput = true; break; default: Console.WriteLine("Invalid Input"); break; } inputStr = ""; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Types; using UnityEngine.UI; using TMPro; using System; public class UIManager : Singleton<UIManager> { public Sprite[] sprites; //[HideInInspector] public EnemyColor chosenColor; public Enemy chosenEnemy; private Color col; public Image enemyImage; [HideInInspector] public int chosenEnemyNumber; public TextMeshProUGUI timeLeftText; public TextMeshProUGUI scoreText; public GameObject TrustPanel; public Texture2D cursor; protected override void Awake() { base.Awake(); } private void Start() { ChooseEnemy(); ChooseColor(); StartCoroutine(HidePanel(1.8f)); } public void ChooseEnemy() { chosenEnemyNumber = UnityEngine.Random.Range(0, sprites.Length); enemyImage.sprite = sprites[chosenEnemyNumber]; } public void ChooseColor() { int randInt = UnityEngine.Random.Range(0, 3); chosenColor = (EnemyColor)randInt; switch (chosenColor) { case EnemyColor.Magenta: col = Color.magenta; break; case EnemyColor.Green: col = Color.green; break; case EnemyColor.Cyan: col = Color.cyan; break; default: break; } enemyImage.color = col; } private void Update() { timeLeftText.text = $"Time:\n{(int)GameManager.Instance.time}"; scoreText.text = $"Score:\n{(int)GameManager.Instance.score}"; } public IEnumerator HidePanel(float time) { yield return new WaitForSeconds(time); TrustPanel.SetActive(false); } }
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; using CrossCutting; using Cs_Gerencial.Aplicacao.Interfaces; using Cs_Gerencial.Dominio.Entities; using Cs_Gerencial.PeriodoDatas; namespace Cs_Gerencial.Windows { /// <summary> /// Interaction logic for CadastroLancamentos.xaml /// </summary> public partial class CadastroLancamentos : Window { private readonly IAppServicoAtribuicoes _appServicoAtribuicoes = BootStrap.Container.GetInstance<IAppServicoAtribuicoes>(); private readonly IAppServicoPlanos _appServicoPlanos = BootStrap.Container.GetInstance<IAppServicoPlanos>(); private readonly IAppServicoFornecedores _appServicoFornecedores = BootStrap.Container.GetInstance<IAppServicoFornecedores>(); private readonly IAppServicoBancos _appServicoBancos = BootStrap.Container.GetInstance<IAppServicoBancos>(); private readonly IAppServicoContas _appServicoContas = BootStrap.Container.GetInstance<IAppServicoContas>(); private readonly IAppServicoLogSistema _appServicoLogSistema = BootStrap.Container.GetInstance<IAppServicoLogSistema>(); Contas contasDepositoSelecionada; Contas contasReceitaSelecionada; Contas contasDespesasSelecionada; string acaoAtual = string.Empty; List<Contas> listaDeposito = new List<Contas>(); List<Contas> listaReceita = new List<Contas>(); List<Contas> listaDespesas = new List<Contas>(); public List<Contas> listaTodos = new List<Contas>(); LogSistema logSistema; Usuario _usuario; public CadastroLancamentos(Usuario usuario) { _usuario = usuario; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { CarregamentoInicial(); } private void CarregamentoInicial() { dpConsultaInicio.SelectedDate = DateTime.Now.Date; dpConsultaFim.SelectedDate = DateTime.Now.Date; var atribuicoes = _appServicoAtribuicoes.GetAll().OrderBy(p => p.Codigo); cmbAtribuicaoDeposito.ItemsSource = atribuicoes; cmbAtribuicaoDeposito.DisplayMemberPath = "Descricao"; cmbAtribuicaoDeposito.SelectedValuePath = "Codigo"; cmbAtribuicaoReceita.ItemsSource = atribuicoes; cmbAtribuicaoReceita.DisplayMemberPath = "Descricao"; cmbAtribuicaoReceita.SelectedValuePath = "Codigo"; cmbPlanoContasDespesas.ItemsSource = _appServicoPlanos.GetAll().OrderBy(p => p.Descricao); cmbPlanoContasDespesas.DisplayMemberPath = "Descricao"; cmbPlanoContasDespesas.SelectedValuePath = "PlanoId"; cmbBancoDespesas.ItemsSource = _appServicoBancos.GetAll().OrderBy(p => p.Nome); cmbBancoDespesas.DisplayMemberPath = "Nome"; cmbBancoDespesas.SelectedValuePath = "BancosId"; cmbFornecedorDespesas.ItemsSource = _appServicoFornecedores.GetAll().OrderBy(p => p.NomeFantasia); cmbFornecedorDespesas.DisplayMemberPath = "NomeFantasia"; cmbFornecedorDespesas.SelectedValuePath = "FornecedorId"; List<string> formaPagamento = new List<string>(); formaPagamento.Add("DINHEIRO"); formaPagamento.Add("CHEQUE"); formaPagamento.Add("CARTÃO"); formaPagamento.Add("BOLETO"); formaPagamento.Add("FATURADO"); cmbFormaPgDespesas.ItemsSource = formaPagamento; } private void DigitarSomenteNumeros(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key >= 34 && key <= 43 || key >= 74 && key <= 83 || key == 2 || key == 3 || key == 23 || key == 25 || key == 32); } private void DigitarSemNumeros(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key == 2 || key == 3 || key == 23 || key == 25 || key == 32); } private void DigitarSomenteNumerosEmReaisComVirgual(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key >= 34 && key <= 43 || key >= 74 && key <= 83 || key == 2 || key == 3 || key == 23 || key == 25 || key == 32 || key == 142 || key == 88); } private void DigitarSomenteLetras(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key == 2 || key == 3 || key == 23 || key == 25 || key == 32 || key >= 44 && key <= 69); } private void txtProtocoloDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtReciboDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtMatriculaDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtFlsInicioDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtFlsFimDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtValorDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { if (txtValorDeposito.SelectionLength == txtValorDeposito.Text.Length) { txtValorDeposito.Text = ""; } if (!txtValorDeposito.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorDeposito.Text.IndexOf(","); if (indexVirgula + 3 == txtValorDeposito.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void txtProtocoloReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtReciboReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtMatriculaReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtFlsInicio_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtFlsFimReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtNumeroReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtCodigoDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtCodigoReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); } private void txtValorReceita_PreviewKeyDown(object sender, KeyEventArgs e) { if (txtValorReceita.SelectionLength == txtValorReceita.Text.Length) { txtValorReceita.Text = ""; } if (!txtValorReceita.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorReceita.Text.IndexOf(","); if (indexVirgula + 3 == txtValorReceita.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void txtValorDespesas_PreviewKeyDown(object sender, KeyEventArgs e) { if (txtValorDespesas.SelectionLength == txtValorDespesas.Text.Length) { txtValorDespesas.Text = ""; } if (!txtValorDespesas.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorDespesas.Text.IndexOf(","); if (indexVirgula + 3 == txtValorDespesas.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void ClickDoBotaoAdicionarDeposito() { gridDadosDeposito.IsEnabled = true; btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; btnCancelarDeposito.IsEnabled = true; btnSalvarDeposito.IsEnabled = true; btnAdicionarDeposito.IsEnabled = false; dataGridDeposito.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemReceita.IsEnabled = false; tabItemDespesas.IsEnabled = false; LimparCamposDeposito(); } private void ClickDoBotaoAlterarDeposito() { gridDadosDeposito.IsEnabled = true; btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; btnCancelarDeposito.IsEnabled = true; btnSalvarDeposito.IsEnabled = true; btnAdicionarDeposito.IsEnabled = false; dataGridDeposito.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemReceita.IsEnabled = false; tabItemDespesas.IsEnabled = false; } private void ClickDoBotaoExcluirDeposito() { if (contasDepositoSelecionada != null) { if (MessageBox.Show("Deseja realmente excluir este registro?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { _appServicoContas.Remove(contasDepositoSelecionada); SalvarLogSistema("Excluiu o registro Descrição = " + contasDepositoSelecionada.Descricao); } catch (Exception ex) { MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } finally { listaDeposito.Remove(contasDepositoSelecionada); dataGridDeposito.Items.Refresh(); if (listaDeposito.Count < 1) { btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; } } } } } private void ClickDoBotaoCancelarDeposito() { gridDadosDeposito.IsEnabled = false; if (contasDepositoSelecionada != null) { btnAlterarDeposito.IsEnabled = true; btnExcluirDeposito.IsEnabled = true; } else { btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; } btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; btnCancelarDeposito.IsEnabled = false; btnSalvarDeposito.IsEnabled = true; btnAdicionarDeposito.IsEnabled = true; tabItemReceita.IsEnabled = true; tabItemDespesas.IsEnabled = true; dataGridDeposito.IsEnabled = true; CarregarCamposDaLinhaSelecionadaDeposito(); } private void ClickDoBotaoSalvarDeposito() { Contas contaSalvar; try { if (acaoAtual == "adicionarDeposito") { contaSalvar = new Contas(); } else { contaSalvar = _appServicoContas.GetById(contasDepositoSelecionada.ContaId); } if (dpDataDeposito.SelectedDate == null) { MessageBox.Show("Informe a data do Depósito.", "Data do Depósito", MessageBoxButton.OK, MessageBoxImage.Exclamation); dpDataDeposito.Focus(); return; } if (txtDescricaoDeposito.Text == "") { MessageBox.Show("Informe a Descrição.", "Descrição", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtDescricaoDeposito.Focus(); return; } if (txtValorDeposito.Text == "") { MessageBox.Show("Informe o Valor.", "Valor", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtValorDeposito.Focus(); return; } if (cmbAtribuicaoDeposito.SelectedIndex < 0) { MessageBox.Show("Informe a Atribuição.", "Atribuição", MessageBoxButton.OK, MessageBoxImage.Exclamation); cmbAtribuicaoDeposito.Focus(); return; } if (txtCodigoDeposito.Text == "") { MessageBox.Show("Informe o Código.", "Código", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtCodigoDeposito.Focus(); return; } contaSalvar.DataMovimento = dpDataDeposito.SelectedDate.Value; contaSalvar.Atribuicao = ((Atribuicoes)cmbAtribuicaoDeposito.SelectedItem).Codigo; if (txtProtocoloDeposito.Text != "") contaSalvar.Protocolo = Convert.ToInt32(txtProtocoloDeposito.Text); if (txtReciboDeposito.Text != "") contaSalvar.Recibo = Convert.ToInt32(txtReciboDeposito.Text); if (txtMatriculaDeposito.Text != "") contaSalvar.Matricula = txtMatriculaDeposito.Text; contaSalvar.Livro = txtLivroDeposito.Text; if (txtFlsInicioDeposito.Text != "") contaSalvar.FolhaInicial = Convert.ToInt32(txtFlsInicioDeposito.Text); if (txtFlsFimDeposito.Text != "") contaSalvar.FolhaFinal = Convert.ToInt32(txtFlsFimDeposito.Text); contaSalvar.Descricao = txtDescricaoDeposito.Text; contaSalvar.Total = Convert.ToDecimal(txtValorDeposito.Text); contaSalvar.Codigo = Convert.ToInt32(txtCodigoDeposito.Text); contaSalvar.Tipo = "DP"; if (acaoAtual == "adicionarDeposito") { _appServicoContas.Add(contaSalvar); SalvarLogSistema("Adicionou o registro Id = " + contaSalvar.ContaId); } else { _appServicoContas.Update(contaSalvar); SalvarLogSistema("Alterou o registro Id = " + contaSalvar.ContaId); } gridDadosDeposito.IsEnabled = false; btnCancelarDeposito.IsEnabled = false; btnSalvarDeposito.IsEnabled = false; btnAdicionarDeposito.IsEnabled = true; if (acaoAtual == "adicionarDeposito") LimparCamposDeposito(); tabItemReceita.IsEnabled = true; tabItemDespesas.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; dataGridDeposito.IsEnabled = true; if (acaoAtual == "adicionarDeposito") { listaDeposito = _appServicoContas.ConsultaPorPeriodo(contaSalvar.DataMovimento, contaSalvar.DataMovimento).Where(p => p.Tipo == "DP").ToList(); } dataGridDeposito.ItemsSource = listaDeposito; dataGridDeposito.SelectedItem = contaSalvar; dataGridDeposito.Items.Refresh(); MessageBox.Show("Registro salvo com sucesso!", "Registro Salvo", MessageBoxButton.OK, MessageBoxImage.Information); if (dataGridDeposito.SelectedIndex > -1) { btnAlterarDeposito.IsEnabled = true; btnExcluirDeposito.IsEnabled = true; } else { btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar salvar o registro. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); gridDadosDeposito.IsEnabled = false; btnCancelarDeposito.IsEnabled = false; btnSalvarDeposito.IsEnabled = false; btnAdicionarDeposito.IsEnabled = true; dataGridDeposito.IsEnabled = true; tabItemReceita.IsEnabled = true; tabItemDespesas.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; LimparCamposDeposito(); } } private void ClickDoBotaoAdicionarReceita() { gridDadosReceita.IsEnabled = true; btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; btnCancelarReceita.IsEnabled = true; btnSalvarReceita.IsEnabled = true; btnAdicionarReceita.IsEnabled = false; dataGridReceita.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemDeposito.IsEnabled = false; tabItemDespesas.IsEnabled = false; LimparCamposReceita(); } private void ClickDoBotaoAlterarReceita() { gridDadosReceita.IsEnabled = true; btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; btnCancelarReceita.IsEnabled = true; btnSalvarReceita.IsEnabled = true; btnAdicionarReceita.IsEnabled = false; dataGridReceita.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemDeposito.IsEnabled = false; tabItemDespesas.IsEnabled = false; } private void ClickDoBotaoExcluirReceita() { if (contasReceitaSelecionada != null) { if (MessageBox.Show("Deseja realmente excluir este registro?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { _appServicoContas.Remove(contasReceitaSelecionada); SalvarLogSistema("Excluiu o registro Descrição = " + contasReceitaSelecionada.Descricao); } catch (Exception ex) { MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } finally { listaReceita.Remove(contasReceitaSelecionada); dataGridReceita.Items.Refresh(); if (listaReceita.Count < 1) { btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; } } } } } private void ClickDoBotaoCancelarReceita() { gridDadosReceita.IsEnabled = false; if (contasReceitaSelecionada != null) { btnAlterarReceita.IsEnabled = true; btnExcluirReceita.IsEnabled = true; } else { btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; } btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; btnCancelarReceita.IsEnabled = false; btnSalvarReceita.IsEnabled = true; btnAdicionarReceita.IsEnabled = true; tabItemDeposito.IsEnabled = true; tabItemDespesas.IsEnabled = true; dataGridReceita.IsEnabled = true; CarregarCamposDaLinhaSelecionadaReceita(); } private void ClickDoBotaoSalvarReceita() { Contas contaSalvar; try { if (acaoAtual == "adicionarReceita") { contaSalvar = new Contas(); } else { contaSalvar = _appServicoContas.GetById(contasReceitaSelecionada.ContaId); } if (dpDataReceita.SelectedDate == null) { MessageBox.Show("Informe a data do Receita.", "Data do Receita", MessageBoxButton.OK, MessageBoxImage.Exclamation); dpDataReceita.Focus(); return; } if (txtDescricaoReceita.Text == "") { MessageBox.Show("Informe a Descrição.", "Descrição", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtDescricaoReceita.Focus(); return; } if (txtValorReceita.Text == "") { MessageBox.Show("Informe o Valor.", "Valor", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtValorReceita.Focus(); return; } if (cmbAtribuicaoReceita.SelectedIndex < 0) { MessageBox.Show("Informe a Atribuição.", "Atribuição", MessageBoxButton.OK, MessageBoxImage.Exclamation); cmbAtribuicaoReceita.Focus(); return; } if (txtCodigoReceita.Text == "") { MessageBox.Show("Informe o Código.", "Código", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtCodigoReceita.Focus(); return; } contaSalvar.DataMovimento = dpDataReceita.SelectedDate.Value; contaSalvar.DataPagamento = dpDataReceita.SelectedDate.Value; contaSalvar.Atribuicao = ((Atribuicoes)cmbAtribuicaoReceita.SelectedItem).Codigo; if (txtProtocoloReceita.Text != "") contaSalvar.Protocolo = Convert.ToInt32(txtProtocoloReceita.Text); if (txtReciboReceita.Text != "") contaSalvar.Recibo = Convert.ToInt32(txtReciboReceita.Text); if (txtMatriculaReceita.Text != "") contaSalvar.Matricula = txtMatriculaReceita.Text; contaSalvar.Livro = txtLivroReceita.Text; if (txtFlsInicioReceita.Text != "") contaSalvar.FolhaInicial = Convert.ToInt32(txtFlsInicioReceita.Text); if (txtFlsFimReceita.Text != "") contaSalvar.FolhaFinal = Convert.ToInt32(txtFlsFimReceita.Text); contaSalvar.Descricao = txtDescricaoReceita.Text; contaSalvar.Total = Convert.ToDecimal(txtValorReceita.Text); contaSalvar.Codigo = Convert.ToInt32(txtCodigoReceita.Text); if (txtSerieReceita.Text != "") contaSalvar.Letra = txtSerieReceita.Text; if (txtNumeroReceita.Text != "") contaSalvar.Numero = Convert.ToInt32(txtNumeroReceita.Text); if (txtAleatorioReceita.Text != "") contaSalvar.Aleatorio = txtAleatorioReceita.Text; contaSalvar.Tipo = "RE"; if (acaoAtual == "adicionarReceita") { _appServicoContas.Add(contaSalvar); SalvarLogSistema("Adicionou o registro Id = " + contaSalvar.ContaId); } else { _appServicoContas.Update(contaSalvar); SalvarLogSistema("Alterou o registro Id = " + contaSalvar.ContaId); } gridDadosReceita.IsEnabled = false; btnCancelarReceita.IsEnabled = false; btnSalvarReceita.IsEnabled = false; btnAdicionarReceita.IsEnabled = true; if (acaoAtual == "adicionarReceita") LimparCamposReceita(); tabItemDeposito.IsEnabled = true; tabItemDespesas.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; dataGridReceita.IsEnabled = true; if (acaoAtual == "adicionarReceita") { listaReceita = _appServicoContas.ConsultaPorPeriodo(contaSalvar.DataMovimento, contaSalvar.DataMovimento).Where(p => p.Tipo == "RE").ToList(); } dataGridReceita.ItemsSource = listaReceita; dataGridReceita.SelectedItem = contaSalvar; dataGridReceita.Items.Refresh(); MessageBox.Show("Registro salvo com sucesso!", "Registro Salvo", MessageBoxButton.OK, MessageBoxImage.Information); if (dataGridReceita.SelectedIndex > -1) { btnAlterarReceita.IsEnabled = true; btnExcluirReceita.IsEnabled = true; } else { btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar salvar o registro. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); gridDadosReceita.IsEnabled = false; btnCancelarReceita.IsEnabled = false; btnSalvarReceita.IsEnabled = false; btnAdicionarReceita.IsEnabled = true; dataGridReceita.IsEnabled = true; tabItemDeposito.IsEnabled = true; tabItemDespesas.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; LimparCamposReceita(); } } private void ClickDoBotaoAdicionarDespesas() { gridDadosDespesas.IsEnabled = true; btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; btnCancelarDespesas.IsEnabled = true; btnSalvarDespesas.IsEnabled = true; btnAdicionarDespesas.IsEnabled = false; dataGridDespesas.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemDeposito.IsEnabled = false; tabItemReceita.IsEnabled = false; LimparCamposDespesas(); } private void ClickDoBotaoAlterarDespesas() { gridDadosDespesas.IsEnabled = true; btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; btnCancelarDespesas.IsEnabled = true; btnSalvarDespesas.IsEnabled = true; btnAdicionarDespesas.IsEnabled = false; dataGridDespesas.IsEnabled = false; btnConsultar.IsEnabled = false; btnSincronizar.IsEnabled = false; tabItemDeposito.IsEnabled = false; tabItemReceita.IsEnabled = false; } private void ClickDoBotaoExcluirDespesas() { if (contasDespesasSelecionada != null) { if (MessageBox.Show("Deseja realmente excluir este registro?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { _appServicoContas.Remove(contasDespesasSelecionada); SalvarLogSistema("Excluiu o registro Descrição = " + contasDespesasSelecionada.Descricao); } catch (Exception ex) { MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } finally { listaDespesas.Remove(contasDespesasSelecionada); dataGridDespesas.Items.Refresh(); if (listaDespesas.Count < 1) { btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; } } } } } private void ClickDoBotaoCancelarDespesas() { gridDadosDespesas.IsEnabled = false; if (contasDespesasSelecionada != null) { btnAlterarDespesas.IsEnabled = true; btnExcluirDespesas.IsEnabled = true; } else { btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; } btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; btnCancelarDespesas.IsEnabled = false; btnSalvarDespesas.IsEnabled = true; btnAdicionarDespesas.IsEnabled = true; tabItemDeposito.IsEnabled = true; tabItemReceita.IsEnabled = true; dataGridDespesas.IsEnabled = true; CarregarCamposDaLinhaSelecionadaDespesas(); } private void ClickDoBotaoSalvarDespesas() { Contas contaSalvar; try { if (acaoAtual == "adicionarDespesas") { contaSalvar = new Contas(); } else { contaSalvar = _appServicoContas.GetById(contasDespesasSelecionada.ContaId); } if (dpDataVencimentoDespesas.SelectedDate == null) { MessageBox.Show("Informe a data do Vencimento.", "Data do Vencimento", MessageBoxButton.OK, MessageBoxImage.Exclamation); dpDataVencimentoDespesas.Focus(); return; } if (dpDataPagamentoDespesas.SelectedDate == null) { MessageBox.Show("Informe a data do Pagamento.", "Data do Pagamento", MessageBoxButton.OK, MessageBoxImage.Exclamation); dpDataPagamentoDespesas.Focus(); return; } if (txtDescricaoDespesas.Text == "") { MessageBox.Show("Informe a Descrição.", "Descrição", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtDescricaoDespesas.Focus(); return; } if (txtValorDespesas.Text == "") { MessageBox.Show("Informe o Valor.", "Valor", MessageBoxButton.OK, MessageBoxImage.Exclamation); txtValorDespesas.Focus(); return; } contaSalvar.DataMovimento = dpDataVencimentoDespesas.SelectedDate.Value; contaSalvar.DataPagamento = dpDataPagamentoDespesas.SelectedDate.Value; if (cmbPlanoContasDespesas.SelectedIndex > -1) { var plano = (Planos)cmbPlanoContasDespesas.SelectedItem; contaSalvar.IdPlano = plano.PlanoId; contaSalvar.Plano = plano.Descricao; } if (cmbFornecedorDespesas.SelectedIndex > -1) { var fornecedor = (Fornecedores)cmbFornecedorDespesas.SelectedItem; contaSalvar.IdFornecedor = fornecedor.FornecedorId; contaSalvar.Fornecedor = fornecedor.NomeFantasia; } if (cmbBancoDespesas.SelectedIndex > -1) { var banco = (Bancos)cmbBancoDespesas.SelectedItem; contaSalvar.IdBanco = banco.BancosId; contaSalvar.Banco = banco.Nome; } if (cmbFormaPgDespesas.SelectedIndex > -1) contaSalvar.FormaPagamento = cmbFormaPgDespesas.Text; if (txtNumeroChequeDespesas.Text != "") contaSalvar.NumeroCheque = txtNumeroChequeDespesas.Text; if (txtDocumentoDespesas.Text != "") contaSalvar.Documento = txtDocumentoDespesas.Text; contaSalvar.Descricao = txtDescricaoDespesas.Text; contaSalvar.Total = Convert.ToDecimal(txtValorDespesas.Text); contaSalvar.Tipo = "DE"; if (acaoAtual == "adicionarDespesas") { _appServicoContas.Add(contaSalvar); SalvarLogSistema("Adicionou o registro id = " + contaSalvar.ContaId); } else { _appServicoContas.Update(contaSalvar); SalvarLogSistema("Alterou o registro id = " + contaSalvar.ContaId); } gridDadosDespesas.IsEnabled = false; btnCancelarDespesas.IsEnabled = false; btnSalvarDespesas.IsEnabled = false; btnAdicionarDespesas.IsEnabled = true; if (acaoAtual == "adicionarDespesas") LimparCamposDespesas(); tabItemReceita.IsEnabled = true; tabItemDeposito.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; dataGridDespesas.IsEnabled = true; if (acaoAtual == "adicionarDespesas") { listaDespesas = _appServicoContas.ConsultaPorPeriodo(contaSalvar.DataMovimento, contaSalvar.DataMovimento).Where(p => p.Tipo == "DE").ToList(); } dataGridDespesas.ItemsSource = listaDespesas; dataGridDespesas.SelectedItem = contaSalvar; dataGridDespesas.Items.Refresh(); MessageBox.Show("Registro salvo com sucesso!", "Registro Salvo", MessageBoxButton.OK, MessageBoxImage.Information); if (dataGridDespesas.SelectedIndex > -1) { btnAlterarDespesas.IsEnabled = true; btnExcluirDespesas.IsEnabled = true; } else { btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar salvar o registro. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); gridDadosDespesas.IsEnabled = false; btnCancelarDespesas.IsEnabled = false; btnSalvarDespesas.IsEnabled = false; btnAdicionarDespesas.IsEnabled = true; dataGridDespesas.IsEnabled = true; tabItemReceita.IsEnabled = true; tabItemDeposito.IsEnabled = true; btnConsultar.IsEnabled = true; btnSincronizar.IsEnabled = true; LimparCamposDespesas(); } } private void dataGridDeposito_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { contasDepositoSelecionada = (Contas)dataGridDeposito.SelectedItem; CarregarCamposDaLinhaSelecionadaDeposito(); } private void dataGridReceita_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { contasReceitaSelecionada = (Contas)dataGridReceita.SelectedItem; CarregarCamposDaLinhaSelecionadaReceita(); } private void dataGridDespesas_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { contasDespesasSelecionada = (Contas)dataGridDespesas.SelectedItem; CarregarCamposDaLinhaSelecionadaDespesas(); } private void btnAdicionarDeposito_Click(object sender, RoutedEventArgs e) { acaoAtual = "adicionarDeposito"; ClickDoBotaoAdicionarDeposito(); } private void btnAlterarDeposito_Click(object sender, RoutedEventArgs e) { acaoAtual = "alterarDeposito"; ClickDoBotaoAlterarDeposito(); } private void btnExcluirDeposito_Click(object sender, RoutedEventArgs e) { acaoAtual = "excluirDeposito"; ClickDoBotaoExcluirDeposito(); } private void btnCancelarDeposito_Click(object sender, RoutedEventArgs e) { acaoAtual = "cancelarDeposito"; ClickDoBotaoCancelarDeposito(); } private void btnSalvarDeposito_Click(object sender, RoutedEventArgs e) { ClickDoBotaoSalvarDeposito(); } private void btnAdicionarReceita_Click(object sender, RoutedEventArgs e) { acaoAtual = "adicionarReceita"; ClickDoBotaoAdicionarReceita(); } private void btnAlterarReceita_Click(object sender, RoutedEventArgs e) { acaoAtual = "alterarReceita"; ClickDoBotaoAlterarReceita(); } private void btnExcluirReceita_Click(object sender, RoutedEventArgs e) { acaoAtual = "excluirReceita"; ClickDoBotaoExcluirReceita(); } private void btnCancelarReceita_Click(object sender, RoutedEventArgs e) { acaoAtual = "cancelarReceita"; ClickDoBotaoCancelarReceita(); } private void btnSalvarReceita_Click(object sender, RoutedEventArgs e) { ClickDoBotaoSalvarReceita(); } private void txtSerieReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteLetras(sender, e); } private void btnAdicionarDespesas_Click(object sender, RoutedEventArgs e) { acaoAtual = "adicionarDespesas"; ClickDoBotaoAdicionarDespesas(); } private void btnAlterarDespesas_Click(object sender, RoutedEventArgs e) { acaoAtual = "alterarDespesas"; ClickDoBotaoAlterarDespesas(); } private void btnExcluirDespesas_Click(object sender, RoutedEventArgs e) { acaoAtual = "excluirDespesas"; ClickDoBotaoExcluirDespesas(); } private void btnCancelarDespesas_Click(object sender, RoutedEventArgs e) { acaoAtual = "cancelarDespesas"; ClickDoBotaoCancelarDespesas(); } private void btnSalvarDespesas_Click(object sender, RoutedEventArgs e) { ClickDoBotaoSalvarDespesas(); } private void LimparCamposDeposito() { dpDataDeposito.SelectedDate = null; cmbAtribuicaoDeposito.SelectedIndex = -1; txtProtocoloDeposito.Text = ""; txtReciboDeposito.Text = ""; txtMatriculaDeposito.Text = ""; txtLivroDeposito.Text = ""; txtFlsInicioDeposito.Text = ""; txtFlsFimDeposito.Text = ""; txtDescricaoDeposito.Text = ""; txtCodigoDeposito.Text = ""; txtValorDeposito.Text = ""; } private void LimparCamposReceita() { dpDataReceita.SelectedDate = null; cmbAtribuicaoReceita.SelectedIndex = -1; txtProtocoloReceita.Text = ""; txtReciboReceita.Text = ""; txtMatriculaReceita.Text = ""; txtLivroReceita.Text = ""; txtFlsInicioReceita.Text = ""; txtFlsFimReceita.Text = ""; txtDescricaoReceita.Text = ""; txtCodigoReceita.Text = ""; txtValorReceita.Text = ""; txtSerieReceita.Text = ""; txtNumeroReceita.Text = ""; txtAleatorioReceita.Text = ""; } private void LimparCamposDespesas() { dpDataVencimentoDespesas.SelectedDate = null; cmbPlanoContasDespesas.SelectedIndex = -1; cmbFornecedorDespesas.SelectedIndex = -1; cmbBancoDespesas.SelectedIndex = -1; cmbFormaPgDespesas.SelectedIndex = -1; txtNumeroChequeDespesas.Text = ""; dpDataPagamentoDespesas.SelectedDate = null; txtDocumentoDespesas.Text = ""; txtDescricaoDespesas.Text = ""; txtValorDespesas.Text = ""; } private void CarregarCamposDaLinhaSelecionadaDeposito() { try { if (contasDepositoSelecionada != null) { dpDataDeposito.SelectedDate = contasDepositoSelecionada.DataMovimento; cmbAtribuicaoDeposito.SelectedValue = contasDepositoSelecionada.Atribuicao; if (contasDepositoSelecionada.Protocolo > 0) txtProtocoloDeposito.Text = contasDepositoSelecionada.Protocolo.ToString(); else txtProtocoloDeposito.Text = ""; if (contasDepositoSelecionada.Recibo > 0) txtReciboDeposito.Text = contasDepositoSelecionada.Recibo.ToString(); else txtReciboDeposito.Text = ""; if (contasDepositoSelecionada.Matricula != null) txtMatriculaDeposito.Text = contasDepositoSelecionada.Matricula; else txtMatriculaDeposito.Text = ""; txtLivroDeposito.Text = contasDepositoSelecionada.Livro; if (contasDepositoSelecionada.FolhaInicial > 0) txtFlsInicioDeposito.Text = contasDepositoSelecionada.FolhaInicial.ToString(); else txtFlsInicioDeposito.Text = ""; if (contasDepositoSelecionada.FolhaFinal > 0) txtFlsFimDeposito.Text = contasDepositoSelecionada.FolhaFinal.ToString(); else txtFlsFimDeposito.Text = ""; txtDescricaoDeposito.Text = contasDepositoSelecionada.Descricao; if (contasDepositoSelecionada.Codigo > 0) txtCodigoDeposito.Text = contasDepositoSelecionada.Codigo.ToString(); else txtCodigoDeposito.Text = ""; txtValorDeposito.Text = string.Format("{0:n2}", contasDepositoSelecionada.Total); } else { LimparCamposDeposito(); } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar carregar os campos. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } } private void CarregarCamposDaLinhaSelecionadaReceita() { try { if (contasReceitaSelecionada != null) { dpDataReceita.SelectedDate = contasReceitaSelecionada.DataMovimento; cmbAtribuicaoReceita.SelectedValue = contasReceitaSelecionada.Atribuicao; if (contasReceitaSelecionada.Protocolo > 0) txtProtocoloReceita.Text = contasReceitaSelecionada.Protocolo.ToString(); else txtProtocoloReceita.Text = ""; if (contasReceitaSelecionada.Recibo > 0) txtReciboReceita.Text = contasReceitaSelecionada.Recibo.ToString(); else txtReciboReceita.Text = ""; if (contasReceitaSelecionada.Matricula != null) txtMatriculaReceita.Text = contasReceitaSelecionada.Matricula; else txtMatriculaReceita.Text = ""; txtLivroReceita.Text = contasReceitaSelecionada.Livro; if (contasReceitaSelecionada.FolhaInicial > 0) txtFlsInicioReceita.Text = contasReceitaSelecionada.FolhaInicial.ToString(); else txtFlsInicioReceita.Text = ""; if (contasReceitaSelecionada.FolhaFinal > 0) txtFlsFimReceita.Text = contasReceitaSelecionada.FolhaFinal.ToString(); else txtFlsFimReceita.Text = ""; txtDescricaoReceita.Text = contasReceitaSelecionada.Descricao; if (contasReceitaSelecionada.Codigo > 0) txtCodigoReceita.Text = contasReceitaSelecionada.Codigo.ToString(); else txtCodigoReceita.Text = ""; if (contasReceitaSelecionada.Letra != null) txtSerieReceita.Text = contasReceitaSelecionada.Letra; else txtSerieReceita.Text = ""; if (contasReceitaSelecionada.Numero > 0) txtNumeroReceita.Text = contasReceitaSelecionada.Numero.ToString(); else txtNumeroReceita.Text = ""; if (contasReceitaSelecionada.Aleatorio != null) txtAleatorioReceita.Text = contasReceitaSelecionada.Aleatorio; else txtAleatorioReceita.Text = ""; txtValorReceita.Text = string.Format("{0:n2}", contasReceitaSelecionada.Total); } else { LimparCamposReceita(); } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar carregar os campos. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } } private void CarregarCamposDaLinhaSelecionadaDespesas() { try { if (contasDespesasSelecionada != null) { dpDataVencimentoDespesas.SelectedDate = contasDespesasSelecionada.DataMovimento; dpDataPagamentoDespesas.SelectedDate = contasDespesasSelecionada.DataPagamento; cmbPlanoContasDespesas.SelectedValue = contasDespesasSelecionada.IdPlano; cmbFornecedorDespesas.SelectedValue = contasDespesasSelecionada.IdFornecedor; cmbBancoDespesas.SelectedValue = contasDespesasSelecionada.IdBanco; cmbFormaPgDespesas.Text = contasDespesasSelecionada.FormaPagamento; txtNumeroChequeDespesas.Text = contasDespesasSelecionada.NumeroCheque; txtDescricaoDespesas.Text = contasDespesasSelecionada.Descricao; txtDocumentoDespesas.Text = contasDespesasSelecionada.Documento; txtValorDespesas.Text = string.Format("{0:n2}", contasDespesasSelecionada.Total); } else { LimparCamposDespesas(); } } catch (Exception ex) { MessageBox.Show("Ocorreu um erro ao tentar carregar os campos. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnConsultar_Click(object sender, RoutedEventArgs e) { if (dpConsultaInicio.SelectedDate == null) { MessageBox.Show("Informe a Data Inicial.", "Data Inicial", MessageBoxButton.OK, MessageBoxImage.Stop); return; } if (dpConsultaFim.SelectedDate == null) { MessageBox.Show("Informe a Data Final.", "Data Final", MessageBoxButton.OK, MessageBoxImage.Stop); return; } try { listaTodos = _appServicoContas.ConsultaPorPeriodo(dpConsultaInicio.SelectedDate.Value, dpConsultaFim.SelectedDate.Value).ToList(); CarregarDataGridDeposito(); CarregarDataGridReceita(); CarregarDataGridDespesas(); } catch (Exception ex) { MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Error); } } public void CarregarDataGridDeposito() { listaDeposito = listaTodos.Where(p => p.Tipo == "DP").ToList(); dataGridDeposito.ItemsSource = listaDeposito; dataGridDeposito.Items.Refresh(); if (listaDeposito.Count > 0) { btnAlterarDeposito.IsEnabled = true; btnExcluirDeposito.IsEnabled = true; dataGridDeposito.SelectedIndex = 0; } else { btnAlterarDeposito.IsEnabled = false; btnExcluirDeposito.IsEnabled = false; } } public void CarregarDataGridReceita() { listaReceita = listaTodos.Where(p => p.Tipo == "RE").ToList(); dataGridReceita.ItemsSource = listaReceita; dataGridReceita.Items.Refresh(); if (listaReceita.Count > 0) { btnAlterarReceita.IsEnabled = true; btnExcluirReceita.IsEnabled = true; dataGridReceita.SelectedIndex = 0; } else { btnAlterarReceita.IsEnabled = false; btnExcluirReceita.IsEnabled = false; } } public void CarregarDataGridDespesas() { listaDespesas = listaTodos.Where(p => p.Tipo == "DE").ToList(); dataGridDespesas.ItemsSource = listaDespesas; dataGridDespesas.Items.Refresh(); if (listaDespesas.Count > 0) { btnAlterarDespesas.IsEnabled = true; btnExcluirDespesas.IsEnabled = true; dataGridDespesas.SelectedIndex = 0; } else { btnAlterarDespesas.IsEnabled = false; btnExcluirDespesas.IsEnabled = false; } } private void cmbFormaPgDespesas_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbFormaPgDespesas.SelectedIndex == 1) { txtNumeroChequeDespesas.IsEnabled = true; } else { txtNumeroChequeDespesas.IsEnabled = false; txtNumeroChequeDespesas.Text = ""; } } private void PassarDeUmCoponenteParaOutro(object sender, KeyEventArgs e) { var uie = e.OriginalSource as UIElement; if (e.Key == Key.Enter) { e.Handled = true; uie.MoveFocus( new TraversalRequest( FocusNavigationDirection.Next)); } } private void gridDadosDeposito_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void gridDadosReceita_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void gridDadosDespesas_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtValorDeposito_LostFocus(object sender, RoutedEventArgs e) { if (txtValorDeposito.Text != "" && txtValorDeposito.Text != ",") txtValorDeposito.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorDeposito.Text)); else txtValorDeposito.Text = ""; } private void txtValorReceita_LostFocus(object sender, RoutedEventArgs e) { if (txtValorReceita.Text != "" && txtValorReceita.Text != ",") txtValorReceita.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorReceita.Text)); else txtValorReceita.Text = ""; } private void txtValorDespesas_LostFocus(object sender, RoutedEventArgs e) { if (txtValorDespesas.Text != "" && txtValorDespesas.Text != ",") txtValorDespesas.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorDespesas.Text)); else txtValorDespesas.Text = ""; } private void SalvarLogSistema(string descricao) { logSistema = new LogSistema(); logSistema.Data = DateTime.Now.Date; logSistema.Descricao = descricao; logSistema.Hora = DateTime.Now.ToLongTimeString(); logSistema.Tela = "Cadastro de Lançamentos"; logSistema.IdUsuario = _usuario.UsuarioId; logSistema.Usuario = _usuario.NomeUsuario; logSistema.Maquina = Environment.MachineName.ToString(); _appServicoLogSistema.Add(logSistema); } private void dpConsultaInicio_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (dpConsultaInicio.SelectedDate > DateTime.Now.Date) { dpConsultaInicio.SelectedDate = DateTime.Now.Date; } dpConsultaFim.SelectedDate = dpConsultaInicio.SelectedDate; if (dpConsultaInicio.SelectedDate > dpConsultaFim.SelectedDate) { dpConsultaFim.SelectedDate = dpConsultaInicio.SelectedDate; } } private void dpConsultaFim_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (dpConsultaInicio.SelectedDate != null) { if (dpConsultaInicio.SelectedDate > dpConsultaFim.SelectedDate) { dpConsultaFim.SelectedDate = dpConsultaInicio.SelectedDate; } } else { dpConsultaInicio.SelectedDate = dpConsultaFim.SelectedDate; } } private void txtAleatorioReceita_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteLetras(sender, e); } private void DataGridCell_MouseDoubleClick(object sender, MouseButtonEventArgs e) { } private void btnSincronizar_Click(object sender, RoutedEventArgs e) { var sincronizar = new PeriodoDataSincronizarLancamentos(_usuario, this); sincronizar.Owner = this; sincronizar.ShowDialog(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InventoryUIDetails : MonoBehaviour { Item item; //Item selected Button selectedItemButton; //Button to item selected Button itemInteractButton; //Button to interact with item Text itemName; //Name of item to appear in details panel Text itemDescriptionText; //Description of item to appear Text itemButtonText; //Button text when interacting with it Quest quest; //quest selected public Text statText; //Text of stats of item void Start() { //Setting all the information for the panel itemName = transform.Find("ItemName").GetComponent<Text>(); itemDescriptionText = transform.Find("ItemDescription").GetComponent<Text>(); itemInteractButton = transform.Find("Button").GetComponent<Button>(); itemButtonText = itemInteractButton.transform.Find("Text").GetComponent<Text>(); //When no item selected, just deactivated gameObject.SetActive(false); } //Set item to display info on side of items public void setItem(Item item, Button button) { //Show details when object selected gameObject.SetActive(true); //Setting stat text here now: statText.text = ""; //If item does not have stats, don't display. If so, loop through and display all if (item.stats != null) { foreach (BaseStat stat in item.stats) { statText.text += stat.name + ": " + stat.baseValue + "\n"; } } //Remove previous listeners for events or everything used will be done multiple times: itemInteractButton.onClick.RemoveAllListeners(); //Setting information for details pannel to show this.item = item; selectedItemButton = button; itemName.text = item.name; itemDescriptionText.text = item.itemDescription; itemButtonText.text = item.interactName; //When button clicked to interact with item, call below method itemInteractButton.onClick.AddListener(onItemInteract); } //Actually use item time public void onItemInteract() { if (quest != null) { Inventory.instance.removeQuest(quest); quest.removeQuest(); quest = null; gameObject.SetActive(false); Destroy(selectedItemButton.gameObject); return; } //Depending on type of item, interact in other ways if (item.itemType == Item.ItemType.Consumable) { Inventory.instance.ConsumeItem(item); Destroy(selectedItemButton.gameObject); } if (item.itemType == Item.ItemType.Craftable) { if (Inventory.instance.ResourcesCheck(item.Item1, item.quantity1) && Inventory.instance.ResourcesCheck(item.Item2, item.quantity2)) { Inventory.instance.ResourcesRemove(item.Item2, item.quantity2); Inventory.instance.ResourcesRemove(item.Item1, item.quantity1); Inventory.instance.Add(item.Item3); } else { Debug.Log("can not craft"); } } if (item.itemType == Item.ItemType.Weapon) { Inventory.instance.EquipItem(item); Destroy(selectedItemButton.gameObject); } //Null item after using and hide item details when not on something item = null; gameObject.SetActive(false); } //Similar for quests now: public void setQuest(Quest quest, Button button) { //Show details when object selected gameObject.SetActive(true); //Setting quest progress text here now: statText.text = ""; foreach (Objective objective in quest.objectives) { statText.text += objective.description + ": " + objective.currProgress + "/" + objective.endAmount + "\n"; } //Remove previous listeners for events or everything used will be done multiple times: itemInteractButton.onClick.RemoveAllListeners(); //Setting information for details pannel to show this.quest = quest; selectedItemButton = button; itemName.text = quest.questName; itemDescriptionText.text = quest.questDescription; itemButtonText.text = "Remove"; //When quest complete, tell player it is done and return to NPC for reward if (quest.isComplete) { statText.text = "Quest is complete! Click remove at bottom to get rid of quest from inventory."; } //When button clicked to interact with item, call below method itemInteractButton.onClick.AddListener(onItemInteract); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JavaPackage { public class PackageItems { private ObservableCollection<MavenElement> _getMavenElement; public ObservableCollection<MavenElement> GetMavenElement { get => _getMavenElement; set => _getMavenElement = value; } } }