text
stringlengths
13
6.01M
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using BlazorUtils.Interfaces.BlazorComponents; using Microsoft.AspNetCore.Blazor.Components; namespace BlazorUtils.Dom.BlazorUtilsComponents { public class LMTEmpty : BlazorComponent, ILMTComponent { } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using BehaviourMachine; using System; public class BM_Rest : StateBehaviour { Agent m_agent; IntVar stamina; void OnEnable() { Debug.Log("Started *Rest*"); Setup(); m_agent.m_navAgent.isStopped = true; StartCoroutine(RegenerateStamina()); } // Called when the state is disabled void OnDisable() { Debug.Log("Stopped *Rest*"); StopAllCoroutines(); m_agent.m_navAgent.isStopped = false; m_agent.resting.Value = false; } void Setup() { m_agent = GetComponent<Agent>(); stamina = blackboard.GetIntVar("Stamina"); m_agent.resting.Value = true; } private IEnumerator RegenerateStamina() { while (enabled) { if (stamina.Value >= 100) break; stamina.Value++; yield return new WaitForSeconds(m_agent.agentProperties.StaminaRegenerationRate); } SendEvent("RegainedEnergy"); } }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { public class NextLevelButton : MonoBehaviour { void OnPress(bool isDown) { if(!isDown) { LevelLoadHelper.NextLevel(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBossMovement : MonoBehaviour { [SerializeField] private float _moveSpeed; [SerializeField] private GameObject _shipCorePrefab; private bool _stopMoving = false; void Update() { if (!_stopMoving) { CalculateMovement(); } if (_shipCorePrefab == null) { Destroy(gameObject); } } void CalculateMovement() { transform.Translate(Vector3.down * _moveSpeed * Time.deltaTime); if (transform.position.y <= 1) { _stopMoving = true; } } }
using System; namespace Cogent.IoC.Generators.Models { internal struct Registration { private readonly RegistrationTypeEnum _registrationType; private readonly object _value; public Registration(TransientRegistration transientRegistration) { _registrationType = RegistrationTypeEnum.Transient; _value = transientRegistration; } public Registration(SingletonRegistration singletonRegistration) { _registrationType = RegistrationTypeEnum.Singleton; _value = singletonRegistration; } public Registration(DelegateRegistration delegateRegistration) { _registrationType = RegistrationTypeEnum.Delegate; _value = delegateRegistration; } public Registration(FactoryRegistration factoryRegistration) { _registrationType = RegistrationTypeEnum.Factory; _value = factoryRegistration; } public T Match<T>( Func<TransientRegistration, T> transientMatch, Func<SingletonRegistration, T> singletonMatch, Func<DelegateRegistration, T> delegateMatch, Func<FactoryRegistration, T> factoryMatch) { switch (_registrationType) { case RegistrationTypeEnum.Transient: return transientMatch((TransientRegistration)_value); case RegistrationTypeEnum.Singleton: return singletonMatch((SingletonRegistration)_value); case RegistrationTypeEnum.Delegate: return delegateMatch((DelegateRegistration)_value); case RegistrationTypeEnum.Factory: return factoryMatch((FactoryRegistration)_value); case RegistrationTypeEnum.Defaulted: throw new Exception($"Default value not is invalid for {nameof(Registration)} type"); default: throw new NotImplementedException($"Not implemented for type {_registrationType}"); } } private enum RegistrationTypeEnum { Defaulted, Transient, Singleton, Delegate, Factory } } }
using System.Runtime.Serialization; namespace Shunxi.Business.Enums { public enum TargetDeviceTypeEnum { [EnumMember(Value = "Unknown")] Unknown = -1, [EnumMember(Value = "Pump")] Pump = 0, [EnumMember(Value = "Rocker")] Rocker = 1, [EnumMember(Value = "Temperature")] Temperature = 2, [EnumMember(Value = "Gas")] Gas = 3, [EnumMember(Value = "Ph")] Ph = 4, [EnumMember(Value = "Do")] Do = 5 } }
using Hayalpc.Library.Common.Enums; using Hayalpc.Library.Repository; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Hayalpc.Fatura.Data.Models { [Table("reset_passwords", Schema = "panel")] public class ResetPassword : HpModel { public Guid Token { get; set; } [Column("user_id")] public long UserId {get;set;} [Updatable] public Status Status { get; set; } } }
using System; using System.Text; using System.Security.Cryptography; namespace PmSoft.Utilities { public static class EncryptionUtility { public static string Base64_Decode(string str) { if (string.IsNullOrEmpty(str)) return str; byte[] bytes = Convert.FromBase64String(str); return Encoding.UTF8.GetString(bytes); } public static string Base64_Encode(string str) { return Base64_Encode(str, Encoding.UTF8); } public static string Base64_Encode(string str, Encoding encoding) { if (string.IsNullOrEmpty(str)) return str; return Convert.ToBase64String(encoding.GetBytes(str)); } public static string MD5(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] byt, bytHash; byt = System.Text.Encoding.UTF8.GetBytes(str); bytHash = md5.ComputeHash(byt); md5.Clear(); string sTemp = ""; for (int i = 0; i < bytHash.Length; i++) { sTemp += bytHash[i].ToString("X").PadLeft(2, '0'); } return sTemp; } public static string MD5_16(string str) { return MD5(str).Substring(8, 0x10); } public static string SymmetricDncrypt(SymmetricEncryptType encryptType, string str, string ivString, string keyString) { if (string.IsNullOrEmpty(str)) { return str; } return new PmSoft.Utilities.SymmetricEncrypt(encryptType) { IVString = ivString, KeyString = keyString }.Decrypt(str); } public static string SymmetricEncrypt(SymmetricEncryptType encryptType, string str, string ivString, string keyString) { if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(ivString)) || string.IsNullOrEmpty(keyString)) { return str; } return new PmSoft.Utilities.SymmetricEncrypt(encryptType) { IVString = ivString, KeyString = keyString }.Encrypt(str); } } }
using System; using TMPro; using UnityEngine; /// <summary> /// Scribble.rs Pad controllers namespace /// </summary> namespace ScribblersPad.Controllers { /// <summary> /// A class that describes a chat box element /// </summary> public class ChatBoxElementControllerScript : AChatBoxElementControllerScript, IChatBoxElementControllerScript { /// <summary> /// Author text /// </summary> [SerializeField] private TextMeshProUGUI authorText = default; /// <summary> /// Content text /// </summary> [SerializeField] private TextMeshProUGUI contentText = default; /// <summary> /// Author text /// </summary> public TextMeshProUGUI AuthorText { get => authorText; set => authorText = value; } /// <summary> /// Content text /// </summary> public TextMeshProUGUI ContentText { get => contentText; set => contentText = value; } /// <summary> /// Sets values in component /// </summary> /// <param name="author">Author</param> /// <param name="content">Content</param> public override void SetValues(string author, string content) { if (author == null) { throw new ArgumentNullException(nameof(author)); } if (content == null) { throw new ArgumentNullException(nameof(content)); } if (authorText) { authorText.text = author; } if (contentText) { contentText.text = content; } } } }
using Bytes2you.Validation; using Cinema.Data.Models; using Cinema.Data.Models.Contracts; using Cinema.Data.Repositories; using Cinema.Data.Services.Contracts; using System; using System.Collections.Generic; using System.Linq; namespace Cinema.Data.Services { public class FilmScreeningService : IFilmScreeningService { private const int InitialSeatsCount = 20; private IRepository<FilmScreening> screenings; private IFilmScreening filmScreeningToCreate; public FilmScreeningService(IRepository<FilmScreening> screenings, IFilmScreening filmScreening) { Guard.WhenArgument(screenings, "screenings").IsNull().Throw(); Guard.WhenArgument(filmScreening, "filmScreening").IsNull().Throw(); this.screenings = screenings; this.filmScreeningToCreate = filmScreening; } public void Create(string date, string movieId, string price) { this.filmScreeningToCreate.Start = DateTime.Parse(date); this.filmScreeningToCreate.TargetMovieId = int.Parse(movieId); this.filmScreeningToCreate.Price = decimal.Parse(price); this.filmScreeningToCreate.Seats = new List<Seat>(InitialSeatsCount); for (int i = 0; i < InitialSeatsCount; i++) { filmScreeningToCreate.Seats.Add((new Seat() { IsFree = true })); } this.screenings.Add((FilmScreening)filmScreeningToCreate); this.screenings.SaveChanges(); } public int GetAvailableCount(string id) { Guard.WhenArgument(id, "id").IsNullOrEmpty().Throw(); int parsedId; bool isNumber = int.TryParse(id, out parsedId); if (!isNumber) { throw new ArgumentException(); } return this.screenings.GetById(parsedId).Seats.Where(x => x.IsFree == true).Count(); } public IQueryable<FilmScreening> GetAllScreenings() { return this.screenings.All(); } public IQueryable<FilmScreening> GetAllScreeningsByDate(string date) { if (!string.IsNullOrEmpty(date)) { DateTime targetDate = DateTime.Parse(date); return this.screenings.All().Where(x => (x.Start.Day == targetDate.Day) && (x.Start.Month == targetDate.Month) && (x.Start.Year == targetDate.Year)); } else { return this.screenings.All(); } } public IQueryable<FilmScreening> GetAllFutureScreenings() { return this.screenings.All().Where(x => x.Start > DateTime.Now); } public IFilmScreening GetById(string id) { Guard.WhenArgument(id, "id").IsNullOrEmpty().Throw(); int parsedId; bool isNumber = int.TryParse(id, out parsedId); if (!isNumber) { throw new ArgumentException(); } return this.screenings.GetById(parsedId); } public void UpdateById(string id, FilmScreening updatedFilmScreening) { Guard.WhenArgument(id, "id").IsNullOrEmpty().Throw(); Guard.WhenArgument(updatedFilmScreening, "updatedFilmScreening").IsNull().Throw(); int parsedId; int.TryParse(id, out parsedId); var targetScreening = this.screenings.GetById(parsedId); targetScreening = updatedFilmScreening; this.screenings.Update(targetScreening); this.screenings.SaveChanges(); } public IQueryable<FilmScreening> GetScreeningsByMovieTitle(string title) { if (!string.IsNullOrEmpty(title)) { return this.screenings.All().Where(s => s.TargetMovie.Name.Contains(title)); } else { return this.screenings.All(); } } public IEnumerable<User> GetUniqueBookersFromScreeningById(string id) { int parsedId; int.TryParse(id, out parsedId); var targetScreening = this.screenings.GetById(parsedId); return targetScreening.Seats.Select(s => s.User).Where(u => u != null).Distinct(); } public string GetMovieTitleByScreeningId(string id) { Guard.WhenArgument(id, "id").IsNullOrEmpty().Throw(); int parsedId; bool isNumber = int.TryParse(id, out parsedId); if (!isNumber) { throw new ArgumentException(); } return this.screenings.GetById(parsedId).TargetMovie.Name; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DemoStandardProject.DTOs; using DemoStandardProject.Models.ServiceResponse; using DemoStandardProject.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace DemoStandardProject.Controllers.Product { [ApiController] [Route("api/product/")] public class ProductController : ControllerBase { ILogger<ProductController> _logger; private readonly IProductService _productService; public ProductController(IProductService productService, ILogger<ProductController> logger) { _productService = productService; _logger = logger; } [HttpGet("all")] public async Task<IActionResult> GetProductAll() { return Ok(await _productService.GetProductAll()); } [HttpGet("{id}")] public async Task<IActionResult> GetProductById(int id) { return Ok(await _productService.GetProductGetById(id)); } [HttpPost("add")] public async Task<IActionResult> AddProduct(AddProductDto newproduct) { try { return Ok(await _productService.AddProduct(newproduct)); } catch (Exception) { _logger.LogError("Failed to execute POST"); return BadRequest(); } } [HttpPut("update")] public async Task<IActionResult> UpdateProduct(UpdateProductDto updateProduct) { try { ServiceResponse<ProductDto> response = await _productService.UpdateProduct(updateProduct); if (response.Data == null) { return NotFound(response); } return Ok(response); } catch (Exception) { _logger.LogError("Failed to execute PUT"); return BadRequest(); } } [HttpDelete("delect/{id}")] public async Task<IActionResult> DelectProduct(int id) { try { ServiceResponse<List<ProductDto>> response = await _productService.DelectProduct(id); if (response.Data == null) { return NotFound(response); } return Ok(response); } catch (Exception) { _logger.LogError("Failed to execute DELETE"); return BadRequest(); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; 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 ContactManager.AdoConnected; using ContactManager.Business; namespace ContactManager { /// <summary> /// Interaction logic for NieuwContact.xaml /// </summary> public partial class NieuwContact : Window { private List<Telefoon> telLijst = new List<Telefoon>(); public Persoon ContactPersoon { get; set; } public NieuwContact() { InitializeComponent(); } //controle toevoegen voor als velden niet ingevoerd zijn !!! TO DO private void OnContactAanmakenButtonClicked(object sender, RoutedEventArgs e) { ContactStore c = new ContactStore(); bool isOrganisatie; if (ContactIsOrganisatieCheckBox.IsChecked == true) isOrganisatie = true; else isOrganisatie = false; //herhaalde logica in aparte method steken voor Organisatie + Persoon if (isOrganisatie) { Organisatie org = new Organisatie(); org.Naam = NieuwContactNaamTextBox.Text; org.Adres.Straat = NieuwContactStraatTextBox.Text; org.Adres.Locatie = NieuwContactLocatieTextBox.Text; org.Adres.Land = NieuwContactLandTextBox.Text; //Hier moet nog gekeken worden hoe op basis van een naam een persoon object toe te voegen if (OrganisatieHeeftContactPersoonCheckBox.IsChecked == true) { //org.ContactPersoon = NieuwContactContactPersoonTextBox.Text; } //beste manier? c.Nieuw(org); } else { Persoon pers = new Persoon(); pers.Naam = NieuwContactNaamTextBox.Text; pers.Adres.Straat = NieuwContactStraatTextBox.Text; pers.Adres.Locatie = NieuwContactLocatieTextBox.Text; pers.Adres.Land = NieuwContactLandTextBox.Text; if (NieuwContactBirthdatePicker != null) { pers.GeboorteDatum = DateTime.Parse(NieuwContactBirthdatePicker.Text); } c.Nieuw(pers); } } private void OnNieuwContactCancelClicked(object sender, RoutedEventArgs e) { this.Close(); } private void OnTelefoonInformatieToevoegenButtonClick(object sender, RoutedEventArgs e) { var tel = new Telefoon(); tel.TelefoonType = TelefoonNaamToevoegenTextBox.Text; tel.Nummer = TelefoonNummerToevoegenTextBox.Text; telLijst.Add(tel); //was nodig om lijst te kunnen refreshen, anders zie ik enkel eerst toegevoegde item TelefoonOverzichtListView.ItemsSource = null; TelefoonOverzichtListView.ItemsSource = telLijst; TelefoonNaamToevoegenTextBox.Clear(); TelefoonNummerToevoegenTextBox.Clear(); } private void KiesContactPersoonButton_Click(object sender, RoutedEventArgs e) { var zoekVenster = new ZoekVenster(this); zoekVenster.ShowDialog(); } } }
namespace DpiConverter.Tests { using Data; using Helpers; using NUnit.Framework; public class LandXmlTests { [TestCase("backsight", ObservationPurpose.Backsight)] [TestCase("traverse", ObservationPurpose.Traverse)] [TestCase("sideshot", ObservationPurpose.Sideshot)] [TestCase("unknown", ObservationPurpose.Sideshot)] public void GetObservationPurpose_ShouldReturnCorrectResult(string purpose, ObservationPurpose observationPurpose) { Assert.AreEqual(observationPurpose, LandXmlHelper.GetObservationPurpose(purpose)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Treees { public class BinaryTree<T> where T : IComparable { public Node<T> Root { get; set; } public BinaryTree() { } public BinaryTree(T value) { Root = new Node<T>(value); } /// <summary> /// this is my method for preorder a tree by traversal /// </summary> /// <param name="currentNode"></param> /// <param name="nodeValues"></param> /// <returns></returns> public T[] PreOrder(Node<T> currentNode, List<T> nodeValues) { if(currentNode == null) { return nodeValues.ToArray(); } nodeValues.Add(currentNode.Value); if (currentNode.Left != null) { PreOrder(currentNode.Left, nodeValues); } if (currentNode.Right != null) { PreOrder(currentNode.Right, nodeValues); } return nodeValues.ToArray(); } public T[] InOrder(Node<T> currentNode, List<T> nodeValues) { if (currentNode == null) return nodeValues.ToArray(); if (currentNode.Left != null) InOrder(currentNode.Left, nodeValues); nodeValues.Add(currentNode.Value); if (currentNode.Right != null) InOrder(currentNode.Right, nodeValues); return nodeValues.ToArray(); } public static List<int> PostOrderTraversal(Node<int> node, List<int> values) { if (node.Left != null) { PostOrderTraversal(node.Left, values); } if (node.Right != null) { PostOrderTraversal(node.Right, values); } values.Add(node.Value); return values; } public T FindMax(T maxValue, Node<T> currentNode) { if (currentNode == null) return maxValue; Console.WriteLine($"currentNode: {currentNode.Value}\tmaxValue: {maxValue}\tCompare: {maxValue.CompareTo(currentNode.Value)}"); if (maxValue.CompareTo(currentNode.Value) < 0) maxValue = currentNode.Value; if (currentNode.Left != null) FindMax(maxValue, currentNode.Left); if (currentNode != null) FindMax(maxValue, currentNode.Right); return maxValue; } public static List<T> BreadthTraversal(BinaryTree<T> tree) { List<T> values = new List<T>(); Queue<Node<T>> nodes = new Queue<Node<T>>(); nodes.Enqueue(tree.Root); while (nodes.Peek() != null) { Node<T> currentNode = nodes.Dequeue(); values.Add(currentNode.Value); if ( currentNode.Left != null ) { nodes.Enqueue(currentNode.Left); } if (currentNode.Right != null) { nodes.Enqueue(currentNode.Right); } } return values; } } }
using Microsoft.AspNetCore.Mvc; using Sp_Medical_Group.Domains; using Sp_Medical_Group.Interfaces; using Sp_Medical_Group.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sp_Medical_Group.Controllers { //define que o tipo de reposta da API será no formato JSON [Produces("application/json")] //define que a rota de uma requisição será no formato domínio/api/NomeController [Route("api/[controller]")] //Define que é um controlador de API [ApiController] public class consultaController : ControllerBase { private IConsultaRepository _consultaRepository { get; set; } public consultaController() { _consultaRepository = new consultaRepository(); } //[HttpGet] //public IActionResult Get() //{ //retorna a resposta da requisição fazendo uma chamada para o método // return Ok(_consultaRepository.Listar()); //} [HttpPost("{id}")] public IActionResult Post(Consulta NovaConsulta) { //faza a chamada para o método _consultaRepository.Cadastrar(NovaConsulta); return StatusCode(201); } [HttpDelete("{id}")] public IActionResult Delete(int id) { //faz a chamada para o método _consultaRepository.Deletar(id); //retorna um status code return StatusCode(204); } [HttpGet] public IActionResult ListarTodasConsultas() { List<Consulta> listaConsultas = _consultaRepository.ListarTodos(); return Ok(listaConsultas); } [HttpGet("{id}")] public IActionResult GetById(int id) { Consulta pacienteBuscado = _consultaRepository.BuscarIdPaciente(id); if (pacienteBuscado == null) { return NotFound("Nenhuma Consulta encontrada!"); } return Ok(pacienteBuscado); } } }
//Write a program that reads a string from the console and prints all different //letters in the string along with information how many times each letter is found. using System; using System.Collections.Generic; using System.Text.RegularExpressions; class LettersInString { static void Main() { Console.WriteLine("Enter a string: "); string input = Console.ReadLine(); Dictionary<char, int> letterscounter = new Dictionary<char,int>(); string pattern = @"[a-z,A-Z]"; Match singleLetter = Regex.Match(input,pattern); while (singleLetter.Success) { if (letterscounter.ContainsKey(Convert.ToChar(singleLetter.Value))) { letterscounter[Convert.ToChar(singleLetter.Value)] = letterscounter[Convert.ToChar(singleLetter.Value)] + 1; } else { letterscounter.Add(Convert.ToChar(singleLetter.Value),1); } singleLetter = singleLetter.NextMatch(); } foreach (var item in letterscounter) { Console.WriteLine("Letter "+item.Key+" - "+item.Value+" times found"); } } }
using UnityEngine; public class Energy { #region Fields private float currentEnergy; private float maximumEnergy; private bool isPlayer; #endregion #region Constructor public Energy(float currentEnergy, float maximumEnergy, bool isPlayer = true) { this.currentEnergy = currentEnergy; this.maximumEnergy = maximumEnergy; this.isPlayer = isPlayer; } #endregion #region Properties public float CurrentEnergy { get { return currentEnergy; } private set { float currentEnergyTmp = currentEnergy; currentEnergy = value; if (currentEnergy > maximumEnergy) currentEnergy = maximumEnergy; if (this.isPlayer) ServiceContainer.Instance.EventManagerParamsFloatAndFloat.CallEvent(EEventParamsFloatAndFloat.PlayerEnergyIsUpdate, currentEnergy, maximumEnergy); else ServiceContainer.Instance.EventManagerParamsFloatAndFloat.CallEvent(EEventParamsFloatAndFloat.EnemyLifeIsUpdate, currentEnergy, maximumEnergy); if (currentEnergy <= 0) { if (this.isPlayer) ServiceContainer.Instance.EventManager.CallEvent(EEvent.GameOver); else ServiceContainer.Instance.EventManager.CallEvent(EEvent.Win); } float otherTmp = (currentEnergyTmp - currentEnergy) / maximumEnergy; if (this.isPlayer) ServiceContainer.Instance.EventManagerParamsFloat.CallEvent(EEventParamsFloat.PlayerEnergyRatioWhenLoose, otherTmp); else ServiceContainer.Instance.EventManagerParamsFloat.CallEvent(EEventParamsFloat.BossHealthRatioWhenLoose, otherTmp); } } public float MaximumEnergy { get { return maximumEnergy; } private set { maximumEnergy = value; } } #endregion #region Behaviour Methods public float Ratio() { return this.CurrentEnergy / this.MaximumEnergy; } public void AddEnergy(float value) { this.CurrentEnergy += value; } public void RemoveEnergy(float value) { this.CurrentEnergy -= value; } public void SetEnergyToZero() { this.CurrentEnergy = 0; } #endregion }
namespace EkwExplorer.FakeScraper; public enum NameFormat { NameSurname, SurnameName } internal class RandomNamesGenerator { private readonly Randomizer<string> _femaleNames = new Randomizer<string>() { "Anna", "Maria", "Katarzyna", "Małgorzata", "Agnieszka", "Barbara", "Krystyna", "Ewa", "Elżbieta", "Zofia", "Teresa", "Magdalena", "Joanna", "Janina", "Monika", "Danuta", "Jadwiga", "Aleksandra", "Halina", "Irena", "Beata", "Marta", "Renata", "Alicja", "Urszula", "Paulina", "Justyna", "Stanisława", "Bożena", "Natalia", "Marianna", "Dorota", "Helena", "Karolina", "Grażyna", "Jolanta", "Iwona" }; private readonly Randomizer<string> _maleNames = new Randomizer<string>() { "Piotr", "Krzysztof", "Andrzej", "Jan", "Stanisław", "Tomasz", "Paweł", "Marcin", "Michał", "Marek", "Grzegorz", "Józef", "łukasz", "Adam", "Zbigniew", "Jerzy", "Tadeusz", "Mateusz", "Dariusz", "Mariusz", "Wojciech", "Ryszard", "Jakub", "Henryk", "Robert", "Rafał", "Kazimierz", "Jacek", "Maciej", "Kamil", "Janusz", "Marian", "Mirosław", "Jarosław", "Sławomir", "Dawid", "Wiesław" }; private readonly Randomizer<string> _surnames = new Randomizer<string>() { "Nowak", "Kowalski", "Wiśniewski", "Wójcik", "Kowalczyk", "Kamiński", "Lewandowski", "Zieliński", "Szymański", "Woźniak", "Dąbrowski", "Kozłowski", "Jankowski", "Mazur", "Wojciechowski", "Kwiatkowski", "Krawczyk", "Kaczmarek", "Piotrowski", "Grabowski", "Zając", "Pawłowski", "Michalski", "Król", "Wieczorek", "Jabłoński", "Wróbel", "Nowakowski", "Majewski", "Olszewski" }; private readonly Random _random = new Random(Guid.NewGuid().GetHashCode()); public string GenerateMale(NameFormat nameFormat = NameFormat.NameSurname) { var name = _maleNames.Next(); var surname = _surnames.Next(); return nameFormat switch { NameFormat.NameSurname => $"{name} {surname}", NameFormat.SurnameName => $"{surname} {name}", _ => throw new ArgumentOutOfRangeException(nameof(nameFormat)) }; } public string GenerateFemale(NameFormat nameFormat = NameFormat.NameSurname) { var name = _femaleNames.Next(); var surname = MaleSurnameToFemale(_surnames.Next()); return nameFormat switch { NameFormat.NameSurname => $"{name} {surname}", NameFormat.SurnameName => $"{surname} {name}", _ => throw new ArgumentOutOfRangeException(nameof(nameFormat)) }; } public string Generate(NameFormat nameFormat = NameFormat.NameSurname) { var isFemale = _random.Next() % 2 == 0; return isFemale ? GenerateFemale(nameFormat) : GenerateMale(nameFormat); } private static string MaleSurnameToFemale(string surname) => surname.Replace("ski", "ska"); }
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 WeifenLuo.WinFormsUI.Docking; using System.Data.SqlClient; using System.IO; namespace RSMS { public partial class StoragePlan : MyFrmBase { public StoragePlan() { InitializeComponent(); } private void StoragePlan_Load(object sender, EventArgs e) { clearContrlText(); // refreshDB(); // 加载指纹信息 } void ZKFGSDK_fgValidFun(object sender, myHelper.OPEventArgs e) { //throw new NotImplementedException(); //获取指纹验证 MessageBox.Show(e.param[0]); } //清除控件值 public void clearContrlText() { myHelper.loadDataToGridView(null, dataGridView1); foreach (Control tb in this.groupBox2.Controls) { string tbName = tb.Name; if (tbName.Length >= 2 && (tbName.Substring(0, 2) == "TB" || tbName.Substring(0, 2) == "PB" || tbName.Substring(0, 2) == "BT" || tbName.Substring(0, 2) == "CB")) { if (tb is TextBox) { tb.Text = ""; ((TextBox)tb).ReadOnly = true; } else if (tb is CheckBox) { ((CheckBox)tb).Checked=false; tb.Enabled=false; }else if (tb is PictureBox){ ((PictureBox)tb).Image=null; }else if(tb is Button){ ((Button)tb).Enabled=false; } else if (tb is ComboBox) { ((ComboBox)tb).Enabled = false; tb.Text = ""; } } } myHelper.loadAuth((myHelper.subWin)this.Tag, this.toolStrip1); } private void checkic_Click(object sender, EventArgs e) { string cICNum = ""; if (myHelper.getDbConn() != null) { #region 获取卡号 if (!TB1.ReadOnly) { if (TB1.Text == "") { clearContrlText(); myHelper.emsg("错误", "请录入卡片号码!"); return; } cICNum = TB1.Text.Trim(); } else { cICNum = WSICReader.getCarNum(); if (cICNum == null) { clearContrlText(); myHelper.emsg("错误", "读取卡号失败,请检查读卡器连接是否正常!"); return; } TB1.Text = cICNum; TB1.ReadOnly = true; } #endregion #region 事务启动 SqlTransaction sqlTran = null; try { sqlTran = myHelper.getDbConn().BeginTransaction(); } catch (Exception) { myHelper.emsg("错误", "启动检查事务失败,请检测网络连接!"); return; } #endregion //MessageBox.Show("测试"); try { #region 检测卡号 DataRow firstDt = myHelper.getOneRow("select [cSeqNum],[cPlateNum],[dInWeightDate],cMemo,[dMadeDate],[cBillNo],[cBillType],[cCusCode],[cCusName],[cOrgPlateNum],[cDriverID],bOut from [realWeighing] with(xlock) where [cICNum]=@v1 and cFaCode=@v2", new SqlParameter[2] { new SqlParameter("@v1", cICNum), new SqlParameter("@v2", myHelper.getFaCode()) }, sqlTran); // 0 1 2 3 4 5 6 7 8 9 10 11 if (firstDt == null) { sqlTran.Rollback(); clearContrlText(); myHelper.emsg("错误", "卡片号码: " + cICNum + " 无效!"); return; } #endregion string billNo = firstDt[5] as string; string billType = firstDt[6] as string; if (!string.IsNullOrEmpty(billNo)) { int ret = webLogin.RFCGETBILLSTATUS(billNo, billType, billType == myHelper.getVA11() ? cICNum.Trim() : ""); if (ret == 0) { sqlTran.Rollback(); clearContrlText(); myHelper.emsg("警告", "业务已结算!"); return; } else { if (ret < 0) { sqlTran.Rollback(); clearContrlText(); webLogin.SAPHitMsg(ret); return; } } } #region 显示信息 //禁用ic录入 TB1.ReadOnly = true; //流水号 string seqNum = firstDt[0] as string; //车牌号 TB2.Text = firstDt[1] as string; //入园时间 TB3.Text = ((DateTime)firstDt[2]).ToString("yyyy-MM-dd HH:mm:ss"); // MessageBox.Show(((DateTime)firstDt[2]).ToString("yyyy-MM-dd HH:mm:ss")); //备注信息 TB12.Text = firstDt[3] as string; //入园车牌图片 PB3.Image = myHelper.base64String2ImgObj(myHelper.getFirst("select [cPicture] from [PictureLog] where cFaCode=@v1 and [cSeNum] in(select [cInPlateImgSN] from [carLog] with(xlock) where [cSeqNum]=@id)", new SqlParameter[2] { new SqlParameter("@id", seqNum), new SqlParameter("@v1", myHelper.getFaCode()) }, sqlTran) as string); PB6.Image = PB3.Image; //预约车牌 TB11.Text = firstDt[9] as string; //订单号 TB5.Text = firstDt[5] as string; //制单时间 TB4.Text = TB5.Text != "" ? ((DateTime)firstDt[4]).ToString("yyyy-MM-dd") : ""; //订单类型 TB6.Text = firstDt[6] as string; //商户代码 TB7.Text = firstDt[7] as string; //商户名称 TB8.Text = firstDt[8] as string; //显示司机信息 if (!string.IsNullOrEmpty(firstDt[10] as string)) { DataRow drPerson = myHelper.getOneRow("select [cPersonID],[cPersonName],[olePicture] from [DriverInfo] where [cPersonID]=@v1", new SqlParameter("@v1", firstDt[10]), sqlTran); if (drPerson != null) { TB9.Text = drPerson[0] as string; TB10.Text = drPerson[1] as string; PB1.Image = myHelper.base64String2ImgObj(drPerson[2] as string); PB2.Image = myHelper.base64String2ImgObj(myHelper.getFirst("select top 1 [cFGPic] from [FGTemplateLib] where [cPersonID]=@v1", new SqlParameter("@v1", firstDt[10]), sqlTran) as string); } } CB1.Checked = (bool)firstDt[11]; //查找公司资料信息 if (!string.IsNullOrEmpty(TB7.Text)) { DataRow drCompany = myHelper.getOneRow("select [cPicture1],[cPicture2] from [clientInfo] where [cCusCode]=@code", new SqlParameter("@code", TB7.Text), sqlTran); if (drCompany != null) { PB4.Image = myHelper.base64String2ImgObj(drCompany[0] as string); PB5.Image = myHelper.base64String2ImgObj(drCompany[1] as string); } } //库存计划:有则显示,无则不显 myHelper.loadDataToGridView(myHelper.getDataTable("select [POSNR],[cInvName],[cInvCode],[iWeighting],[cStoreNum],[cAllocNum],[bCompleted] from sapPlanOrders where [cSeqNum]=@v1 order by AutoId", new SqlParameter("@v1", seqNum), sqlTran), dataGridView1); #endregion } catch (Exception ex) { clearContrlText(); myHelper.emsg("错误", "执行事务中异常,请检查网络连接!("+ex.Message+")"); return; } #region 可以编辑状态 try { sqlTran.Commit(); } catch (Exception) { clearContrlText(); myHelper.emsg("错误", "执行事务结束异常,请检查网络连接!"); return; } //锁定 myHelper.setExclusiveLock(this); CB1.Enabled = true; checkic.Enabled = false; save.Enabled = true; cancle.Enabled = true; BT2.Enabled = true; BT1.Enabled = true; BT3.Enabled = true; BT4.Enabled = true; #region 装载历史备注 TB12.Enabled = true; TB12.Items.Clear(); DataTable dtB = myHelper.getDataTable("select top 10 [cMemo] from (select distinct [cMemo] from [WeightNotes] where isnull(cMemo,'')<>'' ) t"); if (dtB != null) { for (int i = 0, m = dtB.Rows.Count; i < m; i++) { TB12.Items.Add(dtB.Rows[i][0].ToString()); ; } } #endregion return; #endregion } myHelper.emsg("错误", "数据库连接失败,请检查网络连接!"); } private void StoragePlan_FormClosed(object sender, FormClosedEventArgs e) { myHelper.resetExclusiveLoke(this); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { // TB2.ReadOnly = !((CheckBox)sender).Checked; } private void checkBox2_CheckedChanged(object sender, EventArgs e) { TB1.ReadOnly = !((CheckBox)sender).Checked; if (TB1.ReadOnly) { TB1.Text = ""; ((CheckBox)sender).Enabled = false; } } private void handinput_Click(object sender, EventArgs e) { if (!myHelper.getExclusiveLock(this)) { clearContrlText(); TB1.ReadOnly = false; TB1.Focus(); return; } myHelper.emsg("错误", "编辑模式下不能启用!!"); } private void save_Click(object sender, EventArgs e) { if (myHelper.getExclusiveLock(this)) { //获取卡片号码 string cICNum = TB1.Text; string driverId = TB9.Text.Trim(); if (myHelper.getDbConn() == null) { myHelper.emsg("错误", "数据库连接失败,请检测网络连接!"); return; } #region 准备数据 #region 检测卡号 DataRow firstDt = myHelper.getOneRow("select [cSeqNum],[cPlateNum],[dInWeightDate],cMemo,[dMadeDate],[cBillNo],[cBillType],[cCusCode],[cCusName],[cOrgPlateNum],[cDriverID],bOut from [realWeighing] where [cICNum]=@v1 and cFaCode=@v2", new SqlParameter[2] { new SqlParameter("@v1", cICNum), new SqlParameter("@v2", myHelper.getFaCode()) }); // 0 1 2 3 4 5 6 7 8 9 10 11 if (firstDt == null) { myHelper.emsg("错误", "卡片号码: " + cICNum + " 无效!"); return; } #region 检测单据 string billNo = firstDt[5] as string; string billType = firstDt[6] as string; if (!string.IsNullOrEmpty(billNo)) { int ret = webLogin.RFCGETBILLSTATUS(billNo, billType, billType == myHelper.getVA11() ? cICNum.Trim() : ""); if (ret == 0) { //clearContrlText(); myHelper.emsg("警告", "业务已结算!"); return; } else { if (ret < 0) { //clearContrlText(); webLogin.SAPHitMsg(ret); return; } //清理排队信息 if (billType != myHelper.getVA11()) { webLogin.Queue(cICNum, "", "DeleteSubmit"); } } } #endregion //流水号 string seqNum = firstDt[0] as string; if (string.IsNullOrEmpty(firstDt[1] as string)&&string.IsNullOrEmpty(TB2.Text.Trim())) { if (MessageBox.Show("入园车牌号码未知,确定不修正吗?", "警告", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)//空车出园 { return; } } else { if (firstDt[1] as string != TB2.Text.Trim()) { if (MessageBox.Show("确定,入园车牌号码为: " + TB2.Text.Trim() + " ?", "警告", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)//空车出园 { return; } } } //空车出园 bool isNullOut = false; if (CB1.Checked) { if (string.IsNullOrEmpty(TB5.Text)) { if (MessageBox.Show("确定空车出园?", "警告", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)//空车出园 { isNullOut = true; } else { CB1.Checked = false; return; } } } if (!isNullOut) { if (string.IsNullOrEmpty(TB5.Text)) { myHelper.emsg("错误", "请确定预约单!"); return; } if (string.IsNullOrEmpty(driverId)) { myHelper.emsg("错误", "请确定司机!"); return; } } else { if (string.IsNullOrEmpty(TB9.Text.Trim()) && MessageBox.Show("司机未指定,确定继续吗?", "警告", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK) { return; } } if (!string.IsNullOrEmpty(driverId)) { if (myHelper.getFirst("select [cPersonName] from [DriverInfo] where [cPersonID]=@id", new SqlParameter("@id", driverId)) == null) { myHelper.emsg("错误", "司机信息未采集!"); return; } } #endregion #endregion #region 事务启动 SqlTransaction sqlTran = null; try { sqlTran = myHelper.getDbConn().BeginTransaction(); } catch (Exception) { myHelper.emsg("错误", "启动检查事务失败,请检测网络连接!"); return; } #endregion try { #region 再次检查卡号 firstDt = myHelper.getOneRow("select [cSeqNum],[ID],[cBillID],[cBillType],cBSCreatedId,cBillNo,cBillType from [realWeighing] with(xlock) where [cICNum]=@v1 and cFaCode=@v2", new SqlParameter[2] { new SqlParameter("@v1", cICNum), new SqlParameter("@v2", myHelper.getFaCode()) }, sqlTran); // 0 1 2 3 4 5 6 7 8 9 10 11 if (firstDt == null) { myHelper.emsg("错误", "卡片号码: " + cICNum + " 无效!"); return; } seqNum = firstDt[0] as string; #endregion #region 更新司机信息 string driverName = ""; if (!string.IsNullOrEmpty(driverId)) { object obj = myHelper.getFirst("select [cPersonName] from [DriverInfo] where [cPersonID]=@id", new SqlParameter("@id", driverId), sqlTran); if (string.IsNullOrEmpty(obj as string)) { sqlTran.Rollback(); myHelper.emsg("错误", "司机信息未采集!"); return; } driverName = obj as string; } if (myHelper.update("update [carLog] with(xlock) set [cPersonID]=@v1,[cPersonName]=@v2,[cPlateNum]=@v4 where cSeqNum=@v3 ", new SqlParameter[4] { new SqlParameter("@v3", seqNum), new SqlParameter("@v2", driverName), new SqlParameter("@v1", driverId),new SqlParameter("@v4",TB2.Text.Trim()) }, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新(日志)司机信息异常!"); return; } if (myHelper.update("update realWeighing with(xlock) set [cDriverID]=@v1,[cDriverName]=@v2,[cPlateNum]=@v4 where cSeqNum=@v3 ", new SqlParameter[4] { new SqlParameter("@v3", seqNum), new SqlParameter("@v2", driverName), new SqlParameter("@v1", driverId), new SqlParameter("@v4", TB2.Text.Trim()) }, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新(单据)司机信息异常!"); return; } #endregion #region 更新单据作者信息 if (firstDt[4] is DBNull) { if (myHelper.update("update [realWeighing] with(xlock) set cBSCreatedId=@v1,cBSCreatedName=@v2,cBSCreatedDate=getdate() where cSeqNum=@v3", new SqlParameter[3] { new SqlParameter("@v1", myHelper.getUserId()), new SqlParameter("@v2", myHelper.getUserName()),new SqlParameter("@v3",seqNum)}, sqlTran) <= 0) { myHelper.emsg("错误", "更新单据创建者失败!"); return; } } else { if (myHelper.update("update [realWeighing] with(xlock) set cBSEditedId=@v1,cBSEditedName=@v2,cBSEditedDate=getdate() where cSeqNum=@v3", new SqlParameter[3] { new SqlParameter("@v1", myHelper.getUserId()), new SqlParameter("@v2", myHelper.getUserName()), new SqlParameter("@v3", seqNum) }, sqlTran) <= 0) { myHelper.emsg("错误", "更新单据编辑者失败!"); return; } } #endregion #region 更新备注 myHelper.update("update realWeighing with(xlock) set [cMemo]=@v1 where cSeqNum=@v2 ", new SqlParameter[2] {new SqlParameter("@v1", TB12.Text),new SqlParameter("@v2",seqNum)}, sqlTran); #endregion } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!(" + ex.Message + ")"); return; } #region 空车出园与非空车 #region 清理必要的数据 string sapBillType = firstDt[3] as string; try { #region 如果存在预约单信息时要清除 //清理预约单及 if (!string.IsNullOrEmpty(sapBillType)) { if (sapBillType != myHelper.getVA11().ToUpper()) { #region 回写IC //MessageBox.Show("回写IC,现已注释掉,正式版请启用!"); int ret = webLogin.RFCUPDATEBILL(myHelper.getFaCode(), "", firstDt[5] as string); if (ret != 0) { sqlTran.Rollback(); webLogin.SAPHitMsg(ret); return; } #endregion if (myHelper.update("delete from [sapPlanOrders] where [cSeqNum]=@v1 ", new SqlParameter("@v1", seqNum), sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "清除库存计划失败!"); return; } } //清除预约单 if (myHelper.update("delete from [sapOrders] where [cSeqNum]=@v1 ", new SqlParameter("@v1", seqNum), sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "清除预约单失败!"); return; } //更新real单据信息 if (myHelper.update("update realWeighing with(xlock) set [cBillID]=null,[cCusName]=null,[cCusCode]=null,[cOrgPlateNum]=null,[cBillNo]=null,[cBillType]=null,[dMadeDate]=null,[iPlanWeighing]=null where [cSeqNum]=@v1 ", new SqlParameter("@v1", seqNum), sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新单据信息失败!"); return; } } if (myHelper.update("update realWeighing with(xlock) set bOut=1,bIsNoPlan=1 where [cSeqNum]=@v1 ", new SqlParameter("@v1", seqNum), sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新单据信息失败!"); return; } #endregion } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!(" + ex.Message + ")"); return; } #endregion if (isNullOut) { #region 试图提交数据 try { sqlTran.Commit(); } catch (Exception) { myHelper.emsg("错误", "执行事务结束异常,请检查网络连接!"); return; } myHelper.resetExclusiveLoke(this); clearContrlText(); checkic.Enabled = true; save.Enabled = false; cancle.Enabled = false; myHelper.smsg("警告", "保存数据成功!"); return; #endregion } else { try { #region 保存预约单 //保存预约单 SqlParameter[] sqlPar = new SqlParameter[12]; sqlPar[0] = new SqlParameter("@v1", cICNum); sqlPar[1] = new SqlParameter("@v2", seqNum); sqlPar[2] = new SqlParameter("@v3", TB8.Text); sqlPar[3] = new SqlParameter("@v4", TB7.Text); sqlPar[4] = new SqlParameter("@v5", TB5.Text); sqlPar[5] = new SqlParameter("@v6", TB6.Text.ToUpper()); sqlPar[6] = new SqlParameter("@v7", DateTime.Parse(TB4.Text)); sqlPar[7] = new SqlParameter("@v8", myHelper.getUserId()); sqlPar[8] = new SqlParameter("@v9", TB11.Text); sqlPar[9] = new SqlParameter("@v10", TB2.Text); sqlPar[10] = new SqlParameter("@v11", myHelper.getFaCode()); sqlPar[11] = new SqlParameter("@v12", myHelper.getUserName()); string sqlText = "insert into sapOrders([cICNum],[cSeqNum],[cCusName],[cCusCode],[cBillNo],[cBillType],[dMadeDate],[cUserId],[cOrgPlateNum],[cRealPlateNum],cFaCode,cUserName,[dCreateDate]) values(@v1,@v2,@v3,@v4,@v5,@v6,@v7,@v8,@v9,@v10,@v11,@v12,getdate())"; if (myHelper.update(sqlText, sqlPar, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "保存预约单,失败!"); return; } #endregion #region 更新锁定单据信息 object obj = myHelper.getFirst("select AutoID from sapOrders with(xlock) where cSeqNum=@seq", new SqlParameter("@seq", seqNum), sqlTran); if (obj == null) { sqlTran.Rollback(); myHelper.emsg("错误", "获取预约单ID,失败!"); return; } sqlText = "update [realWeighing] with(xlock) set [cCusName]=@v1,[cCusCode]=@v2,[cBillNo]=@v3,[cBillType]=@v4,[dMadeDate]=@v5,[cOrgPlateNum]=@v6,cBillID=@v7 where [cSeqNum]=@v8 "; sqlPar = new SqlParameter[8]; sqlPar[0] = new SqlParameter("@v1", TB8.Text.Trim()); sqlPar[1] = new SqlParameter("@v2", TB7.Text.Trim()); sqlPar[2] = new SqlParameter("@v3", TB5.Text.Trim()); sqlPar[3] = new SqlParameter("@v4", TB6.Text.Trim()); sqlPar[4] = new SqlParameter("@v5", TB4.Text); sqlPar[5] = new SqlParameter("@v6", TB11.Text.Trim()); sqlPar[6] = new SqlParameter("@v7", obj); sqlPar[7] = new SqlParameter("@v8", seqNum); if (myHelper.update(sqlText, sqlPar, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新单据预约单失败!"); return; } #endregion if (TB6.Text.Trim() != myHelper.getVA11().ToUpper()) { #region 获取库存计划 int ret = 0; DataTable dt = webLogin.RFCGETINVPLAN(ref ret, myHelper.getFaCode(), TB5.Text); webLogin.SAPHitMsg(ret); if (dt == null) { sqlTran.Rollback(); myHelper.emsg("错误", "获取SAP库存计划,失败!"); return; } #endregion #region 保存库存计划 sqlText = "insert into [sapPlanOrders]([cInvCode],[cInvName],[cStoreNum],[cAllocNum],[iWeighting],[POSNR],[cFaCode] ,[cUserId],[cUserName],[cSeqNum],[cICNum],[cBillNo],[cBillType],[bCompleted],[dCreateDate]) "; sqlText += " values(@v0,@v1,@v2,@v3,@v4,@v5,@code,@userid,@username,@seq,@ic,@no,@type,0,getdate())"; for (int i = 0, m = dt.Rows.Count; i < m; i++) { int mx = dt.Columns.Count; sqlPar = new SqlParameter[mx + 7]; for (int j = 0; j < mx; j++) { sqlPar[j] = new SqlParameter("@v" + j.ToString(), dt.Rows[i].ItemArray.GetValue(j)); } sqlPar[mx] = new SqlParameter("@code", myHelper.getFaCode()); sqlPar[mx + 1] = new SqlParameter("@userid", myHelper.getUserId()); sqlPar[mx + 2] = new SqlParameter("@seq", seqNum); sqlPar[mx + 3] = new SqlParameter("@ic", cICNum); sqlPar[mx + 4] = new SqlParameter("@username", myHelper.getUserName()); sqlPar[mx + 5] = new SqlParameter("@no", TB5.Text); sqlPar[mx + 6] = new SqlParameter("@type", TB6.Text); if (myHelper.update(sqlText, sqlPar, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "保存库存计划,失败!"); return; } } #endregion #region 回写IC //回写IC //MessageBox.Show("回写IC,现已注释掉,正式版请启用!"); ret = webLogin.RFCUPDATEBILL(myHelper.getFaCode(), cICNum, TB5.Text); if (ret != 0) { sqlTran.Rollback(); webLogin.SAPHitMsg(ret); return; } #endregion } #region 更新real if (myHelper.update("update realWeighing with(xlock) set [bIsNoPlan]=@v1 where [cSeqNum]=@seq", new SqlParameter[2] { new SqlParameter("@v1", TB6.Text.Trim() != myHelper.getVA11().ToUpper() ? true : false), new SqlParameter("@seq", seqNum) }, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "更新单据(库存计划标识),失败!"); return; } #endregion } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!(" + ex.Message + ")"); return; } #region 试图提交数据 try { sqlTran.Commit(); } catch (Exception) { clearContrlText(); myHelper.emsg("错误", "执行事务结束异常,请检查网络连接!"); return; } #endregion myHelper.resetExclusiveLoke(this); OpLog("关联单据", "成功", TB1.Text+"-"+TB2.Text+"-"+TB5.Text); webLogin.Queue(cICNum, ""); clearContrlText(); myHelper.smsg("成功", "保存数据成功!!"); return; } #endregion } } private void cancle_Click(object sender, EventArgs e) { if (myHelper.getExclusiveLock(this)) { myHelper.resetExclusiveLoke(this); checkic.Enabled = true; save.Enabled = false; cancle.Enabled = false; clearContrlText(); TB12.Enabled = false; return; } myHelper.emsg("错误", "非编辑模式!!"); } private void backup_Click(object sender, EventArgs e) { if (myHelper.getExclusiveLock(this)) { SqlParameter[] sqlPar; //检查是否法ic卡号 if (myHelper.getDbConn() != null) { if (TB1.Text == "") { myHelper.emsg("错误", "卡片号码不存在!"); return; } if (MessageBox.Show("卡片号码:" + TB1.Text + ",业务单据信息将完全清除,确定吗?", "警告", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK) { return; } SqlTransaction sqlTran = null; #region 试图开启事务 try { sqlTran=myHelper.getDbConn().BeginTransaction(); } catch (Exception ex) { myHelper.emsg("错误", "启动检查事务失败,请检测网络连接!(" + ex.Message + ")"); return; } #endregion bool isCanOut = false; ; bool isNullPlate = false; string seqNum; DataRow dr = null; #region 事务执行 try { sqlPar = new SqlParameter[2]; sqlPar[0] = new SqlParameter("@ic", TB1.Text); sqlPar[1] = new SqlParameter("@code", myHelper.getFaCode()); dr = myHelper.getOneRow("select [cSeqNum],bOut,[cBillNo],[cBillType],[cBillID] from [realWeighing] with(xlock) where [cICNum]=@ic and cFaCode=@code", sqlPar, sqlTran); if (dr == null) { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; myHelper.emsg("错误", "IC卡号(" + TB1.Text + ")无效!"); return; } seqNum = dr[0] as string; isCanOut = (bool)dr[1]; isNullPlate = (dr[4] is DBNull & isCanOut) ? true : false; if (!isCanOut) { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; myHelper.emsg("错误", "无法撤消,未办理业务的单据!("+TB1.Text+")"); return; } sqlPar = new SqlParameter[3]; sqlPar[0] = new SqlParameter("@v1", myHelper.getUserId()); sqlPar[1] = new SqlParameter("@v2", myHelper.getUserName()); sqlPar[2] = new SqlParameter("seq", seqNum); if (myHelper.update("update realWeighing with(xlock) set bOut=0,[cDriverID]=null,[cDriverName]=null,[cBSCreatedId]=null,[cBSCreatedName]=null,[cBSCreatedDate]=null,[cBSEditedId]=@v1 ,[cBSEditedName]=@v2,[cBSEditedDate]=getdate() where cSeqNum=@seq", sqlPar, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "撤消失败!"); return; } } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检测网络连接!(" + ex.Message + ")"); return; } #endregion #region 空车 //是否空车 if (isNullPlate) { try { sqlTran.Commit(); sqlTran.Dispose(); sqlTran = null; } catch (Exception ex) { myHelper.emsg("错误", "执行事务结束异常,请检查网络连接!(" + ex.Message + ")"); return; } myHelper.resetExclusiveLoke(this); checkic.Enabled = true; save.Enabled = false; cancle.Enabled = false; TB12.Enabled = false; OpLog("撤消单据", "成功", TB1.Text + "-" + TB2.Text + "-" + TB5.Text); clearContrlText(); myHelper.smsg("提示", "撤消成功!"); return; } #endregion #region 结算状态 string billtype = dr[3] as string; string billNo = dr[2] as string; //对装对卸车辆 int sapRet = webLogin.RFCGETBILLSTATUS(billNo, billtype, billtype == myHelper.getVA11() ? TB1.Text.Trim() : ""); switch (sapRet) { case 0: try { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!("+ex.Message+")"); return; } myHelper.emsg("错误", "已结算,不能撤消!!"); return; case 1: if (billtype.ToUpper() != myHelper.getVA11().ToUpper()) { //MessageBox.Show("回写IC,现已注释掉,正式版请启用!"); webLogin.RFCUPDATEBILL(myHelper.getFaCode(), "", billNo); } break; default: try { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!(" + ex.Message + ")"); return; } webLogin.SAPHitMsg(sapRet); return; } #endregion try { #region 删除预约单 if (myHelper.update("delete from [sapOrders] where cSeqNum=@seq ", new SqlParameter("@seq", seqNum), sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("错误", "删除预约单异常,撤消操作失败!"); return; } if (billtype.ToUpper() != myHelper.getVA11().ToUpper()) { int ret = myHelper.update("delete from [sapPlanOrders] where cSeqNum=@seq ", new SqlParameter("@seq", seqNum), sqlTran); if (ret <= 0) { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; myHelper.emsg("错误", "删除库存计划异常,撤消操作失败!"); return; } } sqlPar = new SqlParameter[3]; sqlPar[0] = new SqlParameter("@v1", myHelper.getUserId()); sqlPar[1] = new SqlParameter("@seq", seqNum); sqlPar[2] = new SqlParameter("@v2", myHelper.getUserName()); if (myHelper.update("update [realWeighing] with(xlock) set bOut=0,[cDriverName]=null,[cDriverID]=null,[cCusName]=null,[dMadeDate]=null,[cCusCode]=null,[cOrgPlateNum]=null,[cBillNo]=null,[cBillType]=null,[cBillID]=null,[cBSCreatedId]=null,cBSCreatedName=null,[cBSCreatedDate]=null,[cBSEditedDate]=getdate(),[bIsNoPlan]=0,[cBSEditedId]=@v1,cBSEditedName=@v2 where [cSeqNum]=@seq", sqlPar, sqlTran) <= 0) { sqlTran.Rollback(); sqlTran.Dispose(); sqlTran = null; myHelper.emsg("错误", "更新realWeighing异常,撤消操作失败!"); return; } #endregion } catch (Exception ex) { myHelper.emsg("错误", "执行事务中异常,请检查网络连接!(" + ex.Message + ")"); return; } #region 试图提交事务 try { sqlTran.Commit(); sqlTran.Dispose(); sqlTran = null; } catch (Exception ex) { myHelper.emsg("错误", "执行事务结束异常,请检查网络连接!(" + ex.Message + ")"); return; } #endregion #region 清除排队信息 if (!isNullPlate && billtype.ToUpper() != myHelper.getVA11()) { string ic = TB1.Text; webLogin.Queue(ic, seqNum, "DeleteSubmit"); } #endregion clearContrlText(); myHelper.resetExclusiveLoke(this); checkic.Enabled = true; save.Enabled = false; cancle.Enabled = false; TB12.Enabled = false; myHelper.smsg("提示", "撤消成功!"); return; } myHelper.emsg("错误", "数据库连接异常,请检查网络连接!"); return; } myHelper.emsg("错误", "非编辑模式下,不能进行撤消操作!"); } private void BT2_Click(object sender, EventArgs e) { FrmFGValid fgdi = new FrmFGValid(); fgdi.callBackAction += fgdi_callBackAction; fgdi.showDlg(); } void fgdi_callBackAction(object sender, myHelper.OPEventArgs e) { //throw new NotImplementedException(); //主要用于司机信息获取 if (e.param.Length >= 4) { TB9.Text = e.param[0]; TB10.Text = e.param[1]; PB1.Image = myHelper.base64String2ImgObj(e.param[3]); PB2.Image = myHelper.base64String2ImgObj(e.param[2]); } } private void BT1_Click_1(object sender, EventArgs e) { if (VisionSDK.getIdNum() != null) { string userid = VisionSDK.personInfo.userID; DataRow dr = myHelper.getOneRow("select [cPersonName],[olePicture] from [DriverInfo] where [cPersonID]=@id ", new SqlParameter("@id", userid)); if (dr == null) { myHelper.emsg("错误", "司机信息未采集(" + userid + ")!"); return; } PB1.Image = myHelper.base64String2ImgObj(dr.ItemArray.GetValue(1).ToString()); object obj = myHelper.getFirst("select top 1 cFGPic from FGTemplateLib where cPersonID=@v1", new SqlParameter("@v1", userid)); PB2.Image = myHelper.base64String2ImgObj(obj as string); TB9.Text = userid; TB10.Text = dr.ItemArray.GetValue(0).ToString(); } } private void getlist_Click(object sender, EventArgs e) { GetBillLists gbl = new GetBillLists(); gbl.frmParent = this; gbl.callBackAction += gbl_callBackAction; gbl.setPlateNum(TB2.Text); gbl.showDlg(); } void gbl_callBackAction(object sender, myHelper.OPEventArgs e) { //选定的订单信息 if (e != null) { //预约车牌号 TB11.Text = e.param[0]; //商户全称 TB8.Text = e.param[1]; //商户代码 TB7.Text = e.param[2]; //订单号 TB5.Text = e.param[3]; //订单类型 TB6.Text = e.param[4]; //订单日期 TB4.Text = e.param[5]; e.param = null; //查找此公司资料信息 DataRow dr = myHelper.getOneRow("select [cPicture1],[cPicture2] from [clientInfo] where [cCusCode]=@code", new SqlParameter("@code", TB7.Text)); if (dr != null) { if (!(dr[0] is DBNull)) { PB4.Image = myHelper.base64String2ImgObj((string)dr[0]); PB6.Image = PB4.Image; } if (!(dr[1] is DBNull)) { PB5.Image = myHelper.base64String2ImgObj((string)dr[1]); } } } } private void pictureBox2_DoubleClick(object sender, EventArgs e) { SqlParameter[] sqlPar; //编辑状态 if (myHelper.getExclusiveLock(this) && TB7.Text != "") { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string pic = myHelper.img2Base64String(openFileDialog1.FileName); if (pic == null) { MessageBox.Show("读取资料图片失败!!"); return; } PB4.Image = myHelper.base64String2Bmp(pic); PB6.Image = PB4.Image; if (myHelper.getFirst("select AutoId from clientInfo where cCusCode=@code", new SqlParameter("@code", TB7.Text)) != null) { //更新数据 sqlPar = new SqlParameter[4]; sqlPar[0] = new SqlParameter("@v1", pic); sqlPar[1] = new SqlParameter("@code", TB7.Text); sqlPar[2] = new SqlParameter("@v2", myHelper.getUserId()); sqlPar[3] = new SqlParameter("@v3", myHelper.getUserName()); if (myHelper.update("update clientInfo set cPicture1=@v1,[cEditedID]=@v2,[cEditor]=@v3,[dEditedDate]=getdate() where cCusCode=@code", sqlPar) <= 0) { MessageBox.Show("更新商户资料失败!!"); return; } } else { //增加数据 sqlPar = new SqlParameter[6]; sqlPar[0] = new SqlParameter("@v1", TB7.Text); sqlPar[1] = new SqlParameter("@v2", TB8.Text); sqlPar[2] = new SqlParameter("@v3", pic); sqlPar[3] = new SqlParameter("@v4", myHelper.getUserId()); sqlPar[4] = new SqlParameter("@v5", myHelper.getUserName()); sqlPar[5] = new SqlParameter("@v6", myHelper.getFaCode()); if (myHelper.update("insert into clientInfo([cCusCode],[cCusName],[cPicture1],[cCreatedID],[cCreatedName],[dCreatedDate],cFaCode) values(@v1,@v2,@v3,@v4,@v5,getdate(),@v6)", sqlPar) <= 0) { MessageBox.Show("增加商户资料失败!!"); return; } } } } } private void pictureBox1_DoubleClick(object sender, EventArgs e) { SqlParameter[] sqlPar; //编辑状态 if (myHelper.getExclusiveLock(this) && TB7.Text != "") { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string pic = myHelper.img2Base64String(openFileDialog1.FileName); if (pic == null) { MessageBox.Show("读取资料图片失败!!"); return; } PB5.Image = myHelper.base64String2Bmp(pic); PB6.Image = PB5.Image; if (myHelper.getFirst("select AutoId from clientInfo where cCusCode=@code", new SqlParameter("@code", TB7.Text)) != null) { //更新数据 sqlPar = new SqlParameter[4]; sqlPar[0] = new SqlParameter("@v1", pic); sqlPar[1] = new SqlParameter("@code", TB7.Text); sqlPar[2] = new SqlParameter("@v2", myHelper.getUserId()); sqlPar[3] = new SqlParameter("@v3", myHelper.getUserName()); if (myHelper.update("update clientInfo set cPicture2=@v1,[cEditedID]=@v2,[cEditor]=@v3,[dEditedDate]=getdate() where cCusCode=@code", sqlPar) <= 0) { MessageBox.Show("更新商户资料失败!!"); return; } } else { //增加数据 sqlPar = new SqlParameter[5]; sqlPar[0] = new SqlParameter("@v1", TB7.Text); sqlPar[1] = new SqlParameter("@v2", TB8.Text); sqlPar[2] = new SqlParameter("@v3", pic); sqlPar[3] = new SqlParameter("@v4", myHelper.getUserId()); sqlPar[4] = new SqlParameter("@v5", myHelper.getUserName()); if (myHelper.update("insert into clientInfo([cCusCode],[cCusName],[cPicture2],[cCreatedID],[cCreatedName],[dCreatedDate]) values(@v1,@v2,@v3,@v4,@v5,getdate())", sqlPar) <= 0) { MessageBox.Show("增加商户资料失败!!"); return; } } } } } private void PB4_Click(object sender, EventArgs e) { PB6.Image = PB4.Image; } private void PB5_Click(object sender, EventArgs e) { PB6.Image = PB5.Image; } private void clearPic_Click(object sender, EventArgs e) { //清除图片从数据库 } private void edit_Click(object sender, EventArgs e) { //编辑单据 } private void TB2_MouseDoubleClick(object sender, MouseEventArgs e) { if (myHelper.getExclusiveLock(this)) { ((TextBox)sender).ReadOnly = false; } } private void TB5_MouseDoubleClick(object sender, MouseEventArgs e) { } private void TB9_MouseDoubleClick(object sender, MouseEventArgs e) { } private void PB3_Click(object sender, EventArgs e) { PB6.Image = PB3.Image; } private void button2_Click(object sender, EventArgs e) { if (myHelper.getExclusiveLock(this)) { if (MessageBox.Show("确定要清除司机信息?", "", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK) { TB9.Text = ""; TB10.Text = ""; PB1.Image = null; PB2.Image = null; } } } private void button1_Click(object sender, EventArgs e) { if (myHelper.getExclusiveLock(this)) { if (MessageBox.Show("确定要清除预约单?", "", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK) { TB4.Text = ""; TB5.Text = ""; TB6.Text = ""; TB7.Text = ""; TB8.Text = ""; TB11.Text = ""; myHelper.loadDataToGridView(null, dataGridView1); } } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace WPFWorkSample { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int cmdShow); private const int SW_MAXIMIZE = 3; private const int SW_SHOWNORMAL = 1; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); static readonly IntPtr HWND_TOP = new IntPtr(0); static readonly IntPtr HWND_BOTTOM = new IntPtr(1); const UInt32 SWP_NOSIZE = 0x0001; const UInt32 SWP_NOMOVE = 0x0002; const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE; /// <summary> /// /d /// </summary> [DllImport("user32", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string cls, string win); [DllImport("user32")] static extern IntPtr SetForegroundWindow(IntPtr hWnd); [DllImport("user32")] static extern bool IsIconic(IntPtr hWnd); [DllImport("user32")] static extern bool OpenIcon(IntPtr hWnd); // give the mutex a unique name private string MutexName = "##||ThisApp||##"; // declare the mutex private Mutex _mutex; // overload the constructor bool createdNew; private void Application_Startup(object sender, StartupEventArgs e) { //this.StartupUri = new Uri("Views/Dashboard.xaml", UriKind.Relative); } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (e.Args.Length > 0) MutexName = e.Args[0]; // overloaded mutex constructor which outs a boolean // telling if the mutex is new or not. // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx _mutex = new Mutex(true, MutexName, out createdNew); if (!createdNew) { // if the mutex already exists, notify and quit MessageBox.Show("This program is already running"); //Application.Current.Shutdown(0); } if (!createdNew) { ActivateOtherWindow(); //var procs = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName); //foreach (var p in procs.Where(p => p.MainWindowHandle != IntPtr.Zero)) //{ // ShowWindow(p.MainWindowHandle, SW_MAXIMIZE); // SetWindowPos(p.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS); // Application.Current.Shutdown(0); // return; //} Application.Current.Shutdown(0); return; // overload the OnStartup so that the main window // is constructed and visible } //String[] args = System.Environment.GetCommandLineArgs(); // opened by double clicking project file (passed in filename as command line arguments) if (e.Args.Length > 0) { StringBuilder msg = new StringBuilder(); for(int i = 0; i< e.Args.Length; i++) { msg.AppendLine(string.Format("Param {0}: {1}", i, e.Args[i])); } MessageBox.Show(msg.ToString(), "e.Args"); this.MainWindow.Title = MutexName; this.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative); } // open application directly else { this.StartupUri = new Uri("Views/Dashboard.xaml", UriKind.Relative); } } private void ActivateOtherWindow() { var other = FindWindow(null, MutexName); if (other != IntPtr.Zero) { SetForegroundWindow(other); if (IsIconic(other)) OpenIcon(other); } } public bool CheckSingleInstanceCheck(string saleOrder) { bool isExisted = false; // get all app open Application current = App.Current; return isExisted; } //public Application RunApp(string path) //{ // Application app = Application.AttachOrLaunch(new System.Diagnostics.ProcessStartInfo(path)); // return app; //} public void GetAllsWindowInApplication() { foreach (Window window in Application.Current.Windows) { Console.WriteLine(window.Title); } } } }
using LePapeo.Models; using LePapeoGenNHibernate.CAD.LePapeo; using LePapeoGenNHibernate.CEN.LePapeo; using LePapeoGenNHibernate.EN.LePapeo; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WEBLEPAPEO.Controllers { public class RegistradoController : BasicController { // GET: Registrado public ActionResult Index() { RegistradoCEN registradoCEN = new RegistradoCEN(); IList<RegistradoEN> listregEN = registradoCEN.ReadAll(0, -1); IEnumerable<RegistradoViewModel> listreg = new AssemblerRegistrado().ConvertListENToModel(listregEN); return View(listreg); } // GET: Registrado/Details/5 public ActionResult Details(int id) { return View(); } // GET: Registrado/Create public ActionResult Create() { RegistradoViewModel reg = new RegistradoViewModel(); return View(reg); } // POST: Registrado/Create [HttpPost] public ActionResult Create(RegistradoViewModel reg) { try { // TODO: Add insert logic here RegistradoCEN cen = new RegistradoCEN(); cen.New_(reg.Email, reg.Password, reg.FechaInscripcion, reg.Nombre, reg.Apellidos, reg.Fecha_nacimiento); return RedirectToAction("Index"); } catch { return View(); } } // GET: Registrado/Edit/5 public ActionResult Edit(int id) { RegistradoViewModel reg = null; SessionInitialize(); RegistradoEN regEN = new RegistradoCAD(session).ReadOIDDefault(id); reg = new AssemblerRegistrado().ConvertENToModelUI(regEN); SessionClose(); return View(reg); } // POST: Registrado/Edit/5 [HttpPost] public ActionResult Edit(RegistradoViewModel reg) { try { // TODO: Add update logic here RegistradoCEN cen = new RegistradoCEN(); cen.Modify(reg.id, reg.Email, reg.Password, reg.FechaInscripcion, reg.Nombre, reg.Apellidos, reg.Fecha_nacimiento); return RedirectToAction("Index"); } catch { return View(); } } // GET: Registrado/Delete/5 public ActionResult Delete(int id) { try { SessionInitialize(); RegistradoCAD regCAD = new RegistradoCAD(session); RegistradoCEN cen = new RegistradoCEN(regCAD); RegistradoEN regEN = cen.ReadOID(id); RegistradoViewModel reg = new AssemblerRegistrado().ConvertENToModelUI(regEN); SessionClose(); return View(reg); } catch { //Meter aqui el mensaje de error return View(); } } // POST: Registrado/Delete/5 [HttpPost] public ActionResult Delete(RegistradoViewModel reg) { try { // TODO: Add delete logic here new RegistradoCEN().Destroy(reg.id); return RedirectToAction("Index"); } catch { return View(); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DomainValuesFileImporter.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; using CGI.Reflex.Core.Importers.Models; using CGI.Reflex.Core.Queries; using ClosedXML.Excel; using NHibernate; namespace CGI.Reflex.Core.Importers { internal class DomainValuesFileImporter : BaseFileImporter { public DomainValuesFileImporter() : base("DomainValues", 1) { } protected override FileImporterResult GetTemplateImpl(ISession session, Stream stream) { using (var workbook = new XLWorkbook()) { var model = new DomainValueModel(); foreach (var category in (DomainValueCategory[])Enum.GetValues(typeof(DomainValueCategory))) { var ws = workbook.Worksheets.Add(category.ToString()); model.Prepare(ws, category.ToString()); } workbook.SaveAs(stream); } return new FileImporterResult { Stream = stream, ContentType = XlsxContentType, SuggestedFileName = "DomainValues-template.xlsx" }; } protected override FileImporterResult ExportImpl(ISession session, Stream stream) { using (var workbook = new XLWorkbook()) { var model = new DomainValueModel(); var domainValues = session.QueryOver<DomainValue>().List().GroupBy(dv => dv.Category).ToDictionary(g => g.Key, h => h.ToList()); foreach (var category in domainValues.Keys.OrderBy(k => k.ToString())) { var ws = workbook.Worksheets.Add(category.ToString()); model.Prepare(ws, category.ToString()); var row = ws.Row(4); foreach (var domainValue in domainValues[category].OrderBy(dv => dv.DisplayOrder)) { model = new DomainValueModel(); model.FromEntity(domainValue).ToRow(row); row = row.RowBelow(); } } workbook.SaveAs(stream); } return new FileImporterResult { Stream = stream, ContentType = XlsxContentType, SuggestedFileName = string.Format("DomainValues-export-{0:yyyy-MM-dd}.xlsx", DateTime.Now) }; } protected override IEnumerable<ImportOperationLineResult> ImportImpl(ISession session, Stream inputStream) { var result = new List<ImportOperationLineResult>(); try { using (var workbook = new XLWorkbook(inputStream)) { foreach (var ws in workbook.Worksheets) { DomainValueCategory category; if (!Enum.TryParse(ws.Name, true, out category)) { result.Add(new ImportOperationLineResult { Section = ws.Name, LineNumber = -1, Status = LineResultStatus.Rejected, Message = string.Format("Unrecognized category: {0}", ws.Name) }); continue; } Import<DomainValue, DomainValueModel>(session, result, ws, (sess, model) => new DomainValueQuery { Category = category, Name = model.Name }.SingleOrDefault(sess)); } } } catch (Exception ex) { result.Add(new ImportOperationLineResult { LineNumber = -1, Status = LineResultStatus.Error, Exception = ex, Message = ex.Message }); } return result; } protected override void ComplementaryModelInfo(object model, IXLRow row, IXLWorksheet ws) { ((DomainValueModel)model).Category = (DomainValueCategory)Enum.Parse(typeof(DomainValueCategory), ws.Name); } } }
using UnityEngine; using System.Collections; /* public class PhaseOne : Monbehavior { public int fallSpeed = 15; public GameObject player; public float regSpeed = 5; private Vector3 pointOne = new Vector3(0, 0, 0); private Vector2 pointTwo = new Vector3(5, 0, 0); private bool isFalling = false; private bool wait = false; private float waitTime = 5.0f; public void start(){ startPos = transform.position; } public void restart(){ transform.position = startPos; } private void OnTriggerEnter2D(Collider2D collision){ if(collision.tag == "Player"){ GetComponentInParent<PhaseOneAI>().OnPlayerEnter(); slamDown(); } } private void OnTriggerExit2D(Collider2D collision){ GetComponentInParent<PhaseOneAI>().OnTExit(collision); } void sideToSide(){ transform.position = Vector3.Lerp (pointOne, pointTwo, Mathf.PingPong(Time.time*speed, 1.0f)); } void slamDown(){ regSpeed = fallSpeed; transform.position.Vector3(transform.posx, 0, 0); waitTime -= Time.deltaTime; if(waitTime == 0) rise(); } void rise(){ transform.position(pointOne); waitTime = 5.0f; regSpeed = 5; sideToSide(); } } */
using System; using System.Linq; using System.Windows.Forms; using Relocation.Data; using System.Data.Objects; using Relocation.Classes; using Relocation.Base; using Relocation.Com; using Relocation.Forms.ListBase; namespace Relocation { public partial class projectList : ProjectListBase, IPrintForm { public projectList() : base() { Initialize(); } public projectList(Session session) : base(session) { Initialize(); } #region 初始化 private void Initialize() { InitializeComponent(); this.ObjectQuery = this.Session.DataModel.Projects; this.InitializeRole(); this.InitializeSearch(); this.projectDataview.init(); } /// <summary> /// 初始化权限 /// </summary> private void InitializeRole() { ControlTag roleTag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR)); this.ButtonAdd.Tag = roleTag; this.ButtonEdit.Tag = roleTag; this.ButtonDel.Tag = roleTag; } /// <summary> /// 初始化搜索 /// </summary> private void InitializeSearch() { this.Field_S_Project.Tag = new ControlTag(null, null, new SearchInfo(Projects.GetPropName(t => t.projectName))); } #endregion //页面刷新 public override void Refresh() { try { this.Reload(); } catch (Exception ex) { Log.Error(ex.Message); } } //新增 private void add_Click(object sender, EventArgs e) { try { using (ProjectWindow projectWin = new ProjectWindow(Session)) { projectWin.Text = "项目登记"; if (projectWin.ShowDialog().IsOK()) this.Refresh(); } } catch (Exception ex) { Log.Error(ex.Message); MyMessagebox.Error("操作失败!"); } } //修改 private void alter_Click(object sender, EventArgs e) { try { Projects p = this.GetSelectEntity(); ProjectWindow projectWin = new ProjectWindow(Session, p); projectWin.Text = "项目修改"; if (projectWin.ShowDialog().IsOK()) { if (p.projectID == Session.Project.projectID) { MainWindow mainWin = (MainWindow)this.FindForm().Parent.FindForm(); mainWin.curProject.Text = p.projectName; } this.Refresh(); } } catch (Exception ex) { Log.Error(ex.Message); MyMessagebox.Error("操作失败!"); } } //删除 private void delete_Click(object sender, EventArgs e) { try { Projects project = this.GetSelectEntity(); if (project.projectID == Session.Project.projectID) { MyMessagebox.Show("当前是系统选择项目不允许删除!"); return; } else if (project.isUsed) { MyMessagebox.Show("您所要删除的项目下已有拆迁户,不能删除!"); return; } else { if (MyMessagebox.Confirm("您确定要删除该项目吗?") == DialogResult.Yes) { string strPath; if (project.filePath != null) strPath = project.filePath; else strPath = ""; if (Session.DataModel.Delete(project) < 1) { MyMessagebox.Show("删除失败!"); return; } else { if (string.IsNullOrEmpty(strPath.Trim())) { if (System.IO.File.Exists(strPath)) System.IO.File.Delete(strPath); else MyMessagebox.Show("许可证文件不存在,有可能被删除或转移!"); } } } } this.Refresh(); } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); MyMessagebox.Error("操作失败!"); } } #region IPrintForm 成员 void IPrintForm.Print() { GridToExcel.print(this.projectDataview); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using VSchool.Data.Entities; namespace VSchool.Data.Entities { public class Subject : BaseEntity { public string Label { get; set; } public string Description { get; set; } public Branch Branch { get; set; } public Guid BranchID { get; set; } } }
namespace Checkout.Payment.Query.Seedwork.Extensions { public class TryResult<T> : ITryResult<T> { public bool Success { get; } public string Message { get; } public T Result { get; private set; } public static TryResult<T> CreateSuccessResult(T result) { return new TryResult<T>(result, true); } public static TryResult<T> CreateFailResult(T result) { return new TryResult<T>(result, false); } public static TryResult<T> CreateFailResult(string failMessage) { return new TryResult<T>(false, failMessage); } public static TryResult<T> CreateFailResult() { return new TryResult<T>(false); } private TryResult(T result, bool success, string message = null) { Result = result; Success = success; Message = message; } private TryResult(bool success, string message = null) { Success = success; Message = message; } } public class TryResult : ITryResult { public bool Success { get; } public string Message { get; } private TryResult(bool success, string message = null) { Success = success; Message = message; } public static TryResult CreateSuccessResult() { return new TryResult(true); } public static TryResult CreateFailResult(string failMessage = null) { return new TryResult(false, failMessage); } } }
using System; using Strategy.Interface.Duckling; namespace Strategy.Fly.Duckling { class CanFly : IFly { public void Fly() { Console.WriteLine("I can fly, yeah!"); } } }
namespace LuaLu { using UnityEngine; using System.Collections; using UnityEditor; using System.IO; [NoLuaBinding] [CustomEditor(typeof(LuaComponent))] public class LuaInspector : Editor { // properities of LuaComponent SerializedProperty m_luaFileProp; SerializedProperty m_fileBoundProp; void OnEnable () { // Setup the SerializedProperties. m_luaFileProp = serializedObject.FindProperty ("m_luaFile"); m_fileBoundProp = serializedObject.FindProperty ("m_fileBound"); // if the lua file is not bound yet, open save file panel to create a new lua file if (!m_fileBoundProp.boolValue) { string path = LuaFileHandler.NewComponentLuaFile(m_luaFileProp.stringValue); if (path.Length != 0) { // write file path back m_luaFileProp.stringValue = path; m_fileBoundProp.boolValue = true; serializedObject.ApplyModifiedProperties (); } else { DestroyImmediate (target); } } } public override void OnInspectorGUI() { // Update the serializedProperty - always do this in the beginning of OnInspectorGUI. serializedObject.Update (); // text field for lua file path EditorGUILayout.BeginHorizontal(); GUILayout.Label("Lua File:"); EditorGUILayout.LabelField(Path.GetFileNameWithoutExtension(m_luaFileProp.stringValue), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight), GUILayout.ExpandWidth(true)); Rect filenameRect = GUILayoutUtility.GetLastRect(); EditorGUILayout.EndHorizontal(); // if file not exist, show error and re-bound button // if file exists, check file name click, single click to select, double click to open if(!File.Exists(m_luaFileProp.stringValue)) { // create rebound ui EditorGUILayout.BeginHorizontal(); GUIStyle style = new GUIStyle(EditorStyles.label); style.normal.textColor = Color.red; EditorGUILayout.LabelField("The lua file can not be located.", style); if(GUILayout.Button("Browse")) { string path = EditorUtility.OpenFilePanel("Locate Lua Script", "", "lua"); if(path.Length != 0) { string appPath = Directory.GetParent(Application.dataPath).FullName; if(path.StartsWith(appPath)) { path = path.Substring(appPath.Length); if(path.StartsWith("/")) { path = path.Substring(1); } } m_luaFileProp.stringValue = path; } } EditorGUILayout.EndHorizontal(); } else { // check file name click, single click to select, double click to open Event e = Event.current; if(e.type == EventType.MouseDown && e.button == 0 && filenameRect.Contains(e.mousePosition)) { if(e.clickCount == 1) { UnityEngine.Object asset = AssetDatabase.LoadMainAssetAtPath(m_luaFileProp.stringValue); EditorGUIUtility.PingObject(asset); e.Use(); } else if(e.clickCount == 2) { UnityEngine.Object asset = AssetDatabase.LoadMainAssetAtPath(m_luaFileProp.stringValue); AssetDatabase.OpenAsset(asset); e.Use(); } } // check lua folder, must in Assets/Resources if(!m_luaFileProp.stringValue.StartsWith("Assets/Resources/")) { GUIStyle style = new GUIStyle(EditorStyles.label); style.normal.textColor = Color.red; style.wordWrap = true; EditorGUILayout.LabelField("Currently you must place lua script in Assets/Resources folder, otherwise it won't run", style); } } // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI. serializedObject.ApplyModifiedProperties (); } } }
using Pchp.Core; using System; using System.Collections.Generic; using System.Text; namespace OCP.ShareNS { /** * Interface IShareHelper * * @package OCP\Share * @since 12 */ public interface IShareHelper { /** * @param Node node * @return array [ users => [Mapping uid => pathForUser], remotes => [Mapping cloudId => pathToMountRoot]] * @since 12 */ PhpArray getPathsForAccessList(Files.Node node); } }
/** 版本信息模板在安装目录下,可自行修改。 * OA_RISKEDURECEIVER.cs * * 功 能: N/A * 类 名: OA_RISKEDURECEIVER * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2014/7/22 15:35:10 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; using System.Data; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility;//Please add references namespace PDTech.OA.DAL { /// <summary> /// 数据访问类:OA_RISKEDURECEIVER /// </summary> public partial class OA_RISKEDURECEIVER { public OA_RISKEDURECEIVER() {} #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(decimal? EDUCATION_ID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from OA_RISKEDURECEIVER"); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); SqlParameter[] parameters = { new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4) }; parameters[0].Value = EDUCATION_ID; return DbHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// 增加一条数据 /// </summary> public bool Add(PDTech.OA.Model.OA_RISKEDURECEIVER model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into OA_RISKEDURECEIVER("); strSql.Append("EDUCATION_ID,RECEIVER_ID,READ_STATUS,READ_TIME)"); strSql.Append(" values ("); strSql.Append("@EDUCATION_ID,@RECEIVER_ID,@READ_STATUS,@READ_TIME)"); SqlParameter[] parameters = { new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4), new SqlParameter("@RECEIVER_ID", SqlDbType.Decimal,4), new SqlParameter("@READ_STATUS", SqlDbType.Decimal,4), new SqlParameter("@READ_TIME", SqlDbType.DateTime)}; parameters[0].Value = model.EDUCATION_ID; parameters[1].Value = model.RECEIVER_ID; parameters[2].Value = model.READ_STATUS; parameters[3].Value = model.READ_TIME; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 更新一条数据 /// </summary> public bool Update(PDTech.OA.Model.OA_RISKEDURECEIVER model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update OA_RISKEDURECEIVER set "); strSql.Append("RECEIVER_ID=@RECEIVER_ID,"); strSql.Append("READ_STATUS=@READ_STATUS,"); strSql.Append("READ_TIME=@READ_TIME"); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); SqlParameter[] parameters = { new SqlParameter("@RECEIVER_ID", SqlDbType.Decimal,4), new SqlParameter("@READ_STATUS", SqlDbType.Decimal,4), new SqlParameter("@READ_TIME", SqlDbType.DateTime), new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4)}; parameters[0].Value = model.RECEIVER_ID; parameters[1].Value = model.READ_STATUS; parameters[2].Value = model.READ_TIME; parameters[3].Value = model.EDUCATION_ID; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 更新一条数据 /// </summary> public bool UpdateState(PDTech.OA.Model.OA_RISKEDURECEIVER model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update OA_RISKEDURECEIVER set "); strSql.Append("READ_STATUS=@READ_STATUS,"); strSql.Append("READ_TIME=@READ_TIME,"); strSql.Append("READ_COUNT=@READ_COUNT"); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); strSql.Append(" and RECEIVER_ID=@RECEIVER_ID"); SqlParameter[] parameters = { new SqlParameter("@READ_STATUS", SqlDbType.Decimal,4), new SqlParameter("@READ_TIME", SqlDbType.DateTime), new SqlParameter("@READ_COUNT", SqlDbType.Decimal,4), new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4), new SqlParameter("@RECEIVER_ID", SqlDbType.Decimal,4)}; parameters[0].Value = model.READ_STATUS; parameters[1].Value = model.READ_TIME; parameters[2].Value = model.READ_COUNT; parameters[3].Value = model.EDUCATION_ID; parameters[4].Value = model.RECEIVER_ID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } public bool UpdateReadCount(decimal? EDUCATION_ID, decimal? RECEIVER_ID) { string sql = string.Format("update OA_RISKEDURECEIVER set READ_COUNT=READ_COUNT+1 where EDUCATION_ID = {0} and RECEIVER_ID = {1}", EDUCATION_ID, RECEIVER_ID); int rows = DbHelperSQL.ExecuteSql(sql); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal? EDUCATION_ID) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from OA_RISKEDURECEIVER "); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); SqlParameter[] parameters = { new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4) }; parameters[0].Value = EDUCATION_ID; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string EDUCATION_IDlist) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from OA_RISKEDURECEIVER "); strSql.Append(" where EDUCATION_ID in (" + EDUCATION_IDlist + ") "); int rows=DbHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.OA_RISKEDURECEIVER GetModel(decimal? EDUCATION_ID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select EDUCATION_ID,RECEIVER_ID,READ_STATUS,READ_TIME,READ_COUNT from OA_RISKEDURECEIVER "); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); SqlParameter[] parameters = { new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4) }; parameters[0].Value = EDUCATION_ID; PDTech.OA.Model.OA_RISKEDURECEIVER model=new PDTech.OA.Model.OA_RISKEDURECEIVER(); DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters); if(ds.Tables[0].Rows.Count>0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.OA_RISKEDURECEIVER GetModel(decimal? EDUCATION_ID, decimal userID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select EDUCATION_ID,RECEIVER_ID,READ_STATUS,READ_TIME,READ_COUNT from OA_RISKEDURECEIVER "); strSql.Append(" where EDUCATION_ID=@EDUCATION_ID "); strSql.Append(" and RECEIVER_ID=@RECEIVER_ID "); SqlParameter[] parameters = { new SqlParameter("@EDUCATION_ID", SqlDbType.Decimal,4), new SqlParameter("@RECEIVER_ID", SqlDbType.Decimal)}; parameters[0].Value = EDUCATION_ID; parameters[1].Value = userID; PDTech.OA.Model.OA_RISKEDURECEIVER model = new PDTech.OA.Model.OA_RISKEDURECEIVER(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.OA_RISKEDURECEIVER DataRowToModel(DataRow row) { PDTech.OA.Model.OA_RISKEDURECEIVER model=new PDTech.OA.Model.OA_RISKEDURECEIVER(); if (row != null) { if (row["EDUCATION_ID"] != null) { model.EDUCATION_ID = decimal.Parse(row["EDUCATION_ID"].ToString()); } if(row["RECEIVER_ID"]!=null && row["RECEIVER_ID"].ToString()!="") { model.RECEIVER_ID=decimal.Parse(row["RECEIVER_ID"].ToString()); } if(row["READ_STATUS"]!=null && row["READ_STATUS"].ToString()!="") { model.READ_STATUS=decimal.Parse(row["READ_STATUS"].ToString()); } if(row["READ_TIME"]!=null && row["READ_TIME"].ToString()!="") { model.READ_TIME=DateTime.Parse(row["READ_TIME"].ToString()); } if (row["READ_COUNT"] != null && row["READ_COUNT"].ToString() != "") { model.READ_COUNT = decimal.Parse(row["READ_COUNT"].ToString()); } } return model; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select EDUCATION_ID,RECEIVER_ID,READ_STATUS,READ_TIME,READ_COUNT "); strSql.Append(" FROM OA_RISKEDURECEIVER "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) FROM OA_RISKEDURECEIVER "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } object obj = DbHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
using PSA.DataModel; namespace PSA.DataRepository { /// <summary> /// Interface for data repository. /// /// </summary> public interface IDatabaseRepo { void SaveResult(PageSpeedData pData); } }
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Tizen.NUI; using Tizen.NUI.BaseComponents; using Tizen.NUI.Components; namespace Tizen_NUI_SampleAccount { /// <summary> /// Content page of account sign out /// </summary> public partial class AccountSignOut : ContentPage { /// <summary> /// Initializes a new instance of the <see cref="AccountSignOut"/> class. /// </summary> /// <param name="accountId"> Parameter contains ID of user account</param> /// <param name="userId"> User ID witch user log in with</param> public AccountSignOut(int accountId, string userId) { InitializeComponent(); AccountLabel.Text = userId; SignOutButton.Clicked += SignOutClicked; } /// <summary> /// Event when "SIGN OUT" button is clicked. /// </summary> /// <param name="sender"> Parameter about which object is invoked the current event. </param> /// <param name="args"> Event arguments</param> public void SignOutClicked(object sender, EventArgs args) { // var button = new Button() { Text = "OK", }; button.Clicked += (object s, ClickedEventArgs a) => { Navigator?.Pop(); AccountSignIn xamlPage = new AccountSignIn(); Navigator?.Push(xamlPage); }; DialogPage.ShowAlertDialog("Account Deleted", "ID : " + AccountLabel.Text, button); } } }
using AutoMapper; using Crt.Data.Database.Entities; using Crt.Model; using Crt.Model.Dtos.CodeLookup; using Crt.Model.Dtos.Permission; using Crt.Model.Dtos.Role; using Crt.Model.Dtos.RolePermission; using Crt.Model.Dtos.User; using Crt.Model.Dtos.UserRole; using Crt.Model.Dtos.ServiceArea; using Crt.Model.Dtos.Region; using Crt.Model.Dtos.District; using Crt.Model.Dtos.Note; using Crt.Model.Dtos.Project; using Crt.Model.Dtos.FinTarget; using Crt.Model.Dtos.Element; using Crt.Model.Dtos.QtyAccmp; using Crt.Model.Dtos.Tender; using Crt.Model.Dtos.Segments; using Crt.Model.Dtos.Ratio; namespace Crt.Data.Mappings { public class EntityToModelProfile : Profile { public EntityToModelProfile() { SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); DestinationMemberNamingConvention = new PascalCaseNamingConvention(); CreateMap<CrtPermission, PermissionDto>(); CreateMap<CrtRole, RoleDto>(); CreateMap<CrtRole, RoleCreateDto>(); CreateMap<CrtRole, RoleUpdateDto>(); CreateMap<CrtRole, RoleSearchDto>(); CreateMap<CrtRole, RoleDeleteDto>(); CreateMap<CrtRolePermission, RolePermissionDto>(); CreateMap<CrtSystemUser, UserDto>(); CreateMap<CrtSystemUser, UserCreateDto>(); CreateMap<CrtSystemUser, UserCurrentDto>(); CreateMap<CrtSystemUser, UserSearchDto>(); CreateMap<CrtSystemUser, UserUpdateDto>(); CreateMap<CrtSystemUser, UserDeleteDto>(); CreateMap<CrtSystemUser, UserManagerDto>(); CreateMap<AdAccount, AdAccountDto>(); CreateMap<CrtUserRole, UserRoleDto>(); CreateMap<CrtCodeLookup, CodeLookupDto>(); CreateMap<CrtRegionUser, RegionUserDto>(); CreateMap<CrtServiceArea, ServiceAreaDto>(); CreateMap<CrtRegion, RegionDto>(); CreateMap<CrtRegionDistrict, RegionDistrictDto>(); CreateMap<CrtDistrict, DistrictDto>(); CreateMap<CrtProject, ProjectDto>() .ForMember(x => x.Notes, opt => opt.MapFrom(x => x.CrtNotes)); CreateMap<CrtProject, ProjectCreateDto>(); CreateMap<CrtProject, ProjectUpdateDto>(); CreateMap<CrtProject, ProjectDeleteDto>(); CreateMap<CrtProject, ProjectSearchDto>() .ForMember(x => x.RegionNumber, opt => opt.MapFrom(x => x.Region.RegionNumber)) .ForMember(x => x.RegionName, opt => opt.MapFrom(x => x.Region.RegionName)); CreateMap<CrtProject, ProjectPlanDto>() .ForMember(x => x.FinTargets, opt => opt.MapFrom(x => x.CrtFinTargets)); CreateMap<CrtProject, ProjectTenderDto>() .ForMember(x => x.Tenders, opt => opt.MapFrom(x => x.CrtTenders)) .ForMember(x => x.QtyAccmps, opt => opt.MapFrom(x => x.CrtQtyAccmps)); CreateMap<CrtNote, NoteDto>() .ForMember(x => x.UserId, opt => opt.MapFrom(x => x.AppCreateUserid)) .ForMember(x => x.NoteDate, opt => opt.MapFrom(x => x.AppCreateTimestamp)); CreateMap<CrtProject, ProjectLocationDto>() .ForMember(x => x.Ratios, opt => opt.MapFrom(x => x.CrtRatios)) .ForMember(x => x.Segments, opt => opt.MapFrom(x => x.CrtSegments)); CreateMap<CrtNote, NoteCreateDto>(); CreateMap<CrtNote, NoteUpdateDto>(); CreateMap<CrtElement, ElementDto>(); CreateMap<CrtElement, ElementListDto>(); CreateMap<CrtElement, ElementCreateDto>(); CreateMap<CrtElement, ElementUpdateDto>(); CreateMap<CrtFinTarget, FinTargetDto>(); CreateMap<CrtFinTarget, FinTargetListDto>(); CreateMap<CrtFinTarget, FinTargetCreateDto>(); CreateMap<CrtQtyAccmp, QtyAccmpDto>(); CreateMap<CrtQtyAccmp, QtyAccmpListDto>(); CreateMap<CrtQtyAccmp, QtyAccmpCreateDto>(); CreateMap<CrtTender, TenderDto>(); CreateMap<CrtTender, TenderListDto>(); CreateMap<CrtTender, TenderCreateDto>(); CreateMap<CrtSegment, SegmentDto>(); CreateMap<CrtSegment, SegmentCreateDto>(); CreateMap<CrtSegment, SegmentUpdateDto>(); CreateMap<CrtSegment, SegmentListDto>(); CreateMap<CrtSegment, SegmentGeometryListDto>(); CreateMap<CrtRatio, RatioDto>(); CreateMap<CrtRatio, RatioCreateDto>(); CreateMap<CrtRatio, RatioListDto>(); CreateMap<CrtRatio, RatioUpdateDto>(); CreateMap<CrtCodeLookup, CodeLookupListDto>(); CreateMap<CrtCodeLookup, CodeLookupCreateDto>(); CreateMap<CrtCodeLookup, CodeLookupUpdateDto>(); } } }
namespace HCL.Academy.Model { public class RegisterCandidateResponse { public int statusCode { get; set; } public ResponseBody responseBody { get; set; } } public class ResponseBody { public string username { get; set; } public string message { get; set; } } }
using Student.Model; using Student.Service.interfaces; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Cors; namespace Student.API.API { [EnableCors(origins: "*", headers: "*", methods: "*")] public class ClassesController : ApiController { IClassService _classService; public ClassesController(IClassService classService) { _classService = classService; } // GET: api/Classes public async Task<IHttpActionResult> GetAsync() { var classList = await Task.Run(() => _classService.GetAll().AsEnumerable()); return Ok(classList); } // POST: api/Classes public async Task<IHttpActionResult> Post(Classes @class) { try { var _class = await Task.Run(() => _classService.Create(@class)); return Ok(_class); } catch (Exception ex) { return BadRequest(ex.Message); } } // PUT: api/Classes/5 public async Task<IHttpActionResult> Put([FromBody]Classes @class) { try { await Task.Run(() => _classService.Update(@class)); return Ok(@class); } catch (Exception ex) { return BadRequest(ex.Message); } } // DELETE: api/Classes/5 public async Task<IHttpActionResult> Delete(int id) { try { var @class = await Task.Run(() => _classService.FindById(id)); _classService.Delete(@class); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Brachi.Personas.Business; using Brachi.Personas.Business.Entity; public partial class Clon : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { CargarPersonas(); if (!IsPostBack) { LlenarDDLSexo(); } } catch (Exception ex) { Title = ex.Message; } } private void LinkButton() { EntPersona ent = new EntPersona(); LinkButton lnk = new LinkButton(); lnk.ID = "lnk" + ent.Id; lnk.ToolTip = "Tu id es: " + ent.Id; lnk.CommandArgument = ent.Id.ToString(); lnk.Text = ent.Nombre; lnk.Click += new EventHandler(lnk_Click); phPersonas.Controls.Add(lnk); } private void LlenarDDLSexo() { try { //List<EntSexo> lst = new BusPersona().CargarCombo(); ddlSexo.DataSource = new BusPersona().CargarCombo(); ddlSexo.DataTextField = "Nombre"; ddlSexo.DataValueField = "Id"; ddlSexo.DataBind(); ddlSexo1.DataSource = new BusPersona().CargarCombo(); ddlSexo1.DataTextField = "Nombre"; ddlSexo1.DataValueField = "Id"; ddlSexo1.DataBind(); } catch (Exception ex) { MostrarMensaje(ex.Message); } } private void CargarPersonas() { List<EntPersona> lst = new BusPersona().Obtener(); LiteralControl literal = new LiteralControl(); literal.Text = ""; foreach (EntPersona ent in lst) { literal.Text += "<tr>"; literal.Text += " <td>"; literal.Text += ent.Id; literal.Text += " </td>"; literal.Text += " <td>"; phPersonas.Controls.Add(literal); LinkButton lnk = new LinkButton(); lnk.ID = "lnk" + ent.Id; lnk.ToolTip = "Tu id es: " + ent.Id; lnk.CommandArgument = ent.Id.ToString(); lnk.Text = ent.Nombre; lnk.Click += new EventHandler(lnk_Click); phPersonas.Controls.Add(lnk); literal = new LiteralControl(); literal.Text += " </td>"; literal.Text += " <td>"; literal.Text += ent.fechaNacimiento.ToString("dd/MM/yyyy"); literal.Text += " </td>"; literal.Text += " <td>"; literal.Text += ent.Mail; literal.Text += " </td>"; literal.Text += " <td>"; literal.Text += ent.Sueldo.ToString("C"); literal.Text += " </td>"; literal.Text += " <td>"; literal.Text += ent.Sexo.Nombre; literal.Text += " </td>"; literal.Text += " <td>"; if (ent.Estatus) literal.Text += " <input ID=\"Labefl343\" type=\"checkbox\" checked disabled></input>"; else literal.Text += " <input ID=\"Labefl343\" type=\"checkbox\" disabled></input>"; literal.Text += " </td>"; literal.Text += "</tr>"; } phPersonas.Controls.Add(literal); } protected void btnAgregar_Click(object sender, EventArgs e) { try { EntPersona ent = new EntPersona(); ent.Nombre = txtNomb.Text; ent.Paterno = txtPate.Text; ent.Materno = txtMate.Text; ent.fechaNacimiento = Convert.ToDateTime(txtFech.Text); ent.Mail = txtMail.Text; ent.Sueldo = Convert.ToDouble(txtSuel.Text); ent.SexoId = Convert.ToInt32(ddlSexo.SelectedValue); ent.Estatus = chkEstatus.Checked; new BusPersona().agregar(ent); Response.Redirect(Request.CurrentExecutionFilePath); } catch (Exception ex) { MostrarMensaje(ex.Message); } } private void MostrarMensaje(string mensaje) { mensaje = mensaje.Replace("/n", " ").Replace("/r", " ").Replace("'", " ").Replace("//r", " ").Replace("//n", " "); mensaje = "alert('" + mensaje + "');"; ScriptManager.RegisterStartupScript(this, GetType(), "", mensaje, true); } protected void btnActualizar_Click(object sender, EventArgs e) { try { EntPersona ent = new EntPersona(); ent.Id = Convert.ToInt32(hfId.Value); ent.Nombre = txtNomb.Text; ent.Paterno = txtPate.Text; ent.Materno = txtMate.Text; ent.fechaNacimiento = Convert.ToDateTime(txtFech.Text); ent.Mail = txtMail.Text; ent.Sueldo = Convert.ToDouble(txtSuel.Text); ent.SexoId = Convert.ToInt32(ddlSexo.SelectedValue); ent.Estatus = chkEstatus.Checked; new BusPersona().Actualizar(ent); //No olvidar siempre planchar ala clase BusPersona con la entidad persona en su metodo agregar Response.Redirect(Request.CurrentExecutionFilePath); } catch (Exception ex) { Title = ex.Message; } } protected void btnBorrar_Click(object sender, EventArgs e) { try { int id = Convert.ToInt32(hfId.Value); //hfId.Value = id.ToString(); new BusPersona().Eliminar(id); //por que else metodo anterior no regresa nada solo se coloca new Response.Redirect(Request.CurrentExecutionFilePath); } catch (Exception ex) { Title = ex.Message; } } protected void btnGuardar_Click(object sender, EventArgs e) { } void lnk_Click(object sender, EventArgs e) { try { LinkButton lnk = (LinkButton)sender; int id = Convert.ToInt32(lnk.CommandArgument); hfId.Value = id.ToString(); EntPersona ent = new BusPersona().Obtener(id); txtNomb.Text = ent.Nombre; txtPate.Text = ent.Paterno; txtMate.Text = ent.Materno; txtFech.Text = ent.fechaNacimiento.ToString("dd/MM/yyyy"); txtMail.Text = ent.Mail; txtSuel.Text = ent.Sueldo.ToString(); ddlSexo.SelectedValue = ent.SexoId.ToString(); chkEstatus.Checked = ent.Estatus; } catch (Exception ex) { Title = ex.Message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Frameworks; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; using Xunit; namespace Client.V3Test { public class DependencyInfoTests : TestBase { [Theory] [InlineData("https://www.nuget.org/api/v2")] [InlineData("https://api.nuget.org/v3/index.json")] public async Task DependencyInfo_RavenDb(string source) { // Arrange List<PackageIdentity> packages = new List<PackageIdentity>() { new PackageIdentity("RavenDB.client", NuGetVersion.Parse("2.0.2281-Unstable")), }; NuGetFramework projectFramework = NuGetFramework.Parse("net45"); var repo = GetSourceRepository(source); var depResource = repo.GetResource<DepedencyInfoResource>(); // Act var results = await depResource.ResolvePackages(packages, projectFramework, includePrerelease: true); // Assert Assert.True(results.Any(package => StringComparer.OrdinalIgnoreCase.Equals(package.Id, "RavenDB.client") && package.Version == NuGetVersion.Parse("2.0.2281-Unstable"))); } [Theory] [InlineData("https://www.nuget.org/api/v2")] [InlineData("https://api.nuget.org/v3/index.json")] public async Task DependencyInfo_Mvc(string source) { // Arrange List<PackageIdentity> packages = new List<PackageIdentity>() { new PackageIdentity("Microsoft.AspNet.Mvc.Razor", NuGetVersion.Parse("6.0.0-beta1")), }; NuGetFramework projectFramework = NuGetFramework.Parse("aspnet50"); var repo = GetSourceRepository(source); var depResource = repo.GetResource<DepedencyInfoResource>(); // Act var results = await depResource.ResolvePackages(packages, projectFramework, includePrerelease: true); // Assert Assert.True(results.Any(package => package.Id == "Microsoft.AspNet.Mvc.Razor" && package.Version == NuGetVersion.Parse("6.0.0-beta1"))); } [Theory] [InlineData("https://www.nuget.org/api/v2")] [InlineData("https://api.nuget.org/v3/index.json")] public async Task DependencyInfo_XunitExtensibilityCore200RC4Build2924(string source) { // Arrange var sourceRepo = GetSourceRepository(source); var resource = sourceRepo.GetResource<DepedencyInfoResource>(); var version = new NuGetVersion("2.0.0-rc4-build2924"); // Act var resolved = await resource.ResolvePackages("xunit.extensibility.core", NuGetFramework.Parse("net452"), includePrerelease: true, token: CancellationToken.None); // Assert var targetPackages = resolved.Where(p => StringComparer.OrdinalIgnoreCase.Equals(p.Id, "xunit.abstractions")).Where(p => p.Version == version); Assert.Equal(1, targetPackages.Count()); } [Theory] [InlineData("https://www.nuget.org/api/v2")] [InlineData("https://api.nuget.org/v3/index.json")] public async Task DependencyInfo_XunitCore200RC4Build2924(string source) { // Arrange var sourceRepo = GetSourceRepository(source); var resource = sourceRepo.GetResource<DepedencyInfoResource>(); var version = new NuGetVersion("2.0.0-rc4-build2924"); // Act var resolved = await resource.ResolvePackages("xunit.core", NuGetFramework.Parse("net452"), includePrerelease: true, token: CancellationToken.None); // Assert var targetPackages = resolved.Where(p => StringComparer.OrdinalIgnoreCase.Equals(p.Id, "xunit.abstractions")).Where(p => p.Version == version); Assert.Equal(1, targetPackages.Count()); } [Theory] [InlineData("https://www.nuget.org/api/v2")] [InlineData("https://api.nuget.org/v3/index.json")] public async Task DependencyInfo_Xunit200RC4Build2924(string source) { // Arrange var sourceRepo = GetSourceRepository(source); var resource = sourceRepo.GetResource<DepedencyInfoResource>(); var version = new NuGetVersion("2.0.0-rc4-build2924"); // Act var resolved = await resource.ResolvePackages("xunit", NuGetFramework.Parse("net452"), includePrerelease: true, token: CancellationToken.None); // Assert var targetPackages = resolved.Where(p => StringComparer.OrdinalIgnoreCase.Equals(p.Id, "xunit.abstractions")).Where(p => p.Version == version); Assert.Equal(1, targetPackages.Count()); } } }
using UnityEngine; using System.Collections; public class SplashScreen : MonoBehaviour { private float splashScreenWaitTime = 5f; // in seconds private float gopherIntroductionWaitTime = 1f; // in seconds // Use this for initialization public AudioClip sound; private AudioSource source; // Use this for initialization void Start () { Debug.Log ("Initializing sound object"); source = GetComponent<AudioSource>(); } public void Play (){ Debug.Log ("PLAYING"); source.PlayOneShot(sound,1.0f); } IEnumerator SwitchToMainMenu(){ Debug.Log ("splash screen \"loading\""); Play (); yield return new WaitForSeconds (splashScreenWaitTime); Debug.Log ("splash screen \"loaded\""); SwitchPanels.changePanelStatic ("pSplash:deactivate,pMain:activate"); } bool first = true; // Update is called once per frame void Update () { if (first && !Application.isShowingSplashScreen) { first = false; StartCoroutine (SwitchToMainMenu ()); } //Debug.Log (Input.gyro.attitude); } }
using Finances.Common.Data; using Finances.Common.Helpers; using Finances.Core.Application.Interfaces; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Resx = Finances.Common.Resources; using static Finances.Common.Helpers.Enum; namespace Finances.Core.Application.Authorization.Commands.SignOut { public class SignOutHandler : IRequestHandler<SignOut, JsonDefaultResponse> { private readonly IFinancesDbContext _context; private readonly IMediator _mediator; private readonly CryptoHelper cryptoHelper; private readonly AppSettings Configuration; public SignOutHandler(IFinancesDbContext context, IMediator mediator, IOptions<AppSettings> configuration) { _context = context; _mediator = mediator; Configuration = configuration.Value; cryptoHelper = new CryptoHelper(); } public async Task<JsonDefaultResponse> Handle(SignOut request, CancellationToken cancellationToken) { var userLogged = await _context.User .Where(u => u.Username == request.Username) .Where(u => u.Status == Status.Active) .SingleOrDefaultAsync(); if (userLogged == null) return new JsonDefaultResponse { Success = false, Message = Resx.Strings.ErrorSearchingForUsers }; var tokenInUse = await _context.LoginJwt .Where(t => t.UserId == userLogged.Id) .Where(t => t.ExpireDate > DateTime.Now) .Where(t => t.Status == Status.Active) .SingleOrDefaultAsync(); if (tokenInUse == null) return new JsonDefaultResponse { Success = false, Message = Resx.Strings.ErrorUserNotLoggedYet }; tokenInUse.Status = Status.Expired; tokenInUse.UpdatedDate = DateTime.Now; try { _context.Entry(tokenInUse).State = EntityState.Modified; await _context.SaveChangesAsync(cancellationToken); } catch { return new JsonDefaultResponse { Success = false, Message = Resx.Strings.ErrorLoggingOut }; } return new JsonDefaultResponse { Success = true, Message = Resx.Strings.SuccessUserLoggedOut }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using BreakAway.Domain; using Studentum.Infrastructure; using Studentum.Infrastructure.Caching; using Studentum.Infrastructure.Repository; namespace BreakAway.Web { public class BreakAwayApplicationStarter : ApplicationStarterBase { public BreakAwayApplicationStarter() { RegisterModule(new RepositoryStarterModule(new FluentRepositoryProviderFactory(new ModelMapperPackage()), new CacheRepositoryProviderFactory(new DomainCacheModelMappingPackage()), null, null, new FluentExtensionProvider())); ICacheUpdateInvoker updateInvoker = new SinkCacheUpdateInvoker(); RegisterModule(new CacheStarterModule(updateInvoker, new DomainCacheLoaderPackage())); } } }
 namespace Client { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Stock; /// <summary> /// A single graphical component displaying a specific stock group and its data. /// </summary> public class StockGroupComponent { #region Constants and Fields private readonly List<StockDataPoint> _dataPoints; private readonly int _investmentPercentage; private readonly InvestmentScreen _investmentScreen; private int _maxPossibleSliderValue; private Slider _slider; private String _stockGroupName; private Image _arrowImage; #endregion #region Constructors and Destructors public StockGroupComponent(InvestmentScreen invScreen, String stockGroupName) { Contract.Requires(!ReferenceEquals(stockGroupName, null)); _investmentScreen = invScreen; _stockGroupName = stockGroupName; _investmentPercentage = Communication.Instance.Investments(stockGroupName); _dataPoints = Communication.Instance.StockGroupData(_stockGroupName); CreatePanel(); CreateGraphComponent(); } #endregion #region Public Properties /// <summary> /// Returns the investment screen on which this component is displayed. /// </summary> public InvestmentScreen InvestmentScreen { get { return _investmentScreen; } } /// <summary> /// Gets or sets the current value of the slider. /// </summary> public int SliderValue { [Pure] get { return (int) _slider.Value; } set { Contract.Requires(value >= 0); Contract.Requires(value <= 100); Contract.Ensures(SliderValue == value); Contract.Ensures(InvestmentScreen.SumOfAllSliders == Contract.OldValue(InvestmentScreen.SumOfAllSliders) + (value - Contract.OldValue(SliderValue))); _slider.Value = value; } } /// <summary> /// Gets the stock group name of this component. /// </summary> public String StockGroupName { get { return _stockGroupName; } } #endregion #region Public Methods /// <summary> /// Updates the number displaying the difference between the original and the new value of the investment percentage. /// </summary> public void UpdateGroupInfoHeader() { // Update text in GROUP_INFO_HEADER StackPanel topPanel = _investmentScreen.outerPanel.FindName("topPanel_" + _stockGroupName) as StackPanel; TextBlock groupInfoHeaderTb = topPanel.Children[1] as TextBlock; int difference = (Convert.ToInt32(SliderValue) - Communication.Instance.Investments(_stockGroupName)); String differenceString = difference > 0 ? "+" + difference : "" + difference; groupInfoHeaderTb.Text = "Group: " + _stockGroupName + "\r" + "Investments: " + Convert.ToInt32(SliderValue) + "% (" + differenceString + ")"; } #endregion #region Methods /// <summary> /// Creates the slider and the stock trend graph. /// </summary> private void CreateGraphComponent() { StackPanel graphPanel = _investmentScreen.outerPanel.FindName("graphPanel_" + _stockGroupName) as StackPanel; // Create the slider _slider = new Slider { Name = "slider_" + _stockGroupName, Height = 84, Width = graphPanel.Width - 100, Maximum = 100, Minimum = 0, Value = _investmentPercentage }; _slider.GotFocus += SetMaxPossibleSliderValue; _slider.ValueChanged += UpdateSliderValue; // Create the graph Canvas c = new Canvas(); c.Height = 100; c.Width = graphPanel.Width - 100; Polyline trend = new Polyline(); trend.Stroke = new SolidColorBrush(Color.FromArgb(255, 27, 162, 224)); trend.StrokeThickness = 4; double xOffset = DateTime.Now.AddYears(-5).Ticks / 10000000; double xScale = c.Width / ((DateTime.Now.AddYears(5).Ticks / 10000000) - xOffset); double yOffset = 0; double yScale = c.Height / 200.0; PointCollection trendPoints = new PointCollection(); foreach (StockDataPoint dataPoint in _dataPoints) { double x = (dataPoint.TimeStamp - xOffset) * xScale; double y = (dataPoint.Value - yOffset) * yScale; trendPoints.Add(new Point(x, y)); } trend.Points = trendPoints; c.Children.Add(trend); graphPanel.Children.Add(_slider); graphPanel.Children.Add(c); } /// <summary> /// Creates the top panel of the component. /// </summary> private void CreatePanel() { StackPanel topPanel = new StackPanel { Name = "topPanel_" + _stockGroupName, Width = 470, Height = 80, Margin = new Thickness(0.0, 0.0, 0.0, 0.0), Orientation = System.Windows.Controls.Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; topPanel.Tap += GraphPanelExpandCollapse; _arrowImage = new Image { Name = "image_" + _stockGroupName, Height = 80, Width = 80, Stretch = Stretch.None, Source = _investmentScreen.border_investmentGroups.Resources["img_arrow"] as BitmapImage }; TextBlock groupInfoHeader = new TextBlock // GROUP_INFO_HEADER { Height = 80, Width = 390, Margin = new Thickness(0.0, 12.5, 0.0, 0.0), Text = "Group: " + _stockGroupName + "\r" + "Investments: " + _investmentPercentage + "% (0)" }; topPanel.Children.Add(_arrowImage); topPanel.Children.Add(groupInfoHeader); StackPanel graphComponentPanel = new StackPanel { Name = "graphPanel_" + _stockGroupName, Height = 200, Width = 470, Margin = new Thickness(0.0, 0.0, 0.0, 0.0), Visibility = Visibility.Collapsed }; _investmentScreen.outerPanel.Children.Add(topPanel); _investmentScreen.outerPanel.Children.Add(graphComponentPanel); } /// <summary> /// Expands or collapses the graph panel based on its current state. /// </summary> private void GraphPanelExpandCollapse(object sender, RoutedEventArgs e) { StackPanel sp = _investmentScreen.border_investmentGroups.FindName("graphPanel_" + _stockGroupName) as StackPanel; if (sp.Visibility == Visibility.Collapsed) { sp.Visibility = Visibility.Visible; Duration duration = new Duration(TimeSpan.FromSeconds(0.275)); Storyboard sb = new Storyboard(); sb.Duration = duration; DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; sb.Children.Add(da); RotateTransform rt = new RotateTransform(); Storyboard.SetTarget(da, rt); Storyboard.SetTargetProperty(da, new PropertyPath("Angle")); da.From = 0; da.To = 90; _arrowImage.RenderTransform = rt; _arrowImage.RenderTransformOrigin = new Point(0.3, 0.3); sb.Begin(); /* Animation Storyboard sbShow = border_investmentGroups.Resources["anim_showGroup"] as Storyboard; sbShow.Stop(); Storyboard.SetTarget(anim_showGroup, sp); sbShow.Begin(); img.Source = border_investmentGroups.Resources["img_arrowCollapse"] as BitmapImage; */ } else { sp.Visibility = Visibility.Collapsed; Duration duration = new Duration(TimeSpan.FromSeconds(0.275)); Storyboard sb = new Storyboard(); sb.Duration = duration; DoubleAnimation da = new DoubleAnimation(); da.Duration = duration; sb.Children.Add(da); RotateTransform rt = new RotateTransform(); Storyboard.SetTarget(da, rt); Storyboard.SetTargetProperty(da, new PropertyPath("Angle")); da.From = 90; da.To = 0; _arrowImage.RenderTransform = rt; _arrowImage.RenderTransformOrigin = new Point(0.3, 0.3); sb.Begin(); //img.Source = _investmentScreen.border_investmentGroups.Resources["img_arrowExpand"] as BitmapImage; /* Animation Storyboard sbHide = border_investmentGroups.Resources["anim_hideGroup"] as Storyboard; sbHide.Stop(); Storyboard.SetTarget(anim_hideGroup, sp); sbHide.Begin(); img.Source = border_investmentGroups.Resources["img_arrowExpand"] as BitmapImage; */ } } /// <summary> /// Sets the max possible value of this slider based on the sum of all sliders. /// </summary> private void SetMaxPossibleSliderValue(Object sender, RoutedEventArgs args) { _maxPossibleSliderValue = 100 - _investmentScreen.SumOfAllSliders + SliderValue; } /// <summary> /// Called when the user changes the slider value. /// </summary> private void UpdateSliderValue(Object sender, RoutedPropertyChangedEventArgs<Double> args) { // If the sum of all sliders exceed 100% ... if (args.NewValue > _maxPossibleSliderValue) { _slider.Value = _maxPossibleSliderValue; } _investmentScreen.UpdateSubmitButtonStatus(); UpdateGroupInfoHeader(); _investmentScreen.UpdateControlPanelText(); } #endregion } }
//----------------------------------------------------------------------- // <Author = "Mohammad Reza" /> // <File = "WiXInstallerCreatorForm.cs" /> //----------------------------------------------------------------------- namespace WiXInstallerCreator { using InternalToolsCommon.Forms; using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Windows.Forms; using System.Xml; /// <summary> /// Main application form. Used to provide functionailty to the user so /// that they can create wix based installer with ease. /// </summary> public partial class WiXInstallerCreatorForm : Form { #region Fields /// <summary> /// Stores tool name /// </summary> private string ToolName; /// <summary> /// Stores version number /// </summary> private string VersionNumber; /// <summary> /// Stores project directory /// </summary> private string ProjectDirectory; /// <summary> /// Indicates if version number is set manually /// </summary> private bool Manual = false; /// <summary> /// Stores application name /// </summary> private string ApplicationName; /// <summary> /// Stores installer path /// </summary> private static string installerPath; /// <summary> /// Background worker to create wix installer /// </summary> private BackgroundWorker createInstallerBackgroundWorker = new BackgroundWorker(); /// <summary> /// Background worker to get necessary files from shared network directory /// </summary> private BackgroundWorker getFilesBackgroundWorker = new BackgroundWorker(); /// <summary> /// The network share directory where scripts are stored /// </summary> private const string RequiredFilesDirectory = @"..\\..\\..\\"; /// <summary> /// Harvested wxs file location /// </summary> private const string HarvestedFilesFragment = "scripts\\HarvestedFilesFragment.wxs"; /// <summary> /// Template wxs file location /// </summary> private const string TemplateFile = "scripts\\Template.wxs"; /// <summary> /// Main wxs file location /// </summary> private const string MainFile = "scripts\\Main.wxs"; /// <summary> /// XML document /// </summary> private XmlDocument xmlDoc; /// <summary> /// Inducates if operation is successful /// </summary> private bool success = false; #endregion Fields #region Constructors /// <summary> /// Creates a new wix installer creator form. /// </summary> public WiXInstallerCreatorForm() { InitializeComponent(); createInstallerBackgroundWorker.WorkerSupportsCancellation = true; createInstallerBackgroundWorker.WorkerReportsProgress = true; createInstallerBackgroundWorker.DoWork += new DoWorkEventHandler(CreateInstallerBackgroundWorkerDoWork); createInstallerBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CreateInstallerBackgroundWorkerCompleted); getFilesBackgroundWorker.WorkerSupportsCancellation = true; getFilesBackgroundWorker.WorkerReportsProgress = true; getFilesBackgroundWorker.DoWork += new DoWorkEventHandler(GetFilesBackgroundWorkerDoWork); getFilesBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(GetFilesBackgroundWorkerCompleted); } #endregion Constructors #region Methods /// <summary> /// Removes node from xml document. /// </summary> /// <param name="tagName">Tag name</param> /// <param name="innerText">Inner text</param> private void RemoveChildNode(string tagName, string innerText) { if(xmlDoc != null) { XmlNodeList nodes = xmlDoc.GetElementsByTagName(tagName); foreach(XmlNode node in nodes) { if(node.Attributes["Id"].InnerText == innerText) { node.ParentNode.RemoveChild(node); break; } } } } /// <summary> /// Removes node from xml document. /// </summary> /// <param name="tagName">Tag name</param> private void RemoveChildNode(string tagName) { if(xmlDoc != null) { XmlNodeList nodes = xmlDoc.GetElementsByTagName(tagName); if(nodes.Count > 0) { nodes[0].ParentNode.RemoveChild(nodes[0]); } } } /// <summary> /// BackgroundWorker to create wix installer. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void CreateInstallerBackgroundWorkerDoWork(object sender, DoWorkEventArgs args) { ActionForm reporter = sender as ActionForm; if(reporter != null) { if(!createInstallerBackgroundWorker.CancellationPending) { reporter.StatusText = "Harvesting files"; ExecuteCommand("wix3binaries\\heat.exe dir " + projectBinDirectoryTextBox.Text + " -cg INSTALLFOLDER -gg -scom -sreg -sfrag -srd -out HarvestedFilesFragment.wxs"); reporter.ReportProgress(1, 5); reporter.StatusText = "Making necessary changes to file"; if(File.Exists(HarvestedFilesFragment)) { FindAndReplaceText(HarvestedFilesFragment, HarvestedFilesFragment, "TARGETDIR", "INSTALLFOLDER"); FindAndReplaceText(HarvestedFilesFragment, HarvestedFilesFragment, "SourceDir\\", projectBinDirectoryTextBox.Text + "\\"); FindAndReplaceText(HarvestedFilesFragment, HarvestedFilesFragment, "ComponentGroup Id", "ComponentGroup Id = \"ProductComponents\" Directory"); if(!Manual) { FindAndReplaceText(TemplateFile, MainFile, "[REPLACE_WITH_TOOL_NAME]", GetToolName(HarvestedFilesFragment, projectBinDirectoryTextBox.Text + "\\")); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_FILE_ID_GENERATED_AFTER_HARVESTING]", GetFileIds(HarvestedFilesFragment)); } else { FindAndReplaceText(TemplateFile, MainFile, "[REPLACE_WITH_TOOL_NAME]", ToolName); FindAndReplaceText(MainFile, MainFile, "!(bind.FileVersion.[REPLACE_WITH_FILE_ID_GENERATED_AFTER_HARVESTING])", VersionNumber); } FindAndReplaceText(MainFile, MainFile, "[COMPANY]", companyNameTextBox.Text); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_PATH_TO_ICON_FILE]", iconTextBox.Text); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_PATH_TO_BANNER_BMP]", bannerImageTextBox.Text); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_PATH_TO_DIALOG_BMP]", dialogImageTextBox.Text); FindAndReplaceText(MainFile, MainFile, "[UPGRADE_CODE_GUID]", upgradeCodeTextBox.Text); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_GUID_DESKTOP]", GetGuid()); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_GUID_PROGRAM]", GetGuid()); FindAndReplaceText(MainFile, MainFile, "[REPLACE_WITH_TOOL_DESCRIPTION]", toolDescriptionTextBox.Text); reporter.ReportProgress(1, 5); xmlDoc = new XmlDocument(); xmlDoc.Load(MainFile); if(Manual) { RemoveChildNode("Directory", "DesktopFolder"); RemoveChildNode("Directory", "ProgramMenuFolder"); RemoveChildNode("DirectoryRef", "ApplicationProgramsFolder"); RemoveChildNode("ComponentRef", "ApplicationShortcutDesktop"); RemoveChildNode("ComponentRef", "ApplicationShortcut"); } else { if(!desktopShortcutCheckBox.Checked) { RemoveChildNode("Directory", "DesktopFolder"); RemoveChildNode("ComponentRef", "ApplicationShortcutDesktop"); } } if(!userAgreementCheckBox.Checked) { RemoveChildNode("WixVariable", "WixUILicenseRtf"); } else { RemoveChildNode("UI"); } xmlDoc.Save("scripts\\Main.wxs"); reporter.StatusText = "Compiling"; ExecuteCommand("wix3binaries\\candle.exe HarvestedFilesFragment.wxs Main.wxs"); reporter.ReportProgress(1, 5); reporter.StatusText = "Building"; ToolName = ToolName.Replace(" ", ""); if(File.Exists("scripts\\HarvestedFilesFragment.wixobj") && File.Exists("scripts\\Main.wixobj")) { ExecuteCommand("wix3binaries\\light.exe -ext scripts\\wix3binaries\\WixUIExtension.dll -out " + ToolName + ".msi HarvestedFilesFragment.wixobj Main.wixobj"); reporter.ReportProgress(1, 5); reporter.StatusText = "Removing temporary files"; DeleteUnnecessaryFiles("scripts", "*.wixobj"); DeleteUnnecessaryFiles("scripts", "*.wixpdb"); DeleteUnnecessaryFiles("scripts", "HarvestedFilesFragment.wxs"); DeleteUnnecessaryFiles("scripts", "Main.wxs"); DeleteUnnecessaryFiles("scripts", "*.rtf"); MoveFile("scripts", "*.msi"); reporter.ReportProgress(1, 5); success = true; } else { MessageBox.Show("Unable to find required files!"); success = false; } } else { MessageBox.Show("Unable to find required files!"); success = false; } } } } /// <summary> /// Notifies background workers work status. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void CreateInstallerBackgroundWorkerCompleted(object sender, RunWorkerCompletedEventArgs args) { if(args.Error != null) { // TODO: Report errors. } else { if(success) { OpenFolder(); statusLabel.Text = "Done"; } else { statusLabel.Text = "Errors! Could not create the installer."; } } } /// <summary> /// BackgroundWorker to copy necessary files from network shared directory. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void GetFilesBackgroundWorkerDoWork(object sender, DoWorkEventArgs args) { ActionForm reporter = sender as ActionForm; if(reporter != null) { if(!getFilesBackgroundWorker.CancellationPending) { reporter.ReportProgress(1, 5); //Now Create all of the directories foreach(string dirPath in Directory.GetDirectories(RequiredFilesDirectory + @"\scripts", "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(RequiredFilesDirectory + @"\scripts", @"scripts\")); } reporter.ReportProgress(3, 5); //Copy all the files & Replaces any files with the same name foreach(string newPath in Directory.GetFiles(RequiredFilesDirectory + @"\scripts", "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(RequiredFilesDirectory + @"\scripts", @"scripts\"), true); } reporter.ReportProgress(1, 5); } } } /// <summary> /// Notifies background workers work status. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void GetFilesBackgroundWorkerCompleted(object sender, RunWorkerCompletedEventArgs args) { if(args.Error != null) { // TODO: Report errors. } else { statusLabel.Text = "Ready"; } } /// <summary> /// Run wix commands in command prompt. /// </summary> /// <param name="command">Command to execute</param> private void ExecuteCommand(string command) { int exitCode; ProcessStartInfo processInfo; Process process; processInfo = new ProcessStartInfo("cmd.exe", "/c " + command); processInfo.WorkingDirectory = "scripts"; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; // *** Redirect the output *** processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; try { process = Process.Start(processInfo); process.WaitForExit(); // *** Read the streams *** string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); exitCode = process.ExitCode; // TODO: Report output/error/exitCode. Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output)); Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error)); Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand"); process.Close(); } catch(Exception) { statusLabel.Text = "Could not run process cmd.exe!"; } } /// <summary> /// Button click event to initiate main operation. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void CreateInstallerButtonClick(object sender, EventArgs args) { ToolName = VersionNumber = ApplicationName = String.Empty; if(iconTextBox.Text != String.Empty && projectBinDirectoryTextBox.Text != String.Empty && upgradeCodeTextBox.Text != String.Empty && companyNameTextBox.Text != String.Empty && toolDescriptionTextBox.Text != String.Empty) { if(!projectBinDirectoryTextBox.Text.Contains(" ")) { bool exceptionThrown = false; ProjectDirectory = projectBinDirectoryTextBox.Text; string[] filePaths = null; try { filePaths = Directory.GetFiles(projectBinDirectoryTextBox.Text, "*.exe", SearchOption.TopDirectoryOnly); } catch(Exception) { MessageBox.Show("Project Bin Directory not found"); exceptionThrown = true; } VersionNumberForm versionForm = new VersionNumberForm(filePaths, ProjectDirectory); versionForm.ShowDialog(); if(versionForm.DialogResult == DialogResult.OK) { ApplicationName = versionForm.ApplicationName; ToolName = versionForm.ToolName; VersionNumber = versionForm.VersionNumber; Manual = versionForm.Manual; versionForm.Dispose(); } if(!exceptionThrown) { if(Manual) { if(ToolName != null && ToolName != String.Empty && VersionNumber != null && VersionNumber != String.Empty) { StartOperation(); } } else { if(ApplicationName != null && ApplicationName != String.Empty) { StartOperation(); } } } } else { MessageBox.Show("Project Bin Directory should not contain any space for WiX Installer to work properly!"); } } else { statusLabel.Text = "One or more pieces of information are missing!"; } } /// <summary> /// Triggers CreateInstallerBackgroundWorker to create the installer. /// </summary> private void StartOperation() { if(userAgreementCheckBox.Checked) { licenseRichTextBox.SaveFile("scripts\\license.rtf", RichTextBoxStreamType.RichText); } ActionForm reporter = new ActionForm(); reporter.ActionText = "Operation in progress"; reporter.DoWork += CreateInstallerBackgroundWorkerDoWork; reporter.ActionFinished += CreateInstallerBackgroundWorkerCompleted; reporter.ShowDialog(this); } /// <summary> /// Find and replace text. /// </summary> /// <param name="oldFileName">File to read</param> /// <param name="newFileName">File to write</param> /// <param name="oldValue">String to replace</param> /// <param name="newValue">Replacement string</param> private void FindAndReplaceText(string oldFileName, string newFileName, string oldValue, string newValue) { string text = File.ReadAllText(oldFileName); text = text.Replace(oldValue, newValue); File.WriteAllText(newFileName, text); } /// <summary> /// Find file id of actual executable. /// </summary> /// <param name="fileName">File to parse</param> private string GetFileIds(string fileName) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); XmlNodeList elemList = doc.GetElementsByTagName("File"); string attrIdVal = String.Empty; for(int index = 0; index < elemList.Count; index++) { if(elemList[index].Attributes["Source"].Value.EndsWith(ApplicationName)) { attrIdVal = elemList[index].Attributes["Id"].Value; } } return attrIdVal; } /// <summary> /// Find tool name. /// </summary> /// <param name="fileName">File to parse</param> /// <param name="path">Replace path to get the tool name</param> private string GetToolName(string fileName, string path) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); XmlNodeList elemList = doc.GetElementsByTagName("File"); string attrSourceVal = ""; for(int index = 0; index < elemList.Count; index++) { if(elemList[index].Attributes["Source"].Value.EndsWith(ApplicationName)) { attrSourceVal = elemList[index].Attributes["Source"].Value.Replace(path, "").Replace(".exe", ""); } } ToolName = attrSourceVal; if(ToolName == null || ToolName == String.Empty) { MessageBox.Show("No valid exe file is found in the project directory!"); } return attrSourceVal; } /// <summary> /// Generate Guid. /// </summary> private string GetGuid() { return Guid.NewGuid().ToString(); } /// <summary> /// Populate UpgradeCodeTextBox with new guid value. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void GenerateGuidButtonClick(object sender, EventArgs args) { upgradeCodeTextBox.Text = GetGuid(); } /// <summary> /// Search and delete unnecessary files. /// </summary> /// <param name="path">Path to delete from</param> /// <param name="pattern">Search pattern</param> private void DeleteUnnecessaryFiles(string path, string pattern) { string[] filePaths = Directory.GetFiles(path, pattern); foreach(string filePath in filePaths) { if(filePath.Contains(pattern.Replace("*", ""))) { File.Delete(filePath); } } } /// <summary> /// Search and move file(s). /// </summary> /// <param name="path">Path to move from</param> /// <param name="pattern">Search pattern</param> private void MoveFile(string path, string pattern) { installerPath = "Installer\\" + ToolName + "\\" + DateTime.Now.ToString("yyyy-MM-dd HHmmss"); if(!Directory.Exists(installerPath)) { Directory.CreateDirectory(installerPath); } string[] filePaths = Directory.GetFiles(path, pattern); foreach(string filePath in filePaths) { if(filePath.Contains(pattern.Replace("*", ""))) { File.Move(filePath, Path.Combine(installerPath, filePath.Replace("scripts\\", ""))); } } } /// <summary> /// Opens FolderBrowserDialog to browse for project bin directory. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void BrowseProjectBinFolderButtonClick(object sender, EventArgs args) { DialogResult result = projectFolderBrowserDialog.ShowDialog(); if(result == DialogResult.OK) { projectBinDirectoryTextBox.Text = projectFolderBrowserDialog.SelectedPath; } } /// <summary> /// Opens FileDialog to browse for icon file. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void BrowseIconButtonClick(object sender, EventArgs args) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Icon Files (*.ico)|*.ico"; dialog.InitialDirectory = @"C:\"; dialog.Title = "Please select an icon for the installer."; if(dialog.ShowDialog() == DialogResult.OK) { iconTextBox.Text = dialog.FileName; } } /// <summary> /// Form load event. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void WiXInstallerCreatorFormLoad(object sender, EventArgs args) { Height = MinimumSize.Height; if(!Directory.Exists("scripts")) { ActionForm reporter = new ActionForm(); reporter.ActionText = "Getting necessary files"; reporter.DoWork += GetFilesBackgroundWorkerDoWork; reporter.ActionFinished += GetFilesBackgroundWorkerCompleted; reporter.ShowDialog(this); } iconTextBox.Text = Path.Combine(Directory.GetCurrentDirectory(), "scripts\\icon.ico"); dialogImageTextBox.Text = Path.Combine(Directory.GetCurrentDirectory(), "scripts\\dialogbmp.bmp"); bannerImageTextBox.Text = Path.Combine(Directory.GetCurrentDirectory(), "scripts\\bannerbmp.bmp"); } /// <summary> /// Opens FileDialog to browse for dialog image. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void DialogImageButtonClick(object sender, EventArgs args) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Bitmap (*.bmp)|*.bmp"; dialog.InitialDirectory = @"C:\"; dialog.Title = "Please select a dialog image for the installer."; if(dialog.ShowDialog() == DialogResult.OK) { dialogImageTextBox.Text = dialog.FileName; } } /// <summary> /// Opens FileDialog to browse for banner image. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void BannerImageButtonClick(object sender, EventArgs args) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Bitmap (*.bmp)|*.bmp"; dialog.InitialDirectory = @"C:\"; dialog.Title = "Please select a banner image for the installer."; if(dialog.ShowDialog() == DialogResult.OK) { bannerImageTextBox.Text = dialog.FileName; } } /// <summary> /// Opens folder where newly created installer resides. /// </summary> private void OpenFolder() { if(Directory.Exists(installerPath)) { ProcessStartInfo startInfo = new ProcessStartInfo { Arguments = installerPath, FileName = "explorer.exe" }; Process.Start(startInfo); } else { MessageBox.Show(string.Format("{0} Directory does not exist!", installerPath)); } } /// <summary> /// Check box check changed event. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void UserAgreementCheckBoxCheckedChanged(object sender, EventArgs args) { if(userAgreementCheckBox.Checked) { licenseRichTextBox.Enabled = true; } else { licenseRichTextBox.Enabled = false; } } /// <summary> /// Opens about form. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void AboutToolStripMenuItemClick(object sender, EventArgs args) { new Forms.AboutForm().ShowDialog(); } /// <summary> /// Closes the application. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void ExitToolStripMenuItemClick(object sender, EventArgs args) { Application.Exit(); } /// <summary> /// Show or hide advance options. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void AdvanceButtonClick(object sender, EventArgs args) { if(advanceButton.Text == "Advance") { Height = MaximumSize.Height; advanceButton.Text = "Hide"; licenseGroupBox.Visible = true; installerImagesGroupBox.Visible = true; } else { Height = MinimumSize.Height; advanceButton.Text = "Advance"; licenseGroupBox.Visible = false; installerImagesGroupBox.Visible = false; } } /// <summary> /// Close all background worker before closing the form. /// </summary> /// <param name="sender">Refers to the object that invoked the event that fired the event handler</param> /// <param name="args">Provides a value to use with event</param> private void WiXInstallerCreatorFormFormClosing(object sender, FormClosingEventArgs args) { if(getFilesBackgroundWorker != null && getFilesBackgroundWorker.IsBusy) { getFilesBackgroundWorker.CancelAsync(); } if(createInstallerBackgroundWorker != null && createInstallerBackgroundWorker.IsBusy) { createInstallerBackgroundWorker.CancelAsync(); } } #endregion Methods } }
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_System_Collections_Generic_List_1_UnityEngine_EventSystems_RaycastResult : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int constructor(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> o; if(argc==1){ o=new System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>(); pushValue(l,true); pushValue(l,o); return 2; } else if(matchType(l,argc,2,typeof(int))){ System.Int32 a1; checkType(l,2,out a1); o=new System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>(a1); pushValue(l,true); pushValue(l,o); return 2; } else if(matchType(l,argc,2,typeof(IEnumerable<UnityEngine.EventSystems.RaycastResult>))){ System.Collections.Generic.IEnumerable<UnityEngine.EventSystems.RaycastResult> a1; checkType(l,2,out a1); o=new System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>(a1); pushValue(l,true); pushValue(l,o); return 2; } return error(l,"New object failed."); } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Add(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); self.Add(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int AddRange(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Collections.Generic.IEnumerable<UnityEngine.EventSystems.RaycastResult> a1; checkType(l,2,out a1); self.AddRange(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int AsReadOnly(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); var ret=self.AsReadOnly(); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int BinarySearch(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); var ret=self.BinarySearch(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); System.Collections.Generic.IComparer<UnityEngine.EventSystems.RaycastResult> a2; checkType(l,3,out a2); var ret=self.BinarySearch(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==5){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); UnityEngine.EventSystems.RaycastResult a3; checkValueType(l,4,out a3); System.Collections.Generic.IComparer<UnityEngine.EventSystems.RaycastResult> a4; checkType(l,5,out a4); var ret=self.BinarySearch(a1,a2,a3,a4); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function BinarySearch to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Clear(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); self.Clear(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Contains(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); var ret=self.Contains(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Exists(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.Exists(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Find(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.Find(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int FindAll(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.FindAll(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int FindIndex(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.FindIndex(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Predicate<UnityEngine.EventSystems.RaycastResult> a2; checkDelegate(l,3,out a2); var ret=self.FindIndex(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); System.Predicate<UnityEngine.EventSystems.RaycastResult> a3; checkDelegate(l,4,out a3); var ret=self.FindIndex(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function FindIndex to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int FindLast(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.FindLast(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int FindLastIndex(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.FindLastIndex(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Predicate<UnityEngine.EventSystems.RaycastResult> a2; checkDelegate(l,3,out a2); var ret=self.FindLastIndex(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); System.Predicate<UnityEngine.EventSystems.RaycastResult> a3; checkDelegate(l,4,out a3); var ret=self.FindLastIndex(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function FindLastIndex to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int ForEach(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Action<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); self.ForEach(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetRange(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); var ret=self.GetRange(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int IndexOf(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); var ret=self.IndexOf(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); var ret=self.IndexOf(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); System.Int32 a3; checkType(l,4,out a3); var ret=self.IndexOf(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function IndexOf to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Insert(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); UnityEngine.EventSystems.RaycastResult a2; checkValueType(l,3,out a2); self.Insert(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int InsertRange(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Collections.Generic.IEnumerable<UnityEngine.EventSystems.RaycastResult> a2; checkType(l,3,out a2); self.InsertRange(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int LastIndexOf(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); var ret=self.LastIndexOf(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); var ret=self.LastIndexOf(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); System.Int32 a3; checkType(l,4,out a3); var ret=self.LastIndexOf(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function LastIndexOf to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Remove(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); UnityEngine.EventSystems.RaycastResult a1; checkValueType(l,2,out a1); var ret=self.Remove(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int RemoveAll(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.RemoveAll(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int RemoveAt(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); self.RemoveAt(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int RemoveRange(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); self.RemoveRange(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Reverse(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==1){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); self.Reverse(); pushValue(l,true); return 1; } else if(argc==3){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); self.Reverse(a1,a2); pushValue(l,true); return 1; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function Reverse to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int Sort(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==1){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); self.Sort(); pushValue(l,true); return 1; } else if(matchType(l,argc,2,typeof(IComparer<UnityEngine.EventSystems.RaycastResult>))){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Collections.Generic.IComparer<UnityEngine.EventSystems.RaycastResult> a1; checkType(l,2,out a1); self.Sort(a1); pushValue(l,true); return 1; } else if(matchType(l,argc,2,typeof(System.Comparison<UnityEngine.EventSystems.RaycastResult>))){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Comparison<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); self.Sort(a1); pushValue(l,true); return 1; } else if(argc==4){ System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); System.Collections.Generic.IComparer<UnityEngine.EventSystems.RaycastResult> a3; checkType(l,4,out a3); self.Sort(a1,a2,a3); pushValue(l,true); return 1; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function Sort to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int ToArray(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); var ret=self.ToArray(); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int TrimExcess(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); self.TrimExcess(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int TrueForAll(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); System.Predicate<UnityEngine.EventSystems.RaycastResult> a1; checkDelegate(l,2,out a1); var ret=self.TrueForAll(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_Capacity(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); pushValue(l,true); pushValue(l,self.Capacity); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_Capacity(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); int v; checkType(l,2,out v); self.Capacity=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_Count(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); pushValue(l,true); pushValue(l,self.Count); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int getItem(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); int v; checkType(l,2,out v); var ret = self[v]; pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int setItem(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> self=(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)checkSelf(l); int v; checkType(l,2,out v); UnityEngine.EventSystems.RaycastResult c; checkValueType(l,3,out c); self[v]=c; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"ListRaycastResult"); addMember(l,Add); addMember(l,AddRange); addMember(l,AsReadOnly); addMember(l,BinarySearch); addMember(l,Clear); addMember(l,Contains); addMember(l,Exists); addMember(l,Find); addMember(l,FindAll); addMember(l,FindIndex); addMember(l,FindLast); addMember(l,FindLastIndex); addMember(l,ForEach); addMember(l,GetRange); addMember(l,IndexOf); addMember(l,Insert); addMember(l,InsertRange); addMember(l,LastIndexOf); addMember(l,Remove); addMember(l,RemoveAll); addMember(l,RemoveAt); addMember(l,RemoveRange); addMember(l,Reverse); addMember(l,Sort); addMember(l,ToArray); addMember(l,TrimExcess); addMember(l,TrueForAll); addMember(l,getItem); addMember(l,setItem); addMember(l,"Capacity",get_Capacity,set_Capacity,true); addMember(l,"Count",get_Count,null,true); createTypeMetatable(l,constructor, typeof(System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult>)); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Arrow : MonoBehaviour { public Vector2 initialVelocity = new Vector2(500, 0); public float timeElapsed; private PlayerSpecial rangePwr; private GameObject player; private Rigidbody2D body2d; void Awake() { body2d = GetComponent<Rigidbody2D>(); player = GameObject.FindGameObjectWithTag("Player"); rangePwr = player.GetComponent<PlayerSpecial>(); } // Use this for initialization void Start() { var startVelX = initialVelocity.x * transform.localScale.x; //* PlayerSpecial.RangePwr; body2d.velocity = new Vector2(startVelX, initialVelocity.y); } void Update() { if (timeElapsed >= 5) Destroy(gameObject); timeElapsed += Time.deltaTime; } //void OnCollisionEnter2D(Collider2D col) { // if (col.CompareTag("Enemy")) { // Destroy(this.gameObject); // } //} }
using CMS_Database.Entities; using CMS_Database.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CMS_Database.Repositories { public class CTHoaDonRepository:GenericRepository<CTHoaDon>,ICTHoaDon { public IQueryable<CTHoaDon> GetById(int id) { return _db.CTHoaDon.Where(x => x.IdHoaDon == id); } } }
// dnlib: See LICENSE.txt for more info using System; using System.Diagnostics; using System.Text; namespace dnlib.DotNet { /// <summary> /// See CorHdr.h/CorCallingConvention /// </summary> [Flags, DebuggerDisplay("{Extensions.ToString(this),nq}")] public enum CallingConvention : byte { /// <summary>The managed calling convention</summary> Default = 0x0, /// <summary/> C = 0x1, /// <summary/> StdCall = 0x2, /// <summary/> ThisCall = 0x3, /// <summary/> FastCall = 0x4, /// <summary/> VarArg = 0x5, /// <summary/> Field = 0x6, /// <summary/> LocalSig = 0x7, /// <summary/> Property = 0x8, /// <summary/> Unmanaged = 0x9, /// <summary>generic method instantiation</summary> GenericInst = 0xA, /// <summary>used ONLY for 64bit vararg PInvoke calls</summary> NativeVarArg = 0xB, /// <summary>Calling convention is bottom 4 bits</summary> Mask = 0x0F, /// <summary>Generic method</summary> Generic = 0x10, /// <summary>Method needs a 'this' parameter</summary> HasThis = 0x20, /// <summary>'this' parameter is the first arg if set (else it's hidden)</summary> ExplicitThis = 0x40, /// <summary>Used internally by the CLR</summary> ReservedByCLR = 0x80, } public static partial class Extensions { internal static string ToString(CallingConvention flags) { var sb = new StringBuilder(); switch (flags & CallingConvention.Mask) { case CallingConvention.Default: sb.Append("Default"); break; case CallingConvention.C: sb.Append("C"); break; case CallingConvention.StdCall: sb.Append("StdCall"); break; case CallingConvention.ThisCall: sb.Append("ThisCall"); break; case CallingConvention.FastCall: sb.Append("FastCall"); break; case CallingConvention.VarArg: sb.Append("VarArg"); break; case CallingConvention.Field: sb.Append("Field"); break; case CallingConvention.LocalSig: sb.Append("LocalSig"); break; case CallingConvention.Property: sb.Append("Property"); break; case CallingConvention.Unmanaged: sb.Append("Unmanaged"); break; case CallingConvention.GenericInst: sb.Append("GenericInst"); break; case CallingConvention.NativeVarArg: sb.Append("NativeVarArg"); break; default: sb.Append(string.Format("CC_UNKNOWN_0x{0:X}", (int)(flags & CallingConvention.Mask))); break; } if ((flags & CallingConvention.Generic) != 0) sb.Append(" | Generic"); if ((flags & CallingConvention.HasThis) != 0) sb.Append(" | HasThis"); if ((flags & CallingConvention.ExplicitThis) != 0) sb.Append(" | ExplicitThis"); if ((flags & CallingConvention.ReservedByCLR) != 0) sb.Append(" | ReservedByCLR"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TurnerSoftware.SitemapTools.Tests { [TestClass] public class SitemapEntryTests { [TestMethod] public void Equals_EqualSitemaps() { var sameReferenceSitemap = new SitemapEntry(); var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(1970, 1, 1), Priority = 0.3 }; #pragma warning disable CS1718 // Comparison made to same variable Assert.IsTrue(sameReferenceSitemap.Equals(sameReferenceSitemap)); #pragma warning restore CS1718 // Comparison made to same variable Assert.IsTrue(new SitemapEntry().Equals(new SitemapEntry())); Assert.IsTrue(x.Equals(y)); Assert.IsTrue(y.Equals(x)); } [TestMethod] public void Equals_NotEqualSitemaps() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new SitemapEntry { Location = new Uri("https://localhost/def") }; Assert.IsFalse(new SitemapEntry().Equals((SitemapEntry)null)); Assert.IsFalse(x.Equals(y)); Assert.IsFalse(y.Equals(x)); } [TestMethod] public void EqualsOperator_EqualSitemaps() { var sameReferenceSitemap = new SitemapEntry(); var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(1970, 1, 1), Priority = 0.3 }; #pragma warning disable CS1718 // Comparison made to same variable Assert.IsTrue(sameReferenceSitemap == sameReferenceSitemap); #pragma warning restore CS1718 // Comparison made to same variable Assert.IsTrue(new SitemapEntry() == new SitemapEntry()); Assert.IsTrue(x == y); Assert.IsTrue(y == x); } [TestMethod] public void EqualsOperator_NotEqualSitemaps() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new SitemapEntry { Location = new Uri("https://localhost/def") }; Assert.IsFalse((SitemapEntry)null == new SitemapEntry()); Assert.IsFalse(new SitemapEntry() == (SitemapEntry)null); Assert.IsFalse(x == y); Assert.IsFalse(y == x); } [TestMethod] public void NotEqualsOperator_EqualSitemaps() { var sameReferenceSitemap = new SitemapEntry(); var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(1970, 1, 1), Priority = 0.3 }; #pragma warning disable CS1718 // Comparison made to same variable Assert.IsFalse(sameReferenceSitemap != sameReferenceSitemap); #pragma warning restore CS1718 // Comparison made to same variable Assert.IsFalse(new SitemapEntry() != new SitemapEntry()); Assert.IsFalse(x != y); Assert.IsFalse(y != x); } [TestMethod] public void NotEqualsOperator_NotEqualSitemaps() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new SitemapEntry { Location = new Uri("https://localhost/def") }; Assert.IsTrue((SitemapEntry)null != new SitemapEntry()); Assert.IsTrue(new SitemapEntry() != (SitemapEntry)null); Assert.IsTrue(x != y); Assert.IsTrue(y != x); } [TestMethod] public void Equals_EqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new Uri("https://localhost/"); Assert.IsTrue(x.Equals(y)); } [TestMethod] public void Equals_NotEqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new Uri("https://localhost/def"); Assert.IsFalse(x.Equals(y)); Assert.IsFalse(x.Equals((Uri)null)); } [TestMethod] public void EqualsOperator_EqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new Uri("https://localhost/"); Assert.IsTrue(x == y); Assert.IsTrue(y == x); } [TestMethod] public void EqualsOperator_NotEqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new Uri("https://localhost/def"); Assert.IsFalse((Uri)null == x); Assert.IsFalse(x == (Uri)null); Assert.IsFalse((SitemapEntry)null == new Uri("https://localhost/")); Assert.IsFalse(new Uri("https://localhost/") == (SitemapEntry)null); Assert.IsFalse(x == y); Assert.IsFalse(y == x); } [TestMethod] public void NotEqualsOperator_EqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/"), LastModified = new DateTime(2000, 1, 1), Priority = 0.7 }; var y = new Uri("https://localhost/"); Assert.IsFalse(x != y); Assert.IsFalse(y != x); } [TestMethod] public void NotEqualsOperator_NotEqualSitemapAndUri() { var x = new SitemapEntry { Location = new Uri("https://localhost/abc") }; var y = new Uri("https://localhost/def"); Assert.IsTrue((Uri)null != x); Assert.IsTrue(x != (Uri)null); Assert.IsTrue((SitemapEntry)null != new Uri("https://localhost/")); Assert.IsTrue(new Uri("https://localhost/") != (SitemapEntry)null); Assert.IsTrue(x != y); Assert.IsTrue(y != x); } } }
using System; using System.IO; using ProtoBuf; namespace PushoverQ.Protobuf { class BusProtobufSerializer : ISerializer { public void Serialize(object obj, Stream stream) { // ProtoBuf must have non-zero files stream.WriteByte(42); Serializer.Serialize(stream, obj); } public T Deserialize<T>(Stream stream) where T : class { var signature = stream.ReadByte(); if (signature != 42) throw new InvalidOperationException("Unknown stream for protobuf"); return Serializer.Deserialize<T>(stream); } public object Deserialize(Type type, Stream stream) { var signature = stream.ReadByte(); if (signature != 42) throw new InvalidOperationException("Unknown stream for protobuf"); return Serializer.NonGeneric.Deserialize(type, stream); } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// The actual activity to be redirected to when you click on the node. Note that a node can have many Activities attached to it: but only one will be active at any given time. The list of Node Activities will be traversed, and the first one found to be active will be displayed. This way, a node can layer multiple variants of an activity on top of each other. For instance, one node can control the weekly Crucible Playlist. There are multiple possible playlists, but only one is active for the week. /// </summary> [DataContract] public partial class DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition : IEquatable<DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition" /> class. /// </summary> /// <param name="NodeActivityId">An identifier for this node activity. It is only guaranteed to be unique within the Activity Graph..</param> /// <param name="ActivityHash">The activity that will be activated if the user clicks on this node. Controls all activity-related information displayed on the node if it is active (the text shown in the tooltip etc).</param> public DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition(uint? NodeActivityId = default(uint?), uint? ActivityHash = default(uint?)) { this.NodeActivityId = NodeActivityId; this.ActivityHash = ActivityHash; } /// <summary> /// An identifier for this node activity. It is only guaranteed to be unique within the Activity Graph. /// </summary> /// <value>An identifier for this node activity. It is only guaranteed to be unique within the Activity Graph.</value> [DataMember(Name="nodeActivityId", EmitDefaultValue=false)] public uint? NodeActivityId { get; set; } /// <summary> /// The activity that will be activated if the user clicks on this node. Controls all activity-related information displayed on the node if it is active (the text shown in the tooltip etc) /// </summary> /// <value>The activity that will be activated if the user clicks on this node. Controls all activity-related information displayed on the node if it is active (the text shown in the tooltip etc)</value> [DataMember(Name="activityHash", EmitDefaultValue=false)] public uint? ActivityHash { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition {\n"); sb.Append(" NodeActivityId: ").Append(NodeActivityId).Append("\n"); sb.Append(" ActivityHash: ").Append(ActivityHash).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition); } /// <summary> /// Returns true if DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsDirectorDestinyActivityGraphNodeActivityDefinition input) { if (input == null) return false; return ( this.NodeActivityId == input.NodeActivityId || (this.NodeActivityId != null && this.NodeActivityId.Equals(input.NodeActivityId)) ) && ( this.ActivityHash == input.ActivityHash || (this.ActivityHash != null && this.ActivityHash.Equals(input.ActivityHash)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.NodeActivityId != null) hashCode = hashCode * 59 + this.NodeActivityId.GetHashCode(); if (this.ActivityHash != null) hashCode = hashCode * 59 + this.ActivityHash.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3ListObjectsFunction { private static readonly IAmazonS3 _s3client = new AmazonS3Client(); private static readonly AmazonSimpleNotificationServiceClient _snsClient = new AmazonSimpleNotificationServiceClient(); private const string _bucketName = "<bucket-name>"; private const string _topicArn = "<arn-for-sns-topic>"; public class Function { } public async Task<string> FunctionHandler(ILambdaContext context) { LambdaLogger.Log($"Calling function name: {context.FunctionName}\\n"); var result = await ListingObjectsAsync(); await SendMessage(_snsClient, result); return result; } static async Task<string> ListingObjectsAsync() { var result = string.Empty; try { ListObjectsV2Request request = new ListObjectsV2Request { BucketName = _bucketName, MaxKeys = 10 }; ListObjectsV2Response response; do { response = await _s3client.ListObjectsV2Async(request); foreach (S3Object entry in response.S3Objects) { if (entry.Key.Contains(".csv")) { var status = entry.LastModified.AddHours(4.25) > DateTime.Now ? "[ 🆕 ]" : "[ 👵🏻 ]"; result += $"{entry.Key, -16} : {entry.LastModified.ToString("MM/dd/yyyy hh:mm tt")} {status}\n"; } else { result += "\n"; } } request.ContinuationToken = response.NextContinuationToken; } while (response.IsTruncated); } catch (AmazonS3Exception amazonS3Exception) { LambdaLogger.Log($"S3 error occurred. Exception: {amazonS3Exception.ToString()}"); } catch (Exception e) { LambdaLogger.Log($"Exception: {e.ToString()}"); } return result; } static async Task SendMessage(IAmazonSimpleNotificationService snsClient, string message) { var request = new PublishRequest { TopicArn = _topicArn, Message = message }; await snsClient.PublishAsync(request); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Xml.Linq; namespace ArticleSubmitTool.Tests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var newEl = new XElement("Parent", new XElement("Child", new XAttribute("Test", "1"), new [] { new XElement("TestChild1"), null, null, new XElement("TestChild2") })); var str = newEl.ToString(); } } }
using System; namespace l2p { class Program { static void Main(string[] args) { //l2p1.AverageTemp(); //l2p2.Mounth(); //l2p3.EvenNumber(); // l2p4_v3.Fiscal(); //l2p5.MounthTemp(); //l2p6.list(); Console.ReadLine(); } } }
namespace PhonesStore.ViewModels { public class OperatingSystemViewModel { public string Name { get; set; } public string Version { get; set; } public string Manufacturer { get; set; } public override int GetHashCode() { unchecked { int result = 17; result = result * 23 + ((Name != null) ? this.Name.GetHashCode() : 0); result = result * 23 + ((Version != null) ? this.Version.GetHashCode() : 0); result = result * 23 + ((Manufacturer != null) ? this.Manufacturer.GetHashCode() : 0); return result; } } public override bool Equals(object obj) { var other = obj as OperatingSystemViewModel; if (other == null) { return false; } return this.Name.ToLower() == other.Name.ToLower() && this.Version.ToLower() == other.Version.ToLower() && this.Manufacturer.ToLower() == other.Manufacturer.ToLower(); } public string Id { get; set; } } }
using FundManagerDashboard.Core.DataServices; using ReactiveUI; namespace FundManagerDashboard.Core.ViewModels { public class SummaryTemplateViewModel : ReactiveObject, ISummaryTemplateViewModel { public SummaryTemplateViewModel(string summaryName, ITotalSummaryService servie) { Title = summaryName; _totalNumber = servie.WhenAny(x => x.TotalNumber, change => change.Value) .ToProperty(this, modelView => modelView.TotalNumber); _totalMarketValue = servie.WhenAny(x => x.TotalMarketValue, change => change.Value) .ToProperty(this, modelView => modelView.TotalMarketValue); _totalStockWeight = servie.WhenAny(x => x.TotalStockWeight, change => change.Value) .ToProperty(this, modelView => modelView.TotalStockWeight); } public string Title { get; private set; } readonly private ObservableAsPropertyHelper<long> _totalNumber; readonly private ObservableAsPropertyHelper<decimal> _totalMarketValue; readonly private ObservableAsPropertyHelper<float> _totalStockWeight; public long TotalNumber => _totalNumber.Value; public decimal TotalMarketValue => _totalMarketValue.Value; public float TotalStockWeight => _totalStockWeight.Value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructure { public class BinaryTreeNode { public BinaryTreeNode Parent { get; set; } public BinaryTreeNode Left { get; set; } public BinaryTreeNode Right { get; set; } public int Data { get; private set; } public BinaryTreeNode(int data) { Data = data; } public BinaryTreeNode(int data, BinaryTreeNode parent) : this(data) { Parent = parent; } } }
using System.Text.Json.Serialization; using PlatformRacing3.Common.PrivateMessage; using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; internal sealed class JsonPmsOutgoingMessage : JsonPacket { private protected override string InternalType => "receivePMs"; [JsonPropertyName("requestID")] public uint RequestId { get; set; } [JsonPropertyName("results")] public uint Results { get; set; } [JsonPropertyName("pmArray")] public IReadOnlyCollection<IPrivateMessage> PMs { get; set; } internal JsonPmsOutgoingMessage(uint requestId, uint results, IReadOnlyCollection<IPrivateMessage> pms) { this.RequestId = requestId; this.Results = results; this.PMs = pms; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class WorldController : Singleton<WorldController> { protected WorldController() {} GameObject selectedObject; Color naturalColor; // Use this for initialization void Start () { naturalColor = Color.clear; byte[] I_NEED_UPDATES = { 10 }; Networking.send_udp(Networking.DEFAULT_SERVER_HOSTNAME, Networking.DEFAULT_PORT_UDP, I_NEED_UPDATES, 1); } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(1)) { var worldTouch = Camera.main.ScreenToWorldPoint(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(new Vector2(worldTouch.x, worldTouch.y), Vector2.zero, Mathf.Infinity); if (hit != null && hit.collider != null) { var entity = GameObject.Find(hit.collider.gameObject.name); if (entity != null) { var sprite = entity.GetComponent<SpriteRenderer>(); if (sprite != null) { if (selectedObject != null) { selectedObject.GetComponent<SpriteRenderer>().color = naturalColor; } naturalColor = sprite.color; sprite.color = Color.green; selectedObject = entity; } } } } //var serverData = Networking.recv_udp(); //var entity_array = Networking.Parse(serverData); } public void ping () { } } enum EntityType { UNKN = 3, MOB = 0, FIREBALL = 1, SPELL = 2 }; public struct Entity { EntityType type; uint uniqueId; float x; float y; }
using SharpDX.Direct2D1; using SharpDX.WIC; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ModernCSApp.Renderers { public class Direct2DImageEncoder { private readonly Direct2DFactoryManager factoryManager; private readonly SharpDX.WIC.Bitmap wicBitmap; private readonly WicRenderTarget renderTarget; private readonly int imageWidth, imageHeight; public Direct2DImageEncoder(int imageWidth, int imageHeight, int imageDpi) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; factoryManager = new Direct2DFactoryManager(); wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, imageWidth, imageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties); renderTarget.BeginDraw(); renderTarget.Clear(SharpDX.Color.Yellow); } public void Save(Stream systemStream, Direct2DImageFormat format) { renderTarget.EndDraw(); var stream = new WICStream(factoryManager.WicFactory, systemStream); var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format)); encoder.Initialize(stream); var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(imageWidth, imageHeight); Guid fdc = SharpDX.WIC.PixelFormat.FormatDontCare; //fdc = Direct2DConverter.ConvertImageFormat(Direct2DImageFormat.Gif); bitmapFrameEncode.SetPixelFormat(ref fdc); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); try { encoder.Commit(); }catch(Exception ex){ var f = ex.Message; } bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); } } public class Direct2DFactoryManager { private readonly SharpDX.WIC.ImagingFactory wicFactory; private readonly SharpDX.Direct2D1.Factory d2DFactory; private readonly SharpDX.DirectWrite.Factory dwFactory; public Direct2DFactoryManager() { wicFactory = new SharpDX.WIC.ImagingFactory(); d2DFactory = new SharpDX.Direct2D1.Factory(); dwFactory = new SharpDX.DirectWrite.Factory(); } public SharpDX.WIC.ImagingFactory WicFactory { get { return wicFactory; } } public SharpDX.Direct2D1.Factory D2DFactory { get { return d2DFactory; } } public SharpDX.DirectWrite.Factory DwFactory { get { return dwFactory; } } } public enum Direct2DImageFormat { Png, Gif, Ico, Jpeg, Wmp, Tiff, Bmp } public class Direct2DConverter { public static Guid ConvertImageFormat(Direct2DImageFormat format) { switch (format) { case Direct2DImageFormat.Bmp: return ContainerFormatGuids.Bmp; case Direct2DImageFormat.Ico: return ContainerFormatGuids.Ico; case Direct2DImageFormat.Gif: return ContainerFormatGuids.Gif; case Direct2DImageFormat.Jpeg: return ContainerFormatGuids.Jpeg; case Direct2DImageFormat.Png: return ContainerFormatGuids.Png; case Direct2DImageFormat.Tiff: return ContainerFormatGuids.Tiff; case Direct2DImageFormat.Wmp: return ContainerFormatGuids.Wmp; } throw new NotSupportedException(); } } }
/* 03. Write a program that prints to the console which day of the week is today. Use System.DateTime. */ using System; using System.Globalization; class DayOfWeek { static void Main() { System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DateTime weekDay = new DateTime(); weekDay = DateTime.Now; Console.WriteLine(weekDay.DayOfWeek); } }
// // - PropertyNodeCollection.cs - // // Copyright 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Carbonfrost.Commons.Core; namespace Carbonfrost.Commons.PropertyTrees { public abstract class PropertyNodeCollection : IList<PropertyNode>, IList { public virtual PropertyNode this[QualifiedName name] { get { if (name == null) throw new ArgumentNullException("name"); foreach (var t in this) { if (name == t.QualifiedName) return t; } return null; } } public virtual PropertyNode this[string name, string ns] { get { if (name == null) throw new ArgumentNullException("name"); // $NON-NLS-1 if (name.Length == 0) throw Failure.EmptyString("name"); // $NON-NLS-1 ns = ns ?? string.Empty; return this[QualifiedName.Create(ns, name)]; } } public virtual PropertyNode this[string name] { get { return this[name, null]; } } public virtual PropertyNode this[int index] { get { if (index < 0 || index > this.Count) throw Failure.IndexOutOfRange("index", index, 0, this.Count - 1); foreach (var t in this) { if (index-- == 0) return t; } return null; } } // IList<PropertyNode> implementation PropertyNode IList<PropertyNode>.this[int index] { get { return this[index]; } set { throw Failure.ReadOnlyCollection(); } } public abstract int Count { get; } public virtual bool IsReadOnly { get { return false; } } public virtual int IndexOf(PropertyNode item) { if (item == null) throw new ArgumentNullException("item"); // $NON-NLS-1 int index = 0; foreach (var pn in this) { if (object.Equals(pn, item)) return index; index++; } return -1; } public virtual int IndexOf(QualifiedName name) { if (name == null) throw new ArgumentNullException("name"); int index = 0; foreach (var pn in this) { if (pn.QualifiedName == name) return index; index++; } return -1; } void IList<PropertyNode>.Insert(int index, PropertyNode item) { throw Failure.ReadOnlyCollection(); } void IList<PropertyNode>.RemoveAt(int index) { throw Failure.ReadOnlyCollection(); } void ICollection<PropertyNode>.Add(PropertyNode item) { throw Failure.ReadOnlyCollection(); } void ICollection<PropertyNode>.Clear() { throw Failure.ReadOnlyCollection(); } public virtual bool Contains(PropertyNode item) { return IndexOf(item) >= 0; } public bool Contains(string ns, string name) { return IndexOf(QualifiedName.Create(ns, name)) >= 0; } public bool Contains(string name) { return IndexOf(NamespaceUri.Default + name) >= 0; } public virtual bool Contains(QualifiedName name) { return IndexOf(name) >= 0; } public virtual void CopyTo(PropertyNode[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); // $NON-NLS-1 if (array.Rank != 1) throw Failure.RankNotOne("array"); // $NON-NLS-1 if (arrayIndex < 0 || arrayIndex >= array.Length) throw Failure.IndexOutOfRange("arrayIndex", arrayIndex, 0, array.Length - 1); // $NON-NLS-1 if (arrayIndex + this.Count > array.Length) throw Failure.NotEnoughSpaceInArray("arrayIndex", arrayIndex); // $NON-NLS-1 foreach (var t in this) array[arrayIndex++] = t; } bool ICollection<PropertyNode>.Remove(PropertyNode item) { throw Failure.ReadOnlyCollection(); } public abstract IEnumerator<PropertyNode> GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } object IList.this[int index] { get { return this[index]; } set { throw Failure.ReadOnlyCollection(); } } bool IList.IsFixedSize { get { return false; } } object ICollection.SyncRoot { get { return null; } } bool ICollection.IsSynchronized { get { return false; } } int IList.Add(object value) { throw Failure.ReadOnlyCollection(); } bool IList.Contains(object value) { throw Failure.ReadOnlyCollection(); } int IList.IndexOf(object value) { if (value == null) throw new ArgumentNullException("value"); PropertyNode node = value as PropertyNode; if (node == null) return -1; int index = 0; foreach (var current in this) { if (node == current) return index; index++; } return -1; } void IList.Insert(int index, object value) { throw Failure.ReadOnlyCollection(); } void IList.Remove(object value) { throw Failure.ReadOnlyCollection(); } void ICollection.CopyTo(Array array, int index) { this.ToArray().CopyTo(array, index); } void IList.RemoveAt(int index) { throw Failure.ReadOnlyCollection(); } void IList.Clear() { throw Failure.ReadOnlyCollection(); } } }
using System; using System.Collections.Generic; namespace RMAT3.Models { public class AuditHeader { public AuditHeader() { AuditDetails = new List<AuditDetail>(); } public Guid ClientAuditId { get; set; } public string AddedByUserId { get; set; } public DateTime AddTs { get; set; } public string UpdatedByUserId { get; set; } public DateTime UpdatedTs { get; set; } public string ApprovalStatusCd { get; set; } public DateTime? AuditDt { get; set; } public string AuditLocationAddress1Txt { get; set; } public string AuditLocationAddress2Txt { get; set; } public string AuditLocationCityTxt { get; set; } public string AuditLocationPostalCd { get; set; } public string AuditLocationStateCd { get; set; } public string AuditSummaryTxt { get; set; } public string AuditTxt { get; set; } public string AuditTypeCd { get; set; } public string CleanUpVendorId { get; set; } public string CleanUpVendorPhoneNbr { get; set; } public string CleanUpVendorPhoneOtherNbr { get; set; } public int? ClientId { get; set; } public string ClientCd { get; set; } public string ClientDBANm { get; set; } public string ClientNm { get; set; } public string CompanyAddress1Txt { get; set; } public string CompanyAddress2Txt { get; set; } public string CompanyCityTxt { get; set; } public string CompanyPostalCd { get; set; } public string CompanyRepNm { get; set; } public string CompanyRepId { get; set; } public string CompanyRepPhoneNbr { get; set; } public string CompanyRepPhoneOtherNbr { get; set; } public string CompanyStateCd { get; set; } public bool? IsWarrantyReuiredInd { get; set; } public DateTime? ReopenDt { get; set; } public int? ResubmittedByPartyId { get; set; } public string ResubmittedByPartyNm { get; set; } public DateTime? ResubmittedDt { get; set; } public string RideAlongDriverId { get; set; } public string RideAlongDriverNm { get; set; } public string SafetyContactId { get; set; } public string SafetyContactNm { get; set; } public string SafetyContactPhoneNbr { get; set; } public string SafetyContactPhoneOtherNbr { get; set; } public string StatusCd { get; set; } public string SubmittedByUserId { get; set; } public string SubmittedByUserNm { get; set; } public DateTime? SubmittedDt { get; set; } public string TechnicalConsultantId { get; set; } public string TechnicalConsultantNm { get; set; } public string WarrantyRequiredTxt { get; set; } public Guid PartyEntityRoleTaskId { get; set; } public int AuditTypeId { get; set; } public virtual ICollection<AuditDetail> AuditDetails { get; set; } public virtual AuditType AuditType { get; set; } public virtual EntityTask Task { get; set; } } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using NopSolutions.NopCommerce.BusinessLogic.Caching; using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings; using NopSolutions.NopCommerce.DataAccess; using NopSolutions.NopCommerce.DataAccess.Payment; namespace NopSolutions.NopCommerce.BusinessLogic.Payment { /// <summary> /// Credit card type manager /// </summary> public partial class CreditCardTypeManager { #region Constants private const string CREDITCARDS_ALL_KEY = "Nop.creditcard.all"; private const string CREDITCARDS_BY_ID_KEY = "Nop.creditcard.id-{0}"; private const string CREDITCARDS_PATTERN_KEY = "Nop.creditcard."; #endregion #region Utilities private static CreditCardTypeCollection DBMapping(DBCreditCardTypeCollection dbCollection) { if (dbCollection == null) return null; CreditCardTypeCollection collection = new CreditCardTypeCollection(); foreach (DBCreditCardType dbItem in dbCollection) { CreditCardType item = DBMapping(dbItem); collection.Add(item); } return collection; } private static CreditCardType DBMapping(DBCreditCardType dbItem) { if (dbItem == null) return null; CreditCardType item = new CreditCardType(); item.CreditCardTypeID = dbItem.CreditCardTypeID; item.Name = dbItem.Name; item.SystemKeyword = dbItem.SystemKeyword; item.DisplayOrder = dbItem.DisplayOrder; item.Deleted = dbItem.Deleted; return item; } #endregion #region Methods /// <summary> /// Gets a credit card type /// </summary> /// <param name="CreditCardTypeID">Credit card type identifier</param> /// <returns>Credit card type</returns> public static CreditCardType GetCreditCardTypeByID(int CreditCardTypeID) { if (CreditCardTypeID == 0) return null; string key = string.Format(CREDITCARDS_BY_ID_KEY, CreditCardTypeID); object obj2 = NopCache.Get(key); if (CreditCardTypeManager.CacheEnabled && (obj2 != null)) { return (CreditCardType)obj2; } DBCreditCardType dbItem = DBProviderManager<DBCreditCardTypeProvider>.Provider.GetCreditCardTypeByID(CreditCardTypeID); CreditCardType creditCardType = DBMapping(dbItem); if (CreditCardTypeManager.CacheEnabled) { NopCache.Max(key, creditCardType); } return creditCardType; } /// <summary> /// Marks a credit card type as deleted /// </summary> /// <param name="CreditCardTypeID">Credit card type identifier</param> public static void MarkCreditCardTypeAsDeleted(int CreditCardTypeID) { CreditCardType creditCardType = GetCreditCardTypeByID(CreditCardTypeID); if (creditCardType != null) { UpdateCreditCardType(creditCardType.CreditCardTypeID, creditCardType.Name, creditCardType.SystemKeyword, creditCardType.DisplayOrder, true); } if (CreditCardTypeManager.CacheEnabled) { NopCache.RemoveByPattern(CREDITCARDS_PATTERN_KEY); } } /// <summary> /// Gets all credit card types /// </summary> /// <returns>Credit card type collection</returns> public static CreditCardTypeCollection GetAllCreditCardTypes() { string key = string.Format(CREDITCARDS_ALL_KEY); object obj2 = NopCache.Get(key); if (CreditCardTypeManager.CacheEnabled && (obj2 != null)) { return (CreditCardTypeCollection)obj2; } DBCreditCardTypeCollection dbCollection = DBProviderManager<DBCreditCardTypeProvider>.Provider.GetAllCreditCardTypes(); CreditCardTypeCollection creditCardTypeCollection = DBMapping(dbCollection); if (CreditCardTypeManager.CacheEnabled) { NopCache.Max(key, creditCardTypeCollection); } return creditCardTypeCollection; } /// <summary> /// Inserts a credit card type /// </summary> /// <param name="Name">The name</param> /// <param name="SystemKeyword">The system keyword</param> /// <param name="DisplayOrder">The display order</param> /// <param name="Deleted">A value indicating whether the entity has been deleted</param> /// <returns>A credit card type</returns> public static CreditCardType InsertCreditCardType(string Name, string SystemKeyword, int DisplayOrder, bool Deleted) { DBCreditCardType dbItem = DBProviderManager<DBCreditCardTypeProvider>.Provider.InsertCreditCardType(Name, SystemKeyword, DisplayOrder, Deleted); CreditCardType creditCardType = DBMapping(dbItem); if (CreditCardTypeManager.CacheEnabled) { NopCache.RemoveByPattern(CREDITCARDS_PATTERN_KEY); } return creditCardType; } /// <summary> /// Updates the credit card type /// </summary> /// <param name="CreditCardTypeID">Credit card type identifier</param> /// <param name="Name">The name</param> /// <param name="SystemKeyword">The system keyword</param> /// <param name="DisplayOrder">The display order</param> /// <param name="Deleted">A value indicating whether the entity has been deleted</param> /// <returns>A credit card type</returns> public static CreditCardType UpdateCreditCardType(int CreditCardTypeID, string Name, string SystemKeyword, int DisplayOrder, bool Deleted) { DBCreditCardType dbItem = DBProviderManager<DBCreditCardTypeProvider>.Provider.UpdateCreditCardType(CreditCardTypeID, Name, SystemKeyword, DisplayOrder, Deleted); CreditCardType creditCardType = DBMapping(dbItem); if (CreditCardTypeManager.CacheEnabled) { NopCache.RemoveByPattern(CREDITCARDS_PATTERN_KEY); } return creditCardType; } #endregion #region Property /// <summary> /// Gets a value indicating whether cache is enabled /// </summary> public static bool CacheEnabled { get { return SettingManager.GetSettingValueBoolean("Cache.CreditCardTypeManager.CacheEnabled"); } } #endregion } }
using System.Collections.Generic; namespace stottle_shop_api.Filters.Models { public class Filter : IFilter { public string Id { get; set; } public string DisplayName { get; set; } public string Code { get; set; } public bool IsActive { get; set; } public IEnumerable<FilterItem> Items { get; set; } } }
using PDV.DAO.Atributos; namespace PDV.DAO.Entidades { public class Marca { [CampoTabela("IDMARCA")] [MaxLength(18)] public decimal IDMarca { get; set; } = -1; [CampoTabela("CODIGO")] [MaxLength(40)] public string Codigo { get; set; } = string.Empty; [CampoTabela("DESCRICAO")] [MaxLength(250)] public string Descricao { get; set; } [CampoTabela("CODIGODESCRICAO")] [MaxLength(280)] public string CodigoDescricao { get; set; } [CampoTabela("MARCADEVEICULO")] public bool MarcaDeVeiculo { get; set; } [CampoTabela("MARCADEPRODUTO")] public bool MarcaDeProduto { get; set; } public object ImagemMarca { get; set; } public Marca() { } } }
using APIpoc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace APIpoc.Data { public interface IProduct { bool SaveChanges(); IEnumerable<TblProduct> GetAllProduct(); void CreateProduct(TblProduct product); } }
using UnityEngine; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable] public class SaveState { public List<int> highScores; private int _version; private const int CURRENT_VERSION = 1; private const string SAVE_FILE_NAME = "/save.bin"; private SaveState() { highScores = new List<int>(); } public void Save() { var formatter = new BinaryFormatter(); var file = File.Open(Application.persistentDataPath + SAVE_FILE_NAME, FileMode.OpenOrCreate); formatter.Serialize(file, this); file.Close(); } public static SaveState Load() { if (DoesSaveFileExist) { var formatter = new BinaryFormatter(); var file = File.Open(Application.persistentDataPath + SAVE_FILE_NAME, FileMode.Open); var saveFile = (SaveState)formatter.Deserialize(file); file.Close(); saveFile.ReconcileExistingSaveFile(); return saveFile; } else { return Create(); } } private static SaveState Create() { var newSave = new SaveState(); newSave._version = CURRENT_VERSION; newSave.Save(); return newSave; } public static bool DoesSaveFileExist => File.Exists(Application.persistentDataPath + SAVE_FILE_NAME); private void ReconcileExistingSaveFile() { var shouldResave = false; if (_version < CURRENT_VERSION) { shouldResave = true; ReconcileFileVersion(); } if (shouldResave) { _version = CURRENT_VERSION; Save(); } } private void ReconcileFileVersion() { } }
using EmployeeStorage.DataAccess.Configuration; using EmployeeStorage.DataAccess.Entities; using EmployeeStorage.DataAccess.Interfaces; namespace EmployeeStorage.DataAccess.Repositories { internal class PositionRepository : Repository<Position>, IPositionRepository { public PositionRepository(EmployeeStorageContext context) : base(context) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class roadgame : MonoBehaviour { public GameObject[] tilePref; private float SpawnZ=-3500; private float tileLenght = 5000f; private int roadscreen = 2; private Transform Playertransform; private List<GameObject> Activetiles; private float safeLane = 2600; private int forro; private void Start() { Activetiles = new List<GameObject>(); for (int i = 0; i < roadscreen; i++) { SpawnTİle(); } } private void Update() { Playertransform = GameObject.FindGameObjectWithTag("car").transform; if (Playertransform.position.z-safeLane > (SpawnZ - roadscreen * tileLenght)) { SpawnTİle(); deleteTile(); } } private void SpawnTİle(int prefabIndex = -1) { if (-11 <Score.zo && Score.zo < 10 ) { forro = Random.Range(0, 1); } else if (11 < Score.zo && Score.zo < 200) { forro = Random.Range(0, 3); } else if (201 < Score.zo && Score.zo < 350) { forro = Random.Range(3, 5); } else if (351 < Score.zo && Score.zo < 500) { forro = Random.Range(4, 7); } else if (501 < Score.zo && Score.zo < 750) { forro = Random.Range(7, 10); } else if (751 < Score.zo && Score.zo < 1000) { forro = Random.Range(9, 12); } else if (1000 < Score.zo ) { forro = Random.Range(4, 12); } GameObject go; go = Instantiate(tilePref[forro]) as GameObject; go.transform.SetParent(transform); go.transform.position = Vector3.forward * SpawnZ; SpawnZ += tileLenght; Activetiles.Add(go); } private void deleteTile() { Destroy(Activetiles[0]); Activetiles.RemoveAt(0); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace API { public class DSFactory { public static IDS GetInstance(string file) { string ext = Path.GetExtension(file); switch (ext) { case "bmp": return new DS_Bmp(file); default: return new DS_Bmp(file); } } } }
using UnityEngine; using UnityEngine.Events; namespace Architecture.ViewModel.Applicator { public class UnityEventIntApplicator : CompareApplicator<int> { [SerializeField] private UnityEvent<bool> _notifyCompare; protected override void NotifyBool(bool value) { _notifyCompare.Invoke(value); } } }
///<summary> ///Script Manager: Drake ///Description: ///Handles enemy movement AI, health, and score value. ///</summary> using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public enum eEnemyAIType { STATIC, FOLLOW_PLAYER, FOLLOW_WAYPOINT }; [RequireComponent(typeof(UIHitEffect))] public class EnemyActor : MonoBehaviour { [Header("Global Variables")] [Tooltip("The maximum health this enemy has")] public int m_nHealth; [HideInInspector] public int m_nCurrentHealth; [Tooltip("Whether or not this enemy should rotate to face the player")] [SerializeField] protected bool m_bTrackPlayer; [Tooltip("How fast this enemy should rotate, if 0, will not rotate")] [SerializeField] protected float m_fRotationSpeed; [Tooltip("What type of AI this enemy should have")] [SerializeField] protected eEnemyAIType m_enemyAIType; //Whether or not this enemy is currently active [HideInInspector] public bool m_bIsActive; //Whether or not this enemy is currently alive [HideInInspector] public bool m_bIsAlive; [HideInInspector] public bool m_bIsShooting; //The current level section of this enemy [HideInInspector] public LevelSection m_section; //Reference to the player private GameObject m_player; [Tooltip("Maximum speed the enemy will move at")] [SerializeField] protected float m_fMaxMovementSpeed; [Tooltip("How smoothed the enemy's movement will be, less is more smoothed")] [SerializeField] protected float m_fMovementSmoothing; [Header("Follow Player Variables")] [Tooltip("How far this enemy should try and stay from the player")] [SerializeField] protected Vector3 m_v3Offset; //The current speed of the enemy private Vector3 m_v3Velocity; [Header("Follow Waypoint Variables")] [Tooltip("The transforms of the waypoints this enemy should go between, should have the same size as Delays")] [SerializeField] protected Transform[] m_waypoints; [Tooltip("How long this enemy should spend at each waypoint, should have the same size as Waypoints")] [SerializeField] protected float[] m_delays; [Tooltip("Whether or not the enemy should loop through the waypoints, or if it should just go through them once")] [SerializeField] protected bool m_bLoopWaypoints; //The current/previous waypoint the enemy was at private int m_nCurrentWaypoint = 0; //The waypoint the enemy is moving towards private int m_nDesiredWaypoint = 0; //Timer in seconds private float m_fTimer; //Whether or not the enemy is currently waiting at a waypoint private bool m_bWaitingAtWaypoint; [Header("Score")] [Tooltip("The score value of this enemy immediately upon being killed")] public long m_lRawScore; [Tooltip("The score value of the pickups this enemy drops upon death")] public long m_lPickupScore; [Tooltip("How much additional multiplier this enemy is worth")] public float m_fMultiplier; [Header("Death")] [Tooltip("Fire Death Particle System")] public GameObject m_fireDeathPS; [Tooltip("Ice Death Particle System")] public GameObject m_iceDeathPS; [Tooltip("Lightning Death Particle System")] public GameObject m_lightningDeathPS; private ScoreManager m_ScoreManager; protected virtual void Start() { //Start out inactive but alive m_bIsActive = false; m_bIsAlive = true; //Set current health to maximum health m_nCurrentHealth = m_nHealth; m_ScoreManager = ScoreManager.Instance; //Get player m_player = GameObject.FindGameObjectWithTag("Player"); //Check if waypoints and delays match if (m_waypoints.Length != m_delays.Length) Debug.LogError(name + " has mismatching delays and waypoints"); } private void Update() { //If enemy is active if(m_bIsActive) { //If this enemy tracks player, turn towards them if (m_bTrackPlayer) { Vector3 lookPos = m_player.transform.position - transform.position; lookPos.y = 0; Quaternion targetRotation = Quaternion.LookRotation(lookPos); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, m_fRotationSpeed * Time.deltaTime); } //If enemy does not track player, and has rotation, rotate enemy clockwise at constant rate else if (m_fRotationSpeed != 0.0f) { transform.Rotate(Vector3.up, m_fRotationSpeed * Time.deltaTime); } switch(m_enemyAIType) { case eEnemyAIType.FOLLOW_PLAYER: // desired position Vector3 desiredPosition = new Vector3 ( m_player.transform.position.x + m_v3Offset.x * transform.localScale.x, m_player.transform.position.y + m_v3Offset.y * transform.localScale.y, m_player.transform.position.z + m_v3Offset.z * transform.localScale.z ); GameObject playfield = GameObject.FindGameObjectWithTag("Playfield"); if (desiredPosition.z > playfield.transform.position.z + playfield.GetComponent<BoxCollider>().size.z / 1.5f) desiredPosition.z = playfield.transform.position.z + playfield.GetComponent<BoxCollider>().size.z / 1.5f; // smoothly move to that position transform.position = Vector3.SmoothDamp(transform.position, desiredPosition, ref m_v3Velocity, 1 / m_fMovementSmoothing, m_fMaxMovementSpeed * Time.deltaTime); break; case eEnemyAIType.FOLLOW_WAYPOINT: //If looping waypoints and enemy has reached the last waypoint, set desired waypoint to 0 if(m_bLoopWaypoints && m_nDesiredWaypoint >= m_waypoints.Length) m_nDesiredWaypoint = 0; //If not looping and enemy has reached the last waypoint, deactivate else if (!m_bLoopWaypoints && m_nDesiredWaypoint >= m_waypoints.Length) { Deactivate(); return; } //If currently waiting at a waypoint, start incrementing timer if(m_bWaitingAtWaypoint) { m_fTimer += Time.deltaTime; //When timer reaches delay, reset timer, stop waiting at waypoint, and increment desired waypoint if(m_fTimer >= m_delays[m_nCurrentWaypoint]) { m_fTimer = 0.0f; m_bWaitingAtWaypoint = false; m_nDesiredWaypoint++; } } //Otherwise, smoothly move to the next waypoint else { transform.position = Vector3.SmoothDamp(transform.position, m_waypoints[m_nDesiredWaypoint].position, ref m_v3Velocity, 1 / m_fMovementSmoothing, m_fMaxMovementSpeed * Time.deltaTime); } //If not waiting at waypoint and desired waypoint is valid, check if close to waypoint if(!m_bWaitingAtWaypoint && m_nDesiredWaypoint < m_waypoints.Length) { //If close to desired waypoint, start waiting at waypoint if (Vector3.Distance(transform.position, m_waypoints[m_nDesiredWaypoint].position) < 0.1f) { m_nCurrentWaypoint = m_nDesiredWaypoint; m_bWaitingAtWaypoint = true; } } break; case eEnemyAIType.STATIC: break; default: break; } } } public void Activate(GameObject target, GameObject newParent) { // set isActive to true m_bIsActive = true; // make enemy position and movement relative to the player's movement area transform.parent = newParent.transform; } public virtual void TakeDamage(int damage) { //deal the damage m_nCurrentHealth -= damage; // if enemy runs out of health if(m_nCurrentHealth <= 0) { Die(); } GetComponent<UIHitEffect>().Show(); } public void Die() { //Set inactive and dead m_bIsActive = false; m_bIsAlive = false; //Give multiplier and score m_ScoreManager.AddMultiplier(m_fMultiplier); m_ScoreManager.AddScore(m_lRawScore); m_ScoreManager.DropScorePickup(m_lPickupScore, transform); // Destroy health bar if present if (GetComponent<UIHealthBar>()) { GetComponent<UIHealthBar>().DestroyHealthBar(); } StartDeathAnimation(); //Disable enemy gameObject.SetActive(false); } public void Deactivate() { //Set inactive and dead m_bIsActive = false; m_bIsAlive = false; if (GetComponent<UIHealthBar>()) { GetComponent<UIHealthBar>().DestroyHealthBar(); } //Disable enemy gameObject.SetActive(false); } #region StartDeathAnimation ///<summary> Code by Denver Lacey ///</summary> void StartDeathAnimation() { // get reference to spell manager PlayerSpellManager spellManager = FindObjectOfType<PlayerSpellManager>(); // instantiate death particle system based on current spell type try { switch (spellManager.m_eSpellType) { case eSpellType.FIRE: // instantiate new fire death animation GameObject fireGO = Instantiate(m_fireDeathPS, transform.position, Quaternion.identity, transform.parent); // destroy it once animation complete Destroy(fireGO, fireGO.GetComponent<ParticleSystem>().main.duration); break; case eSpellType.ICE: // instantiate new ice death animation GameObject iceGO = Instantiate(m_iceDeathPS, transform.position, Quaternion.identity, transform.parent); // destroy it once animation complete Destroy(iceGO, iceGO.GetComponent<ParticleSystem>().main.duration); break; case eSpellType.LIGHTNING: // instantiate new lightning death animation GameObject lightningGO = Instantiate(m_lightningDeathPS, transform.position, Quaternion.identity, transform.parent); // destroy it once animation complete Destroy(lightningGO, lightningGO.GetComponent<ParticleSystem>().main.duration); break; default: Debug.LogError("Couldn't find spell type.", gameObject); break; } } catch (Exception e) { Debug.LogError(e.Message); } } #endregion private void OnTriggerStay(Collider other) { if (other.tag == "LightningAttack" && m_bIsActive) { TakeDamage(other.GetComponent<LightningSpellProjectile>().m_nDamage); } } private void OnTriggerEnter(Collider other) { //Check if enemy has collided with player projectile if (other.tag == "PlayerProjectile" && m_bIsActive) { TakeDamage(other.GetComponent<PlayerSpellProjectile>().m_nDamage); } if (other.tag == "Playfield") { m_bIsShooting = true; } } private void OnTriggerExit(Collider other) { if(other.tag == "Playfield") { m_bIsShooting = false; } } }
using System; namespace Reto_Semana_3_02 { class Program { static void Main(string[] args) { //https://youtu.be/djUD5CW20kU //Referencia del valor de cuota moderadora 2021 //https://www.minsalud.gov.co/sites/rid/Lists/BibliotecaDigital/RIDE/VP/DOA/cuotas-moderadoras-copagos-2021.pdf int smmlv = 908526; Console.WriteLine("Ingrese su salario"); int salario = int.Parse(Console.ReadLine()); if (salario < smmlv * 2) { Console.WriteLine("A usted le corresponde la tarifa A"); Console.WriteLine("Con un valor de cuota moderadora de: 3500$"); } else if (salario < smmlv * 5) { Console.WriteLine("A usted le corresponde la tarifa B"); Console.WriteLine("Con un valor de cuota moderadora de: 14000$"); } else { Console.WriteLine("A usted le corresponde la tarifa C"); Console.WriteLine("Con un valor de cuota moderadora de: 36800$"); } } } }
using FluentNHibernate.Mapping; using Psub.Domain.Entities; namespace Psub.DataAccess.Map { public class PublicationCommentMap : ClassMap<PublicationComment> { public PublicationCommentMap() { Id(m => m.Id); Map(m => m.Text).CustomType("StringClob").Not.Nullable(); Map(m => m.UserName).Length(200).Not.Nullable(); Map(m => m.UserGuid).Length(100).Not.Nullable(); Map(m => m.Created); Map(m => m.Guid); References(m => m.AnswerTo).Nullable(); References(m => m.Publication); HasMany(x => x.Likes).Fetch.Join().Inverse().Cascade.SaveUpdate(); HasMany(x => x.Replys).KeyColumn("AnswerToId").KeyNullable(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Final_ConnectFour { public class Cell { public int X { get; } public int Y { get; } public bool IsPlaced { get; private set; } = false; // The default value for player number is -1 if there is no player assigned // this should be used for error checks. // Im not the one handling this so you can change the implementation if you want... // but I was thinking: // Null = 0 // Player 1 = 1 // Player 2 = 2 public int PlayerNumber { get; private set; } = 0; public RoundButton Button { get; set; } public Cell(int x, int y) { this.X = x; this.Y = y; } public Cell(int x, int y, RoundButton button) { this.X = x; this.Y = y; this.Button = button; } public Cell(int x, int y, RoundButton button, bool isPlaced, int playerNumber) { this.X = x; this.Y = y; this.Button = button; this.IsPlaced = isPlaced; this.PlayerNumber = playerNumber; } public void Reset() { this.Button.Enabled = true; this.IsPlaced = false; this.PlayerNumber = 0; this.Button.Reset(); } public void PlaceRed(int playerNumber) { if (IsPlaced || !this.Button.Enabled) return; this.Button.SetRed(); this.PlayerNumber = playerNumber; this.IsPlaced = true; } public void PlaceYellow(int playerNumber) { if (IsPlaced || !this.Button.Enabled) return; this.Button.SetYellow(); this.PlayerNumber = playerNumber; this.IsPlaced = true; } // Debug Functions public override string ToString() => $"({X}, {Y})"; } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using TheMinepack.Items; namespace TheMinepack.Items.Weapons { public class StarrySky : ModItem { public override bool Autoload(ref string name, ref string texture, IList<EquipType> equips) { texture = "TheMinepack/Items/Weapons/StarrySky"; return true; } public override void SetDefaults() { item.name = "Starry Sky"; AddTooltip("Fires large stars from the sky that break into more stars\nLarge stars inflict ichor"); item.width = 28; item.height = 30; item.damage = 60; item.magic = true; item.mana = 10; item.noMelee = true; item.useAnimation = 35; item.useTime = 35; item.useStyle = 5; item.useTurn = true; item.autoReuse = true; item.knockBack = 6f; item.UseSound = SoundID.Item8; item.value = Item.sellPrice(0, 10, 0, 0); item.rare = 6; item.shoot = mod.ProjectileType("StarrySkyProjectileLarge"); item.shootSpeed = 15; } public override bool Shoot(Player player, ref Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack) { int numberProjectiles = 3; for (int index = 0; index < numberProjectiles; ++index) { Vector2 vector2_1 = new Vector2((float)((double)player.position.X + (double)player.width * 0.5 + (double)(Main.rand.Next(201) * -player.direction) + ((double)Main.mouseX + (double)Main.screenPosition.X - (double)player.position.X)), (float)((double)player.position.Y + (double)player.height * 0.5 - 600.0)); vector2_1.X = (float)(((double)vector2_1.X + (double)player.Center.X) / 2.0) + (float)Main.rand.Next(-200, 201); vector2_1.Y -= (float)(100 * index); float num12 = (float)Main.mouseX + Main.screenPosition.X - vector2_1.X; float num13 = (float)Main.mouseY + Main.screenPosition.Y - vector2_1.Y; if ((double)num13 < 0.0) num13 *= -1f; if ((double)num13 < 20.0) num13 = 20f; float num14 = (float)Math.Sqrt((double)num12 * (double)num12 + (double)num13 * (double)num13); float num15 = item.shootSpeed / num14; float num16 = num12 * num15; float num17 = num13 * num15; float SpeedX = num16 + (float)Main.rand.Next(-40, 41) * 0.01f; float SpeedY = num17 + (float)Main.rand.Next(-40, 41) * 0.01f; Projectile.NewProjectile(vector2_1.X, vector2_1.Y, SpeedX, SpeedY, type, damage, knockBack, Main.myPlayer, 0.0f, (float)Main.rand.Next(5)); } return false; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "GalactaniteBar", 10); // 10 Galactanite Bars recipe.AddTile(TileID.MythrilAnvil); // Mythril Anvil recipe.SetResult(this); recipe.AddRecipe(); } }}
using TreeStore.Model.Base; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace TreeStore.Model.Test { public class EntityBaseTest { public static IEnumerable<object[]> GetEntityBaseInstancesForInitzialization() { yield return new Entity().Yield().ToArray(); yield return new Category().Yield().ToArray(); yield return new Tag().Yield().ToArray(); yield return new Facet().Yield().ToArray(); yield return new FacetProperty().Yield().ToArray(); } public static IEnumerable<object[]> GetEntityBaseInstancesForEquality() { var refId = Guid.NewGuid(); var differentId = Guid.NewGuid(); yield return new object[] { new Entity { Id = refId }, new Entity { Id = refId }, new Entity { Id = differentId }, new FacetProperty { Id = refId } }; yield return new object[] { new Category { Id = refId }, new Category { Id = refId }, new Category { Id = differentId }, new Tag { Id = refId } }; yield return new object[] { new Tag { Id = refId }, new Tag { Id = refId }, new Tag { Id = differentId }, new Facet { Id = refId } }; yield return new object[] { new Facet { Id = refId }, new Facet { Id = refId }, new Facet { Id = differentId }, new FacetProperty { Id = refId } }; yield return new object[] { new FacetProperty { Id = refId }, new FacetProperty { Id = refId }, new FacetProperty { Id = differentId }, new Entity { Id = refId } }; } [Theory] [MemberData(nameof(GetEntityBaseInstancesForEquality))] public void EntityBases_are_equal_if_Id_are_equal_and_Type(NamedBase refEntity, NamedBase sameId, NamedBase differentId, NamedBase differentType) { // ACT & ASSERT Assert.Equal(refEntity, refEntity); Assert.Equal(refEntity.GetHashCode(), refEntity.GetHashCode()); Assert.Equal(refEntity, sameId); Assert.Equal(refEntity.GetHashCode(), sameId.GetHashCode()); Assert.NotEqual(refEntity, differentId); Assert.NotEqual(refEntity.GetHashCode(), differentId.GetHashCode()); Assert.NotEqual(refEntity, differentType); Assert.NotEqual(refEntity.GetHashCode(), differentType.GetHashCode()); } [Theory] [MemberData(nameof(GetEntityBaseInstancesForInitzialization))] public void EntityBases_have_empty_name(NamedBase entityBase) { // ACT var result = entityBase.Name; // ASSERT Assert.Equal(string.Empty, result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using ERP_Palmeiras_LA.Models.Facade; using ERP_Palmeiras_LA.Models; namespace ERP_Palmeiras_LA.WebServices { /// <summary> /// Summary description for InfoPagamentoWS /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class InfoPagamentoWS : System.Web.Services.WebService { LogisticaAbastecimento facade = LogisticaAbastecimento.GetInstance(); [WebMethod] public bool EquipamentoPago(int idCompra) { try { CompraEquipamento ce = facade.BuscarCompraEquipamento(idCompra); ce.Status = StatusCompra.COMPRA_CONCLUIDA; ce.DataEntrega = DateTime.Now.Ticks; facade.AlterarCompraEquipamento(ce); return true; } catch (Exception) { return false; } } [WebMethod] public bool MaterialPago(int idCompra) { try { CompraMaterial ce = facade.BuscarCompraMaterial(idCompra); ce.Status = StatusCompra.COMPRA_CONCLUIDA; ce.DataEntrega = DateTime.Now.Ticks; facade.AlterarCompraMaterial(ce); return true; } catch (Exception) { return false; } } [WebMethod] public bool ManutencaoPaga(int idSolicitacao) { try { SolicitacaoManutencao se = facade.BuscarManutencao(idSolicitacao); se.Status = StatusSolicitacaoManutencao.PAGA; se.DataTerminoManutencao = DateTime.Now.Ticks; facade.AlterarManutencao(se); return true; } catch (Exception) { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnimalGame { class Store { private bool _purchasedItem; public List <Item> SetupShop() { Item atkBuff = new Item("Attack Buff", 5, 1, Stat.Attack, 100); Item defBuff = new Item("Defense Buff", 5, 1, Stat.Defense, 60); Item speedBuff = new Item("Speed Buff", 2, 1, Stat.Speed, 40); Item heal = new Item("Heal", 30, 1, Stat.Heal, 100); Item maxHeal = new Item("Max Heal", 1000, 1, Stat.MaxHeal, 300); Item net = new Item("Net", 1, 1, Stat.Catch, 100); List<Item> availableItems = new List<Item> { atkBuff, defBuff, speedBuff, heal, maxHeal, net }; return availableItems; } public void PurchaseItem(List<Item> playerList, Item shopItem, Player player1) { if (player1.Money >= shopItem.Price) { player1.Money = -shopItem.Price; _purchasedItem = true; playerList.Add(shopItem); } } public bool PurchasedItem { get { return _purchasedItem; } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System; namespace IJFinalProject.GameScenes { /// <summary> /// This is action scene for the game. /// </summary> public class ActionScene : Game { private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; private Santa santa; private Random randomPosition = new Random(); private int delayCounter = 0; private int delay = 300; private Present present; private int positionX; private int positionY; private Vector2 presentPosition; private int presentSpeed = 4; private Texture2D presentTexture; private Song gettingSound; Vector2 stage; public ActionScene() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1920; graphics.PreferredBackBufferHeight = 1080; IsMouseVisible = true; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here //Background Texture2D level1 = this.Content.Load<Texture2D>("Images/BG_02"); Texture2D level2 = this.Content.Load<Texture2D>("Images/BG_03"); Texture2D startImage = this.Content.Load<Texture2D>("Images/startImage"); Texture2D village = this.Content.Load<Texture2D>("Images/houses3"); stage = new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); Rectangle srcRec = new Rectangle(0, 0, level1.Width, level1.Height); Vector2 pos = new Vector2(0, 0); Vector2 speed = new Vector2(2, 0); //SoundEffect menuMusic = this.Content.Load<SoundEffect>("Sounds/JazzJingleBell"); //SoundEffect level1Music = this.Content.Load<SoundEffect>("Sounds/Jingle-Bell-Rock-Bobby-Helms"); Song menuMusic = this.Content.Load<Song>("Sounds/JazzJingleBell"); Song level1Music = this.Content.Load<Song>("Sounds/Jingle-Bell-Rock-Bobby-Helms"); Song level2Music = this.Content.Load<Song>("Sounds/Rudolph-The-Red-Nosed-Reindeer-Gene-Autry"); MediaPlayer.IsRepeating = true; ScrollingBackground scrollingBackground = new ScrollingBackground(this, spriteBatch, level2, pos, srcRec, speed); ScrollingBackground houses = new ScrollingBackground(this, spriteBatch, village, pos, srcRec, speed); this.Components.Add(scrollingBackground); this.Components.Add(houses); //Santa //Texture2D santaTexture = Content.Load<Texture2D>("Images/modify_Santa_with_sledgh"); Texture2D santaTextureBig = Content.Load<Texture2D>("Images/santaBig2"); SoundEffect santaVoice = this.Content.Load<SoundEffect>("Sounds/SantaVoice"); Vector2 santaInitialPosition = new Vector2(0, stage.Y / 2); Vector2 santaSpeed = new Vector2(4, 4); int santaDelay = 3; santa = new Santa(this, spriteBatch, santaTextureBig, santaInitialPosition, santaDelay, santaSpeed, stage, santaVoice); this.Components.Add(santa); MediaPlayer.Play(level1Music); //CandyCane Texture2D candyCaneTexture = this.Content.Load<Texture2D>("Images/candyCane1"); Vector2 candyCanePosition = new Vector2(stage.X, randomPosition.Next((int)stage.Y)); //Present presentTexture = this.Content.Load<Texture2D>("Images/present2"); Texture2D present2 = this.Content.Load<Texture2D>("Images/present3"); Texture2D present3 = this.Content.Load<Texture2D>("Images/present4"); gettingSound = this.Content.Load<Song>("Sounds/zapsplat_foley_present_gift_wrapped_pick_up_grab_001_42924"); positionX = graphics.PreferredBackBufferWidth; Random random = new Random(); positionY = random.Next(0, graphics.PreferredBackBufferHeight - presentTexture.Height); presentPosition = new Vector2(positionX, positionY); present = new Present(this, spriteBatch, presentTexture, presentPosition, new Vector2(presentSpeed, 0), stage); this.Components.Add(present); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here delayCounter++; if (delayCounter > delay) { positionX = graphics.PreferredBackBufferWidth; Random random = new Random(); positionY = random.Next(0, graphics.PreferredBackBufferHeight - presentTexture.Height); presentPosition = new Vector2(positionX, positionY); present = new Present(this, spriteBatch, presentTexture, presentPosition, new Vector2(presentSpeed, 0), stage); this.Components.Add(present); delayCounter = 0; } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here base.Draw(gameTime); } } }
namespace Mediati.Core.Events { /// <summary> /// Tag that designates that a command or query triggers an event /// </summary> /// <typeparam name="TEvent">The event type to be created from the triggering message</typeparam> /// <typeparam name="TMessageReturn">The return type of the message that triggers the event</typeparam> public interface ITriggersEvent<TEvent, TMessageReturn> where TEvent : IDomainEvent { /// <summary> /// Converts the result of a message into an event object /// </summary> /// <param name="messageReturn">The return of the message that triggers the event</param> /// <returns>A domain event object</returns> TEvent ToEvent(TMessageReturn messageReturn); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace Dnn.PersonaBar.Recyclebin.Components.Dto { public class UserItem { public int Id { get; set; } public int PortalId { get; set; } public string Username { get; set; } public string DisplayName { get; set; } public string Email { get; set; } public string LastModifiedOnDate { get; set; } public string FriendlyLastModifiedOnDate { get; set; } } }
using System; namespace Number0to9toText { class Number0to9toText { static void Main(string[] args) { byte theNumber; theNumber = byte.Parse(Console.ReadLine()); if(theNumber == 0) { Console.WriteLine("zero"); } else if(theNumber == 1) { Console.WriteLine("one"); } else if (theNumber == 2) { Console.WriteLine("two"); } else if (theNumber == 3) { Console.WriteLine("three"); } else if (theNumber == 4) { Console.WriteLine("four"); } else if (theNumber == 5) { Console.WriteLine("five"); } else if (theNumber == 6) { Console.WriteLine("six"); } else if (theNumber == 7) { Console.WriteLine("seven"); } else if (theNumber == 8) { Console.WriteLine("eight"); } else if (theNumber == 9) { Console.WriteLine("nine"); } else { Console.WriteLine("number too big"); } } } }
using Our.Umbraco.Ditto; using Umbraco.Core.Models; using Umbraco.Web; namespace DittoDemo { public static class DitFloViewModelExtensions { public static IPublishedContent HomePage(this IDittoViewModel model) { return model.CurrentPage.AncestorOrSelf(1); } } }
using CodeOwls.PowerShell.Provider; using TreeStore.Model; using System; using System.Management.Automation; namespace TreeStore.PsModule { public class TreeStoreDriveInfo : Drive, IDisposable { public TreeStoreDriveInfo(PSDriveInfo driveInfo, ITreeStorePersistence persistence) : base(driveInfo) { this.Persistence = persistence; } public ITreeStorePersistence Persistence { get; } public string Database { get; set; } #region IDisposable Support public void Dispose() => this.Persistence.Dispose(); #endregion IDisposable Support } }
using ServerKinect.Shape; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.Clustering { public class KMeansClusterFactory : IClusterFactory { private KMeans algorithm; private IClusterMergeStrategy mergeStrategy; private ClusterDataSourceSettings settings; private ClusterCollection value; public KMeansClusterFactory(ClusterDataSourceSettings settings, IntSize size) : this(settings, new DefaultMergeStrategy(settings), size) { } public KMeansClusterFactory(ClusterDataSourceSettings settings, IClusterMergeStrategy mergeStrategy, IntSize size) { this.settings = settings; this.mergeStrategy = mergeStrategy; this.algorithm = new KMeans(this.settings.ClusterCount, settings.DepthRange, size); this.value = new ClusterCollection(); } public ClusterCollection Create(IList<Point> points) { var reducedPoints = this.ReducePoints(points); if (this.AreEnoughPointsForClustering(reducedPoints.Count)) { this.FindClusters(reducedPoints); this.AssignAllPoints(points); } else { this.value = new ClusterCollection(); } return this.value; } private bool AreEnoughPointsForClustering(int count) { return count >= settings.MinimalPointsForClustering; } private IList<Point> ReducePoints(IList<Point> points) { return points.Where(p => p.X % this.settings.PointModulo == 0 && p.Y % this.settings.PointModulo == 0).ToList(); } private void FindClusters(IList<Point> pointList) { this.InitializeAlgorithm(pointList); this.algorithm.IterateUntilStable(); if (this.algorithm.ClusterCount > 0) { var prototypes = this.FlattenIfRequired(this.MergeClustersIfRequired(this.algorithm.Clusters)); this.value = new ClusterCollection(prototypes.Select(p => p.ToCluster()).ToList()); } } private IList<ClusterPrototype> FlattenIfRequired(IList<ClusterPrototype> clusters) { if (this.settings.MaximumClusterDepth.HasValue) { foreach (var cluster in clusters) { cluster.Flatten(this.settings.MaximumClusterDepth.Value); } } return clusters; } private void InitializeAlgorithm(IList<Point> pointList) { this.algorithm.Initialize(pointList); } private void AssignAllPoints(IList<Point> fullList) { foreach (var cluster in this.value.Clusters) { var allPoints = new List<Point>(); var area = cluster.Area; foreach (var point in fullList) { if (area.Contains(point)) { allPoints.Add(point); } } cluster.AllPoints = allPoints; } } private IList<ClusterPrototype> MergeClustersIfRequired(IEnumerable<ClusterPrototype> clusters) { IList<ClusterPrototype> localClusters = clusters.Where(c => c.PointCount >= settings.MinimalPointsForValidCluster).ToList(); if (localClusters.Count > 1) { int clusterCount; do { clusterCount = localClusters.Count; localClusters = this.mergeStrategy.MergeClustersIfRequired(localClusters); } while (localClusters.Count != clusterCount); } return localClusters.Where(c => c.PointCount <= settings.MaximalPointsForValidCluster).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Reflection; using System.Windows; using System.Windows.Input; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Autodesk.Revit.UI; using System.Net.Http; using System.Threading.Tasks; namespace InfoPanel { public partial class NewForm : Page, IDockablePaneProvider { public NewForm() { InitializeComponent(); } public void SetupDockablePane(DockablePaneProviderData data) { data.FrameworkElement = this as FrameworkElement; data.InitialState = new DockablePaneState(); data.InitialState.MinimumWidth = 300; data.VisibleByDefault = true; data.InitialState.DockPosition = DockPosition.Tabbed; data.InitialState.TabBehind = Autodesk.Revit.UI.DockablePanes.BuiltInDockablePanes.ProjectBrowser; } /// Tab 1 These are the web pages which are not PDFs private void Web_Click(object sender, RoutedEventArgs e) { var bItem = (Button)sender; WebP.Navigate(bItem.Tag.ToString()); } /// This is where we set the forward & back buttons for the web pages private void BrowseBack_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ((WebP != null) && (WebP.CanGoBack)); } private void BrowseBack_Executed(object sender, ExecutedRoutedEventArgs e) { WebP.GoBack(); } private void BrowseForward_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ((WebP != null) && (WebP.CanGoForward)); } private void BrowseForward_Executed(object sender, ExecutedRoutedEventArgs e) { WebP.GoForward(); } //Tab2 private void InfoMenu_Click(object sender, RoutedEventArgs e) { var mItem = (MenuItem)sender; Firm_Info.Navigate(mItem.Tag.ToString()); } private void InfoButton_Click(object sender, RoutedEventArgs e) { var bItem = (Button)sender; Firm_Info.Navigate(bItem.Tag.ToString()); } // Tab 3 /// These are all PDFs, if we load PDFs and webpages in the same tabs we lose the scroll point of the PDF private void StandardsMenu_Click(object sender, RoutedEventArgs e) { var mItem = (MenuItem)sender; Standards.Navigate(mItem.Tag.ToString()); } private void StandardsBtn_Click(object sender, RoutedEventArgs e) { var bItem = (Button)sender; Standards.Navigate(bItem.Tag.ToString()); } //These catch nasty popups void WebBrowser_Navigated( object sender, NavigationEventArgs e) { HideJsScriptErrors((WebBrowser)sender); } public void HideJsScriptErrors(WebBrowser WebP) { // IWebBrowser2 interface // Exposes methods that are implemented by the // WebBrowser control // Searches for the specified field, using the // specified binding constraints. FieldInfo fld = typeof(WebBrowser).GetField( "_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic); if (null != fld) { object obj = fld.GetValue(WebP); if (null != obj) { obj.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, obj, new object[] { true }); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Master.Contract; namespace Master.Contract { public class Port:IContract { public Port() { } public string PortCode { get; set; } public string PortName { get; set; } public string CountryCode { get; set; } public string CountryName { get; set; } public Int16 PortType { get; set; } public string PortTypeDescription { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public string ISOCode { get; set; } public string MappingCode { get; set; } public bool IsActive { get; set; } public string CreatedBy { get; set; } public DateTime CreatedOn { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedOn { get; set; } } }
using System; using Foundation; using WebKit; using UIKit; using Xam.Plugin.WebView.Abstractions; using Xamarin.Forms; namespace Xam.Plugin.WebView.iOS { public class FormsNavigationDelegate : WKNavigationDelegate { readonly WeakReference<FormsWebViewRenderer> Reference; public FormsNavigationDelegate(FormsWebViewRenderer renderer) { Reference = new WeakReference<FormsWebViewRenderer>(renderer); } public bool AttemptOpenCustomUrlScheme(NSUrl url) { var app = UIApplication.SharedApplication; if (app.CanOpenUrl(url)) return app.OpenUrl(url); return false; } public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer)) { completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null); return; } if (renderer?.Element == null) { completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null); return; } if ((!string.IsNullOrWhiteSpace(renderer.Element.Username)) && (!string.IsNullOrWhiteSpace(renderer.Element.Password))) { if (challenge.PreviousFailureCount > 5) //cancel autorization in case of 5 failing requests { completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null); return; } completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(renderer.Element.Username, renderer.Element.Password, NSUrlCredentialPersistence.ForSession)); } else { completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null); } } [Export("webView:decidePolicyForNavigationAction:decisionHandler:")] public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler) { if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer)) return; if (renderer.Element == null) return; System.Console.WriteLine("DecidePolicy" + navigationAction.Request.Url?.Host); System.Console.WriteLine("DecidePolicy" + renderer.Element.BaseUrl); System.Console.WriteLine($"DecidePolicy {navigationAction.Request.Url.Host} {navigationAction.Request is NSMutableUrlRequest}"); #if DEBUG if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { webView.Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookies((NSHttpCookie[] obj) => { System.Diagnostics.Debug.WriteLine("*** DecidePolicy webView.Configuration.WebsiteDataStore"); for (var i = 0; i < obj.Length; i++) { var nsCookie = obj[i]; var domain = nsCookie.Domain; System.Diagnostics.Debug.WriteLine($"Domain={nsCookie.Domain}; Name={nsCookie.Name}; Value={nsCookie.Value};"); } }); } #endif if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { var headers = navigationAction.Request.Headers as NSMutableDictionary; var cookieDictionary = NSHttpCookie.RequestHeaderFieldsWithCookies(NSHttpCookieStorage.SharedStorage.Cookies); foreach (var item in cookieDictionary) { headers.SetValueForKey(item.Value, new NSString(item.Key.ToString())); } } // If navigation target frame is null, this can mean that the link contains target="_blank". Start loadrequest to perform the navigation if (navigationAction.TargetFrame == null) { webView.LoadRequest(navigationAction.Request); decisionHandler(WKNavigationActionPolicy.Cancel); return; } // If the navigation event originates from another frame than main (iframe?) it's not a navigation event we care about if (!navigationAction.TargetFrame.MainFrame) { decisionHandler(WKNavigationActionPolicy.Allow); return; } var response = renderer.Element.HandleNavigationStartRequest(navigationAction.Request.Url.ToString()); var url = navigationAction.Request.Url.ToString(); if (url == "about:blank") { decisionHandler(WKNavigationActionPolicy.Allow); } else { if (response.Cancel || response.OffloadOntoDevice) { if (response.OffloadOntoDevice) AttemptOpenCustomUrlScheme(navigationAction.Request.Url); decisionHandler(WKNavigationActionPolicy.Cancel); } else { //_headerIsSet = false; decisionHandler(WKNavigationActionPolicy.Allow); renderer.Element.Navigating = true; } } } public override void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action<WKNavigationResponsePolicy> decisionHandler) { if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer)) return; if (renderer.Element == null) return; System.Console.WriteLine("DecidePolicy Response" + renderer.Element.BaseUrl); if (navigationResponse.Response is NSHttpUrlResponse) { var code = ((NSHttpUrlResponse)navigationResponse.Response).StatusCode; if (code >= 400) { renderer.Element.Navigating = false; renderer.Element.HandleNavigationError((int)code); decisionHandler(WKNavigationResponsePolicy.Cancel); return; } } decisionHandler(WKNavigationResponsePolicy.Allow); } [Export("webView:didFinishNavigation:")] public async override void DidFinishNavigation(WKWebView webView, WKNavigation navigation) { if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer)) return; if (renderer.Element == null) return; renderer.Element.HandleNavigationCompleted(webView.Url.ToString()); await renderer.OnJavascriptInjectionRequest(FormsWebView.InjectedFunction); if (renderer.Element.EnableGlobalCallbacks) foreach (var function in FormsWebView.GlobalRegisteredCallbacks) await renderer.OnJavascriptInjectionRequest(FormsWebView.GenerateFunctionScript(function.Key)); foreach (var function in renderer.Element.LocalRegisteredCallbacks) await renderer.OnJavascriptInjectionRequest(FormsWebView.GenerateFunctionScript(function.Key)); renderer.Element.CanGoBack = webView.CanGoBack; renderer.Element.CanGoForward = webView.CanGoForward; renderer.Element.Navigating = false; renderer.Element.HandleContentLoaded(); } [Foundation.Export("webView:didStartProvisionalNavigation:")] [ObjCRuntime.BindingImpl(ObjCRuntime.BindingImplOptions.GeneratedCode | ObjCRuntime.BindingImplOptions.Optimizable)] public override void DidStartProvisionalNavigation(WKWebView webView, WKNavigation navigation) { if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer)) return; if (renderer.Element == null) return; Device.BeginInvokeOnMainThread(() => { renderer.Element.CurrentUrl = webView.Url.ToString(); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class EasyRestarter : MonoBehaviour { private float timeRestartButtonHasBeenPressed = 0; public float timeNeeded = 3.0f; private void Update() { if (Input.GetKey(KeyCode.Escape)) { timeRestartButtonHasBeenPressed += Time.deltaTime; } else if (Input.GetKeyUp(KeyCode.Escape)) { timeRestartButtonHasBeenPressed = 0; } if (timeRestartButtonHasBeenPressed > timeNeeded) { //Application.LoadLevel(Application.loadedLevel); SceneManager.LoadScene(0); } } }
using CustomerManagement.Application.DTOs; using CustomerManagement.Application.Interfaces; using CustomerManagement.Infrastructure.CrossCuting.Extensions; using System.Net.Http; using System.Threading.Tasks; namespace CustomerManagement.Application.Services { public class CepService : ICepService { private readonly HttpClient _httpClient; private string _uri => "https://viacep.com.br/ws/{0}/json/"; public CepService() { _httpClient = new HttpClient(); } public async Task<CepDTO.Retorno> ObterCep(CepDTO.Envio dto) { var response = await _httpClient.GetAsync(string.Format(_uri, dto.Cep)); var retornoJson = response.Content.ReadAsStringAsync().Result; var endereco = JsonExtensions.Deserialize<CepDTO.Retorno>(retornoJson); return endereco; } } }
using UnityEngine; using System.Collections; public class GeneradorTuberias : MonoBehaviour { public GameObject prefabTuberias; public float tiempoEntreTuberias = 3.5f; void Start () { InvokeRepeating("CrearTuberia",0,tiempoEntreTuberias); } void Update () { if(GameManager.gameOver){ CancelInvoke("CrearTuberia"); } } void CrearTuberia(){ GameObject nuevaTuberia = Instantiate<GameObject>(prefabTuberias); nuevaTuberia.transform.position = this.transform.position; nuevaTuberia.transform.position += Vector3.up * Random.Range(-2,3); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using FantasyStore.Domain; using FantasyStore.Infrastructure; using FantasyStore.WebApp.Extensions; using FantasyStore.WebApp.ViewModels; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; namespace FantasyStore.WebApp.Controllers { [AllowAnonymous] public class AuthController : Controller { private readonly UnitOfWork _unitOfWork = new UnitOfWork(); private readonly UserManager<User> _userManager; public AuthController() : this(Startup.UserManagerFactory.Invoke()) { } public AuthController(UserManager<User> userManager) { _userManager = userManager; } private User CurrentUser { get { return _userManager.FindById(User.Identity.GetUserId()); } } protected override void Dispose(bool disposing) { if (disposing && _userManager != null) { _userManager.Dispose(); } base.Dispose(disposing); } // // GET: /Auth/ public ActionResult LogIn() { return View(); } private async Task SignIn(User user) { var identity = await _userManager.CreateIdentityAsync( user, DefaultAuthenticationTypes.ApplicationCookie); GetAuthenticationManager().SignIn(identity); } public async Task<ActionResult> Register() { return View(); } private string DisplaySuccessMessage(string message) { return string.Format("<div class='alert alert-success'>{0}</div>", message); } [HttpPost] public async Task<ActionResult> MyAccount(UpdateModel model) { if (!ModelState.IsValid) { return View(); } CurrentUser.FirstName = model.FirstName; CurrentUser.LastName = model.LastName; CurrentUser.Document = model.Document; CurrentUser.BirthDate = Convert.ToDateTime(model.BirthDate, CultureInfo.GetCultureInfo("pt-BR")); CurrentUser.UserName = model.Email; await _userManager.UpdateAsync(CurrentUser); ViewBag.Confirmation = DisplaySuccessMessage("Dados atualizados com sucesso"); ModelState.Clear(); return View(); } [HttpGet] public ActionResult MyAccount() { if (CurrentUser == null) { return Redirect("/Home"); } var model = CurrentUser.ToViewModel(); ViewBag.FirstName = model.FirstName; ViewBag.LastName = model.LastName; ViewBag.Document = model.Document; ViewBag.Email = model.Email; ViewBag.BirthDate = model.BirthDate; return View(); } [HttpGet] public ActionResult CreateAddress() { return View(); } [HttpPost] public ActionResult CreateAddress(AddressViewModel model) { var userId = User.Identity.GetUserId(); if (string.IsNullOrWhiteSpace(userId)) { return RedirectToAction("Login", "Auth"); } var user = _unitOfWork.Users.Get(userId); var address = new Address { Cep = model.Cep, City = model.City, Complement = model.Complement, HouseNumber = model.HouseNumber, IsDeliveryAddress = true, State = model.State, Street = model.Street, User = user }; _unitOfWork.Addresses.Insert(address); _unitOfWork.Commit(); ModelState.Clear(); @ViewBag.Message = @"<div class='alert alert-success'>Endereço cadastrado com sucesso. <strong><a href='/Checkout/Cart'>Voltar ao carrinho de compras</a></strong></div>"; return View(); } [HttpPost] public async Task<ActionResult> Register(RegisterModel model) { if (!ModelState.IsValid) { return View(); } DateTime? birthDate; try { birthDate = DateTime.Parse(model.BirthDate, CultureInfo.GetCultureInfo("pt-BR")); } catch (Exception ex) { return Json(ex); } var user = new User { FirstName = model.FirstName, LastName = model.LastName, UserName = model.Email, Document = model.Document, BirthDate = birthDate }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignIn(user); return RedirectToAction("index", "home"); } foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return View(); } private IAuthenticationManager GetAuthenticationManager() { var ctx = Request.GetOwinContext(); return ctx.Authentication; } [HttpPost] public async Task<ActionResult> LogIn(LogInModel model) { if (!ModelState.IsValid) { return View(); } var user = await _userManager.FindAsync(model.Email, model.Password); if (user != null) { var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); GetAuthenticationManager().SignIn(identity); return Redirect(GetRedirectUrl(model.ReturnUrl)); } // user authN failed ModelState.AddModelError("", "Invalid email or password"); return View(); } private string GetRedirectUrl(string returnUrl) { if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl)) { return Url.Action("index", "home"); } return returnUrl; } public ActionResult LogOut() { var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; var session = Session["CartId"]; if (session != null) { Session.Clear(); } authManager.SignOut("ApplicationCookie"); return RedirectToAction("index", "home"); } } }
using UnityEngine; using System.Collections; public class PlayerID : MonoBehaviour { public int id = 1; // Use this for initialization void Awake () { gameObject.BroadcastMessage ("setId", id); } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using ValidationExperiments.Core.Entities; using ValidationExperiments.Core.Interfaces; namespace ValidationExperiments.Persistence { public partial class AppDbContext : DbContext, IAppDbContext { private readonly IConfiguration configuration; DbSet<AuthorCourseLesson> AuthorCourseLessons { get; set; } public AppDbContext(IConfiguration configuration) { this.configuration = configuration; this.Database.EnsureDeleted(); this.Database.EnsureCreated(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(this.configuration.GetConnectionString("DefaultConnection")); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<AuthorCourseLesson>() .HasKey(p => new { p.AuthorId, p.CourseLessonId }); modelBuilder.Entity<AuthorCourseLesson>() .HasOne(p => p.Author) .WithMany(p => p.CourseLessons) .HasForeignKey(p => p.AuthorId); modelBuilder.Entity<AuthorCourseLesson>() .HasOne(p => p.CourseLesson) .WithMany(p => p.Authors) .HasForeignKey(p => p.CourseLessonId); } } }
using System; using FluentAssertions; using NUnit.Framework; using Simplist.Cqrs.Core; namespace Simplist.Core { [TestFixture] public class SmokeTest { private Burner _burner; [SetUp] public void Setup() { _burner = new Burner(); } [Test] public void Smoke_test_should_work() { var result = _burner.Smoke("test"); result.Should().Be("test smoked"); } [Test] public void Smoke_should_validate_for_null() { _burner.Invoking(_ => _.Smoke(null)) .ShouldThrow<ArgumentNullException>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace bitirme.Models { public class sehir { [Key] public int sehirID { get; set; } public string sehirAd { get; set; } public string sehirresim { get; set; } [NotMapped] public HttpPostedFileBase res { get; set; } public string sehiraciklama { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; class SemanticException : Exception { string m; public SemanticException (string message) { m = message; } public override string ToString() { return m; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xadrez.TabuleiroEntities; namespace Xadrez.PecasXadrez { class Peao : Peca { public Peao(Tabuleiro tabuleiro, Cor cor, PartidaXadrez partida) : base(tabuleiro, cor) { this.Partida = partida; } private PartidaXadrez Partida; public override string ToString() { return "P "; } private bool ExisteInimigo(Posicao posicao) { Peca peca = TabuleiroPeca.RetornarPeca(posicao); return peca != null && peca.CorPeca != CorPeca; } private bool PosicaoLivre(Posicao posicao) { return TabuleiroPeca.RetornarPeca(posicao) == null; } public override bool[,] MovimentosPossiveis() { bool[,] matriz = new bool[TabuleiroPeca.Linhas, TabuleiroPeca.Colunas]; Posicao posicao = new Posicao(0, 0); if (CorPeca == Cor.Branco) { posicao.DefinirValores(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna); if (TabuleiroPeca.PosicaoValida(posicao) && PosicaoLivre(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha - 2, PosicaoPeca.Coluna); Posicao p2 = new Posicao(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna); if (TabuleiroPeca.PosicaoValida(p2) && PosicaoLivre(p2) && TabuleiroPeca.PosicaoValida(posicao) && PosicaoLivre(posicao) && QuantidadeMovimentos == 0) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna - 1); if (TabuleiroPeca.PosicaoValida(posicao) && ExisteInimigo(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha - 1, PosicaoPeca.Coluna + 1); if (TabuleiroPeca.PosicaoValida(posicao) && ExisteInimigo(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; //en passant if(posicao.Linha == 3) { Posicao PecaEsquerda = new Posicao(posicao.Linha, posicao.Coluna - 1); if (TabuleiroPeca.PosicaoValida(PecaEsquerda) && ExisteInimigo(PecaEsquerda) && TabuleiroPeca.RetornarPeca(PecaEsquerda) == Partida.VulneravelEnPassant) matriz[PecaEsquerda.Linha - 1, PecaEsquerda.Coluna] = true; Posicao PecaDireita = new Posicao(posicao.Linha, posicao.Coluna + 1); if (TabuleiroPeca.PosicaoValida(PecaDireita) && ExisteInimigo(PecaDireita) && TabuleiroPeca.RetornarPeca(PecaDireita) == Partida.VulneravelEnPassant) matriz[PecaDireita.Linha - 1, PecaDireita.Coluna] = true; } } else { posicao.DefinirValores(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna); if (TabuleiroPeca.PosicaoValida(posicao) && PosicaoLivre(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha + 2, PosicaoPeca.Coluna); Posicao p2 = new Posicao(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna); if (TabuleiroPeca.PosicaoValida(p2) && PosicaoLivre(p2) && TabuleiroPeca.PosicaoValida(posicao) && PosicaoLivre(posicao) && QuantidadeMovimentos == 0) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna - 1); if (TabuleiroPeca.PosicaoValida(posicao) && ExisteInimigo(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; posicao.DefinirValores(PosicaoPeca.Linha + 1, PosicaoPeca.Coluna + 1); if (TabuleiroPeca.PosicaoValida(posicao) && ExisteInimigo(posicao)) matriz[posicao.Linha, posicao.Coluna] = true; if (posicao.Linha == 4) { Posicao PecaEsquerda = new Posicao(posicao.Linha, posicao.Coluna - 1); if (TabuleiroPeca.PosicaoValida(PecaEsquerda) && ExisteInimigo(PecaEsquerda) && TabuleiroPeca.RetornarPeca(PecaEsquerda) == Partida.VulneravelEnPassant) matriz[PecaEsquerda.Linha + 1, PecaEsquerda.Coluna] = true; Posicao PecaDireita = new Posicao(posicao.Linha, posicao.Coluna + 1); if (TabuleiroPeca.PosicaoValida(PecaDireita) && ExisteInimigo(PecaDireita) && TabuleiroPeca.RetornarPeca(PecaDireita) == Partida.VulneravelEnPassant) matriz[PecaDireita.Linha + 1, PecaDireita.Coluna] = true; } } return matriz; } } }
using System; namespace Faust.PetShopApp.WebApi.Dto { public class PetDto { public int Id { get; set; } public string Name { get; set; } public String PreviousOwnerName { get; set; } } }
using System.Collections.Generic; using DnDPlayerCompanion.Enums; namespace DnDPlayerCompanion { public abstract class BaseRace { public Dictionary<AbilityEnum, int> AbilityMods { get; set; } public Size Size { get; set; } public int Speed { get; set; } public List<Language> Languages { get; set; } public Dictionary<string, string> RaceTraits { get; set; } } }