text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class TaiKhoanController : MonoBehaviour { private int demTK = 0; private TaiKhoan tk; public InputField tenNV, tenDNT, passT, tenDNL, passL; public GameObject MBPanel; void Start() { tk = gameObject.GetComponent<TaiKhoan>(); demTK = PlayerPrefs.GetInt("demTK"); } public void DangKy() { demTK++; PlayerPrefs.SetInt("demTK", demTK); ThemTaiKhoan(demTK, tenNV.text, tenDNT.text, passT.text); MBPanel.GetComponent<MessBox>().textThongBao.text = "Successful registration please login again!"; MBPanel.SetActive(true); } private void ThemTaiKhoan(int demTk, string ten, string tenDN, string pass) { PlayerPrefs.SetInt("idTK" + demTK.ToString(), demTK); PlayerPrefs.SetString("ten" + demTK.ToString(), ten); PlayerPrefs.SetString("tenDN" + demTK.ToString(), tenDN); PlayerPrefs.SetString("pass" + demTK.ToString(), pass); } public void DangNhap() { for (int i = 1; i <= demTK; i++) { tk.LayThongTinTaiKhoan(i); if (tk.TenTK == tenDNL.text && tk.Pass == passL.text) { PlayerPrefs.SetInt("idTKCurrent", i); PlayerPrefs.SetString("tenCurrent", tk.TenNV); SceneManager.LoadScene(2); return; } } MBPanel.GetComponent<MessBox>().textThongBao.text = "Wrong username or password!"; MBPanel.SetActive(true); } public void XoaToanBoTaiKhoan() { for (int i = 1; i <= demTK; i++) { PlayerPrefs.SetInt("saved" + "tk" + i.ToString(), 0); PlayerPrefs.SetInt("story" + "tk" + i.ToString(), 0); PlayerPrefs.SetInt("demCV" + "tk" + i.ToString(), 0); PlayerPrefs.SetInt("demPlan" + "tk" + i.ToString(), 0); } demTK = 0; PlayerPrefs.SetInt("demTK", demTK); MBPanel.GetComponent<MessBox>().textThongBao.text = "Deleted! "; MBPanel.SetActive(true); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CameraMovement : MonoBehaviour { [SerializeField] float moveSpeed = 0.5f; [SerializeField] float rotateSpeed = 0.5f; [SerializeField] CharacterController controller; [SerializeField] float maxX; [SerializeField] float minX; [SerializeField] float maxZ; [SerializeField] float minZ; bool withinRoom; Vector3 playerVelocity; private void Start() { controller = gameObject.AddComponent<CharacterController>(); } void Update () { withinRoom = transform.position.x > minX && transform.position.x < maxX && transform.position.z > minZ && transform.position.z < maxZ; Vector3 position = new Vector3(transform.position.x, transform.position.y, transform.position.z); if (withinRoom){ if (Input.GetAxisRaw("Horizontal") != 0) { //Rotate Player transform.Rotate(0, Input.GetAxis("Horizontal"), 0); } } else { if (transform.position.x < minX) { position.x = minX + .1f; } if (transform.position.x > maxX) { position.x = maxX - .1f; } if (transform.position.z < minZ) { position.z = minZ + .1f; } if (transform.position.z > maxZ) { position.z = maxZ - .1f; } transform.position = position; } } }
using Newtonsoft.Json; using System; namespace EddiConfigService.Configurations { /// <summary>Storage of credentials for a single Elite: Dangerous user to access EDSM</summary> [JsonObject(MemberSerialization.OptOut), RelativePath(@"\edsm.json")] public class StarMapConfiguration : Config { [JsonProperty("apiKey")] public string apiKey { get; set; } [JsonProperty("commanderName")] public string commanderName { get; set; } [JsonProperty("lastSync")] public DateTime lastFlightLogSync { get; set; } = DateTime.MinValue; [JsonProperty("lastJournalSync")] public DateTime lastJournalSync { get; set; } = DateTime.MinValue; } }
using MISA.Business.Interface; using MISA.Common.Models; using MISA.DataAccess.Interface; using System; using System.Collections.Generic; using System.Text; namespace MISA.Business.Service { public class EmployeeService : BaseService<Employee>,IEmployeeService { IEmployeeRepository _employeeRepository; public EmployeeService(IEmployeeRepository employeeRepository):base(employeeRepository) { _employeeRepository = employeeRepository; } public bool CheckEmployeeByCode(string employeeCode) { return _employeeRepository.CheckEmployeeByCode(employeeCode); } protected override bool Validate(Employee entity) { var isValid = true; // Check trùng mã: var isValidExitsCode = CheckEmployeeByCode(entity.EmployeeCode); if (isValidExitsCode) { isValid = false; validateErrorResponseMsg.Add("Mã bị trùng 1"); } return isValid; } } }
using mec.Jobs; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mec.Agent.Notice { class Program { static void Main(string[] args) { Console.WriteLine("Agent Start"); NoticeAgent agent = new NoticeAgent(); agent.Execute(); Console.ReadLine(); } } }
using BassClefStudio.GameModel.Geometry.Transforms; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace BassClefStudio.GameModel.Tests { [TestClass] public class CameraTests { [TestMethod] public void TestIdentity() { TransformGroup testCam = TransformGroup.Identity; var testPt = new Vector2(100, -400); Assert.AreEqual(testPt, testCam.TransformPoint(testPt), "The ViewCamera.Identity camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestIdentityCenter() { TransformGroup testCam = TransformGroup.IdentityFlip; var testPt = new Vector2(100, -400); Assert.AreEqual(Scaling.FlipConstant * testPt, testCam.TransformPoint(testPt), "The ViewCamera.IdentityCenter camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestScale() { float scale = 2; TransformGroup testCam = new TransformGroup(scale, Vector2.Zero); var testPt = new Vector2(100, -400); Assert.AreEqual(scale * testPt, testCam.TransformPoint(testPt), "The 2x ViewCamera camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestTranslate() { Vector2 translate = new Vector2(-100); TransformGroup testCam = new TransformGroup(1, translate); var testPt = new Vector2(100, -400); Assert.AreEqual(testPt - translate, testCam.TransformPoint(testPt), "The translate ViewCamera camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestTransformOrder() { Vector2 translate = new Vector2(-100); float scale = 2; TransformGroup testCam = new TransformGroup(scale, translate); var testPt = new Vector2(100, -400); Assert.AreEqual((testPt - translate) * scale, testCam.TransformPoint(testPt), "The translate/2x ViewCamera camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestViewFit() { Vector2 viewSize = new Vector2(100); Vector2 drawSize = new Vector2(200); TransformGroup testCam = new TransformGroup(viewSize, drawSize, ZoomType.FitAll); Assert.AreEqual(0.5, testCam.Scale, "FitAll ViewCamera has incorrect scale to fit draw-space 2x view-space."); Vector2 newDrawSize = new Vector2(50, 200); testCam = new TransformGroup(viewSize, newDrawSize, ZoomType.FitAll); Assert.AreEqual(0.5, testCam.Scale, "FitAll ViewCamera has incorrect scale to fit rectangular draw-space."); } [TestMethod] public void TestViewFill() { Vector2 viewSize = new Vector2(100); Vector2 drawSize = new Vector2(200); TransformGroup testCam = new TransformGroup(viewSize, drawSize, ZoomType.FillView); Assert.AreEqual(0.5, testCam.Scale, "FillView ViewCamera has incorrect scale to fill draw-space 2x view-space."); Vector2 newDrawSize = new Vector2(50, 200); testCam = new TransformGroup(viewSize, newDrawSize, ZoomType.FillView); Assert.AreEqual(2, testCam.Scale, "FillView ViewCamera has incorrect scale to fill with rectangular draw-space."); } [TestMethod] public void TestCombineCamera() { float[] scaling = new float[] { 2, 2 }; Vector2[] translation = new Vector2[] { new Vector2(1, 1), new Vector2(1, 1) }; TransformGroup viewCam = new TransformGroup(2, new Vector2(1, 1)); TransformGroup drawCam = new TransformGroup(2, new Vector2(1, 1)); TransformGroup testCam = drawCam + viewCam; var testPt = new Vector2(1, -1); Vector2 manualCombine = (((testPt - translation[0]) * scaling[0]) - translation[1]) * scaling[1]; Assert.AreEqual(manualCombine, testCam.TransformPoint(testPt), "The combined ViewCamera camera failed to correctly transform the test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The combined ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } [TestMethod] public void TestCombineCameraFlip() { float[] scaling = new float[] { 2, 2 }; Vector2[] translation = new Vector2[] { new Vector2(1, 1), new Vector2(1, 1) }; TransformGroup viewCam = new TransformGroup(2, new Vector2(1, 1)); TransformGroup drawCam = new TransformGroup(2, new Vector2(1, 1)); TransformGroup testCam = drawCam + TransformGroup.IdentityFlip + viewCam; var testPt = new Vector2(1, -1); Vector2 manualCombine = (((testPt - translation[0]) * scaling[0] * Scaling.FlipConstant) - translation[1]) * scaling[1]; Assert.AreEqual(manualCombine, testCam.TransformPoint(testPt), "The combined ViewCamera camera failed to correctly transform the centered test point."); Assert.AreEqual(testPt, testCam.RetrievePoint(testCam.TransformPoint(testPt)), "The combined ViewCamera did not correctly reverse the transformations applied to the drawing-space."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project_Entity { public class EntityBase { public EntityBase() { IsActive = false; } public int ID { get; set; } public DateTime CreatedDate { get; set; } public DateTime? UpdatedDate { get; set; } public DateTime? DeletedDate { get; set; } public bool IsActive { get; set; } public bool? IsDelete { get; set; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class CardCombo : MonoBehaviour { public GameObject Board = null; public GameObject Hand = null; public GameObject MonsterArea = null; public GameObject PopUp = null; private GameObject board; private GameObject hand; private GameObject monsterArea; public enum CardType { RED, BLUE, GREEN } //string comboText; public int redCount = 0; public int greenCount = 0; public int blueCount = 0; public void setCombo() { this.board = Board; this.hand = Hand; this.monsterArea = MonsterArea; //this.discover = PopUp; } public void comboCheck () { redCount = 0; greenCount = 0; blueCount = 0; string temp; for (int i = 0; i< Board.transform.childCount; i++) { temp = Board.transform.GetChild(i).GetComponent<CardStats>().getName(); Debug.Log("current card: " + temp); if (temp == "BLUE") { blueCount++; Debug.Log("BLUE card: " + blueCount); } else if (temp == "RED") { redCount++; Debug.Log("RED card: " + redCount); } else if (temp == "GREEN") { greenCount++; Debug.Log("GREEN card: " + greenCount); } } } public string getComboName() { //COMBO //BB draw 3 card instancely if (blueCount == 2) { return "Draw 3 Cards"; } //RR deal 3 dmg instancely else if (redCount == 2) { return "Deal 4 Damage"; } //GG convert all left over GREEN card in hand to w/e Color you want, right now just to RED else if (greenCount == 2) { return "Convert GREEN In Hand to RED or BLUE"; } //GB All BLUE TO GREEN else if (greenCount == 1 && blueCount == 1) { return "Convert BLUE In Hand to GREEN or RED"; } //GR All RED TO GREEN else if (greenCount == 1 && redCount == 1) { return "Convert RED In Hand to GREEN or BLUE"; } //BR else if (blueCount == 1 && redCount == 1) { return "Deal 2 Damage, Draw 1 Card"; } else { return "ERRROR!!"; } } public void comboAction() { //COMBO //BB draw 3 card instancely if (blueCount == 2) { hand.GetComponent<DrawCard>().getCard(3, false); } //RR deal 3 dmg instancely else if (redCount == 2) { for (int i = 0; i < MonsterArea.transform.childCount; i++) { monsterArea.transform.GetChild(i).GetComponent<MonsterStats>().minusHealth(4); monsterArea.transform.GetChild(i).GetComponent<CardTextModifier>().updateCardData(); } } //GG convert all left over GREEN card in hand to w/e Color you want, right now just to RED else if (greenCount == 2) { PopUp.GetComponent<DiscoverCard>().chooseCard("BLUE", "RED"); //cardConversion("GREEN", "RED"); } //GB All BLUE TO GREEN else if (greenCount == 1 && blueCount == 1) { PopUp.GetComponent<DiscoverCard>().chooseCard("RED", "GREEN"); //cardConversion("BLUE", "GREEN"); } //GR All RED TO GREEN else if (greenCount == 1 && redCount == 1) { PopUp.GetComponent<DiscoverCard>().chooseCard("BLUE", "GREEN"); //cardConversion("RED", "GREEN"); } //BR else if (blueCount == 1 && redCount == 1) { for (int i = 0; i < MonsterArea.transform.childCount; i++) { monsterArea.transform.GetChild(i).GetComponent<MonsterStats>().minusHealth(2); monsterArea.transform.GetChild(i).GetComponent<CardTextModifier>().updateCardData(); hand.GetComponent<DrawCard>().getCard(1, false); } } } public void cardConversion(string currentCard, string newCard) { int currentType = 0; for (int i = 0; i < hand.transform.childCount; i++) { if (hand.transform.GetChild(i).GetComponent<CardStats>().getName() == currentCard) { currentType++; } } for (int i = 0; i < hand.transform.childCount; i++) { if (hand.transform.GetChild(i).GetComponent<CardStats>().getName() == currentCard) { Destroy(hand.transform.GetChild(i).gameObject); } } for (int i = 0; i < currentType; i++) { hand.GetComponent<DrawCard>().getSpecificCard(newCard); } } }
using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V7.App; using Android.Widget; namespace OdborkyApp.Activities { [Activity(Theme = "@style/MainTheme", MainLauncher = true, NoHistory = true)] public class WelcomeActivity : AppCompatActivity { private const int SyncRequestCode = 4; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); bool firstTime; using (var prefs = GetSharedPreferences("ChallengeApp", FileCreationMode.Private)) { firstTime = prefs.GetBoolean("firstTime", true); } if (firstTime) { SetContentView(Resource.Layout.WelcomeLayout); var btn = FindViewById<Button>(Resource.Id.welcomeBtn); btn.Click += (o, e) => { using (var prefs = GetSharedPreferences("ChallengeApp", FileCreationMode.Private)) using (var prefsEditor = prefs.Edit()) { prefsEditor.PutBoolean("firstTime", false); prefsEditor.Commit(); StartActivity(typeof(SyncDataActivity)); Finish(); } }; } else { StartActivity(typeof(SyncDataActivity)); Finish(); } } protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok && requestCode == SyncRequestCode) { StartActivity(typeof(HomeActivity)); Finish(); } } } }
using Common.Business; using Common.Presentation.Controls; using SessionSettings; using Softgroup.NetResize; using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Common.Presentation { /// <summary> /// Base form used for detached tabs. /// </summary> public partial class DetachedForm : SkinnableFormBase, IDetachable { #region Private Fields private bool mCaptured = false; private bool mClosing = false; private bool mDocking = false; private Point mDragOffset = Point.Empty; private int mInstance = 0; private NetResize mNetResize = null; private new ParameterStruct mParameters = new ParameterStruct(); private DetachableTabControl mTabControl = null; private int mTabId = -1; private DetachableTabPage mTabPage = null; #endregion #region Delegates /// <summary> /// Delegate for reattaching a detached instance. /// </summary> /// <param name="index">The instance to reattach.</param> public delegate void AttachRequestEventHandler(int index); #endregion #region Events /// <summary> /// Event handler for reattaching a detached instance. /// </summary> public event AttachRequestEventHandler Attached; #endregion #region Constructors /// <summary> /// Creates a new default instance of DetachedForm. /// </summary> public DetachedForm() : base() { InitializeComponent(); } #endregion #region Public Properties /// <summary> /// Gets or sets the name of the control. /// </summary> public string ControlName { get; set; } /// <summary> /// Gets or sets the instance number of the form. /// </summary> public int Instance { get { return mInstance; } set { mInstance = value; } } #endregion #region Public Methods /// <summary> /// Closes the current instance of the detached form. /// </summary> public void CloseForm() { mClosing = true; Close(); } /// <summary> /// Loads the selected page onto the form. /// </summary> /// <param name="page">The page being loaded.</param> public void Initialize(DetachableTabPage page) { InitializeForm(page, mInstance); } /// <summary> /// Sets the instance number in the form's title bar. /// </summary> /// <param name="text">The text to set.</param> public void SetInstanceInTitle(string text) { SetTitle(text); Text = text; } #endregion #region Protected Methods /// <summary> /// Sets up the form with the requested data. /// </summary> /// <param name="page">The page to display on the form.</param> /// <param name="instance">The current instance of the form.</param> protected virtual void InitializeForm(DetachableTabPage page, int instance) { if (page.TabParent == null) return; mTabPage = page; mTabControl = (DetachableTabControl)page.TabParent; page.Tag = this; mTabId = mTabControl.TabPages.IndexOf(page); this.Size = ((Form)mTabControl.Parent).Size; Location = mTabControl.PointToScreen(new Point(page.Left, mTabControl.PointToClient(Cursor.Position).Y / 2)); ShowInTaskbar = true; mParameters = Settings.User.ToParameterStruct(); mInstance = instance; if (!DetachableTabControl.IsDisposed) this.DetachableTabControl.TabPages.Clear(); else this.DetachableTabControl = new DetachableTabControl(); UndockFromTab(); mDragOffset = page.PointToScreen(Cursor.Position); mDragOffset.X -= Location.X; mDragOffset.Y -= Location.Y; if (!this.IsDisposed && !titleBar.IsDisposed) { titleBar.SetOwner(this); titleBar.RefreshSize(); } } /// <summary> /// Sets specified properties of the child control on a detached instance. /// </summary> protected virtual void SetChildProperties() { } /// <summary> /// Processes messages sent to the Windows message queue. /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { if (m.Msg == SafeNativeMethods.WM_MOVING) { SafeNativeMethods.RECT rc = (SafeNativeMethods.RECT)m.GetLParam(typeof(SafeNativeMethods.RECT)); Point pt = mTabControl.PointToClient(Cursor.Position); Rectangle pageRect = mTabControl.DisplayRectangle; Rectangle tabRect = Rectangle.Empty; tabRect.Size = new Size(mTabControl.Width, pageRect.Top); if (tabRect.Contains(pt)) DockToTab(); else UndockFromTab(); titleBar.RefreshSize(); } base.WndProc(ref m); switch (m.Msg) { case (int)SafeNativeMethods.WM_NCLBUTTONDBLCLK: Close(); break; case (int)SafeNativeMethods.WM_EXITSIZEMOVE: if (!Visible) Close(); break; case (int)SafeNativeMethods.WM_MOUSEMOVE: if (m.WParam.ToInt32() == 1) { if (!mCaptured) { Point pt = mTabControl.PointToScreen(Cursor.Position); Point newPos = new Point(pt.X - mDragOffset.X, pt.Y - mDragOffset.Y); Location = newPos; } SafeNativeMethods.RECT rc = new SafeNativeMethods.RECT(Bounds); IntPtr lParam = IntPtr.Zero; try { lParam = Marshal.AllocHGlobal(Marshal.SizeOf(rc)); SafeNativeMethods.SendMessage(Handle, (uint)SafeNativeMethods.WM_MOVING, 0, lParam.ToInt32()); } finally { Marshal.FreeHGlobal(lParam); } } break; case (int)SafeNativeMethods.WM_SETCURSOR: mCaptured = true; break; default: break; } } #endregion #region Private Methods /// <summary> /// Allows hotkeys to be displayed on the UI. /// </summary> private void ClearHideAccel() { IntPtr wParam = (IntPtr)((SafeNativeMethods.UISF_HIDEACCEL << 16) | SafeNativeMethods.UIS_CLEAR); SafeNativeMethods.SendMessage(Handle, SafeNativeMethods.WM_UPDATEUISTATE, wParam, IntPtr.Zero); } /// <summary> /// Handles the DockRequested event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Control_DockRequested(object sender, EventArgs e) { DockToTab(); } /// <summary> /// Handles requests to close this form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DetachedForm_FormClosing(object sender, FormClosingEventArgs e) { if (mNetResize != null) { mNetResize.BeforeControlResize -= NetResize_BeforeControlResize; mNetResize.Dispose(); } //Don't prompt the user if we are redocking the tab or closing the form. if (mDocking || mClosing) return; //If the user doesn't want to close the module, cancel the request. if (MessageBox.Show("Are you sure you want to close this window?", "Confirm Close", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.No) e.Cancel = true; else DockToTab(); } /// <summary> /// Handles the Form.Load event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DetachedForm_Load(object sender, EventArgs e) { Softgroup.NetResize.License.LicenseName = Constants.LicenseName; Softgroup.NetResize.License.LicenseUser = Constants.LicenseUser; Softgroup.NetResize.License.LicenseKey = Constants.LicenseKey; } /// <summary> /// Handles the Form.Paint event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DetachedForm_Paint(object sender, PaintEventArgs e) { if (HideAccelIsSet()) ClearHideAccel(); } /// <summary> /// Handles the Form.Shown event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DetachedForm_Shown(object sender, EventArgs e) { SetChildProperties(); mNetResize = new NetResize(this); mNetResize.Enabled = false; mNetResize.BeforeControlResize += NetResize_BeforeControlResize; mNetResize.DataGridViewAutoResize = false; mNetResize.DataGridViewAutoResizeCols = DataGridViewAutoSizeColumnsMode.None; mNetResize.DataGridViewAutoResizeHeaders = false; mNetResize.DataGridViewAutoResizeRows = DataGridViewAutoSizeRowsMode.None; mNetResize.Enabled = true; } /// <summary> /// Reattaches the current tab to the main control. /// </summary> private void DockToTab() { if (!mTabControl.TabPages.Contains(DetachableTabControl.TabPages[0])) { DetachableTabPage page = new DetachableTabPage(); page.Detached = false; //This copies the UserControl from this instance of the form back to the main form. It preserves //any data that has been loaded. Changing the parent of any control removes it from the source control //and puts it on the new control. foreach (Control c in DetachableTabControl.TabPages[0].Controls) { c.Location = new Point(0, 0); c.Dock = DockStyle.Fill; page.Parameters = mParameters; page.Text = DetachableTabControl.TabPages[0].Text; page.Instance = mTabId + 1; page.Controls.Add(c); if (c is ICanCreateTab) { ICanCreateTab icc = c as ICanCreateTab; icc.DockRequested -= Control_DockRequested; icc.Detached = false; icc.Instance = mInstance; icc.ParentTab = page; icc.Parent = mTabControl.Parent; } c.AllowDrop = true; } mDocking = true; mTabControl.DetachedInstances.Remove(mInstance); mTabControl.TabPages.Insert(mTabId, page); mTabControl.SelectedIndex = mTabId; page.TabParent = mTabControl; mTabControl.RenumberTabs(); mTabControl.Capture = true; if (Attached != null) Attached(mTabId); Close(); } } /// <summary> /// Determines whether the hotkeys are being displayed on the UI. /// </summary> /// <returns>Returns true if the hotkeys are hidden; otherwise false.</returns> private bool HideAccelIsSet() { IntPtr result = SafeNativeMethods.SendMessage(Handle, SafeNativeMethods.WM_QUERYUISTATE, IntPtr.Zero, IntPtr.Zero); return (result.ToInt32() & SafeNativeMethods.UISF_HIDEACCEL) != 0; } /// <summary> /// Creates the form and its child controls. /// </summary> private new void InitializeComponent() { this.DetachableTabControl.SuspendLayout(); this.SuspendLayout(); // // titleBar // this.titleBar.CloseVisible = true; this.titleBar.HelpVisible = true; this.titleBar.MinimizeVisible = true; this.titleBar.MinimumSize = new System.Drawing.Size(0, 0); this.titleBar.RestoreVisible = true; this.titleBar.Size = new System.Drawing.Size(1284, 44); // // DetachableTabControl // this.DetachableTabControl.Location = new System.Drawing.Point(0, 44); this.DetachableTabControl.Size = new System.Drawing.Size(1284, 984); // // detachPage // this.detachPage.Location = new System.Drawing.Point(4, 22); this.detachPage.Size = new System.Drawing.Size(1276, 958); // // DetachedForm // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(1284, 1028); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(66)))), ((int)(((byte)(135))))); this.Name = "DetachedForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DetachedForm_FormClosing); this.Load += new System.EventHandler(this.DetachedForm_Load); this.Shown += new System.EventHandler(this.DetachedForm_Shown); this.Paint += new System.Windows.Forms.PaintEventHandler(this.DetachedForm_Paint); this.DetachableTabControl.ResumeLayout(false); this.ResumeLayout(false); } /// <summary> /// Prevents resizing of grid fonts on the child control. /// </summary> /// <param name="oControl">The control to check.</param> /// <param name="bCtrlResize">Flag indicating whether to resize the control.</param> /// <param name="bFontResize">Flag indicating whether to resize the control's font.</param> private void NetResize_BeforeControlResize(Control oControl, ref bool bCtrlResize, ref bool bFontResize) { if (oControl is C1.Win.C1FlexGrid.C1FlexGrid || oControl is EnhancedFlexGrid) bFontResize = false; } /// <summary> /// Detaches the current tab from the main control. /// </summary> private void UndockFromTab() { if (Visible || IsDisposed) return; TabPage page = new TabPage(); foreach (Control c in mTabPage.Controls) { Type t = c.GetType(); ICanCreateTab createTab = null; if (c is ICanCreateTab) createTab = c as ICanCreateTab; object o = Activator.CreateInstance(t); Control target = (Control)o; if (target is ICanCreateTab) { //Enable the event handler for docking without dragging. ICanCreateTab icc = target as ICanCreateTab; icc.DockRequested += Control_DockRequested; icc.Detached = true; icc.DataSource = createTab.DataSource; } //Set needed properties. PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(target); foreach (PropertyDescriptor pd in pdc) { switch (pd.Name) { case "ClientPresentation": pd.SetValue(target, createTab.ClientPresentation); break; case "ControlName": pd.SetValue(target, createTab.ControlName); break; case "Instance": pd.SetValue(target, mInstance); break; case "Parent": pd.SetValue(target, createTab.Parent); break; case "ParentTab": pd.SetValue(target, mTabPage); break; } } target.Location = new Point(0, 0); target.Dock = DockStyle.Fill; target.Visible = true; page.Text = mTabPage.Text; page.Controls.Add(target); } this.DetachableTabControl.TabPages.Add(page); mTabControl.TabPages.Remove(mTabPage); mTabControl.DetachedInstances.Add(mInstance); ApplySkin(mParameters); SetInstanceInTitle(this.DetachableTabControl.ParentName + " - " + mInstance.ToString()); Location = new Point(((Form)mTabControl.Parent).Location.X + 100, ((Form)mTabControl.Parent).Location.Y + 200); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; /** * @brief Base abstract class for all states, objects that hold onto complex functionality defined solely by actions and transitions. * */ public abstract class IState : ScriptableObject { public Color debugColor = Color.gray; // Color to represent the state for debug purposes (gray by default) public IAction[] m_actions; public ITransition[] m_transitions; public virtual void Initialise(StateManager a_controller) { } public virtual void Shutdown(StateManager a_controller) { } public void UpdateState(StateManager a_controller) { // Check transitions last to avoid acting after already transitioning ExecuteActions(a_controller); CheckTransitions(a_controller); } public virtual void ExecuteActions(StateManager a_controller) { if (m_actions != null) { // Perform all assigned actions foreach (var action in m_actions) { action.Act(a_controller); } } } public virtual void CheckTransitions(StateManager a_controller) { if (m_transitions != null) { // Loop through and decide whether a transition should take place foreach (var tr in m_transitions) { // Transition conditions met, set new active state if (tr.Decide(a_controller) == true) a_controller.SetState(a_controller.GetState(tr.transitionState)); } } } }
using AlintaEnergy.ViewModels; using System.Collections.Generic; namespace AlintaEnergy.Application.Services { public interface IAppService { void AddCustomer(CustomerVM value); void DeleteCustomer(int id); CustomerVM GetCustomerById(int id); List<CustomerVM> GetCustomersSearch(string search); List<CustomerVM> GetCustomers(); void UpdateCustomer(CustomerVM value); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace otoKiralama { public partial class agekle : Form { int sayi = 0; int arac_no = 0; int garaj_no = 0; string arac_adi = ""; string garaj_adi = ""; string gun_adii = ""; int[] gunu_no; MySqlConnection baglanti = new MySqlConnection("server = localhost;database=otoKiralama;uid=root;pwd=emre"); public agekle() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { string garaj_goster = "select * from araclar"; MySqlDataAdapter adaptor = new MySqlDataAdapter(garaj_goster, baglanti); DataTable tablo = new DataTable(); baglanti.Open(); adaptor.Fill(tablo); dataGridView2.DataSource = tablo; baglanti.Close(); } private void button3_Click(object sender, EventArgs e) { string seans_goster = "select * from garaj"; MySqlDataAdapter adaptor = new MySqlDataAdapter(seans_goster, baglanti); DataTable tablo = new DataTable(); baglanti.Open(); adaptor.Fill(tablo); dataGridView3.DataSource = tablo; baglanti.Close(); } private void button1_Click(object sender, EventArgs e) { string seans_goster = "select * from gun"; MySqlDataAdapter adaptor = new MySqlDataAdapter(seans_goster, baglanti); DataTable tablo = new DataTable(); baglanti.Open(); adaptor.Fill(tablo); dataGridView1.DataSource = tablo; baglanti.Close(); } private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) { //<> for (int i = 0; i < dataGridView2.Rows.Count; i++) if (dataGridView2.Rows[i].DefaultCellStyle.BackColor == Color.Yellow) dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.White; dataGridView2.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; arac_no = Convert.ToInt32(dataGridView2.Rows[e.RowIndex].Cells[0].Value); } private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e) { for (int i = 0; i < dataGridView3.Rows.Count; i++) if (dataGridView3.Rows[i].DefaultCellStyle.BackColor == Color.Yellow) dataGridView3.Rows[i].DefaultCellStyle.BackColor = Color.White; dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; garaj_no = Convert.ToInt32(dataGridView3.Rows[e.RowIndex].Cells[0].Value); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor == Color.Red) dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White; else dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; gunu_no = new int[100]; for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor == Color.Red) gunu_no[i] = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value); sayi = dataGridView1.Rows.Count; } } private void button4_Click(object sender, EventArgs e) { for (int i = 0; i < sayi; i++) if (gunu_no[i] > 0){ //4 tane kaydediyor! SORUN VAR string toplamEkle = "insert into toplam(a_id,garaj_no,g_id) values(@a_id,@garaj_no,@g_id)"; MySqlCommand komut = new MySqlCommand(toplamEkle, baglanti); komut.Parameters.AddWithValue("@a_id", arac_no); komut.Parameters.AddWithValue("@garaj_no", garaj_no); komut.Parameters.AddWithValue("@g_id", gunu_no[i]); baglanti.Open(); komut.ExecuteNonQuery(); baglanti.Close(); button5_Click(sender, e); } Array.Clear(gunu_no, 0, 100); } private void button5_Click(object sender, EventArgs e) { string arac = "select a_ad,garaj_ad,gunu from araclar,garaj,gun,toplam where araclar.a_id = toplam.a_id and garaj.garaj_no = toplam.garaj_no and gun.g_id = gun.g_id;"; MySqlDataAdapter adaptor = new MySqlDataAdapter(arac, baglanti); DataTable tabloGoster = new DataTable(); adaptor.Fill(tabloGoster); baglanti.Open(); dataGridView4.DataSource = tabloGoster; baglanti.Close(); } private void button6_Click(object sender, EventArgs e) { int toplamSayi = 0; string topm = "select toplam_id from toplam,araclar,garaj,gun where toplam.a_id = araclar.a_id and garaj.garaj_no = toplam.garaj_no and toplam.g_id =gun.g_id and a_ad ='" + arac_adi + "' and garaj_ad = '" + garaj_adi + "' and gunu ='" + gun_adii + "'"; baglanti.Open(); MySqlCommand komut = new MySqlCommand(topm, baglanti); MySqlDataReader okuma = komut.ExecuteReader(); while (okuma.Read()) { toplamSayi = Convert.ToInt32(okuma[0]); } baglanti.Close(); string toplamSill = "delete from toplam where toplam_id = " + toplamSayi; baglanti.Open(); MySqlCommand komutt = new MySqlCommand(toplamSill, baglanti); komutt.ExecuteNonQuery(); baglanti.Close(); button5_Click(sender, e); } private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e) { for (int i = 0; i < dataGridView4.Rows.Count; i++) { if (dataGridView4.Rows[i].DefaultCellStyle.BackColor == Color.Red) dataGridView4.Rows[i].DefaultCellStyle.BackColor = Color.White; } dataGridView4.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; arac_adi = dataGridView4.Rows[e.RowIndex].Cells[0].Value.ToString(); garaj_adi = dataGridView4.Rows[e.RowIndex].Cells[1].Value.ToString(); gun_adii = dataGridView4.Rows[e.RowIndex].Cells[2].Value.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public enum InventoryState { Browse, UseItem, Combine, Closed } [Serializable] public class Inventory { public List<InventoryItem> items; [NonSerialized] public InventoryState myState = InventoryState.Closed; public Inventory () { // fresh inventory items = new List<InventoryItem> (); } // Adding Item public void AddItem(InventoryItem item) { // if there's already an item with the same name, return foreach (InventoryItem inventoryItem in items) { if (inventoryItem.fileName == item.fileName) { Debug.LogError ("There's already an item with the same name"); return; } } items.Add (item); item.Initialize (); EventsHandler.Invoke_cb_inventoryChanged (this); EventsHandler.Invoke_cb_itemAddedToInventory (item); GameManager.instance.SaveData (); } // Removing Item public void RemoveItem(InventoryItem item) { if (items.Contains (item)) { items.Remove (item); } EventsHandler.Invoke_cb_inventoryChanged (this); GameManager.instance.SaveData (); } // Removing Item public void RemoveItem(string itemName) { for (int i = items.Count - 1; i >= 0; i--) { if (items[i].fileName == itemName) { items.RemoveAt (i); } } EventsHandler.Invoke_cb_inventoryChanged (this); GameManager.instance.SaveData (); } }
using System.ComponentModel; namespace ClipModels { public class CameraModel { public int ID { get; set; } [DisplayName("Model Name")] public string Name { get; set; } public virtual CameraBrand CameraBrand { get; set; } public int CameraBrandId { get; set; } public CameraModel() { Name = string.Empty; CameraBrandId = 0; } public CameraModel(CameraModel c) { Name = c.Name; CameraBrandId = c.CameraBrandId; } public void CopyData(CameraModel c) { Name = c.Name; CameraBrandId = c.CameraBrandId; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { public class SumStoreInventory { public int Quantity { get; set; } public decimal Amount { get; set; } public decimal SaleAmount { get; set; } public int TotalCount { get; set; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Plotliner.Entities { class BoxConnection { TextBox box1; TextBox box2; Texture2D rect; public BoxConnection(TextBox one, TextBox two, Game1 gameRef) { box1 = one; box2 = two; rect = new Texture2D(gameRef.GraphicsDevice, 1, 1); rect.SetData(new[] { Color.White }); } public void draw(SpriteBatch spriteBatch) { spriteBatch.Draw(rect, box1.Position.ToVector2() + (box1.Size.ToVector2() / 2), null, Color.Black, (float)Math.Atan2(box2.Position.Y - box1.Position.Y, box2.Position.X - box1.Position.X), new Vector2(0f, 0f), new Vector2(Vector2.Distance(box1.Position.ToVector2(), box2.Position.ToVector2()), 3f), SpriteEffects.None, 0f); } public TextBox Box1 { get { return box1; } } public TextBox Box2 { get { return box2; } } } }
using ServiceCenter.ViewModel.Repair; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; namespace ServiceCenter.View.Repair { public partial class PageEquipment : Page { public PageEquipment() { InitializeComponent(); } private void btnEscape_Click(object sender, RoutedEventArgs e) { if (NavigationService.CanGoBack) NavigationService.GoBack(); } private void tbEquipmentSearch_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Enter) { if (DataContext == null) return; var context = DataContext as PageEquipmentViewModel; context.SearchCommand.Execute(new object()); } } private void ListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (DataContext == null) return; var context = DataContext as PageEquipmentViewModel; context.SendModelCommand.Execute(new object()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ShuJuJieGouStudy { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Array<String> arr = new Array<String>(5); for (int i = 0; i < 10; i++) { arr.AddLast(i.ToString()+"个人"); Console.WriteLine(arr.ToString()); } arr.Add(1, 100.ToString()+"个人"); Console.WriteLine(arr.ToString()); for (int i = 0; i < 11; i++) { arr.RemoveLast(); Console.WriteLine(arr.ToString()); } } } }
#region Using directives using System; using System.Collections; using System.Data; using UFSoft.UBF.UI.MD.Runtime; using UFSoft.UBF.UI.MD.Runtime.Implement; #endregion namespace VouchersUIModel { public partial class VouchersUIModelModel { //初始化UIMODEL之后的方法 public override void AfterInitModel() { //this.Views[0].Fields[0].DefaultValue = thsi.co this.Vouchers.FieldContainUsed.DefaultValue = true; //this.Vouchers_VouchersLine.FieldEffectiveDate.DefaultValue = new DateTime(2000, 1, 1); this.Vouchers_VouchersLine.FieldEffectiveDate.DefaultValue = UFIDA.U9.UI.PDHelper.PDContext.Current.LoginDate; this.Vouchers_VouchersLine.FieldDisabledDate.DefaultValue = new DateTime(9999, 12, 31); this.Vouchers_VouchersLine.FieldIsEffectived.DefaultValue = true; } //UIModel提交保存之前的校验操作. public override void OnValidate() { base.OnValidate() ; OnValidate_DefualtImpl(); //your coustom code ... } } }
using System; using System.IO; namespace DbfDataReader { public class DbfValueNull : IDbfValue { public DbfValueNull(int length) { Length = length; } public int Length { get; } public object GetValue() { return null; } public T GetValue<T>() { throw new NotImplementedException(); } public void Read(BinaryReader binaryReader) { // binaryReader.ReadBytes(Length); binaryReader.ReadByte(); } public override string ToString() { return string.Empty; } } }
using System.Text; using System.Threading; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Direct { public class DirectExample { private readonly IModel channel; public DirectExample() { var factory = new ConnectionFactory() { HostName = "localhost", UserName = "rabbitmq", Password = "rabbitmq", VirtualHost = "/" }; var connection = factory.CreateConnection(); channel = connection.CreateModel(); } public void RunConsumerInfo() { Task.Run(() => { channel.ExchangeDeclare(exchange: "direct-01", type: ExchangeType.Direct); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queueName, "direct-01", "info"); var consumer = new EventingBasicConsumer(channel); consumer.Received += ((model, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); System.Console.WriteLine($"info-{message} ({Thread.CurrentThread.ManagedThreadId})"); for (int i = 0; i < int.MaxValue; i++) { var t = message; } channel.BasicAck(ea.DeliveryTag, false); }); channel.BasicConsume(queueName, false, consumer); while (true) { Thread.Sleep(10); } }); } public void RunConsumerWarning() { Task.Run(() => { channel.ExchangeDeclare(exchange: "direct-01", type: ExchangeType.Direct); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queueName, "direct-01", "warning"); channel.BasicQos(0, 2, true); var consumer = new EventingBasicConsumer(channel); consumer.Received += ((model, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); System.Console.WriteLine($"warning-{message} ({Thread.CurrentThread.ManagedThreadId})"); for (int i = 0; i < int.MaxValue; i++) { var t = message; } channel.BasicAck(ea.DeliveryTag, false); }); channel.BasicConsume(queueName, false, consumer); while (true) { Thread.Sleep(10); } }); } public void RunConsumerError() { Task.Run(() => { channel.ExchangeDeclare(exchange: "direct-01", type: ExchangeType.Direct); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queueName, "direct-01", "error"); var consumer = new EventingBasicConsumer(channel); consumer.Received += ((model, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); System.Console.WriteLine($"error-{message} ({Thread.CurrentThread.ManagedThreadId})"); for (int i = 0; i < int.MaxValue; i++) { var t = message; } channel.BasicAck(ea.DeliveryTag, false); }); channel.BasicConsume(queueName, false, consumer); while (true) { Thread.Sleep(10); } }); } public void RunConsumerAll() { Task.Run(() => { channel.ExchangeDeclare(exchange: "direct-01", type: ExchangeType.Direct); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queueName, "direct-01", "info"); channel.QueueBind(queueName, "direct-01", "warning"); channel.QueueBind(queueName, "direct-01", "error"); var consumer = new EventingBasicConsumer(channel); consumer.Received += ((model, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); System.Console.WriteLine($"ALL-{message} ({Thread.CurrentThread.ManagedThreadId})"); channel.BasicAck(ea.DeliveryTag, false); }); channel.BasicConsume(queueName, false, consumer); while (true) { Thread.Sleep(10); } }); } } }
using Autofac; using EmberKernel.Services.UI.Mvvm.ViewComponent; using EmberKernel.Services.UI.Mvvm.ViewModel.Configuration; using EmberKernel.Services.UI.Mvvm.ViewModel.Plugins; using System; using System.Collections.Generic; using System.Text; namespace EmberKernel.Services.UI.Mvvm { public class MvvmBuilder : IMvvmBuilder { internal KernelBuilder kernelBuilder; public MvvmBuilder(KernelBuilder kernelBuilder) { this.kernelBuilder = kernelBuilder; } public IMvvmBuilder UseConfigurationModel() { kernelBuilder._containerBuilder .RegisterType<ConfigurationModelManager>() .AsSelf() .As<IConfigurationModelManager>() .SingleInstance(); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Windows.Forms; namespace Mercadinho.DAO { class TipoProdutoDAO { private Model.TipoProduto tipoprodutomodel; private MySqlConnection con; private Conexao.Conexao conexao; public TipoProdutoDAO() { } public void InserirDados(String tipoproduto) { con = new MySqlConnection(); tipoprodutomodel = new Model.TipoProduto(); conexao = new Conexao.Conexao(); con.ConnectionString = conexao.getConnectionString(); String query = "INSERT INTO tipoproduto(TipoProduto)"; query += " VALUES (?tipoproduto)"; try { con.Open(); MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("?tipoproduto", tipoproduto); cmd.ExecuteNonQuery(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show("Erro: " + ex); } finally { con.Close(); } } public void AtualizarDadosTipo(String Nome, int idTipoProduto) { con = new MySqlConnection(); conexao = new Conexao.Conexao(); con.ConnectionString = conexao.getConnectionString(); String query = "UPDATE tipoproduto SET TipoProduto = ?Nome WHERE IdTipo = ?IdTipo"; try { con.Open(); MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("?Nome", Nome); cmd.Parameters.AddWithValue("?IdTipo", idTipoProduto); cmd.ExecuteNonQuery(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show("Erro: " + ex); } finally { con.Close(); } } public void RemoverDadosTipo(Int32 IdTipo) { con = new MySqlConnection(); conexao = new Conexao.Conexao(); con.ConnectionString = conexao.getConnectionString(); String query = "DELETE FROM tipoproduto where IdTipo = ?IdTipo"; try { con.Open(); MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("?IdTipo", IdTipo); cmd.ExecuteNonQuery(); cmd.Dispose(); } finally { con.Close(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using NUnit.Framework; using SharpMap.Geometries; namespace UnitTests.Geometries { [TestFixture] public class LinestringTests { [Test] public void Linestring() { LineString l = new LineString(); Assert.IsTrue(l.IsEmpty()); Assert.IsNull(l.GetBoundingBox()); Assert.AreEqual(0, l.Length); Assert.IsFalse(l.Equals(null)); Assert.IsTrue(l.Equals(new LineString())); Collection<Point> vertices = new Collection<Point>(); vertices.Add(new Point(54, 23)); vertices.Add(new Point(93, 12)); vertices.Add(new Point(104, 32)); l.Vertices = vertices; Assert.IsFalse(l.IsEmpty()); Assert.IsFalse(l.IsClosed); Assert.AreEqual(3, l.NumPoints); Assert.AreEqual(new Point(54, 23), l.StartPoint); Assert.AreEqual(new Point(104,32), l.EndPoint); l.Vertices.Add(new Point(54, 23)); Assert.IsTrue(l.IsClosed); Assert.AreEqual(114.15056678325843, l.Length); Assert.AreNotSame(l.Clone(), l); Assert.AreNotSame(l.Clone().Vertices[0], l.Vertices[0]); Assert.AreEqual(l.Clone(), l); LineString l2 = l.Clone(); l2.Vertices[2] = l2.Vertices[2] + new Point(1, 1); Assert.AreNotEqual(l2, l); l2 = l.Clone(); l2.Vertices.Add(new Point(34, 23)); Assert.AreNotEqual(l2, l); } } }
using gView.Framework.Db; using gView.Framework.system; using gView.Framework.UI; using System; using System.Data; using System.Reflection; using System.Threading.Tasks; namespace gView.Framework.Data.Fields.FieldDomains { [RegisterPlugIn("5EE5B5EC-35CC-4d62-8152-6C101D282118")] public class LookupValuesDomain : Cloner, IValuesFieldDomain, IPropertyPage { private DbConnectionString _dbConnString = null; private string _sql = String.Empty, _connString = String.Empty; public DbConnectionString DbConnectionString { get { return _dbConnString; } set { _dbConnString = value; _connString = (_connString != null) ? _dbConnString.ConnectionString : String.Empty; } } public string SqlStatement { get { return _sql; } set { _sql = value; } } #region IValuesFieldDomain Member async public Task<object[]> ValuesAsync() { if (String.IsNullOrEmpty(_connString)) { return null; } try { using (CommonDbConnection connection = new CommonDbConnection()) { connection.ConnectionString2 = _connString; DataSet ds = new DataSet(); if (!await connection.SQLQuery(ds, _sql, "QUERY")) { return null; } DataTable tab = ds.Tables["QUERY"]; object[] values = new object[tab.Rows.Count]; int i = 0; foreach (DataRow row in tab.Rows) { values[i++] = row[0]; } return values; } } catch { return null; } } #endregion #region IFieldDomain Member public string Name { get { return "Lookup Values"; } } #endregion #region IPersistable Member public void Load(gView.Framework.IO.IPersistStream stream) { this.DbConnectionString = (gView.Framework.Db.DbConnectionString)stream.Load("DbConnectionString", null, new DbConnectionString()); this.SqlStatement = (string)stream.Load("SqlStatement", String.Empty); } public void Save(gView.Framework.IO.IPersistStream stream) { if (_dbConnString != null) { stream.Save("DbConnectionString", _dbConnString); } if (_sql != null) { stream.Save("SqlStatement", _sql); } } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"/gView.Win.Data.Fields.UI.dll"); IInitializeClass p = uiAssembly.CreateInstance("gView.Framework.Data.Fields.UI.FieldDomains.Control_LookupValuesDomain") as IInitializeClass; if (p != null) { p.Initialize(this); } return p; } public object PropertyPageObject() { return this; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { public class SearchTransferOrder { public string Code { get; set; } public int Status { get; set; } /// <summary> /// 多个逗号分隔 /// </summary> public string StoreId { get; set; } /// <summary> /// 调出 /// </summary> public bool? From { get; set; } /// <summary> /// 调入 /// </summary> public bool? To { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public string ProductCodeOrBarCode { get; set; } public string ProductName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; [Serializable] public enum LevelType { None, Ambush, Artifact, Energy }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenQA.Selenium; namespace WebAutomationFramework.Pages { class TravelExtrasPage { private IWebDriver Driver { get; set; } public TravelExtrasPage(IWebDriver driver) { Driver = driver; } public void SkipButtonClick() { Wait.WaitForElement(Driver, By.CssSelector("button[class*=skip-link]")); Console.WriteLine("Travel Extras Page"); var skipButtonClick = Driver.FindElement(By.CssSelector("button[class*=skip-link]")); skipButtonClick.Click(); } public void AddInsuranceCoverClick() { Wait.WaitForElement(Driver, By.CssSelector("panel[class*=extra-change]")); var addInsuranceCoverClick = Driver.FindElement(By.CssSelector("panel[class*=extra-change]")); addInsuranceCoverClick.Click(); } public void TakeMeToInsuranceSelectionCloseClick() { Wait.WaitForElement(Driver, By.CssSelector("class[ng-if*=SmartMessageSettings.CloseIconUrl]")); var takeMeToInsuranceSelectionCloseClick = Driver.FindElement(By.CssSelector("class[ng-if*=SmartMessageSettings.CloseIconUrl]")); takeMeToInsuranceSelectionCloseClick.Click(); } } }
using System; using System.Collections.Generic; using System.Configuration; using CLCommonCore.DTO; using CLCommonCore; using CLDatabaseCore; namespace LibraryUICore { internal class Program { static void Main(string[] args) { // loop to continue until user is done - key q string _input = ""; UserDTO user = new UserDTO(); //bool IsFound = false; MockDb db = new MockDb(); string _connection = ConfigurationManager.ConnectionStrings["DBCONN"].ToString(); string _database = ConfigurationManager.AppSettings["MOCKORDB"].ToString(); // either Mock Db or real Db DbAdo ado = new DbAdo(_connection); Printer.MainMenu(); _input = Console.ReadLine().ToLower(); do { // enter app as a guest if (_input.ToLower() == "g") { user = new UserDTO(RoleType.Guest); } if (_input.ToLower() == "pp") { Printer.Profile(user); } if (_input.ToLower() == "pu") { List<UserDTO> _users = new List<UserDTO>(); ; if (_database == DBType.Mock.ToString()) { _users = db.GetUsers(); } else { // database version _users = ado.GetUsers(); } Printer.Users(_users); // TODO: implement this } if (_input.ToLower() == "pr") { // TODO: can I make the configurable?? List<RoleDTO> _roles; if (_database == DBType.Mock.ToString()) { _roles = db.GetRoles(); } else { _roles = ado.GetRoles(); } Printer.Roles(_roles); // TODO: implement this } if (_input.ToLower() == "pm") { Printer.MainMenu(); } if (_input.ToLower() == "r") // REGISTER { UserDTO u = Printer.CollectAddUserData(); if (_database == DBType.Mock.ToString()) { db.CreateUser(u); } else { // database version ado.CreateUser(u); } } Printer.MainMenu(); _input = Console.ReadLine().ToLower(); } while (_input.ToLower() != "q"); Printer.End(); Console.ReadLine(); // stop program } } }
using AlgorithmProblems.Linked_List.Linked_List_Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Linked_List { class MergeSortedLinkedList { /// <summary> /// Merge two sorted linked list w/o using extra space in such a way that the final linked list is sorted /// </summary> /// <param name="list1">linked list to be merged</param> /// <param name="list2">linked list to be merged</param> /// <returns>Merged and sorted linked list</returns> private static SingleLinkedListNode<int> Merge(SingleLinkedListNode<int> list1, SingleLinkedListNode<int> list2) { SingleLinkedListNode<int> mergedListHead = null; SingleLinkedListNode<int> mergedListCurrent = null; while(list1 != null && list2 != null) { if(list1.Data< list2.Data) { AddToMergedList(ref mergedListHead, ref mergedListCurrent, ref list1); } else { AddToMergedList(ref mergedListHead, ref mergedListCurrent, ref list2); } } // Add all list1 items if any of them are left if(list1 != null) { AddToMergedList(ref mergedListHead, ref mergedListCurrent, ref list1); } // Add all the list2 items if any of them are left if(list2 !=null) { AddToMergedList(ref mergedListHead, ref mergedListCurrent, ref list2); } return mergedListHead; } private static void AddToMergedList(ref SingleLinkedListNode<int> mergedListHead, ref SingleLinkedListNode<int> mergedListCurrent, ref SingleLinkedListNode<int> list) { if (mergedListHead == null) { mergedListHead = list; mergedListCurrent = mergedListHead; } else { mergedListCurrent.NextNode = list; mergedListCurrent = mergedListCurrent.NextNode; } list = list.NextNode; } public static void TestMerge() { Console.WriteLine("Test merging of 2 sorted linked list"); SingleLinkedListNode<int> list1 = LinkedListHelper.SortedLinkedList(10); LinkedListHelper.PrintSinglyLinkedList(list1); SingleLinkedListNode<int> list2 = LinkedListHelper.SortedLinkedList(10, 5); LinkedListHelper.PrintSinglyLinkedList(list2); Console.WriteLine("The merged linked list is as follows:"); LinkedListHelper.PrintSinglyLinkedList(Merge(list1, list2)); //Test2 Console.WriteLine("Test2:Test merging of 2 sorted linked list"); list1 = LinkedListHelper.SortedLinkedList(10); LinkedListHelper.PrintSinglyLinkedList(list1); list2 = LinkedListHelper.SortedLinkedList(1, 5); LinkedListHelper.PrintSinglyLinkedList(list2); Console.WriteLine("The merged linked list is as follows:"); LinkedListHelper.PrintSinglyLinkedList(Merge(list1, list2)); } } }
using System.Collections; using BP12; using Cinemachine; using UnityEngine; using UnityEngine.SceneManagement; namespace DChild.Gameplay.Cameras { public class PlayerCamera : SingletonBehaviour<PlayerCamera> { #region NonStatic [SerializeField] private CinemachineBrain m_camera; private CameraShake m_shaker; private Coroutine m_shakeRotoutine; public CinemachineBrain Camera { get { return m_camera; } } private IEnumerator ShakeRoutine(float range, float duration) { m_shaker.m_Range = range; yield return new WaitForSeconds(duration); m_shaker.m_Range = 0; } public void ShakeCamera(float range, float duration) { if (m_shakeRotoutine != null) { StopCoroutine(m_shakeRotoutine); } m_shakeRotoutine = StartCoroutine(ShakeRoutine(range, duration)); } #endregion public static void TransistionToCamera(CinemachineVirtualCamera toCam, float deltaTime) { var fromCam = m_instance.m_camera.ActiveVirtualCamera; if (fromCam == null) { toCam.gameObject.SetActive(true); } else { if (fromCam != (ICinemachineCamera)toCam) { toCam.OnTransitionFromCamera(m_instance.m_camera.ActiveVirtualCamera, Vector3.up, deltaTime); fromCam.VirtualCameraGameObject.SetActive(false); toCam.gameObject.SetActive(true); } } } public static void Shake(float range, float duration) => m_instance.ShakeCamera(range, duration); public static void SetScene(Scene scene) => SceneManager.MoveGameObjectToScene(m_instance.gameObject, scene); } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace StereoCanvasSamples { public class Renderer { public Telescoper Telescoper { get; set; } public void Render(ref DrawingContext drawingContext, int startDx, int startDy) { Color[,] img = new Color[Telescoper.Camera.Width, Telescoper.Camera.Height]; for (long i = 0; i < Telescoper.Camera.Width; i++) { for (long j = 0; j < Telescoper.Camera.Height; j++) { DrawOn(i, j, ref img); } } DrawTo(ref drawingContext, in img, startDx, startDy); } private void DrawOn(long i, long j, ref Color[,] img) { img[i, j] = Telescoper.GetRenderedPixel(i, j); } private void DrawTo(ref DrawingContext drawingContext, in Color[,] img, int startDx, int startDy) { if (Telescoper.Camera.Width <= int.MaxValue && Telescoper.Camera.Height <= int.MaxValue) { for (int x = 0; x < Telescoper.Camera.Width; x++) { for (int y = 0; y < Telescoper.Camera.Height; y++) { DrawPoint(ref drawingContext, in img, x, y, startDx, startDy); } } } else { throw new Exception("Size of image were overflowed!"); } } private void DrawPoint(ref DrawingContext drawingContext, in Color[,] img, int x, int y, int startDx, int startDy) { Brush brush = new SolidColorBrush(Color.FromArgb(img[x, y].A, img[x, y].R, img[x, y].G, img[x, y].B)); Pen pen = new Pen(brush, 1); Rect rect = new Rect( (int)x + startDx, (int)y + startDy, 1, 1); drawingContext.DrawRectangle(brush, pen, rect); } } }
using Alabo.Domains.Entities.Core; using Alabo.Domains.Query; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace Alabo.Datas.Stores.Add { public interface IGetListStore<TEntity, TKey> where TEntity : class, IKey<TKey>, IVersion, IEntity { /// <summary> /// 获取数据的数据列表 /// </summary> IEnumerable<TEntity> GetList(); /// <summary> /// 根据条件查询数据列表 /// </summary> /// <param name="predicate">查询条件</param> IEnumerable<TEntity> GetList(Expression<Func<TEntity, bool>> predicate); /// <summary> /// 根据条件查询数据列表 /// </summary> /// <param name="query"></param> IEnumerable<TEntity> GetList(IExpressionQuery<TEntity> query); /// <summary> /// 获取所有的Id列表 /// </summary> /// <param name="predicate">查询条件</param> IEnumerable<TKey> GetIdList(Expression<Func<TEntity, bool>> predicate = null); } }
namespace Properties.Infrastructure.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddLandlordProperty : DbMigration { public override void Up() { CreateTable( "dbo.LandlordProperties", c => new { LandlordPropertyId = c.Int(nullable: false, identity: true), LandlordPropertyReference = c.String(maxLength: 25), DateCreated = c.DateTime(nullable: false), PropertyType = c.Int(nullable: false), LandlordPropertyStatus = c.Int(nullable: false), AddressLine1 = c.String(maxLength: 100), AddressLine2 = c.String(maxLength: 100), AddressLine3 = c.String(maxLength: 100), AddressLine4 = c.String(maxLength: 100), Postcode = c.String(maxLength: 25), County = c.String(maxLength: 50), PropertyDescription = c.String(), ShortDescription = c.String(), AvailableDate = c.DateTime(nullable: false), DealType = c.Int(nullable: false), LandlordMonthlyValuation = c.Decimal(nullable: false, precision: 18, scale: 2), LetMeMonthlyCost = c.Decimal(nullable: false, precision: 18, scale: 2), ExternalPropertyReference = c.String(), LandlordReference = c.String(), LetMeMonthlyPrice = c.Decimal(nullable: false, precision: 18, scale: 2), LastEditedDate = c.DateTime(nullable: false), ApprovedDate = c.DateTime(nullable: false), ApprovedBy = c.String(), DateDeleted = c.DateTime(), }) .PrimaryKey(t => t.LandlordPropertyId); AddColumn("dbo.Certificates", "LandlordProperty_LandlordPropertyId", c => c.Int()); AddColumn("dbo.PropertyChecks", "LandlordProperty_LandlordPropertyId", c => c.Int()); AddColumn("dbo.PropertyDetails", "LandlordProperty_LandlordPropertyId", c => c.Int()); AddColumn("dbo.Photos", "LandlordProperty_LandlordPropertyId", c => c.Int()); AddColumn("dbo.Videos", "LandlordProperty_LandlordPropertyId", c => c.Int()); CreateIndex("dbo.Certificates", "LandlordProperty_LandlordPropertyId"); CreateIndex("dbo.PropertyChecks", "LandlordProperty_LandlordPropertyId"); CreateIndex("dbo.PropertyDetails", "LandlordProperty_LandlordPropertyId"); CreateIndex("dbo.Photos", "LandlordProperty_LandlordPropertyId"); CreateIndex("dbo.Videos", "LandlordProperty_LandlordPropertyId"); AddForeignKey("dbo.Certificates", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties", "LandlordPropertyId", cascadeDelete: true); AddForeignKey("dbo.PropertyChecks", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties", "LandlordPropertyId", cascadeDelete: true); AddForeignKey("dbo.PropertyDetails", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties", "LandlordPropertyId", cascadeDelete: true); AddForeignKey("dbo.Photos", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties", "LandlordPropertyId", cascadeDelete: true); AddForeignKey("dbo.Videos", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties", "LandlordPropertyId", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Videos", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties"); DropForeignKey("dbo.Photos", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties"); DropForeignKey("dbo.PropertyDetails", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties"); DropForeignKey("dbo.PropertyChecks", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties"); DropForeignKey("dbo.Certificates", "LandlordProperty_LandlordPropertyId", "dbo.LandlordProperties"); DropIndex("dbo.Videos", new[] { "LandlordProperty_LandlordPropertyId" }); DropIndex("dbo.Photos", new[] { "LandlordProperty_LandlordPropertyId" }); DropIndex("dbo.PropertyDetails", new[] { "LandlordProperty_LandlordPropertyId" }); DropIndex("dbo.PropertyChecks", new[] { "LandlordProperty_LandlordPropertyId" }); DropIndex("dbo.Certificates", new[] { "LandlordProperty_LandlordPropertyId" }); DropColumn("dbo.Videos", "LandlordProperty_LandlordPropertyId"); DropColumn("dbo.Photos", "LandlordProperty_LandlordPropertyId"); DropColumn("dbo.PropertyDetails", "LandlordProperty_LandlordPropertyId"); DropColumn("dbo.PropertyChecks", "LandlordProperty_LandlordPropertyId"); DropColumn("dbo.Certificates", "LandlordProperty_LandlordPropertyId"); DropTable("dbo.LandlordProperties"); } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using TryHardForum.Data; using TryHardForum.Models; using TryHardForum.Services; using TryHardForum.ViewModels.Reply; namespace TryHardForum.Controllers { public class ReplyController : Controller { private readonly IPostRepository _postRepository; private readonly UserManager<AppUser> _userManager; private readonly IAppUserRepository _userRepository; private readonly IForumRepository _forumRepository; private readonly IPostReplyRepository _replyRepository; private readonly ITopicRepository _topicRepository; public ReplyController(IPostRepository postRepository, UserManager<AppUser> userManager, IAppUserRepository userRepository, IForumRepository forumRepository, IPostReplyRepository replyRepository, ITopicRepository topicRepository) { _postRepository = postRepository; _userManager = userManager; _userRepository = userRepository; _replyRepository = replyRepository; _forumRepository = forumRepository; _topicRepository = topicRepository; } public async Task<IActionResult> Create(int id) { var post = _postRepository.GetPost(id); var topic = _topicRepository.GetTopic(post.Topic.Id); var user = await _userManager.FindByNameAsync(User.Identity.Name); var model = new PostReplyModel { PostContent = post.Content, PostId = post.Id, AuthorId = user.Id, AuthorName = User.Identity.Name, AuthorImageUrl = user.ProfileImageUrl, AuthorRating = user.Rating, IsAuthorAdmin = user.IsAdmin, TopicId = topic.Id, TopicTitle = topic.Title, Created = DateTime.Now }; return View(model); } [HttpPost] public async Task<IActionResult> Create(PostReplyModel model) { var userId = _userManager.GetUserId(User); var user = await _userManager.FindByIdAsync(userId); var reply = BuildReply(model, user); // Разобраться, что это за метод такой AddReply. await _replyRepository.CreateReply(reply); await _userRepository.UpdateUserRating(userId, typeof(PostReply)); return RedirectToAction("Index", "Topic", new{ id = model.PostId }); } // Используется при создании нового ответа. private PostReply BuildReply(PostReplyModel model, AppUser user) { var post = _postRepository.GetPost(model.PostId); return new PostReply { Post = post, Content = model.ReplyContent, Created = DateTime.Now, AppUser = user }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BlackJack1 { class Player { public int playerCount = 0; public Cards.Card myCard1 = 0, myCard2 = 0; public void CheckScoreWithTUZ() { if ((myCard1 == Cards.Card.TUZ || myCard2 == Cards.Card.TUZ) && playerCount > 21) playerCount -= 10; } } }
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class MainMenuFuncs : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void startBearRun() { SceneManager.LoadScene("bear_chase"); } }
namespace MassEffect.GameObjects.Projectiles { class Laser : Projectile { public Laser(int damage) : base(damage) { } public override void Hit(Interfaces.IStarship targetShip) { int extDamge = 0; if (targetShip.Shields < this.Damage) { extDamge = targetShip.Shields - this.Damage; } targetShip.Shields -= this.Damage; targetShip.Health -= extDamge; } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ex2_API.Models; using ex2_BLL.Services; using ex2_API.Mappers; using ex2_DAL.Models; namespace ex2_API.Controllers { [Route("api/[controller]")] [ApiController] public class PersonController : Controller { private PersonService _personService; public PersonController() { _personService = new PersonService(); } [HttpGet("{id}")] public IActionResult Get(Guid id) { return Ok(_personService.Get(id)); } [HttpGet("GetAll")] public IActionResult GetAll() { return Ok(_personService.GetByFirstName("")); } [HttpGet("GetByFirstName/{firstName}")] public IActionResult GetByFirstName(string firstName) { return Ok(_personService.GetByFirstName(firstName)); } [HttpGet("GetByLastName/{lastName}")] public IActionResult GetByLastName(string lastName) { return Ok(_personService.GetByLastName(lastName)); } [HttpDelete("{id}")] public IActionResult Delete(Guid id) { return Ok(_personService.Delete(id)); } [HttpPost] public IActionResult Post([FromBody] PersonApi person) { if ((person.FirstName != string.Empty) && (person.LastName != string.Empty)) { if (_personService.Add(person.ToDal()) == 1) return Ok(); else return BadRequest("Person can't be added"); } else return BadRequest("LastName and FirstName can't be empty"); } [HttpPut] public IActionResult Put([FromBody] Person person) { if ((person.FirstName != string.Empty) && (person.LastName != string.Empty)) { if (_personService.Update(person) == 1) return Ok(); else return BadRequest("Person can't be updated"); } else return BadRequest("LastName and FirstName can't be empty"); } } }
using UnityEngine; public class Utils { public static string MainDirectionString(Vector3 vec) { if (Mathf.Abs(vec.x) > Mathf.Abs(vec.y)) { if (vec.x > 0) { return "Right"; } else { return "Left"; } } else { if (vec.y > 0) { return "Up"; } else { return "Down"; } } } /// <summary> /// Easing equation function for a quadratic (t^2) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuadEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; } /// <summary> /// Easing equation function for a quadratic (t^2) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="time">Current time in seconds.</param> /// <param name="start">Start Vector3.</param> /// <param name="finish">Finish Vector3.</param> /// <param name="duration">Duration.</param> /// <returns>The tweened Vector3</returns> public static Vector3 QuadEaseInOut(float time, Vector3 start, Vector3 finish, float duration) { Vector3 result = new Vector3 { x = QuadEaseInOut(time, start.x, finish.x, duration), y = QuadEaseInOut(time, start.y, finish.y, duration), z = QuadEaseInOut(time, start.z, finish.z, duration) }; return result; } }
namespace KingNetwork.Shared.Extensions { public static class KingBufferExtensions { #region Extensions public static KingBufferReader ToKingBufferReader(this KingBufferWriter writer) { return KingBufferReader.Create(writer.BufferData); } public static KingBufferWriter ToKingBufferWriter(this KingBufferReader reader) { return KingBufferWriter.Create(reader.BufferData); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Alps.Web.Canteen.Model; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Alps.Web.Canteen.Controllers { [Route("api/[controller]")] public class CanteenController : Controller { private readonly CanteenDbContext _context; public CanteenController(CanteenDbContext context) { this._context = context; } [HttpGet("getdinners")] public IEnumerable<Dinner> GetDinners() { return this._context.Dinners; } [HttpGet("getdiners")] [Authorize("Bearer", Roles = "admin")] public JsonResult GetDiners() { var query = from p in _context.Diners orderby p.Name select new { CardNumber = p.CardNumber, Name = p.Name, ID = p.ID, IDNumber = p.IDNumber == null || p.IDNumber == string.Empty ? "" : p.IDNumber.Substring( 12) }; return Json(query); } [HttpGet("getbinddiners")] [Authorize("Bearer", Roles = "user,admin")] public JsonResult GetBindDiners() { var query = from b in _context.BindRecords from d in _context.Diners where b.DinerID == d.ID && b.CanteenUserID == GetUserID() select new { id = b.ID, bindName = b.BindName, bindIDNumber = b.BindIDNumber, dinerName = d.CardNumber.Substring(4) }; return Json(query); } [HttpGet("getbookablediners")] [Authorize("Bearer", Roles = "user,admin")] public JsonResult GetBookableDiners() { IQueryable query; if (User.IsInRole("admin")) { query = from d in _context.Diners select new { ID = d.ID, Name = d.Name }; } else query = from b in _context.BindRecords from d in _context.Diners where b.DinerID == d.ID && b.CanteenUserID == GetUserID() select new { ID = d.ID, Name = d.Name }; return Json(query); } [HttpGet("getbinddiner/{id}")] [Authorize("Bearer", Roles = "user,admin")] public JsonResult GetBindDiner(Guid id) { var query = (from b in _context.BindRecords from d in _context.Diners where b.DinerID == d.ID && b.CanteenUserID == GetUserID() && b.ID == id select new { bindName = b.BindName, bindIDNumber = b.BindIDNumber, dinerName = d.CardNumber }).FirstOrDefault(); return Json(query); } public class BindDinerDto { public string BindName { get; set; } public string BindIDNumber { get; set; } //public Guid ID { get; set; } //public Guid DinerID { get; set; } } [HttpPost("unbinddiner/{id}")] [Authorize("Bearer", Roles = "user,admin")] public bool UnbindDiner(Guid id) { var existRecord = _context.BindRecords.FirstOrDefault(p => p.ID == id && p.CanteenUserID == GetUserID()); if (existRecord == null) return false; _context.BindRecords.Remove(existRecord); if (_context.SaveChanges() == 1) { return true; } else return false; } [HttpPost("binddiner")] [Authorize("Bearer", Roles = "user,admin")] public bool BindDiner([FromBody]BindDinerDto dto) { var existDiner = _context.Diners.FirstOrDefault(p => p.Name == dto.BindName && p.IDNumber.Substring(p.IDNumber.Length - 6) == dto.BindIDNumber); if (existDiner == null) return false; else { var newRecord = new BindRecord() { BindIDNumber = dto.BindIDNumber, BindName = dto.BindName, CanteenUserID = GetUserID(), DinerID = existDiner.ID }; _context.BindRecords.Add(newRecord); if (_context.SaveChanges() == 1) return true; else return false; } //var existRecord = this._context.BindRecords.Find(dto.ID); //if (existRecord == null) //{ // var newRecord = new BindRecord() { BindIDNumber = dto.BindIDNumber, BindName = dto.BindName, CanteenUserID = GetUserID() }; // if (User.IsInRole("admin")) // newRecord.DinerID = dto.DinerID; // _context.BindRecords.Add(newRecord); //} //else //{ // existRecord.BindIDNumber = dto.BindIDNumber; // existRecord.BindName = dto.BindName; // if (User.IsInRole("admin")) // existRecord.DinerID = dto.DinerID; //} //if (_context.SaveChanges() == 1) // return true; //else // return false; } public class BookActionDto { public Guid DinerID { get; set; } public Guid DinnerID { get; set; } public DateTime DinnerDate { get; set; } public bool UnBook { get; set; } } [HttpPost("book")] [Authorize("Bearer", Roles = "admin,canteen,user")] public bool Book([FromBody]BookActionDto dto) { var dinner = _context.Dinners.Find(dto.DinnerID); if (dinner == null) return false; if (dto.DinnerDate.Add(dinner.DinnerTime).AddHours(7) < DateTime.Now) return false; var diner = _context.Diners.Find(dto.DinerID); if (diner == null) return false; if (dto.UnBook) { BookRecord existRecord = _context.BookRecords.FirstOrDefault(p => p.DinerID == dto.DinerID && p.DinnerID == dto.DinnerID &&p.DinnerDate==dto.DinnerDate.AddHours(8)); if (existRecord != null) { _context.BookRecords.Remove(existRecord); } else return false; } else { BookRecord bookRecord = BookRecord.CreateNewBookRecord(dto.DinerID, dto.DinnerID, dto.DinnerDate.ToLocalTime().Date, GetUserID()); this._context.BookRecords.Add(bookRecord); } if (this._context.SaveChanges() == 1) return true; else return false; } // GET api/values/5 [HttpGet("getbookrecord/{id}")] [Authorize("Bearer", Roles = "admin,canteen,user")] public IEnumerable<BookRecord> GetBookRecordByDinerID(Guid id) { return this._context.BookRecords.Where(p => p.DinerID == id).OrderBy(p => p.DinnerDate); } [HttpGet("getbookinfo")] public JsonResult GetBookInfo() { var date = new DateTime[10]; date[0] = DateTime.Today; for (int i = 1; i < 10; i++) { date[i] = date[0].AddDays(i); } var dinners = _context.Dinners.ToList(); var bookInfoQuery = from t in date from d in dinners select new { Date = t.Date, Name = d.Name, ID = d.ID } into trix join b in _context.BookRecords on new { trix.Date, trix.ID } equals new { Date = b.DinnerDate, ID = b.DinnerID } into jrst from j in jrst.DefaultIfEmpty() group j by new { trix.Date, trix.Name } into g select new { d = g.Key.Date, b = new { n = g.Key.Name, q = g.Count(p => p != null) } } into k group k by k.d into kg select new { d = kg.Key, b = kg.Select(p => new { n = p.b.n, q = p.b.q }) }; var takeInfoQuery = from d in _context.Dinners join t in _context.TakeRecords.Where(p=>p.TakeDate==DateTime.Today.AddHours(-8)) on d.ID equals t.DinnerID into jrst from j in jrst.DefaultIfEmpty() group j by d.Name into g select new { n = g.Key, q = g.Count(p => p != null) }; //where b.DinnerID==d.ID //var bookInfoQuery = from t in date // select new // { // Date = t, // Dinner = // (from d in dinners // select new // { // Dinner = d.Name, // Quantity = ( // from b in this._context.BookRecords // where (b.DinnerID == d.ID && b.DinnerDate == t) // group b by 1 into g // select g.Count()).FirstOrDefault() // }) // }; return Json(new {BookInfo=bookInfoQuery.ToList(),TakeInfo=takeInfoQuery.ToList() }); } [Authorize("Bearer", Roles = "admin")] [HttpGet("getdiner/{id}")] public JsonResult GetDiner(Guid id) { return Json(this._context.Diners.FirstOrDefault(p => p.ID == id)); } private Guid GetUserID() { var idClaim = User.Claims.SingleOrDefault(p => p.Type == "ID"); if (idClaim == null) throw new Exception("令牌有问题"); var userID = Guid.Parse(idClaim.Value); return userID; } public class DinerDto { public string CardNumber { get; set; } public string IDNumber { get; set; } public string Name { get; set; } public Guid ID { get; set; } } [Authorize("bearer", Roles = "admin")] [HttpPost("updatediner")] public bool UpdateDiner([FromBody]DinerDto diner) { if (diner.IDNumber.Length != 18||diner.CardNumber.Length!= 10 || diner.Name == string.Empty) return false; if (diner.ID == Guid.Empty) { var newDiner = new Diner() { CardNumber = diner.CardNumber, Name = diner.Name, IDNumber = diner.IDNumber }; this._context.Diners.Add(newDiner); } else { var existDiner = this._context.Diners.FirstOrDefault(p => p.ID == diner.ID); existDiner.Name = diner.Name; //existDiner.CardNumber = diner.CardNumber; existDiner.IDNumber = diner.IDNumber; } if (this._context.SaveChanges() == 1) return true; else return false; } [Authorize("bearer", Roles = "admin")] [HttpPost("blukupdatediner")] public bool BlukUpdateDiner([FromBody]IList<DinerDto> diners) { int updateCount = 0; foreach (var diner in diners) { var existDiner = this._context.Diners.FirstOrDefault(p => p.CardNumber == diner.CardNumber); if (existDiner == null) { var newDiner = new Diner() { CardNumber = diner.CardNumber, Name = diner.Name,IDNumber=diner.IDNumber }; this._context.Diners.Add(newDiner); updateCount++; } else { if (existDiner.Name != diner.Name || existDiner.IDNumber!=diner.IDNumber) { existDiner.Name = diner.Name; existDiner.IDNumber = diner.IDNumber; updateCount++; } } } if (this._context.SaveChanges() == updateCount) return true; else return false; //if (diner.ID == Guid.Empty) //{ // var newDiner = new Diner() { CardNumber = diner.CardNumber, Name = diner.Name }; // this._context.Diners.Add(newDiner); //} //else //{ // var existDiner = this._context.Diners.FirstOrDefault(p => p.ID == diner.ID); // existDiner.Name = diner.Name; // existDiner.CardNumber = diner.CardNumber; //} //if (this._context.SaveChanges() == 1) // return true; //else // return false; } public class TakeDinnerDto { public Guid DinnerID { get; set; } public DateTime TakeDate { get; set; } public string CardNumber { get; set; } } [Authorize("bearer", Roles = "admin,canteen")] [HttpPost("takedinner")] public bool TakeDinner([FromBody]TakeDinnerDto dto) { var newTake = new TakeRecord { DinnerID = dto.DinnerID, TakeDate = dto.TakeDate, CardNumber = dto.CardNumber, TakeTime = DateTime.Now }; this._context.TakeRecords.Add(newTake); if (this._context.SaveChanges() == 1) return true; else return false; } [Authorize("Bearer", Roles = "admin,canteen")] [HttpGet("gettakerecords")] public JsonResult GetTakeRecords() { var query = from t in this._context.TakeRecords join d in _context.Diners on t.CardNumber equals d.CardNumber into joinrst from d in joinrst.DefaultIfEmpty() where t.TakeDate == DateTime.Today.AddHours(-8) orderby t.TakeTime descending select new { id = t.ID, tt = t.TakeTime.ToString("HH:mm:ss"), cn = d == null ? t.CardNumber : d.Name }; return Json(query.Take(150)); } [Authorize("Bearer", Roles = "admin,canteen")] [HttpPost("deletetakerecord/{id}")] public bool DeleteTakeRecords(Guid id) { var existRecord = this._context.TakeRecords.FirstOrDefault(p => p.ID == id); if (existRecord != null) { _context.TakeRecords.Remove(existRecord); if (_context.SaveChanges() == 1) return true; else return false; } else return false; } public class TakeInfoSearchDto { public string DinerName { get; set; } public string CardNumber { get; set; } } [Authorize("Bearer", Roles = "admin")] [HttpPost("gettakeinfo")] public JsonResult GetTakeInfo([FromBody]TakeInfoSearchDto dto) { if (dto.CardNumber == null ) dto.CardNumber = ""; if (dto.DinerName == null) dto.DinerName = ""; var query = from t in _context.TakeRecords from d in _context.Diners from dd in _context.Dinners where t.CardNumber == d.CardNumber && dd.ID==t.DinnerID && t.CardNumber.Contains(dto.CardNumber) && d.Name.Contains(dto.DinerName) orderby d.Name,t.TakeTime descending select new {Name=d.Name,TakeTime=t.TakeTime.ToString("MM-dd HH:mm:ss"),DinnerName=dd.Name,CardNumber=t.CardNumber }; return Json(query); } } }
using FluentValidation; using Galeri.Business.Abstract; using Galeri.Business.ValidationTool; using Galeri.DataAccess.Abstract; using Galeri.Entities.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Galeri.Business.Concrete { public class ManagerCollection<TEntity, TDal, TValidator> : IServiceCollection<TEntity> where TEntity : class, IEntity, new() where TValidator:IValidator,new() where TDal:IEntityRepository<TEntity>,IFilterMethods<TEntity> { TDal dal; TValidator validator; public ManagerCollection(TDal _dal,TValidator _validator) { dal = _dal; validator = _validator; } public void Add(TEntity entity) { EntityValidator.Validate(validator, entity); dal.Add(entity); } public void Delete(TEntity entity) { dal.Delete(entity); } public List<TEntity> GetEntities(Expression<Func<TEntity, bool>> filter = null) { return dal.GetEntities(filter); } public TEntity GetEntity(Expression<Func<TEntity, bool>> filter) { return dal.GetEntity(filter); } public void Update(TEntity entity) { EntityValidator.Validate(validator, entity); dal.Update(entity); } } }
using System; using MongoDB.Bson; namespace desafio.Models { public class Tdl { public ObjectId _id {get; set;} public string tdl {get; set;} public string description {get; set;} public string type {get; set;} } }
using System; using System.Collections.Generic; using System.Linq; namespace Unique_Usernames { class Program { static void Main(string[] args) { var numberOfRows = int.Parse(Console.ReadLine()); var names = new HashSet<string>(); for (int i = 0; i < numberOfRows; i++) { var name = Console.ReadLine(); names.Add(name); } Console.WriteLine(String.Join("\n",names)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ToDoListApplication.BusinessLayer.Entities { public class Domain { public int Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Data; using Elmah; namespace CreamBell_DMS_WebApps { public partial class frmPurchaseIndentList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty) { Response.Redirect("Login.aspx"); return; } if (Session["SiteCode"] != null) { BindGridview(); } } protected void BindGridview() { try { string query; query = "Select A.Indent_NO,CONVERT(VARCHAR(11),A.Indent_Date,106) as Indent_Date ,coalesce(CONVERT(VARCHAR(11),Required_Date,106),'') as Required_Date," + // "SALEOFFICE_CODE=(select B.SALEOFFICE_CODE from ax.ACXSITEMASTER B where B.SiteId=A.SiteId )," + "SALEOFFICE_CODE=(select B.ACXPLANTCODE from [ax].[INVENTSITE] B where B.SiteId=A.SiteId )," + //"SALEOFFICE_NAME=(select B.SALEOFFICE_NAME from ax.ACXSITEMASTER B where B.SiteId=A.SiteId ),"+ "SALEOFFICE_NAME=(select B.ACXPLANTNAME from [ax].[INVENTSITE] B where B.SiteId=A.SiteId )," + "Box=(Select cast(sum(C.BOX) as decimal(10,2)) BOX from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + "Crates=(Select cast(sum(C.Crates) as decimal(10,2)) Crates from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + "Ltr=(Select cast(sum(C.Ltr) as decimal(10,2)) Ltr from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + "A.So_No, A.Invoice_No ,"+ " case A.STATUS when 1 then 'Confirm' when 0 then 'Pending' end as Confirm "+ "from ax.ACXPURCHINDENTHEADER A where A.indent_No!='' and [Siteid]='" + Session["SiteCode"].ToString() + "' order by A.Indent_Date desc"; CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); DataTable dt = new DataTable(); dt = obj.GetData(query); if (dt.Rows.Count > 0) { gvHeader.DataSource = dt; gvHeader.DataBind(); } else { dt.Rows.Add(dt.NewRow()); gvHeader.DataSource = dt; gvHeader.DataBind(); int columncount = gvHeader.Rows[0].Cells.Count; gvHeader.Rows[0].Cells.Clear(); gvHeader.Rows[0].Cells.Add(new TableCell()); gvHeader.Rows[0].Cells[0].ColumnSpan = columncount; gvHeader.Rows[0].Cells[0].Text = "No Records Found"; } } catch(Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } } public void BindNewLine() { try { DataTable dt = new DataTable(); string query; query = "select A.Indent_No, A.Line_No,A.Product_Group,A.Product_Code," + "Product_Name=(Select B.Product_Name from ax.AcxProductMaster B where B.Product_Code=A.Product_Code and " + "B.Product_GRoup=A.Product_Group)," + "cast(A.Box as decimal(10,2)) Box ,cast(A.Crates as decimal(10,2)) Crates ,cast(A.Ltr as decimal(10,2)) Ltr " + "from ax.ACXPurchIndentLine A Where A.Indent_No='" + Session["IndentNo"].ToString() + "' and A.SITEID='" + Session["SiteCode"].ToString() + "' order by A.Line_no"; CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); dt = obj.GetData(query); if (dt.Rows.Count > 0) { gvLineDetails.DataSource = dt; gvLineDetails.DataBind(); } else { dt.Rows.Add(dt.NewRow()); gvLineDetails.DataSource = dt; gvLineDetails.DataBind(); int columncount = gvHeader.Rows[0].Cells.Count; gvLineDetails.Rows[0].Cells.Clear(); gvLineDetails.Rows[0].Cells.Add(new TableCell()); gvLineDetails.Rows[0].Cells[0].ColumnSpan = columncount; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { } } protected void Status_Click(object sender, EventArgs e) { // GridViewRow gvrow = (GridViewRow)(((LinkButton)sender)).NamingContainer; //GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow; //string abc = (clickedRow.FindControl("lnkbtnDel") as LinkButton).Text; //LinkButton lnk = (LinkButton)gvrow.FindControl("Status"); LinkButton lnk = (LinkButton)sender; Session["TEMP"] = lnk.CommandArgument.ToString(); Response.Redirect("frmPurchaseIndent.aspx"); } protected void lnkbtnso_Click(object sender, EventArgs e) { } protected void lnkbtninv_Click(object sender, EventArgs e) { } protected void lnkbtn_Click(object sender, EventArgs e) { try { GridViewRow gvrow = (GridViewRow)(((LinkButton)sender)).NamingContainer; LinkButton lnk = sender as LinkButton; Session["Lndentno"] = lnk.Text; DataTable dt = new DataTable(); string query; //query = "select A.Indent_No, A.Line_No,A.Product_Group,A.Product_Code," + // "Product_Name=(Select B.Product_Name from ax.AcxProductMaster B where B.Product_Code=A.Product_Code and " + // "B.Product_GRoup=A.Product_Group)," + // "cast(A.Box as decimal(10,2)) Box ,cast(A.Crates as decimal(10,2)) Crates ,cast(A.Ltr as decimal(10,2)) Ltr " + // "from ax.ACXPurchIndentLine A Where A.Indent_No='" + lnk.Text + "' and A.SITEID='" + Session["SiteCode"].ToString() + "' order by A.Line_no"; query = "select A.Indent_No, A.Line_No,A.Product_Group,A.Product_Code," + "Product_Name=(Select B.Product_Name from ax.INVENTTABLE B where B.Itemid=A.Product_Code and " + "B.Product_GRoup=A.Product_Group)," + "cast(A.Box as decimal(10,2)) Box ,cast(A.Crates as decimal(10,2)) Crates ,cast(A.Ltr as decimal(10,2)) Ltr " + "from ax.ACXPurchIndentLine A Where A.Indent_No='" + lnk.Text + "' and A.SITEID='" + Session["SiteCode"].ToString() + "' order by A.Line_no"; CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); dt = obj.GetData(query); if (dt.Rows.Count > 0) { gvLineDetails.DataSource = dt; gvLineDetails.DataBind(); } else { dt.Rows.Add(dt.NewRow()); gvLineDetails.DataSource = dt; gvLineDetails.DataBind(); int columncount = gvHeader.Rows[0].Cells.Count; gvLineDetails.Rows[0].Cells.Clear(); gvLineDetails.Rows[0].Cells.Add(new TableCell()); gvLineDetails.Rows[0].Cells[0].ColumnSpan = columncount; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { } } protected void gvDetails_SelectedIndexChanged(object sender, EventArgs e) { } protected void btn2_Click(object sender, EventArgs e) { if (txtSearch.Text != "" || ddlSerch.SelectedItem.Text == "All") { gvHeader.DataSource = null; gvHeader.DataBind(); gvLineDetails.DataSource = null; gvLineDetails.DataBind(); if (ddlSerch.SelectedItem.Text == "All") { BindGridview(); } else { string search = ""; search = "%" + txtSearch.Text + "%"; try { string query = "Select A.Indent_NO,CONVERT(VARCHAR(11),A.Indent_Date,106) as Indent_Date ,coalesce(CONVERT(VARCHAR(11),Required_Date,106),'') as Required_Date," + //"SALEOFFICE_CODE=(select B.SALEOFFICE_CODE from ax.ACXSITEMASTER B where B.SiteId=A.SiteId )," + "SALEOFFICE_CODE=(select B.ACXPLANTCODE from [ax].[INVENTSITE] B where B.SiteId=A.SiteId )," + //"SALEOFFICE_NAME=(select B.SALEOFFICE_NAME from ax.ACXSITEMASTER B where B.SiteId=A.SiteId )," + "SALEOFFICE_NAME=(select B.ACXPLANTNAME from [ax].[INVENTSITE] B where B.SiteId=A.SiteId )," + "Box=(Select cast(sum(C.BOX) as decimal(10,2)) BOX from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + "Crates=(Select cast(sum(C.Crates) as decimal(10,2)) Crates from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + "Ltr=(Select cast(sum(C.Ltr) as decimal(10,2)) Ltr from ax.ACXPURCHINDENTLINE C where C.Indent_No=A.Indent_No and A.SiteId=C.SiteId )," + " A.So_No, A.Invoice_No ," + " case A.STATUS when 1 then 'Confirm' when 0 then 'Pending' end as Confirm " + "from ax.ACXPURCHINDENTHEADER A where A.indent_No!='' and [Siteid]='" + Session["SiteCode"].ToString() + "' and A." + ddlSerch.SelectedItem.Value + " like '" + search + "' order by A.Indent_No"; DataTable dt = new DataTable(); CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); dt = obj.GetData(query); if (dt.Rows.Count > 0) { gvHeader.DataSource = dt; gvHeader.DataBind(); } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Record Not Found..')", true); } //=============================================== dt.Clear(); search = txtSearch.Text; // query = "select A.Indent_No, A.Line_No,A.Product_Group,A.Product_Code," + //"Product_Name=(Select B.Product_Name from ax.AcxProductMaster B where B.Product_Code=A.Product_Code and " + //"B.Product_GRoup=A.Product_Group)," + //"cast(A.Box as decimal(10,2)) Box ,cast(A.Crates as decimal(10,2)) Crates ,cast(A.Ltr as decimal(10,2)) Ltr " + //"from ax.ACXPurchIndentLine A Where A." + ddlSerch.SelectedItem.Value + "='" + search + "' and A.SITEID='" + Session["SiteCode"].ToString() + "' order by A.Line_no"; query = "select A.Indent_No, A.Line_No,A.Product_Group,A.Product_Code," + "Product_Name=(Select B.Product_Name from ax.INVENTTABLE B where B.Itemid=A.Product_Code and " + "B.Product_GRoup=A.Product_Group)," + "cast(A.Box as decimal(10,2)) Box ,cast(A.Crates as decimal(10,2)) Crates ,cast(A.Ltr as decimal(10,2)) Ltr " + "from ax.ACXPurchIndentLine A Where A." + ddlSerch.SelectedItem.Value + "='" + search + "' and A.SITEID='" + Session["SiteCode"].ToString() + "' order by A.Line_no"; dt = obj.GetData(query); if (dt.Rows.Count > 0) { gvLineDetails.DataSource = dt; gvLineDetails.DataBind(); } else { //ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Record Not Found..')", true); } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } finally { } } } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Enter the text in serchbox..')", true); } } //protected void gvLineDetails_PageIndexChanging(object sender, GridViewPageEventArgs e) //{ // gvLineDetails.PageIndex = e.NewPageIndex; // BindNewLine(); //} protected void gvHeader_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { String Status = string.Empty; LinkButton LblStatus; LblStatus = (LinkButton)e.Row.FindControl("Status"); //Session["lblstatus"] = LblStatus.Text; //int i = e.Row.RowIndex; if (LblStatus.Text == "Confirm") { LblStatus.ForeColor=System.Drawing.Color.Green; LblStatus.Enabled = false; } else if (LblStatus.Text == "Pending") { LblStatus.ForeColor = System.Drawing.Color.DarkOrange; } } } } }
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 FiiiCoin.Wallet.Win.Views.Controls { /// <summary> /// PagerControl.xaml 的交互逻辑 /// </summary> public partial class PagerControl : UserControl { public PagerControl() { InitializeComponent(); } public int PageCount { get { return (int)GetValue(PageCountProperty); } set { SetValue(PageCountProperty, value); } } public static readonly DependencyProperty PageCountProperty = DependencyProperty.Register("PageCount", typeof(int), typeof(PagerControl), new PropertyMetadata(1)); public int CurrentPage { get { return (int)GetValue(CurrentPageProperty); } set { SetValue(CurrentPageProperty, value); } } public static readonly DependencyProperty CurrentPageProperty = DependencyProperty.Register("CurrentPage", typeof(int), typeof(PagerControl), new PropertyMetadata(1)); private void FirstPageClick(object sender, RoutedEventArgs e) { CurrentPage = 1; } private void PrevPageClick(object sender, RoutedEventArgs e) { if (CurrentPage == 1) return; else CurrentPage--; } private void NextPageClick(object sender, RoutedEventArgs e) { if (CurrentPage == PageCount) return; CurrentPage++; } private void LastPageClick(object sender, RoutedEventArgs e) { CurrentPage = PageCount; } } }
using UnityEngine; using UnityEngine.SceneManagement; using UnityAtoms.BaseAtoms; namespace UnityAtoms.SceneMgmt { /// <summary> /// Action to change scene. /// </summary> [EditorIcon("atom-icon-purple")] [CreateAssetMenu(menuName = "Unity Atoms/Actions/Scene Management/Change Scene")] public sealed class ChangeScene : AtomAction { /// <summary> /// Scene to change to. /// </summary> [SerializeField] private StringReference _sceneName = null; /// <summary> /// Change the scene. /// </summary> public override void Do() { SceneManager.LoadScene(_sceneName.Value); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace BDONotiBot.Models { [Table("Notis")] public class Noti { [Key] public int Id { get; set; } public int NotiTime { get; set; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Otiport.API.Data; using Otiport.API.Mappers; using Otiport.API.Mappers.Implementations; using Otiport.API.Providers; using Otiport.API.Repositories; using Otiport.API.Repositories.Implementations; using Otiport.API.Services; using Otiport.API.Services.Implementations; namespace Otiport.API.Extensions { public static class DependencyServicesExtensions { public static IServiceCollection AddaDataLayer(this IServiceCollection services) { var configuration = services.BuildServiceProvider().GetService<IConfiguration>(); services.AddDbContext<OtiportDbContext>(options => { options.UseSqlServer(configuration.GetConnectionString("OtiportDb"), builder => builder.MigrationsAssembly("Otiport.API")); }); return services; } public static IServiceCollection AddRepositoryLayer(this IServiceCollection services) { services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IAdressInformationRepository, AdressInformationRepository>(); services.AddScoped<IMedicineRepository, MedicineRepository>(); services.AddScoped<ITreatmentRepository, TreatmentRepository>(); services.AddScoped<IProfileItemRepository,ProfileItemRepository>(); return services; } public static IServiceCollection AddServicesLayer(this IServiceCollection services) { services.AddScoped<IUserService, UserService>(); services.AddScoped<IAddressInformationService, AddressInformationService>(); services.AddScoped<IMedicineService, MedicineService>(); services.AddScoped<ITreatmentService, TreatmentService>(); services.AddScoped<IProfileItemService, ProfileItemService>(); return services; } public static IServiceCollection AddMapperLayer(this IServiceCollection services) { services.AddTransient<IUserMapper, UserMapper>(); services.AddTransient<IMedicineMapper, MedicineMapper>(); services.AddTransient<ITreatmentMapper, TreatmentMapper>(); services.AddTransient<IProfileItemMapper, ProfileItemMapper>(); return services; } public static IServiceCollection AddProviders(this IServiceCollection services) { services.AddTransient<ITokenProvider, TokenProvider>(); return services; } } }
using System; using System.Collections.Generic; using System.Text; namespace Hayaa.Security.Service.Config { class SecurityServiceRootConfig { } }
using System; using System.Linq; using System.Web.UI.WebControls; namespace Asp_webform_sinav { public partial class Yonetmen : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (EntityModel Database = new EntityModel()) { Tekrar1.DataSource = Database.Director.ToList(); Tekrar1.DataBind(); } if (!IsPostBack) { if (Request.QueryString["ID"] != null) { int id = int.Parse(Request.QueryString["ID"]); using (EntityModel database = new EntityModel()) { var deger = database.Director.Find(id); database.Director.Remove(deger); database.SaveChanges(); Response.Redirect("Yonetmen.aspx"); } } if (Request.QueryString["GID"] != null) { int gid = int.Parse(Request.QueryString["GID"]); using (EntityModel database = new EntityModel()) { var deger = database.Director.Find(gid); txtYonetmenAdi.Text = deger.YonetmenAdi; } } } } protected void butonKaydet_Click(object sender, EventArgs e) { if (txtYonetmenAdi.Text != "") { using (EntityModel database = new EntityModel()) { Models.Director yonetmen = new Models.Director(); yonetmen.YonetmenAdi = txtYonetmenAdi.Text; database.Director.Add(yonetmen); database.SaveChanges(); } Response.Redirect("Yonetmen.aspx"); } } protected void butonGuncelle_Click(object sender, EventArgs e) { if (Request.QueryString["GID"] != null) { using (EntityModel database = new EntityModel()) { int gid = int.Parse(Request.QueryString["GID"]); var deger = database.Director.Find(gid); txtYonetmenAdi.Text = deger.YonetmenAdi; database.SaveChanges(); } Response.Redirect("Yonetmen.aspx"); } } } }
using System.Collections.Generic; namespace PluralsightDdd.SharedKernel { /// <summary> /// Base types for all Entities which track state using a given Id. /// </summary> public abstract class BaseEntity<TId> { public TId Id { get; set; } public List<BaseDomainEvent> Events = new List<BaseDomainEvent>(); } }
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 learn_180330_Graphics_1 { public partial class Form3 : Form { public Form3() { InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { int sum = Method.ConnectSql("SELECT sum(Count) FROM dbo.T_Constellation"); label1.Text += "(共" + sum + "票)"; } private void Form3_Paint(object sender, PaintEventArgs e) { //DrawRectangle(); DrawPie(); } private void DrawRectangle() { pictureBox1.Visible = false; Graphics gra = this.CreateGraphics(); string[] colstr = new string[] { "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "天秤座", "处女座", "天蝎座","射手座", "摩羯座", "水瓶座", "双鱼座" }; Color[] color = new Color[] { Color.LightBlue, Color.Yellow,Color.Green,Color.HotPink,Color.LightYellow,Color.LightSkyBlue,Color.LightGreen, Color.LightGray,Color.LightSeaGreen,Color.LemonChiffon,Color.YellowGreen,Color.Red}; try { Font font = new Font("宋体", 10, FontStyle.Regular); Font font1 = new Font("TIMES NEW ROMAN", 8, FontStyle.Regular); for (int i = 0; i < colstr.Length; i++) { gra.DrawString(colstr[i], font, new SolidBrush(Color.Black), new PointF(33, 40 * (i + 2))); } int sum = Method.ConnectSql("SELECT sum(Count) FROM dbo.T_Constellation"); DataSet ds = Method.GetData("select * from T_Constellation"); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DataRow dr = ds.Tables[0].Rows[i]; string colstr1 = dr["Constellation"].ToString(); int count = int.Parse(dr["Count"].ToString()); for (int j = 0; j < colstr.Length; j++) { if (colstr1 == colstr[j]) { gra.DrawString("(" + Math.Round((double)(count * 100) / sum, 2) + "%)", font1, new SolidBrush(Color.Black), new PointF(75, 40 * (j + 2))); Rectangle re = new Rectangle(130, 40 * (j + 2), (count * 200 / sum), 12); SolidBrush sBrush = new SolidBrush(color[j]); Pen pen = new Pen(sBrush, 2); gra.DrawRectangle(pen, re); gra.FillRectangle(sBrush, re); gra.DrawString(count.ToString(), font, new SolidBrush(Color.Black), new PointF(130, 40 * (j + 2))); break; } } } } catch (Exception ex) { throw new Exception(ex.ToString()); } } private void DrawPie() { pictureBox1.Visible =false; //Bitmap bmp2 = new Bitmap(300, 600); //Graphics gra = Graphics.FromImage(bmp2); Graphics gra = this.CreateGraphics(); string[] colstr = new string[] { "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "天秤座", "处女座", "天蝎座","射手座", "摩羯座", "水瓶座", "双鱼座" }; Color[] color = new Color[] { Color.LightBlue, Color.Yellow,Color.Green,Color.HotPink,Color.LightYellow,Color.LightSkyBlue,Color.LightGreen, Color.LightGray,Color.LightSeaGreen,Color.LemonChiffon,Color.YellowGreen,Color.Red}; try { Font font = new Font("宋体", 10, FontStyle.Regular); Font font1 = new Font("TIMES NEW ROMAN", 9, FontStyle.Regular); //for (int i = 0; i < colstr.Length; i++) //{ // gra.DrawString(colstr[i], font, new SolidBrush(Color.Black), new PointF(33, 40 * (i + 2))); //} int sum = Method.ConnectSql("SELECT sum(Count) FROM dbo.T_Constellation"); float angle = 0; DataSet ds = Method.GetData("select * from T_Constellation"); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DataRow dr = ds.Tables[0].Rows[i]; string colstr1 = dr["Constellation"].ToString(); int count = int.Parse(dr["Count"].ToString()); for (int j = 0; j < colstr.Length; j++) { if (colstr1 == colstr[j]) { //gra.DrawString("(" + Math.Round((double)(count * 100) / sum, 2) + "%)", font1, new SolidBrush(Color.Black), new PointF(75, 40 * (j + 2))); //Rectangle re = new Rectangle(130, 40 * (j + 2), (count * 200 / sum), 12); //SolidBrush sBrush = new SolidBrush(color[j]); //Pen pen = new Pen(sBrush, 2); //gra.DrawRectangle(pen, re); //gra.FillRectangle(sBrush, re); //gra.DrawString(count.ToString(), font, new SolidBrush(Color.Black), new PointF(130, 40 * (j + 2))); gra.FillPie(new SolidBrush(color[j]), 36, 100, 240,240, angle, (float)(count * 360) / sum); angle += (float)(count * 360) / sum; if (j < 6) { gra.FillRectangle(new SolidBrush(color[j]), 36, 400+20*j, 10, 10); gra.DrawString(colstr1 + "(" + count + "票)" + Math.Round((double)(count * 100) / sum, 2) + "%", font1, new SolidBrush(Color.Black), new PointF(50, 400 + 20 * j)); } else { gra.FillRectangle(new SolidBrush(color[j]), 180, 400 + 20 * (j-6), 10, 10); gra.DrawString(colstr1 + "(" + count + "票)" + Math.Round((double)(count * 100) / sum, 2) + "%", font1, new SolidBrush(Color.Black), new PointF(194, 400 + 20 * (j - 6))); } break; } } } //pictureBox1.Image = bmp2; } catch (Exception ex) { throw new Exception(ex.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace XFCovidTrack.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AvoidVirus : ContentPage { public AvoidVirus() { InitializeComponent(); List<avoid> avoid = new List<avoid>() { new avoid{Img = "tosse", Type= "Sintomas & Teste"}, new avoid{Img = "macara", Type= "Prevenção"}, new avoid{Img = "hosp", Type= "Postos de teste"}, }; listOfServicesAvoid.ItemsSource = avoid; } private void listOfServicesAvoid_SelectionChanged(object sender, SelectionChangedEventArgs e) { var type = (e.CurrentSelection.FirstOrDefault() as avoid).Type; if(type == "Sintomas & Teste") { Navigation.PushAsync(new SymptomsPage()); } else if (type == "Prevenção") { StringBuilder covid = new StringBuilder(); covid.AppendLine(""); covid.AppendLine(""); covid.AppendLine("* Limpe suas mãos frequentemente. Use sabão e água, ou esfregue as mãos à base de álcool."); covid.AppendLine(""); covid.AppendLine("* Mantenha uma distância segura de quem estiver tossindo ou espirrando."); covid.AppendLine(""); covid.AppendLine("* Não toque nos olhos, nariz ou boca."); covid.AppendLine(""); covid.AppendLine("* Cubra o nariz e a boca com o cotovelo dobrado ou um lenço de papel quando tossir ou espirrar."); covid.AppendLine(""); covid.AppendLine("* Fique em casa se não se sentir bem."); covid.AppendLine(""); covid.AppendLine("* Se você tiver febre, tosse e dificuldade em respirar, procure atendimento médico. Ligue com antecedência."); covid.AppendLine(""); covid.AppendLine("* Siga as instruções da sua autoridade sanitária local."); App.Current.MainPage.DisplayAlert("Para impedir a propagação do COVID-19:", covid.ToString(), "OK"); Navigation.PushAsync(new PreventionPage()); } else if(type == "Postos de teste") { Navigation.PushAsync(new HealthcarePage()); } Console.WriteLine(type); } } public class avoid { public string Img { get; set; } public string Type { get; set; } } }
using AutoFixture; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Moq; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using SFA.DAS.ProviderUrlHelper; using static SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice.EditApprenticeshipViewModelToValidateApprenticeshipForEditMapperTests; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.ApprenticesControllerTests { public class ApprenticeControllerTestFixtureBase { protected Fixture _autoFixture; protected Mock<IModelMapper> _mockMapper; protected Mock<ICommitmentsApiClient> _mockCommitmentsApiClient; protected Mock<ILinkGenerator> _mockLinkGenerator; protected Mock<IUrlHelper> _mockUrlHelper; protected Mock<ITempDataDictionary> _mockTempData; protected readonly ApprenticeController _controller; public ApprenticeControllerTestFixtureBase() { _autoFixture = new Fixture(); _autoFixture.Customize(new DateCustomisation()); _mockMapper = new Mock<IModelMapper>(); _mockCommitmentsApiClient = new Mock<ICommitmentsApiClient>(); _mockLinkGenerator = new Mock<ILinkGenerator>(); _mockUrlHelper = new Mock<IUrlHelper>(); _mockTempData = new Mock<ITempDataDictionary>(); _controller = new ApprenticeController(_mockMapper.Object, Mock.Of<ICookieStorageService<IndexRequest>>(), _mockCommitmentsApiClient.Object); _controller.Url = _mockUrlHelper.Object; _controller.TempData = _mockTempData.Object; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using Random = UnityEngine.Random; public class BoardManager : MonoBehaviour { [Serializable] public class Count { public int _minimum; public int _maximum; public Count(int min, int max) { _minimum = min; _maximum = max; } } public int Columns = 20; public int Rows = 20; public Count WallCount = new Count(5, 9); public Count FoodCount = new Count(1, 5); public GameObject Exit; public GameObject[] FloorTiles; public GameObject[] WallTiles; public GameObject[] FoodTiles; public GameObject[] EnemyTiles; public GameObject[] OuterWallTiles; private Transform _boardHolder; private List<Vector3> _gridPositions = new List<Vector3>(); void InitialiseList() { _gridPositions.Clear(); for (int x = 1; x < Columns - 1; x++) { for (int y = 1; y < Rows - 1; y++) { _gridPositions.Add(new Vector3(x, y, 0f)); } } } void BoardSetup() { _boardHolder = new GameObject("Board").transform; for (int x = -1; x < Columns + 1; x++) { for (int y = -1; y < Rows + 1; y++) { GameObject toInstantiate = FloorTiles[Random.Range(0, FloorTiles.Length)]; if (x == -1 || x == Columns || y == -1 || y == Rows) { toInstantiate = OuterWallTiles[Random.Range(0, OuterWallTiles.Length)]; } GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0), Quaternion.identity) as GameObject; instance.transform.SetParent(_boardHolder); } } } Vector3 RandomPosition() { int randomIndex = Random.Range(0, _gridPositions.Count); Vector3 randomPosition = _gridPositions[randomIndex]; _gridPositions.RemoveAt(randomIndex); return randomPosition; } void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum) { int objectCount = Random.Range(minimum, maximum + 1); for (int i = 0; i < objectCount; i++) { Vector3 randomPosition = RandomPosition(); GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)]; Instantiate(tileChoice, randomPosition, Quaternion.identity); } } public void SetupScene(int level) { //Creates the outer walls and floor. BoardSetup(); //Reset our list of gridpositions. InitialiseList(); //Instantiate a random number of wall tiles based on minimum and maximum, at randomized positions. LayoutObjectAtRandom(WallTiles, WallCount._minimum, WallCount._maximum); //Instantiate a random number of food tiles based on minimum and maximum, at randomized positions. LayoutObjectAtRandom(FoodTiles, FoodCount._minimum, FoodCount._maximum); //Determine number of enemies based on current level number, based on a logarithmic progression int enemyCount = (int)Mathf.Log(level, 2f); //Instantiate a random number of enemies based on minimum and maximum, at randomized positions. LayoutObjectAtRandom(EnemyTiles, enemyCount, enemyCount); //Instantiate the exit tile in the upper right hand corner of our game board Instantiate(Exit, new Vector3(Columns - (Random.Range(1, 3) == 1 ? 1 : Columns), Rows - Random.Range(1, Rows - 4), 0f), Quaternion.identity); } }
using Autofac; using cyrka.api.web.services; namespace cyrka.api.web._modules { public class WebModule : Module { protected override void Load(ContainerBuilder builder) { builder .RegisterGeneric(typeof(ProjectCommandService<>)); builder .RegisterGeneric(typeof(JobTypeCommandService<>)); builder .RegisterGeneric(typeof(CustomerCommandService<>)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraChange : MonoBehaviour { [SerializeField] Animator camerasAnimator; //[SerializeField] bool trocarIlha = true; [SerializeField] int nIlha; //[SerializeField] string nomeDaIlha; // [SerializeField] WaveSpawner pontosDeSpawn; // [SerializeField] List<GameObject> ilhas = new List<GameObject>(); private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("player")) { camerasAnimator.SetInteger("nIlha", nIlha); /*for (int i = 0; i < pontosDeSpawn.spawnPoints.Length; i++) { pontosDeSpawn.spawnPoints[i].position = ilhas[nIlha].transform.position + (Vector3.forward * 10); }*/ //camerasAnimator.SetBool("trocarDeIlha", trocarIlha); //StartCoroutine(TempoPraTrocar()); } } //private void OnTriggerEnter(Collider other) //{ // if(other.tag == "player") // { // camerasAnimator.SetInteger("nIlha", 0); // } //} //IEnumerator TempoPraTrocar() //{ // yield return new WaitForSeconds(1f); // trocarIlha = false; //} }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace LocusNew.Core.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim("ImageName", this.ImageName)); userIdentity.AddClaim(new Claim("FullName", this.FullName)); return userIdentity; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } public bool isAdmin { get; set; } public bool isAgent { get; set; } public bool isDev { get; set; } public bool isActive { get; set; } public string ImageName { get; set; } public string ImagePath { get; set; } public string AgentCardImageName { get; set; } public string AgentCardImagePath { get; set; } public string Designation { get; set; } [NotMapped] public string FullName { get { return FirstName + " " + LastName; } } } }
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.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace WaveBuilder { /// <summary> /// Interaction logic for KaraokeLineViewer.xaml /// </summary> public partial class KaraokeLineViewer : UserControl { #region Private Fields /// <summary> /// Source text /// </summary> private string sourceLine; #endregion #region Constructor /// <summary> /// Build karaoke line viewer from text line /// </summary> /// <param name="sourceLine">text source line</param> public KaraokeLineViewer(string sourceLine) { InitializeComponent(); this.sourceLine = sourceLine; textBlock.Text = sourceLine; } #endregion #region Protected Method /// <summary> /// Adjust blue bar's width /// </summary> /// <param name="noteCounter">note counter</param> internal void AdjustBlueBar(int noteCounter) { noteCounter++; while (noteCounter > 8) noteCounter -= 8; int desiredLength = (sourceLine.Length * noteCounter) / 8; string blueLine = sourceLine.Substring(0,desiredLength); Action action = new Action(delegate() {textBlockBlue.Text = blueLine; }); Dispatcher.Invoke(DispatcherPriority.Normal, action); } #endregion } }
using Core; using ServiceCenter.Helpers; using System.Windows; namespace ServiceCenter.View.Repair { public partial class FormOrderInfo : Window { public FormOrderInfo(Order order, Employee currentUser, Branch currentBranch, ICallbackUpdate callback, FormState formState = FormState.OnView) { InitializeComponent(); PageOrderInfo pageOrderInfo = new PageOrderInfo(); ViewModel.Repair.PageOrderInfoViewModel context = new ViewModel.Repair.PageOrderInfoViewModel(order, currentUser, currentBranch, callback, formState); pageOrderInfo.DataContext = context; frame_OrderInfo.NavigationService.Navigate(pageOrderInfo); } public FormOrderInfo(Branch currentBranch, Employee currentUser, ICallbackUpdate callback) { InitializeComponent(); PageOrderInfo pageOrderInfo = new PageOrderInfo(); ViewModel.Repair.PageOrderInfoViewModel context = new ViewModel.Repair.PageOrderInfoViewModel(currentBranch, currentUser, callback); pageOrderInfo.DataContext = context; frame_OrderInfo.NavigationService.Navigate(pageOrderInfo); } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Epam.Shops.Entities { public class Feedback { [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid Id { get; set; } [Required] public User User { get; set; } [Required] public Shop Shop { get; set; } public string Text { get; set; } public int Score { get; set; } public DateTime Date { get; set; } public Feedback() { Date = DateTime.Now; } } }
namespace Adapter { public class InHouseDeliveryService : IDeliveryService { public void ShipOrder(Order order) { System.Console.WriteLine($"Your order for {order.ProductName} is shipped using InHouseDelivery"); } } }
namespace _7DRL_2021.Pathfinding { using System.Collections.Generic; /// <summary> /// basic implementation of an UnweightedGraph. All edges are cached. This type of graph is best suited for non-grid based graphs. /// Any nodes added as edges must also have an entry as the key in the edges Dictionary. /// </summary> public class UnweightedGraph<T> : IUnweightedGraph<T> { public Dictionary<T,T[]> Edges = new Dictionary<T,T[]>(); public IEnumerable<T> GetNeighbors( T node ) { return this.Edges[node]; } } }
using AllianceReservations.Data; using System.Collections.Generic; namespace AllianceReservations.Entities { public class Person : Crud<Person> { private static readonly List<Person> Persons = new List<Person>(); public Address Address { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Person()//Needed default contructor because of XML { } public Person(string name, string lastName, Address address) { Id = null; FirstName = name; LastName = lastName; Address = address; } } public class Address : Crud<Address> { public string Place { get; set; } public string District { get; set; } public string State { get; set; } public string Zip { get; set; } public Address()//Needed default contructor because of XML { } public Address(string place, string district, string state, string zip) { Place = place; District = district; State = state; Zip = zip; } } public class Business : Crud<Business> { public Address Address { get; set; } public string Name { get; set; } public Business()//Needed default contructor because of XML { } public Business(string name, Address address) { Id = null; Name = name; Address = address; } } }
namespace GraphicalEditorServer.DTO { public class DivideRenovationDTO { public BaseRenovationDTO baseRenovation { get; set; } public string FirstRoomDescription { get; set; } public string SecondRoomDescription { get; set; } public TypeOfMapObject FirstRoomType { get; set; } public TypeOfMapObject SecondRoomType { get; set; } public DivideRenovationDTO() { } public DivideRenovationDTO(BaseRenovationDTO baseRenovation, string firstRoomDescription, string secondRoomDescription, TypeOfMapObject firstRoomType, TypeOfMapObject secondRoomType) { this.baseRenovation = baseRenovation; FirstRoomDescription = firstRoomDescription; SecondRoomDescription = secondRoomDescription; FirstRoomType = firstRoomType; SecondRoomType = secondRoomType; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LoginFrame { public partial class FrmQueryCustom : Form { DataTable dsLog; public FrmQueryCustom() //初始化组件 { InitializeComponent(); } private void dtp_publishDate_ValueChanged(object sender, EventArgs e) //选择日期 { this.txt_publishDate.Text = this.dtp_publishDate.Value.ToShortDateString(); } private void txt_publishDate_DoubleClick(object sender, EventArgs e) //双击日期框 清空 { this.txt_publishDate.Text = ""; } private void Btn_Query_Click(object sender, EventArgs e) //搜索条件 { string sqlstr = " where 1=1 "; if (this.Txt_Number.Text != "") { sqlstr += " and U_Number like '%" + this.Txt_Number.Text + "%'"; } if (this.Txt_Name.Text != "") { sqlstr += " and U_Name like '%" + this.Txt_Name.Text + "%'"; } if (this.Txt_Tel.Text != "") { sqlstr += " and U_Tel like '%" + this.Txt_Tel.Text + "%'"; } if (this.cb_Type.SelectedValue.ToString() != "0") { sqlstr += " and U_Grade=" + this.cb_Type.SelectedValue.ToString(); } if (this.Txt_Recommend.Text != "") { string number = this.Txt_Recommend.Text; int uid = DAL.performance.getC_ID(number); string UID=uid.ToString(); sqlstr += " and U_Introduce=" + UID; } if (this.txt_publishDate.Text != "") { sqlstr += " and convert(char(11),U_LoginDate,20) ='" + this.txt_publishDate.Text + "'"; } HWhere.Text = sqlstr; BindData(""); string rows = this.textBox1.Text; DAL.dalBook.Update ("U_Row",rows,1); } public void BindData(string strClass) { string Number=this.textBox1.Text; int number; if (int.TryParse(Number, out number)) { if (number < 40 && number > 10) { this.HPageSize.Text = Number; } } int DataCount = 0; int NowPage = 1; int AllPage = 0; int PageSize = Convert.ToInt32(HPageSize.Text); switch (strClass) //下一页 { case "next": NowPage = Convert.ToInt32(HNowPage.Text) + 1; break; case "up": NowPage = Convert.ToInt32(HNowPage.Text) - 1; break; case "end": NowPage = Convert.ToInt32(HAllPage.Text); break; case "refresh": NowPage = Convert.ToInt32(HNowPage.Text); break; default: break; } dsLog = BLL.bllBook.GetBook(NowPage, PageSize, out AllPage, out DataCount, HWhere.Text); if (dsLog.Rows.Count == 0 || AllPage == 1) { LBEnd.Enabled = false; LBHome.Enabled = false; LBNext.Enabled = false; LBUp.Enabled = false; } else if (NowPage == 1) { LBHome.Enabled = false; LBUp.Enabled = false; LBNext.Enabled = true; LBEnd.Enabled = true; } else if (NowPage == AllPage) { LBHome.Enabled = true; LBUp.Enabled = true; LBNext.Enabled = false; LBEnd.Enabled = false; } else { LBEnd.Enabled = true; LBHome.Enabled = true; LBNext.Enabled = true; LBUp.Enabled = true; } this.dataGridView_Book.DataSource = dsLog.DefaultView; PageMes.Text = string.Format("[每页{0}条 第{1}页/共{2}页 共{3}条]", PageSize, NowPage, AllPage, DataCount); HNowPage.Text = Convert.ToString(NowPage++); HAllPage.Text = AllPage.ToString(); if (dsLog.Rows.Count > 0) { this.Btn_Update.Enabled = true; this.Btn_Del.Enabled = true; } else { this.Btn_Update.Enabled = false; this.Btn_Del.Enabled = false; } } /*开始加载窗体后*/ private void FrmQueryBook_Load(object sender, EventArgs e) { this.cb_Type.DataSource = DAL.dalCustom.getType("CustomType","C_Id","C_Name"); this.cb_Type.DisplayMember = "C_Name"; this.cb_Type.ValueMember = "C_Id"; this.checkBox1.Checked = DAL.dalBook.getBool(1); this.textBox1.Text = DAL.dalBook.getString(1); this.HPageSize.Text = DAL.dalBook.getString(1); if(checkBox1.Checked) BindData(""); } private void LBHome_Click(object sender, EventArgs e) { BindData(""); } private void LBUp_Click(object sender, EventArgs e) { BindData("up"); } private void LBNext_Click(object sender, EventArgs e) { BindData("next"); } private void LBEnd_Click(object sender, EventArgs e) { BindData("end"); } private void Btn_Update_Click(object sender, EventArgs e) { if (((System.Windows.Forms.BaseCollection)(dataGridView_Book.SelectedRows)).Count != 1) { MessageBox.Show("请选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { String barcode = this.dataGridView_Book.CurrentRow.Cells[0].Value.ToString(); FrmAddCustom frmAddBook = new FrmAddCustom("update", barcode, this); frmAddBook.ShowDialog(); } } private void Btn_Del_Click(object sender, EventArgs e) { if (((System.Windows.Forms.BaseCollection)(dataGridView_Book.SelectedRows)).Count != 1) { MessageBox.Show("请选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { if (MessageBox.Show("删除吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK) { String barcode = this.dataGridView_Book.CurrentRow.Cells[0].Value.ToString(); if (BLL.bllBook.DelBook(barcode)) MessageBox.Show("删除成功!"); else MessageBox.Show("删除失败!"); BindData("refresh"); } } } private void button2_Click_1(object sender, EventArgs e) { FrmAddCustom frm = new FrmAddCustom(null, null, null); frm.ShowDialog(); /*string path="c:/ee.xls"; //测试 DAL.ExcelIO excel=new DAL.ExcelIO() ; DataTable dsLog = excel.ImportExcel(path); this.dataGridView_Book.DataSource = dsLog.DefaultView;*/ } private void dataGridView_Book_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { Btn_Update_Click(sender, e); } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) DAL.dalBook.Update("U_Check", "1", 1); else DAL.dalBook.Update("U_Check", "0", 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Plugin.Settings; using FuelRadar.Model; namespace FuelRadar.Settings { /// <summary> /// Provides access to the settings of the app /// </summary> public static class AppSettings { private const String FuelTypeKey = "fuelType"; private static readonly int FuelTypeDefault = 0; /// <summary> /// The user selected fuel type /// </summary> public static FuelType FuelType { get { return (FuelType)CrossSettings.Current.GetValueOrDefault<int>(FuelTypeKey, FuelTypeDefault); } set { CrossSettings.Current.AddOrUpdateValue<int>(FuelTypeKey, (int)value); } } } }
using Sales.Helpers; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Sales.Models { public class ClientAccount : ValidatableBindableBase { private int _id; public int ID { get { return _id; } set { SetProperty(ref _id, value); } } private DateTime _registrationDate; public DateTime RegistrationDate { get { return _registrationDate; } set { SetProperty(ref _registrationDate, value); } } private DateTime _date; [Column(TypeName = "Date")] public DateTime Date { get { return _date; } set { SetProperty(ref _date, value); } } private int _clientID; [Required(ErrorMessage ="العميل مطلوب")] public int ClientID { get { return _clientID; } set { SetProperty(ref _clientID, value); } } private string _statement; public string Statement { get { return _statement; } set { SetProperty(ref _statement, value); } } private string _url; public string Url { get { return _url; } set { SetProperty(ref _url, value); } } private string _details; public string Details { get { return _details; } set { SetProperty(ref _details, value); } } private decimal? _debit; public decimal? Debit { get { return _debit; } set { SetProperty(ref _debit, value); } } private decimal? _credit; public decimal? Credit { get { return _credit; } set { SetProperty(ref _credit, value); } } private bool _canDelete; public bool CanDelete { get { return _canDelete; } set { SetProperty(ref _canDelete, value); } } public virtual Client Client { get; set; } } public class ClientAccountVM : ValidatableBindableBase { private decimal? _withoutTotalDebit; public decimal? WithoutTotalDebit { get { return _withoutTotalDebit; } set { SetProperty(ref _withoutTotalDebit, value); } } private decimal? _withoutTotalCredit; public decimal? WithoutTotalCredit { get { return _withoutTotalCredit; } set { SetProperty(ref _withoutTotalCredit, value); } } private decimal? _withoutDuringAccount; public decimal? WithoutDuringAccount { get { return _withoutDuringAccount; } set { SetProperty(ref _withoutDuringAccount, value); } } private decimal? _withoutOldAccount; public decimal? WithoutOldAccount { get { return _withoutOldAccount; } set { SetProperty(ref _withoutOldAccount, value); } } private decimal? _withoutCurrentAccount; public decimal? WithoutCurrentAccount { get { return _withoutCurrentAccount; } set { SetProperty(ref _withoutCurrentAccount, value); } } private decimal? _discountTotalDebit; public decimal? DiscountTotalDebit { get { return _discountTotalDebit; } set { SetProperty(ref _discountTotalDebit, value); } } private decimal? _discountTotalCredit; public decimal? DiscountTotalCredit { get { return _discountTotalCredit; } set { SetProperty(ref _discountTotalCredit, value); } } private decimal? _discountDuringAccount; public decimal? DiscountDuringAccount { get { return _discountDuringAccount; } set { SetProperty(ref _discountDuringAccount, value); } } private decimal? _discountOldAccount; public decimal? DiscountOldAccount { get { return _discountOldAccount; } set { SetProperty(ref _discountOldAccount, value); } } private decimal? _discountCurrentAccount; public decimal? DiscountCurrentAccount { get { return _discountCurrentAccount; } set { SetProperty(ref _discountCurrentAccount, value); } } private decimal? _currentAccount; public decimal? CurrentAccount { get { return _currentAccount; } set { SetProperty(ref _currentAccount, value); } } } }
namespace TripDestination.Services.Data.Contracts { using System.Linq; using Common.Infrastructure.Models; using TripDestination.Data.Models; public interface ITripNotificationServices { IQueryable<TripNotification> GetAll(); TripNotification GetById(int id); IQueryable<Notification> GetForUser(string userId); IQueryable<Notification> GetNotSeenForUser(string userId); void SetAsSeen(int id); BaseResponseAjaxModel ApproveNotification(int notificationId, string userId); BaseResponseAjaxModel DisapproveNotification(int notificationId, string userId); void SetTripFinishActionHasBeenTakenToTrue(TripNotification tripNotification); TripNotification GetTripFinishTripNotificationByTripAndForUser(int tripId, string userId); } }
namespace gView.Interoperability.GeoServices.Exceptions { public class ExecuteQueryException : GeoServicesException { public ExecuteQueryException() : base("Failed to execute query.", 400) { } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Rendering; using Unity.EditorCoroutines.Editor; using UnityEditor.EditorTools; using UnityEditor.Experimental.TerrainAPI; namespace MileCode { public class LightEnv : ScriptableObject { public string sceneName = ""; [HideInInspector] public float tempLightIntensity = 1f; [HideInInspector] public int tempLightOnCount = 3; [HideInInspector] GameObject tempLight; [HideInInspector] public float tempLightAngle = 0; [HideInInspector] public bool environmentLightingDone = false; [HideInInspector] public Material bakedSkybox; public void GetEnvironmentLightingDone() { LightmapEditorSettings.lightmapper = LightmapEditorSettings.Lightmapper.ProgressiveGPU; LightmapEditorSettings.bakeResolution = 10; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.Iterative; Lightmapping.bakeCompleted += this.TurnOffAutoGenerate; } IEnumerator JustWaitAndRun(float seconds) { yield return new EditorWaitForSeconds(seconds); } private void TurnOffAutoGenerate() { JustWaitAndRun(1.0f); this.environmentLightingDone = true; this.bakedSkybox = RenderSettings.skybox; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; Lightmapping.bakeCompleted -= this.TurnOffAutoGenerate; } /* public void AfterLightingDone() { this.environmentLightingDone = true; this.bakedSkybox = RenderSettings.skybox; } */ public void SetLightEnvAngle(float lightAngle) { if(this.tempLight != null) { this.tempLight.transform.localEulerAngles = new Vector3(0, lightAngle, 0); } } public void SetLightEnvIntensity(float intensity) { if(this.tempLight != null) { Light[] lights = this.tempLight.GetComponentsInChildren<Light>(); if(lights != null && lights.Length >= 1) { foreach(Light light in lights) { if(light.transform.name == "light_0") { light.intensity = intensity; } else { light.intensity = intensity * 0.5f; } } } } } public string GetName() { return this.sceneName; } public void SetLightEnvOnNumber(int number) { if(this.tempLight != null) { Light[] lights = this.tempLight.GetComponentsInChildren<Light>(); if(lights != null && lights.Length >= 1) { switch(number) { case 0: lights[0].enabled = true; lights[1].enabled = false; lights[2].enabled = false; break; case 1: lights[0].enabled = true; lights[1].enabled = true; lights[2].enabled = false; break; case 2: lights[0].enabled = true; lights[1].enabled = true; lights[2].enabled = true; break; default: break; } } } } public void CreateEnvironment() { if(GameObject.Find("Temp Light") != null) { Debug.Log("Temp Light exsits."); return; } this.CreateLight(3); } public void RemoveEnvironment() { if(this.tempLight != null) { GameObject.DestroyImmediate(GameObject.Find("Temp Light")); } } public void RemoveTempLight() { GameObject tobeRemovedTempLight = GameObject.Find(this.name); if(tobeRemovedTempLight != null) { GameObject.DestroyImmediate(tobeRemovedTempLight); } } public void CreateLight(int lightNumber) { this.tempLight = new GameObject("Temp Light"); Vector3[] lightsAngles = new Vector3[] { new Vector3(40, 140, 0), new Vector3(50, -40, 0), new Vector3(-50, 0, 150) }; for(int i = 0; i < lightNumber; i++) { GameObject lightObj = new GameObject("light_" + i); Light light = lightObj.AddComponent<Light>(); light.type = LightType.Directional; if(i == 0) { light.intensity = this.tempLightIntensity; light.shadows = LightShadows.Soft; } else { light.intensity = this.tempLightIntensity * 0.5f; light.shadows = LightShadows.None; } light.transform.SetParent(this.tempLight.transform); lightObj.transform.localEulerAngles = lightsAngles[i]; } } [SerializeField] private string[] lightNames; [SerializeField] private Vector3[] lightsTransform_rotation; [SerializeField] [ColorUsage(true, false)] private Color[] lightColors; [SerializeField] private LightmapBakeType[] lightBakeType; [SerializeField] private float[] lightIntensity; [SerializeField] private float[] lightIndirectIntensity; [SerializeField] private LightShadows[] lightShadowType; public void SaveLightParams() { Light[] lights = Light.GetLights(LightType.Directional, 0); if(lights.Length <= 0) { Debug.Log("This scene has no directional light saved."); return; } this.lightNames = new string[lights.Length]; this.lightsTransform_rotation = new Vector3[lights.Length]; this.lightColors = new Color[lights.Length]; this.lightBakeType = new LightmapBakeType[lights.Length]; this.lightIntensity = new float[lights.Length]; this.lightIndirectIntensity = new float[lights.Length]; this.lightShadowType = new LightShadows[lights.Length]; for(int i = 0; i < lights.Length; i++) { lightNames[i] = lights[i].gameObject.name; lightsTransform_rotation[i] = lights[i].transform.rotation.eulerAngles; //Debug.Log(lightsTransform_rotation[i]); lightColors[i] = lights[i].color; lightBakeType[i] = lights[i].lightmapBakeType; lightIntensity[i] = lights[i].intensity; lightIndirectIntensity[i] = lights[i].bounceIntensity; lightShadowType[i] = lights[i].shadows; } //this.lightsTransform_rotation = lights[1].transform.rotation.eulerAngles; } public void UseLightFromScriptObject() { if(this.lightNames.Length <= 0) { Debug.Log("No direction lights in lightEnv"); return; } if(GameObject.Find(this.name) == null) { this.tempLight = new GameObject(this.name); for(int i = 0; i < lightNames.Length; i++) { GameObject lightObj = new GameObject(this.lightNames[i]); Light lightComponent = lightObj.AddComponent<Light>(); lightComponent.type = LightType.Directional; lightComponent.color = this.lightColors[i]; lightComponent.lightmapBakeType = this.lightBakeType[i]; lightComponent.intensity = this.lightIntensity[i]; lightComponent.bounceIntensity = this.lightIndirectIntensity[i]; lightComponent.shadows = this.lightShadowType[i]; lightObj.transform.eulerAngles = this.lightsTransform_rotation[i]; lightObj.transform.SetParent(this.tempLight.transform); } } } [SerializeField] private AmbientMode ambientMode; // if ambient mode is skybox [SerializeField] private float ambientIntensity = 1f; [SerializeField] private Material ambientSkybox = null; [SerializeField] [ColorUsage(false, false)] private Color ambientSkyboxColor; [SerializeField] [ColorUsage(false, true)] private Color[] ambientColors; [SerializeField] [ColorUsage(false, true)] private Color ambientFlatColor; // if ambient mode is flat public void SaveEnvironmentLighting() { ambientMode = RenderSettings.ambientMode; if(this.ambientMode == AmbientMode.Skybox) { this.ambientIntensity = RenderSettings.ambientIntensity; this.ambientSkybox = RenderSettings.skybox; if(this.ambientSkybox == null) { this.ambientSkyboxColor = RenderSettings.ambientSkyColor; } } if(this.ambientMode == AmbientMode.Flat) { this.ambientFlatColor = RenderSettings.ambientSkyColor; } if(this.ambientMode == AmbientMode.Trilight) { this.ambientColors = new Color[3]; this.ambientColors[0] = RenderSettings.ambientSkyColor; this.ambientColors[1] = RenderSettings.ambientEquatorColor; this.ambientColors[2] = RenderSettings.ambientGroundColor; } } public void UseEnvironmentLightFromScriptObject() { RenderSettings.ambientMode = this.ambientMode; if(this.ambientMode == AmbientMode.Skybox) { RenderSettings.ambientIntensity = this.ambientIntensity; if(this.ambientSkybox != null) { RenderSettings.skybox = this.ambientSkybox; } else { RenderSettings.skybox = null; RenderSettings.ambientSkyColor = this.ambientSkyboxColor; } } if(this.ambientMode == AmbientMode.Flat) { RenderSettings.ambientSkyColor = this.ambientFlatColor; } if(this.ambientMode == AmbientMode.Trilight) { RenderSettings.ambientSkyColor = this.ambientColors[0]; RenderSettings.ambientEquatorColor = this.ambientColors[1]; RenderSettings.ambientGroundColor = this.ambientColors[2]; } } [SerializeField] private DefaultReflectionMode defaultReflectionMode; [SerializeField] private Cubemap customReflectionProbe = null; [SerializeField] private float reflectionIntensity = 1; public void SaveReflectionProbe() { this.defaultReflectionMode = RenderSettings.defaultReflectionMode; if(this.defaultReflectionMode == DefaultReflectionMode.Skybox) { } if(this.defaultReflectionMode == DefaultReflectionMode.Custom) { if(RenderSettings.customReflection != null) { this.customReflectionProbe = RenderSettings.customReflection; } } this.reflectionIntensity = RenderSettings.reflectionIntensity; } public void UseReflectionProbeFromScriptObject() { RenderSettings.defaultReflectionMode = this.defaultReflectionMode; if(this.defaultReflectionMode == DefaultReflectionMode.Skybox) { } if(this.defaultReflectionMode == DefaultReflectionMode.Custom) { if(this.customReflectionProbe != null) { RenderSettings.customReflection = this.customReflectionProbe; } } RenderSettings.reflectionIntensity = reflectionIntensity; } [SerializeField] private Cubemap[] additionalReflectionCubeMaps; public void SaveAdditionalProbes() { ReflectionProbe[] probes = GameObject.FindObjectsOfType<ReflectionProbe>(); this.additionalReflectionCubeMaps = new Cubemap[probes.Length]; for(int i = 0; i < probes.Length; i++) { if(probes[i].mode == ReflectionProbeMode.Custom) { if(probes[i].customBakedTexture != null) { //Debug.Log(AssetDatabase.GetAssetPath(probes[i].customBakedTexture)); string CubemapLocation = AssetDatabase.GetAssetPath(probes[i].customBakedTexture); additionalReflectionCubeMaps[i] = AssetDatabase.LoadAssetAtPath<Cubemap>(CubemapLocation); } } else if(probes[i].mode == ReflectionProbeMode.Baked) { if(probes[i].bakedTexture != null) { //Debug.Log(AssetDatabase.GetAssetPath(probes[i].bakedTexture)); string CubemapLocation = AssetDatabase.GetAssetPath(probes[i].bakedTexture); additionalReflectionCubeMaps[i] = AssetDatabase.LoadAssetAtPath<Cubemap>(CubemapLocation); } } } } public bool HasAdditionalProbes() { if(this.additionalReflectionCubeMaps.Length >= 1) { return true; } else { return false; } } private int additionalProbeIndex = 0; public void UseAdditionalReflectionProbe() { //Debug.Log(additionalProbeIndex); RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom; RenderSettings.customReflection = this.additionalReflectionCubeMaps[additionalProbeIndex]; additionalProbeIndex++; if(additionalProbeIndex == this.additionalReflectionCubeMaps.Length) { additionalProbeIndex = 0; } } // ------------------- static --------------------- static List<GameObject> currentLights; public static void SaveCurrentLightEnv() { currentLights = GetSceneDirectionalLights(); } private static List<GameObject> GetSceneDirectionalLights() { List<GameObject> lights = new List<GameObject>(); Light[] allLight = Light.GetLights(LightType.Directional, 0); foreach(Light light in allLight) { lights.Add(light.gameObject); } //Debug.Log(lights.Count + " dir-light found and saved."); return lights; } public static void TurnOffSavedLightEnv() { //Debug.Log(currentLights.Count + " dir-light off."); if(currentLights != null) { if(currentLights.Count >= 1) { foreach(GameObject light in currentLights) { //Debug.Log(light.name); light.SetActive(false); } } } } public static void RestoreSavedLightEnv() { //Debug.Log(currentLights.Count + " dir-light restored."); if(currentLights != null) { if(currentLights.Count >= 1) { foreach(GameObject light in currentLights) { if(light != null) { light.SetActive(true); } } } } } public static void RestoreSavedLightEnv(EditorTool tool) { //Debug.Log(currentLights.Count + " dir-light restored."); if(EditorTools.activeToolType.Name != "LightEnvToolV2") { if(currentLights != null) { if(currentLights.Count >= 1) { foreach(GameObject light in currentLights) { if(light != null) { light.SetActive(true); } } } } } } } }
namespace Agora.EventStore { public class EventStoreServerConfiguration { public int ProcessingInterval = 250; } }
namespace ScheduleService.CustomException { public class DataStorageException : ScheduleServiceException { public DataStorageException() : base() { } public DataStorageException(string message) : base(message) { } } }
namespace LightingBook.Test.Api.Common.Dto { public class SearchHotelLocation { public double? Latitude { get; set; } public double? Longitude { get; set; } public string Name { get; set; } public string Type { get; set; } public string City { get; set; } public string Country { get; set; } public int? RadiusDistance { get; set; } public string Code { get; set; } public string Location { get; set; } public string CountryCode { get; set; } public bool? IsInternational { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebsiteManagerPanel.Data.Entities.Base; namespace WebsiteManagerPanel.Data.Entities { public class FieldItem : AuditEntity { public FieldItem(string value) { Value = value; } public FieldValue FieldValue { get; protected set; } public string Value { get; protected set; } public void Update(string fieldValue) { Value = fieldValue; } } }
using System.Buffers; namespace SuperSocket.ProtoBase { /// <summary> /// FixedSizeReceiveFilter /// 固定请求大小的协议在这种协议之中, 所有请求的大小都是相同的。 /// 如果你的每个请求都是有9个字符组成的字符串,如"KILL BILL", 你应该做的事就是想如下代码这样实现一个接收过滤器(ReceiveFilter): /// </summary> /// <typeparam name="TPackageInfo"></typeparam> public class FixedSizePipelineFilter<TPackageInfo> : PipelineFilterBase<TPackageInfo> where TPackageInfo : class { private int _size; protected FixedSizePipelineFilter(int size) { _size = size; } public override TPackageInfo Filter(ref SequenceReader<byte> reader) { if (reader.Length < _size) return null; var pack = reader.Sequence.Slice(0, _size); try { return DecodePackage(pack); } finally { reader.Advance(_size); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace POSServices.WebAPIInforModel { public class InforStore { public string CONO { get; set; } public string DIVI { get; set; } public string RSTN { get; set; } public string WHLO { get; set; } public string TX40 { get; set; } public string TOWN { get; set; } public string STCE { get; set; } public string CUNO { get; set; } } public class ResultStore { public string transaction { get; set; } public IList<InforStore> records { get; set; } } public class InforStoreAPI { public IList<ResultStore> results { get; set; } public bool wasTerminated { get; set; } public int nrOfSuccessfullTransactions { get; set; } public int nrOfFailedTransactions { get; set; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class RealAngusSelectedButtonParent : MonoBehaviour { InOutTransitioner transitioner; Image image; float selectedBackgroundAlpha = 0.4f; void Awake() { image = GetComponent<Image> (); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { MaybeMakeTransitioner (); if (!transitioner.IsTransitioning()) { if (transitioner.GetFractionIn () == 0) { gameObject.SetActive (false); } return; } UpdateSelectionState (); } void UpdateSelectionState() { transitioner.UpdateTransitionFraction (); UpdateImage (); } void UpdateImage() { float fractionIn = transitioner.GetFractionIn (); image.color = new Color (0, 0, 0, selectedBackgroundAlpha * fractionIn); } public void StartVisibilityTransition(bool visible) { MaybeMakeTransitioner (); transitioner.Transition (visible); if (visible) { gameObject.SetActive(true); UpdateImage(); } } void MaybeMakeTransitioner() { if (transitioner == null) { transitioner = new InOutTransitioner (TweakableParams.realAngusSelectionFadeTime); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ezconet.GerenciamentoProjetos.Domain.Contracts.Services { public interface ISolicitacaoDomainService { void Cadastrar(Entities.SolicitacaoEntity solicitacao); } }
using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Exceptionless; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using Pobs.Web.Helpers; namespace Pobs.Web.Middleware { public class FeatureLoggingMiddleware { private readonly RequestDelegate _next; private readonly IOptions<AppSettings> _appSettings; public FeatureLoggingMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings) { _next = next; _appSettings = appSettings; } public async Task Invoke(HttpContext context) { var stopwatch = Stopwatch.StartNew(); await _next(context); stopwatch.Stop(); if (_appSettings.Value.ExceptionlessApiKey != null) { try { var routeData = context.GetRouteData(); var controller = routeData.Values["controller"] as string; if (controller == "Health") { return; } var action = routeData.Values["action"] as string; var method = context.Request.Method; var featureName = $"{method}-{controller}-{action}"; var exceptionlessClient = new ExceptionlessClient(_appSettings.Value.ExceptionlessApiKey); var feature = exceptionlessClient.CreateFeatureUsage(featureName) .SetProperty("RequestDurationMilliseconds", stopwatch.ElapsedMilliseconds) .SetProperty("UserAgent", context.Request.Headers[HeaderNames.UserAgent].ToString()); foreach (var value in routeData.Values) { if (value.Key != "controller" && value.Key != "action") { feature.SetProperty(value.Key, value.Value); } } if (context.User.Identity.IsAuthenticated) { feature.SetUserIdentity(context.User.Identity.Name); } feature.Submit(); } catch { // Ignore } } } } public static class FeatureLoggingMiddlewareExtensions { public static IApplicationBuilder UseFeatureLogging(this IApplicationBuilder builder) { return builder.UseMiddleware<FeatureLoggingMiddleware>(); } } }
using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.Common.Excepcion; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.DA.Sharepoint; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BELCORP.GestorDocumental.DDP.TJ_VerificarFlagEjecucion { public class TJ_VerificarFlagEjecucion : SPJobDefinition { public const string JobName = "TJ_VerificarFlagEjecucion"; #region Constructores public TJ_VerificarFlagEjecucion() : base() { } public TJ_VerificarFlagEjecucion(string jobName, SPService service) : base(jobName, service, null, SPJobLockType.None) { this.Title = "Timer Job Verificar Flag Ejecucion"; } public TJ_VerificarFlagEjecucion(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.Job) { this.Title = "Timer Job Verificar Flag Ejecucion"; } #endregion public override void Execute(Guid targetInstanceId) { try { bool ejecutarAhora = false; SPSecurity.RunWithElevatedPrivileges(delegate () { SPWebApplication webApp = this.Parent as SPWebApplication; string Url_GestorDocumental = webApp.Sites[0].Url; if (string.IsNullOrEmpty(Url_GestorDocumental)) throw new ErrorPersonalizado("URL de Sitio DDP no está configurado"); using(SPSite oSPSite = new SPSite(Url_GestorDocumental)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { SPList list = oSPWeb.Lists.TryGetList(Constantes.NombreListas.ConfiguracionJob); if (list != null) { SPListItemCollection spliConfiguracionJob = SharePointHelper.ObtenerInformacionLista(oSPWeb, Constantes.NombreListas.ConfiguracionJob, string.Empty); if (spliConfiguracionJob != null) { foreach (SPListItem itemConfiguracion in spliConfiguracionJob) { ejecutarAhora = SharePointUtil.ObtenerValorBoolSPField(itemConfiguracion, "EjecutarAhora"); if (ejecutarAhora) { string nombreJob = SharePointUtil.ObtenerValorStringSPField(itemConfiguracion, "NombreJob"); var remoteAdministratorAccessDenied = SPWebService.ContentService.RemoteAdministratorAccessDenied; SPJobDefinitionCollection myJobsColl = webApp.JobDefinitions; if (webApp == null) throw new SPException("Error obtaining refrence to the Web."); var traceJobs = (from jobDefinition in webApp.JobDefinitions where jobDefinition.DisplayName == nombreJob select jobDefinition); foreach (SPJobDefinition job in traceJobs) { if (!job.IsDisabled) job.RunNow(); } itemConfiguracion["EjecutarAhora"] = false; itemConfiguracion.Update(); oSPWeb.Update(); } } } } } } }); } catch (ErrorPersonalizado ep) { //Se escribe en el log de sharepoint Logging.RegistrarMensajeLogSharePoint( Constantes.CATEGORIA_LOG_TJ_ACTUALIZAR_LISTAMAESTRA, JobName, TraceSeverity.High, EventSeverity.Error, ep); //Se lanza el error para que se registre en el historial del timer job throw; } catch (Exception ex) { //Se escribe en el log de sharepoint Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_TJ_ACTUALIZAR_LISTAMAESTRA, JobName, ex); //Se lanza el error para que se registre en el historial del timer job throw; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ToilluminateClient { public partial class MessageForm : Form { private bool showMessageFlag = false; private MainForm parentForm; private Control[] messageControls; #region " override " protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) { int WM_KEYDOWN = 256; int WM_SYSKEYDOWN = 260; if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN) { switch (keyData) { case Keys.Escape: parentForm.MaxShowThis(true); break; case Keys.Space: parentForm.MaxShowThis(false); break; } } return false; } #endregion public MessageForm() { InitializeComponent(); this.BackColor = ImageApp.BackClearColor; this.TopMost = true; this.TransparencyKey = ImageApp.BackClearColor; this.StartPosition = FormStartPosition.Manual; this.FormBorderStyle = FormBorderStyle.None; messageControls = new Control[] { this.pnlMessage0, this.pnlMessage1, this.pnlMessage2, this.pnlMessage3, this.pnlMessage4, this.pnlMessage5 }; foreach (Control pnlMessage in messageControls) { pnlMessage.Left = -10; pnlMessage.Top = -10; pnlMessage.Width = 1; pnlMessage.Height = 1; pnlMessage.BackColor = ImageApp.BackClearColor; pnlMessage.SendToBack(); } } public void tmrShow_Tick(object sender, EventArgs e) { try { this.tmrShow.Stop(); if (PlayApp.ExecutePlayList != null) { if (PlayApp.ExecutePlayList.PlayListState == PlayListStateType.Stop) { CloseMessage(); return; } } ThreadShow(); ImageApp.MyDrawMessage(this.messageControls[0]); } catch (Exception ex) { LogApp.OutputErrorLog("MessageForm", "tmrMessage_Tick", ex); } finally { this.tmrShow.Start(); } } private void MessageForm_Load(object sender, EventArgs e) { this.tmrShow.Interval = 10; } private void MessageForm_Shown(object sender, EventArgs e) { ShowApp.MessageBackBitmap = new Bitmap(this.Width, this.Height); } private void MessageForm_FormClosing(object sender, FormClosingEventArgs e) { } private void MessageForm_FormClosed(object sender, FormClosedEventArgs e) { } #region " Show Message " public void ThreadShow() { Thread tmpThread = new Thread(this.ThreadShowMessageVoid); tmpThread.IsBackground = true; tmpThread.Start(); } private void ThreadShowMessageVoid() { if (showMessageFlag) { return; } try { showMessageFlag = true; if (PlayApp.ExecutePlayList != null) { foreach (MessageTempleteItem mtItem in PlayApp.ExecutePlayList.MessageTempleteItemList) { if (mtItem.TempleteState != TempleteStateType.Stop) { if (mtItem.TempleteState == TempleteStateType.Wait) { mtItem.ExecuteStart(); } mtItem.ShowCurrent(this); break; } } } } catch (Exception ex) { LogApp.OutputErrorLog("MessageForm", "ThreadShowMessageVoid", ex); } finally { showMessageFlag = false; } } /// <summary> /// 显示信息 /// </summary> /// <param name="mtItem"></param> private void CloseMessage() { try { ShowApp.NowMessageIsShow = false; this.tmrShow.Stop(); foreach (MessageTempleteItem mtItem in PlayApp.ExecutePlayList.MessageTempleteItemList) { mtItem.ExecuteRefresh(); } } catch (Exception ex) { throw ex; } } public void SetMainForm(MainForm mainForm) { parentForm = mainForm; } #endregion private void MessageForm_SizeChanged(object sender, EventArgs e) { try { foreach (DrawMessage dmItem in ShowApp.DrawMessageList) { dmItem.SetParentSize(this.Width, this.Height); } if (ShowApp.DownLoadDrawMessage != null && ShowApp.DownLoadDrawMessage.DrawStyleList.Count > 0) { ShowApp.DownLoadDrawMessage.SetParentSize(this.Width, this.Height); } } catch (Exception ex) { LogApp.OutputErrorLog("MessageForm", "MessageForm_SizeChanged", ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HMSApp.Models { /// <summary> /// Entity to hold user information /// </summary> public class User { /// <summary> /// First Name /// </summary> public string FirstName { get; set; } /// <summary> /// Last Name /// </summary> public string LastName { get; set; } /// <summary> /// Middle Inital /// </summary> public string MiddleInitial { get; set; } /// <summary> /// Address /// </summary> public Address Address { get; set; } /// <summary> /// User Id /// </summary> public string UserId { get; set; } /// <summary> /// User Type /// </summary> public UserType UserType { get; set; } } /// <summary> /// User Type Enum /// </summary> public enum UserType { /// <summary> /// Admin User /// </summary> Admin, /// <summary> /// Front Office Staff /// </summary> FrontOffice, /// <summary> /// Physician /// </summary> Physician } }
using System; using System.Collections.Generic; using System.Text; namespace Paged { //public static class extendClass //{ // // 比如,我要给List<gameProduct>这个泛型集合添加一个MyPrint方法。我们可以这样做,注意函数签名. // //public static String MyPrint(this IEnumerable<object> list) // //{ // // String rt = ""; // // IEnumerator<object> eartor = list.GetEnumerator();// 获得枚举器 // // rt += "{\n"; // // while (eartor.MoveNext()) // // { // // rt += eartor.Current.ToString() + ",\n"; // // } // // rt += "}"; // // return rt; // //} //} //public }
using RomashkaBase.Model; using RomashkaBase.ViewModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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.Navigation; using System.Windows.Shapes; namespace RomashkaBase.View { /// <summary> /// Логика взаимодействия для CompaniesAndUsersView.xaml /// </summary> public partial class CompaniesAndUsersView : Page { CompaniesAndUsersViewModel companiesAndUsersViewModel; public CompaniesAndUsersView(ApplicationContext db) { InitializeComponent(); companiesAndUsersViewModel = new CompaniesAndUsersViewModel(db); DataContext = companiesAndUsersViewModel; } public void ChangeData(ObservableCollection<Company> companies) { companiesAndUsersViewModel.Companies = companies; } } }
namespace SharpStoreDB { using System; using System.Data.Entity; using System.Linq; public class SharpStoreDBcontex : DbContext { public SharpStoreDBcontex() : base("name=SharpStoreDB") { } public virtual DbSet<Knife> Knives { get; set; } public virtual DbSet<Message> Messages { get; set; } } }
namespace SimpleHttpServer.Helpers { using System; using Models; using System.Collections.Generic; using System.Net; using Contracts; using Cookie = Models.Cookie; using CookieCollection = Models.CookieCollection; public static class WebUtils { public static Dictionary<string, string> GetRequestParams(HttpRequest request) { string requestContent = WebUtility.UrlDecode(request.Content); string[] parameters = requestContent.Split('&'); Dictionary<string, string> nameValuePairs = new Dictionary<string, string>(); foreach (var parameter in parameters) { string[] parameterInfo = parameter.Split('='); nameValuePairs.Add(parameterInfo[0], parameterInfo[1]); } return nameValuePairs; } public static ICookieCollection GetCookies() { string cookieContent = Environment.GetEnvironmentVariable("HTTP_COOKIE"); if (cookieContent == "") { return new CookieCollection(); } string[] cookiesArgs = cookieContent.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var cookies = new CookieCollection(); foreach (var cookiesArg in cookiesArgs) { var cookieName = cookiesArg.Split('=')[0]; var cookieValue = cookiesArg.Split('=')[1]; var cookie = new Cookie(cookieName, cookieValue); cookies.AddCookie(cookie); } return cookies; } } }
1>------ Build started: Project: Classes, Configuration: Debug Any CPU ------ 1> Classes -> C:\Users\erau\Desktop\mssa\VCSBS\Chapter 7\Classes\Classes\bin\Debug\Classes.exe ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
using System; namespace CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.Configuration { public class ApiSettings { public Uri Uri { get; set; } } }
using Assets.Scripts.SaveLoad; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Xml; using UnityEngine; /// <summary> /// Management object for a <see cref="Game"/>. /// </summary> public class GameManager : MonoBehaviour { #region Member /// <summary> /// The current game. /// </summary> private Game _game; private ChemicalEntryListFill _entryFill; #endregion Member // Start is called before the first frame update void Start() { _game = Game.New(); _entryFill = FindObjectOfType<ChemicalEntryListFill>(); UpdateEntryList(); InstantiateChemicals(_game.ActiveChemicals, Vector3.zero); } public void Combine(IEnumerable<IChemical> chemicals) { var newChemicals = _game.Combine(chemicals); if(newChemicals.Any()) { var active = FindObjectsOfType<ChemicalBehaviour>(); // destroy old chemicals Vector3? firstRemovedPosition = null; foreach (var removedChemical in chemicals) { var toDestroy = active.First(c => c.Chemical == removedChemical).gameObject; if (!firstRemovedPosition.HasValue) firstRemovedPosition = toDestroy.transform.position; Destroy(toDestroy); } // create new chemicals InstantiateChemicals(newChemicals, firstRemovedPosition ?? Vector3.zero); UpdateEntryList(); } } public IChemical AddChemicalToWorkspace(string name) { var newChemical = _game.AddChemicalToWorkspace(name); return newChemical; } public void Clone(ChemicalBehaviour chemical) { var newChemical = AddChemicalToWorkspace(chemical.Chemical.Name); InstantiateChemicals(new[] { newChemical }, chemical.transform.position + (Vector3)new Vector2(.1f, .1f)); } #region Save / Load /// <summary> /// Saves the game to file. /// </summary> public void SaveGame() { var chemicals = FindObjectsOfType<ChemicalBehaviour>().Select(c => new ChemicalBehaviourData(c.Chemical.Name, c.transform.position)).ToList(); var saveData = new FullSaveData(chemicals, GameSaveData.FromGame(_game)); var serializer = new DataContractSerializer(typeof(FullSaveData)); using (var w = XmlWriter.Create("game.xml", new XmlWriterSettings { Indent = true })) serializer.WriteObject(w, saveData); } /// <summary> /// Loads the game from file. /// </summary> public void LoadGame() { FullSaveData saveData; var serializer = new DataContractSerializer(typeof(FullSaveData)); using (var fs = new FileStream("game.xml", FileMode.Open)) { saveData = (FullSaveData)serializer.ReadObject(fs); } ClearWorkspace(); _game = Game.FromGameData(saveData.GameSaveData); foreach (var ch in saveData.ActiveChemicalBehaviours) InstantiateChemical(new Chemical(ch.ChemicalName), ch.Position); UpdateEntryList(); } #endregion Save / Load public void ClearWorkspace() { _game.CleanUp(); var ac = FindObjectsOfType<ChemicalBehaviour>(); foreach (var c in ac) Destroy(c.gameObject); } private void InstantiateChemicals(IEnumerable<IChemical> chemicals, Vector2 position) { foreach (var newChemical in chemicals) { InstantiateChemical(newChemical, position); } } private void InstantiateChemical(IChemical chemical, Vector2 position) { var obj = Instantiate(Resources.Load<GameObject>("Prefabs/Chemical"), position, Quaternion.identity); obj.GetComponent<ChemicalBehaviour>().Chemical = chemical; } private void UpdateEntryList() { _entryFill.UpdateEntries(_game.UnlockedChemicals); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fly : MonoBehaviour { private Rigidbody rb; private enum JumpPhases {Idle, Up, Down}; private JumpPhases jumpPhase; void Start () { rb = GetComponent<Rigidbody>(); jumpPhase = JumpPhases.Idle; // Remove Jump if exists var jump = this.gameObject.GetComponent("Jump"); if(jump){ Destroy(jump); } } void FixedUpdate () { if (Input.GetKeyDown("space") && jumpPhase == JumpPhases.Idle){ StartCoroutine(JumpPhaseChanger()); Vector3 movement = new Vector3 (0, 300, 0); rb.AddForce (movement); } } IEnumerator JumpPhaseChanger() { jumpPhase = JumpPhases.Up; yield return new WaitForSeconds(0.2f); jumpPhase = JumpPhases.Down; yield return new WaitForSeconds(0.2f); jumpPhase = JumpPhases.Idle; } }
using System.Collections; using System.Collections.Generic; using Pixelplacement; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class BarTween : MonoBehaviour { [SerializeField] float start; [SerializeField] float end; [SerializeField] float speed; [SerializeField] float interval; [SerializeField] AnimationCurve pulseCurve; void Start() { Image image = GetComponent<Image>(); Tween.Value(start, end, (val) => image.fillAmount = val, speed, interval, pulseCurve, Tween.LoopType.Loop, completeCallback: () => image.fillAmount = 0f, obeyTimescale: false); } }
using System; namespace EventFeed.Consumer.EventFeed { public interface IEventDispatcher { void Dispatch(Event @event, Action markEventAsProcessed); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using PROnline.Models.HeartWishes; using PROnline.Models; using PROnline.Src; namespace PROnline.Controllers.HeartWish { public class HeartWishTypeController : Controller { private PROnlineContext db = new PROnlineContext(); // // GET: /HeartWishType/ public ViewResult Index() { ViewBag.User = Utils.CurrentUser(this); return View(db.HeartWishType.Where(n => n.isDeleted == false).ToList()); } //下拉框,未删除的心声类型 public SelectList HeartWishTypeDropDownList() { var list = from c in db.HeartWishType where c.isDeleted == false orderby c.TypeName select c; return new SelectList(list.ToList(), "HeartWishTypeID", "TypeName"); } // // GET: /HeartWishType/Details/5 //得到一条心声类型条目,以及其属于的所有心声条目 public ViewResult Details(Guid id) { HeartWishType type = db.HeartWishType.Find(id); var list = from c in db.HeartWish where c.isDeleted == false && c.HeartWishTypeID == id && c.VerifyingState=="通过" select c; ViewBag.list = list.ToList(); return View(type); } // // GET: /HeartWishType/Create public ActionResult Create() { return View(); } //类型名称重复验证 [HttpGet] public JsonResult HeartWishTypeNameAvailable(String TypeName, Guid HeartWishTypeID) { if (HeartWishTypeID == new Guid("00000000-0000-0000-0000-000000000000")) { //create var list = from c in db.HeartWishType where c.TypeName == TypeName && c.isDeleted == false select c; return Json(!(list.Count() > 0), JsonRequestBehavior.AllowGet); } else { //edit var list = from c in db.HeartWishType where c.TypeName == TypeName && c.HeartWishTypeID != HeartWishTypeID && c.isDeleted == false select c; return Json(!(list.Count() > 0), JsonRequestBehavior.AllowGet); } } // // POST: /HeartWishType/Create [HttpPost] [ValidateInput(false)] public ActionResult Create(HeartWishType type) { if (ModelState.IsValid) { type.HeartWishTypeID = Guid.NewGuid(); type.CreatorID = Utils.CurrentUser(this).Id; type.CreateDate = DateTime.Now; type.isDeleted = false; db.HeartWishType.Add(type); db.SaveChanges(); return RedirectToAction("Index"); } return View(type); } // // GET: /HeartWishType/Edit/5 public ActionResult Edit(Guid id) { HeartWishType type = db.HeartWishType.Find(id); return View(type); } // // POST: /HeartWishType/Edit/5 [HttpPost] [ValidateInput(false)] public ActionResult Edit(HeartWishType type) { if (ModelState.IsValid) { HeartWishType temp = db.HeartWishType.Find(type.HeartWishTypeID); temp.TypeName = type.TypeName; temp.Introduction = type.Introduction; temp.ReplyUserType = type.ReplyUserType; temp.Comment = type.Comment; temp.ModifierID = Utils.CurrentUser(this).Id; temp.ModifyDate = DateTime.Now; db.Entry(temp).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(type); } // // GET: /HeartWishType/Delete/5 public ActionResult Delete(Guid id) { HeartWishType type = db.HeartWishType.Find(id); return View(type); } // // POST: /HeartWishType/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(Guid id) { HeartWishType type = db.HeartWishType.Find(id); type.isDeleted = true; type.ModifierID = Utils.CurrentUser(this).Id; type.ModifyDate = DateTime.Now; db.Entry(type).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
using System; namespace _3_zadanie { class Program { static void Main(string[] args) { Logger logger = new Logger(); logger.Logs = logger.Loop; logger.Logs += delegate { for (int i = 1; i < 5; i++) { Console.WriteLine(i); } }; logger.Logs += () => { for (int i = 1; i < 5; i++) { Console.Write(i); } }; void LocalLoop () { for (int i = 1; i < 5; i++) { Console.WriteLine(i); } } logger.Logs += LocalLoop; logger.GetLogs(); } } class Logger { public Action Logs; public void GetLogs() { foreach (var d in Logs.GetInvocationList()) { var invoke = (Action)d; invoke.Invoke(); } } public void Loop() { for (int i = 1; i < 5; i++) { Console.Write(i); } } } }
using UnityEngine; using System.Collections; public class ChangeToSize : MonoBehaviour { [SerializeField] float sizeMultiplier = 1; public float SizeMultiplier { get { return sizeMultiplier; } set { sizeMultiplier = value; } } void Awake () { GetComponent<IsMergeable>().UpdatedSize += UpdateSize; UpdateSize(GetComponent<IsMergeable>().size); } void OnDisable () { GetComponent<IsMergeable>().UpdatedSize -= UpdateSize; } public void UpdateSize(float size) { float curentScale = size*sizeMultiplier; gameObject.transform.localScale = new Vector3(.3f+curentScale, .3f+curentScale, .3f+curentScale); } }