text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ManageAppleStore_BUS; using ManageAppleStore_DTO; namespace ManageAppleStore_GUI { public partial class frmLogin : Form { public frmLogin() { InitializeComponent(); } #region Properties public delegate void DGLogin(bool bTrangThai, EmployeesDTO nvDangNhap); public DGLogin DLogin; public static EmployeesDTO EmpLogin = null; BindingList<EmployeesDTO> LstEmp = null; public static EmployeesDTO EmpSelected = null; Point LastPoint; #endregion #region Methods #endregion #region Events private void frmLogin_Load(object sender, EventArgs e) { this.Visible = false; Util.EndAnimate(this, Util.Effect.Center, 150, 180); txtID.TabIndex = 0; txtPassword.TabIndex = 1; btnLogin.TabIndex = 2; btnExit.TabIndex = 3; lblError.Visible = false; txtID.Focus(); LstEmp = EmployeesBUS.loadListBUS(); } private void btnLogin_Click(object sender, EventArgs e) { if (LstEmp == null) { MessageBox.Show("Chưa Có Nhân Viên Nào Trong Danh Sách!"); } else { if (txtID.Text == string.Empty) { DevExpress.XtraEditors.XtraMessageBox.Show("Bạn chưa nhập tài khoản", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); lblError.Location = new Point(241, 82); lblError.Visible = true; txtID.Focus(); } else if (txtPassword.Text == string.Empty) { DevExpress.XtraEditors.XtraMessageBox.Show("Bạn chưa nhập mật khẩu", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); lblError.Location = new Point(241, 138); lblError.Visible = true; txtPassword.Focus(); } else { lblError.Visible = false; EmpSelected = new EmployeesDTO(); // Khởi tạo. bool BCheckID = false, BCheckPas = false; foreach (EmployeesDTO Emp in LstEmp) { if (txtID.Text == Emp.StrNumberPhone) { BCheckID = true; if (txtPassword.Text == Emp.StrPassword) { BCheckPas = true; } } if (BCheckID && BCheckPas) { EmpSelected = Emp; EmpLogin = Emp; break; } } if (BCheckID && BCheckPas) { if (DLogin != null) { DLogin(true, EmpSelected); this.Close(); } } else if (!BCheckID) { DevExpress.XtraEditors.XtraMessageBox.Show("Sai Tài Khoản!", "Thông Báo"); lblError.Visible = true; lblError.Location = new Point(241, 82); txtID.Focus(); } else if (!BCheckPas) { DevExpress.XtraEditors.XtraMessageBox.Show("Sai Mật Khẩu!", "Thông Báo"); lblError.Visible = true; lblError.Location = new Point(241, 138); txtPassword.Focus(); } } } } private void btnExit_Click(object sender, EventArgs e) { Util.EndAnimate(this, Util.Effect.Center, 150, 30); this.Close(); } private void frmLogin_MouseDown(object sender, MouseEventArgs e) { LastPoint = new Point(e.X, e.Y); } private void frmLogin_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Left += e.X - LastPoint.X; this.Top += e.Y - LastPoint.Y; } } #endregion } }
using FixyNet.Clases; using FixyNet.Clases.Listas; using FixyNet.Forms; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FixyNet.Clases { class MonitorClass { private Discovery toolPing = new Discovery(); private Grafico grafico = new Grafico(); public event EventHandler CerrarClass; public List<ListaGrafico> listaGraficos = new List<ListaGrafico>(); public int tiempoPooleo = 500; public Timer Reloj = new Timer(); private bool detengoMonitor = false; public void ShowMonitor() { grafico.formGrafico.Show(); grafico.CerrarClass += (s, e) => { InvocarDetener(); }; } public void InvocarDetener() { detengoMonitor = true; this.CerrarClass?.Invoke(this, EventArgs.Empty); } public async Task Monitoreo() { if (detengoMonitor == false) { ShowMonitor(); List<ListaIpMonAct> listaIpMonitor = new List<ListaIpMonAct>(); DispositivosClass dispositivos = new DispositivosClass(); await dispositivos.listaMonActivo(); listaIpMonitor = dispositivos.listaReturn; var tasks = new List<Task>(); foreach (ListaIpMonAct lista in listaIpMonitor) { var task = Monitorear(lista.ip, lista.uuid_dispositivo); tasks.Add(task); } await Task.WhenAny(tasks).ContinueWith(t => { // MessageBox.Show("Dsp: " + listaIpMonitor.Count()); for (int i = 0; i < listaIpMonitor.Count(); i++) { if (tasks[i].Status != TaskStatus.RanToCompletion) { i = 1; } } var taUno = Task.Run(() => grafico.cantidadDispositivos = listaIpMonitor.Count()); taUno.Wait(); var taDos = Task.Run(() => grafico.listaGraficos = listaGraficos); taDos.Wait(); var taTres = Task.Run(() => grafico.Iniciar()); taTres.Wait(); }); listaGraficos.Clear(); // MessageBox.Show(grafico.listaGraficos.Count.ToString()); Reloj.Start(); Reloj.Interval = tiempoPooleo; var taEspera = Task.Run(() => RelojTick()); taEspera.Wait(); } if (detengoMonitor == false) { await Monitoreo(); } } private bool RelojTick() { while (Reloj.Equals(tiempoPooleo)) { } Reloj.Stop(); return true; } private async Task Monitorear(string ipp, string uuid_dispositivo) { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); toolPing.ip = ipp; EventosClass evento = new EventosClass { uuid_dispositivo = uuid_dispositivo }; if (await toolPing.PingAsync(p) == false) { var t = Task.Run(() => listaGraficos.Add(new ListaGrafico { ip = ipp, uuid_dispositivo = uuid_dispositivo, estado = "Error" })); t.Wait(); await evento.addEvento("Error", toolPing.tiempoResp); } else { var t = Task.Run(() => listaGraficos.Add(new ListaGrafico { ip = ipp, uuid_dispositivo = uuid_dispositivo, estado = "Success" })); t.Wait(); await evento.addEvento("Success", toolPing.tiempoResp); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class PlayerUI : MonoBehaviour { public void Show() { gameObject.BroadcastMessage("ShowTMPUI", SendMessageOptions.DontRequireReceiver); GetComponent<TextMeshProUGUI>().enabled = true; } public void Hide() { gameObject.BroadcastMessage("HideTMPUI", SendMessageOptions.DontRequireReceiver); GetComponent<TextMeshProUGUI>().enabled = false; } public void SetValue(int position, int value) { transform.GetChild(position).GetComponent<TextMeshProUGUI>().text = value + ""; } }
using System; using System.Collections.Generic; using System.Linq; using Business.DTO; using Business.Exceptions; namespace Business.Rules { public static class ShortestRoute { private static Dictionary<String, List<String>> dictRoute; public static string GetRoute(string origin, string destin, List<RouteDTO> allRoutes) { if (allRoutes.All(a => a.Origin != origin) && allRoutes.All(a => a.Destin != destin)) { throw new ValidationException("No Route"); } if (dictRoute == null) { dictRoute = new Dictionary<string, List<string>>(); foreach (var route in allRoutes) { if (dictRoute.ContainsKey(route.Origin)) { dictRoute[route.Origin].Add(route.Destin); } else { dictRoute[route.Origin] = new List<string> {route.Destin}; } } } var resultRoute = BFSRoute(origin, destin); if(String.IsNullOrEmpty(resultRoute)) throw new ValidationException("No Route"); return resultRoute; } private static string BFSRoute(string origin, string destin) { var listNodesToVisit = new List<NodeRoute>(); var listNodesVisited = new List<NodeRoute>(); listNodesToVisit.Add(new NodeRoute{Code = origin}); var result = string.Empty; while (listNodesToVisit.Any()) { var currentNode = listNodesToVisit[0]; listNodesToVisit.RemoveAt(0); listNodesVisited.Add(currentNode); if (currentNode.Code == destin) { while (currentNode.Code != origin) { result = string.IsNullOrEmpty(result) ? currentNode.Code: currentNode.Code+ " -> " + result; currentNode = listNodesVisited.First(a => a.Code == currentNode.ParentCode); } return origin + " -> " + result; } var childs = dictRoute[currentNode.Code]; foreach (var child in childs) { if (listNodesVisited.All(a => a.Code != child)) { var childNode = new NodeRoute { Code = child, ParentCode = currentNode.Code }; listNodesToVisit.Add(childNode); } } } return string.Empty; } } public class NodeRoute { public string Code { get; set; } public string ParentCode { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMotor : MonoBehaviour { public float maxSpeed; public float speed; public float acceleration; public float deceleration; public float maxWithWeight; public float currentSpeed; public float Accelerate() { speed += acceleration * Time.deltaTime; speed = Mathf.Clamp(speed, 0, maxWithWeight); return speed; } public float Decelerate() { speed -= deceleration * Time.deltaTime; speed = Mathf.Clamp(speed, 0, maxWithWeight); return speed; } public float MaxSpeedValue(float LibeeCount) { if (LibeeCount > 0) { maxWithWeight = maxSpeed - Mathf.Pow(LibeeCount, 0.5f); return maxWithWeight; } else { maxWithWeight = maxSpeed; return maxWithWeight; } } }
/** 版本信息模板在安装目录下,可自行修改。 * OA_EDUTEST.cs * * 功 能: N/A * 类 名: OA_EDUTEST * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2014/7/22 15:35:27 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; namespace PDTech.OA.Model { /// <summary> /// 试卷表 /// </summary> [Serializable] public partial class OA_EDUTEST { public OA_EDUTEST() {} #region Model private string _edu_t_guid; private string _testname; private decimal? _creator; private DateTime? _createtime; private DateTime? _hopefinishtime; private DateTime? _finishtime; private decimal? _testcount; private decimal? _score; /// <summary> /// 试卷主键 /// </summary> public string EDU_T_GUID { set{ _edu_t_guid=value;} get{return _edu_t_guid;} } /// <summary> /// 试卷名称 /// </summary> public string TESTNAME { set{ _testname=value;} get{return _testname;} } /// <summary> /// 试卷创建人 /// </summary> public decimal? CREATOR { set{ _creator=value;} get{return _creator;} } /// <summary> /// 试卷创建时间 /// </summary> public DateTime? CREATETIME { set{ _createtime=value;} get{return _createtime;} } /// <summary> /// 试题总数 /// </summary> public decimal? TESTCOUNT { set { _testcount = value; } get { return _testcount; } } /// <summary> /// 试卷总分 /// </summary> public decimal? SCORE { set { _score = value; } get { return _score; } } /// <summary> /// 期望完成日期 /// </summary> public DateTime? HOPEFINISHTIME { set{_hopefinishtime=value;} get { return _hopefinishtime; } } /// <summary> /// 实际完成日期 /// </summary> public DateTime? FINISHTIME { set { _finishtime = value; } get { return _finishtime; } } #endregion Model } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Net.Sockets; using System.Timers; using System.Threading; using System.Threading.Tasks; namespace PIT_Server { public static class VisitorBase { static ConcurrentDictionary<Agent, object> Visitors = new ConcurrentDictionary<Agent, object>(50,10000); public static void NewVisitor(Socket visitor) { Agent c = new Agent(visitor); Visitors.TryAdd(c, null); Logger.LogIt(typeof(VisitorBase), "New Visitor " + c.Name + ":" + visitor.LocalEndPoint.ToString()); c.Start(); } public static void DeleteVisitor(Agent agent) { object o; Visitors.TryRemove(agent, out o); agent.Dispose(); Logger.LogIt(typeof(VisitorBase), "Visitor disconnected "+ agent.Name); } public static List<Agent> GetVisitors() { return new List<Agent>(Visitors.Keys); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cognitive_Metier { public class ResultSentimentJson { public List<DocumentSentimentResult> documents { get; set; } public List<Error> errors { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using BehaviourMachine; public class BM_Chase : StateBehaviour { Agent m_agent; GameObjectVar target; Vector3Var destination; [SerializeField] private float ticks = .2f; float sqrDistanceToTarget; public float distanceToReachTarget = 1.5f; float sqrDistanceToReachTarget; // Called when the state is enabled void OnEnable () { Debug.Log("Started Chase"); m_agent = GetComponent<Agent>(); Setup(); SetAgentSpeed(); StartCoroutine(StartChasing()); } // Called when the state is disabled void OnDisable () { Debug.Log("Stopped Chase"); StopAllCoroutines(); } //sets up all references and proper metrics void Setup() { m_agent = GetComponent<Agent>(); target = blackboard.GetGameObjectVar("Target"); destination = blackboard.GetVector3Var("Destination"); sqrDistanceToReachTarget = distanceToReachTarget * distanceToReachTarget; } //Changes agent properties to run from walk private void SetAgentSpeed() { m_agent.m_navAgent.speed = m_agent.agentProperties.RunSpeed; m_agent.m_navAgent.angularSpeed = m_agent.agentProperties.RunAngularSpeed; m_agent.m_navAgent.acceleration = m_agent.agentProperties.RunAcceleration; } //Calculate the distance from target to player position void calculateDistanceFromTarget() { sqrDistanceToTarget = (target.transform.position - transform.position).sqrMagnitude; } //Begins chasing the player IEnumerator StartChasing() { while (enabled) { //sets the destination for the agent to target the player's position if (target.Value != null) { calculateDistanceFromTarget(); destination.Value = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z); m_agent.m_navAgent.SetDestination(destination.Value); } //changes the state of the agent once it reaches a certain distance to the target if (sqrDistanceToTarget < sqrDistanceToReachTarget) { SendEvent("ReachedTarget"); yield return null; } yield return new WaitForSeconds(ticks); } } }
using Sunny.HttpRequestClientManager.Helper; using Sunny.Lib; using Sunny.Lib.Xml; 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 Sunny.HttpRequestClientManager.UI { public partial class PopupCategory : Form { string _categoryName = string.Empty; public PopupCategory(string categoryName) { InitializeComponent(); this._categoryName = categoryName; LoadCategoryInfo(); } private void LoadCategoryInfo() { if (string.IsNullOrEmpty(_categoryName)) { return; } string xPath = string.Format(CategoryInfo.XPath_Get_FilterByCategoryName, _categoryName); CategoryInfo categoryInfo = XMLSerializerHelper.DeserializeByXPath<CategoryInfo>(xPath, Const.WebRequestConfigFileFullPath); if (categoryInfo != null) { richTB_Message.Text = categoryInfo.Remarks; } } private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(_categoryName)) { return; } string remarks = richTB_Message.Text.Trim(); CategoryInfo categoryInfo = new CategoryInfo() { CategoryName = _categoryName, Remarks = remarks }; string xPath = string.Format(CategoryInfo.XPath_Get_FilterByCategoryName, _categoryName); if (XMLHelperUtility.GetSpecialNodeValues(xPath, Const.WebRequestConfigFileFullPath).Count > 0) { XMLHelper.Update(categoryInfo, Const.WebRequestConfigFileFullPath, xPath); } else { XMLHelper.Add(categoryInfo, Const.WebRequestConfigFileFullPath, CategoryInfo.XPath1); } } private void richTB_Message_MouseDoubleClick(object sender, MouseEventArgs e) { this.Close(); } } }
using System.Linq; using System.Threading.Tasks; using TestApplicationDomain.Entities; using TestApplicationInterface.Repository; namespace TestApplicationDB.Repository { public class HotelContactRepository : Repository<HotelContact>, IHotelContactRepository { public HotelContactRepository(DbFactory dbFactory) : base(dbFactory) { } public Task<IQueryable<HotelContact>> GetHotelContacts(string hotelId) { return Task.Run(() => Get(x => x.Hotel.Id == hotelId)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces; namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels { public class VehicleViewModel : PropertyChangedBase { public VehicleViewModel(Vehicle entity) { VehicleEntity = entity; VehicleCategoryViewModel = new VehicleCategoryViewModel(entity.VehicleCategory); OrganizationUnitViewModelModel = new OrganizationUnitViewModel(entity.OrganizationUnit); } public OrganizationUnitViewModel OrganizationUnitViewModelModel { get; private set; } public VehicleCategoryViewModel VehicleCategoryViewModel; public Vehicle VehicleEntity { get; private set; } public String SerialNumber { get { return VehicleEntity.SerialNumber; } set { if (value == VehicleEntity.SerialNumber) return; if (value.Length == 0) return; VehicleEntity.SerialNumber = value; NotifyOfPropertyChange(()=>SerialNumber); } } public String VehicleManufacturer { get { return VehicleEntity.VehicleManufacturer; } set { if (value == VehicleEntity.VehicleManufacturer) return; if (value.Length == 0) return; VehicleEntity.VehicleManufacturer = value; NotifyOfPropertyChange(()=>VehicleManufacturer); } } public String ModelName { get { return VehicleEntity.ModelName; } set { if (value == VehicleEntity.ModelName) return; if (value.Length == 0) return; VehicleEntity.ModelName = value; NotifyOfPropertyChange(()=>ModelName); } } public String OrganizationUnitName { get { return OrganizationUnitViewModelModel.Name; } } public String VehicleCategoryName { get { return VehicleCategoryViewModel.CategoryName; } } } public class VehicleDetailedViewModel : PropertyChangedBase { public VehicleDetailedViewModel(VehicleViewModel vehicleViewModel, IVehicleAttributesService vehicleAttributesService) { _vehicleAttributesService = vehicleAttributesService; VehicleViewModel = vehicleViewModel; var attributes = VehicleViewModel.VehicleEntity.VehicleAttributeValues; VehicleAttributeValues = new BindableCollection<TypedAttributeValueViewModel>(); foreach (var buildingAttributeValue in attributes) { var attributeValueViewModel = new VehicleAttributeValueViewModel(buildingAttributeValue); TypedAttributeValueViewModel typedAttributeValueViewModel; switch (attributeValueViewModel.DataType) { case DataTypes.Int: typedAttributeValueViewModel = new IntAttributeValueViewModel(attributeValueViewModel); break; case DataTypes.Double: typedAttributeValueViewModel = new DoubleAttributeValueViewModel(attributeValueViewModel); break; case DataTypes.DateTime: typedAttributeValueViewModel = new DateTimeAttributeValueViewModel(attributeValueViewModel); break; case DataTypes.String: typedAttributeValueViewModel = new StringAttributeValueViewModel(attributeValueViewModel); break; default: throw new NotImplementedException(); } VehicleAttributeValues.Add(typedAttributeValueViewModel); } } public VehicleViewModel VehicleViewModel { get; private set; } public BindableCollection<TypedAttributeValueViewModel> VehicleAttributeValues { get; private set; } private IVehicleAttributesService _vehicleAttributesService; public void SaveChages() { foreach (var typedAttributeValueViewModel in VehicleAttributeValues) { _vehicleAttributesService.UpdateVehicleAttributesValue(((VehicleAttributeValueViewModel)typedAttributeValueViewModel.AbstractAttributeValueViewModel).VehicleAttributeValueEntity); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using mainApp = Android.App; using Android.Support.V4.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace jumpHelper { public class DeleteConfirmationDialog : DialogFragment { private const string FORMATION = "Formation"; private const string COMMENT = "Comment"; public static DeleteConfirmationDialog NewInstance(string formation, string comment) { DeleteConfirmationDialog fragment = new DeleteConfirmationDialog(); Bundle args = new Bundle(); args.PutString(FORMATION, formation); args.PutString(COMMENT, comment); fragment.Arguments = args; return fragment; } public override mainApp.Dialog OnCreateDialog(Bundle savedInstanceState) { mainApp.AlertDialog.Builder builder = new mainApp.AlertDialog.Builder(Activity); string formation = Arguments.GetString(FORMATION); string comment = Arguments.GetString(COMMENT); builder .SetTitle("Confirm delete") .SetMessage("Are you sure you want to remove a comment \"" + comment + "\" for formation " + formation) .SetPositiveButton("Delete", async (senderAlert, args) => { Dismiss(); await FSNotesHandler.removeComment(formation, comment); }) .SetNegativeButton("Cancel", (senderAlert, args) => { AppEventHandler.emitInfoTextUpdate("Delete cancelled"); }); return builder.Create(); } } }
namespace InfernoInfinity.Models.Weapons { public abstract class Weapon { } }
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 DiaxeirisiPoiotitas { public partial class Ergazomenoi : Form { public Ergazomenoi() { InitializeComponent(); } private void cancelBtn_Click(object sender, EventArgs e) { } private void thesiBtn_Click(object sender, EventArgs e) { Theseis form1 = new Theseis(); form1.ShowDialog(); } private void prosonBtn_Click(object sender, EventArgs e) { Prosonta form1 = new Prosonta(); form1.ShowDialog(); } private void empiriaBtn_Click(object sender, EventArgs e) { Empeiries form1 = new Empeiries(); form1.ShowDialog(); } private void axiolBtn_Click(object sender, EventArgs e) { Axiologiseis form1 = new Axiologiseis(0); form1.ShowDialog(); } private void maskedTextBox2_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace oopsconcepts { public class Enumes { public static void Main() { Console.WriteLine("List of Enums"); Array list = Enum.GetValues(typeof(Months)); foreach (var item in list) { Console.WriteLine(item.GetHashCode() + " values are " + item); } Console.ReadLine(); } } public enum Months { Jan = 1, Feb = 2, Mar = 3, April = 4, May = 5, June = 6, July = 7, August = 8, Sep = 9, Oct = 10, Nov = 11, Dec = 12 } }
using System; using System.Text.Json; using System.Text.Json.Serialization; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CryptobotUi.Models.Cryptodb { [Table("signal", Schema = "public")] public partial class Signal { [NotMapped] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("@odata.etag")] public string ETag { get; set; } [Key] public Int64 signal_id { get; set; } public IEnumerable<SignalCommand> SignalCommands { get; set; } [ConcurrencyCheck] public DateTime created_date_time { get; set; } [ConcurrencyCheck] public DateTime? updated_date_time { get; set; } [ConcurrencyCheck] public Int64 exchange_id { get; set; } public Exchange Exchange { get; set; } [ConcurrencyCheck] public Int64 strategy_pair_id { get; set; } public Strategy Strategy { get; set; } [ConcurrencyCheck] public string symbol { get; set; } [ConcurrencyCheck] public string strategy_pair_name { get; set; } [ConcurrencyCheck] public string position_type { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Menu : MonoBehaviour { public void GoToScene(string name) { SceneManager.LoadScene(name); } public void StartGame() { GameManager.Instance.StartGame(); } public void GoToStartMenu() { GameManager.Instance.GoToStartMenu(); } public void GoToLoadScreen() { GameManager.Instance.GoToLoadScreen(); } public void QuitGame() { GameManager.Instance.QuitGame(); } }
using System; using System.Net; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace Shelly_Server { class SocketHandler { public static string CertPath; public static string CertPass; private static IPAddress localAdd = IPAddress.Parse(Program.Ip); private static TcpListener listener = new TcpListener(localAdd, Program.Port); private static TcpClient client; private static byte[] Buffer; private static SslStream sslStream; // Listen method public static void Listen() { // Start listener listener.Start(); // Accept incoming connection(client) client = listener.AcceptTcpClient(); // Stop listener listener.Stop(); } // Connect method public static void Connect() { // Create new sslstream instace and validate certificate sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); // Create new certificate instance X509Certificate2 cert = new X509Certificate2(CertPath, CertPass); // Authenticate as server sslStream.AuthenticateAsServer(cert, false, SslProtocols.Tls, true); // Set receive timeout sslStream.ReadTimeout = 12000; } // ValidateServerCertificate method public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } // Disconnect method public static void Disconnect() { // Close socket client.Close(); // Set console title Console.Title = "Disconnected"; } // ShutdownServer method public static void ShutdownServer() { // Stop the disconnectionHandler thread Program.disconnectionHandler.Abort(); // Disconnect Disconnect(); // Display message Console.Clear(); Console.WriteLine("Client disconnected"); Thread.Sleep(2500); // Exit Environment.Exit(0); } // GetClientIp method public static string GetClientIp() { // Get client ip IPEndPoint ClientIp = client.Client.RemoteEndPoint as IPEndPoint; // Set variables string input = ClientIp.ToString(); int index = input.IndexOf(":"); // Check if index is greater than 0 if (index > 0) { // Trim string input = input.Substring(0, index); } // Return client ip return input; } // Send method public static void Send(string Message) { // Disable connection checking CheckConnection = false; // Write to the stream sslStream.Write(Encoding.ASCII.GetBytes(" " + Message), 0, Message.Length + 1); // Sleep for a short period of time to make sure the client receives the data Thread.Sleep(100); // Enable connection checking CheckConnection = true; } // Receive method private static string TrimSpace; public static string Receive() { // Setup buffer Buffer = new byte[client.ReceiveBufferSize]; // Read incoming data and strip front space for (int i = 0; i < 2; i++) { TrimSpace = Encoding.ASCII.GetString(Buffer, 0, sslStream.Read(Buffer, 0, Buffer.Length)); } // Return data received return TrimSpace; } // ConnectionStatus method public static bool CheckConnection = true; public static string ConnectionStatus() { // Try to send data to client try { // Check if CheckConnection is equal to true if (CheckConnection == true) { // Write to the stream, send message manually to avoid cross thread errors sslStream.Write(Encoding.ASCII.GetBytes(" " + "."), 0, ".".Length + 1); // Return true if operation succeeded return "true"; } else { // Return false if operation failed return "nc"; } } catch { // Return false, connection is down return "false"; } } } }
using System; namespace yocto.tests.morebad { public static class AssemblyRegistration { public static void Initialize(object notacontainer, object stillnotacontainer) { } } }
using System; using UnityEngine; namespace RO { internal class MaterialHandler_SetChangeColor : MaterialHandler { public Color color; public void Handle(Material m, int i, int j) { if (null != m) { RolePart.SetChangeColor(m, this.color); } } } }
/* Name: Nick Lai Student ID#: 2282417 Chapman email: lai137@mail.chapman.edu Course Number and Section: Panther Games 10/26 Workshop Acts as a container for text objects to be updated by other logic. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class pgUIManager : MonoBehaviour { public pgGameManager gm; public Text timerText; public Text collectibleText; public Text messageText; // Use this for initialization void Start () { gm = GetComponentInParent<pgGameManager>(); messageText.text = "Grab the flashlight!"; } //updates the timer via the GameManager public void DrawTimerText() { timerText.text = gm.timeRemaining.ToString(); } }
using System.Collections.Generic; using System.Linq; namespace FileSearch { public class FilenameContainsFilter : BaseFileFilter, IFileFilter { private readonly IList<string> _wildcards; public FilenameContainsFilter(IList<string> wildcards) { _wildcards = wildcards .Select(s => s.ToUpperInvariant()) .Where(s => !string.IsNullOrWhiteSpace(s)) .OrderBy(s => s) .ToList(); } #region IFileFilter Members public override bool ShouldFilter(IExtendedFileInfo extendedFileInfo) { var filename = extendedFileInfo.Name.ToUpperInvariant(); return !_wildcards.Any(filename.Contains); } #endregion IFileFilter Members } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerHeal : MonoBehaviour { public void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "Heal") { Fuelbar fuelStats = GameObject.FindGameObjectWithTag("fuelhealth").GetComponent<Fuelbar>(); } } }
namespace GdNet.Common.Services { /// <summary> /// Encrypt and decrypt a string /// </summary> public interface IStringEncryptionWorker { /// <summary> /// Encrypt a string /// </summary> string Encrypt(string plainText, string passPhrase); /// <summary> /// Decrypt a string /// </summary> string Decrypt(string cipherText, string passPhrase); } }
namespace PasswordValidator.Demo.Web.Models { public class ManuallyRunningTheValidatorModel { public string Password { get; set; } public bool IsPasswordAcceptable { get; set; } } }
using System.Collections.Generic; using buildings; using UnityEngine; using UnityEngine.UI; using UI.StorageModal; class StorageModal : MonoBehaviour { public Button CloseButton = null; public GameObject Panel = null; public GameObject DataTablePanel = null; public DataRow DataRowPrefab = null; private static StorageModal _instance; public static StorageModal Instance { get { if (!_instance) { _instance = FindObjectOfType(typeof(StorageModal)) as StorageModal; if(!_instance) Debug.LogError("Can't find modal"); } return _instance; } } public void OnClickCloseBtn() { Panel.SetActive(false); } public void Show(Storage storage) { var children = new List<Transform>(); foreach (Transform child in DataTablePanel.transform) children.Add(child); children.ForEach(child => Destroy(child.gameObject)); foreach (var itemPack in storage.items) { var row = Instantiate(DataRowPrefab); row.transform.SetParent(DataTablePanel.transform); row.Set(itemPack.Key, itemPack.Value.ToString()); } Panel.SetActive(true); } }
namespace Project.Client.Web.Entities { public class BrokenData : BaseData { public string Line { get; set; } public string Message { get; set; } } }
using System.Threading; using System.Threading.Tasks; using MediatR; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Workspace; namespace SampleServer { internal class DidChangeWatchedFilesHandler : IDidChangeWatchedFilesHandler { public DidChangeWatchedFilesRegistrationOptions GetRegistrationOptions() => new DidChangeWatchedFilesRegistrationOptions(); public Task<Unit> Handle(DidChangeWatchedFilesParams request, CancellationToken cancellationToken) => Unit.Task; public DidChangeWatchedFilesRegistrationOptions GetRegistrationOptions(DidChangeWatchedFilesCapability capability, ClientCapabilities clientCapabilities) => new DidChangeWatchedFilesRegistrationOptions(); } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; using ToDoApp.Db; using ToDoApp.Db.Domain; namespace ToDoApp.Api.Repositories { public class UserRepository : IUserRepository { private readonly ToDoAppContext _context; public UserRepository(ToDoAppContext context) { _context = context; // throw } public async Task<User> GetById(Guid id) { return await _context.Users.SingleOrDefaultAsync(u => u.Id == id); } public async Task<User> GetByEmail(string email) { return await _context.Users.SingleOrDefaultAsync(u => u.Email.ToLower() == email.ToLower()); } public async Task<User> GetByUsername(string username) { return await _context.Users.SingleOrDefaultAsync(u => u.Username.ToLower() == username.ToLower()); } public async Task<ICollection<User>> GetAll() { return await _context.Users.ToListAsync(); } public async Task<bool> Add(User user) { _context.Users.Add(user); return await _context.SaveChangesAsync() > 0; } public async Task<bool> Remove(User user) { _context.Remove(user); return await _context.SaveChangesAsync() > 0; } public async Task<bool> Update(User user) { return await _context.SaveChangesAsync() > 0; } } }
using Employees.Data; using MediatR; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Employees.Feature.AppState { public class AddToastAction : IRequest<AppState> { public string Header { get; set; } public string Body { get; set; } } public class DelToastAction : IRequest<AppState> { public ToastItem Item { get; set; } } public class LogInAction : IRequest<AppState> { public F0601161Row AbRow { get; set; } } public class LogOutAction : IRequest<AppState> { } }
using System.Collections.ObjectModel; using System.Threading.Tasks; using Kit.Model; using Xamarin.Forms; namespace Kit.Forms.Controls.NotificationBar { public class Notificaciones : StaticModel<Notificaciones> { private static Notificaciones _Instance; public static Notificaciones Instance { get => _Instance; set { _Instance = value; OnGlobalPropertyChanged(); } } public ObservableCollection<Notificacion> Elementos { get; private set; } public static Notificaciones Init() { NotificationBar.Notificaciones.Instance = new NotificationBar.Notificaciones(); return Instance; } public Notificaciones() { this.Elementos = new ObservableCollection<Notificacion>(); } ~Notificaciones() { } private async Task Notificar(Notificacion Notificacion) { await Device.InvokeOnMainThreadAsync(() => { this.Elementos.Add(Notificacion); }); } private async Task Remove(Notificacion notificacion) { await Device.InvokeOnMainThreadAsync(() => { this.Elementos.Remove(notificacion); }); } } }
using System; namespace Queue { public class DoublyLinkedList { private Node _head; private Node _tail; public void AddFirst(int number) { Node newNode = new Node() { Data = number }; if (_head == null) { _head = newNode; _tail = newNode; } else { _head.Prev = newNode; newNode.Next = _head; _head = newNode; } } public void RemoveLast() { if (_tail != null) { _tail = _tail.Prev; _tail.Next = null; } } public Node GetFirst() { return _head; } public int GetTail() { return _tail.Data; } public void PrintList() { PrintList(_head); Console.Write("[X]"); Console.WriteLine(); } private void PrintList(Node node) { if (node != null) { Console.Write("[" + node.Data + "]--->"); PrintList(node.Next); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; namespace Library { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css") .Include("~/Content/*.css")); bundles.Add(new ScriptBundle("~/bundles/serverValidation") .Include("~/Scripts/jquery-{version}.js", "~/Scripts/jquery.validate.js", "~/Scripts/jquery.validate.unobtrusive.js")); bundles.Add(new ScriptBundle("~/bundles/mainScripts") .Include("~/Scripts/script.js")); bundles.Add(new ScriptBundle("~/bundles/jquery") .Include("~/Scripts/jquery-{version}.js")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumeraciones { class Program { static void Main(string[] args) { Console.WriteLine(DiasDeLaSemana.Lunes); Console.WriteLine((int)DiasDeLaSemana.Lunes); DiasDeLaSemana diaMartes = DiasDeLaSemana.Martes; Console.WriteLine(diaMartes); // Dia martes suponiendo que lo cargo desde la base de datos DiasDeLaSemana unDia = (DiasDeLaSemana)1; Console.WriteLine(unDia); Console.ReadKey(); } } }
// Author: Tigran Gasparian // This sample is part Part One of the 'Getting Started with SQLite in C#' tutorial at http://www.blog.tigrangasparian.com/ using System; using System.Data.SQLite; namespace SQLiteSamples { public class SqLiteEasy { // Holds our connection with the database SQLiteConnection _mDbConnection; // Creates an empty database file public void Connection(string filePath) { SQLiteConnection.CreateFile(filePath); // Creates a connection with our database file. _mDbConnection = new SQLiteConnection("Data Source="+filePath+";Version=3;"); _mDbConnection.Open(); } // Creates a table named 'highscores' with two columns: name (a string of max 20 characters) and score (an int) public void Query(string queryText) { var command = new SQLiteCommand(queryText, _mDbConnection); command.ExecuteNonQuery(); } // Writes the highscores to the console sorted on score in descending order. public void Reader(string queryText) { //var command = new SQLiteCommand(queryText, _mDbConnection); //var reader = command.ExecuteReader(); //while (reader.Read()) // Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]); //Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pecs { class e40 { static void Main(string[] args) { StringBuilder test = new StringBuilder(""); for (int i = 1; i <= 1000000; i++) { test.Append(i.ToString()); } int output = int.Parse(test[0].ToString()); output *= int.Parse(test[9].ToString()); output *= int.Parse(test[99].ToString()); output *= int.Parse(test[999].ToString()); output *= int.Parse(test[9999].ToString()); output *= int.Parse(test[99999].ToString()); output *= int.Parse(test[999999].ToString()); Console.WriteLine(output); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Http; using Windows.ApplicationModel.Background; // The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409 namespace IotWebServer { public sealed class StartupTask : IBackgroundTask { HttpWebServer server; public void Run(IBackgroundTaskInstance taskInstance) { HtmlDoc htmlDoc = new HtmlDoc(); string reply = htmlDoc.ResponseText; server = new HttpWebServer(reply); server.Initialise(); // If you start any asynchronous methods here, prevent the task // from closing prematurely by using BackgroundTaskDeferral as // described in http://aka.ms/backgroundtaskdeferral // } } }
namespace SPACore.PhoneBook.PhoneBooks.Persons.Dto { public class CreateOrUpdatePersonInput { public PersonEditDto PersonEditDto { get; set; } } }
using Microsoft.EntityFrameworkCore; using Project33.Services.Models; namespace Project33.Data { public class BooksContext : DbContext { public BooksContext(DbContextOptions<BooksContext> options) : base(options) { } public BooksContext() { Database.EnsureCreated(); } public DbSet<Books> Books { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=Bookstore;Username=postgres;Password=85ilasin85"); } } }
namespace ApplicantAPI.App.Infrastructure { using GreenPipes; using MassTransit; using System.Diagnostics; using MassTransit.MessageData; using MessageExchangeContract; using ApplicantAPI.Messaging.Consumers; using Microsoft.Extensions.DependencyInjection; public static class ServiceBusConfigExtensions { public static IServiceCollection AddMassTransitServiceBus(this IServiceCollection services) { return services.AddMassTransit(mt => { // Register Consumers mt.AddConsumer<RegisterNewApplicantConsumer>(); mt.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(rmq => { if (Debugger.IsAttached) { rmq.Host("localhost", "/", host => { host.Username("guest"); host.Password("guest"); }); } else { rmq.Host("rabbitmq", host => { host.Username("guest"); host.Password("guest"); }); } rmq.UseHealthCheck(provider); rmq.UseMessageData(new InMemoryMessageDataRepository()); // Register Exhanges rmq.Message<IRegisterNewApplicant>(m => m.SetEntityName("register-new-applicant-exchange")); rmq.Message<IEventNotificationMessage>(m => m.SetEntityName("event-notification-exchange")); // Register Endpoints rmq.ReceiveEndpoint("register-new-applicant-queue", endpoint => { endpoint.PrefetchCount = 20; endpoint.UseMessageRetry(retry => retry.Interval(5, 200)); endpoint.Bind<IRegisterNewApplicant>(); endpoint.ConfigureConsumer<RegisterNewApplicantConsumer>(provider); }); })); }) .AddMassTransitHostedService(); } } }
using GameLoanManager.Domain.Entities; using GameLoanManager.Domain.ViewModels; namespace GameLoanManager.Domain.Interfaces { public interface ITokenService { TokenViewModel GenerateToken(User user); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Negozio.DataAccess.DbModel { public class FilmAttore { [Key] public int FilmAttoreId { get; set; } public int AttoreId { get; set; } public int FilmId { get; set; } public virtual Attore Attore { get; set; } public virtual Film Film { get; set; } } }
using System; using System.Text; namespace PluginStudy.Tools { /// <summary> /// ConvertHelper /// </summary> public class ConvertHelper { /// <summary> /// string转DateTime /// 参数格式如果不正确则默认返回当前时间 /// </summary> /// <param name="date">日期格式字符串</param> /// <returns></returns> public static DateTime StringToDateTimeDefaultNow(string date) { DateTime temp; return DateTime.TryParse(date, out temp) ? temp : DateTime.Now; } /// <summary> /// string转DateTime /// 参数格式如果不正确则默认返回最大时间 /// </summary> /// <param name="date">日期格式字符串</param> /// <returns></returns> public static DateTime StringToDateTimeDefaultMax(string date) { DateTime temp; return DateTime.TryParse(date, out temp) ? temp : DateTime.MaxValue; } /// <summary> /// string转DateTime /// 参数格式如果不正确则默认返回最小时间 /// </summary> /// <param name="date">日期格式字符串</param> /// <returns></returns> public static DateTime StringToDateTimeDefaultMin(string date) { DateTime temp; return DateTime.TryParse(date, out temp) ? temp : DateTime.MinValue; } /// <summary> /// string转int /// 失败返回0 /// </summary> /// <param name="str">字符串</param> /// <returns></returns> public static int StringToInt32(string str) { if (string.IsNullOrEmpty(str)) str = "0"; int temp; return int.TryParse(str, out temp) ? temp : 0; } /// <summary> /// string转decimal /// 失败返回0 /// </summary> /// <param name="str">字符串</param> /// <returns></returns> public static decimal StringToDecimal(string str) { if (string.IsNullOrEmpty(str)) str = "0"; decimal temp; return decimal.TryParse(str, out temp) ? temp : 0M; } /// <summary> /// 进制转换 ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。 /// </summary> /// <param name="value">要转换的值</param> /// <param name="fromBase">原进制(2,8,10,16)</param> /// <param name="toBase">目标进制(2,8,10,16)</param> /// <exception cref="NullReferenceException">参数value为空</exception> /// <exception cref="Exception">参数fromBase不正确</exception> /// <exception cref="Exception">参数toBase不正确</exception> /// <returns></returns> public static string ConvertBase(string value, int fromBase, int toBase) { if (string.IsNullOrEmpty(value)) throw new NullReferenceException("参数value为空!"); if (fromBase != 2 || fromBase != 8 || fromBase != 10 || fromBase != 16) throw new Exception("参数fromBase不正确"); if (toBase != 2 || toBase != 8 || toBase != 10 || toBase != 16) throw new Exception("参数toBase不正确"); int intValue = Convert.ToInt32(value, fromBase); string result = Convert.ToString(intValue, toBase); if (toBase == 2) { int resultLength = result.Length; //获取二进制的长度 switch (resultLength) { case 7: result = "0" + result; break; case 6: result = "00" + result; break; case 5: result = "000" + result; break; case 4: result = "0000" + result; break; case 3: result = "00000" + result; break; } } return result; } /// <summary> /// 使用指定的编码将string转成byte[] /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="encoding">编码</param> /// <returns></returns> public static byte[] StringToByte(string str, Encoding encoding) { return encoding.GetBytes(str); } /// <summary> /// 使用指定的编码将byte[]转成string /// </summary> /// <param name="buffer">byte[]</param> /// <param name="encoding">编码</param> /// <returns></returns> public static string ByteToString(byte[] buffer, Encoding encoding) { return encoding.GetString(buffer); } /// <summary> /// 将int转换成byte /// </summary> /// <param name="i">整形参数i</param> /// <returns></returns> public static byte[] Int32ToByte(int i) { return BitConverter.GetBytes(i); } /// <summary> /// 将byte转换成int /// </summary> /// <param name="buffer">要转换的byte数组</param> /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <returns></returns> public static int ByteToInt32(byte[] buffer) { int temp = 0; //如果传入的字节数组长度小于4,则返回0 if (buffer.Length < 4) return temp; //如果传入的字节数组长度大于4,需要进行处理 if (buffer.Length >= 4) { //创建一个临时缓冲区 byte[] tempBuffer = new byte[4]; //将传入的字节数组的前4个字节复制到临时缓冲区 Buffer.BlockCopy(buffer, 0, tempBuffer, 0, 4); //将临时缓冲区的值转换成整数,并赋给num temp = BitConverter.ToInt32(tempBuffer, 0); } //返回整数 return temp; } } }
using System; class Program { public static void Main() { int PlayGroundSide = int.Parse(Console.ReadLine()); double TileWidth = double.Parse(Console.ReadLine()); double TileHeight = double.Parse(Console.ReadLine()); int BenchWidth = int.Parse(Console.ReadLine()); int BenchHeight = int.Parse(Console.ReadLine()); double TileSetTme = 0.2; int BenchSize = BenchWidth * BenchHeight; double TileSize = TileWidth * TileHeight; int PlayGroundSize = PlayGroundSide * PlayGroundSide; double TilesNumber = (double)(PlayGroundSize - BenchSize) / TileSize; double TilesTotalTime = TilesNumber * TileSetTme; Console.WriteLine(TilesNumber); Console.WriteLine(TilesTotalTime); } }
using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace sampleApi.Controllers { [ApiController] [Route("[controller]")] public class ForceAbortController : ControllerBase { static readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); [HttpGet] public async Task<IActionResult> Get() { int actualRunTime = 10000; try { await Task.Delay(actualRunTime, cancellationTokenSource.Token); } catch (TaskCanceledException exception) { // 499 Client Closed Request // Used when the client has closed the request before the server could send a response. return StatusCode(499, "Client Closed Request before the server could send a response. Task cancelled with exception " + exception.Message); } return Ok("ok"); } /// <summary> /// receive the cancel request /// </summary> /// <returns></returns> [HttpPost] public IActionResult Post(int taskId) { cancellationTokenSource.Cancel(); return Ok("task " + taskId + " cancelled"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PESWeb.Profiles.Interface; using PESWeb.Profiles.Presenter; namespace PESWeb.Profiles { public partial class ManagePrivacy : System.Web.UI.Page, IManagePrivacy { private ManagePrivacyPresenter _presenter; protected void Page_Load(object sender, EventArgs e) { _presenter = new ManagePrivacyPresenter(); _presenter.Init(this); } protected override void OnInit(EventArgs e) { base.OnInit(e); btnSave.Click += new EventHandler(btnSave_Click); } void btnSave_Click(object sender, EventArgs e) { lblMessage.Text = ""; foreach (var type in _presenter.GetPrivacyFlagType()) { DropDownList ddl = phPrivacyFlagTypes.FindControl("ddlVisibility" + type.PrivacyFlagTypeID) as DropDownList; if (ddl != null) _presenter.SavePrivacyFlag(type.PrivacyFlagTypeID, Convert.ToInt32(ddl.SelectedValue)); } lblMessage.Text = "Lưu thành công!"; } #region IManagePrivacy Members public void ShowPrivacyTypes(List<Pes.Core.PrivacyFlagType> PrivacyFlagTypes, List<Pes.Core.VisibilityLevel> VisibilityLevels, List<Pes.Core.PrivacyFlag> PrivacyFlags) { foreach (var type in PrivacyFlagTypes) { phPrivacyFlagTypes.Controls.Add(new LiteralControl("<div class='divContainerRow'>")); phPrivacyFlagTypes.Controls.Add(new LiteralControl("<div class='divContainerCellHeader'>")); phPrivacyFlagTypes.Controls.Add(new LiteralControl(type.FieldName)); phPrivacyFlagTypes.Controls.Add(new LiteralControl("</div>")); phPrivacyFlagTypes.Controls.Add(new LiteralControl("<div class='divContainerCell\'>")); DropDownList ddlVisibility = new DropDownList(); ddlVisibility.ID = "ddlVisibility" + type.PrivacyFlagTypeID; foreach (var level in VisibilityLevels) { ListItem li = new ListItem(level.Name, level.VisibilityLevelID.ToString()); if (!IsPostBack) li.Selected = _presenter.IsFlagSelected(type.PrivacyFlagTypeID, level.VisibilityLevelID, PrivacyFlags); ddlVisibility.Items.Add(li); } phPrivacyFlagTypes.Controls.Add(ddlVisibility); phPrivacyFlagTypes.Controls.Add(new LiteralControl("</div>")); phPrivacyFlagTypes.Controls.Add(new LiteralControl("</div>")); } } public void ShowMessage(string Message) { lblMessage.Text += Message; } #endregion } }
using StoreSample.Catalog.Alpha.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace StoreSample.Catalog.Alpha.Interfaces { public interface IProductRepository { Task<IEnumerable<Product>> GetAllAsync(); Task<Product> GetById(int id); Task<Product> GetBySKU(string sku); Task<Product> Register(Product product); Task<Product> Modify(Product modifiedProduct); Task<bool> Delete(Product product); } }
using System; using System.Collections.Generic; using System.Text; namespace DiscordPoker { public class Deck { private Random rand = new Random(); private List<Card> Used = new List<Card>(); private List<Card> Unused = new List<Card>(); public int CardCount { get { return Used.Count + Unused.Count; } } public Deck(int decks, bool shuffle, bool jokers) { if (decks <= 0) { return; } Unused = GenerateDeck(decks, jokers); if (shuffle) { Shuffle(); } } public List<Card> GenerateDeck(int decks, bool jokers) { List<Card> deck = new List<Card>(); foreach (Suit s in Enum.GetValues(typeof(Suit))) { if (s == Suit.NULL || s == Suit.Joker) { continue; } foreach (Rank r in Enum.GetValues(typeof(Rank))) { if (r == Rank.NULL || r == Rank.Joker) { continue; } deck.Add(new Card(r, s)); } } if (jokers) { deck.Add(new Card(Rank.Joker, Suit.Joker)); deck.Add(new Card(Rank.Joker, Suit.Joker)); } return deck; } public void Shuffle() { Used.AddRange(Unused); Unused.Clear(); while (Used.Count > 0) { int next = rand.Next(0, Used.Count); Unused.Add(Used[next]); Used.RemoveAt(next); } } public List<Card> DrawCards(int num) { List<Card> cards = new List<Card>(); if (num > Unused.Count) { cards.AddRange(Unused); Shuffle(); Used.AddRange(cards); foreach (Card c in cards) { Unused.Remove(c); } } if (num > Unused.Count) { throw new Exception("Insufficent number of cards."); } int more = num - cards.Count; cards.AddRange(Unused.GetRange(0, more)); Used.AddRange(Unused.GetRange(0, more)); Unused.RemoveRange(0, more); return cards; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Archive_NewTiob : System.Web.UI.Page { PDTech.OA.BLL.OA_ATTACHMENT_FILE fBll = new PDTech.OA.BLL.OA_ATTACHMENT_FILE(); PDTech.OA.BLL.OA_ARCHIVE ArchiveBll = new PDTech.OA.BLL.OA_ARCHIVE(); PDTech.OA.BLL.ATTRIBUTES attBll = new PDTech.OA.BLL.ATTRIBUTES(); PDTech.OA.BLL.OA_ARCHIVE_TASK tbll = new PDTech.OA.BLL.OA_ARCHIVE_TASK(); PDTech.OA.BLL.WORKFLOW_STEP vStepBll = new PDTech.OA.BLL.WORKFLOW_STEP(); PDTech.OA.BLL.OA_ARCHIVE_TASK taskBll = new PDTech.OA.BLL.OA_ARCHIVE_TASK(); PDTech.OA.BLL.RISK_POINT_INFO rpi_bll = new PDTech.OA.BLL.RISK_POINT_INFO(); int? Archive_Id = 0;/// int? Task_Id = 0;//作用区分接收和办理人员 const decimal ARCHIVE_TYPE = 71; public string t_rand = ""; public int arId = 0; PDTech.OA.Model.OA_ARCHIVE Arwhere = null;//当前公文 const string Symol = "/images/nextIcon.png"; /// <summary> /// 单位发文 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff"); if (Request.QueryString["arId"] != null) { if (AidHelp.IsDecimal(Request.QueryString["arId"].ToString())) arId = int.Parse( Request.QueryString["arId"].ToString()); } if (!IsPostBack) { title.InnerText = "成都市水务局" + S_App.ShowTitle(ARCHIVE_TYPE.ToString()) + "处理单";//设置标题 PDTech.OA.BLL.DEPARTMENT dBll = new PDTech.OA.BLL.DEPARTMENT(); List<PDTech.OA.Model.WORKFLOW_STEP> vStepList = (List<PDTech.OA.Model.WORKFLOW_STEP>)vStepBll.GetStepByArchiveType(ARCHIVE_TYPE);///本流程所有步骤 List<PDTech.OA.Model.WORKFLOW_STEP> vNextList = new List<PDTech.OA.Model.WORKFLOW_STEP>();///下一步可操作步骤集合 if (arId==0) { btnSave.Visible = false; ShowOpList.Visible = false; tipInfo.Visible = false;//隐藏提示图标 } else { btnSubmit.Visible = false; onBindData(); } } } /// <summary> /// 非新增绑定数据 /// </summary> public void onBindData() { PDTech.OA.Model.OA_ARCHIVE Arwhere = new PDTech.OA.Model.OA_ARCHIVE(); #region 获取扩展属性并绑定 Arwhere = ArchiveBll.GetArchiveInfo((decimal)arId); #region 获取和遍历扩展属性 IList<PDTech.OA.Model.ATTRIBUTES> attList = new List<PDTech.OA.Model.ATTRIBUTES>(); attList = attBll.get_AttInfoList(new PDTech.OA.Model.ATTRIBUTES() { LOG_ID = (decimal)Arwhere.ATTRIBUTE_LOG }); if (attList.Count > 0) { foreach (var item in attList) { switch (item.KEY) { case "Curcandelf": hidAttachmentIds.Value = item.VALUE; break; } } } txtTitle.Text = Arwhere.ARCHIVE_TITLE; txtcontent.Text = Arwhere.ARCHIVE_CONTENT; ViewState["const_logId"] = Arwhere.ATTRIBUTE_LOG; ViewState["Creator"] = Arwhere.CREATOR; hidarchtivetype.Value=Arwhere.ARCHIVE_NO; hidArStatus.Value = Arwhere.CURRENT_STATE.ToString(); #endregion #region 获取该公文的附件 PDTech.OA.Model.OA_ATTACHMENT_FILE where = new PDTech.OA.Model.OA_ATTACHMENT_FILE(); where.REF_TYPE = "OA_ARCHIVE"; where.REF_ID = (decimal)arId; IList<PDTech.OA.Model.OA_ATTACHMENT_FILE> aList = fBll.get_InfoList(where); if (aList.Count > 0) { rpt_AttachmentList.DataSource = aList; rpt_AttachmentList.DataBind(); tr_showList.Visible = true; } else { tr_showList.Visible = false; } #endregion ShowOpList.Text = AidHelp.get_PrintInfoListAll_Html((decimal)arId); #endregion } /// <summary> /// 附件文本Doc扫描读入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnImport_Click(object sender, EventArgs e) { } /// <summary> /// 保存修改 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { try { string fjIds = ""; IList<PDTech.OA.Model.ATTRIBUTES> attList = new List<PDTech.OA.Model.ATTRIBUTES>(); PDTech.OA.Model.OA_ARCHIVE Archive = new PDTech.OA.Model.OA_ARCHIVE(); if ( arId != 0) { if (string.IsNullOrEmpty(txtTitle.Text.Trim())) { nPrompt("请填写公文标题!", 0); txtTitle.Focus(); return; } Archive.ARCHIVE_CONTENT = txtcontent.Text.Trim(); Archive.ARCHIVE_TITLE = txtTitle.Text.Trim(); Archive.ARCHIVE_TYPE = ARCHIVE_TYPE; Archive.CREATOR = CurrentAccount.USER_ID; Archive.CURRENT_STATE = 0; if (!String.IsNullOrEmpty(hidarchtivetype.Value)) { Archive.ARCHIVE_NO = hidarchtivetype.Value; } Archive.ARCHIVE_ID = arId; if (ViewState["const_logId"] != null) { Archive.ATTRIBUTE_LOG = decimal.Parse(ViewState["const_logId"].ToString()); } if (!string.IsNullOrEmpty(hidAttachmentIds.Value)) { fjIds = hidAttachmentIds.Value.TrimEnd(','); } if (!string.IsNullOrEmpty(hidAttachmentIds.Value)) { attList.Add(new PDTech.OA.Model.ATTRIBUTES() { KEY = "Curcandelf", VALUE = new ConvertHelper(hidAttachmentIds.Value.Trim()).String }); } bool result = ArchiveBll.Update(Archive, fjIds, attList); if (result) { if (sender == null)//提交调用保存时,成功不提示,直接跳转页面 { return; } nPrompt("保存成功!", 1); } else { nPrompt("保存失败!", 0); } } } catch (Exception ex) { } } protected void rpt_AttachmentList_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "DelItem") { decimal atId = Convert.ToDecimal(e.CommandArgument.ToString()); if (ViewState["Creator"] != null) { if (ViewState["Creator"].ToString() == CurrentAccount.USER_ID.ToString()) fBll.Delete(atId); else nPrompt("您没有权限删除此附件!", 0); } else if (arId == 0) { fBll.Delete(atId); } } BindData(); } protected void rpt_AttachmentList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { PDTech.OA.Model.OA_ATTACHMENT_FILE item = e.Item.DataItem as PDTech.OA.Model.OA_ATTACHMENT_FILE; HyperLink hlDown = e.Item.FindControl("hlDown") as HyperLink; if (hlDown != null) { hlDown.NavigateUrl = "/DownLoad.aspx?file=" + item.FILE_PATH + "&fullName=" + item.FILE_NAME; } } } protected void btnSubmit_Click(object sender, EventArgs e) { try { if (btnSave.Visible) { btnSave_Click(null, null); } #region 新增公文 if (arId==0) { string fjIds = ""; IList<PDTech.OA.Model.ATTRIBUTES> attList = new List<PDTech.OA.Model.ATTRIBUTES>(); PDTech.OA.Model.OA_ARCHIVE Archive = new PDTech.OA.Model.OA_ARCHIVE(); if (string.IsNullOrEmpty(txtTitle.Text.Trim())) { nPrompt("请填写单位发文标题!", 0); txtTitle.Focus(); return; } Archive.ARCHIVE_CONTENT = txtcontent.Text.Trim(); Archive.ARCHIVE_TITLE = txtTitle.Text.Trim(); Archive.ARCHIVE_TYPE = ARCHIVE_TYPE; Archive.CREATOR = CurrentAccount.USER_ID; Archive.CURRENT_STATE = 0; Archive.ARCHIVE_TYPE_NAME = "三重一大"; if (!String.IsNullOrEmpty(hidarchtivetype.Value)) { Archive.ARCHIVE_NO = hidarchtivetype.Value; } if (!string.IsNullOrEmpty(hidAttachmentIds.Value)) { fjIds = hidAttachmentIds.Value.TrimEnd(','); } if (!string.IsNullOrEmpty(hidAttachmentIds.Value)) { attList.Add(new PDTech.OA.Model.ATTRIBUTES() { KEY = "Curcandelf", VALUE = new ConvertHelper(hidAttachmentIds.Value.Trim()).String }); } bool result = ArchiveBll.Add(Archive, CurrentAccount.ClientHostName, CurrentAccount.ClientIP, fjIds, attList, out Archive_Id, out Task_Id); if (result) { nPrompt("提交成功!", 2); } else { nPrompt("提交失败!", 0); } } #endregion } catch (Exception ex) { } } public void nPrompt(string msg, int flag) { if (flag == 0) { this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>layer.alert('" + msg + "',8)</script>"); } else if (flag == 1) { this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>layer.alert('" + msg + "',1);</script>"); } else if (flag == 2) { this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>alert('" + msg + "');window.parent.doRefresh();window.parent.layer.closeAll();</script>"); } } /// <summary> /// 绑定附件 /// </summary> public void BindData() { PDTech.OA.Model.OA_ATTACHMENT_FILE where = new PDTech.OA.Model.OA_ATTACHMENT_FILE(); if (!string.IsNullOrEmpty(hidAttachmentIds.Value.Trim())) { string HidIds = hidAttachmentIds.Value.TrimEnd(','); if (!string.IsNullOrEmpty(HidIds)) where.Append = string.Format(" ATTACHMENT_FILE_ID IN({0}) ", HidIds); if (!string.IsNullOrEmpty(arId.ToString()) && arId != 0 && !string.IsNullOrEmpty(where.Append)) where.Append += string.Format(@" OR ( REF_ID={0} AND REF_TYPE='OA_ARCHIVE')", arId); if (!string.IsNullOrEmpty(arId.ToString()) && arId != 0 && string.IsNullOrEmpty(where.Append)) where.Append += string.Format(@" REF_ID={0} AND REF_TYPE='OA_ARCHIVE' ", arId); IList<PDTech.OA.Model.OA_ATTACHMENT_FILE> aList = fBll.get_InfoList(where); if (aList.Count > 0) { rpt_AttachmentList.DataSource = aList; rpt_AttachmentList.DataBind(); tr_showList.Visible = true; } else { tr_showList.Visible = false; } } if (arId!=0 && !string.IsNullOrEmpty(hidAttachmentIds.Value.Trim())) { string HidIds = hidAttachmentIds.Value.TrimEnd(','); fBll.UpdatePID(HidIds, (decimal)(arId), "OA_ARCHIVE", ""); } } protected void btnSearchList_Click(object sender, EventArgs e) { BindData(); } }
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Text; namespace CSharpBase.Data { public static class DataAccess { public static String Plop() { return "plop"; } public static void InitializeDatabase() { using (SQLiteConnection db = new SQLiteConnection("Data Source=database.db; Version = 3; New = True; Compress = True; ")) { db.Open(); String tableCommand = "CREATE TABLE IF NOT " + "EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " + "Text_Entry NVARCHAR(2048) NULL)"; SQLiteCommand createTable = new SQLiteCommand(tableCommand, db); createTable.ExecuteReader(); } } public static void AddData(string inputText) { using (SQLiteConnection db = new SQLiteConnection("Data Source=database.db; Version = 3; New = True; Compress = True; ")) { db.Open(); SQLiteCommand insertCommand = new SQLiteCommand(); insertCommand.Connection = db; // Use parameterized query to prevent SQL injection attacks insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);"; insertCommand.Parameters.AddWithValue("@Entry", inputText); insertCommand.ExecuteReader(); db.Close(); } } public static List<String> GetData() { List<String> entries = new List<string>(); using (SQLiteConnection db = new SQLiteConnection("Data Source=database.db; Version = 3; New = True; Compress = True; ")) { db.Open(); SQLiteCommand selectCommand = new SQLiteCommand ("SELECT Text_Entry from MyTable", db); SQLiteDataReader query = selectCommand.ExecuteReader(); while (query.Read()) { entries.Add(query.GetString(0)); } db.Close(); } return entries; } public static bool IsCorrectString(String insertString) { if ( String.IsNullOrWhiteSpace(insertString) || insertString.Length > 127) { // EXCEPTION throw new InvalidStringException(""); } else { return true; } } } public class InvalidStringException : Exception { public string errorMessage; public InvalidStringException(string message) : base(message) { errorMessage = message; } } }
using UnityEngine; using System.Collections; using UnityEditor; using System.IO; public class AudioPostProcessor : AssetPostprocessor { private const string music_path = "Assets/RawResources/Audio/Music/"; private const string sound_path = "Assets/RawResources/Audio/Sounds/"; void OnPostprocessAudio(AudioClip clip) { if (assetPath.StartsWith(music_path)) { string abName = new DirectoryInfo(Path.GetFileNameWithoutExtension(assetPath)).Name.ToLower(); assetImporter.assetBundleName = "music/" + abName + ".u3d"; AudioImporter audio = assetImporter as AudioImporter; if (audio != null) { AudioImporterSampleSettings audioSettings = new AudioImporterSampleSettings(); audioSettings.loadType = AudioClipLoadType.Streaming; audioSettings.compressionFormat = AudioCompressionFormat.Vorbis; audioSettings.quality = 0.1f; audioSettings.sampleRateSetting = AudioSampleRateSetting.OverrideSampleRate; audioSettings.sampleRateOverride = 11025; audio.defaultSampleSettings = audioSettings; } } if (assetPath.StartsWith(sound_path)) { string abName = new DirectoryInfo(Path.GetFileNameWithoutExtension(assetPath)).Name.ToLower(); assetImporter.assetBundleName = "sounds/" + abName + ".u3d"; } } }
/*H********************************************************************** * FILENAME : Sphere.cs DESIGN REF: OGLTUT05 * * DESCRIPTION : * Sphere object functions. * * PUBLIC FUNCTIONS : * * void ShapeDrawing( ) * * * NOTES : * These functions are a part of the Computer Graphics course materias suite; * * * Copyright Amr M. Gody. 2019, 2019. All rights reserved. * * AUTHOR : Amr M. Gody START DATE : 24 OCT 2019 * * CHANGES : * * REF NO VERSION DATE WHO DETAIL * 1 1 24OCT19 AG first working version * *******************************************************************************H*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK; using OpenTK.Graphics.OpenGL; namespace OpenTKTut.Shapes { class Sphere : OGLShape { public Sphere(Vector3 center, double radius,bool AutoRotate = false,Vector3 color = default(Vector3)) { if (color == default(Vector3)) { color = new Vector3(1f, 1f, 1f); } Center = center; Radius = radius; EnableAutoRotate = AutoRotate; Color_ = color; rotation_speed = 1; rotationAxis = new Vector3(1f, 1f, 0f); } public double Radius { get; set; } protected override void ShapeDrawing() { base.ShapeDrawing(); GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); MeshPolygons= MeshElement.Sphere(Radius); GL.Begin(PrimitiveType.Quads); GL.Color3(Color_); for(int i=0;i< MeshPolygons.Length;i++) { //GL.Normal3(MeshPolygons[i].Normal); for (int j=0;j< MeshPolygons[i].Vertices.Length;j++) { var p = MeshPolygons[i].Vertices[j].Normalized(); var u = .5 + Math.Atan2(p.Z, p.X) / (2 * Math.PI); var v = .5 - Math.Asin(p.Y) / Math.PI; //var v = .5 - p.Y*.5; GL.TexCoord2(u, v); // set point normal and postion GL.Normal3(MeshPolygons[i].Vertices[j].Normalized()); GL.Vertex3(MeshPolygons[i].Vertices[j]); } } GL.End(); GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); } private Vector3[] ConstructMesh() { throw new NotImplementedException(); } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using trunk.Core.Models; namespace trunk.Controllers.Resources { public class MakeResource : KeyValuePairResource { public ICollection<KeyValuePairResource> Models { get; set; } public MakeResource() { Models = new Collection<KeyValuePairResource>(); } } }
using Assets.Scripts.Common.Interfaces; using Assets.Scripts.Weapons.Interfaces; using UnityEngine; namespace Assets.Scripts.Weapons.Spread { public class BulletBehaviour : MonoBehaviour, IDamaging, IDestructable { Rigidbody2D rigidBody2D; public Vector2 VelocityUnitVector { get; set; } public float VelocityScale { get; set; } public int Damage { get; set; } public Vector2 Velocity => VelocityUnitVector * VelocityScale; void Start() { VelocityUnitVector = transform.up; VelocityScale = 30; rigidBody2D = GetComponent<Rigidbody2D>(); rigidBody2D.velocity = Velocity; } public void Destruct() { Destroy(gameObject); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowingLight : MonoBehaviour { GameObject player; Vector3 desiredPosition; bool playerContact = false, countdownOn = false; public float radius = 10.0f, radiusSpeed = 0.5f, rotationSpeed = 80.0f, timeLeft = 10.0f, timeRemaining, particleHeight = 1.5f; void Start() { //find player and its transform to which the particle will revolve arround player = GameObject.FindWithTag("Player"); } void Update() { //if player gets close enough, call function revolve and countdown RotateAroundPlayer(playerContact); timeRemaining = CountDown(countdownOn); } private void OnTriggerEnter(Collider collision) { //if collision with player, then start revolving and countdown if (collision.gameObject.layer == 8) { playerContact = true; countdownOn = true; } } void RotateAroundPlayer(bool playerContact) { if (playerContact) { //set position to rotate around, the desired position and position transform.RotateAround(player.transform.position, Vector3.up, rotationSpeed * Time.deltaTime); desiredPosition = (transform.position - player.transform.position).normalized * radius + player.transform.position; desiredPosition.y = particleHeight; transform.position = Vector3.MoveTowards(transform.position, desiredPosition, Time.deltaTime * radiusSpeed); } } public float CountDown(bool countdownOn) { //if countdown equals zero, then destroy game objct, the timeleft will also define the intensity of the particles if (countdownOn) { timeLeft -= Time.deltaTime; if(timeLeft < 0) { Destroy(gameObject); return 0; } return timeLeft; } return timeLeft; } }
using ETModel; namespace ETHotfix { //需要UserId请求的转发 要通过网关转发的消息必须继承这个 public interface IUserRequest : IRequest { long UserId { get; set; } } //管理员后台操作的协议 public interface IAdministratorRequest : IUserRequest { string Account { get; set; } string Password { get; set; } } //需要UserId请求的转发 需要获取用户在网关的SessionActorId的要继承这个 public interface IUserActorRequest : IUserRequest { User User { get; set; } long SessionActorId { get; set; } } }
using _2014118187_ENT.Entities; using _2014118187_ENT.IRepositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2014118187_PER.Repositories { public class RanuraDepositoRepository : Repository<RanuraDeposito>, IRanuraDepositoRepository { public RanuraDepositoRepository(_2014118187DbContext context) : base(context) { } /*private readonly _2014118187DbContext _Context; public RanuraDepositoRepository(_2014118265DbContext context) { _Context = context; } private RanuraDepositoRepository() { }*/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SFP.SIT.SERV.Model.SOL { public class SIT_SOL_SEGUIMIENTO { public Int64? repclave { set; get; } public int? usrclave { set; get; } public DateTime segfecestimada { set; get; } public Int64 segultimonodo { set; get; } public int? afdclave { set; get; } public int segedoproceso { set; get; } public int prcclave { set; get; } public DateTime segfeccalculo { set; get; } public int segdiasnolab { set; get; } public int segmultiple { set; get; } public DateTime segfecfin { set; get; } public DateTime segfecamp { set; get; } public int segsemaforocolor { set; get; } public int segdiassemaforo { set; get; } public DateTime segfecini { set; get; } public Int64 solclave { set; get; } public SIT_SOL_SEGUIMIENTO () {} public SIT_SOL_SEGUIMIENTO ( Int64? repclave, int? usrclave, DateTime segfecestimada, Int64 segultimonodo, int? afdclave, int segedoproceso, int prcclave, DateTime segfeccalculo, int segdiasnolab, int segmultiple, DateTime segfecfin, DateTime segfecamp, int segsemaforocolor, int segdiassemaforo, DateTime segfecini, Int64 solclave ) { this.repclave = repclave; this.usrclave = usrclave; this.segfecestimada = segfecestimada; this.segultimonodo = segultimonodo; this.afdclave = afdclave; this.segedoproceso = segedoproceso; this.prcclave = prcclave; this.segfeccalculo = segfeccalculo; this.segdiasnolab = segdiasnolab; this.segmultiple = segmultiple; this.segfecfin = segfecfin; this.segfecamp = segfecamp; this.segsemaforocolor = segsemaforocolor; this.segdiassemaforo = segdiassemaforo; this.segfecini = segfecini; this.solclave = solclave; } } }
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_08 { using System; using System.Threading; using CountDownTimer = System.Timers.Timer; class HelloWorld { static void Main() { CountDownTimer timer; // ... } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Students_and_Courses { interface IStudentCollection { bool Add(Person student, string course); void Print(); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class Spawner : MonoBehaviour { public GameObject boidPrefab; public LayerMask allyLayer; public int spawnCount; public float spawnRadius; public bool respawn = false; // Start is called before the first frame update void Start() { for (var i = 0; i < spawnCount; i++) { Spawn(); } } void Update() { if (!respawn) { return; } Collider[] boids = Physics.OverlapSphere(this.transform.position, 2000, allyLayer); if (boids.Length < spawnCount) { Spawn(); } } public void Spawn() { Vector3 position = this.transform.position + (Random.insideUnitSphere * spawnRadius); var boid = Instantiate(boidPrefab, position, transform.rotation); } }
using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityApi { public static class IWebHostExtensions { public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost, Action<TContext, IServiceProvider> seeder) where TContext : DbContext { using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetService<TContext>(); context.Database.Migrate(); seeder(context, services); } return webHost; } } }
using UnityEngine; using System.Collections; public class CharacterMovement : MonoBehaviour { public float movementSpeed; public float jumpSpeed; bool grounded; Vector2 movement; public int jumps; int currentJumps; // Use this for initialization void Start () { } // Update is called once per frame void FixedUpdate () { float move = Input.GetAxis("Horizontal"); if (move < 0) { transform.localScale = new Vector3(-1,1,1); } if(move > 0){ transform.localScale = new Vector3(1, 1, 1); } if (Input.GetKeyDown(KeyCode.Space) && grounded && currentJumps>0) { currentJumps--; rigidbody2D.AddForce(Vector2.up * jumpSpeed, ForceMode2D.Impulse); } rigidbody2D.velocity = new Vector2( move * movementSpeed, rigidbody2D.velocity.y); } public void Jump() { if (grounded && currentJumps > 0) { currentJumps--; rigidbody2D.AddForce(Vector2.up * jumpSpeed, ForceMode2D.Impulse); } } void OnTriggerEnter2D(Collider2D col) { if (col.tag.Equals("Platform")) { grounded = true; currentJumps = jumps; } } void OnTriggerExit2D(Collider2D col) { if (col.tag.Equals("Platform")) { } } }
using BPiaoBao.Common.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.DataContracts.DomesticTicket { public class DeductionDetailDto { public int ID { get; set; } /// <summary> /// 扣点商户code /// </summary> public string Code { get; set; } /// <summary> /// 扣点商户名 /// </summary> public string Name { get; set; } /// <summary> /// 点数 /// </summary> public decimal Point { get; set; } /// <summary> /// 扣点类型 /// </summary> public AdjustType AdjustType { get; set; } /// <summary> /// 本地 接口 共享 /// </summary> public DeductionType DeductionType { get; set; } public virtual List<DeductionDetailDto> DeductionDetails { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace JJApi.Controllers { [Authorize(Roles = "level2")] public class ServiceController : Controller { // Service [HttpPost] [Route("/service/getDataService")] public string getServiceData([FromForm] IFormFile file, Dictionary<string, string> collection) { BL.queries.blService bService = new BL.queries.blService(Request.Headers["Authorization"].ToString()); string result= bService.getServiceData(null, collection); return result; } [HttpPost] [Route("/service/getDataServiceTran")] public string getServiceTran([FromForm] IFormFile file, Dictionary<string, string> collection) { BL.queries.blService bService = new BL.queries.blService(Request.Headers["Authorization"].ToString()); string result = bService.getServiceTran(null, collection); return result; } [HttpPost] [Route("/service/setData")] public string setDataServiceinfo([FromForm] IFormFile file, Dictionary<string, string> collection) { BL.queries.blService bService = new BL.queries.blService(Request.Headers["Authorization"].ToString()); string result = bService.setDataServiceinfo(null, collection); return result; } // ------------------------ service end } }
using UnityEngine; using System.Collections; public class CameraFacingController : MonoBehaviour { public Camera FacingCamera; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Transform textLookAt = FacingCamera.transform; textLookAt.rotation = Quaternion.identity; transform.LookAt(textLookAt); } }
namespace Yeasca.Metier { public interface IRechercheGlobale : IRecherche { string Texte { get; set; } } }
using System; using System.IO; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Graphics.Imaging; using Windows.Media.Ocr; using Windows.Storage.Streams; using System.Linq; namespace CloudOcr.Core.Windows { // https://medium.com/@leesonLee/microsoft-ocr-uwp-behind-api-rest-553ac725f6fc // https://docs.microsoft.com/fr-fr/windows/apps/desktop/modernize/desktop-to-uwp-enhance // https://dev.to/azure/develop-azure-functions-using-net-core-3-0-gcm public class OcrService { private readonly OcrEngine _ocrEngine; public OcrService() { _ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); if (_ocrEngine == null) { throw new Exception("Failed to create OcrEngine."); } } private async Task<SoftwareBitmap> GetPictureFromStreamAsync(byte[] image) { SoftwareBitmap picture = null; using (InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream()) { await randomAccessStream.WriteAsync(image.AsBuffer()); randomAccessStream.Seek(0); var decoder = await BitmapDecoder.CreateAsync(randomAccessStream); picture = await decoder.GetSoftwareBitmapAsync(); } return picture; } public async Task<string> RecognizeTextAsync(Stream image) { var ms = new MemoryStream(); await image.CopyToAsync(ms); var picture = await GetPictureFromStreamAsync(ms.GetBuffer()); var resultOCR = await _ocrEngine.RecognizeAsync(picture); return resultOCR.Text; } } }
using ModuleTest.Views; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; using PrismUI.Core.Commands; using PrismUI.Core.Services; namespace PrismUi.ViewModels { public class MainWindowViewModel : BindableBase { private readonly IRegionManager _regionManager; private readonly IOpenFileDialogService _openFileDialogService; private string _title = "CEBP"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private IApplicationCommands _applicationCommands; public IApplicationCommands ApplicationCommands { get { return _applicationCommands; } set { SetProperty(ref _applicationCommands, value); } } private string _openFileDialogPath; public string OpenFileDialogPath { get => _openFileDialogPath; set => SetProperty(ref _openFileDialogPath, value); } public DelegateCommand<string> NavigateCommand { get; set; } public DelegateCommand OpenFileDialogCommand { get; set; } public MainWindowViewModel(IApplicationCommands applicationCommands, IRegionManager regionManager, IOpenFileDialogService openFileDialogService) { _regionManager = regionManager; _openFileDialogService = openFileDialogService; _regionManager.RegisterViewWithRegion("NavContentRegion", typeof(TestView)); ApplicationCommands = applicationCommands; NavigateCommand = new DelegateCommand<string>(Navigate); OpenFileDialogCommand = new DelegateCommand(OpenFileDialog); } private void OpenFileDialog() { _openFileDialogService.ShowDialog(); OpenFileDialogPath = _openFileDialogService.OpenFileDialog.FileName; } private void Navigate(string uri) { var p = new NavigationParameters(); p.Add("NavUri", uri); _regionManager.RequestNavigate("NavContentRegion", uri, p); } } }
#region License /*** * Copyright © 2018-2025, 张强 (943620963@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * without warranties or conditions of any kind, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using ZqUtils.Extensions; /**************************** * [Author] 张强 * [Date] 2020-08-28 * [Describe] Assembly工具类 * **************************/ namespace ZqUtils.Helpers { /// <summary> /// Assembly工具类 /// </summary> public class AssemblyHelper { /// <summary> /// 根据指定路径和条件获取程序集 /// </summary> /// <param name="path">程序集路径,默认:AppContext.BaseDirectory</param> /// <param name="filter">程序集筛选过滤器</param> /// <returns></returns> public static Assembly[] GetAssemblies(string path = null, Func<string, bool> filter = null) { var files = Directory .GetFiles(path ?? AppDomain.CurrentDomain.BaseDirectory, "*.*") .Where(x => x.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || x.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) .Select(x => x .Substring(Path.DirectorySeparatorChar.ToString()) .Replace(".dll", "") .Replace(".exe", "")) .Distinct(); //判断筛选条件是否为空 if (filter != null) files = files.Where(x => filter(x)); //加载Assembly集 var assemblies = files.Select(x => Assembly.Load(x)); return assemblies.ToArray(); } /// <summary> /// 获取程序集文件 /// </summary> /// <param name="folderPath">目录路径</param> /// <param name="searchOption">检索模式</param> /// <returns></returns> public static IEnumerable<string> GetAssemblyFiles(string folderPath, SearchOption searchOption) { return Directory .EnumerateFiles(folderPath, "*.*", searchOption) .Where(s => s.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// 根据指定路径和条件获取程序集中所有的类型集合 /// </summary> /// <param name="path">程序集路径,默认:AppContext.BaseDirectory</param> /// <param name="condition">程序集筛选条件</param> /// <returns></returns> public static List<Type> GetTypesFromAssembly(string path = null, Func<string, bool> condition = null) { var types = new List<Type>(); var assemblies = GetAssemblies(path, condition); if (assemblies?.Length > 0) { foreach (var assembly in assemblies) { Type[] typeArray = null; try { typeArray = assembly.GetTypes(); } catch { } if (typeArray?.Length > 0) types.AddRange(typeArray); } } return types; } /// <summary> /// 获取程序集中的所有类型 /// </summary> /// <param name="assembly"></param> /// <returns></returns> public static IReadOnlyList<Type> GetAllTypes(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types; } } } }
#nullable enable using System; using System.Collections.Generic; using Xunit; namespace ShoppingCart.UnitTests { public class ProxyTest : IDisposable { public ProxyTest() { var pd = new ProductData { Sku = "ProxyTest1", Name = "ProxyTestName1", Price = 456 }; Db.Store(pd); } [Fact] public void ProductProxy() { Product p = new ProductProxy("ProxyTest1"); Assert.Equal(456, p.Price); Assert.Equal("ProxyTestName1", p.Name); Assert.Equal("ProxyTest1", p.Sku); } [Fact] public void OrderProxyTotal() { Db.Store(new ProductData("Wheaties", 349, "wheaties")); Db.Store(new ProductData("Crest", 258, "crest")); ProductProxy wheaties = new ProductProxy("wheaties"); ProductProxy crest = new ProductProxy("crest"); OrderData od = Db.NewOrder("testOrderProxy"); OrderProxy order = new OrderProxy(od.OrderId); order.AddItem(crest, 1); order.AddItem(wheaties, 2); Assert.Equal(956, order.Total); } public void Dispose() { Db.Clear(); } } public class OrderProxy : Order { private readonly int orderId; public OrderProxy(int orderId) { this.orderId = orderId; } public void AddItem(ProductProxy productProxy, int qty) { var id = new ItemData(orderId, qty, productProxy.Sku); Db.Store(id); } public string CustomerId { get { OrderData od = Db.GetOrderData(orderId); return od.CustomerId; } } public void AddItem(Product p, int quantity) { ItemData id = new ItemData(orderId, quantity, p.Sku); Db.Store(id); } public int Total { get { OrderImp imp = new OrderImp(CustomerId); IEnumerable<ItemData> itemDataArray = Db.GetItemsForOrder(orderId); foreach (var item in itemDataArray) { imp.AddItem(new ProductProxy(item.Sku), item.Qty); } return imp.Total; } } public int OrderId => orderId; } public class OrderData { public string CustomerId { get; } public int OrderId { get; } public OrderData() { } public OrderData(int orderId, string customerId) { OrderId = orderId; CustomerId = customerId; } } public class ItemData { public readonly int OrderId; public readonly int Qty; public readonly string Sku; public ItemData(int orderId, int qty, string sku) { OrderId = orderId; Qty = qty; Sku = sku; } public override bool Equals(object? obj) { if (obj is ItemData id) { return OrderId == id.OrderId && Qty == id.Qty && Sku.Equals(id.Sku); } return false; } public override int GetHashCode() { return HashCode.Combine(OrderId, Qty, Sku); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Converter.UI.Enums { /// <summary> /// Enumerates the various degrees of severity a single log entry could have /// </summary> public enum LogEntrySeverity { /// <summary> /// The information /// </summary> Info, /// <summary> /// The warning /// </summary> Warning, /// <summary> /// The error /// </summary> Error } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ProyectoASPEmenic.Paginas.Personas { public partial class ListadoNaturales : System.Web.UI.Page { Conexion conexion = new Conexion(); string query = ""; protected void Page_Load(object sender, EventArgs e) { query = "SELECT IdPersona,PrimerNombre,SegundoNombre,PrimerApellido,SegundoApellido," + "DUI,NIT,Activo FROM persona WHERE PersonaNatural = 1;"; conexion.IniciarConexion(); conexion.TablasQuery(query, this.GridListadoNaturales); conexion.CerrarConexion(); } protected void GridListadoNaturales_RowEditing(object sender, GridViewEditEventArgs e) { ////IdPersona de la tabla que selecciona //HFIdPersona.Value = GridListadoNaturales.Rows[e.NewEditIndex].Cells[1].Text; ////Envia IdPersona a formulario de actualizar //Response.Redirect("~/Paginas/Personas/ActualizarNaturales.aspx?act=" + HFIdPersona.Value); } protected void GridListadoNaturales_RowDeleting(object sender, GridViewDeleteEventArgs e) { } protected void btnAgregarRegistro_Click(object sender, EventArgs e) { Response.Redirect("~/Paginas/Personas/RegistroNaturales.aspx"); } protected void GridListadoNaturales_SelectedIndexChanged(object sender, EventArgs e) { } protected void GridListadoNaturales_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Actualizar") { Response.Redirect("~/Paginas/Personas/ActualizarNaturales.aspx?act=" + e.CommandArgument); } } protected void btnGenerarPDF_Click(object sender, EventArgs e) { Response.Redirect("~/Paginas/Reporteria/ReportePersonasNaturales.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumeraciones { enum DiasDeLaSemana: byte { Domingo=6, Lunes=0, Martes=1, Miercoles=2, Jueves=3, Viernes=4, Sabado=5 } }
using System; using System.Reflection; using RestSharp; using Verifalia.Api.EmailAddresses; namespace Verifalia.Api { /// <summary> /// REST client for Verifalia API. /// </summary> public class VerifaliaRestClient { const string DefaultApiVersion = "v1.1"; const string DefaultBaseUrl = "https://api.verifalia.com/"; readonly RestClient _restClient; string _apiVersion; Uri _baseUri; ValidationRestClient _emailValidations; /// <summary> /// Verifalia API version to use when making requests. /// </summary> public string ApiVersion { get { return _apiVersion; } set { if (value == null) throw new ArgumentNullException("value"); _apiVersion = value; UpdateRestClientBaseUrl(); } } /// <summary> /// Base URL of Verifalia API (defaults to https://api.verifalia.com/) /// </summary> public Uri BaseUri { get { return _baseUri; } set { if (value == null) throw new ArgumentNullException("value"); _baseUri = value; UpdateRestClientBaseUrl(); } } /// <summary> /// Allows to submit and manage email validations using the Verifalia service. /// </summary> public ValidationRestClient EmailValidations { get { return _emailValidations ?? (_emailValidations = new ValidationRestClient(_restClient)); } } /// <summary> /// Initializes a new Verifalia REST client with the specified credentials. /// </summary> /// <remarks>Your Account SID and Auth token values can be retrieved in your client area, /// upon clicking on your subscription details, on Verifalia website at: https://verifalia.com/client-area/subscriptions </remarks> public VerifaliaRestClient(string accountSid, string authToken) { if (String.IsNullOrEmpty(accountSid)) throw new ArgumentException("accountSid is null or empty.", "accountSid"); if (String.IsNullOrEmpty(authToken)) throw new ArgumentException("authToken is null or empty.", "authToken"); // Default values used to build the base URL needed to access the service _apiVersion = DefaultApiVersion; _baseUri = new Uri(DefaultBaseUrl); // The user agent string brings the type of the client and its version (for statistical purposes // at the server side): var userAgent = String.Concat("verifalia-rest-client/netfx/", Assembly.GetExecutingAssembly().GetName().Version); // Setup the rest client _restClient = new RestClient { Authenticator = new HttpBasicAuthenticator(accountSid, authToken), UserAgent = userAgent }; UpdateRestClientBaseUrl(); } /// <summary> /// Updates the base URL for the underlying REST client. /// </summary> void UpdateRestClientBaseUrl() { _restClient.BaseUrl = new Uri(BaseUri, ApiVersion).AbsoluteUri; } } }
using PayPal.PayPalAPIInterfaceService; using PayPal.PayPalAPIInterfaceService.Model; using Paypal_API.Models; using PayPalAPISample; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace Paypal_API.API_Call { public class Order { public string Create(TransactionModel model) { // Create request object SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType(); populateRequestObject(request,model); // Invoke the API SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq(); wrapper.SetExpressCheckoutRequest = request; Dictionary<string, string> configurationMap = confiugraion.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); // # API call // Invoke the SetExpressCheckout method in service wrapper object SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper); // Check for API return status HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails); var response=setKeyResponseObjects(service, setECResponse); return response; } private void populateRequestObject(SetExpressCheckoutRequestType request,TransactionModel model) { SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType(); model.ReturnURL = ConfigurationManager.AppSettings["Return_Url"]; model.CancelURL = ConfigurationManager.AppSettings["Cancel_Url"]; model.ipnNotificationUrl = ""; model.PaymentAction = "ORDER"; ecDetails.ReturnURL = model.ReturnURL; ecDetails.CancelURL = model.CancelURL; ecDetails.BuyerEmail = model.BuyerEmail; ecDetails.ReqConfirmShipping = "No"; PaymentDetailsType paymentDetails = new PaymentDetailsType(); ecDetails.PaymentDetails.Add(paymentDetails); // (Required) Total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. Set this field to 0 if the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment that is not immediately charged. When the field is set to 0, purchase-specific fields are ignored. double orderTotal = 0.0; // Sum of cost of all items in this order. For digital goods, this field is required. double itemTotal = 0.0; CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), model.CurrencyCode); if (model.ShippingTotalCost != string.Empty) { paymentDetails.ShippingTotal = new BasicAmountType(currency, model.ShippingTotalCost); orderTotal += Convert.ToDouble(model.ShippingTotalCost); } if (model.InsurenceTotal != string.Empty && !Convert.ToDouble(model.InsurenceTotal).Equals(0.0)) { paymentDetails.InsuranceTotal = new BasicAmountType(currency, model.InsurenceTotal); paymentDetails.InsuranceOptionOffered = "true"; orderTotal += Convert.ToDouble(model.InsurenceTotal); } if (model.HandlingTotal != string.Empty) { paymentDetails.HandlingTotal = new BasicAmountType(currency, model.HandlingTotal); orderTotal += Convert.ToDouble(model.HandlingTotal); } if (model.TaxTotal != string.Empty) { paymentDetails.TaxTotal = new BasicAmountType(currency, model.TaxTotal); orderTotal += Convert.ToDouble(model.TaxTotal); } if (model.ItemDescription != string.Empty) { paymentDetails.OrderDescription = model.ItemDescription; } paymentDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), model.PaymentAction); if (model.name != string.Empty && model.Street1 != string.Empty && model.CityName != string.Empty && model.StateOrProvince != string.Empty && model.Country != string.Empty && model.PostalCode != string.Empty) { AddressType shipAddress = new AddressType(); shipAddress.Name = model.name; shipAddress.Street1 = model.Street1; shipAddress.Street2 = model.Street2; shipAddress.CityName = model.CityName; shipAddress.StateOrProvince = model.StateOrProvince; if(!string.IsNullOrEmpty(model.Country)) { shipAddress.Country = (CountryCodeType) Enum.Parse(typeof(CountryCodeType), model.Country); } shipAddress.PostalCode = model.PostalCode; //Fix for release shipAddress.Phone = model.Phone; ecDetails.PaymentDetails[0].ShipToAddress = shipAddress; } // Each payment can include requestDetails about multiple items // This example shows just one payment item if (model.ItemName != null && model.ItemCost != null && model.Quantity != null) { PaymentDetailsItemType itemDetails = new PaymentDetailsItemType(); itemDetails.Name = model.ItemName; itemDetails.Amount = new BasicAmountType(currency, model.ItemCost); itemDetails.Quantity = model.Quantity; itemDetails.ItemCategory = (ItemCategoryType) Enum.Parse(typeof(ItemCategoryType),model.ItemCategory); itemTotal += Convert.ToDouble(itemDetails.Amount.value) * itemDetails.Quantity.Value; if (model.SalesTax != string.Empty) { itemDetails.Tax = new BasicAmountType(currency, model.SalesTax); orderTotal += Convert.ToDouble(model.SalesTax); } //(Optional) Item description. // Character length and limitations: 127 single-byte characters // This field is introduced in version 53.0. if (model.ItemDescription != string.Empty) { itemDetails.Description = model.ItemDescription; } paymentDetails.PaymentDetailsItem.Add(itemDetails); } orderTotal += itemTotal; paymentDetails.ItemTotal = new BasicAmountType(currency, itemTotal.ToString()); paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString()); paymentDetails.NotifyURL = model.ipnNotificationUrl.Trim(); // Set Billing agreement (for Reference transactions & Recurring payments) if (model.BillingAgreement != string.Empty) { model.BillingType = "RECURRINGPAYMENTS"; BillingCodeType billingCodeType = (BillingCodeType) Enum.Parse(typeof(BillingCodeType), model.BillingType); BillingAgreementDetailsType baType = new BillingAgreementDetailsType(billingCodeType); baType.BillingAgreementDescription = model.BillingAgreement; ecDetails.BillingAgreementDetails.Add(baType); } request.SetExpressCheckoutRequestDetails = ecDetails; } // A helper method used by APIResponse.aspx that returns select response parameters // of interest. private string setKeyResponseObjects(PayPalAPIInterfaceServiceService service, SetExpressCheckoutResponseType setECResponse) { Dictionary<string, string> keyResponseParameters = new Dictionary<string, string>(); keyResponseParameters.Add("API Status", setECResponse.Ack.ToString()); string message = ""; HttpContext CurrContext = HttpContext.Current; if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Count > 0)) { CurrContext.Items.Add("Response_error", setECResponse.Errors); message = setECResponse.Errors[0].LongMessage; CurrContext.Items.Add("Response_redirectURL", null); return message; } else { CurrContext.Items.Add("Response_error", null); keyResponseParameters.Add("EC token", setECResponse.Token); CurrContext.Items.Add("Response_redirectURL", ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"].ToString() + "_express-checkout&token=" + setECResponse.Token); } CurrContext.Items.Add("Response_keyResponseObject", keyResponseParameters); CurrContext.Items.Add("Response_apiName", "SetExpressCheckout"); CurrContext.Items.Add("Response_requestPayload", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload", service.getLastResponse()); foreach(var i in keyResponseParameters){ if (i.Key == "API Status") { message = i.Value; } } if (message == "SUCCESS") { message = CurrContext.Items["Response_redirectURL"].ToString(); } return message; } public TransactionModel doExpressCheckout(string token, string payerId) { Dictionary<string, string> configurationMap = confiugraion.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq(); getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token); // # API call // Invoke the GetExpressCheckoutDetails method in service wrapper object GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper); // Create request object DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; // (Required) The timestamped token value that was returned in the SetExpressCheckout response and passed in the GetExpressCheckoutDetails request. requestDetails.Token = token; // (Required) Unique PayPal buyer account identification number as returned in the GetExpressCheckoutDetails response requestDetails.PayerID = payerId; requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), "ORDER"); // Invoke the API DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper); // Check for API return status var responseARB= setKeyResponseObjects(service, doECResponse,token); responseARB.PayerId=payerId; return responseARB; } private TransactionModel setKeyResponseObjects(PayPalAPIInterfaceServiceService service, DoExpressCheckoutPaymentResponseType doECResponse, string token) { Dictionary<string, string> responseParams = new Dictionary<string, string>(); responseParams.Add("Correlation Id", doECResponse.CorrelationID); responseParams.Add("API Result", doECResponse.Ack.ToString()); HttpContext CurrContext = HttpContext.Current; if (doECResponse.Ack.Equals(AckCodeType.FAILURE) || (doECResponse.Errors != null && doECResponse.Errors.Count > 0)) { CurrContext.Items.Add("Response_error", doECResponse.Errors); } else { CurrContext.Items.Add("Response_error", null); responseParams.Add("EC Token", doECResponse.DoExpressCheckoutPaymentResponseDetails.Token); responseParams.Add("Transaction Id", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID); responseParams.Add("Payment status", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus.ToString()); if (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != null) { responseParams.Add("Pending reason", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString()); } if (doECResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID != null) responseParams.Add("Billing Agreement Id", doECResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID); } CurrContext.Items.Add("Response_keyResponseObject_Authorized", responseParams); CurrContext.Items.Add("Response_apiName", "DoExpressChecoutPayment"); CurrContext.Items.Add("Response_redirectURL", null); CurrContext.Items.Add("Response_requestPayload", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload", service.getLastResponse()); string message = ""; foreach (var i in responseParams) { if (i.Key == "API Result") { message = i.Value; } } var transactionId = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; var responseARB =new TransactionModel(); if (message == "SUCCESS") { // message = CurrContext.Items["Response_redirectURL"].ToString(); responseARB= DoAuthorized(transactionId, "USD", "5.27",token); responseARB.TransactionId = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; responseARB.Paymentstatus = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus.ToString(); } return responseARB; } public TransactionModel DoAuthorized(string transactionId, string currencyCode, string amount, string token) { // Create request object DoAuthorizationRequestType request = new DoAuthorizationRequestType(); // (Required) Value of the order's transaction identification number returned by PayPal. request.TransactionID = transactionId; CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), currencyCode); // (Required) Amount to authorize. request.Amount = new BasicAmountType(currency, amount); // Invoke the API DoAuthorizationReq wrapper = new DoAuthorizationReq(); wrapper.DoAuthorizationRequest = request; Dictionary<string, string> configurationMap = confiugraion.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); // # API call // Invoke the DoAuthorization method in service wrapper object DoAuthorizationResponseType doAuthorizationResponse = service.DoAuthorization(wrapper); // Check for API return status var responseARB= setKeyResponseObjectsAuthorized(service, doAuthorizationResponse,token); return responseARB; } private TransactionModel setKeyResponseObjectsAuthorized(PayPalAPIInterfaceServiceService service, DoAuthorizationResponseType response, string token) { var message = ""; Dictionary<string, string> responseParams = new Dictionary<string, string>(); responseParams.Add("Transaction Id", response.TransactionID); responseParams.Add("Payment status", response.AuthorizationInfo.PaymentStatus.ToString()); responseParams.Add("Pending reason", response.AuthorizationInfo.PendingReason.ToString()); HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("Response_keyResponseObject", responseParams); CurrContext.Items.Add("Response_apiName_Authorized", "DoAuthorization"); CurrContext.Items.Add("Response_redirectURL_Authorized", null); CurrContext.Items.Add("Response_requestPayload_Authorized", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload_Authorized", service.getLastResponse()); if (response.Ack.Equals(AckCodeType.FAILURE) || (response.Errors != null && response.Errors.Count > 0)) { CurrContext.Items.Add("Response_error_Authorized", response.Errors); } else { CurrContext.Items.Add("Response_error_Authorized", null); } message="Payment status" + response.AuthorizationInfo.PaymentStatus.ToString(); ARB obj = new ARB(); var responseARB= obj.CreateRecurring(token); return responseARB; } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Emanate.Extensibility.Converters { [Localizability(LocalizationCategory.NeverLocalize)] public sealed class InverseBooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var bValue = false; if (value is bool) bValue = (bool)value; return (bValue) ? Visibility.Collapsed : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Visibility) return (Visibility)value != Visibility.Visible; return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenTile { public enum Position { BOTTOM_LEFT = 0, BOTTOM = 1, BOTTOM_RIGHT = 2, LEFT = 3, CENTER = 4, RIGHT = 5, TOP_LEFT = 6, TOP = 7, TOP_RIGHT = 8 } public Room.TileType type; public Position position; public GenTile() { } public GenTile(Room.TileType type) { this.type = type; } public GenTile(Room.TileType type, Position position) { this.type = type; this.position = position; } public static Position GetPosition(int xMode, int yMode) { return (Position) ((xMode + 1) + (yMode + 1) * 3); } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Configuration; using System.Linq.Expressions; using JobApplication.Models; namespace DvdApplication.Repositories { public class DbJobsRepository : IJobRepository { private string connectionString = ConfigurationManager .ConnectionStrings["LocalDb"] .ConnectionString; public List<JobApplication.Models.Job> GetAll() { List<Job> jobs = new List<Job>(); using (SqlConnection cn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM Jobs"; cmd.Connection = cn; cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var job = new Job(); job.JobTitle = dr["JobTitle"].ToString(); job.JobCompany = dr["JobCompany"].ToString(); job.InterviewDate = dr["InterviewDate"].ToString(); job.Salary = dr["Salary"].ToString(); job.RecruiterCompany = dr["RecruiterCompany"].ToString(); job.Recruiter = dr["Recruiter"].ToString(); job.JobId = int.Parse(dr["JobId"].ToString()); jobs.Add(job); } } } return jobs; } public void Add(JobApplication.Models.Job job) { //Fix the add segment } public void Delete(int id) { //Fix the delete segment } public void Edit(JobApplication.Models.Job job) { //Fix the edit segment } public JobApplication.Models.Job GetById(int id) { //Get specific job } } }
using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Weapon { private int _damage; public Weapon(int damageVal) { _damage = damageVal; } //Gets damage. public int GetDamage() { return _damage; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : Character { //private variables protected GameObject player; //public variables public float DetectRadius; // Use this for initialization void Start () { player = GameObject.Find("Player"); } // Update is called once per frame void Update () { } protected void checkState() { if (animController == null) animController = GetComponent<Animator>(); if (HP <= 0) { animController.SetInteger("AnimState", 2); StartCoroutine(Death()); } } IEnumerator Death() { yield return new WaitForSeconds(5); Destroy(gameObject); Debug.Log("DED"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonController : MonoBehaviour { CanvasGroup group; public List<Button> menuButtons; void OnEnable() { Player.EOnPlayerDeath += ShowDeathScreen; } void Awake() { group = GetComponent<CanvasGroup>(); group.alpha = 0; foreach (var b in menuButtons) b.gameObject.SetActive(false); } void OnDisable() { Player.EOnPlayerDeath -= ShowDeathScreen; } void ShowDeathScreen() { StartCoroutine(FadeToBlack()); } IEnumerator FadeToBlack() { foreach (var b in menuButtons) b.gameObject.SetActive(true); while (group.alpha < 1.0f) { group.alpha += 0.01f; yield return null; } } public void Reset() { UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); } public void Exit() { Application.Quit(); } }
using CloudFile; using System; using System.IO; using System.Net; using UnityEngine; [CustomLuaClass] public class DUDownLoadTask : DUTask { private RequestObjectForDownload m_requestObject; private bool _isClosed; private string m_md5FromServer; private int m_lengthOfHaveRead; private int _recordReadCount; public DUDownLoadTask(int ID, string url, string localPath) : base(ID, url, localPath) { } protected void _DeleteLocalPath() { if (File.Exists(this._localPath)) { File.Delete(this._localPath); } } protected override void _DoBegin() { base._DoBegin(); this._CreateDirectory(); this._DeleteLocalPath(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(this._url); httpWebRequest.set_Method("GET"); httpWebRequest.get_Headers().Add("Authorization", UpYunServer.AUTH_VALUE); this.m_requestObject = new RequestObjectForDownload(this.m_idForRequestObject); this.m_requestObject.Request = httpWebRequest; this.m_requestObject.Buffer = new byte[DUTaskManager.DownLoadBufferSize]; Debug.LogFormat("{0} _DoBegin {1}", new object[] { this._id, this.m_idForRequestObject }); try { httpWebRequest.BeginGetResponse(new AsyncCallback(this.OnResponse), this.m_requestObject); this.SetTimeOut((float)httpWebRequest.get_Timeout() / 1000f, "request time out"); } catch (Exception e) { this.HandleError(e); } } protected override void _DoPause() { base._DoPause(); } protected override void _DoClose() { base._DoClose(); if (this.m_requestObject != null) { this._isClosed = true; Debug.LogFormat("{0} doclose", new object[] { this._id }); this.m_requestObject.Release(); } this.m_md5FromServer = null; this.m_requestObject = null; this.m_lengthOfHaveRead = 0; this._recordReadCount = 0; } protected void OnResponse(IAsyncResult result) { if (this._isClosed) { Debug.LogFormat("{0} closed but OnResponse,state:{1}", new object[] { this._id, this._state }); } if (this._state == DUTaskState.Running) { RequestObjectForDownload requestObjectForDownload = (RequestObjectForDownload)result.get_AsyncState(); if (requestObjectForDownload != null && requestObjectForDownload.ID == this.m_idForRequestObject) { this.StopCheckTimeOut(); try { if (this.m_requestObject != null) { HttpWebRequest request = requestObjectForDownload.Request; if (!request.get_HaveResponse()) { Debug.LogFormat("{0} Have no Response", new object[] { this._id }); base._CreateError().RecordSystemError("Have no Response"); this._DoClose(); } else { HttpWebResponse httpWebResponse = request.EndGetResponse(result) as HttpWebResponse; requestObjectForDownload.Response = httpWebResponse; if (httpWebResponse.get_StatusCode() == 200) { this.m_md5FromServer = httpWebResponse.get_Headers().get_Item("ETag"); if (!string.IsNullOrEmpty(this.m_md5FromServer)) { this.m_md5FromServer = this.m_md5FromServer.Replace("\"", string.Empty); } Stream responseStream = httpWebResponse.GetResponseStream(); requestObjectForDownload.ResponseStream = responseStream; this.ReadFromResponseStream(); } else { base._CreateError().RecordResponseError(httpWebResponse.get_StatusCode(), "ResponseStatusIsntOK"); this._DoClose(); } } } } catch (Exception e) { this.HandleError(e); } } } else { this._DoClose(); } } protected void ReadFromResponseStream() { if (this._state == DUTaskState.Running && this.m_requestObject != null && this.m_requestObject.ID == this.m_idForRequestObject) { byte[] buffer = this.m_requestObject.Buffer; Stream responseStream = this.m_requestObject.ResponseStream; try { responseStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(this.OnReadFromStream), this.m_requestObject); this.SetTimeOut((float)responseStream.get_ReadTimeout() / 1000f, "download time out"); } catch (Exception e) { this.HandleError(e); } } } private void HandleError(Exception e) { if (this._state == DUTaskState.Running && this.m_requestObject != null && this.m_requestObject.ID == this.m_idForRequestObject) { if (e is WebException) { HttpWebResponse httpWebResponse = ((WebException)e).get_Response() as HttpWebResponse; if (httpWebResponse != null) { base._CreateError().RecordResponseError(httpWebResponse.get_StatusCode(), httpWebResponse.get_StatusDescription()); } else { base._CreateError().RecordWebError(((WebException)e).get_Status(), e.ToString()); } } else if (e is IOException) { base._CreateError().RecordIOError(e.ToString()); } else { base._CreateError().RecordSystemError(e.ToString()); } this._DoClose(); Debug.LogFormat("{0} HandleError", new object[] { this._id }); Debug.Log(e); throw e; } } private void OnReadFromStream(IAsyncResult result) { if (this._state == DUTaskState.Running) { RequestObjectForDownload requestObjectForDownload = (RequestObjectForDownload)result.get_AsyncState(); this.StopCheckTimeOut(); if (requestObjectForDownload.ID == this.m_idForRequestObject) { try { int num = requestObjectForDownload.ResponseStream.EndRead(result); if (num > 0) { FileHelper.AppendBytes(this._localPath, this.m_requestObject.Buffer, num); this.m_lengthOfHaveRead += num; this._progress = (float)this.m_lengthOfHaveRead / (float)this.m_requestObject.ContentLength; this.ReadFromResponseStream(); } else { bool flag = false; if (string.IsNullOrEmpty(this.m_md5FromServer)) { flag = true; } else { string text = MyMD5.HashFile(this._localPath); if (string.Equals(text, this.m_md5FromServer)) { flag = true; } else { base._CreateError().RecordMD5Error(null); Debug.LogFormat("file:{0}, server:{1}.", new object[] { text, this.m_md5FromServer }); } } this._DoClose(); if (flag) { this._SuccessComplete(); } } } catch (Exception e) { this.HandleError(e); } } } } public override void FireProgress(float passedTime) { float num = (float)(this.m_lengthOfHaveRead - this._recordReadCount); this._recordReadCount = this.m_lengthOfHaveRead; this._speed = num / passedTime; base.FireProgress(passedTime); } public override DUTask CloneSelf() { DUDownLoadTask dUDownLoadTask = new DUDownLoadTask(this._id, this._url, this._localPath); dUDownLoadTask._state = this._state; dUDownLoadTask.SetCallBacks(this._completeHandler, this._errorHandler, this._progressHandler); dUDownLoadTask._clonedTimes = this._clonedTimes + 1; return dUDownLoadTask; } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using WordChainKata; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace WordChainKata.Tests { [TestClass()] public class WordChainTests { [TestMethod()] public void should_return_word_chain_from_dictionary() { //setup List<string> dictionary = new List<string>(); WordChain wordChain = new WordChain(dictionary, "lead", "gold"); //act List<string> result = wordChain.GetChain(); //assert Assert.AreEqual(result, "lead,load,goad,gold"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using KT.DB; using KT.DB.CRUD; using KT.DTOs.Objects; using KT.ServiceInterfaces; using KT.Services.Mappers; namespace KT.Services.Services { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "KtQuestionsService" in code, svc and config file together. public class KtQuestionsService : IKtQuestionsService { private static readonly ICrud<Question> Repository = CrudFactory<Question>.Get(); public int GetCountBySubcategory(Guid subCatId) { var count = Repository.ReadArray(a => a.SubcategoryId.Equals(subCatId)).Count(); return count; } public void Delete(Guid id) { Repository.Delete(a => a.Id == id); } public QuestionDto[] GetBySubcategory(Guid id) { var relatedObjects = new[] { "Answers" }; var all = Repository.ReadArray(a => a.SubcategoryId == id, relatedObjects); return (new QuestionsMapper()).Map(all).ToArray(); } public double GetUsability(Guid id) { var testsRepository = CrudFactory<GeneratedTest>.Get(); var questionsRepository = CrudFactory<GeneratedQuestion>.Get(); var q = Repository.Read(a => a.Id == id); if (q != null) { var allSubcatTests = testsRepository.ReadArray(a => a.Test.Subcategory.Id == q.SubcategoryId).Count(); var thisQuestionUsedIn = questionsRepository.ReadArray(a => a.QuestionId == id).Count(); if (allSubcatTests == 0) return 0; double percentage = (thisQuestionUsedIn / allSubcatTests) * 100; return Math.Round(percentage, 2); } return 0; } public QuestionDto GetById(Guid id) { var relatedObjects = new[] { "Subcategory", "Answers" }; var q = Repository.Read(a => a.Id == id, relatedObjects); return (new QuestionsMapper()).Map(q); } public Guid Save(string text, Guid subCatId, Guid? qId = null, bool isMultiple = false, string argument = "") { if (qId.HasValue && !qId.Equals(Guid.Empty)) { var q = Repository.Read(a => a.Id == qId); if (q != null) { q.Text = text; q.MultipleAnswer = isMultiple; q.CorrectArgument = argument; Repository.Update(q); } return qId.Value; } else { var q = new Question { Text = text, Id = Guid.NewGuid(), SubcategoryId = subCatId, CorrectArgument = argument, MultipleAnswer = isMultiple }; q = Repository.Create(q); return q.Id; } } public QuestionDto[] GetAll() { var relatedObjects = new[] { "Answers" }; var all = Repository.ReadArray(a => true, relatedObjects).ToList(); return (new QuestionsMapper()).Map(all).ToArray(); } } }
/* @Auther Jaeung Choi(darker826, darker826@gmail.com) * 녹화 기능을 담당하는 클래스입니다. * 객체를 생성 후 함수를 부르기만 하면 사용이 가능함. * .avi 동영상 파일의 생성에는 AForge.Video.FFMPEG wrapper를 사용하여 FFMPEG 라이브러리를 통해 생성합니다. * 동영상 파일의 프레임은 KinectColorViewer에서 WriteableBitmap를 Bitmap으로 Convert하여 Bitmap을 넣는 것으로 처리합니다. */ namespace Microsoft.Samples.Kinect.WpfViewers { using System; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.Windows.Media.Imaging; using System.Runtime.InteropServices; using Microsoft.Kinect; using AForge.Video.FFMPEG; public class RecordController { private static VideoFileWriter writer; public static bool openBool = true; public static bool recordBool = false; public RecordController() { writer = new VideoFileWriter(); } //녹화 시작할 때 부를 함수. public void recordingStart(ColorImageFrame colorImage, WriteableBitmap writeBmp) { if (recordBool) { // Bitmap bmap = colorFrameToBitmap(colorImage); Bitmap bmap = bitmapFromWriteableBitmap(writeBmp); if (openBool) { String fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".avi"; String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); String file = filePath + "\\" + fileName; openBool = false; writer.Open(fileName, colorImage.Width, colorImage.Height, 25, VideoCodec.MPEG4); } writer.WriteVideoFrame(bmap); } } //녹화를 중지할때 부를 함수 public static void recordingStop() { writer.Close(); } //colorImageFrame을 받아서 Bitmap으로 변환해주는 함수. /* private Bitmap colorFrameToBitmap(ColorImageFrame colorImage) { Bitmap bmap; BitmapData bmapdata; byte[] pixeldata; pixeldata = new byte[colorImage.PixelDataLength]; colorImage.CopyPixelDataTo(pixeldata); bmap = new Bitmap(colorImage.Width, colorImage.Height, PixelFormat.Format24bppRgb); bmap.SetPixel(colorImage.Width-1, colorImage.Height-1, Color.Red); bmapdata = bmap.LockBits( new System.Drawing.Rectangle(0, 0, colorImage.Width, colorImage.Height), ImageLockMode.WriteOnly, bmap.PixelFormat); IntPtr ptr = bmapdata.Scan0; Marshal.Copy(pixeldata, 0, ptr, bmapdata.Stride * bmap.Height); bmap.UnlockBits(bmapdata); return bmap; } */ //기존에 쓰이던 WriteableBitmap을 bitmap으로 convert해주는 함수 public Bitmap bitmapFromWriteableBitmap(WriteableBitmap writeBmp) { Bitmap bmp; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp)); enc.Save(outStream); bmp = new System.Drawing.Bitmap(outStream); } return bmp; } } }
namespace Game.ConsoleUI.Game.Views { using Interfaces.Views; public class PlayersServiceView : IPlayersServiceView { private readonly IBaseView baseView; public PlayersServiceView(IBaseView baseView) { this.baseView = baseView; } public bool ApproveResolution(string playerName, string resolutionWord, string currentPlayer) { var agreed = this.baseView.WaitForConfirmation($"{playerName} please agree resolution from {currentPlayer} - {resolutionWord}"); return agreed; } public string ResolveChallenge(string playerName, char challengeChallengeLetter) { var resolution = this.baseView.WaitForInput($"{playerName} please provide valid word starting on {challengeChallengeLetter}"); return resolution; } } }
using System; using System.Diagnostics; using System.Linq; using Microsoft.AspNetCore.Mvc; using FbPageManager.Models; using FbPageManager.Utilities; namespace FbPageManager.Controllers { public class PageManagerController : Controller { public IActionResult Index() { return View(); } public IActionResult Login() { return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } /* public JsonResult GetAccessToken() { var accessToken = PageManagerUtilities.GetAccessToken(); return Json(new { accessToken }); } */ public JsonResult CreatePost( string pageId, string accessToken, string postContent, bool isPublished) { PageManagerUtilities.CreatePost(pageId, accessToken, postContent, isPublished); return Json(new {}); } public JsonResult UpdatePost( string postId, string pageId, string accessToken, string postContent, bool isPublished) { PageManagerUtilities.UpdatePost(postId, accessToken, postContent, isPublished); return Json(new { }); } public JsonResult SaveSessionInfo( string userInfo, string sessionInfo) { PageManagerUtilities.SaveSessionInfo(userInfo, sessionInfo); return Json(new { }); } public JsonResult ReadPublishedPost(string pageId, string accessToken, string nextPageUrl = "") { var posts = PageManagerUtilities.ReadPost(pageId, accessToken, nextPageUrl); return Json( new { posts.Data, posts.NextPageUrl }); } public JsonResult ReadUnpublishedPost(string pageId, string accessToken, string nextPageUrl = "") { var posts = PageManagerUtilities.ReadUnpublishedPosts(pageId, accessToken, nextPageUrl); return Json(new { posts.Data, posts.NextPageUrl }); } public JsonResult ReadPages(string userInfo) { var posts = PageManagerUtilities.GetPageList(userInfo); return Json(posts.Select(p => new { p.Id, p.Name, p.AccessToken, p.PictureUrl, p.NextPageUrl })); } public JsonResult ReadPageSummary(string pageId, string accessToken) { var posts = PageManagerUtilities.GetPageSummary(pageId, accessToken); return Json(posts.Select(p => new { p.Id, p.Name, p.Title, p.Period, p.Description, p.Values })); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using GameStore.Domain.Infrastructure; using GameStore.Domain.Model; using System.Net.Http; using System.Net; using GameStore.WebUI.Areas.Admin.Models.DTO; using GameStore.WebUI.Areas.Admin.Models; namespace GameStore.WebUI.Apis { [Authorize(Roles = "Admin")] public class OrderController : ApiController { // GET api/<controller> public List<OrderDTO> Get() { List<OrderDTO> list = new List<OrderDTO>(); using (GameStoreDBContext context = new GameStoreDBContext()) { var orders = from o in context.Orders join u in context.Users on o.UserId equals u.Id orderby o.OrderId descending select new { o.OrderId, o.UserId, u.UserName, o.FullName, o.Address, o.City, o.State, o.Zip, o.ConfirmationNumber, o.DeliveryDate }; list = orders.Select(o => new OrderDTO { OrderId = o.OrderId, UserId = o.UserId, UserName = o.UserName, FullName = o.FullName, Address = o.Address, City = o.City, State = o.State, Zip = o.Zip, ConfirmationNumber = o.ConfirmationNumber, DeliveryDate = o.DeliveryDate }).ToList(); } return list; } [Route("api/Order/GetOrderItems/{id}")] public List<OrderItemDTO> GetOrderItems(int id) { List<OrderItemDTO> list = new List<OrderItemDTO>(); using (GameStoreDBContext context = new GameStoreDBContext()) { var orderitems = from i in context.OrderItems join p in context.Products on i.ProductId equals p.ProductId join c in context.Categories on p.CategoryId equals c.CategoryId where i.OrderId == id select new { i.OrderItemId, i.OrderId, i.ProductId, p.ProductName, p.CategoryId, c.CategoryName, p.Price, p.Image, p.Condition, p.Discount, i.Quantity }; list = orderitems.Select(o => new OrderItemDTO { OrderItemId = o.OrderItemId, OrderId = o.OrderId, ProductId = o.ProductId, ProductName = o.ProductName, CategoryId = o.CategoryId, CategoryName = o.CategoryName, Price = o.Price, Image = o.Image, Condition = o.Condition, Discount = o.Discount, Quantity = o.Quantity }).ToList(); } return list; } // GET: api/Order/GetCount/ [Route("api/Order/GetCount")] public int GetCount() { using (GameStoreDBContext context = new GameStoreDBContext()) { return context.Orders.Count(); } } public HttpResponseMessage Delete(int id) { using (GameStoreDBContext context = new GameStoreDBContext()) { var order = context.Orders.Find(id); if (order == null) { return Request.CreateResponse(HttpStatusCode.OK, "No such order [" + id + "]."); } context.Orders.Remove(order); context.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, "Okay"); } } } }
using SDL2; using System; namespace SharpDL.Graphics { [Flags] public enum BlendMode { None = SDL.SDL_BlendMode.SDL_BLENDMODE_NONE, Blend = SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND, Add = SDL.SDL_BlendMode.SDL_BLENDMODE_ADD, Mod = SDL.SDL_BlendMode.SDL_BLENDMODE_MOD, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShowScore : MonoBehaviour { private Text _component; void Start () { this._component = gameObject.GetComponent<Text>(); } // Update is called once per frame void Update () { _component.text = "Score : " + GameManager.Instance.score; } }
 using System.Threading.Tasks; namespace BP.Manager.Manager { public interface IBackgroundTaskHandler<TBackgroundTask> where TBackgroundTask: IBackgroundTaskData { Task StartAsync(BackgroundTask backgroundProcess, IBackgroundTaskData backgroundTask); } }
namespace Blorc.OpenIdConnect { using System.Security.Claims; using System.Text.Json.Serialization; public class Profile { [ClaimType(ClaimTypes.Email)] [JsonPropertyName("email")] public string? Email { get; set; } [JsonPropertyName("email_verified")] public bool EmailVerified { get; set; } [ClaimType(ClaimTypes.Surname)] [JsonPropertyName("family_name")] public string? FamilyName { get; set; } [ClaimType(ClaimTypes.GivenName)] [JsonPropertyName("given_name")] public string? GivenName { get; set; } [ClaimType(ClaimTypes.Name)] [JsonPropertyName("name")] public string? Name { get; set; } [ClaimType("preferred_username")] [JsonPropertyName("preferred_username")] public string? PreferredUsername { get; set; } [ClaimType(ClaimTypes.Role)] [JsonPropertyName("roles")] public string[]? Roles { get; set; } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Hammock; using System.Runtime.Serialization.Json; using System.Collections.Generic; namespace dailyBurnWP7 { public class DailyBurnMealList { public event EventHandler MealListLoaded; private MealNames[] meals; public DailyBurnMealList() { HelperMethods.CallDailyBurnApi(DailyBurnSettings.MealNamesAPI, mealListGetCallback, null); } public Dictionary<int,string> Meals { get { Dictionary<int, string> temp = new Dictionary<int, string>(); temp.Add(0, dbwp7Resources.OptionalAddAParameter); foreach (MealNames m in meals) temp.Add(m.meal_name.id, m.meal_name.name); return temp; } } private void mealListGetCallback(RestRequest request, Hammock.RestResponse response, object obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(MealNames[])); meals = json.ReadObject(response.ContentStream) as MealNames[]; if (MealListLoaded != null) MealListLoaded(this, new EventArgs()); } } public class MealNames { public mealDetails meal_name; } public class mealDetails { public string name; public int id; } }
using System; using System.Globalization; using System.IO; namespace programmersdigest.MT940Parser.Parsing { public class BalanceParser { private StringReader _reader; public Balance ReadBalance(string buffer, BalanceType type) { _reader = new StringReader(buffer); var balance = new Balance { Type = type }; ReadDebitCreditMark(ref balance); return balance; } private void ReadDebitCreditMark(ref Balance balance) { var value = _reader.Read(1); if (value.Length < 1) { throw new InvalidDataException("The balance data ended unexpectedly. Expected credit debit field."); } switch (value) { case "C": balance.Mark = DebitCreditMark.Credit; break; case "D": balance.Mark = DebitCreditMark.Debit; break; default: throw new FormatException($"Debit/Credit Mark must be 'C' or 'D'. Actual: {value}"); } ReadStatementDate(ref balance); } private void ReadStatementDate(ref Balance balance) { var value = _reader.ReadWhile(char.IsDigit, 6); if (value.Length < 6) { throw new InvalidDataException("The balance data ended unexpectedly. Expected value Date with a length of six characters."); } balance.Date = DateParser.Parse(value); ReadCurrency(ref balance); } private void ReadCurrency(ref Balance balance) { var value = _reader.ReadWhile(c => char.IsLetter(c) && char.IsUpper(c), 3); if (value.Length < 3) { throw new InvalidDataException("The balance data ended unexpectedly. Expected value Currency with three uppercase letters."); } balance.Currency = value; ReadAmount(ref balance); } private void ReadAmount(ref Balance balance) { var value = _reader.Read(15); if (value.Length <= 0) { throw new InvalidDataException("The balance data ended unexpectedly. Expected value Amount with a length of at least 1 decimal."); } if (!decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("de"), out var amount)) { throw new FormatException($"Cannot convert value to Decimal: {value}"); } balance.Amount = amount; } } }
using LuaInterface; using SLua; using System; using System.Collections.Generic; using UnityEngine; public class Lua_EventDelegate : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 1) { EventDelegate o = new EventDelegate(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (num == 2) { EventDelegate.Callback call; LuaDelegation.checkDelegate(l, 2, out call); EventDelegate o = new EventDelegate(call); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (num == 3) { MonoBehaviour target; LuaObject.checkType<MonoBehaviour>(l, 2, out target); string methodName; LuaObject.checkType(l, 3, out methodName); EventDelegate o = new EventDelegate(target, methodName); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else { result = LuaObject.error(l, "New object failed."); } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Set(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); MonoBehaviour target; LuaObject.checkType<MonoBehaviour>(l, 2, out target); string methodName; LuaObject.checkType(l, 3, out methodName); eventDelegate.Set(target, methodName); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Execute(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); bool b = eventDelegate.Execute(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Clear(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); eventDelegate.Clear(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Execute_s(IntPtr l) { int result; try { List<EventDelegate> list; LuaObject.checkType<List<EventDelegate>>(l, 1, out list); EventDelegate.Execute(list); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int IsValid_s(IntPtr l) { int result; try { List<EventDelegate> list; LuaObject.checkType<List<EventDelegate>>(l, 1, out list); bool b = EventDelegate.IsValid(list); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Set_s(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate))) { List<EventDelegate> list; LuaObject.checkType<List<EventDelegate>>(l, 1, out list); EventDelegate del; LuaObject.checkType<EventDelegate>(l, 2, out del); EventDelegate.Set(list, del); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate.Callback))) { List<EventDelegate> list2; LuaObject.checkType<List<EventDelegate>>(l, 1, out list2); EventDelegate.Callback callback; LuaDelegation.checkDelegate(l, 2, out callback); EventDelegate o = EventDelegate.Set(list2, callback); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Add_s(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate))) { List<EventDelegate> list; LuaObject.checkType<List<EventDelegate>>(l, 1, out list); EventDelegate ev; LuaObject.checkType<EventDelegate>(l, 2, out ev); EventDelegate.Add(list, ev); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate.Callback))) { List<EventDelegate> list2; LuaObject.checkType<List<EventDelegate>>(l, 1, out list2); EventDelegate.Callback callback; LuaDelegation.checkDelegate(l, 2, out callback); EventDelegate o = EventDelegate.Add(list2, callback); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate), typeof(bool))) { List<EventDelegate> list3; LuaObject.checkType<List<EventDelegate>>(l, 1, out list3); EventDelegate ev2; LuaObject.checkType<EventDelegate>(l, 2, out ev2); bool oneShot; LuaObject.checkType(l, 3, out oneShot); EventDelegate.Add(list3, ev2, oneShot); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate.Callback), typeof(bool))) { List<EventDelegate> list4; LuaObject.checkType<List<EventDelegate>>(l, 1, out list4); EventDelegate.Callback callback2; LuaDelegation.checkDelegate(l, 2, out callback2); bool oneShot2; LuaObject.checkType(l, 3, out oneShot2); EventDelegate o2 = EventDelegate.Add(list4, callback2, oneShot2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o2); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Remove_s(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate))) { List<EventDelegate> list; LuaObject.checkType<List<EventDelegate>>(l, 1, out list); EventDelegate ev; LuaObject.checkType<EventDelegate>(l, 2, out ev); bool b = EventDelegate.Remove(list, ev); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } else if (LuaObject.matchType(l, total, 1, typeof(List<EventDelegate>), typeof(EventDelegate.Callback))) { List<EventDelegate> list2; LuaObject.checkType<List<EventDelegate>>(l, 1, out list2); EventDelegate.Callback callback; LuaDelegation.checkDelegate(l, 2, out callback); bool b2 = EventDelegate.Remove(list2, callback); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b2); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_oneShot(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.oneShot); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_oneShot(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); bool oneShot; LuaObject.checkType(l, 2, out oneShot); eventDelegate.oneShot = oneShot; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_target(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.target); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_target(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); MonoBehaviour target; LuaObject.checkType<MonoBehaviour>(l, 2, out target); eventDelegate.target = target; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_methodName(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.methodName); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_methodName(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); string methodName; LuaObject.checkType(l, 2, out methodName); eventDelegate.methodName = methodName; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_parameters(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.parameters); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_isValid(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.isValid); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_isEnabled(IntPtr l) { int result; try { EventDelegate eventDelegate = (EventDelegate)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, eventDelegate.isEnabled); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "EventDelegate"); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Set)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Execute)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Clear)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Execute_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.IsValid_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Set_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Add_s)); LuaObject.addMember(l, new LuaCSFunction(Lua_EventDelegate.Remove_s)); LuaObject.addMember(l, "oneShot", new LuaCSFunction(Lua_EventDelegate.get_oneShot), new LuaCSFunction(Lua_EventDelegate.set_oneShot), true); LuaObject.addMember(l, "target", new LuaCSFunction(Lua_EventDelegate.get_target), new LuaCSFunction(Lua_EventDelegate.set_target), true); LuaObject.addMember(l, "methodName", new LuaCSFunction(Lua_EventDelegate.get_methodName), new LuaCSFunction(Lua_EventDelegate.set_methodName), true); LuaObject.addMember(l, "parameters", new LuaCSFunction(Lua_EventDelegate.get_parameters), null, true); LuaObject.addMember(l, "isValid", new LuaCSFunction(Lua_EventDelegate.get_isValid), null, true); LuaObject.addMember(l, "isEnabled", new LuaCSFunction(Lua_EventDelegate.get_isEnabled), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_EventDelegate.constructor), typeof(EventDelegate)); } }
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; //namespace ERP.Models.Dal //{ // public class Dal // { // } //} namespace Dal { public sealed class SqlHelper2 { private static SqlDataAdapter adaptr; private static SqlConnection conn; private static SqlCommand command; private static SqlDataReader reader; public SqlHelper2() { adaptr = new SqlDataAdapter(); conn = new SqlConnection(ConfigurationManager.ConnectionStrings ["CS"].ConnectionString); } //return dataset to business layer public static DataSet ExecuteDataSet(string commandText, SqlParameter[] param, bool isProcedure) { command = new SqlCommand(); command.Connection = conn; command.CommandText = commandText; DataSet dataset = new DataSet(); if (isProcedure == false) { command.CommandType = CommandType.Text; } else { command.CommandType = CommandType.StoredProcedure; } if ((param != null) && (param.Length != 0)) { foreach (SqlParameter p in param) { command.Parameters.Add(p); } } adaptr = new SqlDataAdapter(); adaptr.SelectCommand = (SqlCommand)command; adaptr.Fill(dataset); command.Dispose(); return dataset; } //execute procedure without returning cursor public static void ExecuteNonQuery(string commandText, SqlParameter[] param, bool isProcedure) { command = new SqlCommand(); command.Connection = conn; if (conn.State == ConnectionState.Closed) { conn.Open(); } command.CommandText = commandText; if (isProcedure == false) { command.CommandType = CommandType.Text; } else { command.CommandType = CommandType.StoredProcedure; } if ((param != null) && (param.Length != 0)) { foreach (SqlParameter p in param) { command.Parameters.Add(p); } } command.ExecuteNonQuery(); // string rowsEffected = "a"; conn.Close(); command.Dispose(); //return rowsEffected; } //return datatable to business layer public static DataTable ExecuteDataTable(string commandText, SqlParameter[] param, bool isProcedure) { command = new SqlCommand(); command.Connection = conn; command.CommandText = commandText; ; DataTable datatable = new DataTable(); if (isProcedure == false) { command.CommandType = CommandType.Text; } else { command.CommandType = CommandType.StoredProcedure; } if ((param != null) && (param.Length != 0)) { foreach (SqlParameter p in param) { command.Parameters.Add(p); } } adaptr = new SqlDataAdapter(); adaptr.SelectCommand = (SqlCommand)command; adaptr.Fill(datatable); command.Dispose(); return datatable; } //return datareader to business layer public static SqlDataReader ExecuteReader(string commandText, SqlParameter[] param, bool isProcedure) { /// <summary>Executes Command and return DataReader </summary> if (conn.State == ConnectionState.Closed) { conn.Open(); } command = new SqlCommand(); command.CommandText = commandText; if (isProcedure == false) { command.CommandType = CommandType.Text; } else { command.CommandType = CommandType.StoredProcedure; } if ((param != null) && (param.Length != 0)) { foreach (SqlParameter p in param) { command.Parameters.Add(p); } } command.Connection = conn; return (SqlDataReader)command.ExecuteReader(CommandBehavior.CloseConnection); } public static DataTable ExecuteSelectQuery(String _query, SqlParameter[] sqlParameter) { command = new SqlCommand(); DataTable dataTable = new DataTable(); dataTable = null; DataSet ds = new DataSet(); try { if (conn.State == ConnectionState.Closed) { conn.Open(); } command.CommandText = _query; command.Parameters.AddRange(sqlParameter); command.ExecuteNonQuery(); adaptr.SelectCommand = command; adaptr.Fill(ds); dataTable = ds.Tables[0]; } catch (SqlException e) { return null; } finally { // conn.Close; } return dataTable; } public static bool ExecuteInsertQuery(String _query, SqlParameter[] sqlParameter) { command = new SqlCommand(); try { // myCommand.Connection = openConnection(); command.CommandText = _query; command.Parameters.AddRange(sqlParameter); adaptr.InsertCommand = command; command.ExecuteNonQuery(); } catch (SqlException e) { return false; } finally { } return true; } public static bool ExecuteUpdateQuery(String _query, SqlParameter[] sqlParameter) { command = new SqlCommand(); try { // myCommand.Connection = openConnection(); command.CommandText = _query; command.Parameters.AddRange(sqlParameter); adaptr.UpdateCommand = command; command.ExecuteNonQuery(); } catch (SqlException e) { return false; } finally { } return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PPControl : MonoBehaviour { static PPControl instance; public Image pp1; public Image pp2; public GameObject player; public int phypower = 0; // Start is called before the first frame update void Awake() { if (instance != null) Destroy(this); instance = this; } void Start() { } // Update is called once per frame void Update() { phypower=player.GetComponent<Movecontrol>().ppnum; if (phypower == 0) { pp1.gameObject.SetActive(false); pp2.gameObject.SetActive(false); } if (phypower == 1) { pp1.gameObject.SetActive(true); pp2.gameObject.SetActive(false); } if (phypower == 2) { pp1.gameObject.SetActive(true); pp2.gameObject.SetActive(true); } } }
using FastSQL.Sync.Core; using FastSQL.Sync.Core.Indexer; using FastSQL.Sync.Core.Pusher; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FastSQL.API.Controllers { [Route("api/[controller]")] public class PushersController { private readonly IEnumerable<IPusher> _pushers; private readonly IEnumerable<IIndexer> _indexers; public PushersController(IEnumerable<IPusher> pushers, IEnumerable<IIndexer> indexers) { _pushers = pushers; _indexers = indexers; } } }