text
stringlengths
13
6.01M
 using System.Text.Json; namespace RecipeLibrary.Configuration { public class SettingsConfig { // get and set the logging object // it will be based on the Fields.Logging class public LogSettings Logging { get; set; } // get and set the app settings object // it wil be based on the Fields.Appsettings class public AppSettings AppSettings { get; set; } // override the ToString method for this class // it will take in the string and serialize it with indentation public override string ToString() { return JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }); } } }
using System; using System.Runtime.InteropServices; internal static partial class WINAPI { private const string KERNEL32 = nameof(KERNEL32); [DllImport(KERNEL32)] internal static extern void SetLastError(int code); [DllImport(KERNEL32)] public static extern bool SetProcessWorkingSetSize(IntPtr hProcess, IntPtr min, IntPtr max); public static bool SetProcessWorkingSetSize(IntPtr hProcess, int min, int max) { return SetProcessWorkingSetSize(hProcess, (IntPtr)min, (IntPtr)max); } public static bool ReleasePages(IntPtr hProcess) { return SetProcessWorkingSetSize(hProcess, -1, -1); } [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool SetDllDirectory(string path); }
using System; using UnityEngine; namespace DefaultNamespace { public class Footstep : MonoBehaviour { private CharacterController charControl; private AudioSource audio; private void Start() { charControl = GetComponent<CharacterController>(); audio = GetComponent<AudioSource>(); } private void Update() { if (charControl.velocity.magnitude > 2F && audio.isPlaying == false) { audio.Play(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio02 { class Program { /*Ingresar un número y mostrar: el cuadrado y el cubo del mismo. Se debe validar que el número sea mayor que cero, caso contrario, mostrar el mensaje: "ERROR. ¡Reingresar número!". Nota: Utilizar el método ‘Pow’ de la clase Math para realizar la operación.*/ static void Main(string[] args) { int numero; double numCuadrado; double numCubo; Boolean esNumero; Console.Write("Ingresar numero: "); esNumero = int.TryParse(Console.ReadLine(), out numero); while (esNumero != true || numero < 0) { Console.Write("ERROR, reingresar numero! : "); esNumero = int.TryParse(Console.ReadLine(), out numero); } numCuadrado = Math.Pow(numero, 2); numCubo = Math.Pow(numero, 3); Console.Write("Numero cuadrado: {0} Numero cubo: {1}",numCuadrado,numCubo); Console.Read(); } } }
namespace SearchScraper.Contracts { public interface IWebClientFactory { IWebClient Create(); } }
using System.Data; using TLF.Business.WSBiz; using TLF.Framework.Config; namespace TLF.Framework.Utility { /// <summary> /// Application에서 사용할 Code(Database : SystemCode) Util Method를 정의합니다. /// </summary> /// <remarks> /// 2009-01-12 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public class AppCodeUtil { /////////////////////////////////////////////////////////////////////////////////////////////// // 전체 시스템 관련 /////////////////////////////////////////////////////////////////////////////////////////////// #region :: GetCodeMaster :: Code Master를 가져옵니다. /// <summary> /// Code Master를 가져옵니다. /// </summary> /// <param name="pCodeValue">대구분 코드</param> /// <param name="codeValue">소구분 코드</param> /// <returns></returns> /// <remarks> /// 2009-01-12 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public static DataTable GetCodeMaster(string pCodeValue, string codeValue) { DataTable dt = null; using (WsBiz wb = new WsBiz(AppConfig.DEFAULTDB)) { string query = "dbo.CodeMaster_Get"; string[] paramList = new string[] { "@PCodeValue", "@CodeValue" }; object[] valueList = new object[] { pCodeValue, codeValue }; dt = wb.NTx_ExecuteDataSet(AppConfig.DEFAULTDB, query, AppConfig.COMMANDSP, paramList, valueList).Tables[0]; } return dt; } #endregion #region :: GetCodeMaster :: Code Master를 가져옵니다. /// <summary> /// Code Master를 가져옵니다. /// </summary> /// <param name="pCodeValue">대구분 코드</param> /// <param name="codeValue">소구분 코드</param> /// <param name="bDispCode">코드표시여부</param> /// <returns></returns> /// <remarks> /// 2009-01-12 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public static DataTable GetCodeMaster(string pCodeValue, string codeValue,bool bDispCode) { DataTable dt = null; using (WsBiz wb = new WsBiz(AppConfig.DEFAULTDB)) { string query = "dbo.CodeMaster_Get"; /* string[] paramList = new string[] { "@PCodeValue", "@CodeValue", "@DispCode" }; object[] valueList = new object[] { pCodeValue, codeValue, bDispCode }; */ string[] paramList = new string[] { "@PCodeValue", "@CodeValue", }; object[] valueList = new object[] { pCodeValue, codeValue, }; dt = wb.NTx_ExecuteDataSet(AppConfig.DEFAULTDB, query, AppConfig.COMMANDSP, paramList, valueList).Tables[0]; } return dt; } #endregion #region :: GetInspCode :: 검사항목코드를 가져옵니다. /// <summary> /// Code Master를 가져옵니다. /// </summary> /// <param name="pCodeValue">대구분 코드</param> /// <param name="codeValue">소구분 코드</param> /// <returns></returns> /// <remarks> /// 2009-01-12 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public static DataTable GetInspCode(string pCodeValue, string codeValue) { DataTable dt = null; using (WsBiz wb = new WsBiz(AppConfig.MESDB)) { string query = "dbo.usp_MdInspCode_CRUD"; string[] paramList = new string[] { "@iOp1", "@iOp2", "@pCodeValue" }; object[] valueList = new object[] { "R", "3", pCodeValue }; dt = wb.NTx_ExecuteDataSet(AppConfig.MESDB, query, AppConfig.COMMANDSP, paramList, valueList).Tables[0]; } return dt; } #endregion #region :: GetAssemblyID :: AssemblyID 를 가져옵니다. /// <summary> /// AssemblyID 를 가져옵니다. /// </summary> /// <returns></returns> /// <remarks> /// 2009-01-12 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public static DataTable GetAssemblyID() { DataTable dt = null; using (WsBiz wb = new WsBiz(AppConfig.DEFAULTDB)) { string query = "dbo.AssemblyID_Get"; dt = wb.NTx_ExecuteDataSet(AppConfig.DEFAULTDB, query, AppConfig.COMMANDSP, null, null).Tables[0]; } return dt; } #endregion #region :: GetUserId :: 사용자 목록 자겨오기 /// <summary> /// 사용자 목록 자겨오기 /// </summary> /// <param name="VendCd"></param> /// <param name="PlantCd"></param> /// <param name="UserId"></param> /// <param name="UserNm"></param> /// <returns></returns> public static DataTable GetUserId(string VendCd, string PlantCd, string UserId, string UserNm) { DataTable dt; using (WsBiz wb = new WsBiz(AppConfig.DEFAULTDB)) { string query = string.Format("select rtrim(UserId) CodeValue,rtrim(UserId)+' : '+UserName DisplayValue from dbo.UserInfo where Vendor like '{0}%' and PlantCode like '{1}%' and UserId like '{2}%' and UserName like '{3}%' and UseFlag=1 order by UserId " , VendCd.Trim() , PlantCd.Trim() , UserId.Trim() , UserNm.Trim() ); dt = wb.NTx_ExecuteDataSet(AppConfig.DEFAULTDB, query, AppConfig.COMMANDTEXT, null, null).Tables[0]; } return dt; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Core.DataAccess; using Core.DataAccess.Entities; namespace Entities.Concrete { public class Dealer:IEntity { public int Id { get; set; } public int UserId { get; set; } public string? DealerStatusName { get; set; } public string? DealerExplanation { get; set; } } }
using UnityEngine; using System.Collections; public enum GameMode { Capture, KingOfTheHill }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { // Script must be on parent which is always active. Events aren't received on inactive objects public class PauseMenuParent : MonoBehaviour { public void OnPause() { NGUITools.SetActiveChildren(gameObject, true); } public void OnResume() { NGUITools.SetActiveChildren(gameObject, false); } void OnEnable() { Messenger.AddListener(Events.GamePaused, OnPause); Messenger.AddListener(Events.GameResumed, OnResume); } void OnDisable() { Messenger.RemoveListener(Events.GamePaused, OnPause); Messenger.RemoveListener(Events.GameResumed, OnResume); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProjectileLauncher : MonoBehaviour { [SerializeField] Laser prefab = null; [SerializeField] AudioCue audioCue; [SerializeField] FloatReference projectileSpeed = null; [SerializeField] int poolSize = 0; Pool pool; AudioSource audioSource = null; public void Awake() { pool = Pool.GetPool(prefab, poolSize); audioSource = GetComponent<AudioSource>(); } public void Fire(Vector2 startPosition) { var laser = pool.Get(startPosition, Quaternion.identity) as Laser; if (laser == null) { return; } laser.Move(); if (audioCue != null) { audioCue.Play(audioSource); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CombatTarget : MonoBehaviour { [SerializeField] float parryCooldown = 1f; [SerializeField] RandomAudioPlayer parryPlayer; [SerializeField] RandomAudioPlayer parrySuccessPlayer; //CACHE REFERENCES Mover mover; Health health; ComboSystem comboSystem; Animator animator; //PROPERTIES public ColourValue ColourWeakness { get; set; } = ColourValue.None; public bool IsParrying { get; set; } = false; public bool IsDead { get => health.IsDead; } //STATES //False when parry cooling down bool canParry = true; //Damage multiplier when hit by projectile of same colour const int weaknessDamageMultiplier = 3; float stunTimeRemaining = 0f; bool isStunned = false; private void Awake() { mover = GetComponent<Mover>(); health = GetComponent<Health>(); comboSystem = GetComponent<ComboSystem>(); animator = GetComponent<Animator>(); } private void Update() { CheckStunned(); } public bool TakeDamage(int damage, ColourValue colour, Vector3 attackPos) { if (ColourWeakness == colour) damage *= weaknessDamageMultiplier; return TakeDamage(damage, attackPos); } public bool TakeDamage(int damage, Vector3 attackPos) { if (IsParrying) //Parry successful if facing position of attack { float targetDirection = Mathf.Sign(attackPos.x - transform.position.x); if (targetDirection == mover.Direction) { if (parrySuccessPlayer != null) parrySuccessPlayer.PlayRandomAudio(); return false; //Attacker unsucessful } } health.ChangeHealth(-damage); if (!IsDead) animator.SetTrigger("damagedTrigger"); if (tag == "Player 1") comboSystem.BreakCombo(); //Combo for Cardinal broken when damaged return true; } public void Parry() { if (!canParry) return; canParry = false; animator.SetTrigger("parryTrigger"); if (parryPlayer != null) parryPlayer.PlayRandomAudio(); Invoke(nameof(ResetParry), parryCooldown); } private void ResetParry() { canParry = true; } //Stop or start stun based on stun time remaining private void CheckStunned() { if (stunTimeRemaining > 0f) //Remain stunned if stun time remaining { stunTimeRemaining -= Time.deltaTime; if (!isStunned) //set stunned state { isStunned = true; BroadcastMessage("StunUpdate", true); //Controllers notified and cannot move animator.SetTrigger("stunTrigger"); animator.SetBool("isStunned", true); } } else if (isStunned) //Go back to normal { animator.SetBool("isStunned", false); BroadcastMessage("StunUpdate", false); isStunned = false; } } //Stun by adding stun time public void Stun(float duration) { stunTimeRemaining += duration; } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PCGuardDB.DBModel { public class PCGuardDBContext : DbContext { public PCGuardDBContext() : base("name=pc_guard") { } public virtual DbSet<history> history { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("pc_guard"); base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace EdubranApi.Models { /// <summary> /// Application Model /// </summary> public class Application { [Key] public int Id { get; set; } public string motivation { get; set; } public string applicationDate { get; set; } /// <summary> /// -1 failed, 0 pending, 1 successfull /// </summary> public int applicationStatus { get; set; } // Foreign key public int projectId { get; set; } public int studentId { get; set; } public int companyId { get; set; } public Int32 applicationTime { get; set; } //Navigation property [ForeignKey("projectId")] public Project project { get; set; } [ForeignKey("studentId")] public Student student { get; set; } [ForeignKey("companyId")] public Company company { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using System.IO; using aMuleCtrl.Link; using aMuleCtrl.Database; namespace aMuleCtrl { class OutterCommandProcessor { public OutterCommandProcessor() { AMuleInterfaces.Initialize((_op, _data) => OnReceiveMessage(_op, _data)); } public void SearchMagnet(String keyword) { if ("designation".Equals(Config.GetInstance().GetSearchDataType(), StringComparison.CurrentCulture)) { List<MagnetLink> links = MagnetInterface.Search(keyword, Config.GetInstance().GetMagnetMaxCount()); Dictionary<String, List<MagnetLink>> designations = ClassifyMagnets(links); SaveMagnet(designations); } else if ("title".Equals(Config.GetInstance().GetSearchDataType(), StringComparison.CurrentCulture)) { String lastData = Config.GetInstance().GetLastCommands()[1][1]; List<MagnetLink> links = MagnetInterface.Search(keyword, Config.GetInstance().GetMagnetMaxCount()); Dictionary<String, List<MagnetLink>> designations = ClassifyMagnets(links); SaveMagnet(designations); } else if ("artist".Equals(Config.GetInstance().GetSearchDataType(), StringComparison.CurrentCulture)) { String designation = Config.GetInstance().GetCurrentDesignation(); List<MagnetLink> links = MagnetInterface.Search(keyword, Config.GetInstance().GetMagnetMaxCount()); if (links.Count > 0) { Dictionary<String, List<MagnetLink>> designations = new Dictionary<string, List<MagnetLink>>(); designations.Add(designation, links); String artist = keyword; Artist.AddArtist(artist); SaveMagnet(designations, artist); } } } public Boolean Process(String op, String data) { Config.GetInstance().AddLastCommand(op, data); AMuleInterfaces amule = AMuleInterfaces.GetInstance(); if (op.Equals("src", StringComparison.CurrentCultureIgnoreCase)) { if (Config.GetInstance().GetSearchType().Equals("urlmagnet", StringComparison.CurrentCulture)) { SearchMagnet(data); } else { if ("title".Equals(Config.GetInstance().GetSearchDataType(), StringComparison.CurrentCulture)) { Config config = Config.GetInstance(); Designation.AddDesignation(data); config.SetCurrentDesignation(data); } amule.SendMsg(op, data); } } else if (op.Equals("typ", StringComparison.CurrentCultureIgnoreCase)) { Config.GetInstance().SetSearchType(data); if (!"urlmagnet".Equals(data, StringComparison.CurrentCulture)) amule.SendMsg(op, data); } else if (op.Equals("get", StringComparison.CurrentCultureIgnoreCase)) { amule.SendMsg(op, data); } return false; } public static Dictionary<String, List<Ed2kLink>> ClassifyDesignations(List<Ed2kLink> links) { Dictionary<String, List<Ed2kLink>> ret = new Dictionary<string, List<Ed2kLink>>(); foreach (Ed2kLink link in links) { String des = LocalScanner.GetDesignation(link.FileName); if (des != null) { if (!ret.ContainsKey(des)) ret[des] = new List<Ed2kLink>(); ret[des].Add(link); } } return ret; } public void SaveEd2k(Dictionary<String, List<Ed2kLink>> data, String artist = null) { int count = 0; foreach (String designation in data.Keys) { Designation.AddDesignation(designation, null, false, artist); foreach (Ed2kLink edlink in data[designation]) if (Ed2k.AddLink(edlink.Link, designation)) ++count; } if (!Config.GetInstance().IsSilent()) Console.WriteLine(count.ToString() + " links added!"); } public static Dictionary<String, List<MagnetLink>> ClassifyMagnets(List<MagnetLink> links) { var ret = new Dictionary<string, List<MagnetLink>>(); foreach (MagnetLink link in links) { String des = LocalScanner.GetDesignation(link.GetFileName()); if (des != null) { if (!ret.ContainsKey(des)) ret[des] = new List<MagnetLink>(); ret[des].Add(link); } } return ret; } public void SaveMagnet(Dictionary<String, List<MagnetLink>> data, String artist = null) { int count = 0; foreach (String designation in data.Keys) { Designation.AddDesignation(designation, null, false, artist); foreach (MagnetLink maglink in data[designation]) if (Magnet.AddLink(maglink.GetLink(), designation)) ++count; } if (!Config.GetInstance().IsSilent()) Console.WriteLine(count.ToString() + " links added!"); } public void OnReceiveMessage(String op, String data) { Config config = Config.GetInstance(); Console.WriteLine(data); if (config.WillSaveToDb() && op.Equals("get", StringComparison.CurrentCultureIgnoreCase)) { String lastOp = config.GetLastCommands()[1][0]; String lastData = config.GetLastCommands()[1][1]; String dataType = config.GetSearchDataType(); // 根据当前搜索的数据类型, 存入数据库 if (dataType.Equals("designation", StringComparison.CurrentCulture)) { List<Ed2kLink> links = AMuleInterfaces.GetEd2kLinks(data); Dictionary<String, List<Ed2kLink>> designations = ClassifyDesignations(links); SaveEd2k(designations); } else if (dataType.Equals("artist", StringComparison.CurrentCulture)) { String artist = lastData; List<Ed2kLink> links = AMuleInterfaces.GetEd2kLinks(data); Dictionary<String, List<Ed2kLink>> designations = ClassifyDesignations(links); Artist.AddArtist(artist); SaveEd2k(designations, artist); } else if (dataType.Equals("title", StringComparison.CurrentCulture)) { String designation = config.GetCurrentDesignation(); List<Ed2kLink> links = AMuleInterfaces.GetEd2kLinks(data); Dictionary<String, List<Ed2kLink>> designations = new Dictionary<string, List<Ed2kLink>>(); designations.Add(designation, links); SaveEd2k(designations); } } } } }
using System.Collections.Generic; namespace WebApp.Model { public class UserViewModel: BaseViewModel { public List<RoleViewModel> roles { get; set; } } }
using System; namespace TNBase.Repository.UnitTests { public class DatabaseMigration { public int Version { get; set; } public string Name { get; set; } public DateTime CreateDate { get; internal set; } } }
using gufi.webAPI.Domains; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace gufi.webAPI.Interfaces { interface ISituacaoRepository { /// <summary> /// Cadastra uma nova situação /// </summary> /// <param name="situacao">Objeto Situacao que será cadastrado</param> void Cadastrar(Situacao situacao); /// <summary> /// Lista todas as situações cadastradas /// </summary> /// <returns>Uma lista de situações possíveis</returns> List<Situacao> ListarTodos(); /// <summary> /// Retorna uma situação específica /// </summary> /// <param name="id">ID da situação</param> /// <returns>Objeto Situacao que foi buscado</returns> Situacao BuscarPorId(int id); /// <summary> /// Atualiza um situação específica /// </summary> /// <param name="id">ID da situação</param> /// <param name="novaSituacao">Objeto Situacao com as novas informações</param> void Atualizar(int id, Situacao novaSituacao); /// <summary> /// Deleta uma situação específica /// </summary> /// <param name="id">ID da situação a ser deletada</param> void Deletar(int id); } }
using System; namespace RefactoringApp.MovingFeaturesBetweenObjects.HideDelegate { class HideDelegate { public void GetAccountProductsOriginal(Guid accountId) { var account = new Account(); var product = new Product(); var accountProduct = product.GetAccountProduct(account.Id); accountProduct.ShowName(); } public void GetAccountProductsHideDelegate(Guid accountId) { var account = new Account(); account.Product.ShowName(); } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using System.Reflection; using UnityEditor; using UnityEngine; namespace EnhancedEditor.Editor { /// <summary> /// Base class to derive any custom <see cref="EnhancedMethodAttribute"/> drawer from. /// <para/> /// Use this to draw additional GUI elements to represent your method in the inspector. /// </summary> public abstract class MethodDrawer { #region Internal Behaviour /// <summary> /// Creates a new instance of a <see cref="MethodDrawer"/>, /// with a specific <see cref="EnhancedMethodAttribute"/> target. /// </summary> /// <param name="_type">Drawer class type to create (must inherit from <see cref="MethodDrawer"/>).</param>. /// <param name="_serializedObject"><inheritdoc cref="SerializedObject" path="/summary"/></param> /// <param name="_attribute"><inheritdoc cref="Attribute" path="/summary"/></param> /// <param name="_methodInfo"><inheritdoc cref="MethodInfo" path="/summary"/></param>. /// <returns>Newly created <see cref="MethodDrawer"/> instance.</returns> internal static MethodDrawer CreateInstance(Type _type, SerializedObject _serializedObject, EnhancedMethodAttribute _attribute, MethodInfo _methodInfo) { MethodDrawer _drawer = Activator.CreateInstance(_type) as MethodDrawer; DisplayNameAttribute _displayNameAttribute = _methodInfo.GetCustomAttribute<DisplayNameAttribute>(false); string _name = (_displayNameAttribute != null) ? _displayNameAttribute.Label.text : ObjectNames.NicifyVariableName(_methodInfo.Name); _drawer.SerializedObject = _serializedObject; _drawer.Attribute = _attribute; _drawer.MethodInfo = _methodInfo; _drawer.Label = new GUIContent(_name, _attribute.Tooltip); _drawer.OnEnable(); return _drawer; } #endregion #region Drawer Content /// <summary> /// A <see cref="UnityEditor.SerializedObject"/> representing the object(s) being inspected. /// </summary> public SerializedObject SerializedObject { get; private set; } = null; /// <summary> /// The <see cref="EnhancedMethodAttribute"/> associated with this drawer. /// </summary> public EnhancedMethodAttribute Attribute { get; private set; } = null; /// <summary> /// The reflection <see cref="System.Reflection.MethodInfo"/> for the method this drawer represents. /// </summary> public MethodInfo MethodInfo { get; private set; } = null; /// <summary> /// Label associated with this method. /// </summary> public GUIContent Label { get; private set; } = null; // ----------------------- /// <summary> /// Called when this object is created and initialized. /// </summary> public virtual void OnEnable() { } /// <summary> /// Called before this method main GUI representation. /// <br/>Use this to draw additional GUI element(s) above, like a specific message or a feedback. /// </summary> /// <returns>True to stop drawing this method and prevent its associated GUI representation from being drawn, false otherwise.</returns> public virtual bool OnBeforeGUI() { return false; } /// <summary> /// Use this to implement this method main GUI representation. /// </summary> /// <returns>True to prevent any other GUI representations of this method from being drawn, false otherwise.</returns> public virtual bool OnGUI() { return false; } /// <summary> /// Called after this method main GUI representation. /// <br/>Use this to draw additional GUI element(s) below, like a specific message or a feedback. /// </summary> public virtual void OnAfterGUI() { } /// <summary> /// Allows you to add new item(s) to the <see cref="GenericMenu"/> displayed on this method context click. /// </summary> /// <param name="_menu">Menu to add item(s) to.</param> public virtual void OnContextMenu(GenericMenu _menu) { } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AppTechnoLinkMap.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; namespace CGI.Reflex.Core.Mappings { public class AppTechnoLinkMap : BaseEntityMap<AppTechnoLink> { public AppTechnoLinkMap() { References(x => x.Application).Cascade.None(); References(x => x.Technology).Cascade.None(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ProjectAlumni.Models; namespace ProjectAlumni.Controllers { [Authorize] [HandleError] public class UsersController : Controller { private DatabaseEntities db = new DatabaseEntities(); // GET: Users public ActionResult Index() { var aspNetUsers = db.AspNetUsers.Include(a => a.address).Include(a => a.gender); return View(aspNetUsers.ToList()); } // GET: Users/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AspNetUser aspNetUser = db.AspNetUsers.Find(id); if (aspNetUser == null) { return HttpNotFound(); } ViewBag.AddressId = new SelectList(db.addresses, "addressid", "country", aspNetUser.AdressId); ViewBag.genderid = new SelectList(db.genders, "genderid", "NAME", aspNetUser.GenderId); return View(aspNetUser); } // POST: Users/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Email,EmailConfirmed,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName,Description,DateOfBirth,ProfilePicture,AddressId,genderid,hasBeenAccepted")] AspNetUser aspNetUser, HttpPostedFileBase upload) { AspNetUser currentUser = new AspNetUser(); if (ModelState.IsValid) { byte[] profilePicture = null; if (upload != null && upload.ContentLength > 0) { using (var reader = new System.IO.BinaryReader(upload.InputStream)) { profilePicture = reader.ReadBytes(upload.ContentLength); } } currentUser = db.AspNetUsers.FirstOrDefault(p => p.Id == aspNetUser.Id); if (currentUser == null) return HttpNotFound(); if (profilePicture != null) { currentUser.ProfilePicture = profilePicture; } if (aspNetUser.Email != String.Empty && aspNetUser.Email != "" && aspNetUser.Email != null) { currentUser.Email = aspNetUser.Email; } if (aspNetUser.EmailConfirmed != false) { currentUser.EmailConfirmed = aspNetUser.EmailConfirmed; } if (aspNetUser.PhoneNumber != String.Empty && aspNetUser.PhoneNumber != "" && aspNetUser.PhoneNumber != null) { currentUser.PhoneNumber = aspNetUser.PhoneNumber; } if (aspNetUser.PhoneNumber != String.Empty && aspNetUser.PhoneNumber != "" && aspNetUser.PhoneNumber != null) { currentUser.PhoneNumber = aspNetUser.PhoneNumber; } if (aspNetUser.LockoutEnabled != false) { currentUser.LockoutEnabled = aspNetUser.LockoutEnabled; } if (aspNetUser.Lastname != String.Empty && aspNetUser.Lastname != "" && aspNetUser.Lastname != null) { currentUser.Lastname = aspNetUser.Lastname; } if (aspNetUser.UserName != String.Empty && aspNetUser.UserName != "" && aspNetUser.UserName != null) { currentUser.UserName = aspNetUser.UserName; } if (aspNetUser.DateOfBirth != null) { currentUser.DateOfBirth = aspNetUser.DateOfBirth; } if (aspNetUser.Description != String.Empty && aspNetUser.Description != "" && aspNetUser.Description != null) { currentUser.Description = aspNetUser.Description; } if (aspNetUser.GraduationYear != 0 && aspNetUser.GraduationYear != null) { currentUser.GraduationYear = aspNetUser.GraduationYear; } if (aspNetUser.HasBeenAccepted != false) { currentUser.HasBeenAccepted = aspNetUser.HasBeenAccepted; } if (aspNetUser.GenderId != 0 && aspNetUser.GenderId != null) { currentUser.GenderId = aspNetUser.GenderId; } db.Entry(currentUser).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return RedirectToAction("Index"); } // GET: Users/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AspNetUser aspNetUser = db.AspNetUsers.Find(id); if (aspNetUser == null) { return HttpNotFound(); } return View(aspNetUser); } // POST: Users/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { AspNetUser aspNetUser = db.AspNetUsers.Find(id); db.AspNetUsers.Remove(aspNetUser); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutoTagging : MonoBehaviour { // Start is called before the first frame update void Start() { this.tag = transform.parent.tag; this.gameObject.layer = transform.parent.gameObject.layer; } }
/* * Copyright 2014 Technische Universität Darmstadt * * 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.Windows; using KaVE.VS.FeedbackGenerator.UserControls.ValueConverter; using NUnit.Framework; namespace KaVE.VS.FeedbackGenerator.Tests.UserControls.ValueConverter { internal class StringToVisibilityConverterTest { private StringToVisibilityConverter _sut; [SetUp] public void Setup() { _sut = new StringToVisibilityConverter(); } [Test] public void Null() { Assert.AreEqual(Visibility.Collapsed, Convert(null)); } [Test] public void Empty() { Assert.AreEqual(Visibility.Collapsed, Convert("")); } [Test] public void SomeString() { Assert.AreEqual(Visibility.Visible, Convert("x")); } [Test] public void SomethingElse() { Assert.AreEqual(Visibility.Collapsed, Convert(1)); } [Test, ExpectedException(typeof (NotImplementedException))] public void ConvertBackThrows() { _sut.ConvertBack(Visibility.Collapsed, null, null, null); } private object Convert(object o) { return _sut.Convert(o, null, null, null); } } }
using System; using System.Collections.Immutable; using IronPython.Compiler.Ast; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Py2Cs.CodeGraphs; namespace Py2Cs.Translators { public partial class Translator { public CompilationUnitSyntax Translate(PythonAst ast) { var compilationUnit = SyntaxFactory.CompilationUnit(); var state = TranslatorState.Empty; (var children, _) = TranslateBlock_Members(ast.Body, state); if (children.IsError) { return compilationUnit.WithTrailingTrivia(children.Errors); } foreach (var child in children.Syntax) { switch (child) { case MemberDeclarationSyntax member: compilationUnit = compilationUnit.AddMembers(member); break; case UsingDirectiveSyntax usingDirective: compilationUnit = compilationUnit.AddUsings(usingDirective); break; default: var comment = SyntaxFactory.Comment($"// py2cs: Unexpected child statement ({child.GetType()})"); compilationUnit = compilationUnit.WithTrailingTrivia(comment); break; } } return compilationUnit; } public MethodDeclarationSyntax TranslateFunctionDefinition(PythonNode node) { if (node.NodeType != PythonNodeType.Function) throw new ArgumentException(); var function = (FunctionDefinition)node.Statement; var returnType = SyntaxFactory.ParseTypeName("void"); var methodDeclaration = SyntaxFactory.MethodDeclaration(returnType, function.Name) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithBody(SyntaxFactory.Block()); foreach (Parameter pyParameter in function.Parameters) { var parameterSyntax = SyntaxFactory.Parameter(SyntaxFactory.Identifier(pyParameter.Name)) .WithType(SyntaxFactory.ParseTypeName("object")); if (pyParameter.DefaultValue != null) { var parameterExpression = TranslateExpression(pyParameter.DefaultValue, node.State); if (parameterExpression.IsError) parameterSyntax = parameterSyntax.WithTrailingTrivia(parameterExpression.Errors); else parameterSyntax = parameterSyntax.WithDefault(SyntaxFactory.EqualsValueClause(parameterExpression.Syntax)); } methodDeclaration = methodDeclaration.AddParameterListParameters(parameterSyntax); } return methodDeclaration; } public BlockSyntax TranslateFunctionBody(PythonNode node) { if (node.NodeType != PythonNodeType.Function) throw new ArgumentException(); var function = (FunctionDefinition)node.Statement; var body = TranslateBlock_Block(function.Body, node.State); return body; } public BlockSyntax TranslateFunctionBody(PythonFunction function, TranslatorState state) { var body = TranslateBlock_Block(function.PythonDefinition.Body, state); return body; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project_1.Model { class PrimaryKey { string PKName; public string PKName1 { get { return PKName; } set { PKName = value; } } string PkOfTable; internal string PkOfTable1 { get { return PkOfTable; } set { PkOfTable = value; } } List<string> listColumnsPK; internal List<string> ListColumnsPK { get { return listColumnsPK; } set { listColumnsPK = value; } } public PrimaryKey() { listColumnsPK = new List<string>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fairmas.PickupTracking.Shared.ViewModels { public abstract class SettingsViewModelBase : ViewModelBase { private SettingsViewModel _settingsViewModel; public SettingsViewModel SettingsViewModel { get { return _settingsViewModel; } private set { Set(ref _settingsViewModel, value, nameof(SettingsViewModel)); } } public SettingsViewModelBase(SettingsViewModel settingsViewModel) { SettingsViewModel = settingsViewModel; } } }
using System; using System.Collections.Generic; using FairyGUI; using UnityEngine; public class DragManager { private GLoader _agent; private object _sourceData; public const string DROP_EVENT = "__drop"; private static DragManager _inst; public static DragManager inst { get { if (_inst == null) _inst = new DragManager(); return _inst; } } public DragManager() { _agent = new GLoader(); _agent.touchable = false;//important _agent.draggable = true; _agent.SetSize(88, 88); _agent.alwaysOnTop = int.MaxValue; _agent.onDragEnd.Add(__dragEnd); } public GObject dragAgent { get { return _agent; } } public bool dragging { get { return _agent.parent != null; } } public void StartDrag(GObject source, string icon, object sourceData, int touchPointID = -1) { if (_agent.parent != null) return; _sourceData = sourceData; _agent.url = icon; GRoot.inst.AddChild(_agent); Vector2 pt = source.LocalToGlobal(new Vector2(0, 0)); _agent.SetXY(pt.x, pt.y); _agent.StartDrag(null, touchPointID); } public void Cancel() { if (_agent.parent != null) { _agent.StopDrag(); GRoot.inst.RemoveChild(_agent); _sourceData = null; } } private void __dragEnd(EventContext evt) { if (_agent.parent == null) //cancelled return; GRoot.inst.RemoveChild(_agent); object sourceData = _sourceData; _sourceData = null; GObject obj = GRoot.inst.objectUnderMouse; while (obj != null) { EventListener listener = obj.GetEventListener(DROP_EVENT); if (listener != null) { obj.RequestFocus(); listener.Call(sourceData); return; } obj = obj.parent; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TestSimpleRNG; using VectorExtension; using System.Text.RegularExpressions; using System.Linq; public class HeightmapProceduralEditor : MonoBehaviour { public int streamSEED = 99; private System.Random streamsRNG; public IntRange streamSourcesPerPatch = new IntRange(1, 5); public float streamDepth = 0.0005f; public int streamLength = 100; public bool displayStreams = false; List<List<Vector3>> streamPaths; float[,] streamDepressions; public int groundNoiseSeed = 0; public float groundFrq = 12f; public float groundNoiseScale = 0.001f; public float smoothIntensity = 0.2f; public int heightMapSize; Vector3 terrainSize; public float[,] originalHeights; public TerrainManager terrainManager; public AlphamapProceduralEditor alphamapProceduralEditor; Terrain actTerrain; TerrainData terrainData; TerrainCollider terrainCollider; PerlinNoise groundNoise; void Awake() { actTerrain = Terrain.activeTerrain; terrainData = actTerrain.terrainData; terrainCollider = actTerrain.GetComponent<TerrainCollider>(); heightMapSize = terrainData.heightmapWidth; terrainSize = terrainData.size; streamPaths = new List<List<Vector3>>(); originalHeights = terrainData.GetHeights(0, 0, heightMapSize, heightMapSize); streamDepressions = new float[originalHeights.GetLength(0),originalHeights.GetLength(1)]; } public void SaveHeightmap() { if (terrainData.heightmapResolution != 2049) { Debug.LogWarning("Please only save heightmaps corresponding to a 2049x2049 resolution."); return; } Serialization.SaveRaster2D("heightmap", terrainData.GetHeights(0, 0, heightMapSize, heightMapSize)); Serialization.SaveRaster2D("streams", streamDepressions); } #region heightmap modifications public void AddStreams() { //ResetTerrain(); Vector2 patchSize = terrainManager.patchSize; // set up a random number generator dependent on the global RNG and the patch coordinates streamsRNG = new System.Random(streamSEED); // iterate for every patch (c. 100x100), including patches outside the grid for (int x = 0; x < (int)(terrainSize.x / patchSize.x); x++) { for (int z = 0; z < (int)(terrainSize.z / patchSize.y); z++) { // get random number of stream sources //int streamSources = Random.Range(streamSourcesPerPatch.min, streamSourcesPerPatch.max); // get number of stream sources depending on hydro (values between 0-8.6) int streamSources = streamSourcesPerPatch.min + Mathf.RoundToInt(streamSourcesPerPatch.range * streamsRNG.Next()); for (int i = 0; i < streamSources; i++) { // get a random point within a the patch Vector3 sourcePosition = terrainManager.GetRandomPointInPatchSurface(new IntVector2(x, z), streamsRNG); // Create a stream AddStream(sourcePosition); } } } //Debug.Log(originalHeights.Cast<float>().SequenceEqual<float>(terrainData.GetHeights(0, 0, heightMapSize, heightMapSize).Cast<float>())); } void AddStream(Vector3 sourcePosition) { // initialize path List<Vector3> streamPath = new List<Vector3>(); // add point to the path order list streamPath.Add(sourcePosition); int i = 0; while (i < streamLength) { Vector3 lastPoint = streamPath[streamPath.Count - 1]; Vector3 nextPoint = GetDownstreamPoint(lastPoint); // check if there is no neighbour lower than this point if (nextPoint != lastPoint) { // add point to the path order list streamPath.Add(nextPoint); } else { break; } i++; } if (streamPath.Count > 1) // discard fail attempts (one-point dead ends) { streamPaths.Add(streamPath); DrawPathOnTerrain(streamPath); } } private Vector3 GetDownstreamPoint(Vector3 point) { Vector3 currentPoint = point; // sample 4 neighboring points List<IntVector2> neighbors = new List<IntVector2> { IntVector2.left, IntVector2.right, IntVector2.up, IntVector2.down }; // shuffle list neighbors.Shuffle(streamsRNG); foreach (IntVector2 neighbor in neighbors) { //Vector2 unit = terrainManager.unit; // Get the neighbouring point float neighborX = point.x + (neighbor.x * terrainManager.loadedTerrainSize.x / heightMapSize);//(neighbor.x / unit.x) / heightMapSize; float neighborZ = point.z + (neighbor.y * terrainManager.loadedTerrainSize.z / heightMapSize);//(neighbor.y / unit.y) / heightMapSize; // check if the position is within limits if (neighborX < 0 || neighborX >= terrainData.size.x || neighborZ < 0 || neighborZ >= terrainData.size.z) { continue; } // get height //float neighborHeight = terrainManager.GetHeightAtPoint(neighborX, neighborZ); float neighborHeight = Terrain.activeTerrain.SampleHeight(new Vector3(neighborX, 0f, neighborZ)); //Debug.Log("current: " + currentPoint.y + " vs candidate: " + candidate.y); // Compare heights if (neighborHeight < currentPoint.y) { currentPoint = new Vector3(neighborX, neighborHeight, neighborZ); } } return currentPoint; } public void DrawPathOnTerrain(List<Vector3> path) { foreach (Vector3 point in path) { CreateCrater(point); //DeformTexture(point, modifiedAlphas, out modifiedAlphas); } } void CreateCrater(Vector3 craterWorldPosition) { // inspired by // TerrainDeformer - Demonstrating a method modifying terrain in real-time. Changing height and texture // released under MIT License // http://www.opensource.org/licenses/mit-license.php //@author Devin Reimer //@website http://blog.almostlogical.com //Copyright (c) 2010 Devin Reimer float craterSizeInMeters = terrainManager.WholeHeightmapToWorld(IntVector2.one).x; //get the heights only once keep it and reuse, precalculate as much as possible int heightMapCraterWidth = 1;//(int)(craterSizeInMeters * (heightMapSize / terrainSize.x)); int heightMapCraterLength = 1;//(int)(craterSizeInMeters * (heightMapSize / terrainSize.z)); float deformationDepth = streamDepth;//(craterSizeInMeters / 2.0f) / terrainSize.y;// deeper in highlands // bottom-lef position of the crater IntVector2 heightMapStartPos = terrainManager.WorldToWholeHeightmap(craterWorldPosition); heightMapStartPos.x = (int)(heightMapStartPos.x - (heightMapCraterWidth / 2)); heightMapStartPos.y = (int)(heightMapStartPos.y - (heightMapCraterLength / 2)); if (heightMapStartPos.x < 0 || heightMapStartPos.x + heightMapCraterWidth >= heightMapSize || heightMapStartPos.y < 0 || heightMapStartPos.y + heightMapCraterLength >= heightMapSize) { return; } float[,] craterHeights = terrainData.GetHeights(heightMapStartPos.x, heightMapStartPos.y, heightMapCraterWidth, heightMapCraterLength); float circlePosX; float circlePosY; float distanceFromCenter; float depthMultiplier; for (int i = 0; i < heightMapCraterLength; i++) { for (int j = 0; j < heightMapCraterWidth; j++) { circlePosX = (j - (heightMapCraterWidth / 2)) / (heightMapSize / terrainSize.x); circlePosY = (i - (heightMapCraterLength / 2)) / (heightMapSize / terrainSize.z); //convert back to values without skew distanceFromCenter = Mathf.Abs(Mathf.Sqrt(circlePosX * circlePosX + circlePosY * circlePosY)); if (distanceFromCenter < (craterSizeInMeters / 2.0f)) { depthMultiplier = ((craterSizeInMeters / 2.0f - distanceFromCenter) / (craterSizeInMeters / 2.0f)); depthMultiplier += 0.1f; depthMultiplier += (float)streamsRNG.NextDouble() * .1f; depthMultiplier = Mathf.Clamp(depthMultiplier, 0, 1); float depression = deformationDepth * depthMultiplier; craterHeights[i, j] = Mathf.Clamp(craterHeights[i, j] - depression, 0, 1); streamDepressions[heightMapStartPos.x + i, heightMapStartPos.y + j] = depression; } } } terrainData.SetHeights(heightMapStartPos.x, heightMapStartPos.y, craterHeights); } public void LevelTerrain(Rect area, float height) { IntVector2 bottomLeft = terrainManager.WorldToLoadedHeightmap(new Vector3(area.x, 0f, area.y)); //Debug.Log(bottomLeft); IntVector2 topRight = terrainManager.WorldToLoadedHeightmap(new Vector3(area.xMax, 0f, area.yMax)); //Debug.Log(topRight); float[,] areaHeights = terrainData.GetHeights(bottomLeft.x, bottomLeft.y, topRight.x - bottomLeft.x, topRight.y - bottomLeft.y); for (int x = 0; x < areaHeights.GetLength(0); x++) { for (int y = 0; y < areaHeights.GetLength(1); y++) { //Debug.Log(areaHeights[x, y]); areaHeights[x, y] = height / terrainData.size.y; } } terrainData.SetHeights(bottomLeft.x, bottomLeft.y, areaHeights); // update textures alphamapProceduralEditor.UpdateAlphamapArea(area); terrainCollider.terrainData = terrainData; } public void AddNoise() { // set noise seed groundNoise = new PerlinNoise(groundNoiseSeed); // get the heights of the terrain float[,] heights = terrainData.GetHeights(0, 0, heightMapSize, heightMapSize); // we set each sample of the terrain in the size to the desired height for (int x = 0; x < heightMapSize; x++) { for (int z = 0; z < heightMapSize; z++) { heights[z, x] += groundNoise.FractalNoise2D(x, z, 4, groundFrq, groundNoiseScale) + // + 0.1f; (float)SimpleRNG.GetNormal () * groundNoiseScale;/ groundNoise.FractalNoise2D(x, z, 4, Mathf.RoundToInt(0.8f * groundFrq), 0.8f * groundNoiseScale) + groundNoise.FractalNoise2D(x, z, 4, Mathf.RoundToInt(0.5f * groundFrq), 0.5f * groundNoiseScale) + groundNoise.FractalNoise2D(x, z, 4, Mathf.RoundToInt(0.2f * groundFrq), 0.2f * groundNoiseScale); } // set the new height terrainData.SetHeights(0, 0, heights); } } public void Smooth() { float[,] startHeights = terrainData.GetHeights(0, 0, heightMapSize, heightMapSize); // in case there were previous modifications on the original heights float[,] heights = terrainData.GetHeights(0, 0, heightMapSize, heightMapSize); for (int x = 0; x < heightMapSize; x++) { for (int z = 0; z < heightMapSize; z++) { float avHeight = 0; int count = 0; for (int xNeighbor = -1; xNeighbor <= 1; xNeighbor++) { for (int zNeighbor = -1; zNeighbor <= 1; zNeighbor++) { if (z + zNeighbor >= 0 && z + zNeighbor < heightMapSize && x + xNeighbor >= 0 && x + xNeighbor < heightMapSize) { float neighborHeight = startHeights[z + zNeighbor, x + xNeighbor]; avHeight += neighborHeight; count++; } } } avHeight /= count; heights[z, x] += (avHeight - startHeights[z, x]) * smoothIntensity; } // set the new height terrainData.SetHeights(0, 0, heights); } } public void ResetTerrain() { terrainData.SetHeights(0, 0, originalHeights); streamPaths = new List<List<Vector3>>(); } #endregion private void ReApplyTerrain() { float[,] heights = terrainData.GetHeights(0, 0, heightMapSize, heightMapSize); terrainData.SetHeights(0, 0, heights); } //void OnApplicationQuit() //{ // ResetTerrain(); //} void OnDrawGizmos() { Gizmos.color = Color.blue; if (displayStreams && streamPaths != null && streamPaths.Count > 0) { foreach (List<Vector3> streamPath in streamPaths) { foreach (Vector3 point in streamPath) { Gizmos.DrawSphere(point, 10); if (point != streamPath[0]) { int index = streamPath.IndexOf(point); Vector3 lastWorldPoint = streamPath[index - 1]; Gizmos.DrawLine(point, lastWorldPoint); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SincolPDV.BLL; namespace Projeto.Cadastros.produto_telas { public partial class WebForm1 : System.Web.UI.Page { Produto prod = new Produto(); Fabricante fab = new Fabricante(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { PreencherCombo(); } } private void PreencherCombo() { // Preencher a combo Fabricante fab.Descricao = ""; listFabricante.DataSource = fab.Consulta(); listFabricante.DataValueField = "Fab_Codigo"; listFabricante.DataTextField = "Fab_Descricao"; listFabricante.DataBind(); } protected void btnBuscar_Click(object sender, EventArgs e) { prod.Referencia = txtReferencia.Text; prod.Descricao = txtDescricao.Text; prod.Origem = listOrigem.SelectedValue; prod.Fabricante = Convert.ToInt32(listFabricante.SelectedValue); prod.Modelo = txtModelo.Text; prod.Marca = txtMarca.Text; GridView1.DataSource = prod.ListarProduto(); GridView1.DataBind(); } } }
namespace StackExchange.Profiling.Elasticsearch { using System; using System.Linq; using System.Text; using global::Elasticsearch.Net; using Profiling; /// <summary> /// <see cref="IElasticsearchResponse"/> handler class. /// </summary> internal static class MiniProfilerElasticsearch { /// <summary> /// Handles <see cref="IElasticsearchResponse"/> and pushes <see cref="CustomTiming"/> to current <see cref="MiniProfiler"/> session. /// </summary> /// <param name="response"><see cref="IElasticsearchResponse"/> to be handled.</param> /// <param name="profiler">Current <see cref="MiniProfiler"/> session instance.</param> internal static void HandleResponse(IElasticsearchResponse response, MiniProfiler profiler) { if (profiler == null || profiler.Head == null || response.Metrics == null) return; profiler.Head.AddCustomTiming("elasticsearch", new CustomTiming(profiler, BuildCommandString(response)) { Id = Guid.NewGuid(), DurationMilliseconds = response.Metrics.Requests.Sum(c => c.EllapsedMilliseconds), ExecuteType = response.RequestMethod, }); } /// <summary> /// Processes <see cref="IElasticsearchResponse"/> and builds command string for <see cref="CustomTiming"/> instance. /// </summary> /// <param name="response"><see cref="IElasticsearchResponse"/> to be processed.</param> /// <returns></returns> private static string BuildCommandString(IElasticsearchResponse response) { var commandTextBuilder = new StringBuilder(); var url = response.RequestUrl; // Basic request information // HTTP GET - 200 commandTextBuilder.AppendFormat("HTTP {0} - {1}\n", response.RequestMethod, response.HttpStatusCode); if (response.NumberOfRetries > 0) { commandTextBuilder.AppendFormat("Retries: {0}\n", response.NumberOfRetries); } // Request URL commandTextBuilder.AppendFormat("{0}\n\n", url); // Append query if (response.Request != null) { var request = Encoding.UTF8.GetString(response.Request); if (!String.IsNullOrWhiteSpace(request)) { commandTextBuilder.AppendFormat("Request:\n{0}\n\n", request); } } // Append response if (response.ResponseRaw != null) { var responseRaw = Encoding.UTF8.GetString(response.ResponseRaw); if (!String.IsNullOrWhiteSpace(responseRaw)) { commandTextBuilder.AppendFormat("Response:\n{0}\n\n", responseRaw); } } if (response.Success == false) { commandTextBuilder.AppendFormat("\nMessage:\n{0}", response.OriginalException.Message); if (!String.IsNullOrWhiteSpace(response.OriginalException.StackTrace)) { commandTextBuilder.AppendFormat("Stack trace:\n{0}", response.OriginalException.StackTrace); } } // Set the command string to a formatted string return commandTextBuilder.ToString(); } } }
using System; using System.Net; using System.Threading; using System.Web.Http; using System.Collections.Generic; using Proyecto1.DataRequest; using System.Data; namespace Proyecto1.Controllers { /// <summary> /// login controller class for authenticate users /// </summary> [AllowAnonymous] [RoutePrefix("api/login")] /* * Este archivo tendra el contro de todo lo relacionado con el login,peticiones de GET y POST necesarios para emplear la funcionalidad del login */ public class LoginController : ApiController { //Verifica si el usuario ingresado, correo y Contraseña coinciden con alguno guardado en la base de datos [HttpPost] [Route("verificar")] public IHttpActionResult Verificar(Usuario user) { DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_Usuario(); int x = 0; while (x < tbuser.Rows.Count) { if (user.Correo == tbuser.Rows[x]["Correo"].ToString()) { if (user.Contrasena == tbuser.Rows[x]["Contrasena"].ToString()) { return Ok("Correcto"); } else return Ok("Contraseña Incorrecta"); } x++; } return Ok("Usuario no encontrado"); } // Agrega un nuevo usuario a la base de datos [HttpPost] [Route("Registrar")] public IHttpActionResult Registrar(Usuario user) { DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_Usuario(); int x = 0; while (x < tbuser.Rows.Count) { if (user.Correo == tbuser.Rows[x]["Correo"].ToString()) { return Ok("El correo ya ha sido ingresado"); } x++; } Proyecto1.DataRequest.BDConection.Registrar_Usuario(user.Nombre,user.Apellido,user.Correo,user.Contrasena, user.Direccion,user.Continente,user.Pais); Proyecto1.DataRequest.BDConection.Agregar_Aposento(user.Correo, "dormitorio"); Proyecto1.DataRequest.BDConection.Agregar_Aposento(user.Correo, "cocina"); Proyecto1.DataRequest.BDConection.Agregar_Aposento(user.Correo, "sala"); Proyecto1.DataRequest.BDConection.Agregar_Aposento(user.Correo, "comedor"); return Ok("El usuario se ha agregado exitosamente"); } //Edita el perfil, del usuario con el correo como llave [HttpPost] [Route("EditarPerfil")] public IHttpActionResult Editar_Perfil(Usuario user) { DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_Usuario(); int x = 0; while (x < tbuser.Rows.Count) { if (user.Correo == tbuser.Rows[x]["Correo"].ToString()) { DataTable tbuser2 = Proyecto1.DataRequest.BDConection.Consultar_UsuarioPerfil(user.Correo); if (user.Nombre == null ) { user.Nombre = tbuser2.Rows[0]["Nombre"].ToString(); } if (user.Apellido == null) { user.Apellido = tbuser2.Rows[0]["Apellido"].ToString(); } if (user.Continente == null) { user.Continente = tbuser2.Rows[0]["Continente"].ToString(); } if (user.Contrasena == null) { user.Contrasena = tbuser2.Rows[0]["Contrasena"].ToString(); } if (user.Direccion == null) { user.Direccion = tbuser2.Rows[0]["Direccion"].ToString(); } if (user.Pais == null) { user.Pais = tbuser2.Rows[0]["Pais"].ToString(); } user.Correo = tbuser2.Rows[0]["Correo"].ToString(); Proyecto1.DataRequest.BDConection.Editar_Usuario(user.Nombre, user.Apellido, user.Correo, user.Contrasena, user.Direccion, user.Continente, user.Pais); return Ok("El Perfil ha sido actualizado "); } x++; } return Ok("El usuario no se ha agregado"); } // Hace una consulta sobre todos los usuarios y lo retorna en una datatable [HttpGet] [Route("ListaUsuarios")] public IHttpActionResult Lista_Usuarios() { DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_Usuario(); return Ok(tbuser); } //Elimina un usuario por medio de su llave , correo ademas edita los dispositivos y los pone en false para poder ser utilizados por otros usuarios //ademas elimina los aposentos, pedidos y final mente el usuario que estaban relacionados con el correo [HttpPost] [Route("BorrarUsuario")] public IHttpActionResult Borrar_Usuario(Usuario user) { Proyecto1.DataRequest.BDConection.Borrar_Aposento(user.Correo); DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_DispositivoCorreo(user.Correo); int x = 0; while (x < tbuser.Rows.Count) { Proyecto1.DataRequest.BDConection.Editar_Dispositivo((int)tbuser.Rows[x]["Serie"], tbuser.Rows[x]["Marca"].ToString(), (int)tbuser.Rows[x]["Consumo_Electrico"], tbuser.Rows[x]["Aposento"].ToString(), tbuser.Rows[x]["Nombre"].ToString(), tbuser.Rows[x]["Descripcion"].ToString(), (int)tbuser.Rows[x]["Tiempo_Garantia"], false, tbuser.Rows[x]["Historial_Duenos"].ToString()+","+ tbuser.Rows[x]["Dueno"].ToString(), tbuser.Rows[x]["Distribuidor"].ToString(), tbuser.Rows[x]["AgregadoPor"].ToString(), " ", (int)tbuser.Rows[x]["Precio"]); x++; } Proyecto1.DataRequest.BDConection.Borrar_Pedidos(user.Correo); Proyecto1.DataRequest.BDConection.Borrar_Usuario(user.Correo); return Ok("El usuario ha sido eliminado exitosamente"); } //Pide informacion sobre un usuario en especifico [HttpPost] [Route("PerfilUsuario")] public IHttpActionResult Perfil_Usuario(Usuario user) { DataTable tbuser = Proyecto1.DataRequest.BDConection.Consultar_UsuarioPerfil(user.Correo); return Ok(tbuser); } } }
using WebStore.BDD.Tests.Config; namespace WebStore.BDD.Tests.User { public class UserLoginPage : UserPageBase { public UserLoginPage(SeleniumHelper helper) : base(helper) { } public void ClickLoginLink() { Helper.ClickLinkText("Login"); } public void FillLoginForm(User user) { Helper.FillTextBoxById("Input_Email", user.Email); Helper.FillTextBoxById("Input_Password", user.Password); } public bool IsLogingFormFilledProperly(User user) { if (Helper.GetTextBoxValueById("Input_Email") != user.Email) return false; if (Helper.GetTextBoxValueById("Input_Password") != user.Password) return false; return true; } public void ClickLoginButton() { var button = Helper.GetElementByXPath("//*[@id='account']/div[5]/button"); button.Click(); } public bool LoginSucceeded(User user) { GoToStorePage(); ClickLoginLink(); FillLoginForm(user); if (!IsLogingFormFilledProperly(user)) return false; ClickLoginButton(); if (!ValidateGreetingLoggedUser(user)) return false; return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ToggleControlS : MonoBehaviour { public Toggle t = null; public InitialScene scene = null; public Slider xslider = null, yslider = null, zslider = null; public Text xinfo = null, yinfo = null, zinfo = null; // Use this for initialization void Start () { if (t.isOn) initialState (); t.onValueChanged.AddListener(delegate {changeinfo(scene.currentSelected);}); } public void changeinfo(GameObject obj){ if (!t.isOn) return; if (obj == null) { initialState (); return; } xslider.value = obj.transform.localScale.x; yslider.value = obj.transform.localScale.y; zslider.value = obj.transform.localScale.z; xslider.minValue = 0; xslider.maxValue = 10; yslider.minValue = 0; yslider.maxValue = 10; zslider.minValue = 0; zslider.maxValue = 10; xinfo.text = obj.transform.localScale.x.ToString (); yinfo.text = obj.transform.localScale.y.ToString (); zinfo.text = obj.transform.localScale.z.ToString (); } public void initialState() { xslider.value = 0; yslider.value = 0; zslider.value = 0; xinfo.text = "0"; yinfo.text = "0"; zinfo.text = "0"; } // Update is called once per frame void Update () { changeinfo(scene.currentSelected); } }
 using LiteDB; namespace DiscordClients.Core.SQL.Tables { public class SqlDocument { public ObjectId Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CriticalPath.Data { public partial class SizingStandardDTO { partial void Initiliazing(SizingStandard entity) { Constructing(entity); } protected virtual void Constructing(SizingStandard entity) { var sizings = entity.Sizings.OrderBy(c => c.DisplayOrder); foreach (var item in entity.Sizings) { Sizings.Add(new SizingDTO(item)); } } partial void Converting(SizingStandard entity) { var sizings = Sizings.OrderBy(c => c.DisplayOrder); foreach (var item in sizings) { entity.Sizings.Add(item.ToSizing()); } } public ICollection<SizingDTO> Sizings { set { _sizings = value; } get { if (_sizings == null) _sizings = new List<SizingDTO>(); return _sizings; } } private ICollection<SizingDTO> _sizings; } }
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using Microsoft.PSharp.IO; namespace Microsoft.PSharp.TestingServices.Scheduling.Strategies { /// <summary> /// A priority-based probabilistic scheduling strategy. /// /// This strategy is described in the following paper: /// https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/asplos277-pct.pdf /// </summary> public sealed class PCTStrategy : ISchedulingStrategy { /// <summary> /// Random number generator. /// </summary> private readonly IRandomNumberGenerator RandomNumberGenerator; /// <summary> /// The maximum number of steps to schedule. /// </summary> private readonly int MaxScheduledSteps; /// <summary> /// The number of scheduled steps. /// </summary> private int ScheduledSteps; /// <summary> /// Max number of priority switch points. /// </summary> private readonly int MaxPrioritySwitchPoints; /// <summary> /// Approximate length of the schedule across all iterations. /// </summary> private int ScheduleLength; /// <summary> /// List of prioritized operations. /// </summary> private readonly List<IAsyncOperation> PrioritizedOperations; /// <summary> /// Set of priority change points. /// </summary> private readonly SortedSet<int> PriorityChangePoints; /// <summary> /// Initializes a new instance of the <see cref="PCTStrategy"/> class. It uses /// the default random number generator (seed is based on current time). /// </summary> public PCTStrategy(int maxSteps, int maxPrioritySwitchPoints) : this(maxSteps, maxPrioritySwitchPoints, new DefaultRandomNumberGenerator(DateTime.Now.Millisecond)) { } /// <summary> /// Initializes a new instance of the <see cref="PCTStrategy"/> class. /// It uses the specified random number generator. /// </summary> public PCTStrategy(int maxSteps, int maxPrioritySwitchPoints, IRandomNumberGenerator random) { this.RandomNumberGenerator = random; this.MaxScheduledSteps = maxSteps; this.ScheduledSteps = 0; this.ScheduleLength = 0; this.MaxPrioritySwitchPoints = maxPrioritySwitchPoints; this.PrioritizedOperations = new List<IAsyncOperation>(); this.PriorityChangePoints = new SortedSet<int>(); } /// <summary> /// Returns the next asynchronous operation to schedule. /// </summary> public bool GetNext(out IAsyncOperation next, List<IAsyncOperation> ops, IAsyncOperation current) { next = null; return this.GetNextHelper(ref next, ops, current); } /// <summary> /// Returns the next boolean choice. /// </summary> public bool GetNextBooleanChoice(int maxValue, out bool next) { next = false; if (this.RandomNumberGenerator.Next(maxValue) == 0) { next = true; } this.ScheduledSteps++; return true; } /// <summary> /// Returns the next integer choice. /// </summary> public bool GetNextIntegerChoice(int maxValue, out int next) { next = this.RandomNumberGenerator.Next(maxValue); this.ScheduledSteps++; return true; } /// <summary> /// Forces the next asynchronous operation to be scheduled. /// </summary> public void ForceNext(IAsyncOperation next, List<IAsyncOperation> ops, IAsyncOperation current) { this.GetNextHelper(ref next, ops, current); } /// <summary> /// Returns or forces the next asynchronous operation to schedule. /// </summary> private bool GetNextHelper(ref IAsyncOperation next, List<IAsyncOperation> ops, IAsyncOperation current) { var enabledOperations = ops.Where(op => op.IsEnabled).ToList(); if (enabledOperations.Count == 0) { return false; } IAsyncOperation highestEnabledOp = this.GetPrioritizedOperation(enabledOperations, current); if (next is null) { next = highestEnabledOp; } this.ScheduledSteps++; return true; } /// <summary> /// Forces the next boolean choice. /// </summary> public void ForceNextBooleanChoice(int maxValue, bool next) { this.ScheduledSteps++; } /// <summary> /// Forces the next integer choice. /// </summary> public void ForceNextIntegerChoice(int maxValue, int next) { this.ScheduledSteps++; } /// <summary> /// Prepares for the next scheduling iteration. This is invoked /// at the end of a scheduling iteration. It must return false /// if the scheduling strategy should stop exploring. /// </summary> public bool PrepareForNextIteration() { this.ScheduleLength = Math.Max(this.ScheduleLength, this.ScheduledSteps); this.ScheduledSteps = 0; this.PrioritizedOperations.Clear(); this.PriorityChangePoints.Clear(); var range = new List<int>(); for (int idx = 0; idx < this.ScheduleLength; idx++) { range.Add(idx); } foreach (int point in this.Shuffle(range).Take(this.MaxPrioritySwitchPoints)) { this.PriorityChangePoints.Add(point); } return true; } /// <summary> /// Resets the scheduling strategy. This is typically invoked by /// parent strategies to reset child strategies. /// </summary> public void Reset() { this.ScheduleLength = 0; this.ScheduledSteps = 0; this.PrioritizedOperations.Clear(); this.PriorityChangePoints.Clear(); } /// <summary> /// Returns the scheduled steps. /// </summary> public int GetScheduledSteps() => this.ScheduledSteps; /// <summary> /// True if the scheduling strategy has reached the max /// scheduling steps for the given scheduling iteration. /// </summary> public bool HasReachedMaxSchedulingSteps() { if (this.MaxScheduledSteps == 0) { return false; } return this.ScheduledSteps >= this.MaxScheduledSteps; } /// <summary> /// Checks if this is a fair scheduling strategy. /// </summary> public bool IsFair() => false; /// <summary> /// Returns a textual description of the scheduling strategy. /// </summary> public string GetDescription() { var text = $"PCT[priority change points '{this.MaxPrioritySwitchPoints}' ["; int idx = 0; foreach (var points in this.PriorityChangePoints) { text += points; if (idx < this.PriorityChangePoints.Count - 1) { text += ", "; } idx++; } text += "], seed '" + this.RandomNumberGenerator.Seed + "']"; return text; } /// <summary> /// Returns the prioritized operation. /// </summary> private IAsyncOperation GetPrioritizedOperation(List<IAsyncOperation> ops, IAsyncOperation current) { if (this.PrioritizedOperations.Count == 0) { this.PrioritizedOperations.Add(current); } foreach (var op in ops.Where(op => !this.PrioritizedOperations.Contains(op))) { var mIndex = this.RandomNumberGenerator.Next(this.PrioritizedOperations.Count) + 1; this.PrioritizedOperations.Insert(mIndex, op); Debug.WriteLine($"<PCTLog> Detected new operation from '{op.SourceName}' at index '{mIndex}'."); } if (this.PriorityChangePoints.Contains(this.ScheduledSteps)) { if (ops.Count == 1) { this.MovePriorityChangePointForward(); } else { var priority = this.GetHighestPriorityEnabledOperation(ops); this.PrioritizedOperations.Remove(priority); this.PrioritizedOperations.Add(priority); Debug.WriteLine($"<PCTLog> Operation '{priority}' changes to lowest priority."); } } var prioritizedSchedulable = this.GetHighestPriorityEnabledOperation(ops); Debug.WriteLine($"<PCTLog> Prioritized schedulable '{prioritizedSchedulable}'."); Debug.Write("<PCTLog> Priority list: "); for (int idx = 0; idx < this.PrioritizedOperations.Count; idx++) { if (idx < this.PrioritizedOperations.Count - 1) { Debug.Write($"'{this.PrioritizedOperations[idx]}', "); } else { Debug.WriteLine($"'{this.PrioritizedOperations[idx]}({1})'."); } } return ops.First(op => op.Equals(prioritizedSchedulable)); } /// <summary> /// Returns the highest-priority enabled operation. /// </summary> private IAsyncOperation GetHighestPriorityEnabledOperation(IEnumerable<IAsyncOperation> choices) { IAsyncOperation prioritizedOp = null; foreach (var entity in this.PrioritizedOperations) { if (choices.Any(m => m == entity)) { prioritizedOp = entity; break; } } return prioritizedOp; } /// <summary> /// Shuffles the specified list using the Fisher-Yates algorithm. /// </summary> private IList<int> Shuffle(IList<int> list) { var result = new List<int>(list); for (int idx = result.Count - 1; idx >= 1; idx--) { int point = this.RandomNumberGenerator.Next(this.ScheduleLength); int temp = result[idx]; result[idx] = result[point]; result[point] = temp; } return result; } /// <summary> /// Moves the current priority change point forward. This is a useful /// optimization when a priority change point is assigned in either a /// sequential execution or a nondeterministic choice. /// </summary> private void MovePriorityChangePointForward() { this.PriorityChangePoints.Remove(this.ScheduledSteps); var newPriorityChangePoint = this.ScheduledSteps + 1; while (this.PriorityChangePoints.Contains(newPriorityChangePoint)) { newPriorityChangePoint++; } this.PriorityChangePoints.Add(newPriorityChangePoint); Debug.WriteLine($"<PCTLog> Moving priority change to '{newPriorityChangePoint}'."); } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Data.Models.Other; namespace Data.Models { public class Team { [Key] public int TeamId { get; set; } public string Name { get; set; } public string TeamPictureUrl { get; set; } public LeagueType LeagueType { get; set; } [ForeignKey("LeagueType")] public League League { get; set; } public string ColorShort { get; set; } public string ColorShirt { get; set; } public ICollection<PushSubscription> Subscriptions { get; set; } = new List<PushSubscription>(); // public ICollection<Player> Players { get; set; } } }
namespace PetStore.ConsoleClient { using System; using System.Text; public static class RandomGenerator { private static Random random = new Random(Environment.TickCount); public static int RandomInt(int min, int max) { return random.Next(min, max + 1); } public static string RandomString(int len) { const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; StringBuilder builder = new StringBuilder(len); for (int i = 0; i < len; ++i) { builder.Append(chars[random.Next(chars.Length)]); } return builder.ToString(); } public static DateTime RandomDate(DateTime from, DateTime to) { var range = to - from; var randTimeSpan = new TimeSpan((long)(random.NextDouble() * range.Ticks)); return from + randTimeSpan; } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_AnimationCullingType : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.AnimationCullingType"); LuaObject.addMember(l, 0, "AlwaysAnimate"); LuaObject.addMember(l, 1, "BasedOnRenderers"); LuaObject.addMember(l, 2, "BasedOnClipBounds"); LuaObject.addMember(l, 3, "BasedOnUserBounds"); LuaDLL.lua_pop(l, 1); } }
using System; using iQuest.VendingMachine.Services.Authentication; using iQuest.VendingMachine.UseCases.UseCaseList; using iQuest.VendingMachine.PresentationLayer.Views.Interfaces; using iQuest.VendingMachine.UseCases.Interfaces; namespace iQuest.VendingMachine.PresentationLayer.Commands { internal class ManageMachineCommand : ICommand { private readonly IUseCaseFactory useCaseFactory; private readonly IAuthenticationService authenticationService; public string Name => "Manage Machine"; public string Description => " - Manages the products of the Vending Machine\n"; public bool CanExecute => authenticationService.IsUserAuthenticated; public ManageMachineCommand(IUseCaseFactory useCaseFactory, IAuthenticationService authenticationService) { this.useCaseFactory = useCaseFactory ?? throw new ArgumentNullException(nameof(useCaseFactory)); this.authenticationService = authenticationService ?? throw new ArgumentNullException(nameof(authenticationService)); } public void Execute() { useCaseFactory.Create<ManageMachineUseCase>().Execute(); } } }
using System; using System.Collections.Generic; using System.Text; using Xunit; using Microsoft.AspNetCore.Mvc; using BlogProject.Controllers; using BlogProject.Models; namespace BlogProject.Tests { public class BlogControllerTests { BlogController controller; //public BlogControllerTests() //{ // controller = new BlogController(); //} [Fact] public void Index_Returns_A_View() { var result = controller.Index(); Assert.IsType<ViewResult>(result); } [Fact] public void Index_Passes_AllModels_To_View() { var result = controller.Index(); Assert.IsAssignableFrom<Blog>(result.Model); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using MilkingLogApp.Models; namespace MilkingLogApp.Controllers { public class MilkingLogsController : ApiController { private MilkingLogAppContext db = new MilkingLogAppContext(); // GET: api/MilkingLogs public IQueryable<DateMilkingLog> GetMilkingLogs() { var dateMilkingLogs = from m in db.MilkingLogs group m by m.date into g let amountSum = g.Sum(m => m.amount) orderby g.Key descending select new DateMilkingLog() { date = g.Key, amount = amountSum }; return dateMilkingLogs; } // POST: api/MilkingLogs [ResponseType(typeof(MilkingLog))] public IHttpActionResult PostMilkingLog(MilkingLog milkingLog) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var milkingLogs = db.MilkingLogs.Where(m => m.date == milkingLog.date); foreach (var previousMilkingLog in milkingLogs) { if (previousMilkingLog.IsSubsetOf(milkingLog)) { db.MilkingLogs.Remove(previousMilkingLog); } else if (previousMilkingLog.IsOverlapingWith(milkingLog)) { return BadRequest("Selected cycles overlap with the previous entry"); } } db.MilkingLogs.Add(milkingLog); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = milkingLog.id }, milkingLog); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool MilkingLogExists(int id) { return db.MilkingLogs.Count(e => e.id == id) > 0; } } }
using System; using System.Data; using System.Collections.Generic; using System.Text; using Npgsql; using NpgsqlTypes; using CGCN.Framework; using CGCN.DataAccess; namespace QTHT.DataAccess { /// <summary> /// Mô tả thông tin cho bảng NhanVien /// Cung cấp các hàm xử lý, thao tác với bảng NhanVien /// Người tạo (C): /// Ngày khởi tạo: 14/10/2014 /// </summary> public class nhanvien { #region Private Variables private string stridnhanvien; private string stridphongban; private int intidchucvu; private string strtaikhoan; private string strmatkhau; private string strhoten; private DateTime dtmngaysinh; private string strdiachi; private string strdienthoai; private string stremail; private string strghichu; private bool blngioitinh; #endregion #region Public Constructor Functions public nhanvien() { stridnhanvien = string.Empty; stridphongban = string.Empty; intidchucvu = 0; strtaikhoan = string.Empty; strmatkhau = string.Empty; strhoten = string.Empty; dtmngaysinh = DateTime.Now; strdiachi = string.Empty; strdienthoai = string.Empty; stremail = string.Empty; strghichu = string.Empty; blngioitinh = false; } public nhanvien(string stridnhanvien, string stridphongban, int intidchucvu, string strtaikhoan, string strmatkhau, string strhoten, DateTime dtmngaysinh, string strdiachi, string strdienthoai, string stremail, string strghichu, bool blngioitinh) { this.stridnhanvien = stridnhanvien; this.stridphongban = stridphongban; this.intidchucvu = intidchucvu; this.strtaikhoan = strtaikhoan; this.strmatkhau = strmatkhau; this.strhoten = strhoten; this.dtmngaysinh = dtmngaysinh; this.strdiachi = strdiachi; this.strdienthoai = strdienthoai; this.stremail = stremail; this.strghichu = strghichu; this.blngioitinh = blngioitinh; } #endregion #region Properties public string idnhanvien { get { return stridnhanvien; } set { stridnhanvien = value; } } public string idphongban { get { return stridphongban; } set { stridphongban = value; } } public int idchucvu { get { return intidchucvu; } set { intidchucvu = value; } } public string taikhoan { get { return strtaikhoan; } set { strtaikhoan = value; } } public string matkhau { get { return strmatkhau; } set { strmatkhau = value; } } public string hoten { get { return strhoten; } set { strhoten = value; } } public DateTime ngaysinh { get { return dtmngaysinh; } set { dtmngaysinh = value; } } public string diachi { get { return strdiachi; } set { strdiachi = value; } } public string dienthoai { get { return strdienthoai; } set { strdienthoai = value; } } public string email { get { return stremail; } set { stremail = value; } } public string ghichu { get { return strghichu; } set { strghichu = value; } } public bool gioitinh { get { return blngioitinh; } set { blngioitinh = value; } } #endregion #region Public Method private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString); /// <summary> /// Lấy toàn bộ dữ liệu từ bảng nhanvien /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { string strFun = "fn_nhanvien_getall"; try { DataSet dsnhanvien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dsnhanvien.Tables[0]; } catch { return null; } } /// <summary> /// Lấy toàn bộ dữ liệu từ bảng nhanvien(Chỉ lấy id,taikhoan,hoten) /// </summary> /// <returns>DataTable</returns> public DataTable GetAllNotFullField() { string strFun = "fn_nhanvien_getallnotfullfield"; try { DataSet dsnhanvien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dsnhanvien.Tables[0]; } catch { return null; } } /// <summary> /// Hàm lấy nhanvien theo mã /// </summary> /// <returns>Trả về objnhanvien </returns> public nhanvien GetByID(string stridnhanvien) { nhanvien objnhanvien = new nhanvien(); string strFun = "fn_nhanvien_getobjbyid"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = stridnhanvien; DataSet dsnhanvien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if ((dsnhanvien != null) && (dsnhanvien.Tables.Count > 0)) { if (dsnhanvien.Tables[0].Rows.Count > 0) { DataRow dr = dsnhanvien.Tables[0].Rows[0]; objnhanvien.idnhanvien = dr["idnhanvien"].ToString(); objnhanvien.idphongban = dr["idphongban"].ToString(); try { objnhanvien.idchucvu = Convert.ToInt32("0" + dr["idchucvu"].ToString()); } catch { objnhanvien.idchucvu = 0; } objnhanvien.taikhoan = dr["taikhoan"].ToString(); objnhanvien.matkhau = dr["matkhau"].ToString(); objnhanvien.hoten = dr["hoten"].ToString(); try { objnhanvien.ngaysinh = Convert.ToDateTime(dr["ngaysinh"].ToString()); } catch { objnhanvien.ngaysinh = new DateTime(1900, 1, 1); } objnhanvien.diachi = dr["diachi"].ToString(); objnhanvien.dienthoai = dr["dienthoai"].ToString(); objnhanvien.email = dr["email"].ToString(); objnhanvien.ghichu = dr["ghichu"].ToString(); objnhanvien.gioitinh = Convert.ToBoolean(dr["gioitinh"].ToString()); return objnhanvien; } return null; } return null; } catch { return null; } } /// <summary> /// Hàm lấy danh sách nhân viên theo mã phòng ban /// </summary> /// <param name="stridphongban">Mã phòng ban kiểu string</param> /// <returns>DataTable</returns> public DataTable GetByIDPhongBan(string stridphongban) { nhanvien objnhanvien = new nhanvien(); string strFun = "fn_nhanvien_getbyidphongban"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("idphongban", NpgsqlDbType.Varchar); prmArr[0].Value = stridphongban; DataSet dsnhanvien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dsnhanvien.Tables[0]; } catch { return null; } } /// <summary> /// Thêm mới dữ liệu vào bảng: nhanvien /// </summary> /// <param name="obj">objnhanvien</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Insert(nhanvien objnhanvien) { string strProc = "fn_nhanvien_insert"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[13]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = objnhanvien.stridnhanvien; prmArr[1] = new NpgsqlParameter("idphongban", NpgsqlDbType.Varchar); prmArr[1].Value = objnhanvien.stridphongban; prmArr[2] = new NpgsqlParameter("idchucvu", NpgsqlDbType.Integer); prmArr[2].Value = objnhanvien.intidchucvu; prmArr[3] = new NpgsqlParameter("taikhoan", NpgsqlDbType.Varchar); prmArr[3].Value = objnhanvien.strtaikhoan; prmArr[4] = new NpgsqlParameter("matkhau", NpgsqlDbType.Varchar); prmArr[4].Value = objnhanvien.strmatkhau; prmArr[5] = new NpgsqlParameter("hoten", NpgsqlDbType.Varchar); prmArr[5].Value = objnhanvien.strhoten; prmArr[6] = new NpgsqlParameter("ngaysinh", NpgsqlDbType.Date); prmArr[6].Value = objnhanvien.dtmngaysinh; prmArr[7] = new NpgsqlParameter("diachi", NpgsqlDbType.Varchar); prmArr[7].Value = objnhanvien.strdiachi; prmArr[8] = new NpgsqlParameter("dienthoai", NpgsqlDbType.Varchar); prmArr[8].Value = objnhanvien.strdienthoai; prmArr[9] = new NpgsqlParameter("email", NpgsqlDbType.Varchar); prmArr[9].Value = objnhanvien.stremail; prmArr[10] = new NpgsqlParameter("ghichu", NpgsqlDbType.Varchar); prmArr[10].Value = objnhanvien.strghichu; prmArr[11] = new NpgsqlParameter("gioitinh", NpgsqlDbType.Boolean); prmArr[11].Value = objnhanvien.blngioitinh; prmArr[12] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[12].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[12].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Add".ToUpper()) == true) return ""; return "Thêm mới dữ liệu không thành công"; } catch (Exception ex) { return "Thêm mới dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Cập nhật dữ liệu vào bảng: nhanvien /// </summary> /// <param name="obj">objnhanvien</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(nhanvien objnhanvien) { string strProc = "fn_nhanvien_Update"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[13]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = objnhanvien.stridnhanvien; prmArr[1] = new NpgsqlParameter("idphongban", NpgsqlDbType.Varchar); prmArr[1].Value = objnhanvien.stridphongban; prmArr[2] = new NpgsqlParameter("idchucvu", NpgsqlDbType.Integer); prmArr[2].Value = objnhanvien.intidchucvu; prmArr[3] = new NpgsqlParameter("taikhoan", NpgsqlDbType.Varchar); prmArr[3].Value = objnhanvien.strtaikhoan; prmArr[4] = new NpgsqlParameter("matkhau", NpgsqlDbType.Varchar); prmArr[4].Value = objnhanvien.strmatkhau; prmArr[5] = new NpgsqlParameter("hoten", NpgsqlDbType.Varchar); prmArr[5].Value = objnhanvien.strhoten; prmArr[6] = new NpgsqlParameter("ngaysinh", NpgsqlDbType.Date); prmArr[6].Value = objnhanvien.dtmngaysinh; prmArr[7] = new NpgsqlParameter("diachi", NpgsqlDbType.Varchar); prmArr[7].Value = objnhanvien.strdiachi; prmArr[8] = new NpgsqlParameter("dienthoai", NpgsqlDbType.Varchar); prmArr[8].Value = objnhanvien.strdienthoai; prmArr[9] = new NpgsqlParameter("email", NpgsqlDbType.Varchar); prmArr[9].Value = objnhanvien.stremail; prmArr[10] = new NpgsqlParameter("ghichu", NpgsqlDbType.Varchar); prmArr[10].Value = objnhanvien.strghichu; prmArr[11] = new NpgsqlParameter("gioitinh", NpgsqlDbType.Boolean); prmArr[11].Value = objnhanvien.blngioitinh; prmArr[12] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[12].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[12].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Cập nhật dữ liệu không thành công"; } catch (Exception ex) { return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message; } } public string UpdateInfo(string sidnhanvien,string shoten,DateTime dtngaysinh,string sdiachi,string sdienthoai,string semail,string sghichu,bool bgioitinh ) { string strProc = "fn_nhanvien_updateinfo"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[9]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = sidnhanvien; prmArr[1] = new NpgsqlParameter("hoten", NpgsqlDbType.Varchar); prmArr[1].Value = shoten; prmArr[2] = new NpgsqlParameter("ngaysinh", NpgsqlDbType.Date); prmArr[2].Value = dtngaysinh; prmArr[3] = new NpgsqlParameter("diachi", NpgsqlDbType.Varchar); prmArr[3].Value = sdiachi; prmArr[4] = new NpgsqlParameter("dienthoai", NpgsqlDbType.Varchar); prmArr[4].Value = sdienthoai; prmArr[5] = new NpgsqlParameter("email", NpgsqlDbType.Varchar); prmArr[5].Value = semail; prmArr[6] = new NpgsqlParameter("ghichu", NpgsqlDbType.Varchar); prmArr[6].Value = sghichu; prmArr[7] = new NpgsqlParameter("gioitinh", NpgsqlDbType.Boolean); prmArr[7].Value = bgioitinh; prmArr[8] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[8].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[8].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Cập nhật dữ liệu không thành công"; } catch (Exception ex) { return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message; } } public string ChangePass(string sidnhanvien, string smatkhau) { string strProc = "fn_nhanvien_changepass"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[3]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = sidnhanvien; prmArr[1] = new NpgsqlParameter("matkhau", NpgsqlDbType.Varchar); prmArr[1].Value = smatkhau; prmArr[2] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[2].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[2].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Đặt lại mật khẩu người dùng không thành công."; } catch (Exception ex) { return "Đặt lại mật khẩu người dùng không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Xóa dữ liệu từ bảng nhanvien /// </summary> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string Delete(string stridnhanvien) { string strProc = "fn_nhanvien_delete"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = stridnhanvien; prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[1].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string KQ = prmArr[1].Value.ToString().Trim(); if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return ""; return "Xóa dữ liệu không thành công"; } catch (Exception ex) { return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Hàm kiểm tra đăng nhập /// </summary> /// <param name="sTaiKhoan">Tài khoản kiểu string</param> /// <param name="sMatKhau">Mật khẩu kiểu string</param> /// <returns>bool: true-là đúng; false-là sai</returns> public bool Authentication(string sTaiKhoan, string sMatKhau) { string strFun = "fn_user_authen"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("itaikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = sTaiKhoan; prmArr[1] = new NpgsqlParameter("imatkhau", NpgsqlDbType.Varchar); prmArr[1].Value = sMatKhau; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (dsNhanVien.Tables[0].Rows.Count > 0) { return true; } else { return false; } } catch { return false; } } /// <summary> /// Hàm kiểm tra tồn tại tài khoản /// </summary> /// <param name="sTaiKhoan">Tài khoản kiểu string</param> /// <param name="iTrangThai">Trạng thái: 1-Thêm mới; 2-Sửa</param> /// <returns>DataTable</returns> public DataTable CheckExitAccount(string sTaiKhoan,int iTrangThai) { string strFun = "fn_user_checkexit"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("itaikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = sTaiKhoan; prmArr[1] = new NpgsqlParameter("itrangthai", NpgsqlDbType.Integer); prmArr[1].Value = iTrangThai; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dsNhanVien.Tables[0]; } catch { return null; } } /// <summary> /// Hàm kiểm tra tồn tại email /// </summary> /// <param name="semail">Email kiểu string</param> /// <returns>bool: true-tồn tại; false-không tồn tại</returns> public bool CheckEmail(string semail) { string strFun = "fn_user_checkemail"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("email", NpgsqlDbType.Varchar); prmArr[0].Value = semail; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (dsNhanVien.Tables[0].Rows.Count > 0) { return true; } return false; } catch { return true; } } /// <summary> /// Hàm lấy thông tin người dùng theo email /// </summary> /// <param name="semail">Email kiểu string</param> /// <returns>DataTable</returns> public DataTable GetbyEmail(string semail) { string strFun = "fn_user_checkemail"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("email", NpgsqlDbType.Varchar); prmArr[0].Value = semail; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dsNhanVien.Tables[0]; } catch { return null; } } /// <summary> /// Hàm kiểm tra tồn tại người dùng theo mã /// </summary> /// <param name="stridnhanvien">Mã người dùng kiểu string</param> /// <returns>bool</returns> public bool CheckExitAccount(string stridnhanvien) { string strFun = "fn_user_checkexit"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = stridnhanvien; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (dsNhanVien.Tables[0].Rows.Count > 0) { return true; } else { return false; } } catch { return false; } } /// <summary> /// Hàm lấy mã người dùng theo tài khoản đăng nhập /// </summary> /// <param name="stridnhanvien">Mã người dùng kiểu string</param> /// <returns>string</returns> public string GetIDNhanVienByAccount(string strtaikhoan) { string strFun = "fn_user_getidbyaccount"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("taikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = strtaikhoan; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (dsNhanVien.Tables[0].Rows.Count > 0) { return dsNhanVien.Tables[0].Rows[0]["fn_user_getidbyaccount"].ToString().Trim(); } else { return ""; } } catch { return ""; } } /// <summary> /// Hàm lấy thông tin người dùng /// </summary> /// <param name="strtaikhoan">IN: tài khoản</param> /// <param name="siduser">OUT: mã người dùng</param> /// <param name="shoten">OUT: họ tên người dùng</param> /// <param name="iloai">OUT: kiểu người dùng: 0-Người dùng nội bộ;1-Người dùng đăng ký(khách hàng)</param> /// <returns>string:0-Người dùng nội bộ;1-Người dùng đăng ký(khách hàng)</returns> public string GetInfoUserByAccount(string strtaikhoan, out string siduser, out string shoten, out string sloai) { siduser = ""; shoten = ""; sloai = ""; string strFun = "fn_user_getinfobyaccount"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("taikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = strtaikhoan; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (dsNhanVien.Tables[0].Rows.Count > 0) { siduser = dsNhanVien.Tables[0].Rows[0]["iduser"].ToString().Trim(); shoten = dsNhanVien.Tables[0].Rows[0]["hoten"].ToString().Trim(); sloai = dsNhanVien.Tables[0].Rows[0]["loai"].ToString().Trim(); return sloai; } else { return ""; } } catch { return ""; } } /// <summary> /// Hàm tìm kiếm nhân viên /// </summary> /// <param name="sDieuKien">Điều kiện tìm kiếm kiểu string</param> /// <returns>DataTable</returns> public DataTable TimKiem(string sDieuKien) { string query = ""; query = "SELECT nhanvien.idnhanvien,nhanvien.idphongban,nhanvien.hoten,chucvu.tenchucvu, " + "phongban.tenphongban,nhanvien.taikhoan,nhanvien.matkhau,nhanvien.ngaysinh,nhanvien.diachi, " + "nhanvien.dienthoai,nhanvien.email,nhanvien.ghichu,nhanvien.gioitinh " + "FROM public.nhanvien,public.phongban,public.chucvu " + "WHERE " + "nhanvien.idchucvu = chucvu.idchucvu AND " + "nhanvien.idphongban = phongban.idphongban AND " + sDieuKien; try { DataSet ds = mDataAccess.ExecuteDataSet(query, CommandType.Text); return ds.Tables[0]; } catch { return null; } } /// <summary> /// Hàm lấy danh sách nhân viên theo tên tài khoản /// </summary> /// <param name="sTaiKhoan">Tên tài khoản kiểu string</param> /// <returns>DataTable</returns> public DataTable GetByAccountName(string sTaiKhoan) { string strFun = "fn_nhanvien_getbyaccountname"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("itaikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = sTaiKhoan; DataSet dsNhanVien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); return dsNhanVien.Tables[0]; } catch { return null; } } /// <summary> /// Hàm kiểm tra quyền download tư liệu theo loại tư liệu và mã người dùng /// </summary> /// <param name="siduser">Mã người dùng kiểu string</param> /// <param name="sidloaitl">Mã loại tư liệu kiểu string</param> /// <returns>bool: True-Có;False:Không</returns> public bool CheckLoaiTLDownload(string siduser,string sidloaitl) { bool kq = false; string strFun = "fn_user_checkdownload"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("idnhanvien", NpgsqlDbType.Varchar); prmArr[0].Value = siduser; prmArr[1] = new NpgsqlParameter("idloaitulieu", NpgsqlDbType.Varchar); prmArr[1].Value = sidloaitl; DataSet ds = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if (ds.Tables[0].Rows.Count > 0) { kq = true; } return kq; } catch { return false; } } /// <summary> /// Đăng nhập /// </summary> /// <param name="staikhoan">Tài khoản kiểu string</param> /// <param name="smatkhau">Mật khẩu kiểu string đã được băm theo thuật toán MD5</param> /// <returns>bool: True-Thành công; False-Không thành công</returns> public bool DangNhap(string staikhoan, string smatkhau) { string strProc = "fn_nhanvien_dangnhap"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[3]; prmArr[0] = new NpgsqlParameter("taikhoan", NpgsqlDbType.Varchar); prmArr[0].Value = staikhoan; prmArr[1] = new NpgsqlParameter("matkhau", NpgsqlDbType.Varchar); prmArr[1].Value = smatkhau; prmArr[2] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[2].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[2].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("1".ToUpper()) == true) return true; else if (sKQ.ToUpper().Equals("0".ToUpper()) == true) return false; } catch { return false; } return false; } /// <summary> /// Hàm load danh sách nhân viên với trường taikhoan + hoten /// </summary> /// <returns>DataTable</returns> public DataTable LoadDSCBNV() { string strFun = "fn_nhanvien_loadcbnv"; try { DataSet dsnhanvien = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dsnhanvien.Tables[0]; } catch { return null; } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; using System.Web; namespace PVB_Stage_Applicatie.Models { public class TussentijdseEindBeoordelingModel { private StageApplicatieEntities db = new StageApplicatieEntities(); public TussentijdseBeindeging TussentijdseBeeindegingModel { get; set; } public DbSet<RedenStudent> RedenStudent { get { return db.RedenStudent; } } public DbSet<RedenOrganisatie> RedenOrganisatie { get { return db.RedenOrganisatie; } } public DbSet<RedenOnderwijsinstelling> RedenOnderwijsinstelling { get { return db.RedenOnderwijsinstelling; } } //[RegularExpression(@"[0-9\,]", ErrorMessage = "Oi, niet hacken.")] public string RedenenOrganisatie { get; set; } //[RegularExpression(@"[0-9\,]", ErrorMessage = "Oi, niet hacken.")] public string RedenenOnderwijsinstelling { get; set; } //[RegularExpression(@"[0-9\,]", ErrorMessage = "Oi, niet hacken.")] public string RedenenStudent { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { //Written by Ciara Brothers //February 2019 public partial class Home : Form { public Home() { InitializeComponent(); } private void btnSign_Click(object sender, EventArgs e) { frmSignUp form = new frmSignUp(); form.ShowDialog(); } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } int studentCounter = 0; public string address = ""; private void btnLogin_Click(object sender, EventArgs e) { try { string password = txtPassword.Text; string email = txtEmail.Text; bool match = false; string[] student = { }; //Open Text File string path = Path.Combine(Environment.CurrentDirectory, @"..\..\books.txt"); FileInfo fi = new FileInfo(path); using (StreamReader sr = fi.OpenText()) { studentCounter++; string s = ""; while ((s = sr.ReadLine()) != null) { student = s.Split('|'); //Check if Email is Valid if (student[5] == password && student[3] == email) { match = true; sr.Close(); break; } } if (!match) { MessageBox.Show("Email or Password is Incorrect!"); } else { //Open Returning User Screen frmReturn login = new frmReturn(); //Put Student Array Data into Data Array login.data = student; login.ShowDialog(); } } } catch (IndexOutOfRangeException) { MessageBox.Show("Login information invalid"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnReport_Click(object sender, EventArgs e) { frmReport report = new frmReport(); report.ShowDialog(); } private void button1_Click(object sender, EventArgs e) { Help help = new Help(); help.ShowDialog(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConnectionWizardPage.xaml.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.GUI.Configuration.Wizard { using System.Windows.Controls; using System.Windows.Input; /// <summary> /// Interaction logic for ConnectionWizardPage.xaml. /// </summary> public partial class ConnectionWizardPage : Page { /// <summary> /// The wizard controller. /// </summary> private readonly WizardController wizardController; /// <summary> /// Initializes a new instance of the <see cref="ConnectionWizardPage"/> class. /// </summary> /// <param name="wizardController">The wizard controller.</param> public ConnectionWizardPage(WizardController wizardController) { this.wizardController = wizardController; this.InitializeComponent(); this.DataContext = this; this.AutoDetectionCheckbox.DataContext = this.wizardController; this.AddressComboBox.Loaded += (s, e) => { if (this.AddressComboBox.Items.Count > 0) { this.AddressComboBox.SelectedIndex = 0; } this.AddressComboBox.Focus(); }; } /// <summary> /// Handles the key up event for control which allows providing a project address. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param> private void ConnectionAdressKeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Enter) { this.wizardController.GoToNextPage(); } } } }
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Com.Cdi.Merp.Web; public partial class errorPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Exception caughtException = (Exception)Application["TheException"]; if (caughtException != null) { HttpException httpException = (HttpException)caughtException; int STATUS_CODE = httpException.GetHttpCode(); string HTTP_HOST = Request.ServerVariables["HTTP_HOST"].ToString(); string HTTP_USER_AGENT = Request.ServerVariables["HTTP_USER_AGENT"].ToString(); string HTTP_REFERER = Request.ServerVariables["HTTP_REFERER"] != null ? Request.ServerVariables["HTTP_REFERER"].ToString() : ""; string LOCAL_ADDR = Request.ServerVariables["LOCAL_ADDR"].ToString(); string REMOTE_ADDR = IP_Filter.GetIP(); string URL = Request.ServerVariables["URL"].ToString(); string QUERY_STRING = Request.ServerVariables["QUERY_STRING"].ToString(); string STD_ID = SessionClass.stf_id.ToString(); try { string MSG = caughtException.Message + "\r\n Stack Trace : " + caughtException.StackTrace.ToString(); string MSG2 = string.Empty; if (caughtException.InnerException != null) { MSG2 += "\r\n " + caughtException.InnerException.Message+ "\r\n Stack Trace 2 : " + caughtException.InnerException.StackTrace.ToString(); } Com.Cdi.Merp.Biz.Contents.Common o = new Com.Cdi.Merp.Biz.Contents.Common(); o.errorLogging(HTTP_HOST, LOCAL_ADDR, REMOTE_ADDR, HTTP_REFERER, STATUS_CODE, MSG + MSG2, HTTP_USER_AGENT, URL, QUERY_STRING, STD_ID); } catch (Exception ex) { } } } }
 using System.Collections.Generic; using System.ComponentModel; namespace ReDefNet { /// <summary> /// Represents a dynamic data collection that provides notifications when items get added, removed, or when the entire /// collection is refreshed. /// </summary> /// <typeparam name="T">The type of elements in the collection.</typeparam> public interface IObservableCollection<T> : IList<T>, IReadOnlyObservableCollection<T> { /// <summary> /// Gets the number of elements in the collection. /// </summary> /// <value> /// The number of elements in the collection. /// </value> new int Count { get; } /// <summary> /// Gets a value indicating whether the collection is read-only. /// </summary> /// <value> /// <c>true</c>, if the collection is read-only; otherwise, <c>false</c>. /// </value> new bool IsReadOnly { get; } /// <summary> /// Adds the specified range of items to the collection. /// </summary> /// <param name="items">The items.</param> void AddRange(IEnumerable<T> items); /// <summary> /// Moves the item at the specified index to a new location in the collection. /// </summary> /// <param name="oldIndex">The old index.</param> /// <param name="newIndex">The new index.</param> void Move(int oldIndex, int newIndex); } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using WebAPIClient.Models; namespace WebAPIClient { class Program { static void Main(string[] args) { Task.Run(async () => { // Adicionado o pacote Microsoft.AspNet.WebApi.Client var client = new HttpClient(); client.BaseAddress = new Uri("https://localhost:44311/"); // Realiza a requisição Get para a Rota Get da API remota. var response = await client.GetAsync("/api/tarefa"); var getAllTarefas = await response.Content.ReadAsAsync<IEnumerable<Tarefa>>(); // Realiza a requisição Post para a Rota Get da API remota. await client.PostAsJsonAsync("/api/tarefa/", new Tarefa() { Id = 99, Nome = "Criada via requisição app Console", isFinalizado = true }); // Realiza a requisição Put para a Rota Get da API remota. await client.PutAsJsonAsync("/api/tarefa/99", new Tarefa() { Id = 99, Nome = "Criada via requisição app Console - com alteração no nome", isFinalizado = true }); var retorno = await client.DeleteAsync("/api/tarefa/99"); var status = await retorno.Content.ReadAsHttpResponseMessageAsync(); }) .GetAwaiter() .GetResult(); } } }
namespace E01_StudentClass { using System; using System.Collections.Generic; using E01_StudentClass.EnumClasses; public class StudentClassMain { public static void Main(string[] args) { // 01. Student class: // Define a class Student, which contains data about a // student – first, middle and last name, SSN, permanent // address, mobile phone e-mail, course, specialty, university, // faculty. Use an enumeration for the specialties, // universities and faculties. // Override the standard methods, inherited by System.Object: // Equals(), ToString(), GetHashCode() and operators == and !=. // // 02. IClonable: // Add implementations of the ICloneable interface. The Clone() // method should deeply copy all object's fields into a new // object of type Student. // // 03. IComparable: // Implement the IComparable<Student> interface to compare students // by names (as first criteria, in lexicographic order) and by // social security number (as second criteria, in increasing order). Student firstStudent = new Student(); firstStudent.FirstName = "Pesho"; firstStudent.MiddleName = "Goshev"; firstStudent.LastName = "Peshev"; firstStudent.SSN = "1000000"; firstStudent.PermanentAddress = "New York street 17"; firstStudent.MobilePhone = "0777 345 765"; firstStudent.E_mail = "Pesho@York.zoo"; firstStudent.Course = "IV"; firstStudent.University = University.SU; firstStudent.Specialty = Specialty.MedicineMarketing; firstStudent.Faculty = Faculty.Management; Student secondStudent = new Student(); secondStudent.FirstName = "Pesho"; secondStudent.MiddleName = "Goshev"; secondStudent.LastName = "Petrov"; secondStudent.SSN = "4353762"; secondStudent.PermanentAddress = "Moskow street 16"; secondStudent.MobilePhone = "0769 385 965"; secondStudent.E_mail = "Pesho@Moskow.tu"; secondStudent.Course = "III"; secondStudent.University = University.TU; secondStudent.Specialty = Specialty.Informatics; secondStudent.Faculty = Faculty.IT_technology; Student thirdStudent = new Student(); thirdStudent.FirstName = "Pesho"; thirdStudent.MiddleName = "Goshev"; thirdStudent.LastName = "Peshev"; thirdStudent.SSN = "1000055"; thirdStudent.PermanentAddress = "Sofia street 16"; thirdStudent.MobilePhone = "0464 312 325"; thirdStudent.E_mail = "Pesho@Sofia.tu"; thirdStudent.Course = "II"; thirdStudent.University = University.TU; thirdStudent.Specialty = Specialty.Informatics; thirdStudent.Faculty = Faculty.Management; Console.WriteLine("firstStudent = secondStudent : {0}", (firstStudent == secondStudent)); Console.WriteLine("firstStudent = thirdStudent : {0}", (firstStudent == thirdStudent)); Console.WriteLine(); Console.WriteLine("firstStudent Equals secondStudent : {0}", (firstStudent.Equals(secondStudent))); Console.WriteLine("firstStudent Equals thirdStudent : {0}", (firstStudent.Equals(thirdStudent))); Console.WriteLine(); // 02. IClonable: Student cloneStudent = firstStudent.Clone(); Console.WriteLine("firstStudent Equals cloneStudent : {0}", (firstStudent.Equals(cloneStudent))); Console.WriteLine("secondStudent Equals cloneStudent : {0}", (secondStudent.Equals(cloneStudent))); Console.WriteLine(); // 03. IComparable: Console.WriteLine("firstStudent CompareTo cloneStudent : {0}", (firstStudent.CompareTo(cloneStudent))); Console.WriteLine("secondStudent CompareTo cloneStudent : {0}", (secondStudent.CompareTo(cloneStudent))); Console.WriteLine(); List<Student> listStudents = new List<Student>(); listStudents.Add(firstStudent); listStudents.Add(secondStudent); listStudents.Add(cloneStudent); listStudents.Add(thirdStudent); listStudents.Sort(); foreach (var student in listStudents) { Console.WriteLine(student); } } } }
using System; using System.Collections.Generic; using System.Text; using TurkishTechnic.Core.DataAccess.EntityFramework; using TurkishTechnic.DataAccess.Abstract; using TurkishTechnic.DataAccess.Concrete.EntityFramework.Context; using TurkishTechnic.Entities; namespace TurkishTechnic.DataAccess.Concrete.EntityFramework { public class EFWorkingDal : EntityRepositoryBase<WorkingTime, TurkishTechnicContext>, IWorkingTimeDal { } }
// Copyright (c) 2014 Rotorz Limited. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using UnityEngine; using System; using System.Collections.Generic; using Rotorz.Tile; using System.Collections; namespace Custom { /// <summary> /// Maintains map of composite tiles making it possible to identify grouped /// tiles. Aside from providing the ability to erase entire groups of tiles, /// this can also be utilized within user scripts if desired. /// </summary> /// <example> /// <para>Fetch all tiles in group by providing the index of a grouped tile:</para> /// <code language="csharp"><![CDATA[ /// var pickIndex = new TileIndex(1, 2); /// var compositeMap = system.GetComponent<CompositeTileMap>(); /// var group = compositeMap.GetGroupedTileIndices(pickIndex); /// if (group != null) { /// foreach (int flatIndex in group) { /// TileIndex index = compositeMap.TileIndexFromFlatIndex(flatIndex); /// TileData tile = system.GetTile(index); /// if (tile != null) { /// // Filled tile within group. /// } /// else { /// // Empty tile within group. /// } /// } /// } /// ]]></code> /// <code language="unityscript"><![CDATA[ /// var pickIndex:TileIndex = new TileIndex(1, 2); /// var compositeMap:CompositeTileMap = system.GetComponent.<CompositeTileMap>(); /// var group:List.<int> = compositeMap.GetGroupedTileIndices(pickIndex); /// if (group != null) { /// for (var flatIndex:int in group) { /// var index:TileIndex = compositeMap.TileIndexFromFlatIndex(flatIndex); /// var tile:TileData = system.GetTile(index); /// if (tile != null) { /// // Filled tile within group. /// } /// else { /// // Empty tile within group. /// } /// } /// } /// ]]></code> /// </example> public sealed class CompositeTileMap : MonoBehaviour { [SerializeField] private bool _destroyOnAwake; [SerializeField] private bool _stripOnBuild; /// <summary> /// Gets or sets a value indicating whether this component should be /// destroyed upon receiving "Awake" message. /// </summary> public bool DestroyOnAwake { get { return _destroyOnAwake; } set { _destroyOnAwake = value; } } /// <summary> /// Gets or sets a value indicating whether this component should be /// stripped from tile system upon being built. Stripping this component /// helps to reduce memory overhead. /// </summary> public bool StripOnBuild { get { return _stripOnBuild; } set { _stripOnBuild = value; } } private TileSystem _system; /// <summary> /// Gets cached reference to associated tile system component. /// </summary> private TileSystem TileSystem { get { if (_system == null) _system = GetComponent<TileSystem>(); return _system; } } #region Messages and Events private void Awake() { if (DestroyOnAwake) Destroy(this); } #endregion #region Tile Compositions private Dictionary<int,CompositeTileGroup > _groups = new Dictionary<int, CompositeTileGroup>(); /// <summary> /// Convert tile index (row, column) into flat index. /// </summary> /// <param name="index">Tile index.</param> /// <returns> /// Zero-based index of tile within tile system. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public int FlatIndexFromTileIndex(TileIndex index) { if ((int)index.row >= TileSystem.rows || (int)index.column >= TileSystem.columns) throw new ArgumentOutOfRangeException("index"); return index.row * TileSystem.columns + index.column; } /// <summary> /// Convert flat zero-based index to tile index (row, column). /// </summary> /// <param name="index">Zero-based index of tile within tile system.</param> /// <returns> /// Tile index. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public TileIndex TileIndexFromFlatIndex(int index) { int rows = TileSystem.rows; int columns = TileSystem.columns; if ((int)index >= rows * columns) throw new ArgumentOutOfRangeException("index"); TileIndex tileIndex; tileIndex.row = index / columns; tileIndex.column = index % columns; return tileIndex; } /// <summary> /// Get list of grouped tile indices. /// </summary> /// <param name="index">Index of a grouped tile.</param> /// <returns> /// List of tile indices when specified index is part of a group; otherwise /// a value of <c>null</c>. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public CompositeTileGroup GetGroupedTileIndices(TileIndex index) { CompositeTileGroup group; _groups.TryGetValue(FlatIndexFromTileIndex(index), out group); return group; } /// <summary> /// Group specified tiles. /// </summary> /// <remarks> /// <para>The way in which input tiles are grouped varies depending upon /// whether they are already grouped or not:</para> /// <list type="bullet"> /// <item>New group is created if neither input is already grouped.</item> /// <item>Ungrouped input is added to group of other input.</item> /// <item>Groups of inputs are merged.</item> /// </list> /// </remarks> /// <param name="index1">Index of first tile to group.</param> /// <param name="index2">Index of second tile to group.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when one or both of the specified indices are outside bounds /// of tile system. /// </exception> public void GroupTiles(TileIndex index1, TileIndex index2,String CompName) { int flatIndex1 = FlatIndexFromTileIndex(index1); int flatIndex2 = FlatIndexFromTileIndex(index2); CompositeTileGroup group1, group2; _groups.TryGetValue(flatIndex1, out group1); _groups.TryGetValue(flatIndex2, out group2); // Swap groups so that we are always adding to group1. if (group1 == null) { group1 = group2; group2 = null; } else if (group1 == group2) { // These tiles are already grouped! return; } if (flatIndex1 == flatIndex2) { // A group of one tile! group1 = new CompositeTileGroup(CompName); group1.Add(flatIndex1); _groups[flatIndex1] = group1; } else if (group1 == null) { // Neither of these tiles are already grouped. group1 = new CompositeTileGroup(CompName); group1.Add(flatIndex1); group1.Add(flatIndex2); _groups[flatIndex1] = group1; _groups[flatIndex2] = group1; } else if (group2 == null) { // Just need to add second index to first group. group1.Add(flatIndex2); _groups[flatIndex2] = group1; } else { // We need to merge two separate groups! for (int i = 0; i < group2.Count; ++i) { flatIndex2 = group2[i]; group1.Add(flatIndex2); _groups[flatIndex2] = group1; } } } /// <summary> /// Ungroup all tiles from group of input tile. Nothing happens if input /// tile is not actually grouped. /// </summary> /// <param name="index">Index of tile.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public void UngroupTiles(TileIndex index) { CompositeTileGroup group = GetGroupedTileIndices(index); if (group == null) return; int count = group.Count; while (--count >= 0) { int clearTileIndex = group[count]; _groups.Remove(clearTileIndex); } } /// <summary> /// Place input tile within its very own group. Nothing happens if input /// tile is already grouped. /// </summary> /// <param name="index">Index of tile.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public void GroupIndividualTile(TileIndex index) { //GroupTiles(index, index); } /// <summary> /// Remove individual tile from its group. Nothing happens if input tile /// is not actually grouped. /// </summary> /// <param name="index">Index of tile.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public void UngroupIndividualTile(TileIndex index) { int flatIndex = FlatIndexFromTileIndex(index); CompositeTileGroup group; _groups.TryGetValue(flatIndex, out group); if (group == null) return; group.Remove(flatIndex); if (group.Count == 1) _groups[flatIndex] = null; } /// <summary> /// Determine whether tile is part of a group. /// </summary> /// <param name="index">Index of tile.</param> /// <returns> /// A value of <c>true</c> if input tile is grouped with zero or more /// other tiles; otherwise a value of <c>false</c>. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when specified index is outside bounds of tile system. /// </exception> public bool IsGrouped(TileIndex index) { return GetGroupedTileIndices(index) != null; } /// <summary> /// Ungroup all tiles. /// </summary> public void UngroupAll() { _groups.Clear(); } #endregion } public class CompositeTileGroup : IEnumerator<int> { public List<int> Data = new List<int>(); private int curIndex; private int curInt; private String _CompositionName;//name of composite tile map used to create this group(room,etc) public String CompositionName { get { return _CompositionName; } set { _CompositionName = value; } } public CompositeTileGroup(String CompName) { curIndex=-1; CompositionName = CompName; } public IEnumerator<int> GetEnumerator() { return Data.GetEnumerator(); } public void Add(int someint) { Data.Add(someint); } public void Remove(int someint) { Data.Remove(someint); } public int Count { get { return Data.Count; } } public int this[int i] { get { return Data[i]; } set { Data[i] = value; } } public bool MoveNext() { //Avoids going beyond the end of the collection. if (++curIndex >= Data.Count) { return false; } else { // Set current box to next item in collection. curInt = Data[curIndex]; } return true; } public void Reset() { curIndex = -1; } public int Current { get { return curInt; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { throw new NotImplementedException(); } } }
using System; using System.Linq; using ShCore.DataBase.ADOProvider.Attributes; using ShCore.Extensions; using System.Collections.Generic; using ShCore.Reflectors; using System.Reflection; namespace ShCore.DataBase.ADOProvider.ShSqlCommand { /// <summary> /// Build Command từ ModelBase /// </summary> /// <typeparam name="T"></typeparam> public class TSqlBuilder { /// <summary> /// Khởi tạo /// </summary> public TSqlBuilder(Type typeOfT) { this.typeOfT = typeOfT; } /// <summary> /// typeOfT /// </summary> private Type typeOfT = null; public Type TypeOfT { get { return typeOfT; } } private TableInfoAttribute tableInfo = null; /// <summary> /// Thông tin về bảng trong cơ sở dữ liệu /// </summary> public TableInfoAttribute TableInfo { get { // Nếu thông tin bảng chưa có thì lấy ra if (tableInfo == null) tableInfo = typeOfT.GetAttribute<TableInfoAttribute>(); return tableInfo; } } private List<FieldAttribute> fieldPKs = null; /// <summary> /// Danh sách Primary Key /// </summary> public List<FieldAttribute> FieldPKs { get { // Nếu chưa thông tin khóa chính thì lấy ra if (fieldPKs == null) // Chỉ lấy những Field là khóa chính fieldPKs = new ReflectTypeListPropertyWithAttribute<FieldAttribute>()[typeOfT].Where(f => f.T2.IsKey).Select(f => { f.T2.FieldName = f.T1.Name; return f.T2; }).ToList(); // trả ra danh sách khóa chinh return fieldPKs; } } private List<PropertyInfo> allProperties = null; /// <summary> /// Tất cả Property có FieldAttribute /// </summary> public List<PropertyInfo> AllProperties { get { if (allProperties == null) allProperties = new ReflectTypeListPropertyWithAttribute<FieldAttribute>()[typeOfT].Select(f => f.T1).ToList(); return allProperties; } } /// <summary> /// Build ra câu lệnh Command tương ứng /// </summary> /// <typeparam name="TCommand"></typeparam> /// <param name="t"></param> /// <returns></returns> public ShCommand BuildCommand<TCommand>(ModelBase t, params string[] fields) where TCommand : ShCommand, new() { // Build ra câu lệnh Command ShCommand cmd = new TCommand(); // Nếu như Builder hiện tại không hợp lệ thì trả ra command null if (!cmd.IsValid(this)) return null; cmd.Build(t, this, fields); // Trả ra câu lệnh return cmd; } /// <summary> /// Build select với tất cả các field /// </summary> /// <returns></returns> public string BuildSelectAllField() { // Select string str = " SELECT"; // Các fields this.AllProperties.ForEach(p => str += " t.{0},".Frmat(p.Name)); // Build lệnh return str.TrimEnd(',') + " FROM {0} t".Frmat(this.TableInfo.TableName); } } }
using System; namespace Core.Sources { public class BallotMessage : ICloneable, IEquatable<BallotMessage> { public BallotMessage(Kingdom sender, Kingdom receiver, string message) { Sender = sender; Receiver = receiver; Message = message; } public Kingdom Sender { get; } public Kingdom Receiver { get; } public string Message { get; } public void SendMessageToReceivingKingdom() { if (this.Receiver.TryToWin(this.Message)) { this.Sender.AddAllie(this.Receiver); } } public static BallotMessage Create(Kingdom sender,Kingdom receiver,string message) { return new BallotMessage(sender,receiver,message); } public object Clone() { return this.MemberwiseClone(); } public override string ToString() { return this.Sender.ToString() +" "+ this.Receiver.ToString()+" "+this.Message; } public override int GetHashCode() { return this.ToString().GetHashCode(); } public bool Equals(BallotMessage other) { return this.Receiver == other.Receiver && this.Sender == other.Sender && this.Message == other.Message; } public override bool Equals(Object obj) { if (obj == null) return false; BallotMessage message = obj as BallotMessage; if (message == null) return false; else return Equals(message); } public static bool operator ==(BallotMessage operand1, BallotMessage operand2) { if (((object)operand1) == null || ((object)operand2) == null) return Object.Equals(operand1, operand2); return operand1.Equals(operand2); } public static bool operator !=(BallotMessage operand1, BallotMessage operand2) { if (((object)operand1) == null || ((object)operand2) == null) return !Object.Equals(operand1, operand2); return !(operand1.Equals(operand2)); } } }
using Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dao.Seguridad { public interface IAccesoUsuarioDao:IGenericDao<AccesoUsuario> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Sayhi.Controllers { public class SayHiUserValidateController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //判断Session是否为空 if (Session["UserInfo"] == null) { filterContext.Result = RedirectToAction("Login", "SayHiIndex"); } else { PersonController._uModel = Session["UserInfo"] as sayHi.Model.sayHi_UserInfo; } } } }
using System; using AlternateLife.MongoMigration.Interfaces; using MongoDB.Bson; using MongoDB.Driver; namespace AlternateLife.MongoMigration { public abstract class MigrationBase : IMigration { /// <inheritdoc cref="IMigration"/> public string Name => GetType().Name; private IMigrationManager _migrationManager; /// <inheritdoc cref="IMigration"/> public abstract void Up(); /// <inheritdoc cref="IMigration"/> public abstract void Down(); /// <inheritdoc cref="IMigration"/> public virtual void Setup(IMigrationManager migrationManager) { _migrationManager = migrationManager; } /// <summary> /// Get a mongodb database by the name. /// </summary> /// <param name="database">Name of the database</param> /// <returns>MongoDB database instance or null if no database found</returns> /// <exception cref="ArgumentNullException">Thrown if database is null or empty</exception> public IMongoDatabase GetDatabase(string database) { return _migrationManager.GetDatabase(database); } /// <summary> /// Create a new collection in the database if this collection is not already existing. /// /// If the collection already exists, nothing will be changed. /// </summary> /// <param name="database">Database to create the collection in</param> /// <param name="collectionName">Name of the collection</param> protected void CreateCollectionIfNotExisting(IMongoDatabase database, string collectionName) { var collections = database.ListCollections(new ListCollectionsOptions() { Filter = new BsonDocument("name", collectionName) }); if (collections.Any()) { return; } database.CreateCollection(collectionName); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using Tweeter.Data.Models; using Tweeter.Mvc.Infrastructure.Mappings; using Tweeter.Mvc.Infrastructure.Validation; namespace Tweeter.Mvc.Areas.Admin.Models { public class TweetAdminViewModel : IMapFrom<Tweet> { [HiddenInput(DisplayValue = false)] public int Id { get; set; } [Required] [MaxLength(100)] public string Title { get; set; } [Required] [MaxLength(1000)] public string Content { get; set; } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; #nullable disable namespace BillingEnd.Models { public partial class db : DbContext { public db() { } public db(DbContextOptions<db> options) : base(options) { } public virtual DbSet<Cliente> Clientes { get; set; } public virtual DbSet<Factura> Facturas { get; set; } public virtual DbSet<Pedido> Pedidos { get; set; } public virtual DbSet<Producto> Productos { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { // #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. // optionsBuilder.UseSqlServer("Server=DESKTOP-8Q85QCQ;Database=BillingDatabase;trusted_connection=true; "); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "Modern_Spanish_CI_AS"); modelBuilder.Entity<Cliente>(entity => { entity.HasKey(e => e.CliId) .HasName("PK__Cliente__FFEFE14F9FB7B947"); entity.ToTable("Cliente"); entity.Property(e => e.CliId) .ValueGeneratedNever() .HasColumnName("cli_id"); entity.Property(e => e.CliCuil) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("cli_cuil"); entity.Property(e => e.CliDireccion) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("cli_direccion"); entity.Property(e => e.CliDni) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("cli_dni"); entity.Property(e => e.CliNum) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("cli_num"); entity.Property<string>("CliNombre") .HasColumnType("nvarchar(max)"); }); modelBuilder.Entity<Factura>(entity => { entity.HasKey(e => e.FacId) .HasName("PK__Factura__978BA2C3393726D7"); entity.ToTable("Factura"); entity.Property(e => e.FacId) .ValueGeneratedNever() .HasColumnName("fac_id"); entity.Property(e => e.FacDate) .HasColumnType("datetime") .HasColumnName("fac_date"); entity.Property(e => e.FacFkUser).HasColumnName("fac_fk_user"); entity.Property(e => e.FacTotal).HasColumnName("fac_total"); entity.HasOne(d => d.FacFkUserNavigation) .WithMany(p => p.Facturas) .HasForeignKey(d => d.FacFkUser) .HasConstraintName("FK_Factura_Cliente"); }); modelBuilder.Entity<Pedido>(entity => { entity.ToTable("Pedido"); entity.Property(e => e.Id) .ValueGeneratedNever() .HasColumnName("ID"); entity.Property(e => e.Bulto).HasColumnType("money"); entity.Property(e => e.CantidadDeBultos).HasColumnName("Cantidad_De_Bultos"); entity.Property(e => e.Etiqueta) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Factura).HasColumnName("factura"); entity.Property(e => e.Marca) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Medida).HasColumnType("money"); entity.Property(e => e.Producto).HasColumnName("producto"); entity.Property(e => e.Total).HasColumnType("decimal(18, 0)"); entity.Property(e => e.Unitario).HasColumnType("money"); entity.HasOne(d => d.FacturaNavigation) .WithMany(p => p.Pedidos) .HasForeignKey(d => d.Factura) .HasConstraintName("FK_Pedido_Factura"); }); modelBuilder.Entity<Producto>(entity => { entity.HasKey(e => e.ProdId); entity.ToTable("Producto"); entity.Property(e => e.ProdId) .ValueGeneratedNever() .HasColumnName("prod_id"); entity.Property(e => e.PrdoBulto).HasColumnName("prdo_bulto"); entity.Property(e => e.ProdCantidad).HasColumnName("prod_cantidad"); entity.Property(e => e.ProdEtiqueta) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("prod_etiqueta"); entity.Property(e => e.ProdMarca) .HasMaxLength(50) .IsUnicode(false) .HasColumnName("prod_marca"); entity.Property(e => e.ProdMedida).HasColumnName("prod_medida"); entity.Property(e => e.ProdUnitario).HasColumnName("prod_unitario"); entity.Property<double?>("CompraBulto").HasColumnType("float"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public GameObject playerPrefab; public GameObject turretPrefab; public float spawnThreshold = 0.3f; public float minTurretToPlayerDistance = 10f; public float maxTurretToPlayerDistance = 14f; private Rigidbody2D body; private float currentAngle = 0f; [SerializeField] private List<GameObject> killExplosionPrefabs; private void Start() { body = GetComponent<Rigidbody2D>(); } private void Update() { RotateInMovementDirection(); if(body.velocity.magnitude < spawnThreshold) { SpawnPlayer(); SpawnTurret(); } } private void RotateInMovementDirection() { var direction = body.velocity; float radialAngle = Mathf.Atan2(direction.x, direction.y); float degreeAngle = (180 / Mathf.PI) * radialAngle * -1; //as projectile is facing to the left by default, subtract 90 //degreeAngle -= 90; transform.RotateAround(transform.position, new Vector3(0, 0, 1), degreeAngle - currentAngle); currentAngle = degreeAngle; } private void SpawnPlayer() { Instantiate(playerPrefab, transform.position, Quaternion.identity); Destroy(this.gameObject); } private void SpawnTurret() { var distance = Mathf.Lerp(minTurretToPlayerDistance, maxTurretToPlayerDistance, Random.Range(0, 1)); var spawnPoint = EnemyController.instance.GetRandomPointInArena(); while((transform.position - spawnPoint).sqrMagnitude < distance * distance) { spawnPoint = EnemyController.instance.GetRandomPointInArena(); } Instantiate(turretPrefab, spawnPoint, Quaternion.identity); } private void OnTriggerEnter2D(Collider2D other) { if(other.gameObject.tag == "Enemy") { var destructable = other.gameObject.GetComponent<Destructable>(); if(destructable != null && !destructable.IsIndestructable) { foreach (GameObject prefab in killExplosionPrefabs) { Instantiate(prefab, other.transform.position, Quaternion.identity); } destructable.Die(); HighscoreController.instance.IncreaseScore(); } var enemyProjectile = other.gameObject.GetComponent<EnemyBullet>(); if(enemyProjectile != null) { enemyProjectile.DestroySelf(); } } } }
using Chapter2.ViewModel; using Microsoft.ProjectOxford.Vision; using System.Windows.Controls; namespace Chapter2.View { /// <summary> /// Interaction logic for ImageAnalysisView.xaml /// </summary> public partial class ImageAnalysisView : UserControl { public ImageAnalysisView() { InitializeComponent(); } private void VisualFeatures_SelectionChanged(object sender, SelectionChangedEventArgs e) { var vm = (MainViewModel)DataContext; vm.ImageAnalysisVm.SelectedFeatures.Clear(); foreach(VisualFeature feature in VisualFeatures.SelectedItems) { vm.ImageAnalysisVm.SelectedFeatures.Add(feature); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using Application.Command; using Application.DTO; using EFDataAccess; using Application.Exceptions; namespace EFCommands { public class EfAddUserCommand : EfBaseCommand, IAddUserCommand { public EfAddUserCommand(BlogContext context) : base(context) { } public void Execute(AddUserDto request) { var userDto = new Domain.User { IsDeleted = false, FirstName = request.FirstName, LastName = request.LastName, CreatedAt = DateTime.Now, ModifidedAt = null, UserName = request.UserName }; if(Context.Users.Any(u => u.UserName == userDto.UserName)) throw new EntityAllreadyExits("User"); try { Context.SaveChanges(); } catch (Exception) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Persistencia; using Entidade; namespace Negocio { public class NTipoAssociado { PTipoAssociado pTipoAssociado = new PTipoAssociado(); public ETipoAssociado Consultar(int identificador) { try { return pTipoAssociado.Consultar(identificador); } catch (Exception ex) { throw ex; } } public List<ETipoAssociado> Listar() { try { return pTipoAssociado.Listar(); } catch (Exception ex) { throw ex; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Thrift.Protocol; using Thrift.Collections; using Thrift.Server; using Thrift.Transport; using VssDisk.Datastruct; using Newtonsoft.Json; using System.IO; using VssDisk.DAL; using VssDisk.Example; using Vss; namespace VssDisk.BLL { public static class BLLControl { #region 目录结构 public static FileTreeNode RootFileTree; public static void SetRoot(FileTreeNode rootFileTree) { RootFileTree = rootFileTree; } public static void DestoryFile(string fileID) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.Del(GetValidator(), fileID); ClientAdapt.Close(); } public static bool SaveDirectoryInfo() { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); TCommandResult tResult = client.SaveFileTree(BLLControl.GetValidator(), JsonConvert.SerializeObject(RootFileTree)); ClientAdapt.Close(); return tResult == TCommandResult.SUCCESS; } public static bool Login(string vssID, string vssPsw, string vssApp) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); SetValidator(vssID, vssPsw, vssApp); TLoginResult tLoginState = client.Login(GetValidator()); ClientAdapt.Close(); return tLoginState != TLoginResult.SUCCESS; } public static FileTreeNode InitFileTree() { //进行通信,拉取用户的数据。 ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); string strTree = client.GetFileTree(GetValidator()); ClientAdapt.Close(); if (strTree == "None") { return ExampleData.getInitUserFileTree(); } else { return JsonConvert.DeserializeObject<FileTreeNode>(strTree); } } #endregion #region 验证信息 private static TValidator tValidator = null; public static void SetValidator(string vssID, string vssPsw, string vssAPP) { tValidator = new TValidator(vssID, vssPsw, vssAPP); } public static TValidator GetValidator() { return tValidator; } #endregion #region 文件系统存取 public static FileTreeNode UploadTextFile(string sContent, string nodeName ,string strID, string strInfo, ContentKind cKind, string strApp) { TFile file = new TFile(); file.FileContent = System.Text.Encoding.UTF8.GetBytes(sContent); file.FileId = strID; file.FileInfo = strInfo; file.FileKind = (TContentKind)cKind; file.FileSize = file.FileContent.Length; file.FromApp = strApp; file.FileOwner = GetValidator().VssID; ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); string strNewID = client.Put(GetValidator(), file); ClientAdapt.Close(); FileTreeNode fileTreeNode = new FileTreeNode(); System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); fileTreeNode.CreateDate = (uint)(DateTime.Now - startTime).TotalSeconds; fileTreeNode.FileID = strNewID; fileTreeNode.FileInfo = strInfo; fileTreeNode.FileKind = cKind; fileTreeNode.FileSize = (ulong)file.FileContent.Length; fileTreeNode.FromApp = strApp; fileTreeNode.SubNodes = null; fileTreeNode.FileOwner = GetValidator().VssID; fileTreeNode.NodeName = nodeName; return fileTreeNode; } /// <summary> /// 上传一个文件,返回节点描述符。 /// </summary> /// <param name="sPath"></param> /// <returns></returns> public static FileTreeNode UploadFile(string sPath, string strID, string strInfo, ContentKind cKind, string strApp) { TFile file = new TFile(); file.FileContent = File.ReadAllBytes(sPath); FileStream fs = File.OpenRead(sPath); file.FileId = strID; file.FileInfo = strInfo; file.FileKind = (TContentKind)cKind; file.FileSize = fs.Length; file.FromApp = strApp; file.FileOwner = GetValidator().VssID; ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); string strNewID = client.Put(GetValidator(), file); ClientAdapt.Close(); FileTreeNode fileTreeNode = new FileTreeNode(); System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); fileTreeNode.CreateDate = (uint)(DateTime.Now - startTime).TotalSeconds; fileTreeNode.FileID = strNewID; fileTreeNode.FileInfo = strInfo; fileTreeNode.FileKind = cKind; fileTreeNode.FileSize = (ulong)fs.Length; fileTreeNode.FromApp = strApp; fileTreeNode.SubNodes = null; fileTreeNode.FileOwner = GetValidator().VssID; fileTreeNode.NodeName = fs.Name.Substring(fs.Name.LastIndexOf("\\") + 1); return fileTreeNode; } /// <summary> /// 下载一个文件,返回描述符。 /// </summary> /// <param name="sPath"></param> /// <param name="file"></param> /// <returns></returns> public static TFile DownloadFile(string sPath, FileTreeNode file) { string strFID = file.FileID; ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); TFile tFile = client.Get(GetValidator(), strFID); ClientAdapt.Close(); File.WriteAllBytes(sPath, tFile.FileContent); return tFile; } #endregion #region 朋友管理 /// <summary> /// 获取朋友列表(单向) /// </summary> /// <returns></returns> public static List<string> GetFocusList() { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<string> retList = client.GetFocus(GetValidator()); ClientAdapt.Close(); return retList; } /// <summary> /// 获得关注我的朋友的列表(单向指我) /// </summary> /// <returns></returns> public static List<string> GetFollowList() { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<string> retList = client.GetFollow(GetValidator()); ClientAdapt.Close(); return retList; } /// <summary> /// 获取朋友列表(单向) /// </summary> /// <returns></returns> public static List<TFriendMessage> GetFriendMessage() { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<TFriendMessage> retList = client.GetFriendMessage(GetValidator(), 100); ClientAdapt.Close(); return retList; } /// <summary> /// 删除指定ID的朋友消息。 /// </summary> /// <param name="strMsgID"></param> public static void DelFriendMessage(string strMsgID) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.DelFriendMessage(GetValidator(), strMsgID); ClientAdapt.Close(); } /// <summary> /// 添加朋友列表(单向)会自动判断名字是否正确,如果不正确,则不加入!但不返回错误! /// </summary> /// <param name="list"></param> public static void AddFocus(List<string> list) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); TCommandResult res = client.AddFocus(GetValidator(), list); ClientAdapt.Close(); } /// <summary> /// 删除朋友列表(单向)会自动判断名字,不正确则忽略! /// </summary> /// <param name="list"></param> public static void DelFocus(List<string> list) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); TCommandResult res = client.DelFocus(GetValidator(), list); ClientAdapt.Close(); } #endregion #region 授权管理 /// <summary> /// 根据FileID ,获得列表。 /// </summary> /// <param name="fileID"></param> /// <returns></returns> public static List<string> GetFilePrivideList(string fileID) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<string> retList = client.GetFileProvideList(GetValidator(), fileID); ClientAdapt.Close(); return retList; } /// <summary> /// 授权一系列朋友访问某一文件 /// </summary> /// <param name="fileID"></param> /// <param name="listFriends"></param> public static void ProvideFile(string fileID, List<string> listFriends, string provideName) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.Provide(GetValidator(), fileID, listFriends, provideName); ClientAdapt.Close(); } /// <summary> /// 取消一系列朋友对某一个文件的访问授权 /// </summary> /// <param name="fileID"></param> /// <param name="listFriends"></param> public static void RecoverFile(string fileID, List<string> listFriends) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.Recover(GetValidator(), fileID, listFriends); ClientAdapt.Close(); } /// <summary> /// 公开某一个文件 /// </summary> /// <param name="fileID"></param> public static void PublishFile(string fileID, string provideName) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.Provide(GetValidator(), fileID, new List<string>(), provideName); ClientAdapt.Close(); } /// <summary> /// 取消公开某一个文件 /// </summary> /// <param name="fileID"></param> public static void RecallFile(string fileID) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); client.Recover(GetValidator(), fileID, new List<string>()); ClientAdapt.Close(); } /// <summary> /// 获取我发布给别人的 /// </summary> /// <param name="maxNum"></param> /// <returns></returns> public static List<TMessages> GetProvideItems(int maxNum) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<TMessages> retList = client.GetProvideItems(GetValidator(), maxNum); ClientAdapt.Close(); return retList; } /// <summary> /// 获取指定用户们的公开消息 /// </summary> /// <param name="listID"></param> /// <param name="maxNum"></param> /// <returns></returns> public static List<TMessages> GetPublishMessage(List<string> listID, int maxNum) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<TMessages> retList = client.GetPublishMessage(GetValidator(), listID, maxNum); ClientAdapt.Close(); return retList; } /// <summary> /// 获取被授权消息 /// </summary> /// <param name="listID"></param> /// <param name="maxNum"></param> /// <returns></returns> public static List<TMessages> GetProvideMessage(int maxNum) { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); List<TMessages> retList = client.GetProvideMessage(GetValidator(), maxNum); ClientAdapt.Close(); return retList; } #endregion #region 消息管理 /// <summary> /// 获取用户的几个内容量集 /// </summary> /// <returns></returns> public static TNumber GetNumber() { ClientAdapt.Open(); TVssService.Client client = ClientAdapt.GetClient(); TNumber tNumber = client.GetNumber(GetValidator()); ClientAdapt.Close(); return tNumber; } #endregion } }
using System; using System.IO; using System.IO.Compression; using System.Collections.Generic; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Auth; using System.Threading.Tasks; using Microsoft.DataStudio.SolutionDeploymentWorker.Models; using Microsoft.Azure; using System.Net; using System.Diagnostics; using Microsoft.DataStudio.Diagnostics; namespace Microsoft.DataStudio.SolutionDeploymentWorker.Actors { public class DataGenBundleActor { private readonly ILogger logger; public DataGenBundleActor(ILogger logger) { this.logger = logger; } private async Task ExtractDataGeneratorFromZip(string zipFile, string extractPath) { HttpWebRequest zipRequest = (HttpWebRequest)WebRequest.Create(zipFile); using (var respZip = (await zipRequest.GetResponseAsync()).GetResponseStream()) using (var archive = new ZipArchive(respZip, ZipArchiveMode.Read, false)) archive.ExtractToDirectory(extractPath); } private void UpdateConfigFile(string configFilePath, Configuration updateConfig) { var configFileContents = File.ReadAllText(configFilePath); configFileContents = configFileContents.Replace("[IngestEventHubName]", updateConfig.IngestEventHubName); configFileContents = configFileContents.Replace("[PublishEventHubName]", updateConfig.PublishEventHubName); configFileContents = configFileContents.Replace("[EventHubName]", updateConfig.EventHubName); configFileContents = configFileContents.Replace("[MLServiceLocaton]", updateConfig.MLServiceLocation); configFileContents = configFileContents.Replace("[MLEndpointKey]", updateConfig.MLEndpointKey); configFileContents = configFileContents.Replace("[StorageAccountConnectionString]", updateConfig.StorageAccountConnectionString); configFileContents = configFileContents.Replace("[EventHubConnectionString]", updateConfig.EventHubConnectionString); File.WriteAllText(configFilePath, configFileContents); } private async Task<string> ZipDataGenerator(string requestId, Generator generator, Configuration updateConfig) { var connectionString = CloudConfigurationManager.GetSetting("Microsoft.TableStorage.ConnectionString"); // [parvezp] Hack because currently when using local dev storage the copy step fails with 404 // I have asked the Storage team why this is happening and will remove this hack once have a // real solution in place if (connectionString.Contains("UseDevelopmentStorage=true")) { connectionString = CloudConfigurationManager.GetSetting("Microsoft.BlobStorage.ConnectionString"); } var sourceStorageAccount = CloudStorageAccount.Parse(connectionString); var sourceContainer = sourceStorageAccount.CreateCloudBlobClient().GetContainerReference(updateConfig.Generators.ContainerName); bool sourceContainerExists = await sourceContainer.ExistsAsync(); var extractPath = string.Empty; var configName = string.Empty; if (!sourceContainerExists) { throw new Exception(string.Format("DataGenbundleActor: Source container: {0} doesn't exist", sourceContainer.Name)); } else { try { var generatorLink = await sourceContainer.GetBlobReferenceFromServerAsync(generator.Name + ".zip"); var currentPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); var extractRoot = Path.Combine(currentPath, "DataGenerators"); Directory.CreateDirectory("DataGenerators"); extractPath = Path.Combine("DataGenerators", requestId); await ExtractDataGeneratorFromZip(generatorLink.Uri.AbsoluteUri, extractPath); configName = string.IsNullOrEmpty(generator.Config) ? generator.Name : generator.Config; var configFilePath = Path.Combine(extractPath, generator.Name, configName + ".exe.config"); if (!File.Exists(configFilePath)) { foreach (var subdir in Directory.GetDirectories(Path.Combine(extractPath, generator.Name))) { string testPath = Path.Combine(subdir, configName + ".exe.config"); if (File.Exists(testPath)) { configFilePath = testPath; break; } } } UpdateConfigFile(configFilePath, updateConfig); ZipFile.CreateFromDirectory(extractPath, requestId + ".zip"); return new Uri(Path.Combine(currentPath, requestId + ".zip")).LocalPath; } catch (Exception ex) { logger.Write(TraceEventType.Error, "Exception: {0} while updating the config for {1}", ex.Message, configName); throw; } finally { Directory.Delete(extractPath, true); } } } private byte[] GetBytesFromGeneratedZip(string base64ZipFileName) { return File.ReadAllBytes(base64ZipFileName); } private async Task<string> WriteToBlob(byte[] payload, string name, CloudBlobContainer container) { var permissions = new BlobContainerPermissions(); permissions.PublicAccess = BlobContainerPublicAccessType.Blob; container.SetPermissions(permissions); var blockBlob = container.GetBlockBlobReference(name); await blockBlob.UploadFromByteArrayAsync(payload, 0, payload.Length); var sasToken = blockBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTime.UtcNow, //Only creating shared access token with validity of 1 month. //These URLs are going to accessed to download zip files with exe //Once the download is complete end-user won't really have a need for this //URL. Should the validity of this sas token be further reduced? SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(1) }); return blockBlob.Uri.ToString() + sasToken; } public async Task<string> GenerateZipAndGetSASTokenizedUrl(Generator generator, Configuration updateConfig) { var blobClient = CloudStorageAccount.Parse(updateConfig.StorageAccountConnectionString).CreateCloudBlobClient(); var destinationContainer = blobClient.GetContainerReference(updateConfig.Generators.ContainerName); var pathToZip = await ZipDataGenerator(Guid.NewGuid().ToString(), generator, updateConfig); var url = await WriteToBlob(GetBytesFromGeneratedZip(pathToZip), generator.Name + ".zip", destinationContainer); File.Delete(pathToZip); this.logger.Write(TraceEventType.Information, "DataGenBundleActor: Created container {0} in storage and copied zip file from {1} to user blob storage", updateConfig.Generators.ContainerName, pathToZip); return url; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.Linq; using System.IO; public class PopulationController : MonoBehaviour { List<Brain> generation; GameData gd; DNA currentBestDNA; //TODO instead of just the best DNA take the Top x //When one is created, it has a chance to take any of their DNA intermingled //Then slight variations are created. // bot takes 3 joints from A and 1 joint from B // then all joints are slightly tweaked // or bot takes all 4 joints from B // then all joints are slightly tweaked. // TODO check on the variances of the sineFactors // Perhaps squeeze them into closer margins for less chaos // TODO try copying 1 joint's timings to other joints in the same bot // TODO try creating symetric bots // Potentially output the individual instructions to see what is going on public void Awake() { gd = GameObject.FindGameObjectWithTag("GameData").GetComponent<GameData>(); gd.pc = gameObject.GetComponent<PopulationController>(); generation = new List<Brain>(); } public void Start() { GenerateBrains(); // Invoke("GenerateRandomPopulation", 1); Invoke("TestLoop", 1); // Invoke("TEMPLOOP3456", gd.testingtime); } public void TestLoop() { // StreamReader reader = new StreamReader("C:\\iterBot\\DNA.txt"); currentBestDNA = gd.editorDNA; CopyBestDNAToBrains(); GeneratePopulationFromBestDNA(); Invoke("TEMPLOOP3456", gd.testingtime); } public void TEMPLOOP3456() { gd.generationNumber++; bool reset = false; if (Random.Range(0f, 1f) > .95f) { reset = true; } CalculateAllScores(); DeconstructPopulation(); gd.numberPerRow = 6; if(reset) { gd.testingtime = 10; gd.bestScore = 0; reset = false; } GenerateBrains(); CopyBestDNAToBrains(); GeneratePopulationFromBestDNA(); Invoke("TEMPLOOP3456", gd.testingtime); } public void GenerateRandomPopulation() { foreach (Brain bs in generation) bs.MakeRandomBody(); } public void GenerateBrains() { if(generation.Count != gd.numberPerRow*gd.numberPerRow) { foreach (Brain bs in generation) Destroy(bs.gameObject); generation.Clear(); for (int i = 0; i < gd.numberPerRow; i++) { for (int j = 0; j < gd.numberPerRow; j++) generation.Add(Instantiate(gd.brainPrefab, new Vector3(i * gd.distanceBetweenInstantiations, 0, j * gd.distanceBetweenInstantiations), Quaternion.identity).GetComponent<Brain>()); } } } public void GeneratePopulationFromBestDNA() { for(int i = 0; i < generation.Count; i++) { if (i == 0) generation.ElementAt(0).MakeDNABody(); else generation.ElementAt(i).MakeMutatedDNABody(); } } public void CalculateAllScores() { foreach (Brain bs in generation) { float curScore = bs.CalculateCurrentScore(); if (curScore > gd.bestScore) { gd.bestScore = curScore; currentBestDNA = bs.GetDNA(); Debug.Log("best: " + gd.bestScore); } } } public void DeconstructPopulation() { foreach (Brain bs in generation) bs.DeconstructBody(); } public void ToggleAllRenders() { foreach (Brain bs in generation) bs.ToggleAllRenderers(); } public void ToggleAllMuscles() { foreach (Brain bs in generation) bs.ToggleAllMuscles(); } public void CopyBestDNAToBrains() { for (int i = 0; i < generation.Count; i++) generation.ElementAt(i).SetDNA(currentBestDNA); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ordenamientos : MonoBehaviour { void imprimir(int[] arrayImprimir) { for (int i = 0; i < arrayImprimir.Length; i++) { print(arrayImprimir[i] + " "); } } int[] swap(int[] arrayTemp, int iTemp, int jTemp) { int numCambio = arrayTemp[jTemp-1]; arrayTemp[jTemp-1] = arrayTemp[jTemp]; arrayTemp[jTemp] = numCambio; return arrayTemp; } public void BubbleSort(int[] arrayList) { if (arrayList.Length > 0) { for (int a = 0; a < arrayList.Length; a++) { for (int i = 1; i < arrayList.Length; i++) { int aux = arrayList[i]; for (int j = i - 1; j >= 0 && arrayList[j] > aux; j--) { swap(arrayList, j + 1, j); } } } } imprimir(arrayList); } public void insertSort(int[] array) { for (int i = 0; i < array.Length-1; i++) { for (int j = i+1; j > 0 && array[j-1] > array[j]; j--) { array = swap(array, i, j); } } imprimir(array); } // Start is called before the first frame update void Start() { // print("Gatito"); /*var tiempoInicial = Time.realtimeSinceStartup; "Time for MyExpensiveFunction: " + (Time.realtimeSinceStartup - tiempoInicial)"; BubbleSort(arrayImpr);*/ } // Update is called once per frame void Update() { } }
using System; using System.Windows.Forms; namespace MegaDesk_4_Makram_Ibrahim { public partial class DisplayQuote : Form { public DisplayQuote(string clientName, string quoteDate, decimal width, decimal depth, int drawers, SurfaceMaterials material, int rushOptions, decimal quotePrice) { string rushOrder; InitializeComponent(); if (rushOptions == 0) { rushOrder = "none"; } else { rushOrder = rushOptions.ToString() + " Days"; } try { DisplQuote.Text = "-----------------------------------------------------------------------" + Environment.NewLine + "Customer Name: " + clientName + Environment.NewLine + "-----------------------------------------------------------------------" + Environment.NewLine + "Desk Width: " + width + " inches" + Environment.NewLine + "-----------------------------------------------------------------------" + Environment.NewLine + "Desk Depth: " + depth + " inches" + Environment.NewLine + "-----------------------------------------------------------------------" + Environment.NewLine + "Desk Drawers: " + drawers + Environment.NewLine + "-----------------------------------------------------------------------" + Environment.NewLine + "Desk Material: " + material + Environment.NewLine + "------------------------------------------------------------------------" + Environment.NewLine + "Rush Days: " + rushOrder + Environment.NewLine + "-----------------------------------------------------------------------" + Environment.NewLine; quotePrices.Text = "$" + quotePrice.ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Writing the file"); } } private void QuoteBtn_Click(object sender, EventArgs e) { var mainMenu = (MainMenu)Tag; mainMenu.Show(); Close(); } private void label8_Click(object sender, EventArgs e) { } } }
using LiteDB; using TreeStore.Messaging; using TreeStore.Model; namespace TreeStore.LiteDb { public class TagRepository : LiteDbRepositoryBase<Tag>, ITagRepository { public const string CollectionName = "tags"; // private readonly FacetRepository facets; private readonly IChangedMessageBus<ITag> eventSource; public TagRepository(LiteRepository repo, IChangedMessageBus<Messaging.ITag> eventSource) : base(repo, CollectionName) { repo.Database .GetCollection(CollectionName) .EnsureIndex( name: nameof(Tag.Name), expression: $"LOWER($.{nameof(Tag.Name)})", unique: true); this.eventSource = eventSource; } protected override ILiteCollection<Tag> IncludeRelated(ILiteCollection<Tag> from) => from; public override Tag Upsert(Tag entity) { this.eventSource.Modified(base.Upsert(entity)); return entity; } public override bool Delete(Tag tag) { if (base.Delete(tag)) { this.eventSource.Removed(tag); return true; } return false; } public Tag FindByName(string name) => this.LiteCollection() .Query() .Where(t => t.Name.Equals(name)) .FirstOrDefault(); } }
namespace MeterReadings.Schema { public class MeterReadingLenient { public override string ToString() { return $"{nameof(AccountId)}: {AccountId}, {nameof(MeterReadingDateTime)}: {MeterReadingDateTime}, {nameof(MeterReadValue)}: {MeterReadValue}"; } public string AccountId { get; set; } public string MeterReadingDateTime { get; set; } public string MeterReadValue { get; set; } public string Errors { get; set; } } }
using System; using System.Collections.Generic; namespace ESERCIZILIBRO { class Program { static void Main(string[] args) { Console.WriteLine("Inserire numeri del vettore"); int n = int.Parse(Console.ReadLine()); List<int> list = new List<int>(n); List<int> duplicati = new List<int>(); for (int i = 0; i < n; i++) { Console.WriteLine("Inserisci un numero"); int n1 = int.Parse(Console.ReadLine()); if (list.Contains(n1)) duplicati.Add(n1); list.Add(n1); } for (int i = 0; i < duplicati.Count; i++) { Console.WriteLine($"Il numero {duplicati[i]} è doppione."); } Console.ReadLine(); } } }
namespace WebApp.Models { public interface IPhoneNumber { string Label { get; } string Number { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EquipmentPanel : MonoBehaviour { [SerializeField] EquippableItemSlot[] slots; public OnRightClickSlotEvent onRightClickEvent; private void Awake() { if (onRightClickEvent == null) onRightClickEvent = new OnRightClickSlotEvent(); } private void Start() { slots = GetComponentsInChildren<EquippableItemSlot>(); for(int i = 0; i < slots.Length; i++) { slots[i].onRightClickEvent = onRightClickEvent; } } public bool AddItem(EquippableItem item, out EquippableItem previousItem) { EquippableItemSlot slot = TryGetSlot(item.EquipmentType); // No slot was found, so return false if(slot == null) { previousItem = null; return false; } // Assign item to the slot previousItem = (slot.Item != null) ? (EquippableItem)slot.Item : null; slot.Item = item; // Was no space Available return true; } public BasicItem RemoveItem(string itemID) { for(int i = 0; i < slots.Length; i++) { BasicItem item = slots[i].Item; if(item != null && item.ID == itemID) { slots[i].Item = null; return item; } } return null; } public bool RemoveItem(BasicItem item) { for (int i = 0; i < slots.Length; i++) { if (slots[i].Item == item) { slots[i].Item = null; return true; } } return false; } private EquippableItemSlot TryGetSlot(EquipmentType equipmentType) { EquippableItemSlot targetSlot = null; for(int i = 0; i < slots.Length; i++) { if(slots[i].EquipmentType == equipmentType) { if (targetSlot == null) targetSlot = slots[i]; // Assign the new target slot if it is empty if (targetSlot.Item != null && slots[i].Item == null) targetSlot = slots[i]; } } return targetSlot; } }
using Castle.Core; using Castle.MicroKernel.Lifestyle; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Castle.Windsor.InstallerPriority; using Castle.Windsor.ServiceCollection; using Commands; using FastSQL.App.Interfaces; using FastSQL.App.Managers; using FastSQL.Core; using FastSQL.Core.Loggers; using FastSQL.Core.Middlewares; using FastSQL.Core.UI.Interfaces; using FastSQL.Sync.Core; using FastSQL.Sync.Core.Factories; using FastSQL.Sync.Core.Indexer; using FastSQL.Sync.Core.IndexExporters; using FastSQL.Sync.Core.Mapper; using FastSQL.Sync.Core.MessageDeliveryChannels; using FastSQL.Sync.Core.Puller; using FastSQL.Sync.Core.Pusher; using FastSQL.Sync.Core.Queuers; using FastSQL.Sync.Core.Reporters; using FastSQL.Sync.Core.Repositories; using FastSQL.Sync.Core.Settings; using FastSQL.Sync.Core.Workflows; using FastSQL.Sync.Workflow; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Prism.Events; using Serilog; using Serilog.Core; using st2forget.migrations; using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Resources; using System.Windows; using System.Windows.Controls; using WorkflowCore.Interface; using WorkflowCore.Models; namespace FastSQL.App { [InstallerPriority(0)] public class WindsorInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { //var descriptor = container.Resolve<FromAssemblyDescriptor>(); var assembly = this.GetType().Assembly; var assemblyName = assembly.GetName().Name; var assemblyFilter = new AssemblyFilter(AppDomain.CurrentDomain.BaseDirectory); assemblyFilter = assemblyFilter.FilterByName(a => !a.Name.StartsWith("System.") && !a.Name.StartsWith("Microsoft")); var assemblyDescriptor = Classes.FromAssemblyInDirectory(assemblyFilter); container.Register(Component.For<FromAssemblyDescriptor>().UsingFactoryMethod(() => assemblyDescriptor).LifestyleSingleton()); container.Register(Component.For<ResourceManager>().UsingFactoryMethod(p => new ResourceManager($"{assemblyName}.Properties.Resources", assembly)).LifestyleSingleton()); container.Register(Component.For(typeof(DbConnection), typeof(IDbConnection)).UsingFactoryMethod((p) => { var conf = p.Resolve<IConfiguration>(); var connectionString = conf.GetConnectionString("__MigrationDatabase"); var builder = new SqlConnectionStringBuilder(connectionString); builder.MaxPoolSize = 200; var conn = new SqlConnection(builder.ConnectionString); conn.Open(); return conn; }).LifestyleTransient()); //container.Register(Component.For<DbTransaction>().UsingFactoryMethod((c) => { // var conn = c.Resolve<DbConnection>(); // return conn.BeginTransaction(); //}).LifestyleCustom<ScopedLifestyleManager>()); container.Register(Component.For<ResolverFactory>().ImplementedBy<ResolverFactory>().LifestyleSingleton()); container.Register(Component.For<SynchronizerFactory>().ImplementedBy<SynchronizerFactory>().LifestyleTransient()); container.Register(assemblyDescriptor .BasedOn<IRichProvider>() .WithService.Select(new Type[] { typeof(IRichProvider) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Singleton))); container.Register(assemblyDescriptor .BasedOn<IRichAdapter>() .WithService.Select(new Type[] { typeof(IRichAdapter) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IOptionManager>() .WithService.Select(new Type[] { typeof(IOptionManager) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Puller container.Register(assemblyDescriptor .BasedOn<IPuller>() .WithService.Select(new Type[] { typeof(IPuller) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Indexer container.Register(assemblyDescriptor .BasedOn<IIndexer>() .WithService.Select(new Type[] { typeof(IIndexer) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Pusher container.Register(assemblyDescriptor .BasedOn<IPusher>() .WithService.Select(new Type[] { typeof(IPusher) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Pusher container.Register(assemblyDescriptor .BasedOn<IMapper>() .WithService.Select(new Type[] { typeof(IMapper) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Repositories container.Register(assemblyDescriptor .BasedOn<BaseRepository>() .WithService.Select(new Type[] { typeof(BaseRepository) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); // Processors container.Register(assemblyDescriptor .BasedOn<IProcessor>() .WithService.Select(new Type[] { typeof(IProcessor) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Singleton))); container.Register(assemblyDescriptor .BasedOn<ISettingProvider>() .WithService.Select(new Type[] { typeof(ISettingProvider) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IIndexExporter>() .WithService.Select(new Type[] { typeof(IIndexExporter) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IPageManager>() .WithService.Select(new Type[] { typeof(IPageManager) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<ICommand>() .WithService.Select(new Type[] { typeof(ICommand) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<ITransformer>() .WithService.Select(new Type[] { typeof(ITransformer) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IMigrationExecuter>() .WithService.Select(new Type[] { typeof(IMigrationExecuter) }) .WithServiceSelf() .WithServiceAllInterfaces() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<ILogEventSink>() .WithService.Select(new Type[] { typeof(ILogEventSink) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IMiddleware>() .WithService.Select(new Type[] { typeof(IMiddleware) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IReporter>() .WithService.Select(new Type[] { typeof(IReporter) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IMessageDeliveryChannel>() .WithService.Select(new Type[] { typeof(IMessageDeliveryChannel) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(Component.For<JsonSerializer>().UsingFactoryMethod(() => new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver() }).LifestyleSingleton()); container.Register(assemblyDescriptor .BasedOn<BaseViewModel>() .WithService.Select(new Type[] { typeof(BaseViewModel) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<Window>() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<UserControl>() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(Component.For<IConfigurationBuilder>().UsingFactoryMethod((p) => { var appResource = p.Resolve<IApplicationManager>(); var builder = new ConfigurationBuilder() .SetBasePath(appResource.BasePath) .AddJsonFile("appsettings.json", true, true); return builder; }).LifestyleTransient()); container.Register(Component.For<IConfiguration>().UsingFactoryMethod((p) => p.Resolve<IConfigurationBuilder>().Build()).LifestyleTransient()); container.Register(Component.For<SettingManager>().ImplementedBy<SettingManager>().LifestyleSingleton()); container.Register(Component.For<IndexerManager>().ImplementedBy<IndexerManager>().LifestyleTransient()); container.Register(Component.For<PusherManager>().ImplementedBy<PusherManager>().LifestyleTransient()); container.Register(Component.For<MapperManager>().ImplementedBy<MapperManager>().LifestyleTransient()); container.Register(Component.For<QueueChangesManager>().ImplementedBy<QueueChangesManager>().LifestyleTransient()); container.Register(Component.For<IEventAggregator>().ImplementedBy<EventAggregator>().LifestyleSingleton()); container.Register(Component.For<IApplicationManager>().ImplementedBy<ApplicationManager>().LifestyleSingleton()); container.Register(Component.For<LoggerFactory>().ImplementedBy<LoggerFactory>().LifestyleTransient()); container.Register(Component.For<LoggerConfiguration>().UsingFactoryMethod(p => new LoggerConfiguration() .Enrich.FromLogContext()).LifestyleTransient()); container.Register(Component.For<SyncService>().ImplementedBy<SyncService>().LifestyleSingleton()); container.Register(assemblyDescriptor .BasedOn<StepBody>() .WithService.Select(new Type[] { typeof(StepBody) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn<IWorkflow>() .WithService.Select(new Type[] { typeof(IWorkflow) }) .WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(assemblyDescriptor .BasedOn(typeof(IWorkflow<>)) .WithService.Select(new Type[] { typeof(IBaseWorkflow), typeof(IGenericWorkflow) }) //.WithServiceAllInterfaces() .WithServiceSelf() .Configure(x => x.LifeStyle.Is(LifestyleType.Transient))); container.Register(Component.For<WorkingSchedules>().ImplementedBy<WorkingSchedules>().LifeStyle.Singleton); var services = new WindsorServiceCollection(container); services.AddLogging(c => c.AddSerilog(dispose: true)); services.AddWorkflow(o => { var conf = container.Resolve<IConfiguration>(); var connectionString = conf.GetConnectionString("__MigrationDatabase"); o.UseSqlServer(connectionString, true, true); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class mainManager : MonoBehaviour { public bool startTrigger = false; public PlayerScript ps; public Text timeLabel; public float time = 0f; public GameObject bloom; // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (!startTrigger && Input.GetKey(KeyCode.Space)) { startTrigger = true; time = 0; bloom.SetActive(true); } if (!startTrigger && Input.GetKey(KeyCode.R)) { string temp = SceneManager.GetActiveScene().name; SceneManager.LoadScene(temp); //落ちる ゆうあい } if (startTrigger) { time += Time.deltaTime; if (time > 65) { //ResultSceneへ } else if (time > 60) { ps.Score(); FinishGame(); } else { timeLabel.text = (60 - time).ToString("f1"); } } } public void FinishGame() { time = 60; timeLabel.text = "おしまい!"; startTrigger = false; GameUtility.GoResultScene(ps.resultArray); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvvmTest.HtmlAgility { public class NewsModel { /// <summary> /// /// </summary> public int ID { get; set; } /// <summary> /// /// </summary> public string Title { get; set; } /// <summary> /// /// </summary> public string Tips { get; set; } /// <summary> /// /// </summary> public string TitleUrl { get; set; } /// <summary> /// /// </summary> public string Author { get; set; } /// <summary> /// /// </summary> public string CreateTime { get; set; } } }
using System.Web.Mvc; using System.Web.Routing; namespace FacultyV3.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { RouteTable.Routes.LowercaseUrls = true; RouteTable.Routes.AppendTrailingSlash = true; routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "contact", url: "lien-he/{id}", defaults: new { controller = "Contact", action = "ContactView", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "introduceK", url: "gioi-thieu/gioi-thieu-khoa/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "34251e7f-79d1-4fc0-9ad7-ab7900db522a" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "group", url: "gioi-thieu/co-cau-to-chuc/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "F83DE66C-CA9D-4E6E-B8BC-AB7900F16AC6" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "scientific regulations ", url: "nghien-cuu-khoa-hoc/quy-dinh-khoa-hoc/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "aa2f7477-227b-4147-815b-ab7a006f8205" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "general information", url: "nghien-cuu-khoa-hoc/bieu-mau-khoa-hoc/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "df6f8012-7463-452c-a058-ab7a006eb9e4" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "DEPARTMENT", url: "gioi-thieu/to-bo-mon/{id}", defaults: new { controller = "Detail_Menu", action = "ListDepartment", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "LECTURER", url: "gioi-thieu/can-bo-giang-vien/{id}", defaults: new { controller = "Lecturer", action = "LecturerView", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "ADMISSION", url: "tuyen-sinh/{id}", defaults: new { controller = "Detail_Menu", action = "ListAdmission", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "RESOURCE", url: "hoc-lieu/{id}", defaults: new { controller = "Detail_Menu", action = "ListResource", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); //routes.MapRoute( // name: "group", // url: "sinh-vien/doan-thanh-nien/{id}", // defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "F83DE66C-CA9D-4E6E-B8BC-AB7900F16AC6" }, // namespaces: new[] { "FacultyV3.Web.Controllers" } //); routes.MapRoute( name: "doan-thanh-nien", url: "sinh-vien/doan-thanh-nien/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", id = "F4720E44-9366-49DD-82BD-ABBF010B367D" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "so-tay-sinh-vien", url: "sinh-vien/so-tay-sinh-vien", defaults: new { controller = "Detail_Menu", action = "ListNoteBook" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "CONFERENCE", url: "hoi-nghi-khoa-hoc", defaults: new { controller = "Detail_Menu", action = "ListConference" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "FORM", url: "sinh-vien/bieu-mau", defaults: new { controller = "Detail_Menu", action = "ListForm" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "OLD STUDENT", url: "sinh-vien/cuu-sinh-vien", defaults: new { controller = "Student", action = "StudentView" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "MENU", url: "home/{category}/{title}/{id}", defaults: new { controller = "Detail_Menu", action = "DetailMenu", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "New News", url: "tin-moi-nhat/{title}/{id}", defaults: new { controller = "Detail_News", action = "DetailNews", title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "LECTURER DETAIL", url: "can-bo-giang-vien/{title}/{code}", defaults: new { controller = "Lecturer", action = "DetailLecturer", title = UrlParameter.Optional, code = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWSS", url: "thong-tin-thong-bao/", defaults: new { controller = "Detail_News", action = "ListNewss" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "WORK", url: "tuyen-dung-viec-lam", defaults: new { controller = "Detail_News", action = "ListWorks" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "YOUTH_GROUP", url: "doan-thanh-nien", defaults: new { controller = "Detail_News", action = "ListYouth_Group" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWS_FROM_THE_MINISTRY", url: "tin-tuc-chuyen-nganh", defaults: new { controller = "Detail_News", action = "ListMinistry" }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWS_FROM_FACULTY", url: "tin-tu-khoa/{id}", defaults: new { controller = "Detail_News", action = "ListFaculty", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWS_FROM_UNIVERSIT", url: "tin-tu-truong/{id}", defaults: new { controller = "Detail_News", action = "ListUniversity", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWS_FROM_PARTY_CELL", url: "tin-tu-chi-bo/{id}", defaults: new { controller = "Detail_News", action = "ListPartyCell", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "NEWS_FROM_UNION", url: "tin-tu-cong-doan/{id}", defaults: new { controller = "Detail_News", action = "ListUnion", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "Education Program", url: "dao-tao/chuong-trinh-dao-tao/{id}", defaults: new { controller = "Detail_Menu", action = "ListEducation_Program", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "Trainning Sector", url: "dao-tao/nganh-dao-tao/{id}", defaults: new { controller = "Detail_Menu", action = "ListTraining_Sector", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "DETAILNEWS", url: "news/{category}/{title}/{id}", defaults: new { controller = "Detail_News", action = "DetailNews", category = UrlParameter.Optional, title = UrlParameter.Optional, id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "FacultyV3.Web.Controllers" } ); } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using UnityEngine.UI; public class PauseMenuScript : MonoBehaviour { private GameObject[] m_pauseObjects; private GameObject[] m_gameOverObjects; private GameObject m_Panel; public Slider soundSlider; private GameObject m_buildTowerHUD; private GameObject m_totemHUD; private GameObject m_upgradeTower; public GameObject m_checkTextField; public GameObject m_waveText; // Use this for initialization void Start () { Time.timeScale = 1; m_pauseObjects = GameObject.FindGameObjectsWithTag("ShowOnPause"); m_gameOverObjects = GameObject.FindGameObjectsWithTag("ShowOnGameOver"); m_Panel = GameObject.FindGameObjectWithTag("ShowOnPauseAndGameOver"); hidePaused(); m_buildTowerHUD = GameObject.Find("HUDCanvas").transform.FindChild("BuildTowerHUD").gameObject; m_totemHUD = GameObject.Find("HUDCanvas").transform.FindChild("TotemHUD").gameObject; m_upgradeTower = GameObject.Find("HUDCanvas").transform.Find("UpgradeTowerHUD").gameObject; //m_checkTextField = GameObject.Find("HUDCanvas").transform.Find("CheckTextField").gameObject; //m_waveText = GameObject.Find("HUDCanvas").transform.Find("WaveTextBox").gameObject; } // Update is called once per frame void Update () { } public void Reload() { Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); } public void pauseControl() { if(Time.timeScale == 1) { Time.timeScale = 0; m_checkTextField.SetActive(false); m_buildTowerHUD.SetActive(false); m_totemHUD.SetActive(false); m_upgradeTower.SetActive(false); showPaused(); } else if(Time.timeScale == 0) { Time.timeScale = 1; hidePaused(); } } public void showPaused() { m_Panel.SetActive(true); foreach (GameObject g in m_pauseObjects) g.SetActive(true); foreach (GameObject g in m_gameOverObjects) g.SetActive(false); m_waveText.SetActive(false); } public void hidePaused() { m_Panel.SetActive(false); foreach (GameObject g in m_pauseObjects) g.SetActive(false); m_waveText.SetActive(true); } /* public void adjustSound() { AudioListener.volume = soundSlider.value; } */ public void LoadScene(string sceneName) { SceneManager.LoadScene(sceneName); } public void QuitGame() { Application.Quit(); } }
 #region Usings using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Zengo.WP8.FAS.Helpers; #endregion namespace Zengo.WP8.FAS.Controls.ListItems { public partial class PitchItem : UserControl { public PitchItem() { InitializeComponent(); LayoutRoot.ManipulationStarted += Animation.Standard_ManipulationStarted_1; LayoutRoot.ManipulationCompleted += Animation.Standard_ManipulationCompleted_1; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace ToyTwoToolbox { class DarkThemeMenuRender : ToolStripSystemRenderer { public Color DarkTheme_UI_MenuBack = Color.FromArgb(40, 40, 40); public Color DarkTheme_UI_Text = Color.FromArgb(240, 240, 240); public Color DarkTheme_UI_MenuSel = Color.FromArgb(50, 50, 50); protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { e.ToolStrip.BackColor = DarkTheme_UI_MenuBack;//realistically this should only be done once lmao Rectangle rectangle = new Rectangle(Point.Empty, e.Item.Size); if (!e.Item.Selected) { e.Graphics.FillRectangle(new SolidBrush(DarkTheme_UI_MenuBack), rectangle); } else { if (e.Item.Enabled) { this.RenderSelectedButtonFill(e.Graphics, rectangle); } else { e.Graphics.FillRectangle(new SolidBrush(DarkTheme_UI_MenuBack), rectangle); } } } protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { if (e.Item is ToolStripMenuItem) { //AndAlso (e.Item.Selected OrElse e.Item.Pressed) Then e.TextColor = DarkTheme_UI_Text; } base.OnRenderItemText(e); } protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { e.ToolStrip.BackColor = DarkTheme_UI_MenuBack; //AddHandler e.ToolStrip.Items(e.ToolStrip.Items.IndexOf(e.Item)).Paint, AddressOf ExtendedToolStripSeparator_Paint 'dont do this now bcuz of above Rectangle rectangle = new Rectangle(Point.Empty, e.Item.Size); e.Graphics.FillRectangle(new SolidBrush(DarkTheme_UI_MenuBack), rectangle); this.RenderSeparatorInternal(e.Graphics, e.Item, new Rectangle(Point.Empty, e.Item.Size), e.Vertical); } public void ExtendedToolStripSeparator_Paint(object sender, PaintEventArgs e) { ToolStripSeparator toolStripSeparator = (ToolStripSeparator)sender; e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, toolStripSeparator.Width + 15, toolStripSeparator.Height + 15); } protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) { if (e.Item is ToolStripDropDownItem) { e.ArrowColor = DarkTheme_UI_Text; } base.OnRenderArrow(e); } private void RenderSeparatorInternal1(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) { VisualStyleElement separator = vertical ? VisualStyleElement.ToolBar.SeparatorHorizontal.Normal : VisualStyleElement.ToolBar.SeparatorVertical.Normal; if (ToolStripManager.VisualStylesEnabled && (VisualStyleRenderer.IsElementDefined(separator))) { VisualStyleRenderer visualStyleRenderer = new VisualStyleRenderer("ExplorerBar", 0, 0); visualStyleRenderer.SetParameters(separator.ClassName, separator.Part, 1); //GetItemState(item)) visualStyleRenderer.DrawBackground(g, bounds); } else { Color foreColor = item.ForeColor; Color backColor = item.BackColor; Pen foreColorPen = SystemPens.ControlDark; bool disposeForeColorPen = GetPen(foreColor, ref foreColorPen); try { if (vertical) { if (bounds.Height >= 4) { // scoot down 2PX and start drawing bounds.Inflate(0, -2); } bool rightToLeft = (item.RightToLeft == RightToLeft.Yes); Pen leftPen = rightToLeft ? SystemPens.ButtonHighlight : foreColorPen; Pen rightPen = rightToLeft ? foreColorPen : SystemPens.ButtonHighlight; // Draw dark line int startX = bounds.Width / 2; g.DrawLine(leftPen, startX, bounds.Top, startX, bounds.Bottom); // Draw highlight one pixel to the right startX += 1; g.DrawLine(rightPen, startX, bounds.Top, startX, bounds.Bottom); } else { // // horizontal separator if (bounds.Width >= 4) { // scoot over 2PX and start drawing bounds.Inflate(-2, 0); } // Draw dark line int startY = bounds.Height / 2; g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right, startY); // Draw highlight one pixel to the right startY += 1; g.DrawLine(SystemPens.ButtonHighlight, bounds.Left, startY, bounds.Right, startY); } } finally { if (disposeForeColorPen && foreColorPen != null) { foreColorPen.Dispose(); } } } } private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) { Pen foreColorPen = SystemPens.ControlDark; Pen highlightColorPen = SystemPens.ButtonHighlight; bool isASeparator = item is ToolStripSeparator; bool isAHorizontalSeparatorNotOnDropDownMenu = false; if (isASeparator) { if (vertical) { if (!item.IsOnDropDown) { // center so that it matches office bounds.Y += 3; bounds.Height = Math.Max(0, bounds.Height - 6); } } else { // offset after the image margin ToolStripDropDownMenu dropDownMenu = item.GetCurrentParent() as ToolStripDropDownMenu; if (dropDownMenu != null) { if (dropDownMenu.RightToLeft == RightToLeft.No) { // scoot over by the padding (that will line you up with the text - but go two PX before so that it visually looks // like the line meets up with the text). bounds.X += dropDownMenu.Padding.Left - 2; bounds.Width = dropDownMenu.Width - bounds.X; } else { // scoot over by the padding (that will line you up with the text - but go two PX before so that it visually looks // like the line meets up with the text). bounds.X += 2; bounds.Width = dropDownMenu.Width - bounds.X - dropDownMenu.Padding.Right; } } else { isAHorizontalSeparatorNotOnDropDownMenu = true; } } } try { if (vertical) { if (bounds.Height >= 4) { // scoot down 2PX and start drawing bounds.Inflate(0, -2); } bool rightToLeft = (item.RightToLeft == RightToLeft.Yes); Pen leftPen = rightToLeft ? highlightColorPen : foreColorPen; Pen rightPen = rightToLeft ? foreColorPen : highlightColorPen; // Draw dark line int startX = bounds.Width / 2; g.DrawLine(leftPen, startX, bounds.Top, startX, bounds.Bottom - 1); // Draw highlight one pixel to the right startX += 1; g.DrawLine(rightPen, startX, bounds.Top + 1, startX, bounds.Bottom); } else { // // horizontal separator // Draw dark line if (isAHorizontalSeparatorNotOnDropDownMenu && bounds.Width >= 4) { // scoot down 2PX and start drawing bounds.Inflate(-2, 0); } int startY = bounds.Height / 2; g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right - 1, startY); if ((!isASeparator) || isAHorizontalSeparatorNotOnDropDownMenu) { // Draw highlight one pixel to the right startY += 1; g.DrawLine(highlightColorPen, bounds.Left + 1, startY, bounds.Right - 1, startY); } } } finally { //If disposeForeColorPen AndAlso foreColorPen IsNot Nothing Then foreColorPen.Dispose() //If disposeHighlightColorColorPen AndAlso highlightColorPen IsNot Nothing Then highlightColorPen.Dispose() } } private static bool GetPen(Color color, ref Pen pen) { if (color.IsSystemColor) { pen = SystemPens.FromSystemColor(color); return false; } else { pen = new Pen(color); return true; } } private void RenderSelectedButtonFill(Graphics g, Rectangle bounds) { if (bounds.Width == 0 || bounds.Height == 0) { return; } g.FillRectangle(new System.Drawing.SolidBrush(DarkTheme_UI_MenuSel), bounds); //g.FillRectangle(New Drawing2D.LinearGradientBrush( // bounds, // Me.ColorTable.ButtonSelectedGradientBegin, // Me.ColorTable.ButtonSelectedGradientEnd, // Drawing2D.LinearGradientMode.Vertical), // bounds) } protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { base.OnRenderSplitButtonBackground(e); DrawArrow(new ToolStripArrowRenderEventArgs(e.Graphics, e.Item as ToolStripSplitButton, ((ToolStripSplitButton)e.Item).DropDownButtonBounds, Color.FromArgb(240,240,240), ArrowDirection.Down)); //ToolStripSplitButton btn = e.Item as ToolStripSplitButton; //Rectangle rc = btn.DropDownButtonBounds; ////base.DrawArrow(new ToolStripArrowRenderEventArgs(e.Graphics, e.Item, rc, Color.Black, ArrowDirection.Right)); // int x = rc.Left + rc.Width - 8; // int y = rc.Top + rc.Height / 2; // Point[] arrow = new Point[3]; // arrow[0] = new Point(x, y - 5); // arrow[1] = new Point(x + 6, y); // arrow[2] = new Point(x, y + 5); // e.Graphics.FillPolygon(Brushes.Black, arrow); } public void DrawArrow(ToolStripArrowRenderEventArgs e) { OnRenderArrow(e); } protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { } } }
using Foundation; using System; using UIKit; using System.Collections.Generic; namespace ratings.iOS { public partial class PlayersViewController : UITableViewController { public List<Player> Players; public PlayersViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); Players = PlayerRepository.GetPlayers(); //TableView.RegisterClassForCellReuse(UITableViewCellStyle.Subtitle , "PlayerCell"); TableView.Source = new PlayersDataSource(this); } public class PlayersDataSource : UITableViewSource { PlayersViewController controller; public PlayersDataSource(PlayersViewController controller) { this.controller = controller; } public override nint NumberOfSections(UITableView tableView) { return 1; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell("CustomCell") as CustomCell; Player player = controller.Players[indexPath.Row] as Player; cell.UpdateCell(player.Name, player.Game, imageForRating(player.Rating)); return cell; } public override nint RowsInSection(UITableView tableview, nint section) { return controller.Players.Count; } public UIImage imageForRating(int rating) { string imageName = $"{rating}Stars"; return UIImage.FromBundle(imageName); } } [Action ("CancelToPlayersViewController:")] public void CancelToPlayersViewController(UIStoryboardSegue seque) { } [Action ("SavePlayerDetails:")] public void SavePlayerDetails(UIStoryboardSegue seque) { var playerDetailsViewController = seque.SourceViewController as PlayerDetailsViewController; if (playerDetailsViewController != null) { var player = playerDetailsViewController.player; if (player != null) { Players.Add(player); var indexPath = new NSIndexPath[] { NSIndexPath.FromRowSection(Players.Count - 1, 0) }; TableView.InsertRows(indexPath, UITableViewRowAnimation.Automatic); } } } } }
using SGDE.Domain.Converters; using SGDE.Domain.Entities; using SGDE.Domain.Helpers; using SGDE.Domain.ViewModels; using System; namespace SGDE.Domain.Supervisor { public partial class Supervisor { public QueryResult<LibraryViewModel> GetAllLibrary(int skip = 0, int take = 0, string filter = null) { var queryResult = _libraryRepository.GetAll(skip, take, filter); return new QueryResult<LibraryViewModel> { Data = LibraryConverter.ConvertList(queryResult.Data), Count = queryResult.Count }; } public LibraryViewModel GetLibraryById(int id) { var libraryViewModel = LibraryConverter.Convert(_libraryRepository.GetById(id)); return libraryViewModel; } public LibraryViewModel AddLibrary(LibraryViewModel newLibraryViewModel) { var library = new Library { AddedDate = DateTime.Now, ModifiedDate = null, IPAddress = newLibraryViewModel.iPAddress, Reference = newLibraryViewModel.reference, Department = newLibraryViewModel.department, Description = newLibraryViewModel.description, Date = newLibraryViewModel.date, Edition = newLibraryViewModel.edition, Active = newLibraryViewModel.active, File = newLibraryViewModel.file, TypeFile = newLibraryViewModel.typeFile, FileName = newLibraryViewModel.fileName }; _libraryRepository.Add(library); return newLibraryViewModel; } public bool UpdateLibrary(LibraryViewModel libraryViewModel) { if (libraryViewModel.id == null) return false; var library = _libraryRepository.GetById((int)libraryViewModel.id); if (library == null) return false; library.ModifiedDate = DateTime.Now; library.IPAddress = libraryViewModel.iPAddress; library.Reference = libraryViewModel.reference; library.Department = libraryViewModel.department; library.Description = libraryViewModel.description; library.Date = libraryViewModel.date; library.Edition = libraryViewModel.edition; library.Active = libraryViewModel.active; library.File = libraryViewModel.file; library.TypeFile = libraryViewModel.typeFile; library.FileName = libraryViewModel.fileName; return _libraryRepository.Update(library); } public bool DeleteLibrary(int id) { return _libraryRepository.Delete(id); } } }
using Sistema.Arquitetura.Library.Core; using Sistema.Arquitetura.Library.Core.Interface; using Sistema.Arquitetura.Library.Core.Util.Security; using Idealize.VO; namespace Idealize.DAO { /// <summary> /// Classe de Acesso a Dados da Tabela aluno /// </summary> public class OpcoesDAO : NativeDAO<Opcoes> { /// <summary> /// Inicializa uma instância da classe /// </summary> /// <param name="connection">Recebendo como parametro a conexao com banco de dados</param> /// <param name="objectSecurity">Objeto de segurança</param> /// <returns>Objeto inserido</returns> public OpcoesDAO(System.Data.IDbConnection connection, ObjectSecurity objectSecurity) : base(connection, objectSecurity) { } #region Métodos de Persistência Básicos /// <summary> /// Realiza o insert do objeto por stored Procedure /// </summary> /// <param name="pObject">Objeto com os valores a ser inserido</param> /// <returns>Objeto Inserido</returns> public Opcoes InsertByStoredProcedure(Opcoes pObject) { string sql = "dbo.I_sp_Opcoes"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idQuestao", pObject.idQuestao); statement.AddParameter("idQuestionario", pObject.idQuestionario); statement.AddParameter("idCampanha", pObject.idCampanha); statement.AddParameter("Descricao", pObject.descricao); return this.ExecuteReturnT(statement); } /// <summary> /// Realiza o update do objeto por stored Procedure /// </summary> /// <param name="pObject">Objeto com os valores a ser atualizado</param> /// <returns>Objeto Atualizado</returns> public Opcoes UpdateByStoredProcedure(Opcoes pObject) { string sql = "dbo.U_sp_Opcoes"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idOpcao", pObject.idOpcao); statement.AddParameter("idQuestao", pObject.idQuestao); statement.AddParameter("idQuestionario", pObject.idQuestionario); statement.AddParameter("idCampanha", pObject.idCampanha); statement.AddParameter("Descricao", pObject.descricao); return this.ExecuteReturnT(statement); } /// <summary> /// Realiza a deleção do objeto por stored Procedure /// </summary> /// <param name="idObject">PK da tabela</param> /// <returns>Quantidade de Registros deletados</returns> public int DeleteByStoredProcedure(Opcoes pObject, bool flExclusaoLogica, int userSystem) { string sql = "dbo.D_sp_Opcoes"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idOpcao", pObject.idOpcao); statement.AddParameter("idQuestao", pObject.idQuestao); statement.AddParameter("idQuestionario", pObject.idQuestionario); statement.AddParameter("idCampanha", pObject.idCampanha); return this.ExecuteNonQuery(statement); } /// <summary> /// Retorna registro pela PK /// </summary> /// <param name="idObject">PK da tabela</param> /// <returns>Registro da PK</returns> public Opcoes SelectByPK(Opcoes pObject) { string sql = "dbo.S_sp_Opcoes"; StatementDAO statement = new StatementDAO(sql); statement.AddParameter("idOpcao", pObject.idOpcao); statement.AddParameter("idQuestao", pObject.idQuestao); statement.AddParameter("idQuestionario", pObject.idQuestionario); statement.AddParameter("idCampanha", pObject.idCampanha); return this.ExecuteReturnT(statement); } #endregion #region Métodos Personalizados #endregion } }
using System; using System.Threading.Tasks; using Fairmas.PickupTracking.Shared.Interfaces; using Fairmas.PickupTracking.Shared.Models; using System.Collections.Generic; using System.Globalization; namespace Fairmas.PickupTracking.Shared.Services { public class PickupTestDataService : IPickupDataService { public async Task<Hotel[]> GetHotelsAsync() { // API // https://put-development.fairplanner.net/api/Administration/Property/GetProperties try { var client = ServiceLocator.FindService<IWebApiClientService>(); var hotels = await client.GetAsync<Hotel[]>("Administration/Property/", "GetProperties", new[] { new KeyValuePair<string, string>("true", "_=1479254387679"), }); return hotels; } catch (Exception) { return new Hotel[] { }; } } public async Task<ResponseFiguresModel[]> GetMonthlyPickupSummaryAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo) { var random = new Random(); var monthlyPickupSummary = new ResponseFiguresModel[12]; for (int index = 0; index < 12; index++) { var rooms1 = random.Next(120); var rooms2 = random.Next(120); var price = 80.0 + (40.0 * random.NextDouble()); var occupancy = random.NextDouble() * 100d; var adr = 60d + random.NextDouble() * 35d; var puAdr = -50d + random.NextDouble() * 100d; monthlyPickupSummary[index] = (new ResponseFiguresModel() { BusinessDate = DateTime.Today.Date.AddMonths(index), Occupancy = new PickupFigures() { SnapshotOneValue = (decimal)occupancy }, AverageDailyRate = new PickupFigures() { SnapshotOneValue = (decimal)adr, PickupValue = (decimal)puAdr }, Revenue = new PickupFigures() { SnapshotOneValue = rooms1 * (decimal)price, SnapshotTwoValue = rooms2 * (decimal)price, PickupValue = (rooms2 * (decimal)price) - (rooms1 * (decimal)price) }, RoomNights = new PickupFigures() { SnapshotOneValue = rooms1, SnapshotTwoValue = rooms2, PickupValue = rooms2 - rooms1 } }); } return monthlyPickupSummary; } public async Task<ResponseFiguresModel[]> GetDailyPickupSummaryAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo, DateTime month) { var random = new Random(); var calendar = new JulianCalendar(); var days = calendar.GetDaysInMonth(month.Year, month.Month); var dailyPickupSummary = new ResponseFiguresModel[days]; for (int day = 1; day <= days; day++) { var rooms1 = random.Next(120); var rooms2 = random.Next(120); var price = 80.0 + (40.0 * random.NextDouble()); var occupancy = random.NextDouble() * 100d; var adr = 60d + random.NextDouble() * 35d; var puAdr = -50d + random.NextDouble() * 100d; dailyPickupSummary[day - 1] = new ResponseFiguresModel() { BusinessDate = new DateTime(month.Year, month.Month, day), Occupancy = new PickupFigures() { SnapshotOneValue = (decimal)occupancy }, AverageDailyRate = new PickupFigures() { SnapshotOneValue = (decimal)adr, PickupValue = (decimal)puAdr }, Revenue = new PickupFigures() { SnapshotOneValue = rooms1 * (decimal)price, SnapshotTwoValue = rooms2 * (decimal)price, PickupValue = (rooms2 * (decimal)price) - (rooms1 * (decimal)price) }, RoomNights = new PickupFigures() { SnapshotOneValue = rooms1, SnapshotTwoValue = rooms2, PickupValue = rooms2 - rooms1 } }; } return dailyPickupSummary; } public async Task<ResponseFiguresModel[]> GetSegmentedPickupAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo, DateTime day) { var random = new Random(); var segments = new[] {"A1", "A3", "A4", "B1", "B2", "B3", "C1", "C2", "D1" }; var segmentPickup = new ResponseFiguresModel[segments.Length]; for(int i = 1; i <= segments.Length; i++) { var rooms1 = random.Next(120); var rooms2 = random.Next(120); var price = 80.0 + (40.0 * random.NextDouble()); var occupancy = random.NextDouble() * 100d; var adr = 60d + random.NextDouble() * 35d; var puAdr = -50d + random.NextDouble() * 100d; segmentPickup[i - 1] = new ResponseFiguresModel() { BusinessDate = new DateTime(day.Year, day.Month, day.Day), Segment = segments[i-1], Occupancy = new PickupFigures() { SnapshotOneValue = (decimal)occupancy }, AverageDailyRate = new PickupFigures() { SnapshotOneValue = (decimal)adr, PickupValue = (decimal)puAdr }, Revenue = new PickupFigures() { SnapshotOneValue = rooms1 * (decimal)price, SnapshotTwoValue = rooms2 * (decimal)price, PickupValue = (rooms2 * (decimal)price) - (rooms1 * (decimal)price) }, RoomNights = new PickupFigures() { SnapshotOneValue = rooms1, SnapshotTwoValue = rooms2, PickupValue = rooms2 - rooms1 } }; } return segmentPickup; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Business.Abstract; using DataAccess.Repository; using DataAccess.NHibernateHelper; using Domain.Entity; using log4net; namespace Business.Service { public class CustomerServiceImpl : ICustomerService { ILog log = LogManager.GetLogger("CustomerServiceImpl"); CustomerRepository customerRepo; public CustomerServiceImpl() { customerRepo = new CustomerRepository(FluentNHibernateHelper.GetContext()); } public IList<Customer> GetAllCustomers() { return customerRepo.List().Where(x => x.IsDeleted == false).ToList(); } public void SaveCustomer(Customer customer) { log.Debug("Save customer"); customer.CreatedDate = DateTime.Now; customerRepo.Insert(customer); customerRepo.Commit(); } public Customer GetCustomerById(long id) { return customerRepo.List().Where(x => x.IsDeleted == false).ToList().Where(x=>x.ID == id).First(); } public void UpdateCustomer(Customer customer) { customerRepo.Update(customer); customerRepo.Commit(); } public void DeleteCustomer(Customer customer) { customerRepo.Delete(customer); customerRepo.Commit(); } public IList<Customer> GetAllCustomers(string column, string value) { return customerRepo.GetAllCustomers(column, value); } public Customer GetCustomerByEmail(string email) { return customerRepo.GetCustomerByEmail(email); } } }
using Microsoft.DataStudio.Diagnostics; using Microsoft.DataStudio.Solutions.Validators; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace Microsoft.DataStudio.Services.Security { public class SecurityHelper { //TODO : rajdey This will be pulled from secret store static string _key = "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"; string sharedSecret = "AGWBEa4Xv8kan9MID8xwAYI1ZW26k87ZQ5F"; private const string SQl_PASSWORD = "sqlServerPassword"; private const string VALUEPROPERTY = "value"; private byte[] _salt = Encoding.ASCII.GetBytes(_key); private const int KeySizeDivisor = 8; ILogger logger = LoggerFactory.CreateServiceLogger(new LoggerSettings { ComponentId = ComponentID.DataStudioService, EnableMdsTracing = true, SourceLevels = SourceLevels.All }); /// <summary> /// Encrypt the given string using AES. The string can be decrypted using /// Encrypt(). The sharedSecret parameters must match. /// </summary> /// <param name="plainText">The text to encrypt.</param> public async Task<string> EncryptPassword(string plainText) { if(string.IsNullOrEmpty(plainText)) { return null; } //Deserialize the parameter text to a Json object to find the password field JavaScriptSerializer json_serializer = new JavaScriptSerializer(); Dictionary<string, Object> parameterList = (Dictionary<string, Object>)json_serializer.DeserializeObject(plainText); // If ParameterList does not contain a SQL Server Password, No need to encrypt - return the plainText if (!parameterList.Keys.Contains<string>(SQl_PASSWORD)) return plainText; var passwordNode = parameterList[SQl_PASSWORD] as Dictionary<string, object>; // if password field not found throw error ThrowIf.Null(passwordNode, SQl_PASSWORD); // Return the encrypted bytes from the memory stream. var dictionaryObject = new Dictionary<string, Object>(); dictionaryObject.Add(VALUEPROPERTY, await Encrypt(passwordNode.Values.First().ToString())); parameterList[SQl_PASSWORD] = dictionaryObject; return json_serializer.Serialize(parameterList); } public async Task<string> Encrypt(string value) { string outStr = null; // Encrypted string to return RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data. try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / KeySizeDivisor); // Create a encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (var msEncrypt = new MemoryStream()) { // prepend the IV await msEncrypt.WriteAsync(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); await msEncrypt.WriteAsync(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. await swEncrypt.WriteAsync(value); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } catch (Exception ex) { logger.Write(TraceEventType.Error, string.Format("SECURITY EXCEPTION- {0}", ex.Message)); } finally { // Clear the RijndaelManaged object. if (aesAlg != null) aesAlg.Clear(); } return outStr; } /// <summary> /// Decrypt the given string. Assumes the string was encrypted using /// Decrypt(), using an identical sharedSecret. /// </summary> /// <param name="cipherText">The text to decrypt.</param> public async Task<string> DecryptPassword(string cipherText) { if(string.IsNullOrEmpty(cipherText)) { return null; } //Deserialize the parameter text to a Json object to find the password field JavaScriptSerializer json_serializer = new JavaScriptSerializer(); Dictionary<string, Object> parameterList = (Dictionary<string, Object>)json_serializer.DeserializeObject(cipherText); // If ParameterList does not contain a SQL Server Password, No need to decrypt - return the cipherText if (!parameterList.ContainsKey(SQl_PASSWORD)) return cipherText; var passwordNode = parameterList[SQl_PASSWORD] as Dictionary<string, object>; // if password field not found throw error ThrowIf.Null(passwordNode, SQl_PASSWORD); var dictionaryObject = new Dictionary<string, Object>(); dictionaryObject.Add(VALUEPROPERTY, await Decrypt(passwordNode.Values.First().ToString())); parameterList[SQl_PASSWORD] = dictionaryObject; return json_serializer.Serialize(parameterList); } public async Task<string> Decrypt(string value) { // Declare the RijndaelManaged object // used to decrypt the data. RijndaelManaged aesAlg = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(value); using (var msDecrypt = new MemoryStream(bytes)) { // Create a RijndaelManaged object // with the specified key and IV. aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / KeySizeDivisor); // Get the initialization vector from the encrypted stream aesAlg.IV = ReadByteArray(msDecrypt); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = await srDecrypt.ReadToEndAsync(); } } } catch (Exception ex) { logger.Write(TraceEventType.Error, string.Format("SECURITY EXCEPTION- {0}", ex.Message)); } finally { // Clear the RijndaelManaged object. if (aesAlg != null) aesAlg.Clear(); } return plaintext; } private byte[] ReadByteArray(Stream s) { byte[] rawLength = new byte[sizeof(int)]; if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length) { throw new SystemException("Stream did not contain properly formatted byte array"); } byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)]; if (s.Read(buffer, 0, buffer.Length) != buffer.Length) { throw new SystemException("Did not read byte array properly"); } return buffer; } } }
namespace Fakes { partial class FakeRulesDataSet { } } namespace Fakes.FakeRulesDataSetTableAdapters { public partial class ProcessingRulesTableAdapter { } }
namespace Goop.Wpf { public static class BoolBox { public static readonly object True = true; public static readonly object False = false; public static object Box(bool value) => value ? True : False; } }
using Dapper; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using NChampions.Application.Queries; using NChampions.Application.ViewModels; using NChampions.Infra.Data.Context; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace NChampions.Infra.Queries { public class StandingQueries : IStandingQueries { private readonly NChampionsContext context; private readonly SqlConnection _sqlConnection; public StandingQueries(NChampionsContext context) { _sqlConnection = new SqlConnection(context.Database.GetConnectionString()); this.context = context; } public async Task<List<StandingViewModel>> GetChampionshipStanding(Guid ChampionshipID) { var queryArgs = new DynamicParameters(); queryArgs.Add("Id", ChampionshipID); var query = @"Select TeamName, (Wins * 3) + Draws as Points, Wins, Draws, Loses FROM ( Select t.TeamName as TeamName, (select count(1) from ChampionshipGame cg where cg.HomeTeamId = t.Id and cg.HomeScore>cg.AwayScore) + (select count(1) from ChampionshipGame cg where cg.AwayTeamId = t.Id and cg.AwayScore>cg.HomeScore) as Wins , (select count(1) from ChampionshipGame cg where cg.HomeTeamId = t.Id and cg.HomeScore=cg.AwayScore) + (select count(1) from ChampionshipGame cg where cg.AwayTeamId = t.Id and cg.AwayScore=cg.HomeScore) as Draws, (select count(1) from ChampionshipGame cg where cg.HomeTeamId = t.Id and cg.HomeScore<cg.AwayScore) + (select count(1) from ChampionshipGame cg where cg.AwayTeamId = t.Id and cg.AwayScore<cg.HomeScore) as Loses from Team t inner join ChampionshipTeam ct on t.Id=ct.TeamsId where ct.ChampionshipsId = @Id ) Query order by Points desc, Wins desc "; var result = (await _sqlConnection.QueryAsync<StandingViewModel>(query, queryArgs)).AsList<StandingViewModel>(); return result; } } }
using UnityEngine; using System.Collections; public class Playorz : MonoBehaviour { public AudioManager audioManager; public float movementSpeed = 0f; public float jumpSpeed = 0f; public float gravity = 0f; public float gravity_h = 0f; public Transform stairway; Vector3 direction_left = Vector3.zero; Vector3 direction_forward = Vector3.zero; float VSpeed = 0f; public float VSpeedMax = 0f; float HSpeed = 0f; public float HSpeedMax = 0f; Vector3 movementVector = Vector3.zero; CharacterController cc; float jump_timer = 0f; public float radialDistance = 26f; LinkedSpriteManager LSM; Sprite S; UVAnimation anim_idle; UVAnimation anim_runstart; UVAnimation anim_run; UVAnimation anim_jump; string anim_current; bool isJumping = false; float hitTimerH = 0f; float hitTimerV = 0f; void Start () { direction_left = Vector3.left; cc = transform.GetComponent<CharacterController>(); LSM = GameObject.Find("PlayerSpriteManager").GetComponent<LinkedSpriteManager>(); InitSM(); audioManager = GameObject.Find("AudioManager").transform.GetComponent<AudioManager>(); } void InitSM() { S = LSM.AddSprite(this.gameObject, 5, 5, LSM.PixelCoordToUVCoord(0, 0), LSM.PixelSpaceToUVSpace(512, 512), -transform.forward * .4f, false); anim_run = new UVAnimation(); anim_run.SetAnim( new Vector2[]{ LSM.PixelCoordToUVCoord(3072, 0), LSM.PixelCoordToUVCoord(3072+512, 0), LSM.PixelCoordToUVCoord(0, 512), LSM.PixelCoordToUVCoord(512, 512), LSM.PixelCoordToUVCoord(1024, 512), LSM.PixelCoordToUVCoord(1024+512, 512), LSM.PixelCoordToUVCoord(2048, 512), LSM.PixelCoordToUVCoord(2048+512, 512) }); //anim_run.BuildUVAnim(LSM.PixelCoordToUVCoord(3072, 512), LSM.PixelSpaceToUVSpace(512, 512), 16, 2, 16, 2f); anim_run.loopCycles = -1; //anim_run.PlayInReverse(); anim_run.name = "Run"; S.AddAnimation(anim_run); anim_idle = new UVAnimation(); anim_idle.BuildUVAnim(LSM.PixelCoordToUVCoord(0, 512), LSM.PixelCoordToUVCoord(512, 512), 8, 2, 1, 12f); anim_idle.loopCycles = -1; S.AddAnimation(anim_idle); anim_idle.name = "Idle"; anim_runstart = new UVAnimation(); anim_runstart.BuildUVAnim(LSM.PixelCoordToUVCoord(0, 512), LSM.PixelCoordToUVCoord(512, 512), 8, 2, 1, 12f); anim_runstart.loopCycles = -1; S.AddAnimation(anim_runstart); anim_runstart.name = "RunStart"; anim_current = "Run"; S.PlayAnim(anim_run); LSM.ScheduleBoundsUpdate(0.5f); } void Update () { CheckDirection(); movementVector = Vector2.zero; //checking for jump cap. if(cc.isGrounded) { jump_timer = Time.time + 0.25f; isJumping = false; } //gravity if(!cc.isGrounded) { VSpeed -= gravity * Time.deltaTime; HSpeed += HSpeed > 0f ? - gravity_h * Time.deltaTime : gravity_h * Time.deltaTime; } else { VSpeed = 0f; HSpeed = 0f; } //movement if(Input.GetButton("Left")) { if(cc.isGrounded || !isJumping) movementVector += direction_left * movementSpeed; else HSpeed += movementSpeed * Time.deltaTime * 2f; } if(Input.GetButton("Right")) { if(cc.isGrounded || !isJumping) movementVector -= direction_left * movementSpeed; else HSpeed -= movementSpeed * Time.deltaTime * 2f; } if(Input.GetButtonDown("Jump") && jump_timer > Time.time) { HSpeed = Input.GetButton("Right") ? -movementSpeed : (Input.GetButton("Left") ? movementSpeed : 0f); VSpeed = jumpSpeed * (HSpeed == 0f ? 1.25f : .9f); jump_timer = 0f; audioManager.PlaySound(audioManager.sound_jump, 0.65f); isJumping = true; } VSpeed = Mathf.Clamp(VSpeed, -VSpeedMax, VSpeedMax); HSpeed = Mathf.Clamp(HSpeed, -HSpeedMax, HSpeedMax); movementVector.y = VSpeed; movementVector += HSpeed * direction_left; cc.Move(movementVector * Time.deltaTime); CheckPosition(); //UpdateAnimation(); } /*public void UpdateAnimation() { if(cc.velocity.magnitude < 1f && !isJumping) { anim_current = "Idle"; S.PlayAnim("Idle"); } else if(anim_current == "Idle" && cc.velocity.magnitude > 0.1f) { anim_current = "Run"; S.PlayAnim("Run"); } }*/ void CheckPosition() { Vector3 deltaPosition = transform.position - stairway.position; deltaPosition.y = 0; float angle = Vector3.Angle(stairway.transform.right, deltaPosition) * Mathf.Deg2Rad; if( transform.position.z > 0 ) { angle *= -1; } transform.position = Vector3.Lerp ( transform.position, new Vector3( Mathf.Cos(angle) * radialDistance, transform.position.y, -Mathf.Sin(angle) * radialDistance ), Time.deltaTime * 2f ); } void CheckDirection() { direction_left = Vector3.Project(direction_left, Vector3.Cross(stairway.position - transform.position, Vector3.down) ).normalized; direction_forward = stairway.position - transform.position; direction_forward.y = 0; transform.forward = Vector3.Lerp(transform.forward, direction_forward, Time.deltaTime); } public void AdjustRadialDistance(float radialDistance) { this.radialDistance = radialDistance; } void OnControllerColliderHit(ControllerColliderHit hit) { if(hit.normal.y < -0.75f && hitTimerV < Time.time) { VSpeed = -.05f; hitTimerV = Time.time + .5f; } } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; public class Menu : MonoBehaviour { [SerializeField] public GameObject nameBox; public void BtnOffline_Click() { Debug.Log("OfflineMode"); Global.state = false; SceneManager.LoadSceneAsync("MapInstance"); } public void BtnOnline_Click() { Debug.Log("OnlineMode"); Global.state = true; SceneManager.LoadSceneAsync("ServerList"); } public void BtnExit_Click() { Application.Quit(); } void Start() { if (File.Exists(Application.persistentDataPath + "/session")) { Global.sessionToken = Manager.LoadData<SessionToken>("session"); } else nameBox.SetActive(true); } }
using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using UnityEngine; public static class CircuitSolver { //solves the currents for each resistor in a presented list public static Dictionary<BusStopController, float> SolveLinearCircuit(BusStopController[] resistors, float voltage) { //Set up variables based on the arguments of the function float totResistance = TotalResistance(resistors); float totCurrent = FindCurrentThrough(totResistance, voltage); float startVoltage = voltage; List<string> solvedParallels = new List<string>(); Dictionary<BusStopController, float> resistorCurrents = new Dictionary<BusStopController, float>(); //Create a dictionary that allows for the easy return of the resistors and their individual current values foreach (BusStopController resistor in resistors) { resistorCurrents.Add(resistor, 0f); } //Go through each of the individual resistors and find their currents foreach (BusStopController resistor in resistors) { //If the resistor is in series it just has the total current, but it need to reduce the voltage potential if (resistor.gameObject.tag == "series") { resistorCurrents[resistor] = (float) MyRound(totCurrent * 100f) / 100f; float voltDrop = totCurrent * resistor.GetResistance(); startVoltage -= voltDrop; //UnityEngine.Debug.Log(startVoltage.ToString() + "Beforehand"); } //If the resistor is a parallel resistor it needs to be solved along with it's parallel bretheren else if (resistor.gameObject.tag.Substring(0, 8) == "parallel") { //make sure this group of parallel resistors hasn't already been solved if(!solvedParallels.Contains(resistor.gameObject.tag.Substring(0, 9))) { //Create a dictonary to store the resistors in the circuit and their currents Dictionary<string, float> seriesParallels = new Dictionary<string, float>(); Dictionary<BusStopController, float> parallelResistances = new Dictionary<BusStopController, float>(); int i = 0; bool looping = true; string parallelTag; //Loop through all of the resistors that are in a parallel section (eg parallel1) and combine the resistances of their individual series conterparts (e.g parallel1.1 + parallel1.2) while (looping) { i++; parallelTag = resistor.gameObject.tag.Substring(0, 9) + "." + i; seriesParallels.Add(parallelTag, 0f); //Checks each individual resistor in the circuit to see if they belong to a group (e.g parallel1.1 and parallel1.2) foreach (BusStopController subres in resistors) { //adds the values of series resistances inside of the parallel circuit if(subres.gameObject.tag == parallelTag) { seriesParallels[parallelTag] = seriesParallels[parallelTag] + subres.GetResistance(); } } //sends out the parallel tag and it's value for debugging purposes //UnityEngine.Debug.Log(parallelTag); //UnityEngine.Debug.Log(seriesParallels[parallelTag]); //if there reaches a point where one of the subseries is equal to 0, it deletes it from the collection of parallel series resistances and ends the search for parallel series resistances if (seriesParallels[parallelTag] == 0) { seriesParallels.Remove(parallelTag); looping = false; } } //Set a variable as the total parallel resistance float totParallelResistance = 0f; //Go through all of the keys and assign them their various currents foreach (KeyValuePair<string, float> seriesResistance in seriesParallels) { //Sends out the name and value of each individual subseries in the parallel circuit. //UnityEngine.Debug.Log(seriesResistance.Key); //UnityEngine.Debug.Log(seriesResistance.Value); UnityEngine.Debug.Log("The voltage through this resistor is: " + startVoltage); float seriesCurrent = startVoltage / seriesResistance.Value; UnityEngine.Debug.Log("The series current through this resistor is: " + seriesCurrent); //finds the total series current accross a branch of the parallel circuit //sets that series current as the current through each individual resistor in the subseries foreach (BusStopController subres in resistors) { if (subres.gameObject.tag == seriesResistance.Key) { resistorCurrents[subres] = (float) MyRound(seriesCurrent * 100f) / 100f; } } //adds the inverse of the the series resistance to the total value of the parallel circuit's resistance totParallelResistance += 1 / seriesResistance.Value; //UnityEngine.Debug.Log(seriesResistance.Value.ToString()); } //inverses the sum of the inverses of the individual subseries resistances to find the total resistance of the parallel element. totParallelResistance = 1/totParallelResistance; //UnityEngine.Debug.Log("The total resistance of the combined parallels of this tag is " + totParallelResistance); //foreach (BusStopController subres in parallelResistances.Keys) //{ // UnityEngine.Debug.Log(parallelResistances[subres]); // UnityEngine.Debug.Log(startVoltage.ToString() + "Afterwards"); //resistorCurrents[subres] = startVoltage / parallelResistances[subres]; //totParallelResistance += 1/parallelResistances[subres]; //} //Ackgnowedge the total voltage drop across the circuit from the parallel resistance //UnityEngine.Debug.Log(startVoltage.ToString() + "Beforehand"); float voltDrop = totCurrent * 1/totParallelResistance; UnityEngine.Debug.Log("I am dropping the voltage"); startVoltage -= voltDrop; //UnityEngine.Debug.Log(startVoltage.ToString() + "Afterwards"); solvedParallels.Add(resistor.gameObject.tag.Substring(0, 9)); } } } return resistorCurrents; } //Finds the total resistance for a circuit made out of the given list of resistors public static float TotalResistance(BusStopController[] resistors) { //Definie local variables for the method float totResistance = 0f; bool parallel = true; List<BusStopController> parallelResistors = new List<BusStopController>(); List<float> parallelResistances = new List<float>(); int i = 1; //Start checking for parallel circuit elements, check for parallel before series while (parallel) { //Set up the search for parallel1... can be later changed to parallel 2 if there are more than one parallel branch string tag = "parallel" + i.ToString(); //As long as it's not a series resistor, add it if it's part of the parallelx set foreach (BusStopController resistor in resistors) if (resistor.gameObject.tag != "series") { if (resistor.gameObject.tag.Substring(0, 9) == tag) { parallelResistors.Add(resistor); } } //In the case there are no parallel resistors, exit the loop searching for parallel resistors if (parallelResistors.Count == 0) { parallel = false; } //If there are parallel resistors in the circuit: else { //set up local variables bool series = true; int j = 0; Dictionary<string, float> seriesParallels = new Dictionary<string, float>(); //check through the resistances of each branch of the circuit while (series) { j++; string parallelTag = tag + "." + j; seriesParallels.Add(parallelTag, 0f); //adds eacj element of a subseries to it's total series resistance value foreach (BusStopController subresistor in parallelResistors) { if (subresistor.tag == parallelTag) { seriesParallels[parallelTag] = seriesParallels[parallelTag] + subresistor.GetResistance(); } } //If a subseries is reached that is not utilized, delete it from the list of parallel branches and stop the collection of series elements if (seriesParallels[parallelTag] == 0f) { seriesParallels.Remove(parallelTag); series = false; } } //adds the float values of the indidual paths to a list of float values foreach (KeyValuePair<string, float> seriesResistance in seriesParallels) { parallelResistances.Add(seriesResistance.Value); } //Gets the total resistance of all of the path's values from the TotalParallelResistance method totResistance += TotalParallelResistance(parallelResistances); } //resets the circuit to look for the next group of parallel resistors i++; parallelResistors.Clear(); } //adds series resistances to the total resistance of the circuit foreach (BusStopController resistor in resistors) { if (resistor.gameObject.tag == "series") { totResistance += resistor.GetResistance(); } } //Returns the total resistance in the circuit return totResistance; } //Returns the sum of the resistances given to it private static float TotalSeriesResistance(List<float> resistances) { float tot = 0; foreach (float r in resistances) tot += r; return tot; } //Uses the parallel resistor equation to find the total resistance over a set of parallel resistances public static float TotalParallelResistance(List<float> resistances) { float tot = 0; foreach (float r in resistances) tot += (1 / r); tot = 1 / tot; return tot; } //uses Ohm's Law to find the total current in a linear system with a known voltage and resistance private static float FindCurrentThrough(float resistance, float voltage) { return voltage / resistance; } //Custom rounding method used to consistantly round up at a value of .5 public static float MyRound(float value) { if (value % 0.5f == 0) return Mathf.Ceil(value); else return Mathf.Round(value); } }
// // mc.cs: Panel controls // // Authors: // Miguel de Icaza (miguel@gnome.org) // // Licensed under the MIT X11 license // //#define DEBUG using System; using System.Collections; using System.IO; using System.Collections.Generic; using Mono.Terminal; using Mono.Unix; using Mono.Unix.Native; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace MouselessCommander { public class Listing : IEnumerable<Listing.FileNode> { string url; FileNode [] nodes; Comparison<FileNode> compare; public int Count { get; private set; } public class FileNode { public int StartIdx; public int Nested; public bool Marked; public UnixFileSystemInfo Info; // // Have to use this ugly hack, because Mono.Posix does not // return ".." in directory listings. And creating instances // of it, return the parent name, instead of ".." // public virtual string Name { get { return Info.Name; } } public FileNode (UnixFileSystemInfo info) { Info = info; } } public class DirNode : FileNode { public FileNode [] Nodes; public bool Expanded; public DirNode (UnixFileSystemInfo info) : base (info) {} } public class DirNodeDotDot : DirNode { public DirNodeDotDot (UnixFileSystemInfo info) : base (info) {} public override string Name { get { return ".."; } } } public IEnumerator<FileNode> GetEnumerator () { foreach (var a in nodes) yield return a; } IEnumerator IEnumerable.GetEnumerator () { foreach (var a in nodes) yield return a; } FileNode GetNodeAt (int idx, FileNode [] nodes) { if (nodes == null) throw new ArgumentNullException ("nodes"); for (int i = 0; i < nodes.Length; i++){ if (nodes [i].StartIdx == idx) return nodes [i]; if (i+1 == nodes.Length || nodes [i+1].StartIdx > idx) return GetNodeAt (idx, ((DirNode) nodes [i]).Nodes); } return null; } string GetName (int idx, string start, FileNode [] nodes) { for (int i = 0; i < nodes.Length; i++){ if (nodes [i].StartIdx == idx) return Path.Combine (start, nodes [i].Name); if (i+1 == nodes.Length || nodes [i+1].StartIdx > idx) return GetName (idx, Path.Combine (start, nodes [i].Name), ((DirNode) nodes [i]).Nodes); } throw new Exception ("This should not happen"); } string GetPathAt (int idx, FileNode [] nodes) { for (int i = 0; i < nodes.Length; i++){ if (nodes [i].StartIdx == idx) return nodes [i].Name; if (i+1 == nodes.Length || nodes [i+1].StartIdx > idx) return Path.Combine (nodes [i].Name, GetPathAt (idx, ((DirNode) nodes [i]).Nodes)); } return null; } public string GetPathAt (int idx) { return GetPathAt (idx, nodes); } public int NodeWithName (string s) { for (int i = 0; i < nodes.Length; i++){ if (nodes [i].Name == s) return i; } return -1; } public FileNode this [int idx]{ get { var x = GetNodeAt (idx, nodes); return x; } } FileNode [] PopulateNodes (bool need_dotdot, UnixFileSystemInfo [] root) { FileNode [] pnodes = new FileNode [root.Length + (need_dotdot ? 1 : 0)]; int i = 0; if (need_dotdot){ pnodes [0] = new DirNodeDotDot (new UnixDirectoryInfo ("..")); i++; } foreach (var info in root){ if (info.IsDirectory) pnodes [i++] = new DirNode (info); else pnodes [i++] = new FileNode (info); } Array.Sort<FileNode> (pnodes, compare); return pnodes; } int UpdateIndexes (FileNode [] nodes, int start, int level) { foreach (var n in nodes){ DirNode dn = n as DirNode; n.StartIdx = start++; n.Nested = level; if (dn != null && dn.Expanded && dn.Nodes != null) start = UpdateIndexes (dn.Nodes, start, level+1); } return start; } Listing (string url, UnixFileSystemInfo [] root, Comparison<FileNode> compare) { this.url = url; this.compare = compare; nodes = PopulateNodes (url != "/", root); Count = UpdateIndexes (nodes, 0, 0); } public Listing () { nodes = new FileNode [0]; } void LoadChild (int idx) { DirNode dn = this [idx] as DirNode; string name = GetName (idx, url, nodes); try { var udi = new UnixDirectoryInfo (name); dn.Nodes = PopulateNodes (true, udi.GetFileSystemEntries ()); dn.Expanded = true; } catch (Exception e){ Console.WriteLine ("Error loading {0}", name); // Show error? return; } Count = UpdateIndexes (nodes, 0, 0); } public void Expand (int idx) { var node = this [idx] as DirNode; if (node == null) return; if (node.Nodes == null){ LoadChild (idx); } else { node.Expanded = true; Count = UpdateIndexes (nodes, 0, 0); } } public void Collapse (int idx) { var node = this [idx] as DirNode; if (node == null) return; node.Expanded = false; foreach (var n in node.Nodes) n.Marked = false; Count = UpdateIndexes (nodes, 0, 0); } public static Listing LoadFrom (string url, Comparison<FileNode> compare) { try { var udi = new UnixDirectoryInfo (url); return new Listing (url, udi.GetFileSystemEntries (), compare); } catch (Exception e){ return new Listing (); } return null; } } public class Panel : Frame { static int ColorDir; Shell shell; SortOrder sort_order = SortOrder.Name; bool group_dirs = true; Listing listing; int top, selected, marked; string current_path; static Panel () { if (Application.UsingColor) ColorDir = Curses.A_BOLD | Application.MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE); else ColorDir = Curses.A_NORMAL; } public enum SortOrder { Unsorted, Name, Extension, ModifyTime, AccessTime, ChangeTime, Size, Inode } public IEnumerable<Listing.FileNode> Selection () { if (marked > 0){ foreach (var node in listing){ if (node.Marked) yield return node; } } else yield return listing [selected]; } public Listing.FileNode SelectedNode { get { return listing [selected]; } } public string SelectedPath { get { return Path.Combine (CurrentPath, listing.GetPathAt (selected)); } } int CompareNodes (Listing.FileNode a, Listing.FileNode b) { if (a.Name == ".."){ if (b.Name != "..") return -1; return 0; } int nl = a.Nested - b.Nested; if (nl != 0) return nl; if (sort_order == SortOrder.Unsorted) return 0; if (group_dirs){ bool adir = a is Listing.DirNode; bool bdir = b is Listing.DirNode; if (adir ^ bdir){ if (adir) return -1; return 1; } } switch (sort_order){ case SortOrder.Name: return string.Compare (a.Name, b.Name); case SortOrder.Extension: var sa = Path.GetExtension (a.Name); var sb = Path.GetExtension (b.Name); return string.Compare (sa, sb); case SortOrder.ModifyTime: return DateTime.Compare (a.Info.LastWriteTimeUtc, b.Info.LastWriteTimeUtc); case SortOrder.AccessTime: return DateTime.Compare (a.Info.LastAccessTimeUtc, b.Info.LastAccessTimeUtc); case SortOrder.ChangeTime: return DateTime.Compare (a.Info.LastStatusChangeTimeUtc, b.Info.LastStatusChangeTimeUtc); case SortOrder.Size: long r = a.Info.Length - b.Info.Length; if (r < 0) return -1; if (r > 0) return 1; return 0; case SortOrder.Inode: r = a.Info.Inode - b.Info.Inode; if (r < 0) return -1; if (r > 0) return 1; return 0; } return 0; } Panel (Shell shell, string path, int x, int y, int w, int h) : base (x, y, w, h, path) { this.shell = shell; CanFocus = true; Capacity = h - 2; SetCurrentPath (path, false); CurrentPath = path; } void SetCurrentPath (string path, bool refresh) { current_path = path; Title = Path.GetFullPath (path); listing = Listing.LoadFrom (current_path, CompareNodes); top = 0; selected = 0; marked = 0; if (refresh) Redraw (); } public int Capacity { get; private set; } public string CurrentPath { get { return current_path; } set { SetCurrentPath (value, true); } } public override void Redraw () { base.Redraw (); Curses.attrset (ContainerColorNormal); int files = listing.Count; for (int i = 0; i < Capacity; i++){ if (i + top >= files) break; DrawItem (top+i, top+i == selected); } } public override bool HasFocus { get { return base.HasFocus; } set { if (value) shell.CurrentPanel = this; base.HasFocus = value; } } public void DrawItem (int nth, bool is_selected) { char ch; if (nth >= listing.Count) throw new Exception ("overflow"); is_selected = HasFocus && is_selected; Move (y + (nth-top) + 1, x + 1); Listing.FileNode node = listing [nth]; int color; if (node == null) throw new Exception (String.Format ("Problem fetching item {0}", nth)); if (node.Info.IsDirectory){ color = is_selected ? ColorFocus : ColorDir; ch = '/'; } else { color = is_selected ? ColorFocus : ColorNormal; ch = ' '; } if (node.Marked) color = is_selected ? ColorHotFocus : ColorHotNormal; Curses.attrset (color); for (int i = 0; i < node.Nested; i++) Curses.addstr (" "); Curses.addch (ch); Curses.addstr (node.Name); } public override void DoSizeChanged () { base.DoSizeChanged (); if (x == 0){ w = Application.Cols/2; } else { w = Application.Cols/2+Application.Cols%2; x = Application.Cols/2; } h = Application.Lines-4; Capacity = h - 2; } public static Panel Create (Shell shell, string kind, int taken) { var height = Application.Lines - taken; switch (kind){ case "left": return new Panel (shell, Environment.CurrentDirectory, 0, 1, Application.Cols/2, height); case "right": return new Panel (shell, Environment.GetFolderPath (Environment.SpecialFolder.Personal), Application.Cols/2, 1, Application.Cols/2+Application.Cols%2, height); } return null; } bool MoveDown () { if (selected == listing.Count-1) return true; DrawItem (selected, false); selected++; if (selected-top >= Capacity){ top += Capacity/2; if (top > listing.Count - Capacity) top = listing.Count - Capacity; Redraw (); } else { DrawItem (selected, true); } return true; } bool MoveUp () { if (selected == 0) return true; DrawItem (selected, false); selected--; if (selected < top){ top -= Capacity/2; if (top < 0) top = 0; Redraw (); } else DrawItem (selected, true); return true; } void PageDown () { if (selected == listing.Count-1) return; int scroll = Capacity; if (top > listing.Count - 2 * Capacity) scroll = listing.Count - scroll - top; if (top + scroll < 0) scroll = -top; top += scroll; if (scroll == 0) selected = listing.Count-1; else { selected += scroll; if (selected > listing.Count) selected = listing.Count-1; } if (top > listing.Count) top = listing.Count-1; Redraw (); } void PageUp () { if (selected == 0) return; if (top == 0){ DrawItem (selected, false); selected = 0; DrawItem (selected, true); } else { top -= Capacity; selected -= Capacity; if (selected < 0) selected = 0; if (top < 0) top = 0; Redraw (); } } void MoveTop () { selected = 0; top = 0; Redraw (); } void MoveBottom () { selected = listing.Count-1; top = Math.Max (0, selected-Capacity+1); Redraw (); } public bool CanExpandSelected { get { return listing [selected] is Listing.DirNode; } } public void ExpandSelected () { var dn = listing [selected] as Listing.DirNode; if (dn == null) return; listing.Expand (selected); Redraw (); } public void CollapseAction () { var dn = listing [selected] as Listing.DirNode; // If it is a regular file, navigate to the directory if (dn == null || dn.Expanded == false){ for (int i = selected-1; i >= 0; i--){ if (listing [i] is Listing.DirNode){ selected = i; if (selected < top) top = selected; Redraw (); return; } } return; } listing.Collapse (selected); Redraw (); } // // Handler for the return key on an item // void Action () { var node = listing [selected] as Listing.DirNode; if (node != null) ChangeDir (node); } public void ChangeDir (Listing.DirNode node) { string focus = node is Listing.DirNodeDotDot ? Path.GetFileName (Title) : null; SetCurrentPath (Path.Combine (CurrentPath, listing.GetPathAt (selected)), false); if (focus != null){ int idx = listing.NodeWithName (focus); if (idx != -1){ selected = idx; // This could use some work to center on going up. if (selected >= Capacity){ top = selected; } } } Redraw (); } public void Copy (string target_dir) { var msg_file = "Copy file \"{0}\" to: "; int dlen = 68; int ilen = dlen-6; var d = new Dialog (dlen, 8, "Copy"); if (marked > 1) d.Add (new Label (1, 0, String.Format ("Copy {0} files", marked))); else d.Add (new Label (1, 0, String.Format (msg_file, listing.GetPathAt (selected).Ellipsize (ilen-msg_file.Length)))); bool proceed = false; var targetEntry = new Entry (1, 1, ilen, target_dir ?? ""); d.Add (targetEntry); var b = new Button (0, 0, "Ok", true); b.Clicked += delegate { d.Running = false; proceed = true; }; d.AddButton (b); b = new Button (0, 0, "Cancel", false); b.Clicked += (o,s) => d.Running = false; d.AddButton (b); Application.Run (d); if (!proceed) return; if (targetEntry.Text == ""){ Message.Error ("Empty target directory"); return; } PerformCopy (targetEntry.Text); } int ComputeTotalFiles () { // Later we should change this with a directory scan return marked > 0 ? marked : 1; } void PerformCopy (string target_dir) { double? total_bytes = null; var progress = new ProgressInteraction ("Copying", ComputeTotalFiles (), total_bytes); var runstate = Application.Begin (progress); using (var copyOperation = new CopyOperation (progress)){ #if !DEBUG var timer = Application.MainLoop.AddTimeout (TimeSpan.FromSeconds (1), mainloop => { progress.UpdateStatus (copyOperation); return true; }); Task t = Task.Factory.StartNew (delegate { #endif foreach (var node in Selection ()){ bool isDir = node is Listing.DirNode; var r = copyOperation.Perform (CurrentPath, listing.GetPathAt (node.StartIdx), isDir, node.Info.Protection, target_dir); if (r == FileOperation.Result.Cancel) break; } #if !DEBUG Application.Stop (); }, null); Application.RunLoop (runstate, true); Application.MainLoop.RemoveTimeout (timer); #endif } Application.End (runstate); } public override bool ProcessKey (int key) { var result = true; switch (key){ case (int) '>' + Curses.KeyAlt: MoveBottom (); break; case (int) '<' + Curses.KeyAlt: MoveTop (); break; case Curses.KeyUp: case 16: // Control-p result = MoveUp (); break; case Curses.KeyDown: case 14: // Control-n result = MoveDown (); break; case 22: // Control-v case Curses.KeyNPage: PageDown (); break; case (int) '\n': Action (); break; case Curses.KeyPPage: case (int)'v' + Curses.KeyAlt: PageUp (); break; case Curses.KeyInsertChar: case 20: // Control-t if (listing [selected].Name == "..") return true; listing [selected].Marked = !listing [selected].Marked; if (listing [selected].Marked) marked++; else marked--; MoveDown (); break; default: result = false; break; } if (result) Curses.refresh (); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Utility; using System.Drawing; using System.Drawing.Imaging; namespace eIVOGo.Published { /// <summary> /// Summary description for GetBarCode39 /// </summary> public class GetBarCode39 : IHttpHandler { protected float _dpi = 600f; public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; response.Clear(); response.ContentType = "image/Jpeg"; //response.Buffer = true; //response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); //response.Expires = 0; response.Cache.SetCacheability(HttpCacheability.NoCache); String sCode = request.Params["QUERY_STRING"]; if (!String.IsNullOrEmpty(sCode)) { try { using (Bitmap img = sCode.GetCode39(false)) { img.SetResolution(_dpi, _dpi); img.Save(response.OutputStream, ImageFormat.Jpeg); img.Dispose(); } } catch (Exception ex) { Logger.Error(ex); } } //context.Response.CacheControl = "no-cache"; //context.Response.AppendHeader("Pragma", "No-Cache"); } public bool IsReusable { get { return false; } } } }
using UnityEngine; using Zenject; using Futulabs.HoloFramework; using Futulabs.HoloFramework.Targeting; using Futulabs.HoloFramework.Utils; [CreateAssetMenu(fileName = "MainSettings", menuName = "Installers/MainSettings")] public class MainSettings : ScriptableObjectInstaller<MainSettings> { public HeadAndGazeHandler.Settings _headAndGazeSettings; public CanvasCursor.Settings _canvasPointCursorSettings; public Raycaster.Settings _raycasterSettings; public GazeFollower.Settings _gazeFollowingSettings; public override void InstallBindings() { Container.BindInstance(_headAndGazeSettings); Container.BindInstance(_canvasPointCursorSettings); Container.BindInstance(_raycasterSettings); Container.BindInstance(_gazeFollowingSettings); } }
using CommonCore.Config; using CommonCore.Console; using CommonCore.DebugLog; using CommonCore.Messaging; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; namespace CommonCore { /* * CommonCore Base class * Initializes CommonCore components */ public class CCBase { public static bool Initialized { get; private set; } private static List<CCModule> Modules; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void OnApplicationStart() { if (!CCParams.AutoInit) return; Debug.Log("Initializing CommonCore..."); HookApplicationQuit(); HookSceneEvents(); CreateFolders(); Modules = new List<CCModule>(); if (CCParams.AutoloadModules) { InitializeEarlyModules(); InitializeModules(); } Initialized = true; Debug.Log("...done!"); } private static void InitializeEarlyModules() { //initialize Debug, Config, Console, MessageBus Modules.Add(new DebugModule()); Modules.Add(new QdmsMessageBus()); Modules.Add(new ConfigModule()); Modules.Add(new ConsoleModule()); } private static void InitializeModules() { //initialize other modules using reflection var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany((assembly) => assembly.GetTypes()) .Where((type) => typeof(CCModule).IsAssignableFrom(type)) .Where((type) => (!type.IsAbstract && !type.IsGenericTypeDefinition)) .Where((type) => null != type.GetConstructor(new Type[0])) .Where((type) => type.GetCustomAttributes(typeof(CCExplicitModule),true).Length == 0) .ToArray(); foreach (var t in types) { try { Modules.Add((CCModule)Activator.CreateInstance(t)); } catch (Exception e) { Debug.Log(e); } } } private static void HookSceneEvents() { SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.sceneUnloaded += OnSceneUnloaded; Debug.Log("Hooked scene events!"); } static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { Debug.Log("CommonCore: Executing OnSceneLoaded..."); foreach(CCModule m in Modules) { try { m.OnSceneLoaded(); } catch(Exception e) { Debug.Log(e); } } Debug.Log("CommonCore: ...done!"); } static void OnSceneUnloaded(Scene current) { Debug.Log("CommonCore: Executing OnSceneUnloaded..."); foreach (CCModule m in Modules) { try { m.OnSceneUnloaded(); } catch (Exception e) { Debug.Log(e); } } Debug.Log("CommonCore: ...done!"); } //Game start and end are not hooked and must be explicitly called public static void OnGameStart() { Debug.Log("CommonCore: Executing OnGameStart..."); foreach (CCModule m in Modules) { try { m.OnGameStart(); } catch (Exception e) { Debug.Log(e); } } Debug.Log("CommonCore: ...done!"); } public static void OnGameEnd() { Debug.Log("CommonCore: Executing OnGameEnd..."); foreach (CCModule m in Modules) { try { m.OnGameEnd(); } catch (Exception e) { Debug.Log(e); } } Debug.Log("CommonCore: ...done!"); } private static void HookApplicationQuit() { //hook application unload (a bit hacky) GameObject hookObject = new GameObject(); CCExitHook hookScript = hookObject.AddComponent<CCExitHook>(); hookScript.OnApplicationQuitDelegate = new LifecycleEventDelegate(OnApplicationQuit); Debug.Log("Hooked application quit!"); } internal static void OnApplicationQuit() { Debug.Log("Cleaning up CommonCore..."); //execute quit methods and unload modules foreach(CCModule m in Modules) { try { m.OnApplicationQuit(); } catch(Exception e) { Debug.Log(e); } } Modules = null; GC.Collect(); Debug.Log("...done!"); } private static void CreateFolders() { try { Directory.CreateDirectory(CCParams.SavePath); } catch(Exception e) { Debug.LogError("Failed to setup directories (may cause problems during game execution)"); Debug.LogException(e); } } } }
using System.ComponentModel.DataAnnotations; namespace AnimalShelterApi.Models { public class Cat { public int CatId {get;set;} [StringLength(20)] [Required] public string Name {get;set;} [Required] [StringLength(20)] public string Color {get;set;} [Required] [StringLength(20)] public string Temperament {get;set;} [Required] [StringLength(500)] public string Description {get;set;} } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Common.Utilities { /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.Common.Utilities /// Class: CacheItemExpiredCallback /// ----------------------------------------------------------------------------- /// <summary> /// The CacheItemExpiredCallback delegate defines a callback method that notifies /// the application when a CacheItem is Expired (when an attempt is made to get the item) /// </summary> /// ----------------------------------------------------------------------------- public delegate object CacheItemExpiredCallback(CacheItemArgs dataArgs); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication.Controllers { public class BMapController : Controller { // GET: BMap public ActionResult Index() { return View(); } public ActionResult Temp() { return View(); } public ActionResult HoneyComb() { return View(); } public ActionResult PointDensityRect() { return View(); } } }
using UnityEngine; using Game; namespace Player { public class PlayerObstacleCollisionDetector : MonoBehaviour { [SerializeField] private Transform centerEyeCamera; [SerializeField] private float collisionRadius; private CapsuleCollider _collider; // Start is called before the first frame update void Start() { _collider = GetComponent<CapsuleCollider>(); _collider.radius = collisionRadius; } void LateUpdate() { UpdateCollider(); } void UpdateCollider() { var cameraWorldPos = centerEyeCamera.position; var cameraLocalPos = centerEyeCamera.localPosition; //Adjust collider height + collider position according to the HMD position _collider.center = new Vector3(cameraLocalPos.x, (cameraWorldPos.y / 2) + 0.15f, cameraLocalPos.z); _collider.height = cameraWorldPos.y; } private void OnTriggerEnter(Collider other) { //Check For Collisions with obstacles if (other.CompareTag("Obstacle") || other.CompareTag("Enemy")) { GameStats.Stats.obstacleHitCount++; //Round Stats PlayerManager.Instance.AddHealth(-GameSettings.Instance.bulletDamage); } else if (other.CompareTag("Bullet")) { GameStats.Stats.enemyHitCount++; //Round Stats PlayerManager.Instance.AddHealth(-GameSettings.Instance.bulletDamage); } } } }