text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WinCompetitionsParsing.DAL.Domain; using WinCompetitionsParsing.DAL.Repositories.Abstract; namespace WinCompetitionsParsing.DAL.Repositories.Implementation { public class SubcategoryRepository : ISubcategoryRepository { private readonly MakeUpContext db; public SubcategoryRepository() { db = new MakeUpContext(); } public IEnumerable<Subcategory> GetAllSubcategories() { return db.Subcategories; } public IEnumerable<Subcategory> GetSubcategories(string nameCategory) { return db.Subcategories.Where(x => x.Category == nameCategory).ToList(); } } }
using ExamSystem.DataAccess.Context; using ExamSystem.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ExamSystem.DataAccess { public class UserDal : IUserDal { public User Get(Expression<Func<User, bool>> filter) { using (var context = new ExamSystemContext()) { return context.Set<User>().SingleOrDefault(filter); } } public IList<User> GetList(Expression<Func<User, bool>> filter = null) { using (var context = new ExamSystemContext()) { return filter == null ? context.Set<User>().ToList() : context.Set<User>().Where(filter).ToList(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CandyCane { public class Helper { public static string _projectName; public static string _projectType; public static bool _typeSet = false; internal static string GetProjectPath() { string projectPath = Environment.CurrentDirectory; for (int i = 0; i < 2; i++) { projectPath = System.IO.Path.GetDirectoryName(projectPath); } return projectPath + @"\"; } internal static string GetRootPath(string projectName) { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + projectName; return path; } public static void ProjectCreatedStuff(string projectType) { _projectType = projectType; Console.WriteLine("Ein {0}projekt wurde erstellt. Beliebige Taste drücken um zu Beenden.", projectType); _typeSet = true; Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using eIVOGo.Module.EIVO.Item; using Model.InvoiceManagement; using Model.DataEntity; using Model.Security.MembershipManagement; using Business.Helper; using Model.Locale; namespace eIVOGo.SAM { public partial class PrintReceiptPage : System.Web.UI.Page { private UserProfileMember _userProfile; protected void Page_Load(object sender, EventArgs e) { _userProfile = WebPageUtility.UserProfile; initializeData(); } protected virtual void initializeData() { //IEnumerable<int> items = Session["PrintDoc"] as IEnumerable<int>; //Session.Remove("PrintDoc"); //IEnumerable<int> unPrintID = Session["UnPrintDoc"] as IEnumerable<int>; //Session.Remove("UnPrintDoc"); //用來判斷此份收據是否為正本(未列印) IEnumerable<int> items; using (InvoiceManager mgr = new InvoiceManager()) { items = mgr.GetTable<DocumentPrintQueue>().Where(i => i.UID == _userProfile.UID & i.CDS_Document.DocType == (int)Naming.DocumentTypeDefinition.E_Receipt).Select(i => i.DocID).ToList(); } if ( items!=null ) { SOGOReceiptView finalView = null; var mgr = dsEntity.CreateDataManager(); foreach (var item in items) { SOGOReceiptView view = (SOGOReceiptView)this.LoadControl("~/Module/EIVO/Item/SOGOReceiptView.ascx"); finalView = view; view.InitializeAsUserControl(this.Page); view.Item = mgr.EntityList.Where(r => r.ReceiptID == item).FirstOrDefault(); //if (unPrintID.Contains(item)) // view.IsUnPrint = true; //收據是正本 theForm.Controls.Add(view); } if (finalView != null) finalView.IsFinal = true; } } } }
namespace SGDE.API.Controllers { #region Using using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Domain.Supervisor; using Microsoft.Extensions.Logging; using System; using Domain.ViewModels; using System.Linq; #endregion [Authorize] [Route("api/[controller]")] [ApiController] public class HourTypesController : ControllerBase { private readonly ISupervisor _supervisor; private readonly ILogger<HourTypesController> _logger; public HourTypesController(ILogger<HourTypesController> logger, ISupervisor supervisor) { _logger = logger; _supervisor = supervisor; } // GET api/hourtype/5 [HttpGet("{id}")] public object Get(int id) { try { return _supervisor.GetHourTypeById(id); } catch (Exception ex) { _logger.LogError(ex, "Exception: "); return StatusCode(500, ex); } } [HttpGet] public object Get() { try { var data = _supervisor.GetAllHourType().ToList(); return new { Items = data, data.Count }; } catch (Exception ex) { _logger.LogError(ex, "Exception: "); return StatusCode(500, ex); } } [HttpPost] public object Post([FromBody]HourTypeViewModel hourTypeViewModel) { try { var result = _supervisor.AddHourType(hourTypeViewModel); return result; } catch (Exception ex) { _logger.LogError(ex, "Exception: "); return StatusCode(500, ex); } } [HttpPut] public object Put([FromBody]HourTypeViewModel hourTypeViewModel) { try { if (_supervisor.UpdateHourType(hourTypeViewModel) && hourTypeViewModel.id != null) { return _supervisor.GetHourTypeById((int)hourTypeViewModel.id); } return null; } catch (Exception ex) { _logger.LogError(ex, "Exception: "); return StatusCode(500, ex); } } // DELETE: api/hourtype/5 [HttpDelete("{id:int}")] //[Route("hourtype/{id:int}")] public object Delete(int id) { try { return _supervisor.DeleteHourType(id); } catch (Exception ex) { _logger.LogError(ex, "Exception: "); return StatusCode(500, ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Scriptables/StearingRef")] public class SOStearingInputs : ScriptableObject { public SOStearingInputs Instance { get; private set; } public StearingInputs Value { get; private set; } public int _PositiveXMovement { get; private set; } public int _NegativeXMovement { get; private set; } public void CreateRunTimeObject(StearingInputs val) { Instance = ScriptableObject.CreateInstance<SOStearingInputs>(); Instance.SetValue(val); } public void SetValue(StearingInputs val) { Value = val; } public void IncreasePositiveMovement() { _PositiveXMovement++; } public void IncreaseNegativeMovement() { _NegativeXMovement++; } public void ResetDirectionalMovement() { _PositiveXMovement = 0; _NegativeXMovement = 0; } }
using System; using System.Runtime.Serialization; namespace IoUring { /// <summary> /// Exception thrown if the kernel produced more Completion Queue Events than the application was able to consume. /// This is typically the case, if Submission Queue Entries are produced faster than the consumption of their completions. /// By default the Completion Queue is sized twice the size of the Submission Queue to allow for some slack. /// It is however up to the application to ensure Completion Queue Events are consumed before the Queue overflows. /// </summary> public class CompletionQueueOverflowException : Exception { /// <summary> /// The number of overflowed Events /// </summary> public long Overflow { get; } public CompletionQueueOverflowException(long overflow) : base($"Too many unconsumed Completion Queue Events: {overflow}") { Overflow = overflow; } protected CompletionQueueOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
 using System; using System.IO; using System.AddIn.Contract; using System.AddIn.Pipeline; #if PIPELINE_BUILDER using PipelineHints; [assembly: SegmentAssemblyName(PipelineSegment.AddInSideAdapter, "Tivo.Has.AddInSideAdapters")] [assembly: SegmentAssemblyName(PipelineSegment.AddInView, "Tivo.Has.AddInView")] [assembly: SegmentAssemblyName(PipelineSegment.HostSideAdapter, "Tivo.Has.HostSideAdapter")] [assembly: SegmentAssemblyName(PipelineSegment.HostView, "Tivo.Has.HostView")] #endif namespace Tivo.Has.Contracts { [AddInContract] public interface IHmeApplicationDriverContract : IContract { IHasApplicationConfiguratorContract GetApplicationConfiguration(); IListContract<IHmeApplicationIdentityContract> ApplicationIdentities { get; } IHmeConnectionContract CreateHmeConnection(IHmeApplicationIdentityContract identity, string baseUri, IHmeStreamContract inputStream, IHmeStreamContract outputStream); string GetWebPath(IHmeApplicationIdentityContract identity); void HandleEventsAsync(IHmeConnectionContract connection); void RunOneAsync(IHmeConnectionContract connection); #if PIPELINE_BUILDER [EventAdd("ApplicationEnded")] #endif void ApplicationEndedEventAdd(IApplicationEndedEventHandler handler); #if PIPELINE_BUILDER [EventRemove("ApplicationEnded")] #endif void ApplicationEndedEventRemove(IApplicationEndedEventHandler handler); } #if PIPELINE_BUILDER [EventHandler] #endif public interface IApplicationEndedEventHandler : IContract { void Handler(IApplicationEndedEventArgs args); } #if PIPELINE_BUILDER [EventArgs] #endif public interface IApplicationEndedEventArgs : IContract { } }
namespace AppBuilder.Shared { public class ProjectBlob { public string Name { get; set; } public byte[] CompressedFiles { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class SlideEventTrigger : MonoBehaviour { PlayerController player; void Start() { player = GameObject.FindGameObjectWithTag("Player").GetOrAddComponent<PlayerController>(); EventTrigger eventTrigger = gameObject.AddComponent<EventTrigger>(); EventTrigger.Entry entry_PointerDown = new EventTrigger.Entry(); entry_PointerDown.eventID = EventTriggerType.PointerDown; entry_PointerDown.callback.AddListener((data) => { OnPointerDown((PointerEventData)data); }); eventTrigger.triggers.Add(entry_PointerDown); EventTrigger.Entry entry_PointerUp = new EventTrigger.Entry(); entry_PointerUp.eventID = EventTriggerType.PointerUp; entry_PointerUp.callback.AddListener((data) => { OnPointerUp((PointerEventData)data); }); eventTrigger.triggers.Add(entry_PointerUp); } void OnPointerDown(PointerEventData data) { player.SlideBtnDown(); } void OnPointerUp(PointerEventData data) { player.SlideBtnUp(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class cartasRobadas : MonoBehaviour { public int carta; bool coli; //PANEL PARTIDA public GameObject Panel; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Panel == null) { Panel = GameObject.Find("GAME"); } transform.Rotate(Vector3.up * 100 * Time.deltaTime); } void OnCollisionEnter (Collision col) { ///---------------CARTAS--------------- if(col.gameObject.tag == "Player") { if(!coli) { PlayerPrefs.SetInt("card"+carta, PlayerPrefs.GetInt("card"+carta)+1); coli = true; } Panel.GetComponent<GameOffline>().StolenCardsB += 1; Destroy(gameObject); } } }
using NUnit.Framework; using Restaurant365.Core; namespace Restaurant365.Test { class UnlimitedCharcterDelimiterParserTest { const string DelimiterStarting = "//"; const string DelimiterEnding = "\n"; [Test] public void Parser_Should_Parse() { var delimterParser = new UnlimitedCharacterDelimiterParser(DelimiterStarting, DelimiterEnding); var result = delimterParser.Parse("//[***]\n11***22***33"); Assert.IsTrue(result.Contains("***") && result.Count == 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace oopsconcepts { public delegate void Helloword(string test); public class Delegaete { public void testDelegate(string test) { Console.WriteLine("Delegate is "+test ); } public void testDelegate1(string test) { Console.WriteLine("Delegate is " + test); } //Delegate is Type safe function Pointer public static void Main() { Delegaete DE = new Delegaete(); Helloword hw=new Helloword(DE.testDelegate); hw += DE.testDelegate1; hw(" Type safe function Pointer"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace JimBobBennett.JimLib.Collections { public class DefinedSortOrderComparer<T, TKey> : IComparer<T> { private readonly IList<TKey> _sortedKeys; private readonly Func<T, TKey> _keyFunc; public DefinedSortOrderComparer(IEnumerable<TKey> sortedKeys, Func<T, TKey> keyFunc) { _sortedKeys = sortedKeys.ToList(); _keyFunc = keyFunc; } public int Compare(T x, T y) { var xKey = _keyFunc(x); var yKey = _keyFunc(y); var xPos = _sortedKeys.IndexOf(xKey); var yPos = _sortedKeys.IndexOf(yKey); if (xPos > -1) return yPos == -1 ? -1 : xPos.CompareTo(yPos); return yPos > -1 ? 1 : 0; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using System; public class ChangeSpeed : MonoBehaviour, IPointerClickHandler, CannonStateObserver { public CannonStateHandler stateHandler; [SerializeField] private float deltaValue; private float highestValue = 35.0f; private float lowestValue = 15.0f; private void changeSpeed(float increment_value) { CannonState state = stateHandler.getCannonState(); float newSpeed = state.speed + increment_value; if (newSpeed >= this.lowestValue && newSpeed <= this.highestValue) { state.speed = newSpeed; } else if (newSpeed < this.lowestValue) { state.speed = this.lowestValue; } else if (newSpeed > this.highestValue) { state.speed = this.highestValue; } state.speed = (float)Math.Round(state.speed, 1); stateHandler.setCannonState(state); } private void OnMouseDown() { // Michael: added !hasLanded condition (and getCannonState) CannonState state = stateHandler.getCannonState(); if(!state.hasLanded){ this.changeSpeed(this.deltaValue); } } public void OnPointerClick(PointerEventData pointerEventData) { // Michael: added !hasLanded condition (and getCannonState) CannonState state = stateHandler.getCannonState(); if(!state.hasLanded){ this.changeSpeed(this.deltaValue); } } public void applyChange(CannonState state){ gameObject.SetActive(!state.speedIsLocked); } void Start() { stateHandler.subscribe(this); this.applyChange(this.stateHandler.getCannonState()); } }
using System; using System.Linq; using FinanceBot.Models.EntityModels; namespace FinanceBot.Models.Repository { public static class RepositoryExtension { public static bool GetUser(this IUserAccountRepository userAccountRepository, int Id, out UserAccount userAccount) { var userInBase = userAccountRepository.Accounts.Where(u => Id == u.UserId); if (userInBase.Count() == 0) { userAccount = null; return false; } userAccount = userInBase.FirstOrDefault(); return true; } public static void InitUserDates(this UserAccount userAccount, int salaryDay = default) { if (salaryDay != default) { lock (userAccount.GetLock) { userAccount.SalaryDay = salaryDay; } } DateTime CurrentDay; DateTime NextDay; //если зп еще не выдавали в этом месяце, начинаем считать с сегодняшней даты //т.е обрабатываем сразу два случая: //-дата еще не наступила //-в месяце дней меньше, чем значение SalaryDay if (userAccount.SalaryDay > DateTime.Now.Day) { CurrentDay = DateTime.Now; int daysInCurrentMounth = DateTime.DaysInMonth(CurrentDay.Year, CurrentDay.Month); if(userAccount.SalaryDay > daysInCurrentMounth) { NextDay = new DateTime( CurrentDay.Year, CurrentDay.Month, daysInCurrentMounth); } else { NextDay = new DateTime( CurrentDay.Year, CurrentDay.Month, userAccount.SalaryDay); } } else { CurrentDay = new DateTime( DateTime.Today.Year, DateTime.Today.Month, userAccount.SalaryDay); NextDay = CurrentDay.AddMonths(1); } lock (userAccount.GetLock) { userAccount.CountdownDate = CurrentDay; userAccount.ResetDate = NextDay; } } public static Category GetCategory(this ICategoryRepository categoryRepository, UserAccount user, string name) { return categoryRepository .Categories .Where(c => c.Author == user && c.CategoryName == name && !c.IsBasic) .FirstOrDefault(); } } }
using System; using System.ComponentModel.DataAnnotations; namespace GlobalModels { /// <summary> /// DTO Model for frontend -> backend /// </summary> public sealed class NewDiscussion { [Required] [StringLength(20)] public string Movieid { get; set; } [Required] [StringLength(50)] public string Userid { get; set; } [Required] [StringLength(100)] public string Subject { get; set; } [Required] public string Topic { get; set; } public NewDiscussion() { } public NewDiscussion(string movieid, string uid, string subject, string topic) { Movieid = movieid; Userid = uid; Subject = subject; Topic = topic; } } }
using AorFramework.editor; using System; using System.Collections.Generic; namespace AorFramework.NodeGraph { public class AssetSearchController : NodeController { public override void update(bool updateParentLoop = true) { string sp = (string) m_nodeGUI.data.ref_GetField_Inst_Public("SearchPath"); if (string.IsNullOrEmpty(sp)) return; string sp2 = (string)m_nodeGUI.data.ref_GetField_Inst_Public("SearchPattern"); if (string.IsNullOrEmpty(sp2)) { sp2 = "*.*"; } List<EditorAssetInfo> eai; if ((bool) m_nodeGUI.data.ref_GetField_Inst_Public("IgnoreMETAFile")) { eai = EditorAssetInfo.FindEditorAssetInfoInPath(sp, sp2).filter((e) => { return (e.suffix.ToLower() != ".meta"); }); } else { eai = EditorAssetInfo.FindEditorAssetInfoInPath(sp, sp2); } if (eai != null) { List<string> assetPathList = new List<string>(); int i, len = eai.Count; for (i = 0; i < len; i++) { assetPathList.Add(eai[i].path); } string[] list = assetPathList.ToArray(); m_nodeGUI.data.ref_SetField_Inst_Public("AssetsPath", list); base.update(); } } } }
using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Management; namespace WF.SDK.Common { public class WfDriveInfo { public string LocalName { get; private set; } public string MappedUncPath { get; private set; } public long AvailableFreeSpace { get; private set; } public DriveType DriveType { get; private set; } public string DriveFormat { get; private set; } public bool IsLocal { get { return this.DriveType != DriveType.Network; } } public bool IsMapped { get { return !this.IsLocal; } } public WfDriveInfo(DriveInfo info) { this.LocalName = new WfPath(info.Name).FullPath; this.DriveType = info.DriveType; if (info.IsReady) { this.AvailableFreeSpace = info.AvailableFreeSpace; } else { this.AvailableFreeSpace = -1; } if (info.IsReady) { this.DriveFormat = info.DriveFormat; } else { this.DriveFormat = "The device is not ready."; } this.MappedUncPath = "Drive is local."; } /// <summary> /// Turns the given path into a localized path on this machine if it can be. /// </summary> public string LocalizePath(string fullpath) { return this.LocalizePath(new WfPath(fullpath)); } /// <summary> /// Turns the given path into a localized path on this machine if it can be. /// </summary> public string LocalizePath(WfPath fullpath) { var temp = fullpath.FullPath; return temp.Replace(this.MappedUncPath, this.LocalName); } /// <summary> /// Turns the given path into the remotized path on this machine if it can be. /// </summary> public string RemotizePath(string fullpath) { return this.RemotizePath(new WfPath(fullpath)); } /// <summary> /// Turns the given path into the remotized path on this machine if it can be. /// </summary> public string RemotizePath(WfPath fullpath) { var temp = fullpath.FullPath; return temp.Replace(this.LocalName, this.MappedUncPath); } #region Static /// <summary> /// Gets the WfDriveInfo which exists at the root of the path given. If a null is returned, and the path really exists /// then this is a pure unc path with no local drive mapping. /// </summary> public static WfDriveInfo GetWfDriveInfo(string path) { return WfDriveInfo.FindMatchingDrive(WfDriveInfo.GetDrives(), path); } /// <summary> /// Returns a WfDriveInfo object for every drive on the local system. Includes local and mapped disks. /// </summary> public static List<WfDriveInfo> GetDrives() { List<WfDriveInfo> ret = new List<WfDriveInfo>(); //Load up the drive information DriveInfo.GetDrives().ToList().ForEach(i => ret.Add(new WfDriveInfo(i))); //Get the var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_MappedLogicalDisk"); var items = searcher.Get().OfType<ManagementObject>().ToList(); //For network drives, get the path ret.ForEach(i => { if (!i.IsLocal) { try { i.MappedUncPath = new WfPath(items.FirstOrDefault(j => j["Name"].ToString().ToLower() + "\\" == i.LocalName)["ProviderName"].ToString()).FullPath; } catch { } } }); return ret; } /// <summary> /// Attempts to find the WfDriveInfo object that the path is rooted on. /// </summary> private static WfDriveInfo FindMatchingDrive(List<WfDriveInfo> list, string path) { WfDriveInfo ret = null; if (list == null) { return ret; } if (list.Count == 0) { return ret; } var temp = new WfPath(path).FullPath; ret = list.FirstOrDefault(i => temp.StartsWith(i.MappedUncPath.ToLower()) || temp.StartsWith(i.LocalName.ToLower())); return ret; } #endregion } }
using System; namespace Auth0.OidcClient { [Obsolete("It is recommended you leave Browser unassigned to accept the library default or assign an instance of WebAuthenticationBrokerBrowser if you need to enable Windows authentication.")] public class PlatformWebView : WebAuthenticationBrokerBrowser { public PlatformWebView(bool enableWindowsAuthentication = false) : base(enableWindowsAuthentication) { } } }
using PbStore.Domain.Pedidos; using PbStore.Domain.Pedidos.Repositorios; namespace UnitTestProject1.Mocks { public class RepositorioPedido : IRepositorioPedido { public void Salvar(Pedido pedido) { } } }
using Proyecto_Web.Conection; using Proyecto_Web.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Proyecto_Web.Vistas.Private { public partial class gestionar_proveedor : System.Web.UI.Page { private IDatos da = new Datos(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Establece la consulta SQL a ejecutar string consulta = "SELECT ID,NOMBRE FROM sexo"; da.ConsultarDatos(consulta); // Asigna el valor a mostrar en el DropDownList sexolis.DataTextField = "NOMBRE"; ; // Asigna el valor del value en el DropDownList sexolis.DataValueField = "ID"; // Llena el DropDownList con los datos sexolis.DataSource = da.ConsultarDatos(consulta); // Carga los datos al controlador sexolis.DataBind(); } } protected void Consultar(object sender, EventArgs e) { string query = "Select ID_PERSONA,NOMBRE1,NOMBRE2,APELLIDO1,APELLIDO2,CELULAR,NACIMIENTO,DIRECCION,ESTADO,DETALLES,SEXO_ID_SEXO From persona WHERE ID_PERSONA='" + buscar.Text + "'"; da.ConsultarDatos(query); string nom1, nom2, ape1, ape2, celu, naci, direc, esta, deta, sexo, ident; foreach (System.Data.DataRow v in da.ConsultarDatos(query).Rows) { //aca haces las operaciones con cada fila de la tabla ej: ident = v["ID_PERSONA"].ToString(); nom1 = v["NOMBRE1"].ToString(); nom2 = v["NOMBRE2"].ToString(); ape1 = v["APELLIDO1"].ToString(); ape2 = v["APELLIDO2"].ToString(); celu = v["CELULAR"].ToString(); naci = v["NACIMIENTO"].ToString(); direc = v["DIRECCION"].ToString(); esta = v["ESTADO"].ToString(); deta = v["DETALLES"].ToString(); sexo = v["SEXO_ID_SEXO"].ToString(); cedula.Enabled = false; cedula.Text = "" + ident; nombre1.Text = "" + nom1; nombre2.Text = "" + nom2; apellido1.Text = "" + ape1; apellido2.Text = "" + ape2; direccion.Text = "" + direc; celular.Text = "" + celu; nacimiento.Text = "" + naci; sexolis.Text = "" + sexo; estado.Text = "" + esta; detalle.Text = "" + deta; //SelectedValue //mi.ToString = mision; } } protected void Guardar(object sender, EventArgs e) { string query = "UPDATE persona SET NOMBRE1 = '" + nombre1.Text + "', NOMBRE2 = '" + nombre2.Text + "', APELLIDO1 = '" + apellido1.Text + "', APELLIDO2 = '" + apellido2.Text + "', CELULAR = " + celular.Text + ", DIRECCION = '" + direccion.Text + "', ESTADO = '" + estado.Text + "', DETALLES = '" + detalle.Text + "', SEXO_ID_SEXO=" + sexolis.SelectedValue + " WHERE ID_PERSONA =" + cedula.Text + ""; da.OperarDatos(query); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DigitalRuby.WeatherMaker { /// <summary> /// Simple screenshot script for game view. Press R to take screenshots, file is saved to desktop. There is a short delay from pressing R and the screenshot actually saving. /// </summary> public class WeatherMakerScreenshotScript : MonoBehaviour { private int needsScreenshot; private void Update() { if (needsScreenshot == 0) { needsScreenshot = Input.GetKeyDown(KeyCode.R) ? 1 : 0; } else if (++needsScreenshot == 64) { ScreenCapture.CaptureScreenshot(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "/screenshot.png"); needsScreenshot = 0; } } } }
using DotNetNuke.Common; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Permissions; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using DotNetNuke.Instrumentation; namespace QLHD { public partial class QLHD_GIAHAN_CN : DotNetNuke.Entities.Modules.UserModuleBase { #region Khai báo, định nghĩa đối tượng private readonly ILog log = LoggerSource.Instance.GetLogger(typeof(QLHD_GIAHAN_CN).FullName); public string vPathCommon = ClassParameter.vPathCommon; public string vPathCommonJS = ClassParameter.vPathCommonJavascript; ClassCommon clsCommon = new ClassCommon(); QLHDDataContext vDC = new QLHDDataContext(); UserInfo _currentUser = UserController.Instance.GetCurrentUserInfo(); DataTable dtTable; int HD_ID = 0; int GIAHAN_ID = 0; public string vJavascriptMask; #endregion protected void Page_Load(object sender, EventArgs e) { vJavascriptMask = ClassParameter.vJavascriptMaskNumber; HD_ID = Convert.ToInt32(Request.QueryString["HD_ID"]); GIAHAN_ID = Convert.ToInt32(Request.QueryString["GIAHAN_ID"]); try { if (!String.IsNullOrEmpty(Session[TabId.ToString() + "_Message"] as string) && !String.IsNullOrEmpty(Session[TabId.ToString() + "_Type"] as string)) { if (Session[TabId.ToString() + "_Message"].ToString() != "" && Session[TabId.ToString() + "_Type"].ToString() != "") { ClassCommon.THONGBAO_TOASTR(Page, null, _currentUser, Session[TabId.ToString() + "_Message"].ToString(), "Thông báo", Session[TabId.ToString() + "_Type"].ToString()); } Session[TabId.ToString() + "_Message"] = ""; Session[TabId.ToString() + "_Type"] = ""; } if (!IsPostBack) { SetInfoForm(GIAHAN_ID); } } catch (Exception ex) { ClassCommon.THONGBAO_TOASTR(Page, ex, _currentUser, "Có lỗi trong quá trình xử lý, vui lòng liên hệ với quản trị!", "Thông báo lỗi", "error"); log.Error("", ex); } } #region Controller public void UpdateQLHD_GIAHANHD(int HD_ID, int vSoLanGiaHan) { var obj = vDC.QLHD_HDs.Where(x => x.HD_ID == HD_ID).FirstOrDefault(); obj.HD_COGIAHAN = true; obj.HD_SOLANGIAHAN = vSoLanGiaHan; vDC.SubmitChanges(); } public void InsertQLHD_GIAHANHD(QLHD_GIAHANHD objQLHD_GIAHANHD) { vDC.QLHD_GIAHANHDs.InsertOnSubmit(objQLHD_GIAHANHD); vDC.SubmitChanges(); } public void UpdateQLHD_GIAHANHD(QLHD_GIAHANHD objQLHD_GIAHANHD) { var obj = GetQLHD_GIAHANHD(objQLHD_GIAHANHD.GIAHAN_ID); obj.HD_BLTAMUNG_TUNGAY = objQLHD_GIAHANHD.HD_BLTAMUNG_TUNGAY; obj.HD_BLTAMUNG_DENNGAY = objQLHD_GIAHANHD.HD_BLTAMUNG_DENNGAY; obj.HD_BLTAMUNG_TGNHAC = objQLHD_GIAHANHD.HD_BLTAMUNG_TGNHAC; obj.HD_BLTHANHTOANVATTU_DENNGAY = objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_DENNGAY; obj.HD_BLTHANHTOANVATTU_TGNHAC = objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TGNHAC; obj.HD_BLTHANHTOANVATTU_TUNGAY = objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TUNGAY; obj.HD_BLTHUCHIENHOPDONG_DENNGAY = objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_DENNGAY; obj.HD_BLTHUCHIENHOPDONG_TGNHAC = objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TGNHAC; obj.HD_BLTHUCHIENHOPDONG_TUNGAY = objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TUNGAY; obj.HD_HIEULUC_HD = objQLHD_GIAHANHD.HD_HIEULUC_HD; obj.HD_NGAYHETHAN_HD = objQLHD_GIAHANHD.HD_NGAYHETHAN_HD; obj.HD_NGAYKHOICONG = objQLHD_GIAHANHD.HD_NGAYKHOICONG; obj.HD_NGAYHETHANTHICONG = objQLHD_GIAHANHD.HD_NGAYHETHANTHICONG; obj.HD_TGNHAC = objQLHD_GIAHANHD.HD_TGNHAC; obj.HD_THICONG_TGNHAC = objQLHD_GIAHANHD.HD_THICONG_TGNHAC; obj.HD_ID = objQLHD_GIAHANHD.HD_ID; obj.GIAHAN_ID = objQLHD_GIAHANHD.GIAHAN_ID; obj.GIAHAN_GHICHU = objQLHD_GIAHANHD.GIAHAN_GHICHU; vDC.SubmitChanges(); } public QLHD_GIAHANHD GetQLHD_GIAHANHD(int ID) { var objQLHD_GIAHANHD = (from obj in vDC.QLHD_GIAHANHDs where obj.GIAHAN_ID == ID orderby obj.HD_ID descending select obj).FirstOrDefault(); return objQLHD_GIAHANHD; } #endregion #region SetFormInfo public void SetInfoForm(int GIAHAN_ID) { if (GIAHAN_ID == 0) // Thêm mới { var objQLHD_HD = vDC.QLHD_HDs.FirstOrDefault(); if (objQLHD_HD != null) { txtHieuLucHopDong.SelectedDate = objQLHD_HD.HD_HIEULUC_HD; txtNgayHetHanHongDong.SelectedDate = objQLHD_HD.HD_NGAYHETHAN_HD; txtTGDenHanHD.Text = String.Format("{0:#,##0.##}", objQLHD_HD.HD_TGNHAC).Replace(",", "."); txtNgayKhoiCong.SelectedDate = objQLHD_HD.HD_NGAYKHOICONG; txtNgayHetHanThiCong.SelectedDate = objQLHD_HD.HD_NGAYHETHANTHICONG; txtTGDenHanThiCong.Text = String.Format("{0:#,##0.##}", objQLHD_HD.HD_THICONG_TGNHAC).Replace(",", "."); txtBLThucHienHopDongTuNgay.SelectedDate = objQLHD_HD.HD_BLTHUCHIENHOPDONG_TUNGAY; txtBLThucHienHopDongDenNgay.SelectedDate = objQLHD_HD.HD_BLTHUCHIENHOPDONG_DENNGAY; txtTGDenHanBLThucHienHD.Text = String.Format("{0:#,##0.##}", objQLHD_HD.HD_BLTHUCHIENHOPDONG_TGNHAC).Replace(",", "."); txtBLThanhToanVatTuTuNgay.SelectedDate = objQLHD_HD.HD_BLTHANHTOANVATTU_TUNGAY; txtBLThanhToanVatTuDenNgay.SelectedDate = objQLHD_HD.HD_BLTHANHTOANVATTU_DENNGAY; txtTGDenHanBLThanhToanVatTu.Text = String.Format("{0:#,##0.##}", objQLHD_HD.HD_BLTHANHTOANVATTU_TGNHAC).Replace(",", "."); txtBLTamUngTuNgay.SelectedDate = objQLHD_HD.HD_BLTAMUNG_TUNGAY; txtBLTamUngDenNgay.SelectedDate = objQLHD_HD.HD_BLTAMUNG_DENNGAY; txtTGDenHanBLTamUng.Text = String.Format("{0:#,##0.##}", objQLHD_HD.HD_BLTAMUNG_TGNHAC).Replace(",", "."); } } else { var objQLHD_GIAHANHD = vDC.QLHD_GIAHANHDs.Where(x => x.HD_ID == HD_ID && x.GIAHAN_ID == GIAHAN_ID).FirstOrDefault(); txtHieuLucHopDong.SelectedDate = objQLHD_GIAHANHD.HD_HIEULUC_HD; txtNgayHetHanHongDong.SelectedDate = objQLHD_GIAHANHD.HD_NGAYHETHAN_HD; txtTGDenHanHD.Text = String.Format("{0:#,##0.##}", objQLHD_GIAHANHD.HD_TGNHAC).Replace(",", "."); txtNgayKhoiCong.SelectedDate = objQLHD_GIAHANHD.HD_NGAYKHOICONG; txtNgayHetHanThiCong.SelectedDate = objQLHD_GIAHANHD.HD_NGAYHETHANTHICONG; txtTGDenHanThiCong.Text = String.Format("{0:#,##0.##}", objQLHD_GIAHANHD.HD_THICONG_TGNHAC).Replace(",", "."); txtBLThucHienHopDongTuNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TUNGAY; txtBLThucHienHopDongDenNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_DENNGAY; txtTGDenHanBLThucHienHD.Text = String.Format("{0:#,##0.##}", objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TGNHAC).Replace(",", "."); txtBLThanhToanVatTuTuNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TUNGAY; txtBLThanhToanVatTuDenNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_DENNGAY; txtTGDenHanBLThanhToanVatTu.Text = String.Format("{0:#,##0.##}", objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TGNHAC).Replace(",", "."); txtBLTamUngTuNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTAMUNG_TUNGAY; txtBLTamUngDenNgay.SelectedDate = objQLHD_GIAHANHD.HD_BLTAMUNG_DENNGAY; txtTGDenHanBLTamUng.Text = String.Format("{0:#,##0.##}", objQLHD_GIAHANHD.HD_BLTAMUNG_TGNHAC).Replace(",", "."); txtGhiChu.Text = objQLHD_GIAHANHD.GIAHAN_GHICHU; } } #endregion #region Page Event protected void btnCapNhat_Click(object sender, EventArgs e) { try { string o_Messages = ""; if (Check_ThoiGian(DateTime.Parse(txtNgayKhoiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanThiCong.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian(DateTime.Parse(txtBLThucHienHopDongTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongDenNgay.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian(DateTime.Parse(txtBLThanhToanVatTuTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuDenNgay.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian(DateTime.Parse(txtBLTamUngTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLTamUngDenNgay.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtNgayKhoiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanThiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongDenNgay.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuDenNgay.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false || Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtBLTamUngTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLTamUngDenNgay.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false ) { if (Check_ThoiGian(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Ngày hết hạn hợp đồng phải lớn hơn hoặc bằng ngày hiệu lực hợp đồng. Vui lòng kiểm tra lại."; txtNgayHetHanThiCong.Focus(); } if (Check_ThoiGian(DateTime.Parse(txtNgayKhoiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanThiCong.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Ngày hết hạn thi công phải lớn hơn hoặc bằng ngày khởi công. Vui lòng kiểm tra lại."; txtNgayHetHanThiCong.Focus(); } if (Check_ThoiGian(DateTime.Parse(txtBLThucHienHopDongTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongDenNgay.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Bảo lãnh thực hiện hợp đồng đến ngày phải lớn hơn hoặc bằng từ ngày. Vui lòng kiểm tra lại."; txtBLThucHienHopDongDenNgay.Focus(); } if (Check_ThoiGian(DateTime.Parse(txtBLThanhToanVatTuTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuDenNgay.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Bảo lãnh thanh toán vật tư đến ngày phải lớn hơn hoặc bằng từ ngày. Vui lòng kiểm tra lại."; txtBLThanhToanVatTuDenNgay.Focus(); } if (Check_ThoiGian(DateTime.Parse(txtBLTamUngTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLTamUngDenNgay.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Bảo lãnh tạm ứng đến ngày phải lớn hơn hoặc bằng từ ngày. Vui lòng kiểm tra lại."; txtBLThanhToanVatTuDenNgay.Focus(); } if (Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThanhToanVatTuDenNgay.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Thời gian bảo lãnh thanh toán vật tư phải nằm trong thời gian của hợp đồng. Vui lòng kiểm tra lại."; txtNgayKhoiCong.Focus(); } if (Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongTuNgay.SelectedDate.ToString()), DateTime.Parse(txtBLThucHienHopDongDenNgay.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Thời gian bảo lãnh thực hiện hợp đồng phải nằm trong thời gian của hợp đồng. Vui lòng kiểm tra lại."; txtBLThucHienHopDongTuNgay.Focus(); } if (Check_ThoiGian_DuAn_GiaiDoan(DateTime.Parse(txtHieuLucHopDong.SelectedDate.ToString()), DateTime.Parse(txtNgayKhoiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanThiCong.SelectedDate.ToString()), DateTime.Parse(txtNgayHetHanHongDong.SelectedDate.ToString()), out o_Messages) == false) { pnThongBao.Visible = true; lblThongBao.Text = "Thời gian thi công phải nằm trong thời gian của hợp đồng. Vui lòng kiểm tra lại."; txtNgayKhoiCong.Focus(); } } else { if (GIAHAN_ID == 0) // Thêm mới { var objQLHD_GIAHANHD = new QLHD_GIAHANHD(); objQLHD_GIAHANHD.HD_BLTAMUNG_TUNGAY = txtBLTamUngTuNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_BLTAMUNG_DENNGAY = txtBLTamUngDenNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_BLTAMUNG_TGNHAC = Int32.Parse(txtTGDenHanBLTamUng.Text.ToString().Replace(".", "")); objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_DENNGAY = txtBLThanhToanVatTuDenNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TGNHAC = Int32.Parse(txtTGDenHanBLThanhToanVatTu.Text.ToString().Replace(".", "")); objQLHD_GIAHANHD.HD_BLTHANHTOANVATTU_TUNGAY = txtBLThanhToanVatTuTuNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_DENNGAY = txtBLThucHienHopDongDenNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TGNHAC = Int32.Parse(txtTGDenHanBLThucHienHD.Text.ToString().Replace(".", "")); objQLHD_GIAHANHD.HD_BLTHUCHIENHOPDONG_TUNGAY = txtBLThucHienHopDongTuNgay.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_HIEULUC_HD = txtHieuLucHopDong.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_NGAYHETHAN_HD = txtNgayHetHanHongDong.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_TGNHAC = Int32.Parse(txtTGDenHanHD.Text.ToString().Replace(".", "")); objQLHD_GIAHANHD.HD_NGAYHETHANTHICONG = txtNgayHetHanThiCong.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_NGAYKHOICONG = txtNgayKhoiCong.SelectedDate ?? DateTime.Now; objQLHD_GIAHANHD.HD_THICONG_TGNHAC = Int32.Parse(txtTGDenHanThiCong.Text.ToString().Replace(".", "")); objQLHD_GIAHANHD.HD_ID = HD_ID; objQLHD_GIAHANHD.GIAHAN_GHICHU = txtGhiChu.Text; InsertQLHD_GIAHANHD(objQLHD_GIAHANHD); int vSoLanGiaHan = vDC.QLHD_GIAHANHDs.Where(x => x.HD_ID == HD_ID).ToList().Count; UpdateQLHD_GIAHANHD(HD_ID, vSoLanGiaHan); Session[TabId + "_Message"] = "Thêm mới gia hạn hợp đồng thành công"; Session[TabId + "_Type"] = "success"; Response.Redirect(Globals.NavigateURL()); } else { var objQLHD_HD = new QLHD_GIAHANHD(); objQLHD_HD.HD_ID = HD_ID; objQLHD_HD.HD_BLTAMUNG_TUNGAY = txtBLTamUngTuNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_BLTAMUNG_DENNGAY = txtBLTamUngDenNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_BLTAMUNG_TGNHAC = Int32.Parse(txtTGDenHanBLTamUng.Text.ToString().Replace(".", "")); objQLHD_HD.HD_BLTHANHTOANVATTU_DENNGAY = txtBLThanhToanVatTuDenNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_BLTHANHTOANVATTU_TGNHAC = Int32.Parse(txtTGDenHanBLThanhToanVatTu.Text.ToString().Replace(".", "")); objQLHD_HD.HD_BLTHANHTOANVATTU_TUNGAY = txtBLThanhToanVatTuTuNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_BLTHUCHIENHOPDONG_DENNGAY = txtBLThucHienHopDongDenNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_BLTHUCHIENHOPDONG_TGNHAC = Int32.Parse(txtTGDenHanBLThucHienHD.Text.ToString().Replace(".", "")); objQLHD_HD.HD_BLTHUCHIENHOPDONG_TUNGAY = txtBLThucHienHopDongTuNgay.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_HIEULUC_HD = txtHieuLucHopDong.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_NGAYHETHAN_HD = txtNgayHetHanHongDong.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_TGNHAC = Int32.Parse(txtTGDenHanHD.Text.ToString().Replace(".", "")); objQLHD_HD.HD_NGAYHETHANTHICONG = txtNgayHetHanThiCong.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_NGAYKHOICONG = txtNgayKhoiCong.SelectedDate ?? DateTime.Now; objQLHD_HD.HD_THICONG_TGNHAC = Int32.Parse(txtTGDenHanThiCong.Text.ToString().Replace(".", "")); objQLHD_HD.GIAHAN_ID = GIAHAN_ID; objQLHD_HD.GIAHAN_GHICHU = txtGhiChu.Text; UpdateQLHD_GIAHANHD(objQLHD_HD); int vSoLanGiaHan = vDC.QLHD_GIAHANHDs.Where(x => x.HD_ID == HD_ID).ToList().Count; UpdateQLHD_GIAHANHD(HD_ID, vSoLanGiaHan); Session[TabId + "_Message"] = "Cập nhật gia hạn hợp đồng thành công"; Session[TabId + "_Type"] = "success"; Response.Redirect(Globals.NavigateURL(), false); } } } catch (Exception ex) { ClassCommon.THONGBAO_TOASTR(Page, ex, _currentUser, ClassParameter.unknownErrorMessage, "Thông báo lỗi", "error"); log.Error("", ex); } } protected void btnBoQua_Click(object sender, EventArgs e) { Response.Redirect(Globals.NavigateURL("giahan", "mid=" + this.ModuleId, "title=Gia hạn hợp đồng", "HD_ID=" + HD_ID)); } #endregion #region Hàm kiểm tra ngày public bool Check_ThoiGian(DateTime NgayBatDau, DateTime NgayKetThuc, out string o_Messages) { try { o_Messages = ""; if (NgayBatDau > NgayKetThuc) { return false; } else { return true; } } catch (Exception ex) { o_Messages = "Đã có lỗi trong quá trình xử lý"; ClassCommon.THONGBAO_TOASTR(Page, ex, _currentUser, ClassParameter.unknownErrorMessage, "Thông báo lỗi", "error"); log.Error("", ex); return false; } } public bool Check_ThoiGian_DuAn_GiaiDoan(DateTime NgayBatDau, DateTime NgayBatDauGiaiDoan, DateTime NgayKetThucGiaiDoan, DateTime NgayKetThuc, out string o_Messages) { try { o_Messages = ""; if (NgayBatDau <= NgayBatDauGiaiDoan && NgayBatDau <= NgayKetThucGiaiDoan && NgayKetThuc >= NgayBatDauGiaiDoan && NgayKetThuc >= NgayKetThucGiaiDoan) { return true; } else { return false; } } catch (Exception ex) { o_Messages = "Đã có lỗi trong quá trình xử lý"; ClassCommon.THONGBAO_TOASTR(Page, ex, _currentUser, ClassParameter.unknownErrorMessage, "Thông báo lỗi", "error"); log.Error("", ex); return false; } } #endregion } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using System.Web; using static GetLabourManager.Helper.TreeBuilderHelper; namespace GetLabourManager.Helper { public class GangAllocationHelper { RBACDbContext db; public GangAllocationHelper(RBACDbContext _db) { this.db = _db; } //IsGangAllocated public bool IsGangAllocated(string code) { var records = db.GangSheetHeader.Include("SheetItems").FirstOrDefault(x => x.RequestCode == code); List<EmployeeGroup> group_list = new List<EmployeeGroup>(); bool isAssigned = false; if (records.SheetItems.Count > 0) { var categories_id = records.SheetItems.Select(a => a.Category).ToList().Distinct(); foreach (var item_id in categories_id) { var group_id = records.SheetItems.Where(x => x.Category == item_id).Select(a => a.Group).ToList().Distinct(); var allocation = db.GangAllocation.Include("Containers") .FirstOrDefault(x => x.RequestCode == code); foreach (var item in group_id) { var entity = db.EmployeeGroup.FirstOrDefault(x => x.Id == item); if (entity != null) { if (allocation != null) { if (!allocation.Containers.Exists(x => x.GroupId == entity.Id)) { group_list.Add(entity); } } else { group_list.Add(entity); } } } } } isAssigned = group_list.Count > 0 ? false : true; return isAssigned; } public Task<searchHeader> allocatedGangDetails(string term) { TaskCompletionSource<searchHeader> source = new TaskCompletionSource<searchHeader>(); var records = (from a in db.GangSheetHeader.AsEnumerable() join b in db.FieldClient on a.FieldClient equals b.Id where (a.RequestCode.Equals(term) & a.Status == "ALLOCATED") select new searchHeader { Code = a.RequestCode, Issued = string.Format("{0:dd/MM/yyyy}", a.DateIssued), Client = b.Name }).ToList().FirstOrDefault(); source.SetResult(records); return source.Task; } public RequestDetails getRequestDetails(string request_code) { var records = (from a in db.GangSheetHeader.Include("SheetItems").AsEnumerable() join b in db.Gang.AsEnumerable() on a.GangCode equals b.Code join c in db.FieldClient.AsEnumerable() on a.FieldClient equals c.Id where (a.RequestCode == request_code & a.Status == "APPROVED") select new RequestDetails { Id = a.Id, Casuals = a.SheetItems.Count, RequestDate = string.Format("{0:dd/MM/yyyy}", a.DateIssued), RequestedClient = c.Name, RequestedGang = b.Description, Shift = a.WorkShift ?? "", Week = a.WorkWeek ?? "" }).FirstOrDefault(); var sheet_item = db.GangSheetItems.FirstOrDefault(x => x.Header == records.Id); if (sheet_item != null) { var gang_type = db.EmpCategory.FirstOrDefault(x => x.Id == sheet_item.Category); records.GangType = gang_type.Category; } return records; } public Task<List<GangSearch>> SearchAllocatedGangs(string term) { TaskCompletionSource<List<GangSearch>> source = new TaskCompletionSource<List<GangSearch>>(); var records = (from a in db.GangSheetHeader.AsEnumerable() where (a.RequestCode.Contains(term) & a.Status == "ALLOCATED") select new GangSearch { title = a.RequestCode, description = "GANG: " + a.GangCode }).ToList(); source.SetResult(records); return source.Task; } public Task<List<GangAllocatedMembers>> getAllocatedGangs(string term) { TaskCompletionSource<List<GangAllocatedMembers>> source = new TaskCompletionSource<List<GangAllocatedMembers>>(); SqlParameter param = new SqlParameter("@term", term); var result = this.db.Database.SqlQuery<GangAllocatedMembers>("CasualMembersFilter @term", param).ToList(); source.SetResult(result.Distinct().ToList()); return source.Task; } public Task<List<GangRequests>> getGangsRequests() { TaskCompletionSource<List<GangRequests>> source = new TaskCompletionSource<List<GangRequests>>(); var result = this.db.Database.SqlQuery<GangRequests>("GangRequestList").ToList(); foreach (var item in result) { item.RequestDate = string.Format("{0:dd/MM/yyyy}", item.DateIssued); } source.SetResult(result.ToList()); return source.Task; } public GangDetails getGangDetails(string requestcode) { var entity = (from a in db.GangSheetHeader.Include("SheetItems").AsEnumerable() where a.RequestCode == requestcode join b in db.Gang.AsEnumerable() on a.GangCode equals b.Code join c in db.Users.AsEnumerable() on a.PreparedBy equals c.Id join d in db.EmpCategory on a.SheetItems.FirstOrDefault().Category equals d.Id select new GangDetails { Gang = b.Description, GangType = d.Category, PreparedBy = c.UserName, Shift = a.WorkShift + "-" + a.WorkWeek }).FirstOrDefault(); return entity; } public Task<List<GangAllocatedMembers>> getGangMembers(string term) { TaskCompletionSource<List<GangAllocatedMembers>> source = new TaskCompletionSource<List<GangAllocatedMembers>>(); SqlParameter param = new SqlParameter("@term", term); var result = this.db.Database.SqlQuery<GangAllocatedMembers>("AdviceLisApprovalProc @term", param).ToList(); source.SetResult(result.OrderBy(x => x.StaffCode).ThenBy(x => x.GroupName).ToList()); return source.Task; } public Task<List<ContainerDetails>> getGangContainers(string term) { TaskCompletionSource<List<ContainerDetails>> source = new TaskCompletionSource<List<ContainerDetails>>(); SqlParameter param = new SqlParameter("@term", term); var result = this.db.Database.SqlQuery<ContainerDetails>("AdviceListContainer @term", param).ToList(); source.SetResult(result.ToList()); return source.Task; } public Task<CostSheetDetails> getCostSheetRequest(string term) { TaskCompletionSource<CostSheetDetails> source = new TaskCompletionSource<CostSheetDetails>(); SqlParameter param = new SqlParameter("@term", term); var result = this.db.Database.SqlQuery<CostSheetDetails>("CostSheetRquestDetailsProc @term", param).FirstOrDefault(); source.SetResult(result); return source.Task; } // public Task<GangMemberListGrid> getGangCasualMembers(string term) { TaskCompletionSource<GangMemberListGrid> source = new TaskCompletionSource<GangMemberListGrid>(); SqlParameter param = new SqlParameter("@term", term); var result = this.db.Database.SqlQuery<GangRequestMembers>("GangCasualsDetailsProc @term", param).ToList(); foreach (var item in result) { item.Issued = string.Format("{0:dd/MM/yyyy}", item.DateIssued); } GangMemberListGrid members = new GangMemberListGrid() { items = new List<GangRequestMembers>(), totalCount = 0 }; members.items = result; members.totalCount = result.Count; source.SetResult(members); return source.Task; } public Task<ContainerListGrid> getGangContainerList(string term) { TaskCompletionSource<ContainerListGrid> source = new TaskCompletionSource<ContainerListGrid>(); var records = (from a in db.AllocationContainers where a.RequestCode == term join b in db.EmpCategory on a.CategoryId equals b.Id join c in db.VesselContainer on a.ContainerId equals c.Id select new ContainerDetails { Category = b.Category, Container = c.Continer, ContainerNumber = a.ContainerNumber }).ToList(); ContainerListGrid list_grid = new ContainerListGrid() { items = new List<ContainerDetails>(), totalCount = 0 }; list_grid.items = records;list_grid.totalCount = records.Count(); source.SetResult(list_grid); return source.Task; } public class searchHeader { public string Code { get; set; } public string Issued { get; set; } public string Client { get; set; } } public class GangSearch { public string title { get; set; } public string description { get; set; } } public class GangAllocatedMembers { public string RequestCode { get; set; } public string StaffCode { get; set; } public string FullName { get; set; } public string Gang { get; set; } public string GroupName { get; set; } public string Description { get; set; } public int Containers { get; set; } } public class GangAllocatedMembersList : GangAllocatedMembers { public double HoursWorked { get; set; } public double OvertimeHrs { get; set; } } public class GangRequests { public int Id { get; set; } public string RequestCode { get; set; } public string Name { get; set; } public DateTime DateIssued { get; set; } public string Status { get; set; } public string RequestDate { get; set; } } public class GangDetails { public string GangType { get; set; } public string Gang { get; set; } public string Shift { get; set; } public string PreparedBy { get; set; } } public class ContainerDetails { public string Container { get; set; } public string ContainerNumber { get; set; } public string Category { get; set; } } public class CostSheetDetails { public string RequestCode { get; set; } public string Name { get; set; } public string Gang { get; set; } public string Category { get; set; } public int Casuals { get; set; } public int Vessels { get; set; } } public class GangRequestMembers { public DateTime DateIssued { get; set; } public string Issued { get; set; } public string StaffCode { get; set; } public string Name { get; set; } public string GroupName { get; set; } public string Category { get; set; } } public class GangMemberListGrid { public int totalCount { get; set; } public List<GangRequestMembers> items { get; set; } } public class ContainerListGrid { public int totalCount { get; set; } public List<ContainerDetails> items { get; set; } } } }
using System.Threading.Tasks; using lauthai_api.DataAccessLayer.Data; using lauthai_api.DataAccessLayer.Repository.Interfaces; using lauthai_api.Models; using Microsoft.EntityFrameworkCore; namespace lauthai_api.DataAccessLayer.Repository.Implements { public class UserRpository : GenericRepository<User>, IUserRepository { private readonly LauThaiDbContext _context; public UserRpository(LauThaiDbContext context) : base(context) { _context = context; } public async Task<User> GetUserById(int id) { var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == id); return user; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SectorTest.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; using FluentNHibernate.Testing; using NUnit.Framework; namespace CGI.Reflex.Core.Tests.Entities { public class SectorTest : BaseDbTest { [Test] public void It_should_persist() { new PersistenceSpecification<Sector>(NHSession, new PersistenceEqualityComparer()) .CheckProperty(x => x.Name, Rand.String(30)) .VerifyTheMappings(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TruckController : MonoBehaviour { private float m_horizontalInput; private float m_verticalInput; private float m_steeringAngle; public WheelCollider frontRightW, frontLeftW, trailer1_leftW, trailer1_rightW, trailer2_leftW, trailer2_rightW, trailer3_leftW, trailer3_rightW, trailer4_leftW, trailer4_rightW, trailer5_leftW, trailer5_rightW; public Transform frontRightT, frontLeftT, trailer1_leftT, trailer1_rightT, trailer2_leftT, trailer2_rightT, trailer3_leftT, trailer3_rightT, trailer4_leftT, trailer4_rightT, trailer5_leftT, trailer5_rightT; public float maxSteerAngle = 30; // in degrees public float motorForce = 1000; public Player player; public LevelController levelController; private void Start() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); levelController = GameObject.FindGameObjectWithTag("LevelController").GetComponent<LevelController>(); } public void GetInput() { m_horizontalInput = Input.GetAxis("Horizontal"); m_verticalInput = Input.GetAxis("Vertical"); } private void Steer() { m_steeringAngle = maxSteerAngle * m_horizontalInput; frontLeftW.steerAngle = m_steeringAngle; frontRightW.steerAngle = m_steeringAngle; } private void Accelerate() { frontLeftW.motorTorque = m_verticalInput * motorForce; frontRightW.motorTorque = m_verticalInput * motorForce; } private void UpdateWheelPoses() { UpdateWheelPose(frontRightW, frontRightT); UpdateWheelPose(frontLeftW, frontLeftT); UpdateWheelPose(trailer1_leftW, trailer1_leftT); UpdateWheelPose(trailer1_rightW, trailer1_rightT); UpdateWheelPose(trailer2_leftW, trailer2_leftT); UpdateWheelPose(trailer2_rightW, trailer2_rightT); UpdateWheelPose(trailer3_leftW, trailer3_leftT); UpdateWheelPose(trailer3_rightW, trailer3_rightT); UpdateWheelPose(trailer4_leftW, trailer4_leftT); UpdateWheelPose(trailer4_rightW, trailer4_rightT); UpdateWheelPose(trailer5_leftW, trailer5_leftT); UpdateWheelPose(trailer5_rightW, trailer5_rightT); } private void UpdateWheelPose(WheelCollider _collider, Transform _transform) { Vector3 _pos = _transform.position; Quaternion _quat = _transform.rotation; _collider.GetWorldPose(out _pos, out _quat); _transform.position = _pos; _transform.rotation = _quat; if (transform.up.y <= 0) { if (levelController != null) levelController.GameOver(); } } private void FixedUpdate() { if (player.hasStarted) { GetInput(); Steer(); if (Input.GetAxis("Vertical") != 0) { Unbrake(); Accelerate(); } else { Brake(); } UpdateWheelPoses(); } else { Brake(); } } private void Brake() { frontLeftW.brakeTorque = 500; frontRightW.brakeTorque = 500; trailer1_leftW.brakeTorque = 500; trailer1_rightW.brakeTorque = 500; trailer2_leftW.brakeTorque = 500; trailer2_rightW.brakeTorque = 500; trailer3_leftW.brakeTorque = 500; trailer3_rightW.brakeTorque = 500; trailer4_leftW.brakeTorque = 500; trailer4_rightW.brakeTorque = 500; trailer5_leftW.brakeTorque = 500; trailer5_rightW.brakeTorque = 500; } private void Unbrake() { frontLeftW.brakeTorque = 0; frontRightW.brakeTorque = 0; trailer1_leftW.brakeTorque = 0; trailer1_rightW.brakeTorque = 0; trailer2_leftW.brakeTorque = 0; trailer2_rightW.brakeTorque = 0; trailer3_leftW.brakeTorque = 0; trailer3_rightW.brakeTorque = 0; trailer4_leftW.brakeTorque = 0; trailer4_rightW.brakeTorque = 0; trailer5_leftW.brakeTorque = 0; trailer5_rightW.brakeTorque = 0; } }
using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using System.Collections.Generic; using PDTech.OA.Model; namespace PDTech.OA.BLL { /// <summary> /// VIEW_WORKFLOW_STEP_NEXT_INFO /// </summary> public partial class VIEW_WORKFLOW_STEP_NEXT_INFO { private readonly PDTech.OA.DAL.VIEW_WORKFLOW_STEP_NEXT_INFO dal=new PDTech.OA.DAL.VIEW_WORKFLOW_STEP_NEXT_INFO(); public VIEW_WORKFLOW_STEP_NEXT_INFO() {} #region BasicMethod /// <summary> /// 获取一条信息 /// </summary> /// <param name="where"></param> /// <returns></returns> public Model.VIEW_WORKFLOW_STEP_NEXT_INFO Get_ViewInfo(Model.VIEW_WORKFLOW_STEP_NEXT_INFO Model) { return dal.Get_ViewInfo(Model); } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
using System; using System.Globalization; namespace Parsing_and_Persisting_Dates { class Program { static void Main(string[] args) { DateTimeOffset date = new DateTimeOffset( 2021, 05, 10, 18, 30, 59, TimeSpan.FromHours(8)); string dateAsString = date.ToString("O", new CultureInfo("sv-SE")); Console.WriteLine(dateAsString); DateTime parsedDate = DateTime.Parse(dateAsString, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); DateTimeOffset parsedDateAsDateTimeOffset = DateTimeOffset.Parse(dateAsString); Console.WriteLine(parsedDate); Console.WriteLine(parsedDateAsDateTimeOffset); Console.WriteLine(parsedDateAsDateTimeOffset.ToLocalTime()); } } }
using System; using System.Collections.Generic; using Master.Contract; using Master.DataFactory; namespace Master.BusinessFactory { public class HolidayBO { private HolidayDAL holidayDAL; public HolidayBO() { holidayDAL = new HolidayDAL(); } public List<Holiday> GetList(short branchID) { return holidayDAL.GetList(branchID); } public List<Holiday> GetPageView(short branchID,Int64 fetchRows) { return holidayDAL.GetPageView(branchID,fetchRows); } public Int64 GetRecordCount() { return holidayDAL.GetRecordCount(); } public List<Holiday> SearchHoliday(short branchID) { return holidayDAL.SearchHoliday(branchID); } public bool SaveHoliday(Holiday newItem) { return holidayDAL.Save(newItem); } public bool DeleteHoliday(Holiday item) { return holidayDAL.Delete(item); } public Holiday GetHoliday(Holiday item) { return (Holiday)holidayDAL.GetItem<Holiday>(item); } } }
namespace TipsAndTricksLibrary.Testing { using System; using System.Linq.Expressions; using KellermanSoftware.CompareNetObjects; public static class CompareLogicExtensions { public static CompareLogic ExcludePropertyFromComparison<TEntity, TProperty> (this CompareLogic compareLogic, Expression<Func<TEntity, TProperty>> ignoredMember) { var nameIgnoredField = ((MemberExpression)ignoredMember.Body).Member.Name; compareLogic.Config.MembersToIgnore.Add(nameIgnoredField); return compareLogic; } public static CompareLogic SetupMaxDifferencesCount(this CompareLogic compareLogic, int maxDifferencesCount) { compareLogic.Config.MaxDifferences = maxDifferencesCount; return compareLogic; } public static CompareLogic SetupCollectionsOrderChecking(this CompareLogic compareLogic, bool ignoreCollectionsOrder) { compareLogic.Config.IgnoreCollectionOrder = ignoreCollectionsOrder; return compareLogic; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LayerCullingDis : MonoBehaviour { // Start is called before the first frame update void Start() { Camera camera = GetComponent<Camera>(); float[] distances = new float[32]; distances[LayerMask.NameToLayer("Chunk")] = 32; camera.layerCullDistances = distances; camera.layerCullSpherical = true; } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Risk_FortheProcess : System.Web.UI.Page { public string t_rand = ""; PDTech.OA.BLL.VIEW_ARCHIVETASK_STEP ArBll = new PDTech.OA.BLL.VIEW_ARCHIVETASK_STEP(); PDTech.OA.BLL.OA_ARCHIVE_TASK taskBll = new PDTech.OA.BLL.OA_ARCHIVE_TASK(); public string Archive_id; public string allSealdata = string.Empty; protected void Page_Load(object sender, EventArgs e) { t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff"); if (Request.QueryString["ArId"] != null) { Archive_id = Request.QueryString["ArId"].ToString(); PDTech.OA.Model.OA_ARCHIVE_TASK oaTask = new PDTech.OA.Model.OA_ARCHIVE_TASK(); oaTask.ARCHIVE_ID = decimal.Parse(Archive_id); IList<PDTech.OA.Model.OA_ARCHIVE_TASK> list = taskBll.get_TaskInfoList(oaTask); if (list != null && list.Count > 0) { foreach (PDTech.OA.Model.OA_ARCHIVE_TASK task in list) { if (!string.IsNullOrEmpty(task.Sing_data)) { allSealdata += task.Sing_data + ","; } } } if (!IsPostBack) { BindData(); } } } /// <summary> /// 获取并绑定数据 /// </summary> public void BindData() { int record = 0; IList<PDTech.OA.Model.VIEW_ARCHIVETASK_STEP> ArList = new List<PDTech.OA.Model.VIEW_ARCHIVETASK_STEP>(); ArList = ArBll.get_Paging_ArchiveTask_StepList(new PDTech.OA.Model.VIEW_ARCHIVETASK_STEP() { ARCHIVE_ID = decimal.Parse(Archive_id), SortFields = " START_TIME ASC " }, AspNetPager.CurrentPageIndex, AspNetPager.PageSize, out record); rpt_taskList.DataSource = ArList; rpt_taskList.DataBind(); AspNetPager.RecordCount = record; } protected void AspNetPager_PageChanged(object sender, EventArgs e) { BindData(); } /// <summary> /// 判定是否有风险处置单 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void rpt_taskList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { LinkButton lbntGnt = e.Item.FindControl("lbntGnt") as LinkButton; LinkButton lbntSel = e.Item.FindControl("lbntSel") as LinkButton; HiddenField hidRiskId = e.Item.FindControl("hidRiskId") as HiddenField; if (!string.IsNullOrEmpty(hidRiskId.Value)) { lbntGnt.Visible = false; } else { lbntSel.Visible = false; } } } /// <summary> /// 新增或查看风险处置单 /// </summary> /// <param name="source"></param> /// <param name="e"></param> protected void rpt_taskList_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Gnt") { HiddenField hidArchiveId = e.Item.FindControl("hidArchiveId") as HiddenField; HiddenField hidArchiveType = e.Item.FindControl("hidArchiveType") as HiddenField; HiddenField hidArchive_Task_Id = e.Item.FindControl("hidArchive_Task_Id") as HiddenField; this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>editRisk('" + hidArchiveType.Value + "','" + hidArchive_Task_Id.Value + "','" + hidArchiveId.Value + "');</script>"); } if (e.CommandName == "Sel") { HiddenField hidRiskId = e.Item.FindControl("hidRiskId") as HiddenField; this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>selrisk('" + hidRiskId.Value + "');</script>"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.ServiceModel; using System.Data.SqlClient; namespace BLL集团客运综合管理.USRE { [ServiceContract] class USER_DENGLU { DALPublic.DALMethod myDAL = new DALPublic.DALMethod(); [OperationContract]//查询用户 public DataSet Selectyonghu() { SqlParameter[] sqlPas = { new SqlParameter("@SN",SqlDbType.NChar), }; sqlPas[0].Value = "Selectyonghu"; DataTable dt = myDAL.QueryDataTable("UserLogin", sqlPas); DataSet ds = new DataSet(); ds.Tables.Add(dt); return ds; } [OperationContract]//查询密码通过用户 public DataSet SelectMiMaBYyonghu(int UserID) { SqlParameter[] sqlPas = { new SqlParameter("@SN",SqlDbType.NChar), new SqlParameter("@UserID",SqlDbType.Int), }; sqlPas[0].Value = "SelectMiMaBYyonghu"; sqlPas[1].Value = UserID; DataTable dt = myDAL.QueryDataTable("UserLogin", sqlPas); DataSet ds = new DataSet(); ds.Tables.Add(dt); return ds; } [OperationContract]//直接输入看是否 public DataSet selectzhijie(string UserMC ,string Password) { SqlParameter[] sqlPas = { new SqlParameter("@SN",SqlDbType.NChar), new SqlParameter("@UserMC",SqlDbType.NChar), new SqlParameter("@Password",SqlDbType.NChar), }; sqlPas[0].Value = "SelectMiMaBYyonghu"; sqlPas[1].Value = UserMC; sqlPas[2].Value = Password; DataTable dt = myDAL.QueryDataTable("UserLogin", sqlPas); DataSet ds = new DataSet(); ds.Tables.Add(dt); return ds; } } }
using System; using System.Collections.Generic; using System.Text; namespace DeviceInterface { public interface IDeviceObserver : Orleans.IGrainObserver { void ForwardTo(string message, string action); } }
using Migration.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Migration.Common.Log; namespace JiraExport { static class Program { static void Main(string[] args) { VersionInfo.PrintInfoMessage("Jira Exporter"); try { var cmd = new JiraCommandLine(args); cmd.Run(); } catch (Exception ex) { Logger.Log(ex, "Application stopped due to an unexpected exception", LogLevel.Critical); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; namespace Dao.Solicitud { public class ContactoArchivosDao : GenericDao<crmContactoArchivos>, IContactoArchivosDao { } }
using System; using System.Collections.Generic; using System.Linq; namespace filter.framework.core.Db { public static class MySQLQueryHelper { public static List<string> BuildConditionList(this Dictionary<string, string> conditions, Type type, string prefix = "") { if (conditions == null) return new List<string>(); var list = conditions .Where(c => !string.IsNullOrEmpty(c.Value)) .Select(c => Build(type, prefix, c.Key, c.Value)) .Where(c => !string.IsNullOrEmpty(c)).ToList(); return list; } private static string Build(Type type, string prefix, string key, string value) { if (key.Contains("_or_")) { var list = key.Split(new[] { "_or_" }, StringSplitOptions.RemoveEmptyEntries) .ToList() .Select(t => Build(type, prefix, t, value)) .Where(t => !string.IsNullOrEmpty(t)) .ToList(); if (list.Count <= 0) { return null; } return " ( " + string.Join(" OR ", list) + " ) "; } var strings = key.Split(new[] { "_" }, StringSplitOptions.RemoveEmptyEntries); var s = strings[0]; for (int i = 1; i < strings.Length - 1; i++) { s += "_" + strings[i]; } var propertyInfo = type.GetProperty(s); if (propertyInfo == null) return null; s = "`" + s + "`"; if (propertyInfo.PropertyType == typeof(int) || propertyInfo.PropertyType == typeof(float) || propertyInfo.PropertyType == typeof(long) || propertyInfo.PropertyType == typeof(double) || propertyInfo.PropertyType == typeof(decimal) || propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(TimeSpan)) { if (strings.Length <= 1) { return s + "=" + value; } switch (strings[strings.Length - 1]?.ToLower()) { case "gt": return prefix + s + ">" + value; case "lt": return prefix + s + "<" + value; case "gte": return prefix + s + ">=" + value; case "lte": return prefix + s + "<=" + value; case "eq": return prefix + s + "=" + value; case "in": return prefix + s + " in (" + value + ") "; } } else { if (strings.Length <= 1) { return prefix + s + "='" + value + "'"; } switch (strings[strings.Length - 1]?.ToLower()) { case "contains": return prefix + s + " like '%" + value + "%'"; case "startswith": return prefix + s + " like '" + value + "%'"; case "endswith": return prefix + s + " like '%" + value + "'"; case "gt": return prefix + s + ">'" + value + "'"; case "lt": return prefix + s + "<'" + value + "'"; case "gte": return prefix + s + ">='" + value + "'"; case "lte": return prefix + s + "<='" + value + "'"; case "eq": return prefix + s + "='" + value + "'"; case "in": return prefix + s + " in (" + value + ") "; } } return s + "=" + value; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using BPiaoBao.Common.Enums; namespace BPiaoBao.DomesticTicket.Domain.Models.Orders { public enum EnumOperationType { /// <summary> /// 分润 /// </summary> [Description("分润")] Profit = 0, /// <summary> /// 收款 /// </summary> [Description("收款")] Receivables = 1, /// <summary> /// 付款 /// </summary> [Description("付款")] PayMoney = 2, /// <summary> /// 出票服务费 /// </summary> [Description("服务费")] IssuePayServer = 3, /// <summary> /// 运营商收取服务费 /// </summary> [Description("服务费")] CarrierRecvServer = 4, /// <summary> /// 运营商支出服务费 /// </summary> [Description("服务费")] CarrierPayServer = 5, /// <summary> /// 运营商支出分润服务费 /// </summary> [Description("分润服务费")] CarrierPayProfitServer = 6, /// <summary> /// 合作者收取分润服务费 /// </summary> [Description("分润服务费")] ParterProfitServer = 7, /// <summary> /// 合作者收取服务费 /// </summary> [Description("服务费")] ParterServer = 8, /// <summary> /// 保留费用 /// </summary> [Description("保留")] ParterRetainServer = 9, /// <summary> /// 保险金额 /// </summary> [Description("保险")] Insurance = 10, /// <summary> /// 保险服务费 /// </summary> [Description("保险服务费")] InsuranceServer = 11, /// <summary> /// 保险收款 /// </summary> [Description("保险收款")] InsuranceReceivables = 12, /// <summary> /// 系统分润(平台扣点) /// </summary> [Description("系统分润")] ParterProfit = 13 } /// <summary> /// 收支明细 /// </summary> public class PayBillDetail { public int ID { get; set; } /// <summary> /// 商户号 /// </summary> public string Code { get; set; } /// <summary> /// 钱袋子合作方 /// </summary> public string CashbagCode { get; set; } /// <summary> /// 商户名 /// </summary> public string Name { get; set; } /// <summary> /// 金额 /// </summary> public decimal Money { get; set; } /// <summary> /// 婴儿服务费 金额 /// </summary> public decimal InfMoney { get; set; } /// <summary> /// 点数 /// </summary> public decimal Point { get; set; } /// <summary> /// 操作类型 /// </summary> public EnumOperationType OpType { get; set; } /// <summary> /// 扣点类型 /// </summary> public AdjustType AdjustType { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } } }
using Patterns.Command.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Patterns.Command.Classes { class StereoCommand : ICommand { private Stereo _stereo; public StereoCommand(Stereo stereo) { this._stereo = stereo; } public void Execute() { _stereo.On(); _stereo.SetCD(); _stereo.SetVolume(11); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Creedy_Chicken { public partial class Form1 : Form { public Form1() { InitializeComponent(); pictureBox1.MouseEnter += OnMouseEnter; pictureBox1.MouseLeave += OnMouseLeave; pictureBox2.MouseEnter += MouseEnter; pictureBox2.MouseLeave += MouseLeave; } private void OnMouseEnter(object sender, EventArgs e) { pictureBox1.Size = new Size(250, 90); } private void OnMouseLeave(object sender, EventArgs e) { pictureBox1.Size = new Size(244, 84); } private void MouseLeave(object sender, EventArgs e) { pictureBox2.Size = new Size(244, 84); } private void MouseEnter(object sender, EventArgs e) { pictureBox2.Size = new Size(250, 90); } private void pictureBox1_Click(object sender, EventArgs e) { this.Hide(); Form2 f2 = new Form2(); f2.ShowDialog(); this.Close(); } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } } }
// ----------------------------------------------------------------------- // Copyright (c) David Kean. All rights reserved. // ----------------------------------------------------------------------- extern alias pcl; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using PclWebUtility = pcl::System.Net.WebUtility; using SystemWebUtility = System.Net.WebUtility; namespace Portable.Net { [TestClass] public class WebUtilityIntegrationTests { [TestMethod] public void HtmlEncode_EncodesSameCharactersAsPlatform() { for (char c = '\0'; c < ushort.MaxValue; c++) { string left = SystemWebUtility.HtmlEncode(c.ToString()); string right = PclWebUtility.HtmlEncode(c.ToString()); Assert.AreEqual(left, right); } } } }
#region License //=================================================================================== //Copyright 2010 HexaSystems Corporation //=================================================================================== //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. //=================================================================================== #endregion using System; using System.Collections.Generic; using System.Windows.Forms; using System.Threading; using System.IO; namespace Hexa.xText.CheckDuplicates { /// <summary> /// Small appplication that verifies repeated lines in the translations file /// </summary> class Program { [STAThread] static void Main(string[] args) { // Declare a fileDialog to get the file location OpenFileDialog openFileDialog = new OpenFileDialog(); // Check the user click ok in the dialog if (openFileDialog.ShowDialog() == DialogResult.OK) { // Create a new thread to make the operation Thread newThread = new Thread(Program.CheckDuplicates); newThread.Start(openFileDialog.FileName); } } /// <summary> /// Check for repeated lines in the translation file /// </summary> /// <param name="file">The file name</param> public static void CheckDuplicates(object file) { int count = 0; List<string> tags = new List<string>(); List<string> repeatedTags = new List<string>(); string line = ""; // Create the object to open the file FileStream fs = File.Open(file.ToString(), FileMode.Open); // Create the object to read the file content StreamReader reader = new StreamReader(fs); // Iterate through the file content while ((line = reader.ReadLine()) != null) { count++; // Check that the current line its a msgid if (line.Contains("msgid")) { // Get the line string theLine = line.Replace("msgid", "").Replace("\"", "").Trim(); // If the tag is not already added if (!tags.Contains(theLine)) { // Add to the collection tags.Add(theLine); } else { repeatedTags.Add(theLine); // Show the message for repated line to the user Console.WriteLine("Duplicated msgid on line: " + count.ToString() + ", Tag: " + theLine + "\n"); } } } reader.Close(); fs.Close(); if (repeatedTags.Count > 0) { Console.WriteLine("Total Duplicated msgid's: " + repeatedTags.Count + "\n"); } else { Console.WriteLine("PO File is Ok!!!\n"); } Console.WriteLine("Duplicated msgid's Validation is Complete"); Console.ReadLine(); } } }
using System; namespace ScreenLock { public interface IScreenLock { void Lock(); void Unlock(); } }
using System; /// <summary> /// Advent of Code - Day 1 namespace /// </summary> namespace AdventOfCodeDay1 { /// <summary> /// Program class /// </summary> internal class Program { /// <summary> /// Main entry point /// </summary> /// <param name="args">Command line arguments</param> private static void Main(string[] args) { string line; uint line_count = 0U; bool calculate_with_fuel_mass = false; foreach (string arg in args) { string trimmed_arg = arg.Trim().ToLower(); if ((trimmed_arg == "-c") || (trimmed_arg == "--calculate-with-fuel-mass")) { calculate_with_fuel_mass = true; break; } } FuelCalculator fuel_calculator = new FuelCalculator(calculate_with_fuel_mass); while ((line = Console.ReadLine()) != null) { int mass; ++line_count; if (int.TryParse(line, out mass)) { fuel_calculator.Add(mass); } else { Console.Error.WriteLine("Can't parse line " + line_count + ": \"" + line + "\" is not an integer."); } } Console.WriteLine(fuel_calculator.Fuel); } } }
namespace GraphQLSampleAPI.Models { public class GadgetInput { public string productName { get; set; } public string brandName { get; set; } public decimal cost { get; set; } public string type { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp.text; using iTextSharp.text.pdf; namespace ReportGenerator { public abstract class GenerateFile { public ReportType reportType; public BlockchainData blockchainData; public int personID; public DateTime begin; public DateTime end; public abstract void GeneratePrescriptionReport(); public abstract void GenerateSoldMedicamentsReport(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CraneMonitor { /// <summary> /// Interaction logic for AzimuthMeter.xaml /// </summary> public partial class AzimuthMeter : UserControl { private const double radius = 200; private double org_fig_size_x = 0; private double org_fig_size_y = 0; private int div_phi = 180; private int meter_val = 0; public int MeterValue { get { return meter_val; } set { meter_val = value; meter_label.Content = meter_val; canvas_transform.Matrix = CalcTransMat(); } } private Matrix CalcTransMat() { org_fig_size_x = this.main_canvas.Width; org_fig_size_y = this.main_canvas.Height; double x_ratio = RenderSize.Width / org_fig_size_x; double y_ratio = RenderSize.Height / org_fig_size_y; Matrix mat_total = new Matrix(); Matrix mat = new Matrix(); mat.Translate(-org_fig_size_x / 2, -org_fig_size_y / 2); mat_total.Append(mat); mat = new Matrix(); mat.Rotate(meter_val); mat_total.Append(mat); mat = new Matrix(); mat.Translate(org_fig_size_x / 2, org_fig_size_y / 2); mat_total.Append(mat); mat = new Matrix(); if (y_ratio > x_ratio) { mat.Scale(x_ratio, x_ratio); switch (VerticalContentAlignment) { case VerticalAlignment.Top: mat.Translate(0, 0); break; case VerticalAlignment.Bottom: mat.Translate(0, RenderSize.Height - x_ratio * org_fig_size_y); break; case VerticalAlignment.Center: default: mat.Translate(0, (RenderSize.Height - x_ratio * org_fig_size_y) / 2); break; } } else { mat.Scale(y_ratio, y_ratio); switch (HorizontalContentAlignment) { case HorizontalAlignment.Left: mat.Translate(0, 0); break; case HorizontalAlignment.Right: mat.Translate(RenderSize.Width - y_ratio * org_fig_size_x, 0); break; case HorizontalAlignment.Center: default: mat.Translate((RenderSize.Width - y_ratio * org_fig_size_x) / 2, 0); break; } } mat_total.Append(mat); return mat_total; } public AzimuthMeter() { InitializeComponent(); Render(); SizeChanged += delegate { canvas_transform.Matrix = CalcTransMat(); }; } public void Render() { main_canvas.Children.Clear(); for (int i = 0; i < div_phi; i++) { bool scale = i % (div_phi / 4) == 0; double ratio1 = scale ? 1.0 : 0.98; double ratio2 = scale ? 0.8 : 0.85; double thick = scale ? 6 : 2; // Add a Line Element Line line = new Line(); double angle = Math.PI * 2 * i / div_phi - Math.PI / 2; Point r1 = Pol2Cart(radius * ratio1, angle); line.X1 = r1.X; line.Y1 = r1.Y; Point r2 = Pol2Cart(radius * ratio2, angle); line.X2 = r2.X; line.Y2 = r2.Y; line.Stroke = (i != 0) ? System.Windows.Media.Brushes.White : System.Windows.Media.Brushes.Red; line.StrokeThickness = thick; line.HorizontalAlignment = HorizontalAlignment.Center; line.VerticalAlignment = VerticalAlignment.Center; //Canvas.SetLeft(line, this.main_canvas.Width / 2); //Canvas.SetTop(line, this.main_canvas.Height / 2); main_canvas.Children.Add(line); } } private Point Pol2Cart(double radius, double angle) { return new Point(this.main_canvas.Width / 2 + radius * Math.Cos(angle), this.main_canvas.Height / 2 + radius * Math.Sin(angle)); } } }
using jjs.Common; using jjs.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace jjs.Controllers { public class ShowController : FrontBaseController { private JiJiaShangDB db = new JiJiaShangDB(); // POST: MessageCreate/Create [HttpPost] public ActionResult MessageCreate(FormCollection collection) { try { if (ModelState.IsValid) { string name = collection["Name"]; string phone = collection["Phone"]; string address = collection["Address"]; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(address)) { return Content("姓名、电话、地址都必须填写!"); } Message messageModel = new Message() { Name = name, Phone = phone, Address = address, InDateTime = DateTime.Now, EditDateTime = DateTime.Now }; db.Messages.Add(messageModel); db.SaveChanges(); return Content(" <script type=\"text/javascript\"> alert(\"留言完成\"); ", "text/html", System.Text.Encoding.UTF8); } return Content(""); } catch (Exception ex) { return Content("出异常了,稍后重试!"); } } //// GET: ShowItem //public ActionResult Index() //{ // string idstr = Request.QueryString["id"]; // int id = 0; // if (idstr == null || !Int32.TryParse(idstr, out id)) // { // return View("error"); // } // LayoutViewModel masterModel = new LayoutViewModel(db); // ArticleContent model = db.ArticleContents.Find(id); // // 根据不同的类型可以把title改下 // AcTypeEmun typeEnum = (AcTypeEmun)Enum.Parse((typeof(AcTypeEmun)), model.ACType); // string emumtext = RemarkAttribute.GetEnumRemark(typeEnum); // ViewBag.Title = "吉家尚" + emumtext + "详情页"; // ViewBag.Content = model.AContent; // masterModel.groupBuilds = db.ArticleContents // .Where(w => w.ACType == AcTypeEmun.GROUPBUILD.ToString().ToUpper()) // .Take(4).OrderBy(o => new { o.ACSortNum, o.InDateTime }) // .OrderBy(o => o.ACSortNum).ToList(); // return View(masterModel); //} /// <summary> /// 热门套餐,经典案例,团装,家居设计,环保装修详情页 /// </summary> /// <returns></returns> public ActionResult ArticleContent() { string idstr = Request.QueryString["id"]; int id = 0; if (idstr == null || !Int32.TryParse(idstr, out id)) { return View("error"); } ArticleContent model = db.ArticleContents.Find(id); if (model == null) { return View("error"); } // 根据不同的类型可以把title改下 AcTypeEmun typeEnum = (AcTypeEmun)Enum.Parse((typeof(AcTypeEmun)), model.ACType); string emumtext = RemarkAttribute.GetEnumRemark(typeEnum); ViewBag.Title = "吉家尚" + emumtext + "详情页"; ViewBag.Content = model.AContent; LayoutViewModel masterModel = new LayoutViewModel(db); masterModel.groupBuilds = db.ArticleContents .Where(w => w.ACType == AcTypeEmun.GROUPBUILD.ToString().ToUpper()) .Take(4).OrderBy(o => new { o.ACSortNum, o.InDateTime }) .OrderBy(o => o.ACSortNum).ToList(); return View(masterModel); } /// <summary> /// 经典案例 /// </summary> /// <returns></returns> public ActionResult ClassCases() { // 根据不同的类型可以把title改下 string emumtext = RemarkAttribute.GetEnumRemark(AcTypeEmun.CLASSCASE); ViewBag.Title = "吉家尚" + emumtext + "列表页"; LayoutViewModel masterModel = new LayoutViewModel(db); masterModel.classicCase = db.ArticleContents .Where(w => w.ACType == AcTypeEmun.CLASSCASE.ToString().ToUpper()) .OrderBy(o => new { o.ACSortNum, o.InDateTime }) .OrderBy(o => o.ACSortNum).ToList(); masterModel.groupBuilds = db.ArticleContents .Where(w => w.ACType == AcTypeEmun.GROUPBUILD.ToString().ToUpper()) .Take(4).OrderBy(o => new { o.ACSortNum, o.InDateTime }) .OrderBy(o => o.ACSortNum).ToList(); return View(masterModel); } /// <summary> /// 所有设计者列表 /// </summary> /// <returns></returns> public ActionResult Designers() { LayoutViewModel layoutViewModel = new LayoutViewModel(db); layoutViewModel.designers = db.Designers.ToList(); layoutViewModel.groupBuilds = db.ArticleContents .Where(w => w.ACType == AcTypeEmun.GROUPBUILD.ToString().ToUpper()) .Take(4).OrderBy(o => new { o.ACSortNum, o.InDateTime }) .OrderBy(o => o.ACSortNum).ToList(); ViewBag.Title = "吉家尚设计师团队"; return View(layoutViewModel); } /// <summary> /// 设计师+案例 /// </summary> /// <returns></returns> public ActionResult DesignerCase() { // 设计师编号 string idstr = Request.QueryString["id"]; int id = 0; if (idstr == null || !Int32.TryParse(idstr, out id)) { return View("error"); } LayoutViewModel layoutViewModel = new LayoutViewModel(db); layoutViewModel.designers = db.Designers.ToList(); if (layoutViewModel.designers == null || layoutViewModel.designers.Count() == 0) { return View("error"); } // 团装小区 layoutViewModel.groupBuilds = db.ArticleContents .Where(w => w.ACType == AcTypeEmun.GROUPBUILD.ToString().ToUpper()) .Take(4).OrderBy(o => new { o.ACSortNum, o.InDateTime }) .OrderBy(o => o.ACSortNum).ToList(); ViewBag.Title = "吉家尚设计师" + layoutViewModel.designers.First().DName + "案例"; layoutViewModel.classicCase = db.ArticleContents.Where(w => w.DId == id).ToList(); ViewBag.CaseNameList = string.Join("、", layoutViewModel.classicCase.Select(s => s.ACTitle)); layoutViewModel.designers = db.Designers.Where(w => w.Id == id).ToList(); return View(layoutViewModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace yaruo_anka { using Statas = System.Collections.Generic.List<int>; class PlayerData { //PlayerのIDカウント用 static int MaxPlayerCounter = 0; static void PlayerPlus() { MaxPlayerCounter++; } ParamData param; //PlayerのID int _PlimaryNumber; string _Name; int _Level; //パラメータの数値 Statas _StatasList = new Statas(); //dataをテキストから数値に変えたほうがいいか検討 public PlayerData(string name, int level, Statas data) { _PlimaryNumber = MaxPlayerCounter; PlayerPlus(); _Name = name; _Level = level; _StatasList = data; } //dataをテキストから数値に変えたほうがいいか検討 public PlayerData(string name, string level, List<string> data) { _PlimaryNumber = MaxPlayerCounter; PlayerPlus(); _Name = name; _Level = int.Parse(level); _StatasList = data.Select(x=>int.Parse(x)).ToList(); } public int GetID() { return _PlimaryNumber; } //Player名取得 public string GetName() { return this._Name; } //各パラメータ取得 //エラーはー1で返す public int GetParam(int index) { if (index < 0) return -1; if (index > _StatasList.Count) return 0; int param=index==0?_Level:_StatasList.ElementAt(index-1); return param; } //パラメータ編集時に使用 //intに変換する際をどうするか検討 public bool SGetParam(int index,string data) { if (index < 0) return false; if (index == 0) { _Level = int.Parse(data); return true; } _StatasList.Insert(index - 1,int.Parse( data)); _StatasList.RemoveAt(index); return true; } //データを文字列の配列に //保存やListViewに使える public string[] GetStringListData() { string[] data = new string[param.Length]; for (int i = 0; i < param.Length; i++) { switch (i) { case 0: data[i] = _Name; break; case 1: data[i] = _Level.ToString(); break; default: data[i] = _StatasList.ElementAt(i - 2).ToString(); break; } } return data; } } }
namespace FatCat.Nes.OpCodes.AddressingModes { public class IndirectXMode : AddressMode { private byte highAddress; private byte location; private byte lowAddress; public override string Name => "(Indirect,X)"; public IndirectXMode(ICpu cpu) : base(cpu) { } public override int Run() { ReadLocation(); ReadLowAddress(); ReadHighAddress(); SetAbsoluteAddress(highAddress, lowAddress); return 0; } private void ReadHighAddress() { var highLocation = (ushort)(location + 1).ApplyLowMask(); highAddress = cpu.Read(highLocation); } private void ReadLocation() { location = ReadProgramCounter(); location += cpu.XRegister; } private void ReadLowAddress() { var lowLocation = (ushort)location.ApplyLowMask(); lowAddress = cpu.Read(lowLocation); } } }
using System; namespace WebSocketChatSample { public abstract class Message { public string MessageType { get; set; } } public class JoinMessage : Message { public const string MessageTypeKeyword = "JoinMessage"; public string UserName { get; set; } } public class ChatMessage { public string UserName { get; set; } public string Message { get; set; } public DateTimeOffset RecieveTime { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthBarManager : MonoBehaviour { [SerializeField] private GameObject healthBarPrefab; private List<Entity> entities; private List<HealthBar> healthBars; private HealthBarManager() { entities = new List<Entity>(); healthBars = new List<HealthBar>(); } private void Start() { foreach (Entity entity in FindObjectsOfType<Entity>()) { entity.HealthBar = SetupHealthBarForEntity(entity); } } public HealthBar SetupHealthBarForEntity(Entity entity) { if (!entities.Contains(entity)) { entities.Add(entity); HealthBar healthBar = Instantiate(healthBarPrefab).GetComponent<HealthBar>(); healthBar.SetupHealthBar(entity); healthBar.transform.SetParent(transform, false); healthBars.Add(healthBar); return healthBar; } return null; } public void RemoveHealthBarOfDeletedEntity(Entity entity) { foreach (HealthBar healthBar in healthBars) { if (healthBar.GetEntity() == entity) { healthBars.Remove(healthBar); entities.Remove(entity); Destroy(healthBar.gameObject); break; } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DesiClothing4u.Common.Models; using System.Net.Http; using Newtonsoft.Json; namespace DesiClothing4u.UI.Controllers { public class MenuController : Controller { // GET: MenuController public async Task<ActionResult<IEnumerable<productExt>>> Index(int CatId) { LoadProductExt load = new LoadProductExt(); //Featured--field name MarkAsNew var clientF = new HttpClient(); var urlF = "https://localhost:44356/api/Products/GetProductsByCat?CatId=" + CatId; var responseF = await clientF.GetAsync(urlF); var ProductExts = responseF.Content.ReadAsStringAsync().Result; load.ProductExts = JsonConvert.DeserializeObject<productExt[]>(ProductExts); return View("ProductsByCat",load); } } }
using System; using System.Collections.Generic; using System.Text; namespace KnapsackProblem.Common { public class KnapsackConfiguration { public KnapsackConfiguration() { } public KnapsackConfiguration(KnapsackConfiguration other) { Price = other.Price; Weight = other.Weight; ItemVector = new List<bool>(other.ItemVector); } public int Price { get; set; } public int Weight { get; set; } public int Cost { get; set; } public IList<bool> ItemVector { get; set; } } }
using System.Collections.Generic; using System.Net; using System; using HtmlAgilityPack; using System.Threading; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Windows; namespace ApergiesTileUpdate { public class StrikeLoader { WebClient webc; private List<StrikeRecord> strikeList; public NotifyDataList dataNotifier; public StrikeLoader() { //Constructor webc = new WebClient(); webc.OpenReadCompleted += new OpenReadCompletedEventHandler(webc_OpenReadCompleted); this.strikeList = new List<StrikeRecord>(); } public void LoadStrikes(string url) { webc.OpenReadAsync(new Uri(url)); } public List<StrikeRecord> GetStrikes() { return strikeList; } void webc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { HtmlDocument doc = new HtmlDocument(); bool errorExist = false; if (e.Error == null) { // Complete try { doc.Load(e.Result); var items = from item in doc.DocumentNode.Descendants("li") select new { Title = item.InnerText }; foreach (var item in items) { this.strikeList.Add(new StrikeRecord(HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(item.Title)), "")); } } catch (Exception ex) { errorExist = true; } } else { errorExist = true; } dataNotifier(errorExist); } } }
using Logic_Circuit.Models.BaseNodes; using Logic_Circuit.Models.Nodes.NodeInputTypes; using System.Collections.Generic; using System.Windows.Media; namespace Logic_Circuit.Models.Nodes { /// <summary> /// The only real logic node, representing a NAND-GATE. /// </summary> public class NandNode : IMultipleInputs { public string Name { get; set; } public string UID { get; set; } public string Type { get => "NAND"; set { } } public int RealDepth { get => CalcRealDepth(); set { } } public List<INode> Inputs { get; set; } = new List<INode>(); public NandNode(string name) { Name = name; UID = "name(" + name + ")_UID(" + Cache.GetUniqueInt() + ")"; } private int CalcRealDepth() { int result; if ((result = Cache.GetDepth(UID)) != int.MinValue) { return result; } int highest = 0; foreach (INode input in Inputs) { if (input.RealDepth > highest) highest = input.RealDepth; } Cache.PushDepth(UID, highest + 1); return highest + 1; } public bool[] Process() { bool[] result; if ((result = Cache.Get(UID)) != null) { return result; } foreach (INode input in Inputs) { foreach (bool res in input.Process()) { if (!res) { Cache.Push(UID, new bool[] { true }); return new bool[] { true }; } } } Cache.Push(UID, new bool[] { false }); return new bool[] { false }; } public Brush GetDisplayableValue(Brush ifTrue, Brush ifFalse, Brush ifMixed) { bool[] res = Process(); return res[0] ? ifTrue : ifFalse; } public INode Clone() { return new NandNode(this.Name); } } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_CheckUIEventByWidget : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_onDrag(IntPtr l) { int result; try { CheckUIEventByWidget checkUIEventByWidget = (CheckUIEventByWidget)LuaObject.checkSelf(l); UICamera.VectorDelegate vectorDelegate; int num = LuaDelegation.checkDelegate(l, 2, out vectorDelegate); if (num == 0) { checkUIEventByWidget.onDrag = vectorDelegate; } else if (num == 1) { CheckUIEventByWidget expr_30 = checkUIEventByWidget; expr_30.onDrag = (UICamera.VectorDelegate)Delegate.Combine(expr_30.onDrag, vectorDelegate); } else if (num == 2) { CheckUIEventByWidget expr_53 = checkUIEventByWidget; expr_53.onDrag = (UICamera.VectorDelegate)Delegate.Remove(expr_53.onDrag, vectorDelegate); } LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_onClick(IntPtr l) { int result; try { CheckUIEventByWidget checkUIEventByWidget = (CheckUIEventByWidget)LuaObject.checkSelf(l); UICamera.VoidDelegate voidDelegate; int num = LuaDelegation.checkDelegate(l, 2, out voidDelegate); if (num == 0) { checkUIEventByWidget.onClick = voidDelegate; } else if (num == 1) { CheckUIEventByWidget expr_30 = checkUIEventByWidget; expr_30.onClick = (UICamera.VoidDelegate)Delegate.Combine(expr_30.onClick, voidDelegate); } else if (num == 2) { CheckUIEventByWidget expr_53 = checkUIEventByWidget; expr_53.onClick = (UICamera.VoidDelegate)Delegate.Remove(expr_53.onClick, voidDelegate); } LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.CheckUIEventByWidget"); LuaObject.addMember(l, "onDrag", null, new LuaCSFunction(Lua_RO_CheckUIEventByWidget.set_onDrag), true); LuaObject.addMember(l, "onClick", null, new LuaCSFunction(Lua_RO_CheckUIEventByWidget.set_onClick), true); LuaObject.createTypeMetatable(l, null, typeof(CheckUIEventByWidget), typeof(MonoBehaviour)); } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Confluent.Kafka; using mlservice.Interface; using Serilog; namespace mlservice { public class KafkaConsumer<TKey, TValue> : IKafkaConsumer<TKey, TValue> where TValue : class { private readonly IConfiguration _config; private readonly IServiceScopeFactory _serviceScopeFactory; private readonly ILogger _logger; private string _topic; private IKafkaHandler<TKey, TValue> _handler; private IConsumer<TKey, TValue> _consumer; public KafkaConsumer(IConfiguration config, IServiceScopeFactory serviceScopeFactory, ILogger logger) { _serviceScopeFactory = serviceScopeFactory; _config = config; _logger = logger; } public void Close() { _consumer.Close(); } public async Task Consume(string topic, CancellationToken stoppingToken) { using var scope = _serviceScopeFactory.CreateScope(); _handler = scope.ServiceProvider.GetRequiredService<IKafkaHandler<TKey, TValue>>(); _topic = topic; var consumerConfig = new ConsumerConfig(){ BootstrapServers = _config.GetValue<string>("Kafka:BootstrapServers"), GroupId = _config.GetValue<string>("Kafka:GroupId"), AutoOffsetReset = (AutoOffsetReset)Enum.Parse(typeof(AutoOffsetReset), _config.GetValue<string>("Kafka:AutoOffsetReset"), true) }; _consumer = new ConsumerBuilder<TKey, TValue>(consumerConfig).Build(); await Task.Run(() => StartConsumerLoop(stoppingToken), stoppingToken); } public void Dispose() { _consumer.Dispose(); } private async Task StartConsumerLoop(CancellationToken cancellationToken) { _consumer.Subscribe(_topic); while (!cancellationToken.IsCancellationRequested) { try { var result = _consumer.Consume(cancellationToken); if (result != null) { await _handler.HandleAsync(result.Message.Key, result.Message.Value); } } catch (OperationCanceledException) { break; } catch (ConsumeException e) { // Consumer errors should generally be ignored (or logged) unless fatal. _logger.Error($"Consume error: {e.Error.Reason}"); if (e.Error.IsFatal) { break; } } catch (Exception e) { _logger.Error($"Unexpected error: {e}"); break; } } } } }
namespace Otchi.BitOperations { public static partial class BitOperations { public static bool IsBitSet(this sbyte t, int pos) { return (t & (1 << pos)) != 0; } public static bool IsBitSet(this byte t, int pos) { return (t & (1 << pos)) != 0; } public static bool IsBitSet(this short t, int pos) { return (t & (1 << pos)) != 0; } public static bool IsBitSet(this ushort t, int pos) { return (t & (1u << pos)) != 0; } public static bool IsBitSet(this int t, int pos) { return (t & (1 << pos)) != 0; } public static bool IsBitSet(this uint t, int pos) { return (t & (1u << pos)) != 0; } public static bool IsBitSet(this long t, int pos) { return (t & (1L << pos)) != 0; } public static bool IsBitSet(this ulong t, int pos) { return (t & (1ul << pos)) != 0; } } }
using System.Collections.Generic; namespace CarWash.ClassLibrary.Models { /// <summary> /// Well-known information /// </summary> public class WellKnown { /// <summary> /// List of bookable slots and their capacity. /// </summary> /// <remarks> /// Capacity is in number of cars per slot, not in minutes! /// </remarks> public List<Slot> Slots { get; set; } = new List<Slot>(); /// <summary> /// List of companies whose users can use the CarWash app. /// </summary> public List<Company> Companies { get; set; } = new List<Company>(); /// <summary> /// List of parking garages where cars are allowed to be left. /// </summary> public List<Garage> Garages { get; set; } = new List<Garage>(); /// <summary> /// CarWash app settings referring to reservations. /// </summary> public CarWashConfiguration.ReservationSettings ReservationSettings { get; set; } = new CarWashConfiguration.ReservationSettings(); } }
using System; namespace CTCI { // Write code to partition a linked list around a value x, such that all nodes less // than x come before all nodes greater than or equal to x. lf x is contained within //the list, the values of x only need to be after the elements less than x (see below). //The partition element x can appear anywhere //in the "right partition"; it does not //need to appear between the left and right partitions. class Partition { //Input: 3 -> 5 -> 8 -> 5 ->10 -> 2 -> 1[partition=5) //Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 public Node partition(Node head, int partition) { Node before = null; Node after = null; Node beforeTail = null; while (head != null) { if (head.data < partition) { if (before == null) before = new Node(head.data); else { before.appendToTail(head.data); beforeTail = before.next; } } else { if (after == null) after = new Node(head.data); else after.appendToTail(head.data); } head = head.next; } beforeTail.next.next = after; return before; ; } public void Test() { Node a = new Node(3); a.appendToTail(5); a.appendToTail(8); a.appendToTail(5); a.appendToTail(10); a.appendToTail(2); a.appendToTail(1); Node par = null; par = partition(a, 5); } } }
using System.Collections.Generic; using System.Linq; using AutoMapper; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { /// <summary> /// This ensures that the custom membership provider properties are not mapped - these property values are controller by the membership provider /// </summary> /// <remarks> /// Because these properties don't exist on the form, if we don't remove them for this map we'll get validation errors when posting data /// </remarks> internal class MemberDtoPropertiesResolver { public IEnumerable<ContentPropertyDto> Resolve(IMember source) { var defaultProps = Constants.Conventions.Member.GetStandardPropertyTypeStubs(); //remove all membership properties, these values are set with the membership provider. var exclude = defaultProps.Select(x => x.Value.Alias).ToArray(); return source.Properties .Where(x => exclude.Contains(x.Alias) == false) .Select(Mapper.Map<Property, ContentPropertyDto>); } } }
namespace ns25 { using ns26; using System; using System.Collections.Generic; using Triton.Game.Mono; internal class Class268 : MonoClass { internal Class268(IntPtr address) : base(TritonHs.MainAssemblyDir + @"\mscorlib.dll", "System.Collections.Generic", "List<" + typeof(string).FullName + ">") { base.Address = address; base.UInt32_0 = MonoClass.Class272_0.method_10(address, true); } public string method_24(int int_1) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.I4 }; object[] objArray1 = new object[] { int_1 }; return base.method_12("get_Item", enumArray1, objArray1); } public List<string> method_25() { List<string> list = new List<string>(); int num = this.Int32_0; for (int i = 0; i < num; i++) { list.Add(this.method_24(i)); } return list; } public int Int32_0 { get { return base.method_11<int>("get_Count", Array.Empty<object>()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Collections; using System.Diagnostics; namespace GoorooIO.SqlBacked { public class PerformanceLogger : IDisposable { public class Counter { public double TotalMilliseconds; public int Count; public string Stack; public void Add(PerformanceLogger log) { Count++; TotalMilliseconds += log._time; Stack = Environment.StackTrace; } } public static double TotalTime(string counterName, IDictionary persistence) { Counter counter; var counters = PerformanceCounters(persistence); if (counters != null && counters.TryGetValue(counterName, out counter)) { return counter.TotalMilliseconds; } else { return 0; } } public static int Count(string counterName, IDictionary persistence) { Counter counter; var counters = PerformanceCounters(persistence); if (counters != null && counters.TryGetValue(counterName, out counter)) { return counter.Count; } else { return 0; } } public static Dictionary<string, Counter> PerformanceCounters(IDictionary persistence) { if (persistence != null) { return persistence["request-counters"] as Dictionary<string, Counter>; } else { return null; } } private void Increment(PerformanceLogger logger) { if (_persistence != null) { if (_persistence != null) { Dictionary<string, Counter> counters; if (_persistence.Contains("request-counters")) { counters = _persistence["request-counters"] as Dictionary<string, Counter>; } else { counters = new Dictionary<string, Counter>(); _persistence["request-counters"] = counters; } if (counters.ContainsKey(logger._name)) { counters[logger._name].Add(logger); } else { counters[logger._name] = new Counter() { TotalMilliseconds = logger._time, Count = 1, Stack = Environment.StackTrace }; } } } } private DateTime _startTime; private double _time; private string _name; private IDictionary _persistence; public PerformanceLogger(string name, System.Collections.IDictionary persistence) { _persistence = persistence; _startTime = DateTime.UtcNow; _name = name; } public void Dispose() { _time = DateTime.UtcNow.Subtract(_startTime).TotalMilliseconds; Increment(this); System.Diagnostics.Trace.WriteLine(string.Format("log\t{0}: {1}ms", _name, _time)); } } }
using System.Collections.Generic; namespace CallCenter.Common.Entities { public interface IChat : IIdentifier { IEnumerable<IChatTopic> Topics { get; set; } IChatTopic CurrentTopic { get; } IEnumerable<IChatAction> ChatActions { get; set; } } }
/// <summary> /// Scribble.rs Pad namespace /// </summary> namespace ScribblersPad { /// <summary> /// Used to signal when main menu has been shown /// </summary> public delegate void MainMenuShownDelegate(); }
using System; using DavisVantage.WeatherReader.Extensions; namespace DavisVantage.WeatherReader.Models.Extremes { public class WeatherdayExtremes { public int BarometerMax { get; set; } public int BarometerMin { get; set; } public DateTime BarometerMaxTime { get; set; } public DateTime BarometerMinTime { get; set; } public int MaxWindSpeed { get; set; } public DateTime MaxWindSpeedTime { get; set; } public decimal MaxIndoorTemp { get; set; } public DateTime MaxIndoorTempTime { get; set; } public decimal MinIndoorTemp { get; set; } public DateTime MinIndoorTempTime { get; set; } public int HumidityInsideMax { get; set; } public DateTime HumidityInsideMaxTime { get; set; } public int HumidityInsideMin { get; set; } public DateTime HumidityInsideMinTime { get; set; } public decimal MaxOutdoorTemp { get; set; } public decimal MinOutdoorTemp { get; set; } public DateTime MaxOutdoorTempTime { get; set; } public DateTime MinOutdoorTempTime { get; set; } public decimal WindChillMin { get; set; } public DateTime WindChillMinTime { get; set; } public decimal ThswMax { get; set; } public DateTime ThswMaxTime { get; set; } public decimal HighSolar { get; set; } public DateTime HighSolarTime { get; set; } public decimal HighUv { get; set; } public DateTime HighUvTime { get; set; } public override string ToString() { return this.PrintAllProperties(); } } }
#region License // Copyright (C) 2017 AlienGames // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA #endregion using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace AlienEngine { /// <summary> /// Represents a three dimensional vector. /// </summary> [Serializable] [TypeConverter(typeof(StructTypeConverter<Vector3f>))] [StructLayout(LayoutKind.Sequential)] public struct Vector3f : IEquatable<Vector3f>, ILoadFromString { /// <summary> /// The X component of the Vector3f. /// </summary> public float X; /// <summary> /// The Y component of the Vector3f. /// </summary> public float Y; /// <summary> /// The Z component of the Vector3f. /// </summary> public float Z; /// <summary> /// Defines a unit-length Vector3f that points towards the X-axis. /// </summary> public static readonly Vector3f UnitX = new Vector3f(1, 0, 0); /// <summary> /// Defines a unit-length Vector3f that points towards the Y-axis. /// </summary> public static readonly Vector3f UnitY = new Vector3f(0, 1, 0); /// <summary> /// /// Defines a unit-length Vector3f that points towards the Z-axis. /// </summary> public static readonly Vector3f UnitZ = new Vector3f(0, 0, 1); /// <summary> /// Defines a zero-length Vector3f. /// </summary> public static readonly Vector3f Zero = new Vector3f(0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector3f One = new Vector3f(1); /// <summary> /// Defines the size of the Vector3f struct in bytes. /// </summary> public const int SizeInBytes = sizeof(float) * 3; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector3f(float value) { X = value; Y = value; Z = value; } /// <summary> /// Constructs a new Vector3f. /// </summary> /// <param name="x">The x component of the Vector3f.</param> /// <param name="y">The y component of the Vector3f.</param> /// <param name="z">The z component of the Vector3f.</param> public Vector3f(float x, float y, float z) { X = x; Y = y; Z = z; } /// <summary> /// Constructs a new Vector3f from the given Vector2ui. /// </summary> /// <param name="v">The Vector2ui to copy components from.</param> public Vector3f(Vector2ui vec) { X = vec.X; Y = vec.Y; Z = 0f; } /// <summary> /// Constructs a new Vector3f from the given Vector2i. /// </summary> /// <param name="v">The Vector2i to copy components from.</param> public Vector3f(Vector2i vec) { X = vec.X; Y = vec.Y; Z = 0f; } /// <summary> /// Constructs a new Vector2f from the given Vector2d. /// </summary> /// <param name="v">The Vector2d to copy components from.</param> public Vector3f(Vector2d vec) { X = (float)vec.X; Y = (float)vec.Y; Z = 0f; } /// <summary> /// Constructs a new Vector3f from the given Vector2f. /// </summary> /// <param name="v">The Vector2f to copy components from.</param> public Vector3f(Vector2f vec) { X = vec.X; Y = vec.Y; Z = 0f; } /// <summary> /// Constructs a new Vector3f from the given Vector3ui. /// </summary> /// <param name="v">The Vector3ui to copy components from.</param> public Vector3f(Vector3ui vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Constructs a new Vector3f from the given Vector3i. /// </summary> /// <param name="v">The Vector3i to copy components from.</param> public Vector3f(Vector3i vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Constructs a new Vector2f from the given Vector3d. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> public Vector3f(Vector3d vec) { X = (float)vec.X; Y = (float)vec.Y; Z = (float)vec.Z; } /// <summary> /// Constructs a new Vector3f from the given Vector3f. /// </summary> /// <param name="v">The Vector3f to copy components from.</param> public Vector3f(Vector3f vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Constructs a new Vector3f from the given Vector4ui. /// </summary> /// <param name="v">The Vector4ui to copy components from.</param> public Vector3f(Vector4ui vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Constructs a new Vector3f from the given Vector4i. /// </summary> /// <param name="v">The Vector4i to copy components from.</param> public Vector3f(Vector4i vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Constructs a new Vector2f from the given Vector4d. /// </summary> /// <param name="v">The Vector4d to copy components from.</param> public Vector3f(Vector4d vec) { X = (float)vec.X; Y = (float)vec.Y; Z = (float)vec.Z; } /// <summary> /// Constructs a new Vector3f from the given Vector4f. /// </summary> /// <param name="v">The Vector4f to copy components from.</param> public Vector3f(Vector4f vec) { X = vec.X; Y = vec.Y; Z = vec.Z; } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { if (index == 0) return X; else if (index == 1) return Y; else if (index == 2) return Z; throw new IndexOutOfRangeException("You tried to access this vector at index: " + index); } set { if (index == 0) X = value; else if (index == 1) Y = value; else if (index == 2) Z = value; throw new IndexOutOfRangeException("You tried to set this vector at index: " + index); } } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public float Length { get { return MathHelper.Sqrt(X * X + Y * Y + Z * Z); } } /// <summary> /// Gets an approximation of the vector length (magnitude). /// </summary> /// <remarks> /// This property uses an approximation of the square root function to calculate vector magnitude, with /// an upper error bound of 0.001. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthSquared"/> public float LengthFast { get { return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthFast"/> public float LengthSquared { get { return X * X + Y * Y + Z * Z; } } /// <summary> /// Gets the normalized instance of t <see cref="Vector3f"/>. /// </summary> public Vector3f Normalized { get { return Normalize(this); } } /// <summary> /// Scales the Vector3f to unit length. /// </summary> public void Normalize() { if (this != Vector3f.Zero) { float scale = 1.0f / this.Length; X *= scale; Y *= scale; Z *= scale; } } /// <summary> /// Scales the Vector3f to approximately unit length. /// </summary> public void NormalizeFast() { float scale = MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z); X *= scale; Y *= scale; Z *= scale; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="other">The second vector</param> /// <returns>The dot product of the two inputs</returns> public float Dot(Vector3f other) { return X * other.X + Y * other.Y + Z * other.Z; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="other">The second vector</param> /// <returns>The cross product of the two inputs</returns> public Vector3f Cross(Vector3f other) { return new Vector3f( Y * other.Z - Z * other.Y, Z * other.X - X * other.Z, X * other.Y - Y * other.X ); } /// <summary> /// Checks to see if any value (x, y, z) are within 0.0001 of 0. /// If so this method truncates that value to zero. /// </summary> public void Truncate() { this = Truncate(this); } /// <summary> /// Rotate a vector by an angle. /// </summary> /// <param name="angle">The angle in radians.</param> /// <param name="axis">The axis used for rotation.</param> /// <returns>The result of the operation.</returns> public void Rotate(float angle, Vector3f axis) { this = Rotate(this, angle, axis); } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector3f Add(Vector3f a, Vector3f b) { Vector3f res; Add(ref a, ref b, out res); return res; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector3f a, ref Vector3f b, out Vector3f result) { result = new Vector3f(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector3f Subtract(Vector3f a, Vector3f b) { Vector3f res; Subtract(ref a, ref b, out res); return res; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector3f a, ref Vector3f b, out Vector3f result) { result = new Vector3f(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3f Multiply(Vector3f vector, float scale) { Vector3f res; Multiply(ref vector, scale, out res); return res; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3f vector, float scale, out Vector3f result) { result = new Vector3f(vector.X * scale, vector.Y * scale, vector.Z * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3f Multiply(Vector3f vector, Vector3f scale) { Vector3f res; Multiply(ref vector, ref scale, out res); return res; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3f vector, ref Vector3f scale, out Vector3f result) { result = new Vector3f(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3f Divide(Vector3f vector, float scale) { Vector3f res; Divide(ref vector, scale, out res); return res; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3f vector, float scale, out Vector3f result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3f Divide(Vector3f vector, Vector3f scale) { Vector3f res; Divide(ref vector, ref scale, out res); return res; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3f vector, ref Vector3f scale, out Vector3f result) { result = new Vector3f(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z); } /// <summary> /// Computes the squared distance between two vectors. /// </summary> /// <param name="a">First vector.</param> /// <param name="b">Second vector.</param> /// <returns>Squared distance between the two vectors.</returns> public static float DistanceSquared(Vector3f a, Vector3f b) { float res; DistanceSquared(ref a, ref b, out res); return res; } /// <summary> /// Computes the squared distance between two vectors. /// </summary> /// <param name="a">First vector.</param> /// <param name="b">Second vector.</param> /// <param name="distanceSquared">Squared distance between the two vectors.</param> public static void DistanceSquared(ref Vector3f a, ref Vector3f b, out float distanceSquared) { float x = a.X - b.X; float y = a.Y - b.Y; float z = a.Z - b.Z; distanceSquared = x * x + y * y + z * z; } /// <summary> /// Computes the distance between two two vectors. /// </summary> /// <param name="a">First vector.</param> /// <param name="b">Second vector.</param> /// <returns>Distance between the two vectors.</returns> public static float Distance(Vector3f a, Vector3f b) { float toReturn; Distance(ref a, ref b, out toReturn); return toReturn; } /// <summary> /// Computes the distance between two two vectors. /// </summary> /// <param name="a">First vector.</param> /// <param name="b">Second vector.</param> /// <param name="distance">Distance between the two vectors.</param> public static void Distance(ref Vector3f a, ref Vector3f b, out float distance) { float x = a.X - b.X; float y = a.Y - b.Y; float z = a.Z - b.Z; distance = MathHelper.Sqrt(x * x + y * y + z * z); } /// <summary> /// Negates a vector. /// </summary> /// <param name="v">Vector to negate.</param> /// <param name="negated">Negated vector.</param> public static Vector3f Negate(Vector3f v) { Vector3f res; Negate(ref v, out res); return res; } /// <summary> /// Negates a vector. /// </summary> /// <param name="v">Vector to negate.</param> /// <param name="negated">Negated vector.</param> public static void Negate(ref Vector3f v, out Vector3f negated) { negated.X = -v.X; negated.Y = -v.Y; negated.Z = -v.Z; } /// <summary> /// Creates a vector from the lesser values in each vector. /// </summary> /// <param name="a">First input vector to compare values from.</param> /// <param name="b">Second input vector to compare values from.</param> /// <returns>Vector containing the lesser values of each vector.</returns> public static Vector3f ComponentMin(Vector3f a, Vector3f b) { Vector3f result; ComponentMin(ref a, ref b, out result); return result; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void ComponentMin(ref Vector3f a, ref Vector3f b, out Vector3f result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; } /// <summary> /// Creates a vector from the greater values in each vector. /// </summary> /// <param name="a">First input vector to compare values from.</param> /// <param name="b">Second input vector to compare values from.</param> /// <returns>Vector containing the greater values of each vector.</returns> public static Vector3f ComponentMax(Vector3f a, Vector3f b) { Vector3f result; ComponentMax(ref a, ref b, out result); return result; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void ComponentMax(ref Vector3f a, ref Vector3f b, out Vector3f result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; } /// <summary> /// Returns the Vector3f with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3f</returns> public static Vector3f Min(Vector3f left, Vector3f right) { return left.LengthSquared < right.LengthSquared ? left : right; } /// <summary> /// Returns the Vector3f with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3f</returns> public static Vector3f Max(Vector3f left, Vector3f right) { return left.LengthSquared >= right.LengthSquared ? left : right; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector3f Clamp(Vector3f vec, Vector3f min, Vector3f max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; vec.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector3f vec, ref Vector3f min, ref Vector3f max, out Vector3f result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; result.Z = vec.Z < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector3f Normalize(Vector3f vec) { if (vec != Vector3f.Zero) { float scale = 1.0f / vec.Length; vec.X *= scale; vec.Y *= scale; vec.Z *= scale; } return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector3f vec, out Vector3f result) { float scale = 1.0f / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector3f NormalizeFast(Vector3f vec) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z); vec.X *= scale; vec.Y *= scale; vec.Z *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector3f vec, out Vector3f result) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z); result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector3f left, Vector3f right) { float res; Dot(ref left, ref right, out res); return res; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector3f left, ref Vector3f right, out float result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> public static Vector3f Cross(Vector3f left, Vector3f right) { Vector3f result; Cross(ref left, ref right, out result); return result; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> /// <param name="result">The cross product of the two inputs</param> public static void Cross(ref Vector3f left, ref Vector3f right, out Vector3f result) { result = new Vector3f( left.Y * right.Z - left.Z * right.Y, left.Z * right.X - left.X * right.Z, left.X * right.Y - left.Y * right.X ); } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector3f Lerp(Vector3f a, Vector3f b, float blend) { Vector3f toReturn; Lerp(ref a, ref b, blend, out toReturn); return toReturn; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector3f a, ref Vector3f b, float blend, out Vector3f result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; } /// <summary> /// Computes an intermediate location using hermite interpolation. /// </summary> /// <param name="value1">First position.</param> /// <param name="tangent1">Tangent associated with the first position.</param> /// <param name="value2">Second position.</param> /// <param name="tangent2">Tangent associated with the second position.</param> /// <param name="interpolationAmount">Amount of the second point to use.</param> /// <returns>Interpolated intermediate state.</returns> public static Vector3f Hermite(Vector3f value1, Vector3f tangent1, Vector3f value2, Vector3f tangent2, float interpolationAmount) { Vector3f toReturn; Hermite(ref value1, ref tangent1, ref value2, ref tangent2, interpolationAmount, out toReturn); return toReturn; } /// <summary> /// Computes an intermediate location using hermite interpolation. /// </summary> /// <param name="value1">First position.</param> /// <param name="tangent1">Tangent associated with the first position.</param> /// <param name="value2">Second position.</param> /// <param name="tangent2">Tangent associated with the second position.</param> /// <param name="interpolationAmount">Amount of the second point to use.</param> /// <param name="result">Interpolated intermediate state.</param> public static void Hermite(ref Vector3f value1, ref Vector3f tangent1, ref Vector3f value2, ref Vector3f tangent2, float interpolationAmount, out Vector3f result) { float weightSquared = interpolationAmount * interpolationAmount; float weightCubed = interpolationAmount * weightSquared; float value1Blend = 2 * weightCubed - 3 * weightSquared + 1; float tangent1Blend = weightCubed - 2 * weightSquared + interpolationAmount; float value2Blend = -2 * weightCubed + 3 * weightSquared; float tangent2Blend = weightCubed - weightSquared; result.X = value1.X * value1Blend + value2.X * value2Blend + tangent1.X * tangent1Blend + tangent2.X * tangent2Blend; result.Y = value1.Y * value1Blend + value2.Y * value2Blend + tangent1.Y * tangent1Blend + tangent2.Y * tangent2Blend; result.Z = value1.Z * value1Blend + value2.Z * value2Blend + tangent1.Z * tangent1Blend + tangent2.Z * tangent2Blend; } /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector3f BaryCentric(Vector3f a, Vector3f b, Vector3f c, float u, float v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector3f a, ref Vector3f b, ref Vector3f c, float u, float v, out Vector3f result) { result = a; // copy Vector3f temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } /// <summary> /// Transforms the vector by the matrix. /// </summary> /// <param name="v">Vector2 to transform. Considered to be a row vector for purposes of multiplication.</param> /// <param name="matrix">Matrix to use as the transformation.</param> /// <param name="result">Row vector product of the transformation.</param> public static void Transform(ref Vector2f v, ref Matrix2x3f matrix, out Vector3f result) { #if !WINDOWS result = new Vector3f(); #endif result.X = v.X * matrix.M11 + v.Y * matrix.M21; result.Y = v.X * matrix.M12 + v.Y * matrix.M22; result.Z = v.X * matrix.M13 + v.Y * matrix.M23; } /// <summary> /// Transforms the vector by the matrix. /// </summary> /// <param name="v">Vector2 to transform. Considered to be a column vector for purposes of multiplication.</param> /// <param name="matrix">Matrix to use as the transformation.</param> /// <param name="result">Column vector product of the transformation.</param> public static void Transform(ref Vector2f v, ref Matrix3x2f matrix, out Vector3f result) { #if !WINDOWS result = new Vector3f(); #endif result.X = matrix.M11 * v.X + matrix.M12 * v.Y; result.Y = matrix.M21 * v.X + matrix.M22 * v.Y; result.Z = matrix.M31 * v.X + matrix.M32 * v.Y; } /// <summary> /// Transforms the vector by the matrix. /// </summary> /// <param name="v">Vector3 to transform.</param> /// <param name="matrix">Matrix to use as the transformation.</param> /// <returns>Product of the transformation.</returns> public static Vector3f Transform(Vector3f v, Matrix3f matrix) { Vector3f result; Transform(ref v, ref matrix, out result); return result; } /// <summary> /// Transforms the vector by the matrix. /// </summary> /// <param name="v">Vector3 to transform.</param> /// <param name="matrix">Matrix to use as the transformation.</param> /// <param name="result">Product of the transformation.</param> public static void Transform(ref Vector3f v, ref Matrix3f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; #if !WINDOWS result = new Vector3f(); #endif result.X = vX * matrix.M11 + vY * matrix.M21 + vZ * matrix.M31; result.Y = vX * matrix.M12 + vY * matrix.M22 + vZ * matrix.M32; result.Z = vX * matrix.M13 + vY * matrix.M23 + vZ * matrix.M33; } /// <summary> /// Transforms the vector by the matrix's transpose. /// </summary> /// <param name="v">Vector3 to transform.</param> /// <param name="matrix">Matrix to use as the transformation transpose.</param> /// <returns>Product of the transformation.</returns> public static Vector3f TransformTranspose(Vector3f v, Matrix3f matrix) { Vector3f result; TransformTranspose(ref v, ref matrix, out result); return result; } /// <summary> /// Transforms the vector by the matrix's transpose. /// </summary> /// <param name="v">Vector3 to transform.</param> /// <param name="matrix">Matrix to use as the transformation transpose.</param> /// <param name="result">Product of the transformation.</param> public static void TransformTranspose(ref Vector3f v, ref Matrix3f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; #if !WINDOWS result = new Vector3f(); #endif result.X = vX * matrix.M11 + vY * matrix.M12 + vZ * matrix.M13; result.Y = vX * matrix.M21 + vY * matrix.M22 + vZ * matrix.M23; result.Z = vX * matrix.M31 + vY * matrix.M32 + vZ * matrix.M33; } /// <summary> /// Transforms a vector using a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void Transform(ref Vector3f v, ref Matrix4f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; result.X = vX * matrix.M11 + vY * matrix.M21 + vZ * matrix.M31 + matrix.M41; result.Y = vX * matrix.M12 + vY * matrix.M22 + vZ * matrix.M32 + matrix.M42; result.Z = vX * matrix.M13 + vY * matrix.M23 + vZ * matrix.M33 + matrix.M43; } /// <summary> /// Transforms a vector using the transpose of a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to tranpose and apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformTranspose(ref Vector3f v, ref Matrix4f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; result.X = vX * matrix.M11 + vY * matrix.M12 + vZ * matrix.M13 + matrix.M14; result.Y = vX * matrix.M21 + vY * matrix.M22 + vZ * matrix.M23 + matrix.M24; result.Z = vX * matrix.M31 + vY * matrix.M32 + vZ * matrix.M33 + matrix.M34; } /// <summary> /// Transforms a vector using a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to apply to the vector.</param> /// <returns>Transformed vector.</returns> public static Vector3f TransformNormal(Vector3f v, Matrix4f matrix) { Vector3f toReturn; TransformNormal(ref v, ref matrix, out toReturn); return toReturn; } /// <summary> /// Transforms a vector using a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformNormal(ref Vector3f v, ref Matrix4f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; result.X = vX * matrix.M11 + vY * matrix.M21 + vZ * matrix.M31; result.Y = vX * matrix.M12 + vY * matrix.M22 + vZ * matrix.M32; result.Z = vX * matrix.M13 + vY * matrix.M23 + vZ * matrix.M33; } /// <summary> /// Transforms a vector using the transpose of a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to tranpose and apply to the vector.</param> /// <returns>Transformed vector.</returns> public static Vector3f TransformNormalTranspose(Vector3f v, Matrix4f matrix) { Vector3f toReturn; TransformNormalTranspose(ref v, ref matrix, out toReturn); return toReturn; } /// <summary> /// Transforms a vector using the transpose of a matrix. /// </summary> /// <param name="v">Vector to transform.</param> /// <param name="matrix">Transform to tranpose and apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformNormalTranspose(ref Vector3f v, ref Matrix4f matrix, out Vector3f result) { float vX = v.X; float vY = v.Y; float vZ = v.Z; result.X = vX * matrix.M11 + vY * matrix.M12 + vZ * matrix.M13; result.Y = vX * matrix.M21 + vY * matrix.M22 + vZ * matrix.M23; result.Z = vX * matrix.M31 + vY * matrix.M32 + vZ * matrix.M33; } /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3f TransformVector(Vector3f vec, Matrix4f mat) { Vector3f v; v.X = Vector3f.Dot(vec, new Vector3f(mat.Column0)); v.Y = Vector3f.Dot(vec, new Vector3f(mat.Column1)); v.Z = Vector3f.Dot(vec, new Vector3f(mat.Column2)); return v; } /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformVector(ref Vector3f vec, ref Matrix4f mat, out Vector3f result) { result.X = vec.X * mat.M11 + vec.Y * mat.M21 + vec.Z * mat.M31; result.Y = vec.X * mat.M12 + vec.Y * mat.M22 + vec.Z * mat.M32; result.Z = vec.X * mat.M13 + vec.Y * mat.M23 + vec.Z * mat.M33; } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed position</returns> public static Vector3f TransformPosition(Vector3f pos, Matrix4f mat) { Vector3f p; p.X = Vector3f.Dot(pos, new Vector3f(mat.Column0)) + mat.M41; p.Y = Vector3f.Dot(pos, new Vector3f(mat.Column1)) + mat.M42; p.Z = Vector3f.Dot(pos, new Vector3f(mat.Column2)) + mat.M43; return p; } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed position</param> public static void TransformPosition(ref Vector3f pos, ref Matrix4f mat, out Vector3f result) { result.X = pos.X * mat.M11 + pos.Y * mat.M21 + pos.Z * mat.M31 + mat.M41; result.Y = pos.X * mat.M12 + pos.Y * mat.M22 + pos.Z * mat.M32 + mat.M42; result.Z = pos.X * mat.M13 + pos.Y * mat.M23 + pos.Z * mat.M33 + mat.M43; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector3f Transform(Vector3f vec, Quaternion quat) { Vector3f result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector3f vec, ref Quaternion quat, out Vector3f result) { // Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows: // vec + 2.0 * cross(quat.XYZ, cross(quat.XYZ, vec) + quat.w * vec) Vector3f XYZ = quat.XYZ, temp, temp2; Cross(ref XYZ, ref vec, out temp); Multiply(ref vec, quat.W, out temp2); Add(ref temp, ref temp2, out temp); Cross(ref XYZ, ref temp, out temp); Multiply(ref temp, 2, out temp); Add(ref vec, ref temp, out result); result.Truncate(); //result = ((quat * vec) * Quaternion.Conjugate(quat)).XYZ; } /// <summary> /// Transforms a vector using a quaternion. Specialized for x,0,0 vectors. /// </summary> /// <param name="x">X component of the vector to transform.</param> /// <param name="rotation">Rotation to apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformX(float x, ref Quaternion rotation, out Vector3f result) { //This operation is an optimized-down version of v' = q * v * q^-1. //The expanded form would be to treat v as an 'axis only' quaternion //and perform standard quaternion multiplication. Assuming q is normalized, //q^-1 can be replaced by a conjugation. float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float zz2 = rotation.Z * z2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; //Defer the component setting since they're used in computation. float transformedX = x * (1f - yy2 - zz2); float transformedY = x * (xy2 + wz2); float transformedZ = x * (xz2 - wy2); result.X = transformedX; result.Y = transformedY; result.Z = transformedZ; } /// <summary> /// Transforms a vector using a quaternion. Specialized for 0,y,0 vectors. /// </summary> /// <param name="y">Y component of the vector to transform.</param> /// <param name="rotation">Rotation to apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformY(float y, ref Quaternion rotation, out Vector3f result) { //This operation is an optimized-down version of v' = q * v * q^-1. //The expanded form would be to treat v as an 'axis only' quaternion //and perform standard quaternion multiplication. Assuming q is normalized, //q^-1 can be replaced by a conjugation. float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; float wx2 = rotation.W * x2; float wz2 = rotation.W * z2; //Defer the component setting since they're used in computation. float transformedX = y * (xy2 - wz2); float transformedY = y * (1f - xx2 - zz2); float transformedZ = y * (yz2 + wx2); result.X = transformedX; result.Y = transformedY; result.Z = transformedZ; } /// <summary> /// Transforms a vector using a quaternion. Specialized for 0,0,z vectors. /// </summary> /// <param name="z">Z component of the vector to transform.</param> /// <param name="rotation">Rotation to apply to the vector.</param> /// <param name="result">Transformed vector.</param> public static void TransformZ(float z, ref Quaternion rotation, out Vector3f result) { //This operation is an optimized-down version of v' = q * v * q^-1. //The expanded form would be to treat v as an 'axis only' quaternion //and perform standard quaternion multiplication. Assuming q is normalized, //q^-1 can be replaced by a conjugation. float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float xx2 = rotation.X * x2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; //Defer the component setting since they're used in computation. float transformedX = z * (xz2 + wy2); float transformedY = z * (yz2 - wx2); float transformedZ = z * (1f - xx2 - yy2); result.X = transformedX; result.Y = transformedY; result.Z = transformedZ; } /// <summary> /// Rotate a vector by an angle. /// </summary> /// <param name="angle">The angle in radians.</param> /// <param name="axis">The axis used for rotation.</param> /// <returns>The result of the operation.</returns> public static Vector3f Rotate(Vector3f vec, float angle, Vector3f axis) { Quaternion rotation = Quaternion.FromAxisAngle(axis, angle); Vector3f result; Transform(ref vec, ref rotation, out result); return result; } /// <summary>Transform a Vector3f by the given Matrix, and project the resulting Vector4f back to a Vector3f</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3f TransformPerspective(Vector3f vec, Matrix4f mat) { Vector3f result; TransformPerspective(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector3f by the given Matrix, and project the resulting Vector4f back to a Vector3f</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformPerspective(ref Vector3f vec, ref Matrix4f mat, out Vector3f result) { Vector4f v = new Vector4f(vec, 1); Vector4f.Transform(ref v, ref mat, out v); result.X = v.X / v.W; result.Y = v.Y / v.W; result.Z = v.Z / v.W; } /// <summary> /// Returns a <see cref="Vector3f"/> with positive version of its components. /// </summary> /// <param name="v">The vector.</param> public static Vector3f Abs(Vector3f v) { Vector3f res; Abs(ref v, out res); return res; } /// <summary> /// Returns a <see cref="Vector3f"/> with positive version of its components. /// </summary> /// <param name="v">The input vector.</param> /// <param name="o">The output vector.</param> public static void Abs(ref Vector3f v, out Vector3f o) { o = new Vector3f(System.Math.Abs(v.X), System.Math.Abs(v.Y), System.Math.Abs(v.Z)); } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float CalculateAngle(Vector3f first, Vector3f second) { return MathHelper.Acos((Dot(first, second)) / (first.Length * second.Length)); } /// <summary>Calculates the angle (in radians) between two vectors.</summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void CalculateAngle(ref Vector3f first, ref Vector3f second, out float result) { float temp; Vector3f.Dot(ref first, ref second, out temp); result = MathHelper.Acos(temp / (first.Length * second.Length)); } /// <summary> /// Checks to see if any value (x, y, z) are within 0.0001 of 0. /// If so this method truncates that value to zero. /// </summary> /// <returns>A truncated Vector3f</returns> public static Vector3f Truncate(Vector3f vec) { float _x = (System.Math.Abs(vec.X) - 0.0001 < 0) ? 0 : vec.X; float _y = (System.Math.Abs(vec.Y) - 0.0001 < 0) ? 0 : vec.Y; float _z = (System.Math.Abs(vec.Z) - 0.0001 < 0) ? 0 : vec.Z; return new Vector3f(_x, _y, _z); } #region FromYawPitch /// <summary> /// Get Direction vector from Yaw and Pitch (in radians). /// </summary> /// <param name="Yaw">Yaw in radians.</param> /// <param name="Pitch">Pitch in radians.</param> /// <returns>Direction vector</returns> public static Vector3f FromYawPitch(float Yaw, float Pitch) { float CosPitch = MathHelper.Cos(Pitch); //Optimization Vector3f result = new Vector3f(CosPitch * MathHelper.Sin(Yaw), MathHelper.Sin(Pitch), CosPitch * MathHelper.Cos(Yaw)); //Result.Normalize(); return result; } #endregion /// <summary> /// Gets or sets an Vector2f with the X and Y components of this instance. /// </summary> public Vector2f XY { get { return new Vector2f(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an Vector2f with the X and Z components of this instance. /// </summary> public Vector2f XZ { get { return new Vector2f(X, Z); } set { X = value.X; Z = value.Y; } } /// <summary> /// Gets or sets an Vector2f with the Y and X components of this instance. /// </summary> public Vector2f YX { get { return new Vector2f(Y, X); } set { Y = value.X; X = value.Y; } } /// <summary> /// Gets or sets an Vector2f with the Y and Z components of this instance. /// </summary> public Vector2f YZ { get { return new Vector2f(Y, Z); } set { Y = value.X; Z = value.Y; } } /// <summary> /// Gets or sets an Vector2f with the Z and X components of this instance. /// </summary> public Vector2f ZX { get { return new Vector2f(Z, X); } set { Z = value.X; X = value.Y; } } /// <summary> /// Gets or sets an Vector2f with the Z and Y components of this instance. /// </summary> public Vector2f ZY { get { return new Vector2f(Z, Y); } set { Z = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an Vector3f with the X, Z, and Y components of this instance. /// </summary> public Vector3f XZY { get { return new Vector3f(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an Vector3f with the Y, X, and Z components of this instance. /// </summary> public Vector3f YXZ { get { return new Vector3f(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } } /// <summary> /// Gets or sets an Vector3f with the Y, Z, and X components of this instance. /// </summary> public Vector3f YZX { get { return new Vector3f(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } } /// <summary> /// Gets or sets an Vector3f with the Z, X, and Y components of this instance. /// </summary> public Vector3f ZXY { get { return new Vector3f(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } } /// <summary> /// Gets or sets an Vector3f with the Z, Y, and X components of this instance. /// </summary> public Vector3f ZYX { get { return new Vector3f(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator +(Vector3f left, Vector3f right) { left.X += right.X; left.Y += right.Y; left.Z += right.Z; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator -(Vector3f left, Vector3f right) { left.X -= right.X; left.Y -= right.Y; left.Z -= right.Z; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator -(Vector3f vec) { vec.X = -vec.X; vec.Y = -vec.Y; vec.Z = -vec.Z; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator *(Vector3f vec, Vector3f scale) { return Multiply(vec, scale); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator *(Vector3f vec, float scale) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator *(float scale, Vector3f vec) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3f operator /(Vector3f vec, float scale) { float mult = 1.0f / scale; vec.X *= mult; vec.Y *= mult; vec.Z *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector3f left, Vector3f right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector3f left, Vector3f right) { return !left.Equals(right); } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> [CLSCompliant(false)] unsafe public static explicit operator float* (Vector3f v) { return &v.X; } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> public static explicit operator IntPtr(Vector3f v) { unsafe { return (IntPtr)(&v.X); } } /// <summary> /// Explicitly cast this <see cref="Vector3f"/> into a <see cref="Assimp.Vector3D"/>. /// </summary> /// <param name="vec">The vector to cast.</param> [CLSCompliant(false)] public static explicit operator Assimp.Vector3D(Vector3f vec) { return new Assimp.Vector3D(vec.X, vec.Y, vec.Z); } /// <summary> /// Explicitly cast this <see cref="Vector3f"/> into a <see cref="Assimp.Vector3D"/>. /// </summary> /// <param name="vec">The vector to cast.</param> [CLSCompliant(false)] public static explicit operator Vector3f(Assimp.Vector3D vec) { return new Vector3f(vec.X, vec.Y, vec.Z); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector3f)) return false; return this.Equals((Vector3f)obj); } /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector3f other) { return X == other.X && Y == other.Y && Z == other.Z; } /// <summary> /// Load this instance from the <see cref="System.String"/> representation. /// </summary> /// <param name="value">The <see cref="System.String"/> value to convert.</param> void ILoadFromString.FromString(string value) { var parts = value.Trim('(', ')').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); float.TryParse(parts[0].Trim(), out X); float.TryParse(parts[1].Trim(), out Y); float.TryParse(parts[2].Trim(), out Z); } /// <summary> /// Convert a <see cref="string"/> to a <see cref="Vector3f"/>. /// </summary> /// <param name="s">The <see cref="string"/> to convert.</param> /// <returns>The <see cref="Vector3f"/> result of the conversion.</returns> public static Vector3f Parse(string s) { var result = Zero as ILoadFromString; result.FromString(s); return (Vector3f)result; } /// <summary> /// Returns a string that represents this <see cref="Vector3f"/>. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0} , {1} , {2})", X, Y, Z); } /// <summary> /// Gets the array representation of this <see cref="Vector3f"/>. /// </summary> public float[] ToArray() { return new float[] { X, Y, Z }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.WindowsAPICodePack.Dialogs; namespace GITRepoManager { public partial class CloneRepoFRMold : Form { public CloneRepoFRMold() { InitializeComponent(); } private void BrowseRepoSourceBT_Click(object sender, EventArgs e) { CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = @"C:\", IsFolderPicker = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { MoveRepoData.Repository_Source = dialog.FileName; RepoSourceTB.Text = MoveRepoData.Repository_Source; } } private void BrowseRepoSourceBT_MouseEnter(object sender, EventArgs e) { BrowseRepoSourceBT.BackgroundImage = Properties.Resources.Browse_Icon_Hover; //CloneRepoDescriptionSSLB.Text = Properties.Resources.CLONE_REPO_BROWSE_SOURCE_INFO; } private void BrowseRepoSourceBT_MouseLeave(object sender, EventArgs e) { BrowseRepoSourceBT.BackgroundImage = Properties.Resources.Browse_Icon; CloneRepoDescriptionSSLB.Text = string.Empty; } private void BrowseCloneDestinationBT_Click(object sender, EventArgs e) { CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = @"C:\", IsFolderPicker = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { MoveRepoData.Repository_Source = dialog.FileName; CloneDestinationTB.Text = MoveRepoData.Repository_Source; } } private void BrowseCloneDestinationBT_MouseEnter(object sender, EventArgs e) { BrowseCloneDestinationBT.BackgroundImage = Properties.Resources.Browse_Icon_Hover; //CloneRepoDescriptionSSLB.Text = Properties.Resources.CLONE_REPO_BROWSE_DESTINATION_INFO; } private void BrowseCloneDestinationBT_MouseLeave(object sender, EventArgs e) { BrowseCloneDestinationBT.BackgroundImage = Properties.Resources.Browse_Icon; CloneRepoDescriptionSSLB.Text = string.Empty; } private void CloneRepoFRM_FormClosing(object sender, FormClosingEventArgs e) { bool StoreData = true; if ( string.IsNullOrEmpty(RepoSourceTB.Text) && string.IsNullOrEmpty(CloneDestinationTB.Text) && string.IsNullOrWhiteSpace(RepoSourceTB.Text) && string.IsNullOrWhiteSpace(CloneDestinationTB.Text) ) { } else { if (String.IsNullOrEmpty(RepoSourceTB.Text) || String.IsNullOrWhiteSpace(RepoSourceTB.Text)) { StoreData = false; var Verify = MessageBox.Show ( this, "Repository Source is empty, close window?", "Close Clone Repo Window", MessageBoxButtons.YesNo ); e.Cancel = (Verify == DialogResult.No); } if (String.IsNullOrEmpty(CloneDestinationTB.Text) || String.IsNullOrWhiteSpace(CloneDestinationTB.Text)) { StoreData = false; var Verify = MessageBox.Show ( this, "Clone Destination is empty, close window?", "Close Clone Repo Window", MessageBoxButtons.YesNo ); e.Cancel = (Verify == DialogResult.No); } if (StoreData) { CloneRepoData.Repository_Source = RepoSourceTB.Text; CloneRepoData.Clone_Destination = CloneDestinationTB.Text; var Verify = MessageBox.Show ( this, "Are you sure you want to clone this repository?", "Close Clone Repo Window", MessageBoxButtons.YesNo ); if (Verify == DialogResult.Yes) { CloneRepoMethods.Clone_Repository(); } else { Verify = MessageBox.Show ( this, "Close Window?", "Close Clone Repo Window", MessageBoxButtons.YesNo ); e.Cancel = (Verify == DialogResult.No); } } else { CloneRepoData.Repository_Source = string.Empty; CloneRepoData.Clone_Destination = string.Empty; } } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Telerik"> // Telerik // </copyright> // <summary> // The program. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Task02Refactoring { /// <summary> /// The program. /// </summary> internal class Program { /// <summary> /// The cook. /// </summary> /// <param name="p"> /// The p. /// </param> private static void Cook(Potato p) { } /// <summary> /// The visit cell. /// </summary> private static void VisitCell() { } /// <summary> /// The main. /// </summary> /// <param name="args"> /// The args. /// </param> private static void Main(string[] args) { // First part of the task var potato = new Potato(); if (potato != null) { if (!potato.HasNotBeenPeeled && !potato.IsRotten) { Cook(potato); } } // Second part of the task int x = 0, y = 0; const int MIN_X = 0; const int MIN_Y = 0; const int MAX_X = 0; const int MAX_Y = 0; var shouldVisitCell = true; if (shouldVisitCell && (MIN_X >= x && x <= MAX_X) && (MIN_Y >= y && y <= MAX_Y)) { VisitCell(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EquippableItemSlot : ItemSlot { public EquipmentType EquipmentType; protected override void OnValidate() { base.OnValidate(); gameObject.name = "Equipment slot - " + EquipmentType.ToString(); } //protected override void OnRightClickHandler(BasicItem item) //{ // // TODO: Assign Equipment to right position //} }
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using GitlabManager.Framework; using GitlabManager.Services.BusinessLogic; using GitlabManager.Services.Database; using GitlabManager.Services.Database.Model; using GitlabManager.Services.Dialog; using GitlabManager.Services.Gitlab.Client; using GitlabManager.Services.Gitlab.Model; using GitlabManager.Services.System; namespace GitlabManager.Model { /// <summary> /// Model for the Project-Detail Window /// </summary> public class WindowProjectDetailModel : AppModel { #region Dependencies private readonly GitlabProjectManager _gitlabProjectManager; private readonly ISystemService _systemService; private readonly DatabaseService _databaseService; private readonly GitlabProjectDownloader _gitlabProjectDownloader; private readonly IDialogService _dialogService; #endregion #region Private Internal State private DbProject _dbProject; private JsonProject _jsonProject; #endregion #region Public Properties exposed to ViewModel public string ProjectNameWithNamespace => _dbProject.NameWithNamespace; public string Description => _dbProject.Description; public string AccountIdentifier => _dbProject.Account.Identifier; public int CommitCount => _jsonProject.Statistics.CommitCount; public int GitlabProjectId => _jsonProject.Id; public int TagCount => _jsonProject.TagList.Count; public int StarCount => _jsonProject.StarCount; public int OpenIssueCount => _jsonProject.OpenIssuesCount; public string WebUrl => _jsonProject.WebUrl; public List<string> TagList => _jsonProject.TagList; public bool IsProjectDownloaded => !string.IsNullOrWhiteSpace(_dbProject.LocalFolder); public bool ProjectDownloading { get; set; } #endregion /// <summary> /// Constructor /// </summary> /// <param name="gitlabProjectManager">Service to access gitlab projects</param> /// <param name="systemService">Service to access system functionality</param> /// <param name="databaseService">Service to access database</param> /// <param name="gitlabProjectDownloader">Service that cares about downloading git projects</param> /// <param name="dialogService">Service to open dialogs</param> public WindowProjectDetailModel(GitlabProjectManager gitlabProjectManager, ISystemService systemService, DatabaseService databaseService, GitlabProjectDownloader gitlabProjectDownloader, IDialogService dialogService) { _gitlabProjectManager = gitlabProjectManager; _systemService = systemService; _databaseService = databaseService; _gitlabProjectDownloader = gitlabProjectDownloader; _dialogService = dialogService; } #region Public Actions /// <summary> /// Init ViewModel for projectId /// </summary> /// <param name="projectId">Internal ProjectId (Database) that should be opened</param> public async void Init(int projectId) { // get project info from database _dbProject = _gitlabProjectManager.GetProject(projectId); // get json project meta data _jsonProject = await _gitlabProjectManager.GetCachedProjectMeta(_dbProject); // init download for specific gitlab account _gitlabProjectDownloader.InitForClient( new GitlabAccountClientImpl(_dbProject.Account.HostUrl, _dbProject.Account.AuthenticationToken) ); // delete local folder in database if folder not present on client if (!string.IsNullOrEmpty(_dbProject.LocalFolder) && !Directory.Exists(_dbProject.LocalFolder)) { _databaseService.UpdateLocalFolderForProject(_dbProject, ""); } RaiseUpdateProject(); } /// <summary> /// Open a project in the web browser /// </summary> public void OpenProjectInBrowser() { _systemService.OpenBrowser(WebUrl); } /// <summary> /// Clone a Git-project to local directory /// </summary> public void CloneProjectToDefaultFolder() { // build folder name and path var folderName = _jsonProject.NameWithNamespace .Replace("/", "-") .Replace(" ", "") .Replace("ß", "ss") .ToLower(); var folderPath = $"{_gitlabProjectDownloader.ProjectsDefaultFolder}/{folderName}"; CloneProjectToFolder(folderPath); } public void CloneProjectToCustomFolder() { // build folder name and path var folderPath = _dialogService.SelectFolderDialog( description: "Select folder in which project should be cloned" ); CloneProjectToFolder(folderPath); } private void CloneProjectToFolder(string folderPath) { Task.Run(async () => { // set ui loading SetProjectDownloadingStatus(true); // download project await _gitlabProjectDownloader.DownloadGitlabProject(_jsonProject.HttpUrlToRepo, folderPath); // set path to database _databaseService.UpdateLocalFolderForProject(_dbProject, folderPath); // set ui not loading any more SetProjectDownloadingStatus(false); RaisePropertyChanged(nameof(IsProjectDownloaded)); }); } /// <summary> /// Open project in App /// </summary> /// <param name="appName">Name of app (currently explorer or vscode)</param> public void OpenInApp(string appName) { switch (appName) { case "explorer": _systemService.OpenFolderInExplorer(_dbProject.LocalFolder); break; case "vscode": _systemService.OpenFolderInVsCode(_dbProject.LocalFolder); break; } } #endregion #region Private Utility Methods private void RaiseUpdateProject() { RaisePropertyChanged(nameof(ProjectNameWithNamespace)); RaisePropertyChanged(nameof(Description)); RaisePropertyChanged(nameof(AccountIdentifier)); RaisePropertyChanged(nameof(CommitCount)); RaisePropertyChanged(nameof(GitlabProjectId)); RaisePropertyChanged(nameof(TagCount)); RaisePropertyChanged(nameof(StarCount)); RaisePropertyChanged(nameof(OpenIssueCount)); RaisePropertyChanged(nameof(WebUrl)); RaisePropertyChanged(nameof(TagList)); RaisePropertyChanged(nameof(IsProjectDownloaded)); } private void SetProjectDownloadingStatus(bool downloading) { ProjectDownloading = downloading; RaisePropertyChanged(nameof(ProjectDownloading)); } #endregion } }
using System.ComponentModel.DataAnnotations; namespace iCopy.Model.Request { public class Login { [Required(ErrorMessage = "ErrNoUsername")] [MaxLength(100, ErrorMessage = "ErrMaxLengthUsername")] public string Username { get; set; } [Required(ErrorMessage = "ErrNoPassword")] [MaxLength(100, ErrorMessage = "ErrMaxLengthPassword")] [DataType(DataType.Password, ErrorMessage = "ErrDataTypePassword")] public string Password { get; set; } } }
using UnityEngine; using System.Collections; public class ButtonsCS : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void StartButtonClick() { echoServerCS.SetStart (); } public void StopButtonClick() { echoServerCS.SetStop (); } }
using UnityEngine; public class EnemyManager : MonoBehaviour { public GameObject _Enemy = null; private void Start () { GenerateEnemy (); } public void GenerateEnemy () { Instantiate (_Enemy, Camera.main.transform.position + new Vector3 (0f, 375f, 0f), Quaternion.identity); } }
using BerlinClock.Enum; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BerlinClock.Classes.Utility { public static class TimeParser { public static int TimeToSeconds(this string time) { return int.Parse(time.Split(':')[(int)HourFormatEnum.Sec]); } public static int TimeToMinutes(this string time) { return int.Parse(time.Split(':')[(int)HourFormatEnum.Min]); } public static int TimeToHour(this string time) { return int.Parse(time.Split(':')[(int)HourFormatEnum.Hour]); } } }
// Copyright (c) 2020 Markus Wackermann // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; using System.Windows.Media; namespace neXn { namespace BlockMatrix { public class BlockMatrix { private readonly List<Block> BlockList = new List<Block>(); /// <summary> /// Returns the percantage of "On" Blocks as string ex. "19 %" /// </summary> public string UsagePercentage { get; set; } /// <summary> /// 0-255 / Byte <br/> /// How many blocks should be "On" /// </summary> public byte RandomDegree { get; set; } = 0xc0; private readonly Grid refGrid; /// <summary> /// Create a new BlockMatrix /// </summary> /// <param name="refGrid">Grid it should be drawn</param> public BlockMatrix(ref Grid refGrid) { this.refGrid = refGrid; this.AnimationSequence.Tick += AnimationSequence_Tick; } /// <summary> /// Draw a new Matrix /// </summary> /// <param name="columCount"></param> /// <param name="rowCount"></param> public void CreateMatrix(int columCount = 19, int rowCount = 4) { int X = 10; // +40 int Y = 10; // +15 int count = 0; //17 * 4 = 68 for (int i = 0; i < columCount * rowCount; i++) { Block acc = new Block() { Width = 36, Height = 12, CornerRadius = new CornerRadius(4), Margin = new Thickness(X, Y, 0, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Name = "Block_" + count.ToString(), ID = count }; acc.Width = 36; count -= -1; Debug.Print("Block created X: " + X.ToString() + " Y: " + Y.ToString()); BlockList.Add(acc); X -= -40; if (X >= (columCount * 40) + 10) { X = 10; Y -= -15; } if (count >= columCount * rowCount) { break; } } BlockList.All(x => { this.refGrid.Children.Add(x); return true; }); } public class Block : Border { private readonly SolidColorBrush OffBrush = new SolidColorBrush(Color.FromRgb(200, 210, 220)); private readonly SolidColorBrush OnBrush = new SolidColorBrush(Color.FromRgb(28, 166, 0)); public int ID { get; set; } public bool IsActive { get; set; } public Block() { base.Background = OffBrush; this.IsActive = false; } public void On() { base.Background = OnBrush; this.IsActive = true; } public void Off() { base.Background = OffBrush; this.IsActive = false; } } private readonly Timer AnimationSequence = new Timer(); private void AnimationSequence_Tick(object sender, EventArgs e) { BlockList.All(x => { Random random = new Random(Guid.NewGuid().GetHashCode()); int rand = random.Next(1, 256); if (rand <= RandomDegree) { x.Off(); } else { x.On(); } return true; }); this.UsagePercentage = ((BlockList.Count(x => x.IsActive) * 100) / BlockList.Count).ToString() + " %"; } public void Start() { this.AnimationSequence.Enabled = true; this.AnimationSequence.Interval = 100; this.AnimationSequence.Start(); } public void Stop() { this.AnimationSequence.Enabled = false; this.AnimationSequence.Stop(); } } } }
using System.Collections.Generic; using System.Linq; using Renting.Domain.Agreements; namespace Renting.Persistence.InMemory { public class InMemoryAgreementRepository : IAgreementRepository { private readonly List<Agreement> _agreements = new List<Agreement>(); public void Save(Agreement agreement) { _agreements.Add(agreement); } public Agreement Get(AgreementId agreementId) { return _agreements.SingleOrDefault(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.SqlClient; using System.Text; using Maticsoft.DBUtility; namespace PDTech.OA.DAL { /// <summary> /// 数据访问类:USER_INFO /// </summary> public partial class USER_INFO { PDTech.OA.DAL.VIEW_USER_RIGHT vidal = new VIEW_USER_RIGHT(); OPERATION_LOG log = new OPERATION_LOG(); const string USER_CREATE = "USER_CREATE"; const string USER_UP = "USER_UP"; public USER_INFO() { } #region BasicMethod public object get_db_para_value(object in_p) { if (in_p == null) return DBNull.Value; else return in_p; } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(decimal USER_ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from USER_INFO"); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@USER_ID", SqlDbType.BigInt) }; parameters[0].Value = USER_ID; return DbHelperSQL.Exists(strSql.ToString(), parameters); } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(string LOGIN_NAME) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from USER_INFO"); strSql.Append(" where LOGIN_NAME=@LOGIN_NAME "); SqlParameter[] parameters = { new SqlParameter("@LOGIN_NAME", SqlDbType.NVarChar,20) }; parameters[0].Value = LOGIN_NAME; return DbHelperSQL.Exists(strSql.ToString(), parameters); } /// <summary> /// 增加一条数据 /// </summary> public int Add(PDTech.OA.Model.USER_INFO model, string HostName, string Ip, decimal operId) { int Flag = 0; try { string reruneVal = ""; if (Exists(model.LOGIN_NAME)) { return -2; } StringBuilder strSql = new StringBuilder(); strSql.Append("insert into USER_INFO("); strSql.Append("LOGIN_NAME,FULL_NAME,LOGIN_PWD,PHONE,MOBILE,DEPARTMENT_ID,ATTRIBUTE_LOG,SORT_NUMBER,IS_DISABLE,DUTY_INFO,PUBLIC_NAME,E_MAILE,REMARK)"); strSql.Append(" values ("); strSql.Append("@LOGIN_NAME,@FULL_NAME,@LOGIN_PWD,@PHONE,@MOBILE,@DEPARTMENT_ID,@ATTRIBUTE_LOG,@SORT_NUMBER,@IS_DISABLE,@DUTY_INFO,@PUBLIC_NAME,@E_MAILE,@REMARK) select @OUT_LOG_ID = SCOPE_IDENTITY() "); SqlParameter uid_out = new SqlParameter("@OUT_LOG_ID", SqlDbType.Int); uid_out.Direction = ParameterDirection.Output; SqlParameter[] parameters = { new SqlParameter("@LOGIN_NAME", SqlDbType.VarChar,20), new SqlParameter("@FULL_NAME", SqlDbType.VarChar,20), new SqlParameter("@LOGIN_PWD", SqlDbType.VarChar,32), new SqlParameter("@PHONE", SqlDbType.VarChar,30), new SqlParameter("@MOBILE", SqlDbType.VarChar,20), new SqlParameter("@DEPARTMENT_ID", SqlDbType.Decimal,4), new SqlParameter("@ATTRIBUTE_LOG", SqlDbType.Decimal,4), new SqlParameter("@SORT_NUMBER", SqlDbType.Decimal,4), new SqlParameter("@IS_DISABLE", SqlDbType.Char,1), new SqlParameter("@DUTY_INFO", SqlDbType.NVarChar,50), new SqlParameter("@PUBLIC_NAME", SqlDbType.NVarChar,20), new SqlParameter("@E_MAILE", SqlDbType.NVarChar,100), new SqlParameter("@REMARK", SqlDbType.NVarChar,2000), uid_out}; parameters[0].Value = get_db_para_value(model.LOGIN_NAME); parameters[1].Value = get_db_para_value(model.FULL_NAME); parameters[2].Value = get_db_para_value(model.LOGIN_PWD); parameters[3].Value = get_db_para_value(model.PHONE); parameters[4].Value = get_db_para_value(model.MOBILE); parameters[5].Value = get_db_para_value(model.DEPARTMENT_ID); parameters[6].Value = get_db_para_value(model.ATTRIBUTE_LOG); parameters[7].Value = get_db_para_value(model.SORT_NUMBER); parameters[8].Value = get_db_para_value(model.IS_DISABLE); parameters[9].Value = get_db_para_value(model.DUTY_INFO); parameters[10].Value = get_db_para_value(model.PUBLIC_NAME); parameters[11].Value = get_db_para_value(model.E_MAILE); parameters[12].Value = get_db_para_value(model.REMARK); int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); reruneVal = uid_out.Value.ToString(); if (rows > 0) { PDTech.OA.Model.OPERATION_LOG Qwhere = new Model.OPERATION_LOG(); Qwhere.OPERATOR_USER = operId; Qwhere.OPERATION_TYPE = USER_CREATE; Qwhere.ENTITY_TYPE = (decimal)ENTITY_TYPE.用户; Qwhere.ENTITY_ID = decimal.Parse(reruneVal); Qwhere.HOST_IP = Ip; Qwhere.HOST_NAME = HostName; Qwhere.OPERATION_DESC = "新增用户信息:LOGIN_NAME=" + model.LOGIN_NAME + ",FULL_NAME=" + model.FULL_NAME + ",PHONE=" + model.PHONE + ",MOBILE=" + model.MOBILE + "..."; Qwhere.OPERATION_DATA = ""; log.Add(Qwhere); Flag = 1; } else { Flag = 0; } } catch (Exception ex) { Flag = -1; } return Flag; } /// <summary> /// 更新一条数据 /// </summary> public int Update(PDTech.OA.Model.USER_INFO model, string HostName, string Ip, decimal operId) { int IntFlag = 0; try { StringBuilder strSql = new StringBuilder(); strSql.Append("update USER_INFO set "); strSql.Append("FULL_NAME=@FULL_NAME,"); strSql.Append("PHONE=@PHONE,"); strSql.Append("MOBILE=@MOBILE,"); strSql.Append("DEPARTMENT_ID=@DEPARTMENT_ID,"); strSql.Append("ATTRIBUTE_LOG=@ATTRIBUTE_LOG,"); strSql.Append("SORT_NUMBER=@SORT_NUMBER,"); strSql.Append("IS_DISABLE=@IS_DISABLE,"); strSql.Append("DUTY_INFO=@DUTY_INFO,"); strSql.Append("PUBLIC_NAME=@PUBLIC_NAME,"); strSql.Append("E_MAILE=@E_MAILE,"); strSql.Append("REMARK=@REMARK"); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@FULL_NAME", SqlDbType.VarChar,20), new SqlParameter("@PHONE", SqlDbType.VarChar,30), new SqlParameter("@MOBILE", SqlDbType.VarChar,20), new SqlParameter("@DEPARTMENT_ID", SqlDbType.Decimal,4), new SqlParameter("@ATTRIBUTE_LOG", SqlDbType.Decimal,4), new SqlParameter("@SORT_NUMBER", SqlDbType.Decimal,4), new SqlParameter("@IS_DISABLE", SqlDbType.Char,1), new SqlParameter("@DUTY_INFO", SqlDbType.NVarChar,50), new SqlParameter("@PUBLIC_NAME", SqlDbType.NVarChar,20), new SqlParameter("@E_MAILE", SqlDbType.NVarChar,100), new SqlParameter("@REMARK", SqlDbType.NVarChar,2000), new SqlParameter("@USER_ID", SqlDbType.Decimal,4)}; parameters[0].Value = model.FULL_NAME; parameters[1].Value = model.PHONE; parameters[2].Value = model.MOBILE; parameters[3].Value = model.DEPARTMENT_ID; parameters[4].Value = model.ATTRIBUTE_LOG; parameters[5].Value = model.SORT_NUMBER; parameters[6].Value = model.IS_DISABLE; parameters[7].Value = model.DUTY_INFO; parameters[8].Value = model.PUBLIC_NAME; parameters[9].Value = model.E_MAILE; parameters[10].Value = model.REMARK; parameters[11].Value = model.USER_ID; DAL_Helper.get_db_para_value(parameters); int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { PDTech.OA.Model.OPERATION_LOG Qwhere = new Model.OPERATION_LOG(); Qwhere.OPERATOR_USER = operId; Qwhere.OPERATION_TYPE = USER_UP; Qwhere.ENTITY_TYPE = (decimal)ENTITY_TYPE.用户; Qwhere.ENTITY_ID = model.USER_ID; Qwhere.HOST_IP = Ip; Qwhere.HOST_NAME = HostName; Qwhere.OPERATION_DESC = "修改用户信息:LOGIN_NAME=" + model.LOGIN_NAME + ",FULL_NAME=" + model.FULL_NAME + ",PHONE=" + model.PHONE + ",MOBILE=" + model.MOBILE + "..."; Qwhere.OPERATION_DATA = ""; log.Add(Qwhere); IntFlag = 1; } else { IntFlag = 0; } } catch { IntFlag = -1; } return IntFlag; } /// <summary> /// 更新一条数据(用户基本信息) /// </summary> public bool Update(PDTech.OA.Model.USER_INFO model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update USER_INFO set "); strSql.Append("PHONE=@PHONE,"); strSql.Append("MOBILE=@MOBILE"); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@PHONE", SqlDbType.VarChar,30), new SqlParameter("@MOBILE", SqlDbType.VarChar,20), new SqlParameter("@USER_ID", SqlDbType.Decimal,4)}; parameters[0].Value = model.PHONE; parameters[1].Value = model.MOBILE; parameters[2].Value = model.USER_ID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 修改密码 /// </summary> public bool UpdatePwd(PDTech.OA.Model.USER_INFO model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update USER_INFO set "); strSql.Append("login_pwd=@login_pwd"); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@login_pwd", SqlDbType.VarChar,32), new SqlParameter("@USER_ID", SqlDbType.Decimal,22)}; parameters[0].Value = model.LOGIN_PWD; parameters[1].Value = model.USER_ID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal USER_ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from USER_INFO "); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@USER_ID", SqlDbType.Decimal,22) }; parameters[0].Value = USER_ID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string USER_IDlist) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from USER_INFO "); strSql.Append(" where USER_ID in (" + USER_IDlist + ") "); int rows = DbHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.USER_INFO GetModel(decimal USER_ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select USER_ID,LOGIN_NAME,FULL_NAME,LOGIN_PWD,PHONE,MOBILE,DEPARTMENT_ID,ATTRIBUTE_LOG,SORT_NUMBER,IS_DISABLE from USER_INFO "); strSql.Append(" where USER_ID=@USER_ID "); SqlParameter[] parameters = { new SqlParameter("@USER_ID", SqlDbType.Decimal,22) }; parameters[0].Value = USER_ID; PDTech.OA.Model.USER_INFO model = new PDTech.OA.Model.USER_INFO(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } public PDTech.OA.Model.USER_INFO GetModel(string userName) { StringBuilder strSql = new StringBuilder(); strSql.Append("select USER_ID,LOGIN_NAME,FULL_NAME,LOGIN_PWD,PHONE,MOBILE,DEPARTMENT_ID,ATTRIBUTE_LOG,SORT_NUMBER,IS_DISABLE from USER_INFO "); strSql.Append(" where FULL_NAME=@FULL_NAME "); SqlParameter[] parameters = { new SqlParameter("@FULL_NAME", SqlDbType.VarChar,20) }; parameters[0].Value = userName; PDTech.OA.Model.USER_INFO model = new PDTech.OA.Model.USER_INFO(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.USER_INFO DataRowToModel(DataRow row) { PDTech.OA.Model.USER_INFO model = new PDTech.OA.Model.USER_INFO(); if (row != null) { if (row["USER_ID"] != null && row["USER_ID"].ToString() != "") { model.USER_ID = decimal.Parse(row["USER_ID"].ToString()); } if (row["LOGIN_NAME"] != null) { model.LOGIN_NAME = row["LOGIN_NAME"].ToString(); } if (row["FULL_NAME"] != null) { model.FULL_NAME = row["FULL_NAME"].ToString(); } if (row["LOGIN_PWD"] != null) { model.LOGIN_PWD = row["LOGIN_PWD"].ToString(); } if (row["PHONE"] != null) { model.PHONE = row["PHONE"].ToString(); } if (row["MOBILE"] != null) { model.MOBILE = row["MOBILE"].ToString(); } if (row["DEPARTMENT_ID"] != null && row["DEPARTMENT_ID"].ToString() != "") { model.DEPARTMENT_ID = decimal.Parse(row["DEPARTMENT_ID"].ToString()); } if (row["ATTRIBUTE_LOG"] != null && row["ATTRIBUTE_LOG"].ToString() != "") { model.ATTRIBUTE_LOG = decimal.Parse(row["ATTRIBUTE_LOG"].ToString()); } if (row["SORT_NUMBER"] != null && row["SORT_NUMBER"].ToString() != "") { model.SORT_NUMBER = decimal.Parse(row["SORT_NUMBER"].ToString()); } if (row["IS_DISABLE"] != null) { model.IS_DISABLE = row["IS_DISABLE"].ToString(); } } return model; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select USER_ID,LOGIN_NAME,FULL_NAME,LOGIN_PWD,PHONE,MOBILE,DEPARTMENT_ID,ATTRIBUTE_LOG,SORT_NUMBER,IS_DISABLE "); strSql.Append(" FROM USER_INFO "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获取分管部门下属所有人员 /// </summary> /// <param name="uid">当前用户id</param> /// <returns></returns> public IList<Model.USER_INFO> GetOwnerDeptUsersModelList(string uid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select USER_ID,LOGIN_NAME,FULL_NAME,LOGIN_PWD,PHONE,MOBILE,DEPARTMENT_ID,ATTRIBUTE_LOG,SORT_NUMBER,IS_DISABLE "); strSql.Append(" FROM USER_INFO WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM USERS_DEPT_OWNER_MAP WHERE USER_ID = {0})"); DataTable dt = DbHelperSQL.GetTable(string.Format(strSql.ToString(),uid)); return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) FROM USER_INFO "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } object obj = DbHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 获取用户信息---未分页 /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.USER_INFO> get_UserInfoList(Model.USER_INFO where) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format("SELECT U.*,(SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) DEPARTMENT_NAME FROM USER_INFO U WHERE 1=1 {0} ", condition); DataTable dt = DbHelperSQL.GetTable(strSQL); return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } /// <summary> /// 获取用户信息---未分页 /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.USER_INFO> get_UserInfoList(decimal uId) { string strSQL = string.Format("SELECT U.*,(SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) DEPARTMENT_NAME FROM USER_INFO U WHERE DEPARTMENT_ID={0} ORDER BY SORT_NUMBER ASC ", uId); DataTable dt = DbHelperSQL.GetTable(strSQL); return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } /// <summary> /// 获取用户信息--返回dataTable /// </summary> /// <param name="where"></param> /// <returns></returns> public DataTable get_UserTab(Model.USER_INFO where) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format("SELECT U.*,(SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) DEPARTMENT_NAME FROM USER_INFO U WHERE 1=1 {0} ", condition); DataTable dt = DbHelperSQL.GetTable(strSQL); return dt; } /// <summary> /// 查询用户信息 /// </summary> /// <param name="uId">用户ID</param> /// <returns>返回一条用户信息</returns> public Model.USER_INFO GetUserInfo(decimal uId) { string strSQL = string.Format("SELECT U.*,(SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) DEPARTMENT_NAME FROM USER_INFO U WHERE USER_ID={0}", uId); DataTable dt = DbHelperSQL.Query(strSQL).Tables[0]; if (dt.Rows.Count > 0) { return DAL_Helper.CommonFillList<Model.USER_INFO>(dt)[0]; } else { return null; } } /// <summary> /// 查询用户信息 /// </summary> /// <param name="deptId">部门ID</param> /// <returns>某一部门的所有用户</returns> public IList<Model.USER_INFO> GetUserInfoBydeptId(string deptId) { StringBuilder strSql = new StringBuilder(); strSql.Append("select full_name,phone,mobile,e_maile,"); strSql.Append("(select department_name from department d where d.department_id=u.department_id) as department_name "); strSql.Append("from user_info u "); strSql.Append("where u.department_id='" + deptId + "' AND IS_DISABLE='0' order by sort_number asc"); DataTable dt = DbHelperSQL.Query(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) { return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } else { return null; } } /// <summary> /// 获取一条用户信息 /// </summary> /// <param name="where"></param> /// <returns></returns> public Model.USER_INFO GetUserInfo(string LOGIN_NAME, string LOGIN_PWD) { string strLogin = string.Format(@"SELECT USER_ID,LOGIN_NAME,FULL_NAME,DEPARTMENT_ID,PHONE,MOBILE,(SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=USER_INFO.DEPARTMENT_ID) DEPARTMENT_NAME FROM USER_INFO WHERE LOGIN_NAME='{0}' AND LOGIN_PWD='{1}' AND IS_DISABLE='0'", LOGIN_NAME, LOGIN_PWD); //DataTable dt = DbHelperSQL.GetTable(strLogin); DataTable dt = DbHelperSQL.Query(strLogin).Tables[0]; if (dt.Rows.Count > 0) { return DAL_Helper.CommonFillList<Model.USER_INFO>(dt)[0]; } else { return null; } } /// <summary> /// /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.USER_INFO> get_tUserList(Model.USER_INFO where) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format("SELECT * FROM USER_INFO WHERE 1=1 {0}", condition); DataTable dt = DbHelperSQL.GetTable(strSQL); return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } /// <summary> /// 获取用户信息-使用分页 /// </summary> /// <param name="where"></param> /// <param name="currentpage"></param> /// <param name="pagesize"></param> /// <param name="totalrecord"></param> /// <returns></returns> public IList<Model.USER_INFO> get_Paging_UserInfoList(Model.USER_INFO where, int currentpage, int pagesize, out int totalrecord) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format(@"SELECT TOP (100) PERCENT U.*, (SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) DEPARTMENT_NAME, (SELECT SORT_NUM FROM DEPARTMENT WHERE DEPARTMENT_ID=U.DEPARTMENT_ID) SORT_NUM FROM USER_INFO U WHERE 1=1 {0} ", condition); PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = currentpage; pdes.PageSize = pagesize; DataTable dt = pdes.PageDescribes(strSQL); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.USER_INFO>(dt); } /// <summary> /// 用户是否启用 /// </summary> /// <param name="deptId">用户ID</param> /// <param name="disType">修改值</param> /// <returns></returns> public int ModDisable(decimal userId, string disType) { int result = 0; string ModSQL = string.Format(@"UPDATE USER_INFO SET IS_DISABLE='{0}' WHERE USER_ID={1}", disType, userId); result = DbHelperSQL.ExecuteSql(ModSQL); return result; } /// <summary> /// 获取用户信息返回为datatable /// </summary> /// <param name="uName">full_name</param> /// <param name="Right_Code">权限编码</param> /// <returns></returns> public DataTable GetUserList(string uName, string Right_Code) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * from user_info where is_disable='0' and upper(full_name) like '%' + upper('" + uName + "') + '%' "); if (!string.IsNullOrEmpty(Right_Code)) { strSql.Append(" AND USER_ID IN(SELECT USER_ID FROM VIEW_USER_RIGHT WHERE 1=1 AND RIGHT_CODE='" + Right_Code + "' )"); } strSql.Append(" ORDER BY SORT_NUMBER ASC"); return DbHelperSQL.GetTable(strSql.ToString()); } public DataTable GetCurDeptUserList(string uid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * from user_info where is_disable='0' and DEPARTMENT_ID=(select DEPARTMENT_ID from USER_INFO where USER_ID="+uid.ToString()+")"); strSql.Append(" ORDER BY SORT_NUMBER ASC"); return DbHelperSQL.GetTable(strSql.ToString()); } /// <summary> /// 修改登录状态 /// </summary> /// <param name="userId"></param> /// <returns></returns> public bool UpdateLogin_State(decimal userId, int state, string clientIp) { string ModSQL = ""; switch (state) { case 1: ModSQL = string.Format(@"UPDATE USER_INFO SET IS_ONLINE=1,LAST_DATE=GETDATE(),LAST_IP='{0}' WHERE 1=1 AND USER_ID={1}", clientIp, userId); break; case 0: ModSQL = string.Format(@"UPDATE USER_INFO SET IS_ONLINE=0 WHERE 1=1 AND USER_ID={0}", userId); break; } int rows = DbHelperSQL.ExecuteSql(ModSQL); if (rows > 0) { return true; } else { return false; } } #endregion BasicMethod #region ExtensionMethod /// <summary> /// 用户登录 /// </summary> /// <param name="where"></param> /// <param name="?"></param> /// <returns></returns> public int UserLogin(PDTech.OA.Model.USER_INFO where, out PDTech.OA.Model.USER_INFO Ac, out IList<PDTech.OA.Model.VIEW_USER_RIGHT> vList, string clientIp) { int intFlag = 0; Ac = null; vList = null; try { string ChkUser = string.Format(@"SELECT COUNT(1) FROM USER_INFO WHERE 1=1 AND LOGIN_NAME=@LOGIN_NAME"); SqlParameter[] parameters = { new SqlParameter("@LOGIN_NAME",SqlDbType.VarChar,20)}; //SqlParameter[] parameters = { // new SqlParameter("@LOGIN_NAME", SqlDbType.VarChar,20)}; parameters[0].Value = where.LOGIN_NAME; int chkValue = DbHelperSQL.ExecuteScalar(ChkUser, parameters); if (chkValue == 0) { return -1; } Ac = GetUserInfo(where.LOGIN_NAME, where.LOGIN_PWD); if (Ac != null) { vList = vidal.get_ViewList(new Model.VIEW_USER_RIGHT() { USER_ID = Ac.USER_ID }); UpdateLogin_State((decimal)Ac.USER_ID, 1, clientIp); intFlag = 1; } else { intFlag = 0; } } catch (Exception ex) { intFlag = -2; } finally { } return intFlag; } /// <summary> /// 查询用户基本信息 /// </summary> /// <param name="uid">用户ID</param> /// <returns>返回基本信息</returns> public DataTable GetUserInfo(string uid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select (select department_name from department d where d.department_id=u.department_id) as department_name,full_name,phone,mobile "); strSql.Append("from user_info u "); strSql.Append("where u.user_id='" + uid + "' "); return DbHelperSQL.GetTable(strSql.ToString()); } /// <summary> /// 查询用户密码 /// </summary> /// <param name="uid">用户ID</param> /// <returns>返回密码</returns> public string GetUserPassword(string uid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select login_pwd from user_info where user_id='" + uid + "'"); DataTable dt = DbHelperSQL.GetTable(strSql.ToString()); return dt.Rows[0]["login_pwd"].ToString(); } #endregion ExtensionMethod } }
namespace Belot.AI.SmartPlayer.Strategies { using Belot.Engine.Cards; public static class CardHelpers { public static Card GetCardThatSurelyWinsATrickInAllTrumps( CardCollection availableCardsToPlay, CardCollection playerCards, CardCollection playedCards, int cardsThreshold) { foreach (var card in availableCardsToPlay) { if (card.Type == CardType.Jack && playedCards.GetCount(x => x.Suit == card.Suit) + playerCards.GetCount(x => x.Suit == card.Suit) > cardsThreshold) { return card; } if (card.Type == CardType.Nine && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.Ace && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.Ten && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.King && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.Queen && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.Eight && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } if (card.Type == CardType.Seven && playedCards.Contains(Card.GetCard(card.Suit, CardType.Eight)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack))) { return card; } } return null; } public static Card GetCardThatSurelyWinsATrickInNoTrumps( CardCollection availableCardsToPlay, CardCollection playerCards, CardCollection playedCards) { foreach (var card in availableCardsToPlay) { if (card.Type == CardType.Ace && playedCards.GetCount(x => x.Suit == card.Suit) + playerCards.GetCount(x => x.Suit == card.Suit) > 4) { return card; } if (card.Type == CardType.Ten && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.King && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.Queen && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.Jack && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.Nine && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.Eight && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } if (card.Type == CardType.Seven && playedCards.Contains(Card.GetCard(card.Suit, CardType.Eight)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Nine)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Jack)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Queen)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.King)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ten)) && playedCards.Contains(Card.GetCard(card.Suit, CardType.Ace))) { return card; } } return null; } } }
using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace publicApiTest { public class JsonTest { [Test] public void jsontest() { var str = Properties.Resources.accountInfo; var jo = JObject.Parse(str); var needmodify = new Dictionary<string, string>(); foreach (var child in jo) { var key = child.Key; var value = child.Value; var dic = ((JObject)value).Properties().ToDictionary(p => p.Name , p=>p.Value); if(dic.ContainsKey("verified")) { dic["verified"] = "1"; } var dicstr = JsonConvert.SerializeObject(dic, Formatting.Indented); jo[value.Path] = JObject.Parse(dicstr); } var displayname = jo["displayname"]; } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class DynFachabteilung { public DynFachabteilung() { ArcAktenaufenthalt = new HashSet<ArcAktenaufenthalt>(); DynAusleiheUserFachabteilung = new HashSet<DynAusleiheUserFachabteilung>(); DynStation = new HashSet<DynStation>(); } public int FachabteilungId { get; set; } public string Bezeichnung { get; set; } public bool? Aktiv { get; set; } public int? Kisid { get; set; } public string KurzBezeichnung { get; set; } public int? HausId { get; set; } public int? StandortId { get; set; } public virtual DynHaus Haus { get; set; } public virtual DynStandort Standort { get; set; } public virtual ICollection<ArcAktenaufenthalt> ArcAktenaufenthalt { get; set; } public virtual ICollection<DynAusleiheUserFachabteilung> DynAusleiheUserFachabteilung { get; set; } public virtual ICollection<DynStation> DynStation { get; set; } } }
using MonoGame.Extended.Input; using MonoGame.Extended.Input.InputListeners; namespace MonoGame.Extended.NuclexGui.Controls.Desktop { // Always move in absolute (offset) coordinates? // Or always move in fractional coordinates? // // Preferring b), because I restores the user's display to the exact // state it was if the resolution is changed, including that fact that // lower resolutions would cause the windows to go off-screen. // // However, b) would mean a call to GetAbsolutePosition() each frame. // Which isn't so bad, but... avoidable with a) // Properties: // Boundaries (for constraining a control to a region) // Moveable (turn moveability on or off) /// <summary>Control the user can drag around with the mouse</summary> public abstract class GuiDraggableControl : GuiControl { /// <summary>Whether the control is currently being dragged</summary> private bool _beingDragged; /// <summary>Whether the control can be dragged</summary> private bool _enableDragging; /// <summary>X coordinate at which the control was picked up</summary> private float _pickupX; /// <summary>Y coordinate at which the control was picked up</summary> private float _pickupY; /// <summary>Initializes a new draggable control</summary> public GuiDraggableControl() { EnableDragging = true; } /// <summary>Initializes a new draggable control</summary> /// <param name="canGetFocus">Whether the control can obtain the input focus</param> public GuiDraggableControl(bool canGetFocus) : base(canGetFocus) { EnableDragging = true; } /// <summary>Whether the control can be dragged with the mouse</summary> protected bool EnableDragging { get { return _enableDragging; } set { _enableDragging = value; _beingDragged &= value; } } /// <summary>Called when the mouse position is updated</summary> /// <param name="x">X coordinate of the mouse cursor on the GUI</param> /// <param name="y">Y coordinate of the mouse cursor on the GUI</param> protected override void OnMouseMoved(float x, float y) { if (_beingDragged) { // Adjust the control's position within the container var dx = x - _pickupX; var dy = y - _pickupY; Bounds.AbsoluteOffset(dx, dy); } else { // Remember the current mouse position so we know where the user picked // up the control when a drag operation begins _pickupX = x; _pickupY = y; } } /// <summary>Called when a mouse button has been pressed down</summary> /// <param name="button">Index of the button that has been pressed</param> protected override void OnMousePressed(MouseButton button) { if (button == MouseButton.Left) _beingDragged = _enableDragging; } /// <summary>Called when a mouse button has been released again</summary> /// <param name="button">Index of the button that has been released</param> protected override void OnMouseReleased(MouseButton button) { if (button == MouseButton.Left) _beingDragged = false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnStone : MonoBehaviour { public GameObject Stone; // Объект Который будет спавнится public BoxCollider2D StoneColl; // Коллайдер, если объекту нужно действие при косании с чем либо private void Awake() { StoneColl = GetComponent<BoxCollider2D>(); // Добавление компонента коллайдера на обьект } void Start() { StartCoroutine(Spawn()); // пристарте запускается метод спавна Объектов } IEnumerator Spawn() // Метод спавна объектов { while (!Player.lose) // Цикл который выполняется пока игрок жив { yield return new WaitForSeconds(Random.Range(10f, 60f)); // Задержка перед спавном объектов Instantiate(Stone, new Vector2(Random.Range(-2.85f, 2.85f), 5.521f), Quaternion.identity); // Первое - Это объект который будет спавнится, Второе - это это рандомное положение спавна(Координата от и до) } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChatLibrary.EaseMob; namespace ChatLibrary { /// <summary> /// /// </summary> public enum ChatLibraryType { //环信 EaseMob } public static class ChatClientFactory { private static Dictionary<ChatLibraryType, IChatClient> dictChatClient = new Dictionary<ChatLibraryType, IChatClient>(); private static IChatClient defaultClient = null; /// <summary> /// 获取默认的聊天接口 /// </summary> /// <returns></returns> public static IChatClient getDefaultChatClient() { IChatClient client=getChatClient(ChatLibraryType.EaseMob); //自动请求token ((EaseMobChatClient)client).AutoQueryToken(); return client; } public static IChatClient getChatClient(ChatLibraryType type) { if (!dictChatClient.ContainsKey(type)) { switch(type) { case ChatLibraryType.EaseMob:{ dictChatClient.Add(type, new EaseMobChatClient()); };break; } } return dictChatClient[ChatLibraryType.EaseMob]; } } }
using System; using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class ManualOrderButton : MonoBehaviour { [SerializeField] private SomewhatFancierExample3 _source; [SerializeField] private Button _button; private void Start() { _button.OnPointerClickAsObservable() .ThrottleFirst(TimeSpan.FromMilliseconds(500)) .Subscribe(_ => _source.OrderEspresso()) .AddTo(this); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class LaserToPoint : MonoBehaviour { private static GameObject LaserObj; public static void LaserToCoord() { Params.laserX1 = 0; Params.laserX2 = 0; Params.laserY1 = 0; Params.laserY2 = 0; LaserObj = GameObject.FindGameObjectWithTag("Laser"); if (LaserObj == null) { Debug.Log("No Laser Set"); } else { Params.laserX1 = LaserObj.transform.position.x + 1.75f*LaserObj.transform.lossyScale.x*Math.Cos(LaserObj.transform.rotation.z*(Math.PI/180)); Params.laserX2 = LaserObj.transform.position.y + 1.75f*LaserObj.transform.lossyScale.x*Math.Sin(LaserObj.transform.rotation.z*(Math.PI/180)); Params.laserY1 = LaserObj.transform.position.x - 1.75f*LaserObj.transform.lossyScale.x*Math.Cos(LaserObj.transform.rotation.z*(Math.PI/180)); Params.laserY2 = LaserObj.transform.position.y - 1.75f*LaserObj.transform.lossyScale.x*Math.Sin(LaserObj.transform.rotation.z*(Math.PI/180)); Debug.Log(Params.laserX1 + " " + Params.laserY1); Debug.Log(Params.laserX2 + " " + Params.laserY2); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace YoungCat.Toolkit { public struct Interval<T> { public T Start { get; private set; } public T End { get; private set; } public Interval(T start, T end) : this() { Start = start; End = end; } } public class IntervalCollection<TKey, TValue> : IDictionary<Interval<TKey>, TValue>, IDictionary where TKey : IComparable<TKey> { private readonly SortedList<TKey, MapValueType> map = new SortedList<TKey, MapValueType>(); private struct MapValueType { public readonly TValue Value; public readonly bool IsEnd; public MapValueType(TValue value, bool isEnd) { Value = value; IsEnd = isEnd; } } public void Add(TKey start, TKey end, TValue value) { throw new NotImplementedException(); } public void Clear() { map.Clear(); Count = 0; } public int Count { get; private set; } public bool ContainsKey(Interval<TKey> key) { return IndexOfKey(key) >= 0; } public bool ContainsPoint(TKey point) { return IndexOfPoint(point) >= 0; } private int IndexOfKey(Interval<TKey> key) { int index = map.IndexOfKey(key.Start); if (index > 0 && map.Count > index + 1 && !map.Values[index].IsEnd && map.Keys[index + 1].CompareTo(key.End) == 0) return index; else return -1; } private int IndexOfPoint(TKey point) { int index = map.BinarySearch(point); if (index < 0) index = (~index) - 1; if (map.Count > index + 1 && !map.Values[index].IsEnd && map.Keys[index + 1].CompareTo(point) > 0) return index; else return -1; } public KeyValuePair<Interval<TKey>, TValue> this[TKey point] { get { KeyValuePair<Interval<TKey>, TValue> entry; if (TryGetEntry(point, out entry)) return entry; else throw new KeyNotFoundException(); } } public TValue this[Interval<TKey> key] { get { TValue value; if (TryGetValue(key, out value)) return value; else throw new KeyNotFoundException(); } set { int index = IndexOfKey(key); if (index >= 0) map.Values[index] = new MapValueType(value, map.Values[index].IsEnd); else Add(key.Start, key.End, value); } } public bool Remove(TKey exactStart, TKey exactEnd) { throw new NotImplementedException(); } public bool Remove(Interval<TKey> key) { return Remove(key.Start, key.End); } public bool Subtract(TKey start, TKey end) { throw new NotImplementedException(); } public bool TryGetEntry(TKey point, out KeyValuePair<Interval<TKey>, TValue> entry) { int index = IndexOfPoint(point); if (index >= 0) { entry = new KeyValuePair<Interval<TKey>, TValue>( new Interval<TKey>(map.Keys[index], map.Keys[index + 1]), map.Values[index].Value); return true; } else { entry = default(KeyValuePair<Interval<TKey>, TValue>); return false; } } public bool TryGetValue(Interval<TKey> key, out TValue value) { int index = IndexOfKey(key); if (index >= 0) { value = map.Values[index].Value; return true; } else { value = default(TValue); return false; } } public List<Interval<TKey>> Keys { get { return null; } } public List<TValue> Values { get { return null; } } public IEnumerator<KeyValuePair<Interval<TKey>, TValue>> GetEnumerator() { throw new NotImplementedException(); } #region 显式实现接口 void IDictionary<Interval<TKey>, TValue>. Add(Interval<TKey> key, TValue value) { Add(key.Start, key.End, value); } void ICollection<KeyValuePair<Interval<TKey>, TValue>>. Add(KeyValuePair<Interval<TKey>, TValue> item) { Add(item.Key.Start, item.Key.End, item.Value); } void IDictionary. Add(object key, object value) { Interval<TKey> key2 = (Interval<TKey>)key; Add(key2.Start, key2.End, (TValue)value); } bool IDictionary. Contains(object key) { return ContainsKey((Interval<TKey>)key); } bool ICollection<KeyValuePair<Interval<TKey>, TValue>>. Contains(KeyValuePair<Interval<TKey>, TValue> item) { int index = IndexOfKey(item.Key); return (index >= 0 && map.Values[index].Equals(item.Value)); } void ICollection<KeyValuePair<Interval<TKey>, TValue>>. CopyTo(KeyValuePair<Interval<TKey>, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } void ICollection. CopyTo(Array array, int index) { (this as ICollection<KeyValuePair<Interval<TKey>, TValue>>). CopyTo((KeyValuePair<Interval<TKey>, TValue>[])array, index); } IEnumerator IEnumerable. GetEnumerator() { return GetEnumerator(); } IDictionaryEnumerator IDictionary. GetEnumerator() { throw new NotImplementedException(); } bool IDictionary. IsFixedSize { get { return false; } } bool ICollection<KeyValuePair<Interval<TKey>, TValue>>. IsReadOnly { get { return false; } } bool IDictionary. IsReadOnly { get { return false; } } bool ICollection. IsSynchronized { get { return false; } } ICollection<Interval<TKey>> IDictionary<Interval<TKey>, TValue>. Keys { get { return Keys; } } ICollection IDictionary. Keys { get { return Keys; } } bool ICollection<KeyValuePair<Interval<TKey>, TValue>>. Remove(KeyValuePair<Interval<TKey>, TValue> item) { throw new NotImplementedException(); } void IDictionary. Remove(object key) { throw new NotImplementedException(); } object IDictionary. this[object key] { get { return this[(Interval<TKey>)key]; } set { this[(Interval<TKey>)key] = (TValue)value; } } object ICollection. SyncRoot { get { throw new NotSupportedException(); } } ICollection<TValue> IDictionary<Interval<TKey>, TValue>. Values { get { return Values; } } ICollection IDictionary. Values { get { return Values; } } #endregion } }
using Godot; using System; using static Lib; public class BlueWTower : KinematicBody { protected Root root; protected Area attackArea; protected Vector3 move; protected float timeFromAttack; protected float attackTimeout = 1.0f; public override void _Ready() { root = (Root)GetNode("/root/root"); attackArea = (Area)GetNode("AttackArea"); move = BLUE_W_TOWER_SPEED * RandAngleV(root.rand); timeFromAttack = 0.0f; } public override void _Process(float delta) { Unit unit = null; var enemies = attackArea.GetOverlappingBodies(); timeFromAttack += delta; if (timeFromAttack >= attackTimeout && enemies != null && enemies.Count > 0) { unit = enemies[root.rand.Next() % enemies.Count] as Unit; if (unit != null) { unit.Damage(root.wizardClockConst[ELEMENTAL_WIZARD] * BLUE_W_TOWER_DAMAGE, -1, -1); } else { GD.Print("Blue wizard tower attack unit error."); } timeFromAttack = 0.0f; } MoveAndSlide(new Vector3(move.x, 0.0f, move.z)); if (GetSlideCount() > 0) { KinematicCollision c = GetSlideCollision(0); move = -move.Rotated(c.Normal, Mathf.Pi); move.y = 0.0f; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AddressBook { class DuplicateRecordException : Exception { public DuplicateRecordException(string message) { Console.WriteLine(message); } } public class InvalidSyntaxException : Exception { public InvalidSyntaxException(string Message) { Console.WriteLine(Message); } } public class NoRecordFoundException : Exception { public NoRecordFoundException(string message) { Console.WriteLine(message); } } public class InvalidPhoneNumber : Exception { public InvalidPhoneNumber(string message) { Console.WriteLine(message); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; namespace NicoLiveAlertTwitterWPF.Info { class AppUpdateCheck { //GitHubのReleaseに追加していくのでGitHubのReleaseのAPIを叩く public async void checkNewVersion() { var url = "https://api.github.com/repos/takusan23/NicoLiveAlertTwitterWPF/releases/latest"; // 指定したサイトのHTMLをストリームで取得する var client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "NicoLiveAlert_Twitter;@takusan_23"); using (var stream = await client.GetAsync(new Uri(url))) { if (stream.StatusCode == System.Net.HttpStatusCode.OK) { var json = JsonConvert.DeserializeObject<JSONClass.GitHubReleaseRootObject>(await stream.Content.ReadAsStringAsync()); var name = json.name; var created = json.created_at; var body = json.body; //ダウンロードリンク var downloadLink = json.assets[0].browser_download_url; //バージョンが違うときは出す if (MainWindow.AppVersion != name) { //ダイアログ表示 var result = MessageBox.Show($"現在の最新バージョンは以下のとおりです。\n{name} {created}\n{body}\nダウンロードする場合は「はい」を押してね。", "更新の確認", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(downloadLink); } } else { var result = MessageBox.Show("このバージョンは最新のバージョンです。", "更新の確認", MessageBoxButton.OK, MessageBoxImage.Information); } } else { var result = MessageBox.Show("更新の確認に問題が発生しました。", "更新の確認", MessageBoxButton.OK, MessageBoxImage.Information); } } } } }
using System.Web; using System.Web.Optimization; namespace LateOS { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { //Bootstrap bundles.Add(new StyleBundle("~/Content/bootstrap").Include( "~/Content/bootstrap/bootstrap.min.css", "~/Content/bootstrap/animate.css", "~/Content/bootstrap/style.css", "~/Content/toastr/toastr.min.css", "~/Content/bootstrap/datatables.min.css", "~/Content/slick/slick-theme.css", "~/Content/slick/slick.css")); //font-awesome bundles.Add(new StyleBundle("~/Content/font-awesome").Include( "~/Content/font-awesome/css/font-awesome.css", new CssRewriteUrlTransform())); //jquery.css bundles.Add(new StyleBundle("~/Content/gritter").Include( "~/Content/gritter/jquery.gritter.css")); //jquery bundles.Add(new ScriptBundle("~/scripts/jquery").Include( "~/scripts/jquery/jquery-2.1.1.js", "~/scripts/jquery-ui/jquery-ui.min.js", "~/scripts/jquery/datatables.min.js")); //bootstrap bundles.Add(new ScriptBundle("~/scripts/bootstrap").Include( "~/scripts/bootstrap/bootstrap.min.js")); //metisMenu bundles.Add(new ScriptBundle("~/scripts/metisMenu").Include( "~/scripts/metisMenu/jquery.metisMenu.js")); //slimscroll bundles.Add(new ScriptBundle("~/scripts/slimscroll").Include( "~/scripts/slimscroll/jquery.slimscroll.min.js")); //inspinia bundles.Add(new ScriptBundle("~/scripts/inspinia").Include( "~/scripts/inspinia.js", "~/scripts/pace/pace.min.js", "~/scripts/slick.min.js")); //más bundles.Add(new ScriptBundle("~/scripts/mas").Include( "~/scripts/jasny/jasny-bootstrap.min.js", "~/scripts/dropzone/dropzone.js", "~/scripts/codemirror/codemirror.js", "~/scripts/dropzone/xml/xml.js")); //adicionales bundles.Add(new StyleBundle("~/Content/mas").Include( "~/Content/codemirror/codemirror.css", "~/Content/dropzone/basic.css", "~/Content/dropzone/dropzone.css", "~/Content/jasny/jasny-bootstrap.min.css")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using FPViewModel; using FPModel.Entity; namespace FPUI { /// <summary> /// Interaction logic for LoginWindow.xaml /// </summary> public partial class LoginWindow { public LoginWindow() { InitializeComponent(); } private void CustomerViewModel_RequestClose(Customer cus) { FPUI.MainWindow main = new FPUI.MainWindow(); main.Resources.Add("customerViewMode", new CustomerViewModel() { Customer = cus }); main.Show(); this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace CallGenericFunction { class Program { static void Main(string[] args) { } public void aa() { //获取当前程序集 Assembly mockAssembly = Assembly.GetExecutingAssembly(); //可以使用LoadFrom(URL)方法加载其他程序集(.dll文件),url是绝对路劲 //Assembly mockAssembly = Assembly.LoadFrom("C:/test/test.dll"); //通过类名获取类,参数是类的全名,命名空间+类名,Myclass是泛型方法中fun<T>()中的T var curType = mockAssembly.GetType("Myspacename.Myclass"); //获取方法所在类的Type,MethodClass是存放fun<T>()方法的类 var MethodType = typeof(MethodClass); //如果是泛型类,如 MyGenericClass<T>{},要这样获得Type var MethodType = typeof(MyGenericClass<>); //获取泛型方法, var GenericMethod = MethodType.GetMethod(MethodName); //如果方法是多态的,即有多个同名方法,可以通过传入Type[]参数来找到方法 //这样可以找到方法fun(string para1,int para2) var GenericMethod = MethodType.GetMethod( MethodName, new Type[] { typeof(string), typeof(int) }); //合并生成最终的函数 MethodInfo curMethod = GenericMethod.MakeGenericMethod(curType); //执行函数 //如果要执行的是静态函数,则第一个参数为null //第二个参数为参数值 //即要调用的函数应该为 static fun<T>(string para1,int para2) curMethod.Invoke(null, new object[] { "第一个参数的值", 1 }); //如果是非静态参数,第一个参数得传MethodClass的实例化对象 //即要调用的函数应该为 fun<T>(string para1,int para2) var classobj = new MethodClass(); curMethod.Invoke(classobj, new object[] { "第一个参数的值", 1 }); } } }
using Microsoft.Data.Entity; using Microsoft.Data.Sqlite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ToDo.Client.Core; using ToDo.Client.Core.Lists; using ToDo.Client.Core.Tasks; namespace ToDo.Client { public partial class Workspace : DbContext { private static Workspace instance; /* public static async Task LoadWorkspaceAsync(string workspacePath, string dbFile) { LoadWorkspace(workspacePath, dbFile); } */ public static void LoadWorkspace(string workspacePath, string dbFile) { try { if (instance == null) { instance = new Workspace(workspacePath, dbFile); instance.Database.EnsureCreated(); } } catch (Exception e) { instance = null; throw; } } public static Workspace Instance { get { return instance; } } public DbSet<Comment> Comments {get; set; } public DbSet<TaskList> Lists { get; set; } public DbSet<TaskItem> Tasks { get; set; } public DbSet<TaskLog> TasksLog { get; set; } private string workspacePath, dbPath; private Workspace(string workspacePath, string dbPath) { //TODO: Change to just one this.workspacePath = workspacePath; this.dbPath = dbPath; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<TaskLog>() .HasKey(x => new { x.TaskID, x.Date }); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = dbPath }; var connectionString = connectionStringBuilder.ToString(); var connection = new SqliteConnection(connectionString); optionsBuilder.UseSqlite(connection); } //TODO: Add Seed(...) and Unique indexes //Not supported in EF7... public void RejectChanges() { foreach (var entry in ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Modified: { //entry.State.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; break; } case EntityState.Deleted: { entry.State = EntityState.Unchanged; break; } case EntityState.Added: { entry.State = EntityState.Detached; break; } } } } public static void Unload() { TasksUpdateTimer.StopTimer(); instance.Dispose(); instance = null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class mainSceneGameControllerScript : MonoBehaviour { public playerJump player; public Camera cam; public Text gameScoreText; public GameObject[] blockPrefabs; private float blockPointer = 0; private float safeSpace = 21; private bool isGameOver = false; // Start is called before the first frame update void Start() { blockPointer = -12; } void generateNewBlock() { int blockIndex = Random.Range(1, blockPrefabs.Length); if(blockPointer < 0) { blockIndex = 0; } GameObject blockObj = Instantiate(blockPrefabs[blockIndex]); blockObj.transform.SetParent(this.transform); Scr_block block = blockObj.GetComponent<Scr_block>(); blockObj.transform.position = new Vector3( blockPointer + block.size/2, 0, 0 ); blockPointer += (block.size); } // Update is called once per frame void Update() { if (player != null) { cam.transform.position = new Vector3( player.transform.position.x, 0, -10 ); gameScoreText.text = "Score : " + Mathf.Floor(player.transform.position.x); if (player.transform.position.x > blockPointer - safeSpace) { generateNewBlock(); } } else { if (!isGameOver) { isGameOver = true; gameScoreText.text += "\n GAME OVER \nPress R to Restart"; } if ( Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } } }
using UnityEngine; using UnityEditor; namespace Assets.Scripts { public class Ammunition : InventoryItem { public Player Player; public readonly int cost = 250; public string Message; public Ammunition() { Message = $"You need {cost} score to buy this"; } public override void OnPickup() { Debug.Log("in ammo pickup function"); if (Player.Score >= cost) { Player.DecreaseScore(cost); if (Inventory.Items[0] != null) { (Inventory.Items[0] as AssaultRifle).PickupAmmunition(); } if (Inventory.Items[1] != null) { (Inventory.Items[1] as Handgun).PickupAmmunition(); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CameraFollowPoppa : MonoBehaviour { //STAY IN CAMERA FIELD, FOLLOW MILKY BOY IN THE BACKGROUND //ANIMATIONS LINKED private void OnEnable() { SceneManager.activeSceneChanged += ChangeSize; } private void Start() { transform.localScale = new Vector3(1.3f, 1.3f, 1.3f); } private void ChangeSize(Scene prevScene, Scene currentScene) { transform.localScale = new Vector3(1, 1, 1); } }