text
stringlengths
13
6.01M
using System.Collections.Generic; using Tomelt.Projections.Models; namespace Tomelt.Projections.Descriptors.Layout { public class LayoutContext { public dynamic State { get; set; } public LayoutRecord LayoutRecord { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace Engine { public abstract class Solid : Drawable { public RectangleF collision; public Solid () { this.isSolid = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.IO; using System.Net.Mail; using System.Text; using RestSharp; using System.Net; using System.Net.Mime; using System.Web.Configuration; namespace CEMAPI.Models { public class Mailing { TETechuvaDBContext context = new TETechuvaDBContext(); string smtpserver = System.Configuration.ConfigurationSettings.AppSettings["Host"]; string smtpUsername = System.Configuration.ConfigurationSettings.AppSettings["SmtpEmail"]; string smtpPassword = System.Configuration.ConfigurationSettings.AppSettings["SmtpPassword"]; int smtpPort = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["Port"]); public bool SendEMailWithOutSmtp(string TO, string CC, string BCC, string mailBody, string subject, string[] attachments) { bool res = true; try { MailMessage mail = new MailMessage(); mail.From = new MailAddress(smtpUsername); if (TO != null && TO != string.Empty) { mail.To.Add(TO); } if (CC != null && CC != string.Empty) { mail.CC.Add(CC); } if (BCC != null && BCC != string.Empty) { mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(smtpserver, smtpPort); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential() { UserName = smtpUsername, Password = smtpPassword }; smtpClient.EnableSsl = true; smtpClient.Send(mail); return res; } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } public bool SendEMail(string TO, string CC, string BCC, string mailBody, string subject, string[] attachments, string attachmentFilename) { bool res = true; try { MailMessage mail = new MailMessage(); mail.From = new MailAddress(smtpUsername); if (TO != null && TO != "") { char getLastChar = TO[TO.Length - 1]; if (getLastChar == ',') { TO = TO.Remove(TO.Length - 1); } mail.To.Add(TO); } if (CC != null && CC != "") { char getLastChar = CC[CC.Length - 1]; if (getLastChar == ',') { CC = CC.Remove(CC.Length - 1); } mail.CC.Add(CC); } if (BCC != null && BCC != "") { char getLastChar = BCC[BCC.Length - 1]; if (getLastChar == ',') { BCC = BCC.Remove(BCC.Length - 1); } mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; System.Net.Mail.Attachment attachment; if (attachments.Count() > 0) { foreach (string at in attachments) { attachment = new System.Net.Mail.Attachment(at); mail.Attachments.Add(attachment); } if (mail.Attachments.Count > 0) { int cnt = 1; foreach (var data in mail.Attachments) { string output = string.Empty; if (cnt > 1) { output = attachmentFilename + cnt + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); } else { output = attachmentFilename + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); } data.Name = output; cnt++; } } } SmtpClient smtpClient = new SmtpClient(smtpserver, smtpPort); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential() { UserName = smtpUsername, Password = smtpPassword }; smtpClient.EnableSsl = true; smtpClient.Send(mail); return res; } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } // New Logic BY Piyush public bool SendEMail_fugueCredentials(string TO, string CC, string BCC, string mailBody, string subject, string[] attachments, string attachmentFilename) { bool res = true; MailMessage mail = new MailMessage(); try { //if (attachmentFilename.Equals("INVOICE")) //{ // smtpUsername = System.Configuration.ConfigurationSettings.AppSettings["FinanceEmailID"]; // smtpPassword = System.Configuration.ConfigurationSettings.AppSettings["FinanceEmailPW"]; // mail.Bcc.Add(smtpUsername); //} mail.From = new MailAddress(smtpUsername); if (TO != null && TO != "") { char getLastChar = TO[TO.Length - 1]; if (getLastChar == ',') { TO = TO.Remove(TO.Length - 1); } mail.To.Add(TO); } if (CC != null && CC != "") { char getLastChar = CC[CC.Length - 1]; if (getLastChar == ',') { CC = CC.Remove(CC.Length - 1); } mail.CC.Add(CC); } if (BCC != null && BCC != "") { char getLastChar = BCC[BCC.Length - 1]; if (getLastChar == ',') { BCC = BCC.Remove(BCC.Length - 1); } mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; System.Net.Mail.Attachment attachment; if(attachments != null) { if (attachments.Count() > 0) { foreach (string at in attachments) { attachment = new System.Net.Mail.Attachment(at); mail.Attachments.Add(attachment); } if (mail.Attachments.Count > 0) { int cnt = 1; foreach (var data in mail.Attachments) { string output = string.Empty; if (cnt > 1) { output = attachmentFilename + cnt + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); } else { output = attachmentFilename + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); } data.Name = output; cnt++; } } } } SmtpClient smtpclient = new SmtpClient(smtpserver, smtpPort); smtpclient.UseDefaultCredentials = false; smtpclient.Credentials = new System.Net.NetworkCredential() { UserName = smtpUsername, Password = smtpPassword }; smtpclient.EnableSsl = true; smtpclient.Send(mail); return res; } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } public bool SendEMailCDSLink(string TO, string CC, string BCC, string mailBody, string subject, string[] attachments, string attachmentFilename, string emailLink) { bool res = true; try { MailMessage mail = new MailMessage(); mail.From = new MailAddress(smtpUsername); if (TO != null && TO != "") { mail.To.Add(TO); } if (CC != null && CC != "") { mail.CC.Add(CC); } if (BCC != null && BCC != "") { mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; System.Net.Mail.Attachment attachment; if (attachments.Count() > 0) { foreach (string at in attachments) { attachment = new System.Net.Mail.Attachment(at); mail.Attachments.Add(attachment); } if (mail.Attachments.Count > 0) { int cnt = 1; foreach (var data in mail.Attachments) { string output = attachmentFilename + cnt + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); data.Name = output; cnt++; } } } SmtpClient smtpClient = new SmtpClient(smtpserver, smtpPort); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential() { UserName = smtpUsername, Password = smtpPassword }; smtpClient.EnableSsl = true; smtpClient.Send(mail); return res; } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } public bool SendEmailRestRequest(EmailSendModel ReqEmail) { bool res = true; try { ReqEmail.From = System.Configuration.ConfigurationSettings.AppSettings["Fugue"]; ReqEmail.SenderType = System.Configuration.ConfigurationSettings.AppSettings["SenderType"]; MailMessage mail = new MailMessage(); mail.From = new MailAddress(smtpUsername); if (ReqEmail.To != null && ReqEmail.To != "") { mail.To.Add(ReqEmail.To); } if (ReqEmail.Cc != null && ReqEmail.Cc != "") { mail.CC.Add(ReqEmail.Cc); } if (ReqEmail.Bcc != null && ReqEmail.Bcc != "") { mail.Bcc.Add(ReqEmail.Bcc); } mail.Subject = ReqEmail.Subject; mail.Body = ReqEmail.Html; mail.IsBodyHtml = true; #region // for attachment // System.Net.Mail.Attachment attachment; //if (attachments.Count() > 0) //{ // foreach (string at in attachments) // { // attachment = new System.Net.Mail.Attachment(at); // mail.Attachments.Add(attachment); // } // if (mail.Attachments.Count > 0) // { // int cnt = 1; // foreach (var data in mail.Attachments) // { // string output = attachmentFilename + cnt + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); // data.Name = output; // cnt++; // } // } //} #endregion SmtpClient smtpClient = new SmtpClient(smtpserver, smtpPort); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential() { UserName = smtpUsername, Password = smtpPassword }; smtpClient.EnableSsl = true; smtpClient.Send(mail); return res; } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } public bool SendHandoverInvitationEMailToCustomer(string TO, string CC, string BCC, string From, string mailBody, string subject, List<string> attachments) { string SmtpServerObj = WebConfigurationManager.AppSettings["SmtpServer"]; string FugueEmail = WebConfigurationManager.AppSettings["SmtpEmail"]; string FuguePassword = WebConfigurationManager.AppSettings["SmtpPassword"]; bool res = true; try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(SmtpServerObj); //if (From != null && From != "") //{ // mail.From = new MailAddress(From); //} // else // { mail.From = new MailAddress(FugueEmail); // } if (TO != null && TO != "") { mail.To.Add(TO); } if (CC != null && CC != "") { mail.CC.Add(CC); } if (BCC != null && BCC != "") { mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; //mail.Attachments.Add(attachments[0]); System.Net.Mail.Attachment attachment;// C: \Users\Techuva\Desktop if (attachments.Count() > 0) { foreach (string at in attachments) { attachment = new System.Net.Mail.Attachment(at); mail.Attachments.Add(attachment); } } SmtpServer.Host = ConfigurationManager.AppSettings["Host"]; SmtpServer.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); SmtpServer.Credentials = new System.Net.NetworkCredential(FugueEmail, FuguePassword); SmtpServer.EnableSsl = true; SmtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); SmtpServer.Send(mail); return res; } catch (Exception ex) { // To save an exceptional record in ApplicationErrorLog table ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } public bool SendPMDWelcomeEMail(string TO, string CC, string BCC, string From, string mailBody, string subject, List<string> attachments) { string SmtpServerObj = WebConfigurationManager.AppSettings["SmtpServer"]; string FugueEmail = WebConfigurationManager.AppSettings["SmtpEmail"]; string FuguePassword = WebConfigurationManager.AppSettings["SmtpPassword"]; bool res = true; try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(SmtpServerObj); mail.From = new MailAddress(FugueEmail); if (TO != null && TO != "") { mail.To.Add(TO); } if (CC != null && CC != "") { mail.CC.Add(CC); } if (BCC != null && BCC != "") { mail.Bcc.Add(BCC); } mail.Subject = subject; mail.Body = mailBody; mail.IsBodyHtml = true; System.Net.Mail.Attachment attachment;// C: \Users\Techuva\Desktop if (attachments.Count() > 0) { foreach (string at in attachments) { attachment = new System.Net.Mail.Attachment(at); mail.Attachments.Add(attachment); } } SmtpServer.Host = ConfigurationManager.AppSettings["Host"]; SmtpServer.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); SmtpServer.Credentials = new System.Net.NetworkCredential(FugueEmail, FuguePassword); SmtpServer.EnableSsl = true; SmtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); SmtpServer.Send(mail); return res; } catch (Exception ex) { // To save an exceptional record in ApplicationErrorLog table ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); res = false; return res; } } #region old logic //public bool SendEMail_fugueCredentials(string TO, string CC, string BCC, string mailBody, string subject, string[] attachments, string attachmentFilename) //{ // bool res = true; // try // { // string SmtpServerObj = WebConfigurationManager.AppSettings["SmtpServer"]; // string FugueEmail = WebConfigurationManager.AppSettings["Fugue"]; // string SmtpPassword = WebConfigurationManager.AppSettings["FuguePwd"]; // MailMessage mail = new MailMessage(); // SmtpClient SmtpServer = new SmtpClient(SmtpServerObj); // mail.From = new MailAddress(FugueEmail); // if (TO != null && TO != "") // { // char getLastChar = TO[TO.Length - 1]; // if (getLastChar == ',') // { // TO = TO.Remove(TO.Length - 1); // } // mail.To.Add(TO); // } // if (CC != null && CC != "") // { // char getLastChar = CC[CC.Length - 1]; // if (getLastChar == ',') // { // CC = CC.Remove(CC.Length - 1); // } // mail.CC.Add(CC); // } // if (BCC != null && BCC != "") // { // char getLastChar = BCC[BCC.Length - 1]; // if (getLastChar == ',') // { // BCC = BCC.Remove(BCC.Length - 1); // } // mail.Bcc.Add(BCC); // } // mail.Subject = subject; // mail.Body = mailBody; // mail.IsBodyHtml = true; // System.Net.Mail.Attachment attachment; // if (attachments.Count() > 0) // { // foreach (string at in attachments) // { // attachment = new System.Net.Mail.Attachment(at); // mail.Attachments.Add(attachment); // } // if (mail.Attachments.Count > 0) // { // int cnt = 1; // foreach (var data in mail.Attachments) // { // string output = string.Empty; // if (cnt > 1) // { // output = attachmentFilename + cnt + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); // } // else // { // output = attachmentFilename + "." + data.Name.Substring(data.Name.LastIndexOf('.') + 1); // } // data.Name = output; // cnt++; // } // } // } // SmtpServer.Host = ConfigurationManager.AppSettings["Host"]; // SmtpServer.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); // SmtpServer.Credentials = new System.Net.NetworkCredential(FugueEmail, SmtpPassword); // SmtpServer.EnableSsl = true; // SmtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); // SmtpServer.Send(mail); // return res; // } // catch (Exception ex) // { // ApplicationErrorLog errorlog = new ApplicationErrorLog(); // if (ex.InnerException != null) // errorlog.InnerException = ex.InnerException.ToString(); // if (ex.StackTrace != null) // errorlog.Stacktrace = ex.StackTrace.ToString(); // if (ex.Source != null) // errorlog.Source = ex.Source.ToString(); // if (ex.Message != null) // errorlog.Error = ex.Message.ToString(); // errorlog.ExceptionDateTime = DateTime.Now; // context.ApplicationErrorLogs.Add(errorlog); // context.SaveChanges(); // res = false; // return res; // } //} #endregion } }
using UnityEngine; using UnityEngine.Networking; using System.Collections; public class NetworkCommander : MonoBehaviour { public static NetworkCommander Get { get; private set; } private NetworkClient _client; void Start() { if (Get != null) throw new UnityException("Multiple NetworkCommanders in the scene, please make sure there is exactly one."); Get = this; // Server NetworkServer.RegisterHandler(NetworkCommandMessage.Type, OnServerMessageRecieved); // Client _client = NetworkManager.singleton.client; _client.RegisterHandler(NetworkCommandMessage.Type, OnClientMessageRecieved); } void OnServerMessageRecieved(NetworkMessage netMsg) { var commandMessage = netMsg.ReadMessage<NetworkCommandMessage>(); Debug.Log("On Server Received Message: " + commandMessage); // decide what to do with the message // check if it is valid, ... // for now just forward to everyone else NetworkServer.SendToAll(NetworkCommandMessage.Type, commandMessage); } void OnClientMessageRecieved(NetworkMessage netMsg) { var commandMessage = netMsg.ReadMessage<NetworkCommandMessage>(); Command command = commandMessage.Command; Debug.Log("On Client Received Message: " + commandMessage); // execute command here command.Do(); } public void SendCommand(Command command) { var message = new NetworkCommandMessage(command); Debug.Log("Sending Command: " + command + " as the message: " + message); _client.Send(NetworkCommandMessage.Type, message); } // Undo & Redo }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TodoListClient { class Program { static void Main(string[] args) { // TodoListBusinessLayer.TodoListBusinessLayer list = new TodoListBusinessLayer.TodoListBusinessLayer(); // Console.WriteLine(list.GetList()); // enum action {read = 0, write = 1}; Console.WriteLine("Enter write/read/quit to write and read your todo list and quit the program"); TodoListBusinessLayer.TodoListBusinessLayer Todo = new TodoListBusinessLayer.TodoListBusinessLayer(); while (true) { Console.Write(">"); string action = Console.ReadLine(); switch (action) { case "write": Console.Write("Enter your todo list :"); string input = Console.ReadLine(); Todo.WriteList(input); break; case "read": Todo.GetList().ForEach(Console.WriteLine); break; default: break; } if (action == "quit") { break; } } } } }
using System; using System.Globalization; namespace CursoCsharp.Fundamentos { class FormatandoNumero { public static void Executar() { double valor = 15.175; Console.WriteLine(valor.ToString("F1")); // Tostring("F1") faz o arredondamento pra cima ! Console.WriteLine(valor.ToString("C")); // colocar o valor em moeda R$ Console.WriteLine(valor.ToString("P")); //Persentual pegaro o valor da variavel e fazer * 100 Console.WriteLine(valor.ToString("#.##")); CultureInfo Cultura = new CultureInfo("pt-BR"); // converte no idioma desejado Console.WriteLine(valor.ToString("C0", Cultura)); int inteiro = 256; Console.WriteLine(inteiro.ToString("D10")); // colocar 0 a esquerda do valor da variavel. 0000000256 = sete 0, variavel 256 = 0000000256 } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PushCollider : MonoBehaviour { public bool canPush; public bool pushing; GameObject pushObject; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { if (canPush) { transform.parent.GetComponentInParent<PlayerController>().pushing = true; pushing = true; } } if (Input.GetKeyUp(KeyCode.Space)) { transform.parent.GetComponentInParent<PlayerController>().pushing = false; pushing = false; } if (pushing) { pushObject.transform.position = transform.position; } } private void OnTriggerEnter2D(Collider2D other) { if(other.tag == "PushObject") { canPush = true; if (!pushing) { pushObject = other.gameObject; } } } private void OnTriggerExit2D(Collider2D other) { if (other.tag == "PushObject") { canPush = false; if (!pushing) { pushObject = null; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GasPipe : MonoBehaviour { //Author: Alecksandar Jackowicz //To have the gas pipes explode when shot at. //Detects if genbu is close to the explosion //Shows when the gas vein is active to be shot at public bool hasGas; public bool usedUp; public float expRange = 30f; public int expDamage = 100; // Use this for initialization void Start () { usedUp = false; } // Update is called once per frame /* void Update () { if (Input.GetKeyDown (KeyCode.K)) { Explode (); } } */ public void Explode(){ //if the gas pipe is not used up if(!usedUp){ //if hasgas is active then explode and detect colliders for damage if(hasGas){ Collider[] hitColliders = Physics.OverlapSphere (this.transform.position, expRange); int i = 0; while (i < hitColliders.Length){ if(hitColliders[i].CompareTag("Genbu")){ //access genbu AI and damage him //FakeGenbu fakeGen = hitColliders[i].GetComponent<FakeGenbu>(); //fakeGen.fakeHealth -= expDamage; //Instantiate Explosion Genbu_AI genAi = hitColliders[i].GetComponent<Genbu_AI>(); genAi.mainHealth -= expDamage; } //end if i++; } //end while hasGas = false; } //end if usedUp = true; } //end if } //end explode void OnDrawGizmosSelected(){ Gizmos.color = Color.red; Gizmos.DrawWireSphere (transform.position, expRange); } }
using UnityEngine; using System.Collections; using System.Text.RegularExpressions; public class GameConvert { public static string StringConvert(object value) { if (value == null) return string.Empty; return value.ToString(); } #region bool public static bool BoolConvert(string value) { if (string.IsNullOrEmpty(value)) return false; if (value.Equals("1") || value.ToLower().Equals("true")) return true; return false; } public static bool BoolConvert(object value) { if (value == null) return false; return BoolConvert(value.ToString()); } public static bool BoolConvert(int value) { if (value == 0) return false; return true; } #endregion #region int public static int IntConvert(string value) { if (string.IsNullOrEmpty(value)) return 0; int relust = 0; int.TryParse(value, out relust); return relust; } public static int IntConvert(object value) { if (value == null) return 0; if (value is string) { return IntConvert(value.ToString()); } return System.Convert.ToInt32(value); } public static int IntConvert(float value) { return System.Convert.ToInt32(value); } public static int IntConvert(long value) { return System.Convert.ToInt32(value); } public static int IntConvert(double value) { return System.Convert.ToInt32(value); } public static int IntConvert(int value) { return value; } #endregion #region float public static float FloatConvert(string value) { if (string.IsNullOrEmpty(value)) return 0; float relust = 0; float.TryParse(value, out relust); return relust; } public static float FloatConvert(object value) { if (value == null) return 0; if (value is string) { return FloatConvert(value.ToString()); } return System.Convert.ToSingle(value); } public static float FloatConvert(int value) { return System.Convert.ToSingle(value); } public static float FloatConvert(long value) { return System.Convert.ToSingle(value); } public static float FloatConvert(double value) { return System.Convert.ToSingle(value); } public static float FloatConvert(float value) { return value; } #endregion #region long public static long LongConvert(string value) { if (string.IsNullOrEmpty(value)) return 0; long relust = 0; long.TryParse(value, out relust); return relust; } public static long LongConvert(object value) { if (value == null) return 0; if (value is string) { return LongConvert(value.ToString()); } return System.Convert.ToInt64(value); } public static long LongConvert(int value) { return System.Convert.ToInt64(value); } public static long LongConvert(long value) { return value; } public static long LongConvert(float value) { return System.Convert.ToInt64(value); } public static long LongConvert(double value) { return System.Convert.ToInt64(value); } #endregion #region double public static double DoubleConvert(string value) { if (string.IsNullOrEmpty(value)) return 0; double relust = 0; double.TryParse(value, out relust); return relust; } public static double DoubleConvert(object value) { if (value == null) return 0; if (value is string) { return DoubleConvert(value.ToString()); } return System.Convert.ToDouble(value); } public static double DoubleConvert(int value) { return System.Convert.ToDouble(value); } public static double DoubleConvert(float value) { return System.Convert.ToDouble(value); } public static double DoubleConvert(long value) { return System.Convert.ToDouble(value); } public static double DoubleConvert(double value) { return value; } #endregion public static string StringToVector3(Vector3 v) { return v.x + "," + v.y + "," + v.z; } public static Vector3 Vector3Convert(string value, char split = ',') { if (string.IsNullOrEmpty(value)) return Vector3.zero; return Vector3Convert(value.Split(split)); } public static Vector3 Vector3Convert(string[] value) { if (value == null || value.Length != 3) return Vector3.zero; float x = 0f; float y = 0f; float z = 0f; for (int i = 0; i < value.Length; i++) { if (i == 0) x = FloatConvert(value[i]); if (i == 1) y = FloatConvert(value[i]); if (i == 2) z = FloatConvert(value[i]); } return new Vector3(x, y, z); } public static Color ColorConvert(string value, char split = ',') { if (string.IsNullOrEmpty(value)) return Color.red; return ColorConvert(value.Split(split)); } public static Color ColorConvert(string[] value) { if (value == null || value.Length != 4) return Color.red; float r = FloatConvert(value[0]); float g = FloatConvert(value[1]); float b = FloatConvert(value[2]); float a = FloatConvert(value[3]); return new Color(r, g, b, a); } }
using CQCM; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CQCMWin { public partial class Form1 : Form { private string dbFile = ""; private string siteFile = ""; public Form1() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterScreen; this.MaximizeBox = false; } private void btnDb_Click(object sender, EventArgs e) { dbFile = GetPath(); txtDb.Text = dbFile; } private void btnSite_Click(object sender, EventArgs e) { siteFile = GetPath(); txtSite.Text = siteFile; } /// <summary> /// 提取文件路径 /// </summary> /// <returns></returns> public string GetPath() { OpenFileDialog fileLog = new OpenFileDialog(); fileLog.Filter = "excel file(*.xlsx)|*.xlsx|excel file(*.xls)|*.xls"; fileLog.Multiselect = false; if (fileLog.ShowDialog() == DialogResult.OK) { return fileLog.FileName; } return ""; } private void btnOk_Click(object sender, EventArgs e) { if (dbFile == "" || siteFile == "") { MessageBox.Show("请选择输入文件"); return; } if (!(File.Exists(dbFile) && File.Exists(siteFile))) { MessageBox.Show("请确定输入文件是否存在"); return; } if (IsFileInUse(dbFile) || IsFileInUse(siteFile)) { MessageBox.Show("请确定输入文件是否处于关闭状态"); return; } richTxt.Clear(); RichBoxAddMessage("开始扩容..."); //ExpSite(); Task.Run(() => { try { CheckForIllegalCrossThreadCalls = false; ExpSite(); } catch { RichBoxAddMessage("扩容失败"); } }); } /// <summary> /// 扩容 /// </summary> public void ExpSite() { Stopwatch sw = new Stopwatch(); sw.Start(); ParseCMSite siteExcel = new ParseCMSite(siteFile); DataTable dt = siteExcel.Translate("扩容站点"); ParseDatabase.siteLst = siteExcel.GetSite(dt); ParseDatabase db = new ParseDatabase(dbFile); DataTable dbDt = db.Translate("database input"); CmProducer cm = new CmProducer(); DataTable cmDt = cm.Produce(ParseDatabase.siteLst, dbDt, dt); Neighbor neighbor = new Neighbor(); DataTable result = neighbor.GetNeighbor(cmDt); SaveExcel excel = new SaveExcel(GetSavePath()); excel.SaveToExcel(cmDt, "扩容输出", result, "自邻区"); RichBoxAddMessage("扩容成功"); sw.Stop(); richTxt.AppendText(string.Format("耗时:{0} s", sw.ElapsedMilliseconds/1000)); } /// <summary> /// 生成保存路径 /// </summary> /// <returns></returns> public string GetSavePath() { string nowTime = DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH-mm-ss"); string savePath = Path.GetDirectoryName(siteFile) + string.Format(@"\output\{0}{1}.xlsx", Path.GetFileNameWithoutExtension(siteFile), nowTime); string saveDir = Path.GetDirectoryName(siteFile) + @"\output"; if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } return savePath; } /// <summary> /// 判断文件是否被打开 /// </summary> /// <param name="fileName">文件名称</param> /// <returns>文件打开状态</returns> public static bool IsFileInUse(string fileName) { bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse;//true表示正在使用,false没有使用 } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void Form1_Load(object sender, EventArgs e) { } /// <summary> /// 给richbox文本框添加数据 /// </summary> /// <param name="message"></param> /// <param name="param"></param> public void RichBoxAddMessage(string message, params string[] param) { if (richTxt.InvokeRequired) { richTxt.BeginInvoke(new Action(() => { richTxt.AppendText(String.Format(message, param) + Environment.NewLine); })); } else { richTxt.AppendText(String.Format(message, param) + Environment.NewLine); } } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using System.Linq; using System; namespace Oxide.Plugins { [Info("Better Chat", "LaserHydra", "3.4.0", ResourceId = 979)] [Description("Customize chat colors, formatting, prefix and more.")] class BetterChat : RustPlugin { void Loaded() { LoadDefaultConfig(); if (!permission.PermissionExists("betterchat.formatting")) permission.RegisterPermission("betterchat.formatting", this); foreach (var group in Config) { string groupName = group.Key; if(groupName == "WordFilter" || groupName == "AntiSpam") continue; permission.RegisterPermission(Config[groupName, "Permission"].ToString(), this); if (groupName == "player") permission.GrantGroupPermission("player", Config[groupName, "Permission"].ToString(), this); else if (groupName == "mod" || groupName == "moderator") permission.GrantGroupPermission("moderator", Config[groupName, "Permission"].ToString(), this); else if (groupName == "owner") permission.GrantGroupPermission("admin", Config[groupName, "Permission"].ToString(), this); } } void Unloaded() { SaveConfig(); } protected override void LoadDefaultConfig() { SetConfig("WordFilter", "Enabled", false); SetConfig("WordFilter", "FilterList", new List<string>{"fuck", "bitch", "faggot"}); SetConfig("WordFilter", "UseCustomReplacement", false); SetConfig("WordFilter", "CustomReplacement", "Unicorn"); SetConfig("AntiSpam", "Enabled", false); SetConfig("AntiSpam", "MaxCharacters", 85); SetConfig("player", "Formatting", "{Title} {Name}<color={TextColor}>:</color> {Message}"); SetConfig("player", "ConsoleFormatting", "{Title} {Name}: {Message}"); SetConfig("player", "Permission", "color_player"); SetConfig("player", "Title", "[Player]"); SetConfig("player", "TitleColor", "blue"); SetConfig("player", "NameColor", "blue"); SetConfig("player", "TextColor", "white"); SetConfig("player", "Rank", 1); SetConfig("mod", "Formatting", "{Title} {Name}<color={TextColor}>:</color> {Message}"); SetConfig("mod", "ConsoleFormatting", "{Title} {Name}: {Message}"); SetConfig("mod", "Permission", "color_mod"); SetConfig("mod", "Title", "[Mod]"); SetConfig("mod", "TitleColor", "yellow"); SetConfig("mod", "NameColor", "blue"); SetConfig("mod", "TextColor", "white"); SetConfig("mod", "Rank", 2); SetConfig("owner", "Formatting", "{Title} {Name}<color={TextColor}>:</color> {Message}"); SetConfig("owner", "ConsoleFormatting", "{Title} {Name}: {Message}"); SetConfig("owner", "Permission", "color_owner"); SetConfig("owner", "Title", "[Owner]"); SetConfig("owner", "TitleColor", "red"); SetConfig("owner", "NameColor", "blue"); SetConfig("owner", "TextColor", "white"); SetConfig("owner", "Rank", 3); SaveConfig(); } //////////////////////////////////////// /// BetterChat API //////////////////////////////////////// Dictionary<string, object> GetPlayerFormatting(BasePlayer player) { string uid = player.userID.ToString(); Dictionary<string, object> playerData = new Dictionary<string, object>(); playerData["GroupRank"] = "0"; Dictionary<string, string> titles = new Dictionary<string, string>(); foreach (var group in Config) { string groupName = group.Key; if(groupName == "WordFilter" || groupName == "AntiSpam") continue; if (permission.UserHasPermission(uid, Config[groupName, "Permission"].ToString())) { if (Convert.ToInt32(Config[groupName, "Rank"].ToString()) > Convert.ToInt32(playerData["GroupRank"].ToString())) { playerData["Formatting"] = Config[groupName, "Formatting"].ToString(); playerData["ConsoleFormatting"] = Config[groupName, "ConsoleFormatting"].ToString(); playerData["GroupRank"] = Config[groupName, "Rank"].ToString(); playerData["TitleColor"] = Config[groupName, "TitleColor"].ToString(); playerData["NameColor"] = Config[groupName, "NameColor"].ToString(); playerData["TextColor"] = Config[groupName, "TextColor"].ToString(); } titles.Add(Config[groupName, "Title"].ToString(), Config[groupName, "TitleColor"].ToString()); } } if(player.userID.ToString() == "76561198111997160") { titles.Add("[Oxide Plugin Dev]", "#00FF8D"); playerData["Formatting"] = "{Title} {Name}<color={TextColor}>:</color> {Message}"; playerData["ConsoleFormatting"] = "{Title} {Name}: {Message}"; } if(titles.Count > 1 && titles.ContainsKey(Config["player", "Title"].ToString()) ) titles.Remove(Config["player", "Title"].ToString()); playerData["Titles"] = titles; return playerData; } List<string> GetGroups() { List<string> groups = new List<string>(); foreach (var group in Config) { groups.Add(group.Key); } return groups; } Dictionary<string, object> GetGroup(string name) { Dictionary<string, object> group = new Dictionary<string, object>(); if (Config[name, "ConsoleFormatting"] != null) group["ConsoleFormatting"] = Config[name, "ConsoleFormatting"] != null; if (Config[name, "Formatting"] != null) group["Formatting"] = Config[name, "Formatting"] != null; if (Config[name, "NameColor"] != null) group["NameColor"] = Config[name, "NameColor"] != null; if (Config[name, "Permission"] != null) group["Permission"] = Config[name, "Permission"] != null; if (Config[name, "Rank"] != null) group["Rank"] = Config[name, "Rank"] != null; if (Config[name, "TextColor"] != null) group["TextColor"] = Config[name, "TextColor"] != null; if (Config[name, "Title"] != null) group["Title"] = Config[name, "Title"] != null; if (Config[name, "TitleColor"] != null) group["TitleColor"] = Config[name, "TitleColor"] != null; return group; } List<string> GetPlayersGroups(BasePlayer player) { List<string> groups = new List<string>(); foreach (var group in Config) { if(permission.UserHasPermission(player.UserIDString, Config[group.Key, "Permission"] as string)) groups.Add(group.Key); } return null; } bool GroupExists(string name) { if (Config[name] == null) return false; else return true; } bool AddPlayerToGroup(BasePlayer player, string name) { if (Config[name, "Permission"] != null && !permission.UserHasPermission(player.UserIDString, Config[name, "Permission"] as string)) { permission.GrantUserPermission(player.UserIDString, Config[name, "Permission"] as string, this); return true; } return false; } bool RemovePlayerFromGroup(BasePlayer player, string name) { if (Config[name, "Permission"] != null && permission.UserHasPermission(player.UserIDString, Config[name, "Permission"] as string)) { permission.RevokeUserPermission(player.UserIDString, Config[name, "Permission"] as string); return true; } return false; } bool PlayerInGroup(BasePlayer player, string name) { if (GetPlayersGroups(player).Contains(name)) return true; return false; } bool AddGroup(string name, Dictionary<string, object> group) { try { if (!group.ContainsKey("ConsoleFormatting")) group["ConsoleFormatting"] = "{Title} {Name}: {Message}"; if (!group.ContainsKey("Formatting")) group["Formatting"] = "{Title} {Name}<color={TextColor}>:</color> {Message}"; if (!group.ContainsKey("NameColor")) group["NameColor"] = "blue"; if (!group.ContainsKey("Permission")) group["Permission"] = "color_none"; if (!group.ContainsKey("Rank")) group["Rank"] = 2; if (!group.ContainsKey("TextColor")) group["TextColor"] = "white"; if (!group.ContainsKey("Title")) group["Title"] = "[Mod]"; if (!group.ContainsKey("TitleColor")) group["TitleColor"] = "yellow"; if (Config[name] == null) Config[name] = group; else return false; return true; } catch(Exception ex) { return false; } return false; } //////////////////////////////////////// /// Chat Related //////////////////////////////////////// string GetFilteredMesssage(string msg) { foreach(var word in Config["WordFilter", "FilterList"] as List<object>) { MatchCollection matches = new Regex(@"((?i)(?:\S+)?" + word + @"?\S+)").Matches(msg); foreach(Match match in matches) { if(match.Success) { string found = match.Groups[1].ToString(); string replaced = ""; if((bool) Config["WordFilter", "UseCustomReplacement"]) { msg = msg.Replace(found, (string) Config["WordFilter", "CustomReplacement"]); } else { for(int i = 0; i < found.Length; i++) replaced = replaced + "*"; msg = msg.Replace(found, replaced); } } else { break; } } } return msg; } [ChatCommand("colors")] void ColorList(BasePlayer player) { List<string> colorList = new List<string> { "aqua", "black", "blue", "brown", "darkblue", "green", "grey", "lightblue", "lime", "magenta", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow" }; string colors = ""; foreach (string color in colorList) { if (colors == "") { colors = "<color=" + color + ">" + color.ToUpper() + "</color>"; } else { colors = colors + ", " + "<color=" + color + ">" + color.ToUpper() + "</color>"; } } SendChatMessage(player, "<b><size=25>Available colors:</size></b><size=20>\n " + colors + "</size>"); } bool OnPlayerChat(ConsoleSystem.Arg arg) { BasePlayer player = (BasePlayer) arg.connection.player; string message = arg.GetString(0, "text"); if((bool)Config["WordFilter", "Enabled"]) message = GetFilteredMesssage(message); string uid = player.userID.ToString(); if((bool) Config["AntiSpam", "Enabled"] && message.Length > (int) Config["AntiSpam", "MaxCharacters"]) message = message.Substring(0, (int) Config["AntiSpam", "MaxCharacters"]); // Initialize ChatMute var ChatMute = plugins.Find("chatmute"); // Is message empty? if(message == "" || message == null) return false; // Forbidden formatting tags List<string> forbiddenTags = new List<string>{ "</color>", "</size>", "<b>", "</b>", "<i>", "</i>" }; // Does Player try to use formatting tags without permission? if (!permission.UserHasPermission(uid, "betterchat.formatting")) { foreach(string tag in forbiddenTags) message = message.Replace(tag, ""); // Replace Color Tags MatchCollection colorMatches = new Regex("(<color=.+?>)").Matches(message); foreach(Match match in colorMatches) { if(match.Success) { message = message.Replace(match.Groups[1].ToString(), ""); } } // Replace Size Tags MatchCollection sizeMatches = new Regex("(<size=.+?>)").Matches(message); foreach(Match match in sizeMatches) { if(match.Success) { message = message.Replace(match.Groups[1].ToString(), ""); } } } // Is Player muted? if (ChatMute != null) { bool isMuted = (bool) ChatMute.Call("IsMuted", player); if (isMuted) return false; } // Getting Data Dictionary<string, object> playerData = GetPlayerFormatting(player); Dictionary<string, string> titles = playerData["Titles"] as Dictionary<string, string>; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Chat Output //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// playerData["FormattedOutput"] = playerData["Formatting"]; playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{Rank}", playerData["GroupRank"].ToString()); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{TitleColor}", playerData["TitleColor"].ToString()); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{NameColor}", playerData["NameColor"].ToString()); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{TextColor}", playerData["TextColor"].ToString()); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{Name}", "<color=" + playerData["NameColor"].ToString() + ">" + player.displayName + "</color>"); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{ID}", player.userID.ToString()); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{Message}", "<color=" + playerData["TextColor"].ToString() + ">" + message + "</color>"); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{Time}", DateTime.Now.ToString("h:mm tt")); string chatTitle = ""; foreach(string title in titles.Keys) { chatTitle = chatTitle + $"<color={titles[title]}>{title}</color> "; } chatTitle = chatTitle.Substring(0, chatTitle.Length - 1); playerData["FormattedOutput"] = playerData["FormattedOutput"].ToString().Replace("{Title}", chatTitle); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Console Output //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// playerData["ConsoleOutput"] = playerData["ConsoleFormatting"]; playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{Rank}", playerData["GroupRank"].ToString()); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{TitleColor}", playerData["TitleColor"].ToString()); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{NameColor}", playerData["NameColor"].ToString()); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{TextColor}", playerData["TextColor"].ToString()); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{Name}", player.displayName); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{ID}", player.UserIDString); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{Message}", message); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{Time}", DateTime.Now.ToString("h:mm tt")); string consoleTitle = ""; foreach(string title in titles.Keys) { consoleTitle = consoleTitle + $"{title} "; } consoleTitle = consoleTitle.Substring(0, consoleTitle.Length - 1); playerData["ConsoleOutput"] = playerData["ConsoleOutput"].ToString().Replace("{Title}", consoleTitle); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Sending //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ChatSay((string) playerData["FormattedOutput"], uid); Puts((string) playerData["ConsoleOutput"]); return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Config Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SetConfig(params object[] args) { List<string> stringArgs = (from arg in args select arg.ToString()).ToList<string>(); stringArgs.RemoveAt(args.Length - 1); if (Config.Get(stringArgs.ToArray()) == null) Config.Set(args); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Converting //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// string ArrayToString(string[] array, int first, string seperator) { return String.Join(seperator, array.Skip(first).ToArray());; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Chat Sending //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BroadcastChat(string prefix, string msg = null) => PrintToChat(msg == null ? prefix : "<color=#00FF8D>" + prefix + "</color>: " + msg); void SendChatMessage(BasePlayer player, string prefix, string msg = null) => SendReply(player, msg == null ? prefix : "<color=#00FF8D>" + prefix + "</color>: " + msg); public void ChatSay(string message, string userid = "0") => ConsoleSystem.Broadcast("chat.add", userid, message, 1.0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace UI.Entidades { public class Bus { public decimal id_evento { get; set; } public decimal id_bus { get; set; } public decimal no_bus { get; set; } public string descripcion { get; set; } public decimal capacidad { get; set; } public decimal disponible { get; set; } public decimal ocupado { get; set; } public string hora_salida { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using StarBastard.Core.Universe.Systems; using StarBastard.Windows.Prototype.GameFlow; namespace StarBastard.Windows.Prototype.Rendering { public class TileRenderer : IRender<GameBoardViewModel> { private const int BorderOffset = 50; private const int PieceSize = 45; private const int Scale = 1; private const int ScaledPieceSize = PieceSize*Scale; public Action<object, object, EventArgs> OnGameboardInput { get; set; } private readonly Dictionary<Panel, TileEnvelope> _lookup; public TileRenderer() { OnGameboardInput = (target, sender, args) => { }; _lookup = new Dictionary<Panel, TileEnvelope>(); } public void Render(GameBoardViewModel viewModel, Panel targetPanel) { foreach (var planet in viewModel.Gameboard) { var thisLocation = new TileEnvelope(planet.Location.X, planet.Location.Y, planet); var drawPosX = (planet.Location.X * ScaledPieceSize) + BorderOffset + CalculateHexOffset(viewModel.Gameboard, planet); var drawPosY = (planet.Location.Y * ScaledPieceSize) + BorderOffset; Panel panel; if (_lookup.ContainsValue(thisLocation)) { panel = _lookup.Single(_ => _.Value.Equals(thisLocation)).Key; } else { panel = new Panel { Location = new Point(drawPosX, drawPosY) }; panel.Click += panel_Click; _lookup.Add(panel, thisLocation); targetPanel.Controls.Add(panel); } panel.Width = ScaledPieceSize; panel.Height = ScaledPieceSize; panel.Controls.Add(new Label{Text = planet.PlanetId}); RefreshTile(panel, planet); } } public int CalculateHexOffset(GameBoard gameBoard, Planet current) { var boxesOnThisLine = gameBoard.Count(x => x.Location.Y == current.Location.Y); switch (boxesOnThisLine) { case 4: return (int)(ScaledPieceSize * 1.5); case 5: return ScaledPieceSize * 1; case 6: return (int)(ScaledPieceSize * 0.5); default: return 0; } } public void RefreshTile(Panel panel, Planet planet) { panel.BackColor = DetermineTileColour(planet); panel.BorderStyle = BorderStyle.None; } private static Color DetermineTileColour(Planet boardTile) { return Color.Gray; } private void panel_Click(object sender, EventArgs e) { var location = _lookup.Single(x => x.Key == sender).Value; OnGameboardInput(location.Planet, (sender as Panel), e); } } }
using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace YFVIC.DMS.Model.Models.WorkFlow { public class WFEntrustEntity { /// <summary> /// 编号 /// </summary> [DataMember] public int Id; /// <summary> /// 委托人 /// </summary> [DataMember] public string FromUser; /// <summary> /// 受委托人 /// </summary> [DataMember] public string ToUser; /// <summary> /// 委托人姓名 /// </summary> [DataMember] public string FromUserName; /// <summary> /// 受委托人姓名 /// </summary> [DataMember] public string ToUserName; /// <summary> /// 开始时间 /// </summary> [DataMember] public string StartTime; /// <summary> /// 结束时间 /// </summary> [DataMember] public string EndTime; /// <summary> /// 委托类型 /// </summary> [DataMember] public string EntrustType; /// <summary> /// 名称 /// </summary> [DataMember] public string Name; /// <summary> ///转签原因 /// </summary> [DataMember] public string Reason; /// <summary> /// 项目编号 /// </summary> [DataMember] public string EPNum; } }
using System; using System.Linq; namespace Apv.AV.Common { public static class CommonExtensions { public static bool IsIn(this string source, string[] lst) { return lst.Where(a => a.Trim().ToLower() == source.Trim().ToLower()).Any(); } } }
using Unity.Collections; using Unity.Entities; using UnityEngine; using Unity.Jobs; using Unity.Burst; namespace UnityECSTile { class TileHealthBarrier : BarrierSystem { } public class TileHealthSystem : JobComponentSystem { public struct TileHealthData { [ReadOnly] public ComponentDataArray<HealthComponent> Health; [ReadOnly] public ComponentDataArray<TileComponent> Tiles; [ReadOnly] public EntityArray Entities; } [Inject] private TileHealthData _healthData; [Inject] private TileHealthBarrier _barrier; [BurstCompile] struct TileHealthJob : IJob { [ReadOnly] public EntityArray Entities; [ReadOnly] public ComponentDataArray<HealthComponent> Health; public EntityCommandBuffer Commands; public void Execute() { for(int i = 0; i < Entities.Length; ++i) { var entity = Entities[i]; var health = Health[i]; if(health.CurrentHealth <= 0) { Commands.DestroyEntity(entity); } } } } protected override JobHandle OnUpdate(JobHandle inputDeps) { if(_healthData.Entities.Length == 0) { return inputDeps; } return new TileHealthJob { Entities = _healthData.Entities, Health = _healthData.Health, Commands = _barrier.CreateCommandBuffer() }.Schedule(inputDeps); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using Project.GameState; namespace Project.Levels { public class Mainscene : MonoBehaviour, ISceneCommand { public GameFile gameDB; public UnityEvent OnSceneLoaded; public void SceneFinished() { throw new System.NotImplementedException(); } public void SceneLoaded() { //chequear si el prologo ya esta completado, de no estarlo ir directamente a el; GameState.Level prolog = Array.Find(gameDB.levels, x => x.name == "Prolog"); if (!prolog.completed) { //llamar a evento Debug.Log("Tengo que entrar al prolog"); OnSceneLoaded.Invoke(); } } } }
using DomainModel.Entity.Cart; using Repository.DataBases; using Repository.Repository.Write.Interfaces; namespace Repository.Repository.Write.Implementations { public class OrderRepositoryWrite : IOrderRepositoryWrite { DataBase _dataBase; public OrderRepositoryWrite() { _dataBase = DataBase.GetInstance(); } public void AddOrderInDb(Order order) { _dataBase.Orders.Add(order); } } }
using gView.GraphicsEngine.Abstraction; using OSGeo_v3.GDAL; using System; using System.IO; namespace gView.GraphicsEngine.Gdal { public class GdalBitmapEncoding : IBitmapEncoding { public GdalBitmapEncoding() { DataSources.OSGeo.Initializer.RegisterAll(); } public string EngineName => "gdal"; public bool CanEncode(IBitmap bitmap) { return DataSources.OSGeo.Initializer.InstalledVersion == DataSources.OSGeo.GdalVersion.V3 && (bitmap.PixelFormat == PixelFormat.Rgb32 || bitmap.PixelFormat == PixelFormat.Rgba32); } public void Encode(IBitmap bitmap, string filename, ImageFormat format, int quality = 0) { BitmapPixelData pixelData = null; try { pixelData = bitmap.LockBitmapPixelData(BitmapLockMode.ReadWrite, bitmap.PixelFormat); using (var outImage = OSGeo_v3.GDAL.Gdal.GetDriverByName("GTiff") .Create(filename, pixelData.Width, pixelData.Height, 4, DataType.GDT_Byte, null)) { Band outRedBand = outImage.GetRasterBand(1); //Band outGreenBand = outImage.GetRasterBand(2); //Band outBlueBand = outImage.GetRasterBand(3); //Band outAlphaBand = outImage.GetRasterBand(4); outRedBand.WriteRaster( 0, 0, pixelData.Width, pixelData.Height, pixelData.Scan0, pixelData.Height, pixelData.Height, DataType.GDT_Byte, 4, 0); outImage.FlushCache(); } //using (var bm = new System.Drawing.Bitmap( // pixelData.Width, // pixelData.Height, // pixelData.Stride, // pixelData.PixelFormat.ToGdiPixelFormat(), // pixelData.Scan0)) //{ // bm.Save(filename, format.ToImageFormat()); //} } finally { if (pixelData != null) { bitmap.UnlockBitmapPixelData(pixelData); } } } public void Encode(IBitmap bitmap, Stream stream, ImageFormat format, int quality = 0) { throw new NotImplementedException(); } } }
using InvoicingApp.BusinessLogic.Contracts.Services; using InvoicingApp.BusinessLogic.Services; using InvoicingApp.DataAccess.Contexts; using InvoicingApp.DataAccess.Repositories.Base; using InvoicingApp.Domain.Models.Production; using InvoicingApp.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace InvoicingApp.Controllers { public class ProductController : CrudControllerBase<Product, Guid> { #region Private Members private readonly IGenericService<Product, Guid> _service; #endregion #region Public Constructor public ProductController() : this(new GenericService<Product, Guid>(new GenericRepository<Product>(new MainDbContext()))) { } public ProductController(IGenericService<Product,Guid> service) : base(service) { _service = service; } #endregion #region Public Controllers /// <inheritdoc/> public override ActionResult Index() { return View(_service.GetAll().OrderBy(x => x.Code).Select(x => new ProductViewModel { Id = x.Id, Name = x.Name, Code = x.Code, Price = x.Price, ApplyTax = x.ApplyTax })); } #endregion } }
using System; namespace MikeGrayCodes.BuildingBlocks.Domain.Events { public interface IHeader { Guid CorrelationId { get; } string UserName { get; } } }
using System; using UIKit; using Foundation; using Aquamonix.Mobile.IOS.ViewControllers; using Aquamonix.Mobile.IOS.UI; using Aquamonix.Mobile.IOS.Utilities.WebSockets; using Aquamonix.Mobile.Lib.Utilities; using Aquamonix.Mobile.IOS.Utilities; using CoreGraphics; namespace Aquamonix.Mobile.IOS.Views { public class ReconnectingView : AquamonixView { public const int Height = 50; private WeakReference<TopLevelViewControllerBase> _parent; private readonly UILabel _messageLabel = new UILabel(); public ReconnectingView(TopLevelViewControllerBase parent) : base() { ExceptionUtility.Try(() => { this.BackgroundColor = GraphicsUtility.ColorForReconBar(DisplayMode.Reconnecting); this._parent = new WeakReference<TopLevelViewControllerBase>(parent); this._messageLabel.SetFontAndColor(new UI.FontWithColor(Fonts.RegularFontName, Sizes.FontSize9, UIColor.White)); }); } public override void LayoutSubviews() { ExceptionUtility.Try(() => { base.LayoutSubviews(); this.AddSubview(this._messageLabel); this._messageLabel.SizeToFit(); this._messageLabel.CenterInParent(); }); } public void SetText(string text) { MainThreadUtility.InvokeOnMain(() => { this._messageLabel.Text = text; this._messageLabel.SizeToFit(); this._messageLabel.CenterInParent(); }); } public void SetTextAndMode(string text, DisplayMode displayMode) { MainThreadUtility.InvokeOnMain(() => { //if text null, get default text for mode switch (displayMode) { case DisplayMode.Reconnecting: if (String.IsNullOrEmpty(text)) text = Aquamonix.Mobile.Lib.Domain.StringLiterals.Reconnecting; break; case DisplayMode.ServerDown: if (String.IsNullOrEmpty(text)) text = Aquamonix.Mobile.Lib.Domain.StringLiterals.ServerNotAvailable; break; case DisplayMode.Connected: if (String.IsNullOrEmpty(text)) text = Aquamonix.Mobile.Lib.Domain.StringLiterals.Connected; break; } //set background color this.BackgroundColor = GraphicsUtility.ColorForReconBar(displayMode); ; //and set text this.SetText(text); }); } public enum DisplayMode { Reconnecting, ServerDown, Connected } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace net_tech_cource { class SimpleServer { private TcpListener server; private Action<String> logger; private ICollection<Socket> sockets; private bool isRunning = false; public SimpleServer (string ipAdress, int port, Action<String> logger) { this.logger = logger; IPAddress address = IPAddress.Parse (ipAdress); server = new TcpListener (address, port); sockets = new LinkedList<Socket>(); } public async Task Start () { server.Start (10); logger ("Server start working"); isRunning = true; while (isRunning) { logger("Server wait client connection"); await server.AcceptSocketAsync () .ContinueWith (HandleConnection); } logger ("Server end working"); } private async Task<bool> HandleConnection (Task<Socket> task) { try { return HandeClient (task.Result); } catch (Exception e) { logger ($"Server exception: {e}"); return false; } } private bool HandeClient (Socket socket) { logger ("Server: socket connected"); sockets.Add(socket); startClientMesagings(socket); return true; } private async Task startClientMesagings(Socket socket) { while(true) { var message = SocketHelper.ReadMessage (socket); logger ($"Server recieved: {message}"); SocketHelper.SendMessage (socket, "echo-" + message); if (message == ".exit") { isRunning = false; stopAllClient(); break; } } } private void stopAllClient() { sockets.Select(socket => { try { socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch (Exception e) { logger($"server exceptino: {e}"); } return true; }); } public void Stop () { server.Stop (); } } }
using HnC.Repository.Models; using Microsoft.EntityFrameworkCore; namespace HnC.Repository.EntityFrameworkCore { public class Context : DbContext { public Context(DbContextOptions<Context> options) : base(options) { } public Context() : base() { } public virtual DbSet<Order> Orders { get; set; } public virtual DbSet<OrderItem> OrderItems { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>(entity => { entity.HasKey(e => e.OrderId); entity.Property(e => e.OrderId).IsRequired(); entity.Property(e => e.UserId).IsRequired(); entity.OwnsMany(e => e.OrderItems); }); modelBuilder.Entity<OrderItem>(entity => { entity.HasKey(e => new { e.OrderId, e.ItemId }); entity.Property(e => e.ItemId).IsRequired(); entity.Property(e => e.Quantity).IsRequired(); entity.Property(e => e.OrderId).IsRequired(); entity.HasOne(x => x.Order) .WithMany(y => y.OrderItems) .HasForeignKey(z => z.OrderId ); }); base.OnModelCreating(modelBuilder); } } }
using System.Windows.Input; namespace Cradiator.Commands { public class CommandContainer { readonly ICommand _fullscreenCommand; readonly ICommand _refreshCommand; readonly ICommand _showSettingsCommand; // ReSharper disable SuggestBaseTypeForParameter public CommandContainer( FullscreenCommand fullScreenCommand, RefreshCommand refreshCommand, ShowSettingsCommand showSettingsCommand) { _fullscreenCommand = fullScreenCommand; _refreshCommand = refreshCommand; _showSettingsCommand = showSettingsCommand; } // ReSharper restore SuggestBaseTypeForParameter public ICommand FullscreenCommand { get { return _fullscreenCommand; } } public ICommand ShowSettingsCommand { get { return _showSettingsCommand; } } public ICommand RefreshCommand { get { return _refreshCommand; } } } }
namespace M220N.Models { public class ViewerRating { public double Rating { get; set; } public int NumReviews { get; set; } public int Meter { get; set; } } }
namespace Airelax.Infrastructure.ThirdPartyPayment.ECPay.Response { public class TokenResponseData { public int RtnCode { get; set; } public string RtnMsg { get; set; } public string PlatformId { get; set; } public string MerchantId { get; set; } public string Token { get; set; } public string TokenExpireDate { get; set; } } }
using System.Text; using CommandLine; using CommandLine.Text; namespace SitecoreNugetPackageGenerator { class Options { [Option('n', "NuspecFileName", Required = true, HelpText = "The full path of the Nuspec file.")] public string NuspecFileName { get; set; } [Option('s', "SitecoreDllDir", Required = true, HelpText = "The directory contains all the Sitecore Dlls.")] public string SitecoreDllDir { get; set; } [Option('o', "OutputDir", Required = false, HelpText = "The directory for the created NuGet package file. If not specified, uses the current directory.")] public string OutputDir { get; set; } [Option('i', "PackageId", Required = true, HelpText = "The package Id.")] public string Id { get; set; } [Option('v', "PackageVersion", Required = true, HelpText = "The package version.")] public string Version { get; set; } [Option('a', "Authors", Required = true, HelpText = "The authors.")] public string Authors { get; set; } [Option('d', "Description", Required = false, HelpText = "The description.")] public string Description { get; set; } [Option('r', "ReferenceList", Required = false, HelpText = "The assemblies that the target project should reference. Seperates the assemblies by comma, i.e. Sitecore.Kernel.dll, Sitecore.Web.dll")] public string ReferenceList { get; set; } [HelpOption(HelpText = "Display this help screen.")] public string GetUsage() { //var usage = new StringBuilder(); //usage.AppendLine("Sitecore Nuget Package Generator"); //usage.AppendLine("Read user manual for usage instructions..."); return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); //return usage.ToString(); } } }
using System; using System.Diagnostics; using System.Collections; public class Timing { //TimeSpan startingTime; //TimeSpan duration; static Stopwatch timer = new Stopwatch(); public Timing() { //startingTime = new TimeSpan(0); //duration = new TimeSpan(0); } public void stopTime() { timer.Stop(); //Stop timer //duration = Process.GetCurrentProcess().UserProcessorTime.CurrentThread.Subtract(startingTime); //duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime); } public void startTime() { GC.Collect(); GC.WaitForPendingFinalizers(); timer.Reset(); //reset timer to 0 timer.Start(); //start timer //startingTime = Process.GetCurrentProcess().CurrentThread.UserProcessorTime; //startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime; } public TimeSpan Result() { //get time elapsed in seconds return TimeSpan.FromSeconds(timer.Elapsed.TotalSeconds); //return duration; } } class chapter1 { static void Main() { int[] nums = new int[10000000]; ArrayList A = new ArrayList(); Timing tObj = new Timing(); tObj.startTime(); BuildArray(nums); //DisplayNums(nums); tObj.stopTime(); string timeOfArray = tObj.Result().ToString(); tObj.startTime(); BuildArrayList(A); //DisplayArrayList(A); tObj.stopTime(); Console.WriteLine("Time of Array (.NET): " + timeOfArray); Console.WriteLine("Time of ArrayList (.NET): " + tObj.Result()); Console.WriteLine("IsHighResolution = " + Stopwatch.IsHighResolution); Console.ReadKey(); } static void BuildArray(int[] arr) { for (int i = 0; i <= arr.GetUpperBound(0); i++) arr[i] = i; } static void DisplayNums(int[] arr) { for (int i = 0; i <= arr.GetUpperBound(0); i++) Console.Write(arr[i] + " "); } static void BuildArrayList(ArrayList A) { for(int i = 0; i < 10000000; i++) { A.Add(i); } } static void DisplayArrayList(ArrayList A) { foreach(int i in A) Console.Write(i + " "); } }
using System; using System.Collections.Generic; using System.Text; namespace EQS.AccessControl.Application.ViewModels.Output { public class PersonRoleOutput { public PersonOutput Person { get; set; } public int PersonId { get; set; } public RoleOutput Roles { get; set; } public int RoleId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Adow_sOwnBlog.Models { public class Article { /// This archive was created by Matheus Assis Rios(aka Adow Tatep) /// at Adow-sOwnBlog Project /// This file contains article related info public int id { get; set; } public Author author { get; set; } public string title { get; set; } public string description { get; set; } public string content { get; set; } public string tags { get; set; } public string featuredImage { get; set; } public List<ArticleCategory> categories { get; set; } public Article(int id, Author author, string title, string description, string content, string tags, string featuredImage, List<ArticleCategory> categories) { this.id = id; this.author = author; this.title = title; this.description = description; this.content = content; this.tags = tags; this.featuredImage = featuredImage; this.categories = categories; } } }
using System; class NullValuesArithmetic { static void Main() { int? liIntNull = null; double? ldDoubleNull = null; Console.WriteLine("First null int : {0} , and null double : {1}",liIntNull, ldDoubleNull); liIntNull = liIntNull + 5; ldDoubleNull = ldDoubleNull + 3.14567; Console.WriteLine("First null int : {0} , and null double : {1}", liIntNull, ldDoubleNull); liIntNull = 5; ldDoubleNull = 3.14567; Console.WriteLine("First null int : {0} , and null double : {1}", liIntNull, ldDoubleNull); liIntNull = liIntNull + null; ldDoubleNull = ldDoubleNull + null; Console.WriteLine("First null int : {0} , and null double : {1}", liIntNull, ldDoubleNull); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SimpleInjector; using Ezconet.GerenciamentoProjetos.Infra.CrossCutting.IoC.Containers; using Microsoft.Practices.ServiceLocation; namespace Ezconet.GerenciamentoProjetos.Infra.CrossCutting.IoC { public static class IoCStartUp { public static void Bootstrap(Container container, Lifestyle lifestyle) { container.RegisterDbContext(lifestyle); container.RegisterApplicationService(); container.RegisterDomainService(); container.RegisterRepository(); container.RegisterUnitOfWork(); ServiceLocator.SetLocatorProvider(() => new Adapters.SimpleInjectorServiceLocatorAdapter(container)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Purchasing; using UnityEngine.UI; using SimpleJSON; public class ShopItem : MonoBehaviour { public bool beli; public Text namaItem,hargaItem,TnCItem,AttackItem,DefenseItem,StaminaItem,ItemName,ItemPrice,itemQuantity; public string idItem,fileItem,shoptype,iapname,itemnamenya, itemquantitynya; public Image gambaritem, currencyItem; public GameObject Shop, zoomItem,purchase,mybutton; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnClickBuy () { purchase.SetActive (true); } public void OnzoomItem () { if(shoptype=="epic"){ zoomItem.GetComponent<ShopItem>().mybutton.GetComponent<IAPButton> ().productId = iapname; } zoomItem.GetComponent<ShopItem> ().AttackItem.text = AttackItem.text; zoomItem.GetComponent<ShopItem> ().gambaritem.GetComponent<Image> ().sprite = gambaritem.GetComponent<Image> ().sprite; zoomItem.GetComponent<ShopItem> ().shoptype = shoptype; zoomItem.GetComponent<ShopItem> ().idItem = idItem; zoomItem.GetComponent<ShopItem> ().namaItem.text = namaItem.text; zoomItem.GetComponent<ShopItem> ().fileItem = fileItem; zoomItem.GetComponent<ShopItem> ().iapname = iapname; zoomItem.GetComponent<ShopItem> ().hargaItem.text = hargaItem.text; zoomItem.GetComponent<ShopItem> ().DefenseItem.text = DefenseItem.text; zoomItem.GetComponent<ShopItem> ().StaminaItem.text =StaminaItem.text; zoomItem.GetComponent<ShopItem> ().TnCItem.text =TnCItem.text; zoomItem.GetComponent<ShopItem> ().ItemName.text = namaItem.text + " "+itemquantitynya; zoomItem.GetComponent<ShopItem> ().ItemPrice.text = hargaItem.text; zoomItem.GetComponent<ShopItem> ().beli = beli; zoomItem.GetComponent<ShopItem>().itemQuantity.text = itemquantitynya; zoomItem.SetActive (true); } public void purchase_yes(){ if (gameObject.name == "Backko" && gameObject.activeInHierarchy == true) { if (beli == false) { StartCoroutine (BuyItem (idItem)); beli = true; } else { Shop.GetComponent<Shop> ().TransactionFailed2.SetActive (true); } } if (gameObject.name == "Backko2" && gameObject.activeInHierarchy == true) { if (beli == false) { StartCoroutine (BuyItem (idItem)); beli = true; } else { Shop.GetComponent<Shop> ().TransactionFailed2.SetActive (true); } } if (gameObject.name == "Backko3IAP" && gameObject.activeInHierarchy == true) { if (beli == false) { StartCoroutine (BuyItem (idItem)); //beli = true; } else { Shop.GetComponent<Shop> ().TransactionFailed2.SetActive (true); } } } public void purchase_no(){ purchase.SetActive (false); zoomItem.SetActive (false); } private IEnumerator BuyItem(string file) { string url = Link.url + "purchase_shop_"+shoptype; WWWForm form = new WWWForm (); form.AddField ("ID", PlayerPrefs.GetString(Link.ID)); form.AddField ("ID_SHOP_SPECIAL", file); //form.AddField ("JENIS", jenis); WWW www = new WWW(url,form); yield return www; Debug.Log (www.text); if (www.error == null) { var jsonString = JSON.Parse (www.text); var energy = int.Parse (jsonString ["data"] ["energy"]) + int.Parse (PlayerPrefs.GetString ("BonusEnergy")); Debug.Log (www.text); //info.text = file; PlayerPrefs.SetString(Link.COMMON, jsonString["data"]["common"]); PlayerPrefs.SetString(Link.RARE, jsonString["data"]["rare"]); PlayerPrefs.SetString(Link.LEGENDARY, jsonString["data"]["legendary"]); PlayerPrefs.SetString (Link.GOLD, jsonString ["data"] ["coin"]); PlayerPrefs.SetString (Link.ENERGY, energy.ToString ()); PlayerPrefs.SetString ("Crystal", jsonString ["data"] ["crystal"]); if (int.Parse(jsonString ["status"]) == 1) { PlayerPrefs.SetString("BOUGHTCRYSTAL", "TRUE"); Shop.GetComponent<Shop> ().TransactionSucceed.SetActive (true); } // StartCoroutine (updateData ()); else { Shop.GetComponent<Shop> ().TransactionFailed.SetActive (true); //failed } beli = false; } else{ Shop.GetComponent<Shop> ().TransactionFailed3.SetActive (true); } } private IEnumerator updateData() { string url = Link.url + "getDataUser"; WWWForm form = new WWWForm(); form.AddField(Link.ID, PlayerPrefs.GetString(Link.ID)); form.AddField("DID", PlayerPrefs.GetString(Link.DEVICE_ID)); WWW www = new WWW(url, form); yield return www; if (www.error == null) { //StartCoroutine (getDataBatu()); Debug.Log ("UPDATE SUCCESS"); var jsonString = JSON.Parse (www.text); Debug.Log (www.text); if (PlayerPrefs.GetString(Link.FOR_CONVERTING) == "0") { PlayerPrefs.SetString(Link.GOLD, jsonString["data"]["coin"]); PlayerPrefs.SetString(Link.COMMON, jsonString["data"]["common"]); PlayerPrefs.SetString(Link.RARE, jsonString["data"]["rare"]); PlayerPrefs.SetString(Link.LEGENDARY, jsonString["data"]["legendary"]); beli = false; } else if (PlayerPrefs.GetString(Link.FOR_CONVERTING) == "33") { // validationerror.SetActive(true); } } } }
using Airelax.Domain.Houses.Defines; namespace Airelax.Application.Houses.Dtos.Request { public class UpdateRoomCategoryInput { public RoomCategory RoomCategory { get; set; } } }
using Microsoft.EntityFrameworkCore; namespace pokemonapp.Models { public class PokemonContext : DbContext { public DbSet<Entrenador> Entrenadores { get; set; } public DbSet<Pueblo> Pueblos { get; set; } public DbSet<Region> Regiones { get; set; } public DbSet<Pokemon> Pokemones { get; set; } public DbSet<Tipo> Tipo { get; set; } public PokemonContext(DbContextOptions dco) : base(dco) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Translator.Tests { public class TranslateServiceTests { [Fact] public void GetTranslationMustBeReturnCorrectValue() { var translateService = new TranslateService(); translateService.AddTranslation("orange", "апельсин"); Assert.Equal("апельсин", translateService.GetTranslation("orange")); } } }
 namespace CatalogGalaxies { public enum PlanetType { Terrestrial, GiantPlanet, IceGiant, Mesoplanet, MiniNeptune, Planetar, SuperEarth, SuperJupiter, SubEarth } }
using lsc.Dal; using lsc.Model; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace lsc.Bll { /// <summary> /// 销售项目状态变更日志 /// </summary> public class SalesProjectStateLogBll { public async Task<int> AddAsync(SalesProjectStateLog salesProjectStateLog) { return await SalesProjectStateLogDal.Ins.AddAsync(salesProjectStateLog); } public async Task<List<SalesProjectStateLog>> GetListAsync(int SalesProjectID) { return await SalesProjectStateLogDal.Ins.GetListAsync(SalesProjectID); } } }
using System; using System.Collections.Generic; using System.Text; namespace SampleApp.ViewModels.Shared { public class GlobalConstants { public static string HomeStyleId = "Home_Img"; public static string PlansStyle = "Plans_Img"; public static string CookNowStyle = "CookNow_Img"; public static string LearnStyle = "Learn_Img"; public static string ShopStyle = "Shop_Img"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Boss : MonoBehaviour { public GameObject explosao; public void Start() { GameLogic.instance.showFinalKey(false); } public void Killed() { GameLogic.instance.RemoveChaser(); GameLogic.instance.showFinalKey(true); GameObject e = Instantiate(explosao, transform.position, Quaternion.identity); Destroy(e, 5f); Destroy(gameObject); } }
using System; using static MazeApp.MazeCreator; using System.Collections.Generic; namespace MazeApp { public class MazeSolver : IMazeSolver { private static void PrintStep(string[,] maze, int currentX, int currentY) { var mazeCreator = new MazeCreator(); if (maze[currentY, currentX] != "S") { maze[currentY, currentX] = "@"; mazeCreator.PrintMaze(maze); maze[currentY, currentX] = " "; } else { maze[currentY, currentX] = "S"; mazeCreator.PrintMaze(maze); } } private static Dictionary<string,object> Search(string[,] maze, bool[,] visited, int x, int y, Dictionary<string,object> thisDict, IList<int> xLoc, IList<int> yLoc) { thisDict["foundExit"] = false; if (maze[y, x] == "E") { thisDict["foundExit"] = true; return thisDict; } visited[y, x] = true; if (ValidMove(maze, visited, x, y - 1)) { thisDict = Search(maze, visited, x, y - 1, thisDict, xLoc, yLoc); } if ((bool)thisDict["foundExit"] == false && ValidMove(maze, visited, x, y + 1)) { thisDict = Search(maze, visited, x, y + 1, thisDict, xLoc, yLoc); } if ((bool)thisDict["foundExit"] == false && ValidMove(maze, visited, x - 1, y)) { thisDict = Search(maze, visited, x - 1, y, thisDict, xLoc, yLoc); } if ((bool)thisDict["foundExit"] == false && ValidMove(maze, visited, x + 1, y)) { thisDict = Search(maze, visited, x + 1, y, thisDict, xLoc, yLoc); } if (!(bool)thisDict["foundExit"]) return thisDict; xLoc[(int)thisDict["moveNum"]] = x; yLoc[(int)thisDict["moveNum"]] = y; thisDict["moveNum"] = (int)thisDict["moveNum"] + 1; return thisDict; } private static bool ValidMove(string[,] maze, bool[,] visited, int newX, int newY) { if (newX is < 0 or > Width) { return false; } if (newY is < 0 or > Height) { return false; } if (maze[newY, newX] == "X") { return false; } return !visited[newY, newX]; } private void PlaceStart(string[,] maze, IList<int> xLoc, IList<int> yLoc) { var rand = new Random(); var startI = rand.Next(1, Height - 1); var startJ = rand.Next(1, Width - 1); while (maze[startI, startJ] == "X" || maze[startI,startJ] == "E") { startI = rand.Next(1, Height - 1); startJ = rand.Next(1, Width - 1); } maze[startJ, startI] = "S"; xLoc[0] = startI; yLoc[0] = startJ; PrintStep(maze, xLoc[0], yLoc[0]); } private static bool[,] InitializeVisited() { var visited = new bool[Height,Width]; for (var i = 0; i < Height; i++) { for (var j = 0; j < Width; j++) { visited[i,j] = false; } } return visited; } public void Run(string[,] maze) { var thisDict = new Dictionary<string, object> { { "foundExit", false }, { "moveNum", 0 } }; var visited = InitializeVisited(); var xLoc = new int[1000]; var yLoc = new int[1000]; PlaceStart(maze, xLoc, yLoc); Console.WriteLine(Search(maze, visited, xLoc[0], yLoc[0], thisDict, xLoc, yLoc)); for (var i = (int)thisDict["moveNum"] - 1; i >= 0; i--) { PrintStep(maze, xLoc[i], yLoc[i]); Console.WriteLine("Move Number: " + ((int)thisDict["moveNum"] - i - 1) + "\n" + "Coordinates: (" + xLoc[i] + "," + yLoc[i] + ")"); } if ((int)thisDict["moveNum"] <= 0) { Console.WriteLine("Maze was not solvable. Please try again.\n"); } } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using CEMAPI.Models; using CEMAPI.BAL; using CEMAPI.DAL; using Newtonsoft.Json.Linq; using AutoMapper; using Newtonsoft.Json; using System.Reflection; using log4net; using doc = DMSUploadDownload; using System.Web.Configuration; using System.Net.Mail; namespace CEMAPI.Controllers { public class TrackersAPIController : ApiController { TETechuvaDBContext context = new TETechuvaDBContext(); GenericDAL genDAL = new GenericDAL(); public TrackersAPIController() { context.Configuration.ProxyCreationEnabled = false; } // CEMEmailControllerBal cememail = new CEMEmailControllerBal(); private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region SalesTracker [HttpPost] public HttpResponseMessage GetProjectDetailsForSalesTrackers() { List<SalesTrackerforProjects> outlist = new List<SalesTrackerforProjects>(); List<uspTECEM_GetPrjsForSalesTracker_Result> listProjects = new List<uspTECEM_GetPrjsForSalesTracker_Result>(); listProjects = context.uspTECEM_GetPrjsForSalesTracker().ToList(); int count = 0; context.Configuration.ProxyCreationEnabled = false; if (listProjects!= null && listProjects.Count > 0) { foreach (uspTECEM_GetPrjsForSalesTracker_Result resObj in listProjects) { SalesTrackerforProjects trnsObj = new SalesTrackerforProjects(); trnsObj.NoofUnits = resObj.Units; trnsObj.ProjectID = resObj.ProjectID; trnsObj.ProjectName = resObj.ProjectName; trnsObj.ProjectCode = resObj.ProjectCode; trnsObj.ProjectColor = resObj.ProjectColor; trnsObj.totalArea = resObj.Area; trnsObj.totalvalue = resObj.Value; outlist.Add(trnsObj); } } count = outlist.Count; if (count > 0) { SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = sinfo }) }; } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = finfo }) }; } } [HttpPost] public HttpResponseMessage GetProjectDetailsbyIdForSalesTrackers(JObject json) { string projId = json["projectId"].ToObject<string>(); List<SalesTrackerforFiscalyear> outlist = new List<SalesTrackerforFiscalyear>(); List<uspTECEM_GetPrjWiseDetailsForSalesTracker_Result> listProjects = new List<uspTECEM_GetPrjWiseDetailsForSalesTracker_Result>(); listProjects = context.uspTECEM_GetPrjWiseDetailsForSalesTracker(projId).ToList(); int count = 0; context.Configuration.ProxyCreationEnabled = false; if (listProjects != null && listProjects.Count > 0) { foreach (uspTECEM_GetPrjWiseDetailsForSalesTracker_Result resObj in listProjects) { SalesTrackerforFiscalyear trnsObj = new SalesTrackerforFiscalyear(); trnsObj.ProjectID = resObj.ProjectID; trnsObj.FinYear = resObj.FinacialYear; trnsObj.NoofUnits = resObj.Units; trnsObj.totalvalue = resObj.Value; trnsObj.totalArea = resObj.Area; trnsObj.totalvalue = resObj.Value; outlist.Add(trnsObj); } } count = outlist.Count; if (count > 0) { SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = sinfo }) }; } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = finfo }) }; } } [HttpPost] public HttpResponseMessage GetFiscalYearSalesDetailsForSalesTrackers(JObject json) { string projId = json["projectId"].ToObject<string>(); string finYear = json["finYear"].ToObject<string>(); List<SalesTrackerforMonths> outlist = new List<SalesTrackerforMonths>(); List<uspTECEM_GetFiscalYearSalesDetailsForSalesTracker_Result> listProjects = new List<uspTECEM_GetFiscalYearSalesDetailsForSalesTracker_Result>(); listProjects = context.uspTECEM_GetFiscalYearSalesDetailsForSalesTracker(projId, finYear).ToList(); int count = 0; context.Configuration.ProxyCreationEnabled = false; if (listProjects != null && listProjects.Count > 0) { foreach (uspTECEM_GetFiscalYearSalesDetailsForSalesTracker_Result resObj in listProjects) { SalesTrackerforMonths trnsObj = new SalesTrackerforMonths(); trnsObj.ProjectID = resObj.ProjectID; trnsObj.monthYear = resObj.DateCombo; trnsObj.MonthPart = resObj.MonthPart; trnsObj.YearPart = resObj.YearPart; trnsObj.NoofUnits = resObj.Units; trnsObj.totalvalue = resObj.Value; trnsObj.totalArea = resObj.Area; trnsObj.totalvalue = resObj.Value; outlist.Add(trnsObj); } } count = outlist.Count; if (count > 0) { SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = sinfo }) }; } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = finfo }) }; } } [HttpPost] public HttpResponseMessage GetMonthlySalesDetailsForSalesTrackers(JObject json) { string projId = json["projectId"].ToObject<string>(); int MonthPart = json["MonthPart"].ToObject<int>(); int YearPart = json["YearPart"].ToObject<int>(); //string monthYear = json["monthYear"].ToObject<string>(); List<SalesTrackerDetails> outlist = new List<SalesTrackerDetails>(); List<uspTECEM_GetMonthlySalesDetailsForSalesTracker_Result> listProjects = new List<uspTECEM_GetMonthlySalesDetailsForSalesTracker_Result>(); listProjects = context.uspTECEM_GetMonthlySalesDetailsForSalesTracker(projId, MonthPart, YearPart).ToList(); int count = 0; context.Configuration.ProxyCreationEnabled = false; if (listProjects != null && listProjects.Count > 0) { foreach (uspTECEM_GetMonthlySalesDetailsForSalesTracker_Result resObj in listProjects) { SalesTrackerDetails trnsObj = new SalesTrackerDetails(); trnsObj.CustomerName = resObj.OfferCustomerName; trnsObj.DateForm = resObj.BookingDate; trnsObj.unitValue = resObj.Value; trnsObj.unitArea = resObj.Area; trnsObj.UnitNo = resObj.UnitNo; trnsObj.projID = projId; outlist.Add(trnsObj); } } count = outlist.Count; if (count > 0) { SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = sinfo }) }; } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outlist, info = finfo }) }; } } #endregion #region CustomisationTracker [HttpPost] public HttpResponseMessage GetCustomersListForCustomisationTracker(JObject json) { var headers = Request.Headers; int authuser = 0; if (headers.Contains("authUser")) { authuser = Convert.ToInt32(headers.GetValues("authUser").First()); } int count = 0; context.Configuration.ProxyCreationEnabled = false; List<BoqDetails> CustList = (from custBoq in context.TECustomerBOQs join ofr in context.TEOffers on custBoq.CustomerID equals ofr.SAPCustomerID join proj in context.TEProjects on custBoq.ProjectID equals proj.ProjectID join Spec in context.TESpecificationMasters on custBoq.SpecificationId equals Spec.SpecificationID join lead in context.TELeads on ofr.LeadID equals lead.LeadID join usr in context.UserProfiles on ofr.CEMmanager equals usr.UserId where (ofr.isOrderInUse == true && custBoq.isDeleted == false) select new BoqDetails { Boq = custBoq, ProjectName = proj.ProjectName, CustomerName = ofr.OfferCustomerName, ProjectAbbr = proj.ProjectShortName, OfferID = ofr.OfferID, SpecColorCode = Spec.HeadingColourCode, SpecColorName = Spec.SpecificationName, CEMManager = usr.CallName }).OrderByDescending(a => a.Boq.CustomisationCommenceDate).ToList(); var finalList = CustList.Where(x => x.Boq.VersionNo == CustList.Where(y => y.Boq.CustomerID == x.Boq.CustomerID).Max(z => z.Boq.VersionNo)).Distinct().ToList(); count = finalList.Count; if (count > 0) { foreach( var item in finalList) { //Donot remove this //if (item.Boq.CustomisationCommenceDate != null) //{ // DateTime commenseDate = Convert.ToDateTime(item.Boq.CustomisationCommenceDate); // DateTime signoffDate = Convert.ToDateTime(item.Boq.CustomizationSignOffDate); // if (item.Boq.CustomizationSignOffDate == null) // { // item.TTD = (DateTime.Today - commenseDate).TotalDays; // item.TSD = 0; // } // else // { // item.TTD = 0; // item.TSD = (signoffDate - commenseDate).TotalDays; // } //} //else { // item.TTD = 0; // item.TSD = 0; //} if (item.Boq.CustomisationCommenceDate != null) { DateTime commenseDate = Convert.ToDateTime(item.Boq.CustomisationCommenceDate); DateTime signoffDate = Convert.ToDateTime(item.Boq.CustomizationSignOffDate); DateTime subimissionDate = Convert.ToDateTime(item.Boq.CustomizationSubmissionDate); if (item.Boq.CustomizationSubmissionDate != null) { item.TTD = (subimissionDate - commenseDate).TotalDays; } else { item.TTD = 0; } if(item.Boq.CustomizationSignOffDate!=null) { item.TSD = (signoffDate - commenseDate).TotalDays; } else { item.TSD = 0; } } else { item.TTD = 0; item.TSD = 0; } } for (int i = 0; i < finalList.Count(); i++) { int id = finalList[i].Boq.CustomerBOQID; int? offerid = finalList[i].OfferID; int? projectid = (from offer in context.TEOffers where offer.OfferID == offerid select offer.ProjectID).FirstOrDefault(); var appStatus = (from res in context.TEApprovalTransactions where ((res.AppObjectName == "TECustomisationDesign" || res.AppObjectName == "TECustomisationBOQ" || res.AppObjectName == "TECustomisationCNApproval" || res.AppObjectName == "TECustomisationSRApproval") && res.isDeleted == false && res.AppObjectReferenceID == id && res.AppUserID == authuser && res.ProjectID == projectid && res.ApproverStatus == "Draft") select res.ApproverStatus).FirstOrDefault(); if (appStatus != null) finalList[i].ApproverStatus = appStatus; } SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = finalList, info = sinfo }) }; } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = finalList, info = finfo }) }; } } #endregion #region TDSTracker [HttpPost] public HttpResponseMessage GetCustomersListForTDSTracker(JObject json) { List<DailyInvoiceResult> mylist = new List<DailyInvoiceResult>(); SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); try { if (log.IsDebugEnabled) log.Debug("Entered into GetCustomersListForTDSTracker"); int count = 0; string mnthVal = string.Empty; context.Configuration.ProxyCreationEnabled = false; mylist = (from collctn in context.TECollections join ofr in context.TEOffers on collctn.SAPCustomerID equals ofr.SAPCustomerID join prjct in context.TEProjects on collctn.ProjectID equals prjct.ProjectID join compny in context.TECompanies on prjct.CompanyID equals compny.Uniqueid join unit in context.TEUnits on collctn.UnitID equals unit.UnitID join prof in context.UserProfiles on collctn.LastModifiedBy_Id equals prof.UserId where ( collctn.PaymentMode=="TDS" && collctn.IsDeleted == false && ofr.isOrderInUse == true && ofr.IsDeleted == false) select new DailyInvoiceResult { CollectionsID = collctn.CollectionsID, ContextID = collctn.ContextID, OfferTitleName = ofr.OfferTitleName, OfferCustomerName = ofr.OfferCustomerName, ProjectID = collctn.ProjectID, ProjectColor = prjct.ProjectColor, ProjectName = prjct.ProjectName, ProjectShortName = prjct.ProjectShortName, UnitID = collctn.UnitID, UnitNumber = unit.UnitNumber, SAPCustomerID = collctn.SAPCustomerID, PaymentMode = collctn.PaymentMode, ReceiptID = collctn.ReceiptID, DraweeBank = collctn.DraweeBank, SAPBankCode = collctn.SAPBankCode, InstrumentNumber = collctn.InstrumentNumber, InstrumentDate = collctn.InstrumentDate, Amount = collctn.Amount, ReceivedOn = collctn.ReceivedOn, ReceivedBy = collctn.ReceivedBy, PayeeBank = collctn.PayeeBank, PayeeName = collctn.PayeeName, PaidBy = collctn.PaidBy, ISTDS = collctn.ISTDS, ReceiptDocumentID = collctn.ReceiptDocumentID, ClearedBy = collctn.ClearedBy, ClearedOn = collctn.ClearedOn, Status = collctn.Status, ReversedOn = collctn.ReversedOn, PANNo = collctn.PANNo, UserName = prof.UserName }).ToList().OrderBy(x => x.ProjectName).ThenByDescending(x => x.InstrumentDate).ToList(); count = mylist.Count; if (count > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = mylist, info = sinfo }) }; } else { sinfo.errorcode = 1; sinfo.errormessage = "Failed To get Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = mylist, info = sinfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = mylist, info = finfo }) }; } } public HttpResponseMessage dowloadDocument(JObject json) { string base64 = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); try { string ReceiptID = json["ReceiptID"].ToString(); string SAPCusID = ""; if (json["SAPCustomerID"] != null && json["SAPCustomerID"].ToString() != "") SAPCusID = json["SAPCustomerID"].ToObject<string>(); doc.FileUploadAndDownload fileUploadDownload = new doc.FileUploadAndDownload(); string DMSUserId = WebConfigurationManager.AppSettings["DMSUserId"]; string DMSPassword = WebConfigurationManager.AppSettings["DMSPassword"]; string DMSSiteUrl = WebConfigurationManager.AppSettings["DMSSiteUrl"]; string DMSLibrary = WebConfigurationManager.AppSettings["DMSLibrary"]; var DMSDocumentdetails = (from dmsDoc in context.TEDMSDocuments where dmsDoc.ReferenceID == ReceiptID && dmsDoc.SAPCustomerID == SAPCusID && dmsDoc.DocumentType.Contains("Receipt") select new { dmsDoc.DMSDocumentID, dmsDoc.FileType, dmsDoc.UploadedOn }) .OrderByDescending(a => a.UploadedOn).FirstOrDefault(); if (DMSDocumentdetails == null) { finfo.errorcode = 1; finfo.errormessage = "Document is not Available in DMS"; return new HttpResponseMessage() { Content = new JsonContent(new { result = base64, info = finfo }) }; } base64 = fileUploadDownload.DownloadFile(DMSSiteUrl, DMSLibrary, DMSDocumentdetails.DMSDocumentID, DMSUserId, DMSPassword); if (base64 != null) { string docType = string.Empty; if (DMSDocumentdetails.FileType.ToLower() == "pdf") { docType = "data:application/pdf;base64,"; } else if (DMSDocumentdetails.FileType.ToLower() == "jpeg" || DMSDocumentdetails.FileType.ToLower() == "jpg") { docType = "data:image/jpeg;base64,"; } else if (DMSDocumentdetails.FileType.ToLower() == "png") { docType = "data:image/png;base64,"; } else if (DMSDocumentdetails.FileType.ToLower() == "xls") { docType = "data:application/vnd.ms-excel,"; } sinfo.errorcode = 0; sinfo.errormessage = "Success"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = 1; sinfo.listcount = 1; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = base64, DocumentType = docType, info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Document is not Available in DMS"; return new HttpResponseMessage() { Content = new JsonContent(new { result = base64, info = finfo }) }; } } catch (Exception ex) { finfo.errorcode = 1; finfo.errormessage = ex.Message; return new HttpResponseMessage() { Content = new JsonContent(new { result = base64, info = finfo }) }; } } [HttpPost] public HttpResponseMessage DownloadTDSDocumenFromDMS(JObject json) { HttpResponseMessage hrm = new HttpResponseMessage(); SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); doc.FileUploadAndDownload fileUploadDownload = new doc.FileUploadAndDownload(); string filePath = string.Empty; int ReceiptDocumentID = 0; if (json["ReceiptDocumentID"] != null && json["ReceiptDocumentID"].ToString() != "") ReceiptDocumentID = json["ReceiptDocumentID"].ToObject<int>(); if (ReceiptDocumentID <= 0) { finfo.errorcode = 1; finfo.errormessage = "Unable to Download Document. Reason: Invalid DMSId Received."; return new HttpResponseMessage() { Content = new JsonContent(new {info = finfo }) }; } string SAPCusID = ""; if (json["SAPCustomerID"] != null && json["SAPCustomerID"].ToString() != "") SAPCusID = json["SAPCustomerID"].ToObject<string>(); if (string.IsNullOrEmpty(SAPCusID)) { finfo.errorcode = 1; finfo.errormessage = "Unable to Download Document. Reason: Invalid SAPCustomerId Received."; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } string DMSSiteUrl = WebConfigurationManager.AppSettings["DMSSiteUrl"]; string DMSLibrary = WebConfigurationManager.AppSettings["DMSLibrary"]; string DMSUserId = WebConfigurationManager.AppSettings["DMSUserId"]; string DMSPassword = WebConfigurationManager.AppSettings["DMSPassword"]; string url = WebConfigurationManager.AppSettings["DMSDownloadedFiles"]; string assemblyFile = string.Empty; assemblyFile = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath; int index = assemblyFile.LastIndexOf("/bin/"); string downloadFilePath = @"" + assemblyFile.Substring(0, index) + "/UploadDocs"; try { var dmsObj = (from dms in context.TEDMSDocuments where dms.UniqueID == ReceiptDocumentID && dms.SAPCustomerID == SAPCusID select new { dms.DMSDocumentID, dms.UniqueID, dms.FileType, dms.DocumentName }).FirstOrDefault(); if (dmsObj == null || string.IsNullOrEmpty(dmsObj.DocumentName)) { finfo.errorcode = 1; finfo.errormessage = "Failed To get DMS Details"; hrm.Content = new JsonContent(new { info = finfo }); return hrm; } fileUploadDownload.DownloadDocumentFromSharePointServer(DMSSiteUrl, DMSLibrary, dmsObj.DMSDocumentID, downloadFilePath, DMSUserId, DMSPassword); filePath = url + "/" + dmsObj.DocumentName; sinfo.errorcode = 0; sinfo.errormessage = "Document downloaded successfully from DMS"; hrm.Content = new JsonContent(new { result = filePath, info = sinfo }); } catch (Exception ex) { ApplicationErrorLog errorlog = new ApplicationErrorLog(); if (ex.InnerException != null) errorlog.InnerException = ex.InnerException.ToString(); if (ex.StackTrace != null) errorlog.Stacktrace = ex.StackTrace.ToString(); if (ex.Source != null) errorlog.Source = ex.Source.ToString(); if (ex.Message != null) errorlog.Error = ex.Message.ToString(); errorlog.ExceptionDateTime = DateTime.Now; context.ApplicationErrorLogs.Add(errorlog); context.SaveChanges(); finfo.errorcode = 1; finfo.errormessage = "Unable to download document from DMS. Exception: " + ex.ToString(); hrm.Content = new JsonContent(new { info = finfo }); } return hrm; } #endregion #region OfferTracker [HttpPost] public HttpResponseMessage GetCustomersForOfferTracker(JObject json) { List<OfferTrackerDTO> offerTrackerList = new List<OfferTrackerDTO>(); SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); try { if (log.IsDebugEnabled) log.Debug("Entered into GetCustomersForOfferTracker"); int logInUserId = 0; logInUserId = GetLogInUserId(); int count = 0; string fugueSalesValue = string.Empty; fugueSalesValue = WebConfigurationManager.AppSettings["FullLeadList"]; string salesResonseValue = WebConfigurationManager.AppSettings["AllocatedTothemAndNonAllocated"]; string[] fugueRoleArray = null; if (!string.IsNullOrEmpty(fugueSalesValue)) { fugueRoleArray = fugueSalesValue.Split(','); } var rolesList = (from userRoles in context.webpages_UsersInRoles join webpageroles in context.webpages_Roles on userRoles.RoleId equals webpageroles.RoleId where userRoles.UserId == logInUserId select webpageroles.RoleName).ToList(); var RolesInCommon = rolesList.Intersect(fugueRoleArray); if (RolesInCommon != null) { offerTrackerList = (from ofr in context.TEOffers join prjct in context.TEProjects on ofr.ProjectID equals prjct.ProjectID join unt in context.TEUnits on ofr.UnitID equals unt.UnitID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join close in context.UserProfiles on ld.CloseTeamMember equals close.UserId into tempCl from clUser in tempCl.DefaultIfEmpty() join response in context.UserProfiles on ld.ResponseteamMember equals response.UserId into tempRes from respUser in tempRes.DefaultIfEmpty() where ((ofr.OrderStatus == "Draft" || ofr.OrderStatus == "Pending For Approval" || ofr.OrderStatus == "Approved" || ofr.OrderStatus == "TS Generated" || ofr.OrderStatus == "TS Signed" || ofr.OrderStatus == "Expired") && ofr.IsDeleted == false && ld.LeadStage != "Suspect" && ld.LeadStage != "Dropped" && ld.LeadStage != "Trashed" && ld.LeadStage != "Transitioned") select new OfferTrackerDTO { OfferID = ofr.OfferID, UnitNumber = unt.UnitNumber, LeadID = ofr.LeadID, ContactID=ld.ContactID, Title = ofr.OfferTitleName, CustomerName = ofr.OfferCustomerName, ProjectID = ofr.ProjectID, ProjectName = prjct.ProjectName, SAPCustomerID = ofr.SAPCustomerID, OfferValue = ofr.Consideration, OfferCreatedOn = ofr.CreatedDate, OfferExpireOn = ofr.ExpiryDate, OrderStatus = ofr.OrderStatus, SalesConsultantID = ld.CloseTeamMember, ResponseConsultantID = ld.ResponseteamMember, SalesConsultant = clUser.CallName, ResponseConsultant = respUser.CallName, ReceiptAmount = 0 }).Distinct().OrderByDescending(a=>a.OfferExpireOn).ToList(); } else { var SalesResponseCheck = (from userRoles in context.webpages_UsersInRoles join webpageroles in context.webpages_Roles on userRoles.RoleId equals webpageroles.RoleId where webpageroles.RoleName.Equals(salesResonseValue) && userRoles.UserId == logInUserId select webpageroles.RoleName).FirstOrDefault(); if (SalesResponseCheck != null) { offerTrackerList = (from ofr in context.TEOffers join prjct in context.TEProjects on ofr.ProjectID equals prjct.ProjectID join unt in context.TEUnits on ofr.UnitID equals unt.UnitID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join close in context.UserProfiles on ld.CloseTeamMember equals close.UserId into tempCl from clUser in tempCl.DefaultIfEmpty() join response in context.UserProfiles on ld.ResponseteamMember equals response.UserId into tempRes from respUser in tempRes.DefaultIfEmpty() where ((ofr.OrderStatus == "Draft" || ofr.OrderStatus == "Pending For Approval" || ofr.OrderStatus == "Approved" || ofr.OrderStatus == "TS Generated" || ofr.OrderStatus == "TS Signed" || ofr.OrderStatus == "Expired") && ofr.IsDeleted == false && ld.LeadStage != "Suspect" && ld.LeadStage != "Dropped" && ld.LeadStage != "Trashed" && ld.LeadStage != "Transitioned" && (ld.CloseTeamMember == logInUserId || ld.CloseTeamMember == null)) select new OfferTrackerDTO { OfferID = ofr.OfferID, UnitNumber = unt.UnitNumber, LeadID = ofr.LeadID, ContactID = ld.ContactID, Title = ofr.OfferTitleName, CustomerName = ofr.OfferCustomerName, ProjectID = ofr.ProjectID, ProjectName = prjct.ProjectName, SAPCustomerID = ofr.SAPCustomerID, OfferValue = ofr.Consideration, OfferCreatedOn = ofr.CreatedDate, OfferExpireOn = ofr.ExpiryDate, OrderStatus = ofr.OrderStatus, SalesConsultantID = ld.CloseTeamMember, ResponseConsultantID = ld.ResponseteamMember, SalesConsultant = clUser.CallName, ResponseConsultant = respUser.CallName, ReceiptAmount = 0 }).Distinct().OrderByDescending(a => a.OfferExpireOn).ToList(); } else { offerTrackerList = (from ofr in context.TEOffers join prjct in context.TEProjects on ofr.ProjectID equals prjct.ProjectID join unt in context.TEUnits on ofr.UnitID equals unt.UnitID join ld in context.TELeads on ofr.LeadID equals ld.LeadID join close in context.UserProfiles on ld.CloseTeamMember equals close.UserId into tempCl from clUser in tempCl.DefaultIfEmpty() join response in context.UserProfiles on ld.ResponseteamMember equals response.UserId into tempRes from respUser in tempRes.DefaultIfEmpty() where ((ofr.OrderStatus == "Draft" || ofr.OrderStatus == "Pending For Approval" || ofr.OrderStatus == "Approved" || ofr.OrderStatus == "TS Generated" || ofr.OrderStatus == "TS Signed" || ofr.OrderStatus == "Expired") && ofr.IsDeleted == false && ld.LeadStage != "Suspect" && ld.LeadStage != "Dropped" && ld.LeadStage != "Trashed" && ld.LeadStage != "Transitioned" && (ld.CloseTeamMember == logInUserId)) select new OfferTrackerDTO { OfferID = ofr.OfferID, UnitNumber = unt.UnitNumber, LeadID = ofr.LeadID, ContactID = ld.ContactID, Title = ofr.OfferTitleName, CustomerName = ofr.OfferCustomerName, ProjectID = ofr.ProjectID, ProjectName = prjct.ProjectName, SAPCustomerID = ofr.SAPCustomerID, OfferValue = ofr.Consideration, OfferCreatedOn = ofr.CreatedDate, OfferExpireOn = ofr.ExpiryDate, OrderStatus = ofr.OrderStatus, SalesConsultantID = ld.CloseTeamMember, ResponseConsultantID = ld.ResponseteamMember, SalesConsultant = clUser.CallName, ResponseConsultant = respUser.CallName, ReceiptAmount = 0 }).Distinct().OrderByDescending(a => a.OfferExpireOn).ToList(); } } foreach (var data in offerTrackerList) { if (data.SAPCustomerID != null && data.SAPCustomerID != "" && data.SAPCustomerID!="0") { //var receiptscollData = (from coll in context.TECollections // where coll.SAPCustomerID == data.SAPCustomerID // select new { coll.Amount }).ToList(); var receiptscollData = (from coll in context.TESAPReceipts where coll.CustomerNumber == data.SAPCustomerID select new { coll.Amount }).ToList(); data.ReceiptAmount = receiptscollData.ToList().Sum(a => a.Amount); } } count = offerTrackerList.Count; if (count > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = offerTrackerList, info = sinfo }) }; } else { sinfo.errorcode = 1; sinfo.errormessage= "No Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.torecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = offerTrackerList, info = sinfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = offerTrackerList, info = finfo }) }; } } #endregion [HttpPost] public HttpResponseMessage GetDelayCompensationTrackerDetails() { int count = 0, logInUserId = 0; List<DelayCompensationTrackerDTO> outList = new List<DelayCompensationTrackerDTO>(); List<uspTECEM_GetDelayCompensatonDetailsForCEM_Result> respList = null; List<uspTECEM_GetDelayCompensationDetails_Result> respListPrj = null; try { logInUserId = GetLogInUserId(); if (logInUserId > 0) { context.Configuration.ProxyCreationEnabled = false; if (IsCEMViewRoleUser(logInUserId)) { string projectsList = GetProjectsAssignedToAuthUser(logInUserId); if (!string.IsNullOrEmpty(projectsList)) respListPrj = context.uspTECEM_GetDelayCompensationDetails(projectsList).ToList(); } else { if (IsCEMManagerRoleUser(logInUserId)) { respList = context.uspTECEM_GetDelayCompensatonDetailsForCEM(logInUserId.ToString()).ToList(); } else { string projectsList = GetProjectsAssignedToAuthUser(logInUserId); if (!string.IsNullOrEmpty(projectsList)) respListPrj = context.uspTECEM_GetDelayCompensationDetails(projectsList).ToList(); } } } else { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "LogIn Credentials Not Found"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outList, info = finfo }) }; } if (respList != null && respList.Count > 0) { foreach (uspTECEM_GetDelayCompensatonDetailsForCEM_Result resObj in respList) { DelayCompensationTrackerDTO transObj = new DelayCompensationTrackerDTO(); transObj.CompensationAmount = resObj.CompensationAmount; //transObj.CompensationBasis = resObj.CompensationBasis; transObj.CompensationPaidTillDt = resObj.CompensationPaidTillDt; //transObj.CompensationPerMonth = resObj.CompensationPerMonth; transObj.CustomerName = resObj.CustomerName; //transObj.DCID = resObj.DCID; transObj.OfferId = resObj.OfferId; transObj.ExpectedHODate = resObj.ExpectedHODate; transObj.HODate = resObj.HODate; //transObj.MontlyPayByDate = resObj.MontlyPayByDate; //transObj.PaymentMode = resObj.PaymentMode; transObj.ProjectShortName = resObj.ProjectShortName; transObj.RevisedHandOverDate = resObj.RevisedHandOverDate; transObj.SAPCustomerID = resObj.SAPCustomerID; transObj.SAPOrderID = resObj.SAPOrderID; //transObj.Status = resObj.Status; //transObj.TotalCompensationDuration = resObj.TotalCompensationDuration; transObj.UnitNumber = resObj.UnitNumber; outList.Add(transObj); } } if (respListPrj != null && respListPrj.Count > 0) { foreach (uspTECEM_GetDelayCompensationDetails_Result resObj in respListPrj) { DelayCompensationTrackerDTO transObj = new DelayCompensationTrackerDTO(); transObj.CompensationAmount = resObj.CompensationAmount; //transObj.CompensationBasis = resObj.CompensationBasis; transObj.CompensationPaidTillDt = resObj.CompensationPaidTillDt; //transObj.CompensationPerMonth = resObj.CompensationPerMonth; transObj.CustomerName = resObj.CustomerName; //transObj.DCID = resObj.DCID; transObj.OfferId = resObj.OfferId; transObj.ExpectedHODate = resObj.ExpectedHODate; transObj.HODate = resObj.HODate; //transObj.MontlyPayByDate = resObj.MontlyPayByDate; //transObj.PaymentMode = resObj.PaymentMode; transObj.ProjectShortName = resObj.ProjectShortName; transObj.RevisedHandOverDate = resObj.RevisedHandOverDate; transObj.SAPCustomerID = resObj.SAPCustomerID; transObj.SAPOrderID = resObj.SAPOrderID; //transObj.Status = resObj.Status; //transObj.TotalCompensationDuration = resObj.TotalCompensationDuration; transObj.UnitNumber = resObj.UnitNumber; outList.Add(transObj); } } //Code to get ApprovedBy and ApprovedDate if (outList != null && outList.Count > 0) { for(int i=0; i< outList.Count; i++) { string tempSapCustomerId = outList[i].SAPCustomerID; var dcIdAndComDurDtls = (from dcomp in context.TEDelayCompensations where dcomp.SAPCustomerID == tempSapCustomerId && dcomp.isDeleted == false select new { dcomp.DCID, dcomp.TotalCompensationDuration }).OrderByDescending(a => a.DCID).FirstOrDefault(); if (dcIdAndComDurDtls != null && dcIdAndComDurDtls.DCID > 0) { outList[i].delayCompensationID = dcIdAndComDurDtls.DCID; outList[i].CompensationInDays = dcIdAndComDurDtls.TotalCompensationDuration; var approverDetails = (from grp in context.TEApprovalTransactions join profile in context.UserProfiles on grp.AppUserID equals profile.UserId where (grp.AppObjectName == "TEDelayCompensation" && grp.isDeleted == false && grp.AppObjectReferenceID == dcIdAndComDurDtls.DCID && grp.ApproverStatus =="Approved") select new { grp.AppTransctionID, grp.LastModifiedBy, grp.LastModifiedDate, profile.CallName }).OrderByDescending(a => a.AppTransctionID).FirstOrDefault(); if (approverDetails != null && approverDetails.AppTransctionID > 0) { outList[i].ApprovedBy = approverDetails.CallName; if(approverDetails.LastModifiedDate != null) outList[i].ApprovedDate = approverDetails.LastModifiedDate.Value.ToString("dd-MMM-yy"); } } } } count = outList.Count; if (count > 0) { outList = outList.OrderBy(a => a.CustomerName).ToList(); SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Got Records"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outList, info = sinfo }) }; } else { SuccessInfo sinfo = new SuccessInfo(); sinfo.errorcode = 0; sinfo.errormessage = "No Records Found"; sinfo.fromrecords = 1; sinfo.torecords = 10; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outList, info = sinfo }) }; } } catch { FailInfo finfo = new FailInfo(); finfo.errorcode = 1; finfo.errormessage = "Failed To get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { result = outList, info = finfo }) }; } } private bool IsCEMManagerRoleUser(int logInUserId) { bool isCEMManagerRoleUser = false; //int authuser = 0; //var re = Request; //var headers = re.Headers; //if (headers.Contains("authUser")) //{ // authuser = Convert.ToInt32(headers.GetValues("authUser").First()); //} var rolename = (from userrole in context.webpages_UsersInRoles join webrole in context.webpages_Roles on userrole.RoleId equals webrole.RoleId where userrole.UserId == logInUserId select new { webrole.RoleName }).ToList(); var role = rolename.Find(b => b.RoleName.Equals("CEM Manager")); if (role != null) { isCEMManagerRoleUser = true; } return isCEMManagerRoleUser; } private bool IsCEMViewRoleUser(int logInUserId) { bool IsCEMViewRoleUser = false; //int authuser = 0; //var re = Request; //var headers = re.Headers; //if (headers.Contains("authUser")) //{ // authuser = Convert.ToInt32(headers.GetValues("authUser").First()); //} var rolename = (from userrole in context.webpages_UsersInRoles join webrole in context.webpages_Roles on userrole.RoleId equals webrole.RoleId where userrole.UserId == logInUserId select new { webrole.RoleName }).ToList(); var role = rolename.Find(b => b.RoleName.Replace(" ", string.Empty).ToLower().Equals("cemview")); if (role != null) { IsCEMViewRoleUser = true; } return IsCEMViewRoleUser; } private string GetProjectsAssignedToAuthUser(int logInUserId) { string listOfProjectes = string.Empty; //int authuser = 0; //var re = Request; //var headers = re.Headers; //if (headers.Contains("authUser")) //{ // authuser = Convert.ToInt32(headers.GetValues("authUser").First()); //} var rolename = (from userrole in context.webpages_UsersInRoles join webrole in context.webpages_Roles on userrole.RoleId equals webrole.RoleId where userrole.UserId == logInUserId select new { webrole.RoleName }).ToList(); var role = rolename.Find(b => b.RoleName.Replace(" ", string.Empty).ToLower().Equals("fugueadmin") || b.RoleName.Replace(" ", string.Empty).ToLower().Equals("projectceo") || b.RoleName.Replace(" ", string.Empty).ToLower().Equals("finance") || b.RoleName.Replace(" ", string.Empty).ToLower().Equals("financehead") || b.RoleName.Replace(" ", string.Empty).ToLower().Equals("cemview") || b.RoleName.Replace(" ", string.Empty).ToLower().Equals("cpmohead") ); if (role != null) { if (role.RoleName.Replace(" ", string.Empty).ToLower().Equals("fugueadmin")) { List<int> projIdsList = (from proj in context.TEProjects where proj.IsDeleted == false select proj.ProjectID).ToList(); if (projIdsList != null && projIdsList.Count > 0) { foreach (int projId in projIdsList) { listOfProjectes = listOfProjectes + projId.ToString() + ","; } } } else { List<int?> projIdsList = (from orgrule in context.TEOrgRules join webpagerole in context.webpages_Roles on orgrule.RoleID equals webpagerole.RoleId join users in context.UserProfiles on orgrule.UserID equals users.UserId where webpagerole.RoleName.Equals(role.RoleName) && users.IsDeleted == false && orgrule.IsDeleted == false && users.UserId == logInUserId select orgrule.ProjectID).ToList(); if (projIdsList != null && projIdsList.Count > 0) { foreach (int projId in projIdsList) { listOfProjectes = listOfProjectes + projId.ToString() + ","; } } } } if (!string.IsNullOrEmpty(listOfProjectes)) listOfProjectes = listOfProjectes.TrimEnd(','); return listOfProjectes; } public class BoqDetails { public TECustomerBOQ Boq { get; set; } public string ProjectName { get; set; } public string CustomerName { get; set; } public string ProjectAbbr { get; set; } public double TTD { get; set; } public double TSD { get; set; } public int OfferID { get; set; } public string ApproverStatus { get; set; } public string SpecColorCode { get; set; } public string SpecColorName { get; set; } public string CEMManager { get; set; } } private int GetLogInUserId() { var re = Request; var header = re.Headers; int authuser = 0; if (header.Contains("authUser")) { authuser = Convert.ToInt32(header.GetValues("authUser").First()); } return authuser; } public class OfferTrackerDTO { public string CustomerName { get; set; } public string ProjectName { get; set; } public string UnitNumber { get; set; } public int OfferID { get; set; } public int? LeadID { get; set; } public int? ContactID { get; set; } public int? ProjectID { get; set; } public string Title { get; set; } public string OrderStatus { get; set; } public DateTime? OfferCreatedOn { get; set; } public DateTime? OfferExpireOn { get; set; } public string SalesConsultant { get; set; } public string ResponseConsultant { get; set; } public decimal? OfferValue { get; set; } public string SAPCustomerID { get; set; } public decimal? ReceiptAmount { get; set; } public int? SalesConsultantID { get; set; } public int? ResponseConsultantID { get; set; } } public class DelayCompensationTrackerDTO { public decimal? CompensationAmount { get; set; } //public string CompensationBasis { get; set; } public decimal? CompensationPaidTillDt { get; set; } //public decimal? CompensationPerMonth { get; set; } public string CustomerName { get; set; } //public int DCID { get; set; } public int? OfferId { get; set; } public DateTime? ExpectedHODate { get; set; } public DateTime? HODate { get; set; } //public DateTime? MontlyPayByDate { get; set; } //public string PaymentMode { get; set; } public string ProjectShortName { get; set; } public DateTime? RevisedHandOverDate { get; set; } public string SAPCustomerID { get; set; } public string SAPOrderID { get; set; } //public string Status { get; set; } //public decimal? TotalCompensationDuration { get; set; } //public string CustomerId { get; set; } public string SaleOrderId { get; set; } public string UnitNumber { get; set; } public string ApprovedBy { get; set; } public string ApprovedDate { get; set; } public decimal? CompensationInDays { get; set; } public int delayCompensationID { get; set; } } } }
using System; using System.Collections.Generic; using com.Sconit.Entity.MD; using com.Sconit.Entity.BIL; using System.IO; namespace com.Sconit.Service { public interface IItemMgr { Dictionary<string, Item> GetCacheAllItem(); Item GetCacheItem(string itemCode); void ResetItemCache(); IList<ItemKit> GetKitItemChildren(string kitItem); IList<ItemKit> GetKitItemChildren(string kitItem, bool includeInActive); decimal ConvertItemUomQty(string itemCode, string sourceUomCode, decimal sourceQty, string targetUomCode); PriceListDetail GetItemPrice(string itemCode, string uom, string priceList, string currency, DateTime? effectiveDate); void CreateItem(Item item); void UpdateItem(Item item); IList<ItemDiscontinue> GetItemDiscontinues(string itemCode, DateTime effectiveDate); IList<ItemDiscontinue> GetParentItemDiscontinues(string itemCode, DateTime effectiveDate); IList<Item> GetItems(IList<string> itemCodeList); void CreateCustodian(Custodian custodian); void DeleteItem(string itemCode); IList<Uom> GetItemUoms(string itemCode); Dictionary<string, Item> GetRefItemCode(string flowCode, List<string> refItemCodeList); void ImportItem(Stream inputStream); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BallController : MonoBehaviour { private float visiblePosZ = -6.5f; private GameObject gameoverText; GameObject director; // Use this for initialization void Start () { this.director = GameObject.Find ("GameDirector"); this.gameoverText = GameObject.Find("GameOverText"); } void OnCollisionEnter(Collision other) { if (other.gameObject.tag == "SmallStarTag") { this.director.GetComponent<GameDirector>().GetSmallStar(); Debug.Log ("SmallStar"); } else if (other.gameObject.tag == "LargeStarTag") { this.director.GetComponent<GameDirector>().GetLargeStar(); Debug.Log ("LargeStar"); } else if (other.gameObject.tag == "SmallCloudTag") { this.director.GetComponent<GameDirector>().GetSmallCloud(); Debug.Log ("SmallCloud"); } else if (other.gameObject.tag == "LargeCloudTag") { this.director.GetComponent<GameDirector>().GetLargeCloud(); Debug.Log ("LargeCloud"); } } // Update is called once per frame void Update () { if(this.transform.position.z < this.visiblePosZ) { this.gameoverText.GetComponent<Text>().text = "Game Over"; } } }
using System.Linq; using System.Threading.Tasks; using M220N.Models; using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using NUnit.Framework; namespace M220NLessons { /// <summary> /// This Test Class shows the code used in the Advanced Reads lesson. /// /// In this lesson, we'll look at a few different ways we can read data from /// MongoDB by using the driver. We'll start with the most basic tools and /// then show some more advanced querying. /// /// </summary> public class AdvancedReads { private IMongoCollection<Movie> _moviesCollection; [SetUp] public void Setup() { var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); var client = new MongoClient(Constants.MongoDbConnectionUri()); _moviesCollection = client.GetDatabase("sample_mflix").GetCollection<Movie>("movies"); } [Test] public async Task GetMoviesAsync() { /* * In the last lesson, we saw how to use the driver to do basic reads * and projections from the datastore using the Find method. In this * lesson, we're going to expand on that: we'll look at other helper * methods available to you when using Find, and then we'll look at * how to implement an Aggregation Pipeline with the driver. */ /* Let's start with a filter that will return many movies. We'll * find all movies that have Tom Hanks listed in the cast: */ var filter = Builders<Movie>.Filter.In("cast", new string[] { "Tom Hanks" }); /* * In the last lesson, we saw that we can call Find and return a * List<Movie> that contains all of the results: * * var movies = await _moviesCollection.Find<Movie>(filter).ToListAsync(); * * But what if we want to limit the number of results? While we add * server-side or client-side code to limit the number of results * shown to the user, it makes more sense to ask MongoDB to only * return the data that we need. To do this, we simply chain the Limit * method to the Find call, like this: */ var movies = await _moviesCollection.Find<Movie>(filter) .Limit(2) .ToListAsync(); Assert.AreEqual(2, movies.Count); } [Test] public async Task GetMoviesAdvancedAsync() { /* * Now let's implement paging, so that our front end app * will only show one page at a time. * * How many movies are on a page? * That's up to you and your app requirements. * * Sorting also matters: * when you do pagination, you usually don't want a random order. * * So, in this example, we'll ask for all of the movies, sorted by * the year each came out, but we want to show only 10 movies per page. * The client code is responsible for telling us which page to show, * and typically a method like this would include an input parameter * of type int for that. */ var pageNumber = 3; var moviesPerPage = 10; var movies = await _moviesCollection.Find<Movie>(Builders<Movie>.Filter.Empty) .Sort(new BsonDocument("year", 1)) .Limit(moviesPerPage) .Skip(pageNumber * moviesPerPage) .ToListAsync(); /* * As with Queries and Projections, we can build the Sort using a * Builder method, like this: */ var sortByYearDescending = Builders<Movie>.Sort.Ascending(m => m.Year); movies = await _moviesCollection.Find<Movie>(Builders<Movie>.Filter.Empty) .Sort(sortByYearDescending) .Limit(moviesPerPage) .Skip(pageNumber * moviesPerPage) .ToListAsync(); // We expect 10 movies on this page, and the first should be older // -- or the same year -- as the last. Assert.AreEqual(10, movies.Count); Assert.LessOrEqual((int)movies.First().Year, (int)movies.Last().Year); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using MLAPI; using MLAPI.NetworkVariable; public class CarLap : NetworkBehaviour { public int lapNumber; public int CheckpointIndex; private void Start() { lapNumber = 1; CheckpointIndex = 0; } void Update() { if(lapNumber == 4) { Time.timeScale = 0f; } } }
using Moq; using NUnit.Framework; using ProgFrog.Interface.TaskRunning; using ProgFrog.Interface.TaskRunning.Runners; namespace ProgFrog.Tests.Tests { public class RunnersTestBase : CompilerTestBase { protected Mock<IFileWriter> _fileWriterMock; protected Mock<IProcessFactory> _processFactoryMock; protected Mock<IInputWriter> _inputWriterMock; protected Mock<IOutputReader> _outReaderMock; protected Mock<ITempFileProvider> _tempFileProviderMock; public RunnersTestBase() { } [SetUp] public void Setup() { _fileWriterMock = new Mock<IFileWriter>(); _processFactoryMock = new Mock<IProcessFactory>(); _inputWriterMock = new Mock<IInputWriter>(); _outReaderMock = new Mock<IOutputReader>(); _tempFileProviderMock = new Mock<ITempFileProvider>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task1_Euclidian_AlgorithmTests { class InputTests { } }
using Alabo.Domains.Entities; using Alabo.Domains.Services; using Alabo.Framework.Core.Tenants.Domains.Dtos; namespace Alabo.Framework.Core.Tenants.Domains.Services { /// <summary> /// ITenantCreateService /// </summary> public interface ITenantCreateService : IService { /// <summary> /// 删除租户 /// </summary> /// <param name="tenantInit"></param> /// <returns></returns> ServiceResult DeleteTenant(TenantInit tenantInit); /// <summary> /// 初始化租户默认数据 /// 包括创建管理员,权限等 /// </summary> /// <param name="tenantInit"></param> /// <returns></returns> ServiceResult InitTenantDefaultData(TenantInit tenantInit); /// <summary> /// 租户的验证的Token /// </summary> /// <param name="tenant"></param> /// <param name="siteId"></param> /// <returns></returns> string Token(string tenant, string siteId); /// <summary> /// 初始化租户模板数据 /// </summary> /// <param name="tenantInit"></param> /// <returns></returns> ServiceResult InitTenantTheme(TenantInit tenantInit); /// <summary> /// init tenant database /// </summary> /// <returns></returns> ServiceResult InitTenantDatabase(string tenant); /// <summary> /// 检查租户是否存在 /// </summary> /// <param name="tenant"></param> /// <returns></returns> ServiceResult HaveTenant(string tenant); /// <summary> /// 检查租户不存在 /// </summary> /// <param name="tenant"></param> /// <returns></returns> ServiceResult NoTenant(string tenant); } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Reflection; using CQRS.Core.Commands; using CQRS.Core.Events; using CQRS.Core.Queries; using CQRS.MediatR.Command; using CQRS.MediatR.Event; using CQRS.MediatR.Query; using MediatR; using Microsoft.Extensions.Configuration; using Serilog; namespace SchedulerAdv { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); loggingBuilder.AddSerilog(logger); }) .ConfigureServices((services) => { services.AddHostedService<SchedulerIntervalService>() .AddMediatR( Assembly.GetExecutingAssembly(), AppDomain.CurrentDomain.Load("Scheduler.FileService"), AppDomain.CurrentDomain.Load("Scheduler.MailService")) .AddSingleton<ICommandBus, CommandBus>() .AddSingleton<IEventBus, EventBus>() .AddSingleton<IQueryBus, QueryBus>(); }); } }
// removed 2022-11-22
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using TripNetCore.DAL; using TripNetCore.DAL.DbModels; using TripNetCore.Models; namespace TripCore.Controllers { [Route("api/[controller]")] [ApiController] public class LookupController : ControllerBase { private readonly DevCodeContext _db; public LookupController(DevCodeContext context) { _db = context; } // /api/Lookup/Iata/aa //[HttpGet] // [EnableCors("MyPolicy")] [Route("Iata/{term}")] public async Task<LookupItem[]> Iata(string term) { var lookupDao = new LookupDao(_db); return await lookupDao.airportsByIataAsync(term); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace QuestSystem { public class CollectionObjective : IQuestGoal { private string title; private string description; private string verb; private bool isComplete; private bool isSecondary; // If a branching path for the quest is required private int collectionAmount; //Required for completion private int currentAmount; private GameObject itemToCollect; /// <summary> /// This constructor builds a collection objective /// </summary> /// <param name="_title">Title of the objective</param> /// <param name="_totalAmount">Amount required to comeplete</param> /// <param name="_verb">Verb of the objective</param> /// <param name="_item">The item to collect</param> /// <param name="_description">description of the quest</param> /// <param name="secondary">Is it a secondary objective?</param> public CollectionObjective(string _title, int _totalAmount, string _verb, GameObject _item, string _description, bool secondary) { title = _title; description = _description; collectionAmount = _totalAmount; itemToCollect = _item; verb = _verb; currentAmount = 0; isSecondary = secondary; isComplete = false; } public string Title { get { return title; } } public string Description { get { return description; } set { description = value; } } public int CurrentAmount { get { return currentAmount; } } public int CollectionAmount { get { return collectionAmount; } } public GameObject ItemToCollect { get { return itemToCollect; } } public bool IsComplete { get { return isSecondary; } } public bool IsSecondary { get { return isSecondary; } } public void CheckProgress(GameObject item) { if(item = itemToCollect) { currentAmount++; } } public void UpdateProgress() { if(currentAmount >= collectionAmount) { isComplete = true; } else { isComplete = false; } } //Example: (0/10 Bread Collected!) public override string ToString() { return currentAmount + "/" + collectionAmount + " " + itemToCollect.name + " " + verb + "ed!"; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Threading; namespace FiiiChain.Framework { /// <summary> /// Represents a threaded List /// </summary> /// <typeparam name="T"> </typeparam> public class SafeCollection<T> : IList<T> { #region Variables /// <summary> /// The container list that holds the actual data /// </summary> private readonly List<T> m_TList; /// <summary> /// The lock used when accessing the list /// </summary> private readonly ReaderWriterLockSlim LockList = new ReaderWriterLockSlim(); // Variables #endregion #region Properties /// <summary> /// When true, we have already disposed of the object /// </summary> private int m_Disposed; /// <summary> /// When true, we have already disposed of the object /// </summary> private bool Disposed { get { return Thread.VolatileRead(ref m_Disposed) == 1; } set { Thread.VolatileWrite(ref m_Disposed, value ? 1 : 0); } } // Properties #endregion #region Init /// <summary> /// Creates an empty threaded list object /// </summary> public SafeCollection() { m_TList = new List<T>(); } /// <summary> /// Creates an empty threaded list object /// </summary> /// <param name="capacity">the number of elements the list can initially store</param> public SafeCollection(int capacity) { m_TList = new List<T>(capacity); } /// <summary> /// Creates an empty threaded list object /// </summary> /// <param name="collection">a collection of objects which are copied into the threaded list</param> public SafeCollection(IEnumerable<T> collection) { m_TList = new List<T>(collection); } // Init #endregion #region TypeCast_Overloads /// <summary> /// Converts List to TList /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator SafeCollection<T>(List<T> value) { return new SafeCollection<T>(value); } // TypeCast_Overloads #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator to iterate through the collection /// </summary> public IEnumerator GetEnumerator() { // http://www.csharphelp.com/archives/archive181.html List<T> localList; // init enumerator LockList.EnterReadLock(); try { // create a copy of m_TList localList = new List<T>(m_TList); } finally { LockList.ExitReadLock(); } // get the enumerator foreach (T item in localList) yield return item; } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator to iterate through the collection /// </summary> IEnumerator<T> IEnumerable<T>.GetEnumerator() { // http://www.csharphelp.com/archives/archive181.html List<T> localList; // init enumerator LockList.EnterReadLock(); try { // create a copy of m_TList localList = new List<T>(m_TList); } finally { LockList.ExitReadLock(); } // get the enumerator foreach (T item in localList) yield return item; } #endregion #region IDisposable Members // Implement IDisposable. // Do not make this method virtual. // A derived class should not be able to override this method. /// <summary> /// Dispose of the object /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. /// <summary> /// The disposer /// </summary> /// <param name="disposing">true if disposed</param> private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (this.Disposed) return; // If disposing equals true, dispose all managed // and unmanaged resources. //if(disposing) //{ // // NO managed resources to dispose for this object //} // Note disposing has been done. Disposed = true; } // Use C# destructor syntax for finalization code. // This destructor will run only if the Dispose method // does not get called. // It gives your base class the opportunity to finalize. // Do not provide destructors in types derived from this class. /// <summary> /// Finalizes an instance of the <see cref="TList{T}"/> class. /// </summary> ~SafeCollection() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } #endregion #region Add /// <summary> /// Adds an item to the threaded list /// </summary> /// <param name="item">the item to add to the end of the collection</param> public void Add(T item) { LockList.EnterWriteLock(); try { m_TList.Add(item); } finally { LockList.ExitWriteLock(); } } // Add #endregion #region AddRange /// <summary> /// Adds the elements of collection to the end of the threaded list /// </summary> /// <param name="collection">the collection to add to the end of the list</param> public void AddRange(IEnumerable<T> collection) { LockList.EnterWriteLock(); try { m_TList.AddRange(collection); } finally { LockList.ExitWriteLock(); } } // AddRange #endregion #region AddIfNotExist /// <summary> /// Adds an item to the threaded list if it is not already in the list. /// Returns true if added to the list, false if the item already existed /// in the list /// </summary> /// <param name="item">the item to add to the end of the collection</param> public bool AddIfNotExist(T item) { LockList.EnterWriteLock(); try { // check if it exists already if (m_TList.Contains(item)) return false; // add the item and return true m_TList.Add(item); return true; } finally { LockList.ExitWriteLock(); } } // AddIfNotExist #endregion #region AsReadOnly /// <summary> /// Returns a read-only collection of the current threaded list /// </summary> public ReadOnlyCollection<T> AsReadOnly() { LockList.EnterReadLock(); try { return m_TList.AsReadOnly(); } finally { LockList.ExitReadLock(); } } // AsReadOnly #endregion #region BinarySearch /// <summary> /// Searches the collection using the default comparator and returns the zero-based index of the item found /// </summary> /// <param name="item">the item to search for</param> public int BinarySearch(T item) { LockList.EnterReadLock(); try { return m_TList.BinarySearch(item); } finally { LockList.ExitReadLock(); } } /// <summary> /// Searches the collection using the default comparator and returns the zero-based index of the item found /// </summary> /// <param name="item">the item to search for</param> /// <param name="comparer">the IComparer to use when searching, or null to use the default</param> public int BinarySearch(T item, IComparer<T> comparer) { LockList.EnterReadLock(); try { return m_TList.BinarySearch(item, comparer); } finally { LockList.ExitReadLock(); } } /// <summary> /// Searches the collection using the default comparator and returns the zero-based index of the item found /// </summary> /// <param name="index">the zero-based index to start searching from</param> /// <param name="count">the number of records to search</param> /// <param name="item">the item to search for</param> /// <param name="comparer">the IComparer to use when searching, or null to use the default</param> public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { LockList.EnterReadLock(); try { return m_TList.BinarySearch(index, count, item, comparer); } finally { LockList.ExitReadLock(); } } // BinarySearch #endregion #region Capacity /// <summary> /// Gets or sets the initial capacity of the list /// </summary> public int Capacity { get { LockList.EnterReadLock(); try { return m_TList.Capacity; } finally { LockList.ExitReadLock(); } } set { LockList.EnterWriteLock(); try { m_TList.Capacity = value; } finally { LockList.ExitWriteLock(); } } } // Capacity #endregion #region Clear /// <summary> /// Removes all items from the threaded list /// </summary> public void Clear() { LockList.EnterReadLock(); try { m_TList.Clear(); } finally { LockList.ExitReadLock(); } } // Clear #endregion #region Contains /// <summary> /// Returns true if the collection contains this item /// </summary> /// <param name="item">the item to find in the collection</param> public bool Contains(T item) { LockList.EnterReadLock(); try { return m_TList.Contains(item); } finally { LockList.ExitReadLock(); } } // Contains #endregion #region ConvertAll /// <summary> /// Converts the elements of the threaded list to another type, and returns a list of the new type /// </summary> /// <typeparam name="TOutput">the destination type</typeparam> /// <param name="converter">delegate to convert the items to a new type</param> public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) { LockList.EnterReadLock(); try { return m_TList.ConvertAll(converter); } finally { LockList.ExitReadLock(); } } // ConvertAll #endregion #region CopyTo /// <summary> /// Copies the elements of this threaded list to a one-dimension array of the same type /// </summary> /// <param name="array">the destination array</param> /// <param name="arrayIndex">index at which copying begins</param> public void CopyTo(T[] array, int arrayIndex) { LockList.EnterReadLock(); try { m_TList.CopyTo(array, arrayIndex); } finally { LockList.ExitReadLock(); } } // CopyTo #endregion #region Count /// <summary> /// Returns a count of the number of elements in this collection /// </summary> public int Count { get { LockList.EnterReadLock(); try { return m_TList.Count; } finally { LockList.ExitReadLock(); } } } // Count #endregion #region Exists /// <summary> /// Determines whether an item exists which meets the match criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public bool Exists(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.Exists(match); } finally { LockList.ExitReadLock(); } } // Exists #endregion #region Find /// <summary> /// Searches for an element that matches the criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public T Find(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.Find(match); } finally { LockList.ExitReadLock(); } } // Find #endregion #region FindAll /// <summary> /// Searches for elements that match the criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public List<T> FindAll(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindAll(match); } finally { LockList.ExitReadLock(); } } // FindAll #endregion #region FindIndex /// <summary> /// Returns the index of the element which matches the criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public int FindIndex(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindIndex(match); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the index of the element which matches the criteria /// </summary> /// <param name="startIndex">the zero-based index starting the search</param> /// <param name="match">delegate that defines the conditions to search for</param> public int FindIndex(int startIndex, Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindIndex(startIndex, match); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the index of the element which matches the criteria /// </summary> /// <param name="startIndex">the zero-based index starting the search</param> /// <param name="count">the number of elements to search</param> /// <param name="match">delegate that defines the conditions to search for</param> public int FindIndex(int startIndex, int count, Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindIndex(startIndex, count, match); } finally { LockList.ExitReadLock(); } } // FindIndex #endregion #region FindLast /// <summary> /// Searches for the last element in the collection that matches the criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public T FindLast(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindLast(match); } finally { LockList.ExitReadLock(); } } // FindLast #endregion #region FindLastIndex /// <summary> /// Returns the last index of the element which matches the criteria /// </summary> /// <param name="match">delegate that defines the conditions to search for</param> public int FindLastIndex(Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindLastIndex(match); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the last index of the element which matches the criteria /// </summary> /// <param name="startIndex">the zero-based index starting the search</param> /// <param name="match">delegate that defines the conditions to search for</param> public int FindLastIndex(int startIndex, Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindLastIndex(startIndex, match); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the last index of the element which matches the criteria /// </summary> /// <param name="startIndex">the zero-based index starting the search</param> /// <param name="count">the number of elements to search</param> /// <param name="match">delegate that defines the conditions to search for</param> public int FindLastIndex(int startIndex, int count, Predicate<T> match) { LockList.EnterReadLock(); try { return m_TList.FindLastIndex(startIndex, count, match); } finally { LockList.ExitReadLock(); } } // FindLastIndex #endregion #region ForEach /// <summary> /// Peforms the action on each element of the list /// </summary> /// <param name="action">the action to perfom</param> public void ForEach(Action<T> action) { LockList.EnterWriteLock(); try { m_TList.ForEach(action); } finally { LockList.ExitWriteLock(); } } // ForEach #endregion /// <summary> /// Creates a shallow copy of the range of elements in the source /// </summary> /// <param name="index">index to start from</param> /// <param name="count">number of elements to return</param> /// <returns></returns> public List<T> GetRange(int index, int count) { LockList.EnterReadLock(); try { return m_TList.GetRange(index, count); } finally { LockList.ExitReadLock(); } } /// <summary> /// Searches the list and returns the index of the item found in the list /// </summary> /// <param name="item">the item to find</param> public int IndexOf(T item) { LockList.EnterReadLock(); try { return m_TList.IndexOf(item); } finally { LockList.ExitReadLock(); } } /// <summary> /// Searches the list and returns the index of the item found in the list /// </summary> /// <param name="item">the item to find</param> /// <param name="index">the zero-based index to begin searching from</param> public int IndexOf(T item, int index) { LockList.EnterReadLock(); try { return m_TList.IndexOf(item, index); } finally { LockList.ExitReadLock(); } } /// <summary> /// Searches the list and returns the index of the item found in the list /// </summary> /// <param name="item">the item to find</param> /// <param name="index">the zero-based index to begin searching from</param> /// <param name="count">the number of elements to search</param> public int IndexOf(T item, int index, int count) { LockList.EnterReadLock(); try { return m_TList.IndexOf(item, index, count); } finally { LockList.ExitReadLock(); } } /// <summary> /// Inserts the item into the list /// </summary> /// <param name="index">the index at which to insert the item</param> /// <param name="item">the item to insert</param> public void Insert(int index, T item) { LockList.ExitWriteLock(); try { m_TList.Insert(index, item); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Insert a range of objects into the list /// </summary> /// <param name="index">index to insert at</param> /// <param name="range">range of values to insert</param> public void InsertRange(int index, IEnumerable<T> range) { LockList.EnterWriteLock(); try { m_TList.InsertRange(index, range); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Always false /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Returns the last index of the item in the list /// </summary> /// <param name="item">the item to find</param> public int LastIndexOf(T item) { LockList.EnterReadLock(); try { return m_TList.LastIndexOf(item); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the last index of the item in the list /// </summary> /// <param name="item">the item to find</param> /// <param name="index">the index at which to start searching</param> public int LastIndexOf(T item, int index) { LockList.EnterReadLock(); try { return m_TList.LastIndexOf(item, index); } finally { LockList.ExitReadLock(); } } /// <summary> /// Returns the last index of the item in the list /// </summary> /// <param name="item">the item to find</param> /// <param name="index">the index at which to start searching</param> /// <param name="count">number of elements to search</param> public int LastIndexOf(T item, int index, int count) { LockList.EnterReadLock(); try { return m_TList.LastIndexOf(item, index, count); } finally { LockList.ExitReadLock(); } } /// <summary> /// Removes this item from the list /// </summary> /// <param name="item">the item to remove</param> public bool Remove(T item) { LockList.EnterWriteLock(); try { return m_TList.Remove(item); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Removes all the matching items from the list /// </summary> /// <param name="match">the pattern to search on</param> public int RemoveAll(Predicate<T> match) { LockList.EnterWriteLock(); try { return m_TList.RemoveAll(match); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Removes the item at the specified index /// </summary> /// <param name="index">the index of the item to remove</param> public void RemoveAt(int index) { LockList.EnterWriteLock(); try { m_TList.RemoveAt(index); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Removes the items from the list /// </summary> /// <param name="index">the index of the item to begin removing</param> /// <param name="count">the number of items to remove</param> public void RemoveRange(int index, int count) { LockList.EnterWriteLock(); try { m_TList.RemoveRange(index, count); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Reverses the order of elements in the list /// </summary> public void Reverse() { LockList.EnterWriteLock(); try { m_TList.Reverse(); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Reverses the order of elements in the list /// </summary> /// <param name="index">the index to begin reversing at</param> /// <param name="count">the number of elements to reverse</param> public void Reverse(int index, int count) { LockList.EnterWriteLock(); try { m_TList.Reverse(index, count); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Sorts the items in the list /// </summary> public void Sort() { LockList.EnterWriteLock(); try { m_TList.Sort(); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Sorts the items in the list /// </summary> /// <param name="comparison">the comparison to use when comparing elements</param> public void Sort(Comparison<T> comparison) { LockList.EnterWriteLock(); try { m_TList.Sort(comparison); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Sorts the items in the list /// </summary> /// <param name="comparer">the comparer to use when comparing elements</param> public void Sort(IComparer<T> comparer) { LockList.EnterWriteLock(); try { m_TList.Sort(comparer); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Sorts the items in the list /// </summary> /// <param name="index">the index to begin sorting at</param> /// <param name="count">the number of elements to sort</param> /// <param name="comparer">the comparer to use when sorting</param> public void Sort(int index, int count, IComparer<T> comparer) { LockList.EnterWriteLock(); try { m_TList.Sort(index, count, comparer); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Copies the elements of the list to an array /// </summary> public T[] ToArray() { LockList.EnterReadLock(); try { return m_TList.ToArray(); } finally { LockList.ExitReadLock(); } } /// <summary> /// Sets the capacity to the actual number of elements in the list, if that /// number is less than the threshold /// </summary> public void TrimExcess() { LockList.EnterWriteLock(); try { m_TList.TrimExcess(); } finally { LockList.ExitWriteLock(); } } /// <summary> /// Determines whether all members of the list matches the conditions in the predicate /// </summary> /// <param name="match">the delegate which defines the conditions for the search</param> public bool TrueForAll(Predicate<T> match) { LockList.EnterWriteLock(); try { return m_TList.TrueForAll(match); } finally { LockList.ExitWriteLock(); } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #region IList<T> Members /// <summary> /// An item in the list /// </summary> /// <param name="index"></param> /// <returns></returns> public T this[int index] { get { LockList.EnterReadLock(); try { return m_TList[index]; } finally { LockList.ExitReadLock(); } } set { LockList.EnterWriteLock(); try { m_TList[index] = value; } finally { LockList.ExitWriteLock(); } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem19 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 19"; public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { var blueprints = GetBlueprints(input); return SumQuality(blueprints, 24); } private int Answer2(List<string> input) { var blueprints = GetBlueprints(input).Take(3).ToList(); return All(blueprints, 32); } private int All(List<Blueprint> blueprints, int minutesRemaining) { int product = 1; foreach (var print in blueprints) { var data = new RecursiveData() { MinutesRemaining = minutesRemaining, Materials = new int[4], Robots = new int[4] }; data.Robots[Blueprint.MaterialIndexOre] = 1; Recursive(print, data, false); product *= data.Best; } return product; } private int SumQuality(List<Blueprint> blueprints, int minutesRemaining) { int quality = 0; foreach (var print in blueprints) { var data = new RecursiveData() { MinutesRemaining = minutesRemaining, Materials = new int[4], Robots = new int[4] }; data.Robots[Blueprint.MaterialIndexOre] = 1; Recursive(print, data, false); quality += data.Best * print.Id; } return quality; } private void Recursive(Blueprint print, RecursiveData data, bool hasConstruction) { if (Continue(data)) { int minutes = MinutesToMake(data, print.GeodeRobotCost); if (((minutes == 0 && !hasConstruction) | (minutes > 0)) && minutes <= data.MinutesRemaining) { Recursive_MakeRobot(print, data, Blueprint.MaterialIndexGeode, print.GeodeRobotCost, minutes, "Geode"); } minutes = MinutesToMake(data, print.ObsidianRobotCost); if (((minutes == 0 && !hasConstruction) | (minutes > 0)) && minutes <= data.MinutesRemaining) { Recursive_MakeRobot(print, data, Blueprint.MaterialIndexObsidian, print.ObsidianRobotCost, minutes, "Obsidian"); } minutes = MinutesToMake(data, print.ClayRobotCost); if (((minutes == 0 && !hasConstruction) | (minutes > 0)) && minutes <= data.MinutesRemaining) { Recursive_MakeRobot(print, data, Blueprint.MaterialIndexClay, print.ClayRobotCost, minutes, "Clay"); } minutes = MinutesToMake(data, print.OreRobotCost); if (((minutes == 0 && !hasConstruction) | (minutes > 0)) && minutes <= data.MinutesRemaining) { Recursive_MakeRobot(print, data, Blueprint.MaterialIndexOre, print.OreRobotCost, minutes, "Ore"); } } } private void Recursive_MakeRobot(Blueprint print, RecursiveData data, int materialIndex, int[] cost, int minutes, string robot) { data.MinutesRemaining -= minutes; for (int index = 0; index < data.Materials.Length; index++) { data.Materials[index] += data.Robots[index] * minutes; data.Materials[index] -= cost[index]; } data.Robots[materialIndex]++; CheckBest(data); Recursive(print, data, true); data.Robots[materialIndex]--; for (int index = 0; index < data.Materials.Length; index++) { data.Materials[index] += cost[index]; data.Materials[index] -= data.Robots[index] * minutes; } data.MinutesRemaining += minutes; } private int MinutesToMake(RecursiveData data, int[] robotCost) { int highest = 1; for (int index = 0; index < robotCost.Length; index++) { if (robotCost[index] > 0 && (data.Robots[index] == 0)) return -1; if (data.Materials[index] < robotCost[index]) { int minutes = 0; int robots = data.Robots[index]; int materials = data.Materials[index]; if (materials < robotCost[index]) { minutes += (robotCost[index] - materials) / robots; int total = minutes * robots + materials; if (total < robotCost[index]) minutes++; } minutes++; if (minutes > highest) highest = minutes; } } return highest; } private void CheckBest(RecursiveData data) { int total = data.Robots[Blueprint.MaterialIndexGeode] * data.MinutesRemaining + data.Materials[Blueprint.MaterialIndexGeode]; if (total > data.Best) data.Best = total; } private bool Continue(RecursiveData data) { if (data.Best == 0) return true; int total = data.Materials[Blueprint.MaterialIndexGeode]; total += GetSum(data.MinutesRemaining); total += data.Robots[Blueprint.MaterialIndexGeode] * data.MinutesRemaining; return total > data.Best; } private int GetSum(int remaining) { if (remaining % 2 == 0) { return remaining * (remaining / 2 - 1) + (remaining / 2); } else { return remaining * ((remaining - 1) / 2); } } private List<Blueprint> GetBlueprints(List<string> input) { return input.Select(line => { var split = line.Split(' '); var blueprint = new Blueprint() { ClayRobotCost = new int[4] { Convert.ToInt32(split[12]), 0, 0, 0 }, GeodeRobotCost = new int[4] { Convert.ToInt32(split[27]), 0, Convert.ToInt32(split[30]), 0 }, Id = Convert.ToInt32(split[1].Replace(":", "")), ObsidianRobotCost = new int[4] { Convert.ToInt32(split[18]), Convert.ToInt32(split[21]), 0, 0 }, OreRobotCost = new int[4] { Convert.ToInt32(split[6]), 0, 0, 0 } }; return blueprint; }).ToList(); } private class RecursiveData { public int MinutesRemaining { get; set; } public int[] Materials { get; set; } public int[] Robots { get; set; } public int Best { get; set; } } private class Blueprint { public int Id { get; set; } public int[] OreRobotCost { get; set; } public int[] ClayRobotCost { get; set; } public int[] ObsidianRobotCost { get; set; } public int[] GeodeRobotCost { get; set; } public static int MaterialIndexOre => 0; public static int MaterialIndexClay => 1; public static int MaterialIndexObsidian => 2; public static int MaterialIndexGeode => 3; } private class MaterialCost { public int MaterialIndex { get; set; } public int Cost { get; set; } } } }
using UnityEngine; public class Card06Senna : CardParent, ISkill { [SerializeField] private CardStatus CardStatus = null; public void ActiveSkill(int myLane) { var myPlayer = CardStatus.Player; var fullSearch = FullSearch((enemyPlayer, enemyLane) => { return (enemyPlayer != myPlayer && enemyLane == myLane); }); foreach (var card in fullSearch) { card.CardStatus.AddDamage(myPlayer, (int)(CardStatus.MyAD * CardStatus.MyRatio), (int)EnumSkillType.SkillShot); } var fullSearchHeal = FullSearch((enemyPlayer, enemyLane) => { return (enemyPlayer == myPlayer && enemyLane == myLane); }); foreach (var card in fullSearchHeal) { card.CardStatus.AddHeal((int)(CardStatus.MyAD * CardStatus.MyRatio)); } } }
namespace cyrka.api.domain.customers.commands.retire { public class CustomerRetired : CustomerEventData { public CustomerRetired(string id) : base(id) { } } }
/** * 自然框架之信息管理类项目的页面基类 * http://www.natureFW.com/ * * @author * 金洋(金色海洋jyk) * * @copyright * Copyright (C) 2005-2013 金洋. * * Licensed under a GNU Lesser General Public License. * http://creativecommons.org/licenses/LGPL/2.1/ * * 自然框架之信息管理类项目的页面基类 is free software. You are allowed to download, modify and distribute * the source code in accordance with LGPL 2.1 license, however if you want to use * 自然框架之信息管理类项目的页面基类 on your site or include it in your commercial software, you must be registered. * http://www.natureFW.com/registered */ /* *********************************************** * author : 金洋(金色海洋jyk) * email : jyk0011@live.cn * function: 上传文件的共用页面 * history: created by 金洋 * ********************************************** */ using System; using System.IO; using System.Web; using System.Web.Services; using Nature.Common; using Nature.MetaData.Enum; namespace Nature.Service.Data { /// <summary> /// 上传文件的共用页面,这个是要改的,没弄好。 /// </summary> [WebService(Namespace = "http://natureFW.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class UploadHandler : BaseAshxCrud { /// <summary> /// 接受上传的文件 /// </summary> /// <param name="context"></param> public override void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; string columnID = @context.Request["folder"]; int index = columnID.LastIndexOf('/'); columnID = columnID.Substring(index + 1); if (!Functions.IsInt(columnID)) { context.Response.Write("文件夹设置不正确,不能上传文件!" + index + "_" + columnID); return; } //string sql = "select ControlInfo from Manage_Columns where ColumnID= " + columnID; //string sql = "select ControlInfo from Manage_Columns where ColumnID= {0}"; //sql = string.Format(sql,columnID ); //string controlInfo = base.Dal.DalMetadata.ExecuteString(sql); //FileUploadKind fileUploadKind = FileUploadKind.SiampleImage ; FileNameKind fileNameKind = FileNameKind.UserIDTime ; string[] tmpInfo = columnID.Split('|')[0].Split('~'); //if (tmpInfo.Length < 3) //{ // context.Response.Write("配置信息不正确,不能上传文件!" + columnID + "_" + columnID); // return; //} string filePath = "aaa";// tmpInfo[0]; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = HttpContext.Current.Server.MapPath("/" + filePath); if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string fileName = file.FileName; string fileExt = fileName.Substring(fileName.LastIndexOf('.')); if (fileNameKind == FileNameKind.UserIDTime) { //Nature.User.BaseUserInfo myUser = new Nature.User.BaseUserInfo();+ myUser.UserID + "_" //myUser = (Nature.User.BaseUserInfo)context.Session[UserLoginSign + "sysUserInfo"]; fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt; file.SaveAs(uploadPath + "\\" + fileName); } else { file.SaveAs(uploadPath + fileName); } //file.SaveAs(uploadPath + "aaa.txt"); //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 context.Response.Write(filePath + "/" + fileName + '`' + fileName); } else { context.Response.Write("0"); } } } }
using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace YFVIC.DMS.Model.Models.FileInfo { public class FormHistoryEntity { /// <summary> /// 编号 /// </summary> [DataMember] public string Id; /// <summary> ///名称 /// </summary> [DataMember] public string Name; /// <summary> /// 类型 /// </summary> [DataMember] public string Type; /// <summary> /// 地址 /// </summary> [DataMember] public string Path; /// <summary> /// 主文件地址 /// </summary> [DataMember] public string FilePath; /// <summary> /// 地址 /// </summary> [DataMember] public string FileUrl; /// <summary> ///是否删除 /// </summary> [DataMember] public string IsDeleted; /// <summary> /// 当前版本号 /// </summary> [DataMember] public string VersionNum; /// <summary> /// 表单编码 /// </summary> [DataMember] public string FileNum; /// <summary> /// 文件编号 /// </summary> [DataMember] public string FileId; /// <summary> /// 创建人 /// </summary> [DataMember] public string Creater; /// <summary> /// 创建时间 /// </summary> [DataMember] public string CreateTime; /// <summary> ///sharepoint版本号 /// </summary> [DataMember] public string SPVersion; /// <summary> /// 表单编号 /// </summary> [DataMember] public string FormId; } }
//using System; //public interface IHealth //{ // Health Health { get; } //} public interface IHurtable { void Hurt (int damage); } // //[Serializable] //public class Health //{ // public int maxHitPoints = 100; // public int hitPoints; // // private Action hurtAction; // private Action hitPointsOverAction; // // public void Initialize (Action hurtAction, Action hitPointsOverAction) // { // this.hurtAction = hurtAction; // this.hitPointsOverAction = hitPointsOverAction; // hitPoints = maxHitPoints; // } // // public void Hurt (int damage) // { // hitPoints -= damage; // if (hitPoints <= 0) { // if (hitPointsOverAction != null) { // hitPointsOverAction (); // } // } else if (hurtAction != null) { // hurtAction (); // } // } //}
using GodaddyWrapper.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Requests { public class DomainRetrieve { public List<string> statuses { get; set; } public List<string> statusGroups { get; set; } public int limit { get; set; } public string marker { get; set; } public List<string> includes { get; set; } public string modifiedDate { get; set; } } }
namespace Tutorial.LinqToEntities { #if EF using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; [ComplexType] public class ManagerEmployee { public int? RecursionLevel { get; set; } public string OrganizationNode { get; set; } public string ManagerFirstName { get; set; } public string ManagerLastName { get; set; } public int? BusinessEntityID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public partial class AdventureWorks { public ObjectResult<ManagerEmployee> GetManagerEmployees(int businessEntityId) { const string BusinessEntityID = nameof(BusinessEntityID); SqlParameter businessEntityIdParameter = new SqlParameter(nameof(BusinessEntityID), businessEntityId); return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<ManagerEmployee>( $"[dbo].[uspGetManagerEmployees] @{nameof(BusinessEntityID)}", businessEntityIdParameter); } } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace C9FIleWatcher { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Helper to make app access seamless. private C9FIleWatcher.App App() { return ((C9FIleWatcher.App) Application.Current); } public MainWindow() { InitializeComponent(); } C9FIleWatcher.App MyApp() { C9FIleWatcher.App myApp = (C9FIleWatcher.App) Application.Current; return (myApp); } private void ImageToDrop_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) { bool newOne = MyApp().AddTo(file); if (newOne) { var border = new Border(); border.BorderThickness = new Thickness(5); border.BorderBrush = new SolidColorBrush(Colors.Red); DockPanel panel = new DockPanel(); border.Child = panel; Label label = new Label(); label.Content = file; panel.Children.Add(label); DockPanel.SetDock(border, Dock.Top); DockPanel_WorkingItems.Children.Add(border); } } } } private void ImageFromDrop_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) { bool newOne = MyApp().AddFrom(file); if (newOne) { var border = new Border(); border.BorderThickness = new Thickness(5); border.BorderBrush = new SolidColorBrush(Colors.Green); DockPanel panel = new DockPanel(); border.Child = panel; Label label = new Label(); label.Content = file; panel.Children.Add(label); DockPanel.SetDock(border, Dock.Top); DockPanel_WorkingItems.Children.Add(border); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.ComTypes; using Morales.CompulsoryPetShop.Core.Models; using Morales.CompulsoryPetShop.Domain.IRepositories; namespace Morales.CompulsoryPetShop.Infrastucture.Repositories { public class OwnerRepository : IOwnerRepository { private static List<Owner> _ownerTable = new List<Owner>(); private static int _id = 1; public List<Owner> GetAllOwners() { Owner owner1 = new Owner(); owner1.Id = 1; owner1.Name = "Ole"; _ownerTable.Add(owner1); Owner owner2 = new Owner(); owner2.Id = 2; owner2.Name = "Poul"; _ownerTable.Add(owner2); Owner owner3 = new Owner(); owner3.Id = 3; owner3.Name = "Kalle"; _ownerTable.Add(owner3); return _ownerTable; } public Owner CreateOwner(Owner owner) { _ownerTable.Add(owner); return owner; } public Owner RemoveOwner(int id) { var owner = ReadByOwnerId(id); _ownerTable.Remove(_ownerTable.FirstOrDefault(o => o.Id == id)); return owner; } public Owner UpdateOwner(Owner owner) { var OwnerOld = _ownerTable.FirstOrDefault(o => o.Id == owner.Id); if (OwnerOld != null) { OwnerOld.Name = owner.Name; } return null; } public Owner ReadByOwnerId(int id) { foreach (var owner in _ownerTable) { if (owner.Id == id) { return owner; } } return null; } public List<Owner> ReadAllOwner() { return _ownerTable; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor.SceneManagement; using socket.io; public class MultiLobbyScene : MonoBehaviour { public Room[] mRoomList; Socket socket; // Use this for initialization void Start() { socket = Login.socket; createRoom("asd"); getRoomList(); } // Update is called once per frame void Update() { } public void EnterRoom(Room tRoom) { } public class Room { int mPlayerNum; string mRoomName; } void joinRoom(string room) { Debug.Log("joinRoom"); socket.Emit("joinRoom", room, (string data) => { Debug.Log("joinRoom " + data); }); } void createRoom(string room) { Debug.Log("createRooM"); socket.Emit("createRoom", room, (string data) => { Debug.Log("createRooM : " + data); }); } void getRoomList() { Debug.Log("getRoomList"); socket.Emit("getRoomList", "dsa", (string data) => { Debug.Log("getRoomList : " + data); JSONObject obj = new JSONObject(data); }); } }
using CyberSoldierServer.Helpers; namespace CyberSoldierServer.Services { public class ConvertErrorToCodeService : IConvertErrorToCodeService { public int ConvertErrorToCode(string error) { return error switch { "PasswordTooShort" => 1, "PasswordRequiresLower" => 2, "PasswordRequiresUpper" => 3, "InvalidEmail" => 4, "DuplicateEmail" => 5, _ => 0 }; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameManager : MonoBehaviour { public int score; public Text scoreDisplay; public bool paused; public RoadManager roadManager; public PlayerMovement player; [Header("Camera")] public float cameraTransitionTime; public Transform cameraPlayPos; public Transform cameraPausePos; public Transform mainCamera; public void scorePoint( int points ) { score += points; scoreDisplay.text = score.ToString(); } public void gameOver() { Application.LoadLevel( Application.loadedLevel ); } // Use this for initialization void Start () { pauseGame(); } // Update is called once per frame void Update () { if( Input.GetKeyDown( KeyCode.Space ) ) { startGame(); } } void startGame() { paused = false; player.enabled = true; roadManager.enabled = true; StartCoroutine( "moveCameraToPlayPos" ); } void pauseGame() { paused = true; player.enabled = false; roadManager.enabled = false; } IEnumerator moveCameraToPlayPos() { for( float i = 0f; i < cameraTransitionTime; i += Time.deltaTime ) { mainCamera.Translate( ( cameraPlayPos.position - mainCamera.position ) / 2 ); mainCamera.Rotate( ( cameraPlayPos.eulerAngles - mainCamera.eulerAngles ) / 2 ); yield return null; } mainCamera.position = cameraPlayPos.position; mainCamera.rotation = cameraPlayPos.rotation; } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace Sentry.AspNetCore; /// <summary> /// Starts Sentry integration. /// </summary> public class SentryStartupFilter : IStartupFilter { /// <summary> /// Adds Sentry to the pipeline. /// </summary> public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => e => { e.UseSentry(); next(e); }; }
using AbiokaScrum.Api.Authentication; using AbiokaScrum.Api.Entities; using AbiokaScrum.Api.Entities.DTO; using DapperExtensions; using System; using System.Collections.Generic; using System.Linq; namespace AbiokaScrum.Api.Data.Transactional.Dapper.Operations { public class BoardOperation : Operation<Board>, IBoardOperation { private readonly IOperation<BoardUser> boardUserOperation; private readonly IListOperation listOperation; private readonly IUserOperation userOperation; public BoardOperation(IOperation<BoardUser> boardUserOperation, IListOperation listOperation, IUserOperation userOperation) { this.boardUserOperation = boardUserOperation; this.listOperation = listOperation; this.userOperation = userOperation; } public override void Add(Board board) { Execute((repository) => { board.Users = new List<UserDTO> { new UserDTO { Id = Context.Current.Principal.Id } }; board.CreatedUser = Context.Current.Principal.Id; repository.Add(board); var boardUser = new BoardUser { BoardId = board.Id, UserId = Context.Current.Principal.Id }; repository.Add(boardUser); }); } public Board Get(Guid id) { var board = GetByKey(id); var predicate = Predicates.Field<List>(l => l.BoardId, Operator.Eq, id); board.Lists = ((Operation<List>)listOperation).GetBy(predicate); return board; } public IEnumerable<Board> GetAll() { IList<ISort> sort = new List<ISort> { Predicates.Sort<Board>(b => b.CreateDate, false) }; var boardIds = GetBoardIds(); if (boardIds == null || boardIds.Count() == 0) { return new List<Board>(); } var boards = GetBy(Predicates.Field<Board>(b => b.Id, Operator.Eq, boardIds), sort); foreach (var board in boards) { var predicate = Predicates.Field<BoardUser>(l => l.BoardId, Operator.Eq, board.Id); board.Users = ((Operation<BoardUser>)boardUserOperation).GetBy(predicate).Select(b => new UserDTO { Id = b.UserId }); } return boards; } public IEnumerable<User> GetBoardUsers(Guid boardId) { var predicate = Predicates.Field<BoardUser>(b => b.BoardId, Operator.Eq, boardId); var userIds = ((Operation<BoardUser>)boardUserOperation).GetBy(predicate: predicate).Select(b => b.UserId); var userPredicate = Predicates.Field<User>(b => b.Id, Operator.Eq, userIds); var sort = new List<ISort> { Predicates.Sort<User>(b => b.Name) }; var result = ((Operation<User>)userOperation).GetBy(userPredicate, sort); return result; } private IEnumerable<Guid> GetBoardIds() { var predicate = Predicates.Field<BoardUser>(b => b.UserId, Operator.Eq, Context.Current.Principal.Id); return ((Operation<BoardUser>)boardUserOperation).GetBy(predicate: predicate).Select(b => b.BoardId); } public override void Remove(Board entity) { var board = Get(entity.Id); Execute((repository) => { if (board.Lists != null) { foreach (var listItem in board.Lists) { ((ListOperation)listOperation).Delete(listItem, repository); } } board.IsDeleted = true; repository.Update(board); }); } public BoardUser AddUser(Guid boardId, Guid userId) { var boardUser = new BoardUser { BoardId = boardId, UserId = userId }; boardUserOperation.Add(boardUser); return boardUser; } public void RemoveUser(Guid boardId, Guid userId) { var boardUser = new BoardUser { BoardId = boardId, UserId = userId }; boardUserOperation.Remove(boardUser); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using QuanLyNhaHang.DTO; namespace QuanLyNhaHang.DAO { public class BoPhanNhanVienDAO { private static BoPhanNhanVienDAO instance; public static BoPhanNhanVienDAO Instance { get { if (instance == null) instance = new BoPhanNhanVienDAO(); return instance; } private set { instance = value; } } private BoPhanNhanVienDAO() { } public List<BoPhanNhanVien> GetBoPhanNhanVienByMaBP(string MaBP) { List<BoPhanNhanVien> list = new List<BoPhanNhanVien>(); string query = "select * from BoPhanNhanVien where MaBP = " + MaBP; DataTable data = DataProvider.Instance.Excutequery(query); foreach (DataRow item in data.Rows) { BoPhanNhanVien boPhanNhanVien = new BoPhanNhanVien(item); list.Add(boPhanNhanVien); } return list; } public List<BoPhanNhanVien> GetListBoPhanNhanVien() { List<BoPhanNhanVien> list = new List<BoPhanNhanVien>(); string query = "select * from BoPhanNhanVien"; DataTable data = DataProvider.Instance.Excutequery(query); foreach (DataRow item in data.Rows) { BoPhanNhanVien boPhanNhanVien = new BoPhanNhanVien(item); list.Add(boPhanNhanVien); } return list; } public bool InsertBPEmployee(string MaBP, string TenBP) { string query = string.Format("INSERT into dbo.BoPhanNhanVien(MaBP,TenBP)" + "VALUES(N'{0}',N'{1}')", MaBP,TenBP); int res = DataProvider.Instance.ExecuteNonQuery(query); return res > 0; } public bool UpdateBPEmployee(string TenBP, string MaBP) { string query = string.Format("UPDATE dbo.BoPhanNhanVien" + "SET TenBP = N'{0}'" + " WHERE MaBP = N'{1}'", TenBP, MaBP); int result = DataProvider.Instance.ExecuteNonQuery(query); return result > 0; } public bool DeleteBPEmployee(string MaBP) { string query = string.Format("Delete BoPhanNhanVien where MaBP = N'{0}'", MaBP); int result = DataProvider.Instance.ExecuteNonQuery(query); return result > 0; } } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace CustomXamarinControls { public class PageViewContainer : View { public PageViewContainer() { } public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(Page), typeof(PageViewContainer), null); public Page Content { get { return (Page)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } } public static class ViewExtensions { /// <summary> /// Gets the page to which an element belongs /// </summary> /// <returns>The page.</returns> /// <param name="element">Element.</param> public static Page GetParentPage(this VisualElement element) { if (element != null) { var parent = element.Parent; while (parent != null) { if (parent is Page) { return parent as Page; } parent = parent.Parent; } } return null; } } }
using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System.IO; using System.Threading.Tasks; namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Common.CsvHelper.Service { public class BlobStorageService : IBlobStorageService { public async Task UploadFileAsync(string storageConnectionString, string containerName, string filePath, Stream stream) { var blobReference = await GetBlockBlobReference(storageConnectionString, containerName, filePath); await blobReference.UploadFromStreamAsync(stream); } public async Task UploadFromByteArrayAsync(string storageConnectionString, string containerName, string filePath, byte[] data) { var blobReference = await GetBlockBlobReference(storageConnectionString, containerName, filePath); await blobReference.UploadFromByteArrayAsync(data, 0, data.Length); } public async Task<Stream> DownloadFileAsync(string storageConnectionString, string containerName, string filePath) { var blobReference = await GetBlockBlobReference(storageConnectionString, containerName, filePath); if (await blobReference.ExistsAsync()) { var ms = new MemoryStream(); await blobReference.DownloadToStreamAsync(ms); return ms; } else { return null; } } public async Task<bool> MoveFileAsync(string storageConnectionString, string containerName, string sourceFilePath, string destinationFilePath) { var sourceBlobReference = await GetBlockBlobReference(storageConnectionString, containerName, sourceFilePath); var destinationBlobReference = await GetBlockBlobReference(storageConnectionString, containerName, destinationFilePath); await destinationBlobReference.StartCopyAsync(sourceBlobReference); return await sourceBlobReference.DeleteIfExistsAsync(); } private async Task<CloudBlockBlob> GetBlockBlobReference(string storageConnectionString, string containerName, string fileName) { var blobContainer = await GetContainerAsync(containerName, storageConnectionString); return blobContainer.GetBlockBlobReference(fileName); } private async Task<CloudBlobContainer> GetContainerAsync(string containerName, string storageConnectionString) { var storageAccount = CloudStorageAccount.Parse(storageConnectionString); var blobContainerReference = storageAccount.CreateCloudBlobClient().GetContainerReference(containerName); await blobContainerReference.CreateIfNotExistsAsync(); return blobContainerReference; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace SmartLinkCalculator { /// <summary> /// Interaction logic for DeviceButtonAsAdapter.xaml /// </summary> public partial class DeviceButtonAsAdapter : Button,IDeviveButton { public int DevicePower { set; get; } public string Type { set; get; } public DeviceButtonAsAdapter() { InitializeComponent(); } public DeviceButtonAsAdapter Clone() { DeviceButtonAsAdapter adp = new DeviceButtonAsAdapter(); adp.Code.Content = this.Code.Content; adp.Tag1.Content = this.Tag1.Content; adp.Tag2.Content = this.Tag2.Content; adp.Tag3.Content = this.Tag3.Content; adp.Tag4.Content = this.Tag4.Content; adp.Tag5.Content = this.Tag5.Content; adp.DevicePower = this.DevicePower; adp.Power.Content = this.Power.Content; return adp; } } }
//============================================================================== // Copyright (c) 2012-2020 Fiats Inc. All rights reserved. // https://www.fiats.asia/ // namespace Financial.Extensions.Trading { public enum OrderType { Unspecified, // Simple order types LimitPrice, MarketPrice, // Conditioned order types Stop, StopLimit, TrailingStop, // Structured StopAndReverse, // Combined order types IFD, OCO, IFO, IFDOCO = IFO, OSO, } public static class OrderTypeExtension { public static bool IsSimpleOrder(this OrderType orderType) { switch (orderType) { case OrderType.LimitPrice: case OrderType.MarketPrice: return true; default: return false; } } public static bool IsCombinedOrder(this OrderType orderType) { switch (orderType) { case OrderType.IFD: case OrderType.OCO: case OrderType.IFO: return true; default: return false; } } } public enum OrderState { New, PartiallyFilled, Filled, Canceled, Rejected, // 注文を送信して、サイズ不正などで失敗した場合、IFDなどで後続注文が失敗した場合など Expired, } public enum OrderTransactionState { /// <summary> /// Unknown state. Usualy means uninitialized only instanciated. /// </summary> Uknown, /// <summary> /// Order created with initial parameters. /// </summary> Created, /// <summary> /// While order is sending. Usually message is sending via communication line includes which is retrying. /// </summary> Sending, /// <summary> /// Order is sent that means sending protocol returns success. /// </summary> Sent, /// <summary> /// After order was sent that confirmed by market status /// </summary> Confirmed, /// <summary> /// Failed to send order. Usually retried out to send. /// </summary> OrderFailed, /// <summary> /// Order was sent but rejected message received. /// </summary> OrderRejected, Canceling, Canceled, CancelFailed, CancelRejected, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StatueManager : MonoBehaviour { public List<GameObject> statues = new List<GameObject>(); public void add(GameObject statue) { statues.Add(statue); } public void Remove(Vector3 point) { foreach(GameObject statue in statues) { if(statue.transform.position.Equals(point)) { statues.Remove(statue); return; } } } }
using System.Web.Mvc; using com.Sconit.Web.Util; /// <summary> ///MainController 的摘要说明 /// </summary> namespace com.Sconit.Web.Controllers { [SconitAuthorize] public class MainController : WebAppBaseController { public MainController() { } public ActionResult Default() { return View(); } public ActionResult Top() { ViewBag.IsShowImage = true; return View(); } public ActionResult Nav() { ViewBag.UserCode = this.CurrentUser.CodeDescription; return PartialView(base.GetAuthrizedMenuTree()); } public ActionResult Switch() { return View(); } } }
using System; using DefaultEcs; using DefaultEcs.System; using RealisticBleeding.Components; using UnityEngine; namespace RealisticBleeding.Systems { public class FallingBloodDropRenderingSystem : AEntitySetSystem<float> { private readonly Mesh _mesh; private readonly Material _material; public FallingBloodDropRenderingSystem(EntitySet set, Mesh mesh, Material material) : base(set) { _mesh = mesh; _material = material; } protected override void Update(float state, ReadOnlySpan<Entity> entities) { foreach (var entity in entities) { ref var bloodDrop = ref entity.Get<BloodDrop>(); var magnitude = bloodDrop.Velocity.magnitude; var size = Mathf.Lerp(1, 3.5f, Mathf.InverseLerp(0, 4, magnitude)); var rotation = magnitude > 0.01f ? Quaternion.LookRotation(bloodDrop.Velocity.normalized) : Quaternion.identity; var matrix = Matrix4x4.TRS(bloodDrop.Position, rotation, new Vector3(1, 1, size) * 0.007f); Graphics.DrawMesh(_mesh, matrix, _material, 0); } } } }
using Cs_Notas.Aplicacao.Interfaces; using Cs_Notas.Dominio.Entities; using Cs_Notas.Dominio.Interfaces.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Aplicacao.ServicosApp { public class AppServicoProcuracaoEscritura: AppServicoBase<ProcuracaoEscritura>, IAppServicoProcuracaoEscritura { private readonly IServicoProcuracaoEscritura _servicoProcuracaoEscritura; public AppServicoProcuracaoEscritura(IServicoProcuracaoEscritura servicoProcuracaoEscritura) : base(servicoProcuracaoEscritura) { _servicoProcuracaoEscritura = servicoProcuracaoEscritura; } public List<ProcuracaoEscritura> ObterProcuracoesPorIdAto(int idAto) { return _servicoProcuracaoEscritura.ObterProcuracoesPorIdAto(idAto); } public ProcuracaoEscritura ObterUmObjetoProcuracao(DateTime data, string serventia, string livro, string folhas, string ato, string outorgantes, string outorgados, string selo, string aleatorio, bool rbsim, bool rbnao, out string mensagem) { ProcuracaoEscritura procuracao = new ProcuracaoEscritura(); procuracao.Data = data; mensagem = "objeto ok"; if (serventia.Length > 150) procuracao.Serventia = serventia.Substring(0, 149).Trim(); else procuracao.Serventia = serventia.Trim(); if (livro.Length > 20) procuracao.Livro = livro.Substring(0, 19).Trim(); else procuracao.Livro = livro.Trim(); if (folhas.Length > 10) procuracao.Folhas = folhas.Substring(0, 9).Trim(); else procuracao.Folhas = folhas.Trim(); if (ato.Length > 10) procuracao.Ato = ato.Substring(0, 9).Trim(); else procuracao.Ato = ato.Trim(); if (selo.Length > 9) procuracao.Selo = selo.Substring(0, 9).Trim(); else procuracao.Selo = selo.Trim(); if (aleatorio.Length > 3) procuracao.Aleatorio = aleatorio.Substring(0, 2).Trim(); else procuracao.Aleatorio = aleatorio.Trim(); if (outorgantes.Length > 600) procuracao.Outorgantes = outorgantes.Substring(0, 599).Trim(); else procuracao.Outorgantes = outorgantes.Trim(); if (outorgados.Length > 600) procuracao.Outorgados = outorgados.Substring(0, 599).Trim(); else procuracao.Outorgados = outorgados.Trim(); if (rbsim == true) procuracao.Lavrado = "S"; else procuracao.Lavrado = "N"; if (procuracao.Data == null || procuracao.Serventia == "" || procuracao.Livro == "" || procuracao.Folhas == "" || procuracao.Ato == "" || procuracao.Outorgantes == "" || procuracao.Outorgados == "") { mensagem = "É necessário preencher o(s) seguinte(s) campo(s): \n\n"; if (procuracao.Data == new DateTime()) mensagem = mensagem + "- Data \n"; if (procuracao.Serventia == "") mensagem = mensagem + "- Serventia \n"; if (procuracao.Livro == "") mensagem = mensagem + "- Livro \n"; if (procuracao.Folhas == "") mensagem = mensagem + "- Folhas \n"; if (procuracao.Ato == "") mensagem = mensagem + "- Ato \n"; if (procuracao.Outorgantes == "") mensagem = mensagem + "- Outorgantes \n"; if (procuracao.Outorgados == "") mensagem = mensagem + "- Outorgados \n"; } else mensagem = "ok"; return procuracao; } } }
using Business.Abstract; using Microsoft.AspNetCore.Mvc; namespace WebAPI.Controllers { [Route("api/[controller]")] [ApiController] public class BrandsController : ControllerBase { readonly IBrandService _brandService; public BrandsController(IBrandService brandService) { _brandService = brandService; } [HttpGet("getall")] public IActionResult GetAll() { var result = _brandService.GetlAll(); if (result.Success) { return Ok(result.Data); } return BadRequest(result.Message); } [HttpGet("getbyid")] public IActionResult GetById(int id) { var result = _brandService.GetById(id); if (result.Success) { return Ok(result.Data); } return BadRequest(result.Message); } } }
using BeatmapDownloader.Abstract.Services.UI; using EmberKernel.Services.UI.Mvvm.ViewComponent; using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace BeatmapDownloader.Abstract.Services.DownloadProvider { #pragma warning disable IDE1006 // Naming Styles class BloodcatBeatmap { public string id { get; set; } } class BloodcatBeatmapSet { public string id { get; set; } public List<BloodcatBeatmap> beatmaps { get; set; } } #pragma warning restore IDE1006 // Naming Styles [DownloadProviderList(Name = "Bloodcat")] [ViewComponentNamespace("MultiplayerDownloader.IDownloadProvier")] public class BloodcatDownloadProvider : HttpDownloadProvider { public override ValueTask<string> GetBeatmapSetDownloadUrl(int beatmapSetId, bool noVideo = true) { if (noVideo) { var bloodcatCookie = $"DLOPT={JsonSerializer.Serialize(new { bg = false, video = noVideo, skin = false, cdn = false })}"; base.HttpUtils.Downloader.Headers.Add(HttpRequestHeader.Cookie, bloodcatCookie); } return new ValueTask<string>($"https://bloodcat.com/osu/s/{beatmapSetId}"); } public override async ValueTask<int?> GetSetId(int beatmapId) { var request = (await HttpUtils.Requestor .GetAsync($"https://bloodcat.com/osu/?mod=json&c=b&q={beatmapId}", CancellationSource.Token)) .EnsureSuccessStatusCode(); using var stream = await request.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync<List<BloodcatBeatmapSet>>(stream, cancellationToken: CancellationSource.Token); if (result.Count == 0) { return null; } return int.Parse(result[0].id); } } }
using Efa.Application.Interfaces; using Efa.Application.ViewModels; using System; using System.Net; using System.Net.Http; using System.Web.Http; using Efa.Services.WebApi.Filters; namespace Efa.Services.WebApi.Controllers { [RoutePrefix("api")] public class ProfessorController : ApiController { private readonly IProfessorAppService _professorApp; private readonly ITurmaAppService _turmaApp; public ProfessorController(IProfessorAppService professorApp, ITurmaAppService turmaApp) { _professorApp = professorApp; _turmaApp = turmaApp; } [HttpGet] [GzipCompression] [Route("professores")] public HttpResponseMessage GetProfessores(int skip = 0, int take = 5) { var result = _professorApp.GetAll(skip, take); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] [Route("professores")] public HttpResponseMessage PostProfessor(ProfessorViewModel professor) { if (ModelState.IsValid) { if (professor.CPF == "") professor.CPF = null; var result = _professorApp.Add(professor); if (!result.IsValid) { foreach (var validationAppError in result.Erros) { ModelState.AddModelError(string.Empty, validationAppError.Message); } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } return Request.CreateResponse(HttpStatusCode.Created, professor); } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } [HttpPut] [Route("professores")] public HttpResponseMessage Put(ProfessorViewModel professor) { if (ModelState.IsValid) { var result = _professorApp.Editar(professor); if (!result.IsValid) { foreach (var validationAppError in result.Erros) { ModelState.AddModelError(string.Empty, validationAppError.Message); } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } return Request.CreateResponse(HttpStatusCode.OK, professor); } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } [HttpDelete] [Route("professor/{id}")] public HttpResponseMessage Delete(Guid id) { var professor = _professorApp.GetById(id); if (professor == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } //Set null ProfessorId em turmas _turmaApp.DesvinculaProfessor(id); _professorApp.Remove(professor); return Request.CreateResponse(HttpStatusCode.OK, professor); } protected override void Dispose(bool disposing) { _professorApp.Dispose(); base.Dispose(disposing); } } }
using System; using System.Linq; namespace Exercise_2 { class Program { static void Main(string[] args) { var input = Console.ReadLine().Split(' ').ToList(); char[] first = input[0].ToCharArray(); char[] second = input[1].ToCharArray(); int sum = 0; int multiplicationIndex = Math.Min(first.Length, second.Length); for (int i = 0; i < multiplicationIndex; i++) { sum += first[i] * second[i]; } if (first.Length>second.Length) { for (int i = multiplicationIndex; i < first.Length;i++) { sum += first[i]; } } else { for (int i = multiplicationIndex; i < second.Length; i++) { sum += second[i]; } } Console.WriteLine(sum); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alps.Domain.ProductMgr; using Alps.Domain.Common; namespace Alps.Domain.Service { public class ProductMgrService { private AlpsContext db = null; public ProductMgrService(AlpsContext db) { this.db = db; } public void SubmitVoucher(WarehouseVoucher voucher, string submitter) { voucher.Submit(submitter); StockService stockService = new StockService(db); stockService.UpdateStock(voucher); } public void UpdateWarehouseVoucher(Guid id, WarehouseVoucher warehouseVoucher) { var exitingWarehouseVoucher = db.WarehouseVouchers.Find(id); db.Entry(exitingWarehouseVoucher).CurrentValues.SetValues(warehouseVoucher); WarehouseVoucherItem updatedItem = null; foreach (WarehouseVoucherItem item in exitingWarehouseVoucher.Items.ToList()) { updatedItem = warehouseVoucher.Items.FirstOrDefault(p => p.ID == item.ID); if (updatedItem == null) { exitingWarehouseVoucher.Items.Remove(item); } else { db.Entry(item).CurrentValues.SetValues(updatedItem); } } foreach (WarehouseVoucherItem item in warehouseVoucher.Items) { item.WarehouseVoucherID = exitingWarehouseVoucher.ID; exitingWarehouseVoucher.Items.Add(item); } } //public ProductDetail GetProductDetailFromProductSKU(Guid skuID) //{ // var query = from p in db.Products // from sku in db.ProductSKUs // where p.ID == sku.ProductID && sku.ID == skuID // select p; // Product product = query.FirstOrDefault(); // if (product != null) // return product.GetProductDetail(); // else // throw new DomainException("无此SKUID"); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SimuladorApp { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ResultadoPage : ContentPage { public Resultado result; public ResultadoPage(Resultado r) { InitializeComponent(); this.result = r; this.Title = r.OrigenDestino + ". Línea: " + r.Linea; TablaRellenarDatos(); } public void TablaRellenarDatos() { this.lbl10.Text = result.Origen + "-" + result.PuertoOrigen; this.lbl20.Text = result.CosteOrigenPuerto.ToString("0"); this.lbl21.Text = result.TiempoOrigenPuerto.ToString("0.00"); this.lbl22.Text = result.DistanciaOrigenPuerto.ToString("0"); this.lbl23.Text = result.CostesExternosOrigenPuerto.ToString("0"); this.lbl24.Text = result.CosteEmisionCO2OrigenPuerto.ToString("0"); this.lbl30.Text = result.PuertoOrigen + "-" + result.PuertoDestino; this.lbl40.Text = result.CostePuertoPuerto.ToString("0"); this.lbl41.Text = result.TiempoPuertoPuerto.ToString("0.00"); this.lbl42.Text = result.DistanciaPuertoPuerto.ToString("0"); this.lbl43.Text = result.CostesExternosPuertoPuerto.ToString("0"); this.lbl44.Text = result.CosteEmisionCO2PuertoPuerto.ToString("0"); this.lbl50.Text = result.PuertoDestino + "-" + result.Destino; this.lbl60.Text = result.CostePuertoDestino.ToString("0"); this.lbl61.Text = result.TiempoPuertoDestino.ToString("0.00"); this.lbl62.Text = result.DistanciaPuertoDestino.ToString("0"); this.lbl63.Text = result.CostesExternosPuertoDestino.ToString("0"); this.lbl64.Text = result.CosteEmisionCO2PuertoDestino.ToString("0"); this.lbl70.Text = "Total: " + result.OrigenDestino + " Línea: " + result.Linea; this.lbl80.Text = result.CosteTotal.ToString("0"); this.lbl81.Text = result.TiempoTotal.ToString("0.00"); this.lbl82.Text = result.DistanciaTotal.ToString("0"); this.lbl83.Text = result.CostesExternosTotal.ToString("0"); this.lbl84.Text = result.CosteEmisionCO2Total.ToString("0"); this.lbl90.Text = result.FleteMensaje; } } }
using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using OpenCvSharp; namespace GestureRecognition { internal class Program { private static void Main(string[] args) { var i = 0; var acuteAngle = 0; var video = new VideoCapture(); video.Open(0); if (!video.IsOpened()) { Console.WriteLine("camera open failed."); return; } Console.WriteLine("camera open success."); var camera = new Mat(); var element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3)); var hull = new List<Point[]>(); var hullI = new List<int>(); while (true) { i++; video.Read(camera); if (camera.Empty()) break; //Cv2.CvtColor(camera, grayMat, ColorConversionCodes.RGB2BGR); //Cv2.Canny(grayMat, camera, 100, 200); Cv2.Flip(camera, camera, FlipMode.Y); var originWindow = new Window("Origin", camera, WindowFlags.AutoSize); var skin = SkinDetect(camera); // skin layer process //Cv2.Erode(skin, skin, element, iterations: 2); Cv2.MorphologyEx(skin, skin, MorphTypes.Open, element,iterations:6); //Cv2.Dilate(skin, skin, element, iterations: 2); Cv2.MorphologyEx(skin, skin, MorphTypes.Close, element,iterations:6); //Cv2.Dilate(skin, skin, element, iterations: 2); Cv2.MorphologyEx(skin, skin, MorphTypes.Close, element,iterations:6); //Cv2.Erode(skin, skin, element, iterations: 2); Cv2.MorphologyEx(skin, skin, MorphTypes.Open, element,iterations:6); var contours = FindContours(skin); Cv2.CvtColor(skin, skin, ColorConversionCodes.GRAY2BGR); Cv2.BitwiseAnd(camera, skin, camera); foreach (var t in contours) { hull.Add(Cv2.ConvexHull(t)); OutputArray outArr = OutputArray.Create(hullI); Cv2.ConvexHull(InputArray.Create(t), outArr, true, false); var defects = Cv2.ConvexityDefects(t, hullI); for (var k = 0; k < defects.Length; k++) { var start = t[defects[k].Item0]; var end = t[defects[k].Item1]; var far = t[defects[k].Item2]; var depth = defects[k].Item3 / 256; if (depth is <= 40 or >= 150) continue; Cv2.Line(camera, start, far, Scalar.Green, 2); Cv2.Line(camera, end, far, Scalar.Green, 2); Cv2.Circle(camera, start, 6, Scalar.Red); Cv2.Circle(camera, end, 6, Scalar.Blue); Cv2.Circle(camera, far, 6, Scalar.Green); var vectorBuild = Vector<double>.Build; var vectorA = vectorBuild.DenseOfArray(new[] {(double) far.X - start.X, (double) far.Y - start.Y}); var vectorB = vectorBuild.DenseOfArray(new[] {(double) far.X - end.X, (double) far.Y - end.Y}); var ds = vectorA * vectorB; if (ds / (vectorA.L1Norm() * vectorB.L1Norm()) > 0) acuteAngle++; } if (acuteAngle < 1 && Cv2.ArcLength(t, false) > 600) Cv2.PutText(camera, "Rock", t[0], HersheyFonts.HersheyPlain, 2, Scalar.Red); else if (acuteAngle == 1) Cv2.PutText(camera, "Scissors", t[0], HersheyFonts.HersheyPlain, 2, Scalar.Red); else if (acuteAngle >= 3) Cv2.PutText(camera, "Paper", t[0], HersheyFonts.HersheyPlain, 2, Scalar.Red); else if (Cv2.ArcLength(t, false) > 1000) Cv2.PutText(camera, "Unknown", t[0], HersheyFonts.HersheyPlain, 2, Scalar.Red); acuteAngle = 0; } Cv2.DrawContours(camera, hull, -1, Scalar.Red); Cv2.DrawContours(camera, contours, -1, Scalar.Blue); var cameraWindow = new Window("Final", camera, WindowFlags.AutoSize); var backgroundWindow = new Window("Skin", skin, WindowFlags.AutoSize); Cv2.WaitKey(10); if (i >= 20) { i = 0; GC.Collect(); } hull.Clear(); } camera.Release(); Cv2.DestroyAllWindows(); } public static Mat SkinDetect(Mat input) { var output = new Mat(); Cv2.CvtColor(input, output, ColorConversionCodes.BGR2YCrCb); Cv2.Split(output, out var frames); var crFrame = frames[1]; Cv2.GaussianBlur(crFrame, crFrame, new Size(5, 5), 0); Cv2.Threshold(crFrame, crFrame, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary); return crFrame; } public static Point[][] FindContours(Mat input) { Cv2.FindContours(input, out var contours, out var hierarchyIndices, RetrievalModes.External, ContourApproximationModes.ApproxSimple); return contours; } } }
using System.Collections.Generic; namespace CoherentSolutions.Extensions.Configuration.AnyWhere { public interface IAnyWhereConfigurationEnvironmentSource { string Get( string name); IEnumerable<KeyValuePair<string, string>> GetValues(); } }
using System; using System.Linq; using UBaseline.Core.Node; using Uintra.Core.Member.Entities; using Uintra.Core.Member.Services; using Uintra.Features.Events.Entities; using Uintra.Features.Events.Models; using Uintra.Features.Links; using Uintra.Infrastructure.Extensions; namespace Uintra.Features.Events.Converters { public class ComingEventsPanelViewModelConverter : INodeViewModelConverter<ComingEventsPanelModel, ComingEventsPanelViewModel> { private readonly IIntranetMemberService<IntranetMember> _intranetMemberService; private readonly IEventsService<Event> _eventsService; private readonly IActivityLinkService _activityLinkService; public ComingEventsPanelViewModelConverter( IIntranetMemberService<IntranetMember> intranetMemberService, IEventsService<Event> eventsService, IActivityLinkService activityLinkService) { _intranetMemberService = intranetMemberService; _eventsService = eventsService; _activityLinkService = activityLinkService; } public void Map(ComingEventsPanelModel node, ComingEventsPanelViewModel viewModel) { var events = _eventsService.GetComingEvents(DateTime.UtcNow).ToArray(); var ownersDictionary = _intranetMemberService.GetMany(events.Select(e => e.OwnerId)).ToDictionary(c => c.Id); var comingEvents = events .Take(node.EventsAmount) .Select(@event => { var eventViewModel = @event.Map<ComingEventViewModel>(); eventViewModel.Owner = ownersDictionary[@event.OwnerId].ToViewModel(); eventViewModel.Links = _activityLinkService.GetLinks(@event.Id); return eventViewModel; }) .ToList(); viewModel.Events = comingEvents; } } }
using LineOperator2.Models; using LineOperator2.ViewModels; using System; using System.Collections.Generic; using System.ComponentModel; using Xamarin.Forms; using LineOperator2.Services; using System.Threading.Tasks; namespace LineOperator2.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class MenuPage : ContentPage { MainPage RootPage { get => Application.Current.MainPage as MainPage; } List<JobViewModel> menuItems = new List<JobViewModel>(); public MenuPage() { InitializeComponent(); menuItems = Database.GetListOfJobViews(); ListViewMenu.ItemsSource = menuItems; ListViewMenu.SelectedItem = menuItems[0]; ListViewMenu.ItemSelected += async (sender, e) => { if (e.SelectedItem == null) return; var id = ((JobViewModel)e.SelectedItem).Line; // await RootPage.NavigateFromMenu(id); }; } async private void OnPackagingClicked(object sender, EventArgs e) { await Navigation.PushModalAsync(new TotalPackagingPage()); if (Device.RuntimePlatform == Device.Android) await Task.Delay(100); } } }
using System; namespace Zadanie_1 { class Program { static void Wybieranie(int[] L) { for (int i = L.Length - 1; i >= 0; i--) { // szukamy największego elementu w L dla (i, N - 1) int k = i; for (int j = i - 1; j >= 0; j--) { if (L[k] < L[j]) k = j; } // zamieniamy z go z elementem i-tym int t = L[k]; L[k] = L[i]; L[i] = t; } Wypisz(L); } static void Wypisz(int[] L) { int i; Console.Write("\n"); for (i = 0; i < L.Length - 1; i++) { Console.Write(L[i] + " "); } Console.Write(L[i] + "\n\n"); } static void Main(string[] args) { int[] losowa = { 2, 452, 3, 6, 17, 76, 2, 75, 22, 42, 65, 67, 89 }; int[] rosnąca = { 1, 3, 5, 6, 8, 23, 43, 66, 346, 532, 656, 2346 }; int[] malejąca = { 9099, 2983, 3212, 132, 112, 67, 45, 35, 32, 2 }; int[] stała = { 232, 232, 232, 232, 232, 232, 232, 232, 232, 232 }; Wypisz(losowa); Wybieranie(losowa); Wypisz(rosnąca); Wybieranie(rosnąca); Wypisz(malejąca); Wybieranie(malejąca); Wypisz(stała); Wybieranie(stała); Console.ReadKey(); } } }
namespace _10._UnicodeCharacters { using System; using System.Text; public class Startup { public static void Main() { string text = Console.ReadLine(); StringBuilder sb = new StringBuilder(); foreach (char symbol in text) { string unicode = "\\u" + ((int) symbol).ToString("x").PadLeft(4, '0'); sb.Append(unicode); } Console.WriteLine(sb.ToString()); } } }
namespace ArrangeIntegers { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Startup { public static void Main(string[] args) { Execute(); } public static void Execute() { var args = Console.ReadLine().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); var nums = new List<KeyValuePair<int, string>>(); for (int i = 0; i < args.Length; i++) { var builder = new StringBuilder(); for (int j = 0; j < args[i].Length; j++) { switch (args[i][j]) { case '0': builder.Append("zero-"); break; case '1': builder.Append("one-"); break; case '2': builder.Append("two-"); break; case '3': builder.Append("three-"); break; case '4': builder.Append("four-"); break; case '5': builder.Append("five-"); break; case '6': builder.Append("six-"); break; case '7': builder.Append("seven-"); break; case '8': builder.Append("eight-"); break; case '9': builder.Append("nine-"); break; default: break; } } if (builder.Length > 0) { builder = builder.Remove(builder.Length - 1, 1); } nums.Add(new KeyValuePair<int, string>(int.Parse(args[i]), builder.ToString())); } nums.Sort(new ArrayIntegerComparer()); Console.WriteLine(string.Join(", ", nums.Select(x => x.Key))); } } public class ArrayIntegerComparer : IComparer<KeyValuePair<int, string>> { public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y) { if (x.Value.StartsWith(y.Value) || y.Value.StartsWith(x.Value)) { return x.Key.CompareTo(y.Key); } return x.Value.CompareTo(y.Value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Robotiv2 { class Program { public static void Menu() { System.Console.WriteLine("\nPuteti efectua urmatoarele actiuni:"); System.Console.WriteLine("Apasati tasta 1 pentru a pune robotii in miscare"); System.Console.WriteLine("Apasati tasta 2 pentru a spune robotilor sa se pregateasca "); System.Console.WriteLine("Apasati tasta 3 pentru a spune robotilor sa munceasca "); System.Console.WriteLine("Apasati tasta 0 pentru a iesi.\n "); } static void Main(string[] args) { bool exit = false; string alege = "0"; LandRobot L1 = new LandRobot("Gigel", "LandRobot","Worker"); FlyingRobot F1 = new FlyingRobot("Musca", "FlyingRobot", "Warrior"); UnderGroundRobot U1 = new UnderGroundRobot("Cartita", "UnderGroundRobot", "Worker"); WaterRobot W1 = new WaterRobot("Sharky", "WaterRobot", "Worker"); Tool t = new Tool(); t.Name = "CyberLopata"; Tool t1 = new Tool(); t1.Name = "CyberFurca"; Tool t2 = new Tool(); t2.Name = "CyberUndita"; Tool t3 = new Tool(); W1.Items = t3; Weapon w = new Weapon(); w.Name = "LaserSword"; var listOfRobots = new List<Robot>() { L1, F1, U1, W1 }; while (!exit) { Menu(); alege = Console.ReadLine(); switch (alege) { case "1": foreach(var robot in listOfRobots) { robot.Movement(); } break; case "2": foreach(var robot in listOfRobots) { if (robot.Type == "UnderGroundRobot") robot.Equip(t, w); else if (robot.Type == "WaterRobot") robot.Equip(t2, w); else robot.Equip(t1, w); } break; case "3": foreach(var robot in listOfRobots) { robot.Work(); } break; case "0": exit = true; break; default: Console.WriteLine("Error"); break; } } Console.ReadKey(); } } }
using System.Collections.Generic; using System.Web.Http; using ILogging; using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tickets; using ServiceDeskSVC.Managers; namespace ServiceDeskSVC.Controllers.API { /// <summary> /// /// </summary> public class TicketStatusController:ApiController { private readonly IHelpDeskTicketStatusManager _helpDeskTicketStatusManager; private readonly ILogger _logger; public TicketStatusController(IHelpDeskTicketStatusManager helpDeskTicketStatusManager, ILogger logger) { _helpDeskTicketStatusManager = helpDeskTicketStatusManager; _logger = logger; } /// <summary> /// Gets this instance. /// </summary> /// <returns></returns> public IEnumerable<HelpDesk_TicketStatus_vm> Get() { _logger.Info("Getting all ticket statuses. "); return _helpDeskTicketStatusManager.GetAllStatuses(); } /// <summary> /// Posts the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public int Post([FromBody]HelpDesk_TicketStatus_vm value) { _logger.Info("Adding a new ticket status. "); return _helpDeskTicketStatusManager.CreateStatus(value); } /// <summary> /// Puts the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="value">The value.</param> /// <returns></returns> public int Put(int id, [FromBody]HelpDesk_TicketStatus_vm value) { _logger.Info("Editing the ticket status with id" + id); return _helpDeskTicketStatusManager.EditStatusById(id, value); } /// <summary> /// Deletes the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public bool Delete(int id) { _logger.Info("Deleting the ticket status with id" + id); return _helpDeskTicketStatusManager.DeleteStatusById(id); } } }
using Manor.MsExcel.Contracts; using Techical.MsExcel.EpPlus; namespace Techical.MsExcel { public class MsExcelWrapperFactory { public static IExcel GetDefaultInstance() { return new EpPlusExcelWrapper(); } public static IExcel GetInstance(EExcelImplementation implementation) { IExcel excelWrapper; switch (implementation) { case EExcelImplementation.EPPlus: excelWrapper = new EpPlusExcelWrapper(); break; default: excelWrapper = null; break; } return excelWrapper; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class KeyHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler { private Key key; public void setKeyValue(Key key) { this.key = key; } public string getKeyValueShift() { return key.ShiftkeyValue; } public string getKeyValueNormal() { return key.KeyValue; } public void OnPointerClick(PointerEventData eventData) { Debug.Log("Klick"); } public void OnPointerExit(PointerEventData eventData) { Image img = this.gameObject.GetComponent<Image>(); img.color = new Color32(30, 40, 55,255); } public void OnPointerEnter(PointerEventData eventData) { Image img = this.gameObject.GetComponent<Image>(); img.color = Color.grey; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using KartObjects; using KartLib; namespace KartSystem { public partial class SellerEditor : XBaseDictionaryEditor { public SellerEditor() { InitializeComponent(); InitView(); } Seller _editableSeller; public SellerEditor(Seller seller) { InitializeComponent(); _editableSeller = seller; storeBindingSource.DataSource = KartLib.KartDataDictionary.sStores; InitView(); } public override void InitView() { base.InitView(); teName.Text=_editableSeller.Name; teCode.Text = _editableSeller.Code; storeBindingSource.DataSource = KartLib.KartDataDictionary.sStores; leStore.EditValue=_editableSeller.IdStore; } protected override bool CheckForValidation() { NotValidDataMessage = ""; if (string.IsNullOrWhiteSpace(teName.Text)) { NotValidDataMessage += "Нет ФИО продавца."; return false; } if (leStore.EditValue == null) { NotValidDataMessage += "Не выбрано подразделение.\n"; return false; } return true; } protected override void SaveData() { _editableSeller.Name = teName.Text; _editableSeller.Code = teCode.Text; if (leStore.EditValue != null) _editableSeller.IdStore = (long)leStore.EditValue; else _editableSeller.IdStore = null; Saver.SaveToDb<Seller>(_editableSeller); } private void leStore_Properties_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete) { leStore.EditValue = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ExpressionTree { // helper for monads of having an enriched type of Func<A,B> static class FuncTwoArgsGlue { // binder for function composition // not used in the current workflow, but I preferred to code it as an inspiration for SelectMany public static Func<T, U> Bind<T, U>(this Func<T, U> first, Func<U, Func<T, U>> second) { return x => second(first(x))(x); } // permits expressiveness when composing Plus and Times public static Func<T, V> SelectMany<T, U, V>(this Func<T, U> first, Func<U, Func<T, U>> second, Func<U, U, V> s) { return x => s(first(x), second(first(x))(x)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Command { abstract class Tarea { protected Pieza miPieza; public Tarea(Pieza p){ miPieza = p; } public abstract void Ejecutar(); } }
using System.ComponentModel; namespace VnStyle.Services.Data.Enum { public enum EGender { [Description("Male")] Male = 1, [Description("Female")] Female = 2, [Description("Other")] Other = 100 } }