text
stringlengths
13
6.01M
namespace CubeProperties { using System; public class StartUp { public static void Main() { double sideCube = double.Parse(Console.ReadLine()); string parameter = Console.ReadLine(); switch (parameter) { case "face": GetFaceDiagonalCube(sideCube); break; case "space": GetSpaceDiagonalCube(sideCube); break; case "volume": GetVolumeCube(sideCube); break; case "area": GetAreaCube(sideCube); break; } } public static void GetFaceDiagonalCube(double sideCube) { double faceDiagonal = Math.Sqrt(2 * sideCube * sideCube); Console.WriteLine($"{faceDiagonal:f2}"); } public static void GetSpaceDiagonalCube(double sideCube) { double spaceDiagonal = Math.Sqrt(3 * sideCube * sideCube); Console.WriteLine($"{spaceDiagonal:f2}"); } public static void GetVolumeCube(double sideCube) { double volumeCube = Math.Pow(sideCube, 3); Console.WriteLine($"{volumeCube:f2}"); } public static void GetAreaCube(double sideCube) { double areaCube = (6 * sideCube * sideCube); Console.WriteLine($"{areaCube:f2}"); } } }
using iSukces.Code.Interfaces; using Xunit; namespace iSukces.Code.Tests { public class CsTests { [Fact] public void T01_ShouldCsCite() { const string quote = "\""; const string backslash = "\\"; const string specialR = "\r"; Assert.Equal(1, specialR.Length); Assert.Equal(quote + backslash + "r" + quote, specialR.CsEncode()); var specialN = "\n"; Assert.Equal(1, specialN.Length); Assert.Equal(quote + backslash + "n" + quote, specialN.CsEncode()); var specialT = "\t"; Assert.Equal(1, specialT.Length); Assert.Equal(quote + backslash + "t" + quote, specialT.CsEncode()); } [Fact] public void T02_Should_Create_operator() { var cl = new CsClass("Src1"); cl.Kind = CsNamespaceMemberKind.Struct; cl.AddMethod("*", "Result") .WithBodyAsExpression("new Result(left.Value * right.Value)") .WithParameter("left", "Src1") .WithParameter("right", "Src2"); // odwrotny ICsCodeWriter w = new CsCodeWriter(); cl.MakeCode(w); var expected = @"public struct Src1 { public static Result operator *(Src1 left, Src2 right) { return new Result(left.Value * right.Value); } } "; Assert.Equal(expected.Trim(), w.Code.Trim()); } [Fact] public void T03_Should_Create_auto_property_with_initialisation() { var cl = new CsClass("Src1"); var p = cl.AddProperty("A", "int"); p.MakeAutoImplementIfPossible = true; //p.ConstValue = "12"; // odwrotny var w = new CsCodeWriter(); cl.MakeCode(w); var expected = @"public class Src1 { public int A { get; set; } } "; Assert.Equal(expected.Trim(), w.GetCodeTrim()); p.ConstValue = "12"; w = new CsCodeWriter(); cl.MakeCode(w); expected = @"public class Src1 { public int A { get; set; } = 12; } "; Assert.Equal(expected.Trim(), w.GetCodeTrim()); } [Fact] public void T04_Should_Create_interface() { var cl = new CsClass("ITest") { Kind = CsNamespaceMemberKind.Interface }; var m = cl.AddMethod("Count", "int") .WithBody("return 12;"); var p = cl.AddProperty("A", "int"); p.MakeAutoImplementIfPossible = true; p.OwnGetter = "return 123;"; //p.ConstValue = "12"; // odwrotny var w = new CsCodeWriter(); cl.MakeCode(w); var expected = @" public interface ITest { int Count(); int A { get; set; } }"; Assert.Equal(expected.Trim(), w.GetCodeTrim()); p.ConstValue = "12"; w = new CsCodeWriter(); cl.MakeCode(w); Assert.Equal(expected.Trim(), w.GetCodeTrim()); } [Fact] public void T05_Should_generate_compiler_directive() { var cl = new CsClass("Src1"); var p = cl.AddProperty("A", "int"); p.MakeAutoImplementIfPossible = true; cl.CompilerDirective = "DEBUG"; var w = new CsCodeWriter(); cl.MakeCode(w); var expected = @" #if DEBUG public class Src1 { public int A { get; set; } } #endif "; Assert.Equal(expected.Trim(), w.GetCodeTrim()); } [Fact] public void T06_Should_cut_namespace() { var f = new CsFile(); f.AddImportNamespace("System.Alpha"); var ns = f.GetOrCreateNamespace("Custom.Beta"); ns.AddImportNamespace("Custom.Private"); var c = ns.GetOrCreateClass("Gamma"); Assert.True(c.IsKnownNamespace("Custom.Beta")); Assert.True(c.IsKnownNamespace("System.Alpha")); Assert.True(c.IsKnownNamespace("Custom.Private")); Assert.False(c.IsKnownNamespace("Some.Unknown.Namespace")); Assert.True(ns.IsKnownNamespace("Custom.Beta")); Assert.True(ns.IsKnownNamespace("System.Alpha")); Assert.True(ns.IsKnownNamespace("Custom.Private")); Assert.False(ns.IsKnownNamespace("Some.Unknown.Namespace")); Assert.False(f.IsKnownNamespace("Custom.Beta")); Assert.True(f.IsKnownNamespace("System.Alpha")); Assert.False(f.IsKnownNamespace("Custom.Private")); Assert.False(f.IsKnownNamespace("Some.Unknown.Namespace")); var w = new CsCodeWriter(); f.MakeCode(w); const string expected = @"// ReSharper disable All using System.Alpha; namespace Custom.Beta { using Custom.Private; public class Gamma { } } "; Assert.Equal(expected.Trim(), w.Code.Trim()); } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; public static class GestorTraducciones { private static JObject traducciones = new JObject(); static GestorTraducciones() { try { //Recupera de la clase de configuracion el ultimo idioma establecido TextAsset jsonTextFile = Resources.Load<TextAsset>($"Traducciones/T{GestorConfiguracion.RecuperarUltimoIdioma()}"); traducciones = JObject.Parse(jsonTextFile.text); } catch { TextAsset jsonTextFile = Resources.Load<TextAsset>($"Traducciones/TES-ES"); traducciones = JObject.Parse(jsonTextFile.text); } } public static bool Inicializar(string idioma) { bool correcto = true; return correcto; } public static string RecuperarCambioIdioma(string nuevoIdioma) { try { TextAsset jsonTextFile = Resources.Load<TextAsset>($"Traducciones/T{nuevoIdioma}"); return JObject.Parse(jsonTextFile.text)["CambioIdioma"].ToString(); } catch { return ""; } } public static string TraducirTexto(string texto) { try { string nuevoTexto = ""; bool encontradoIni = false; string textoBusc = ""; for (int i = 0; i < texto.Length; i++) { if(texto[i] == '{') { encontradoIni = true; } else if (texto[i] == '}') { encontradoIni = false; nuevoTexto += traducciones[textoBusc].ToString(); } else if (!encontradoIni) { nuevoTexto += texto[i]; } else if(encontradoIni) { textoBusc += texto[i]; } } return nuevoTexto; } catch { return texto; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Trendyol.Case.Models { public class ListPageModel { public IList<Product>Products { get; set; } public int PageCount { get; set; } public ListPageModel() { Products = new List<Product>(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using NLog; using Simple.Wpf.Composition.Infrastructure; using Simple.Wpf.Composition.Services; using Simple.Wpf.Composition.Workspaces; namespace Simple.Wpf.Composition.Startup { public sealed class MainController : BaseController<MainViewModel> { private const int DisposeDelay = 333; private readonly CompositeDisposable _disposable; private readonly Logger _logger; private readonly IEnumerable<IWorkspaceDescriptor> _workspaceDescriptors; public MainController(MainViewModel viewModel, IMemoryService memoryService, IDiagnosticsService diagnosticsService, IEnumerable<IWorkspaceDescriptor> workspaceDescriptors) : base(viewModel) { _logger = LogManager.GetCurrentClassLogger(); _logger.Debug("Main controller starting..."); _workspaceDescriptors = workspaceDescriptors; var availableWorkspaces = _workspaceDescriptors.OrderBy(x => x.Position) .Select(x => x.Name) .ToList(); foreach (var availableWorkspace in availableWorkspaces) _logger.Debug("Available workspace - '{0}'", availableWorkspace); availableWorkspaces.Insert(0, string.Empty); ViewModel.AddAvailableWorkspaces(availableWorkspaces); _disposable = new CompositeDisposable { ViewModel.AddWorkspaceStream .Subscribe(CreateWorkspace), ViewModel.RemoveWorkspaceStream .Do(RemoveWorkspace) .Delay(TimeSpan.FromMilliseconds(DisposeDelay)) .Do(DeleteWorkspace) .Subscribe(), memoryService.MemoryInMegaBytes .DistinctUntilChanged() .Throttle(TimeSpan.FromSeconds(1)) .Subscribe(UpdateUsedMemory), diagnosticsService.PerformanceCounters(1000) .Subscribe(x => { Debug.WriteLine("PrivateWorkingSetMemory = " + decimal.Round(Convert.ToDecimal(x.PrivateWorkingSetMemory) / (1024 * 1000), 2)); Debug.WriteLine("TotalAvailableMemoryMb = " + x.TotalAvailableMemoryMb); }), diagnosticsService.LoadedAssembly .Subscribe(x => Debug.WriteLine("Assembly = " + x.FullName)) }; for (var i = 0; i < 200; i++) _logger.Debug("Log Item = " + i); } public override void Dispose() { base.Dispose(); _disposable.Dispose(); } private void CreateWorkspace(string requestedWorkspace) { _logger.Debug("Creating workspace, name - '{0}'", requestedWorkspace); var newWorkspace = _workspaceDescriptors.Single(x => x.Name == requestedWorkspace).CreateWorkspace(); var group = ViewModel.Workspaces.GroupBy(x => x.Type.FullName) .FirstOrDefault(x => x.Key == newWorkspace.Type.FullName); var title = group == null ? requestedWorkspace : string.Format("{0} ({1})", requestedWorkspace, group.Count() + 1); newWorkspace.Title = title; _logger.Debug("Workspace title - '{0}'", title); ViewModel.AddWorkspace(newWorkspace); _logger.Debug("Workspace count = {0}", ViewModel.Workspaces.Count); } private void RemoveWorkspace(Workspace workspace) { _logger.Debug("Removing workspace, title - '{0}'", workspace.Title); ViewModel.RemoveWorkspace(workspace); _logger.Debug("Workspace count = {0}", ViewModel.Workspaces.Count); } private void DeleteWorkspace(Workspace workspace) { _logger.Debug("Deleting workspace, title - '{0}'", workspace.Title); workspace.Dispose(); } private void UpdateUsedMemory(decimal usedMemory) { ViewModel.UpdateMemoryUsed(usedMemory); _logger.Debug("Used memory = {0}", ViewModel.MemoryUsed); } } }
using UnityEngine; public class Node : IHeapItem<Node> { [HideInInspector] public bool walkable; [HideInInspector] public Vector3 worldPosition; [HideInInspector] public Bounds bounds; [HideInInspector] public int gridX, gridY; [HideInInspector] public int gCost, hCost; [HideInInspector] public Node parent; int heapIndex; public Node(bool _walkable, Vector3 _worldPosition, int _gridX, int _gridY ) { walkable = _walkable; worldPosition = _worldPosition; gridX = _gridX; gridY = _gridY; } public int fCost { get { return gCost + hCost; } } public int HeapIndex { get { return heapIndex; } set { heapIndex = value; } } public int CompareTo ( Node _nodeToCompare ) { int compare = fCost.CompareTo(_nodeToCompare.fCost); if ( compare == 0 ) { compare = hCost.CompareTo(_nodeToCompare.hCost); } return -compare; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightingBook.Tests.Api.Product.Dto.TravelSearch { public class Passenger { public string Identifier { get; set; } public string PassengerIdentifier { get; set; } public string ClientId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cracking { class Tests { public static void testModulo(int lenght, int n) { n = n % lenght; Console.WriteLine( "n is {0}, length is {1}",n,lenght); } public static void testReverse() { int[] a = { 1,2,3,4}; Utils.print_r(a); Utils.Reverse(a, 0, a.Length-1); Utils.print_r(a); } public static void test1() { string explodeme = "1,2,3,4,5"; string[] pieces = explodeme.Split(','); Console.WriteLine(string.Join(":",pieces)); } public static int[] BubbleSort(int[] nums , int n) { for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (nums[i]>nums[j])//both reach the end Utils.swap(nums, i, j); } } return nums; } } }
using Log.Api.Models; using System.Collections.Generic; namespace Log.Api.Components { public interface ILogRepository { ICollection<JsonLog> RetrieveJsonLogs(long id, int limit); int WriteLog(EventLog log); int WriteLog(ICollection<JsonLog> logs); } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public enum menuState {Main, Options, Credits, Instructions} public class MainMenu : MonoBehaviour { [SerializeField] GameObject MainMenuPanel; [SerializeField] GameObject OptionPanel; [SerializeField] GameObject CreditPanel; [SerializeField] GameObject InstructionsPanel; [SerializeField] GameObject StartGameButton; [SerializeField] Slider volumeSlider; AudioManager audioManager = AudioManager.GetInstance(); menuState currentMenu = menuState.Main; void Start() { MainMenuPanel.SetActive(true); OptionPanel.SetActive(false); CreditPanel.SetActive(false); InstructionsPanel.SetActive(false); StartGameButton.SetActive(false); } public void StartClick() { MainMenuPanel.SetActive(false); InstructionsPanel.SetActive(true); currentMenu = menuState.Instructions; Invoke("ShowGameStart", 2f); } public void OptionClick() { MainMenuPanel.SetActive(false); OptionPanel.SetActive(true); currentMenu = menuState.Options; GetOptions(); } public void OptionApplyClick() { SetOptions(); MainMenuPanel.SetActive(true); OptionPanel.SetActive(false); currentMenu = menuState.Options; } public void OptionCancelClick() { MainMenuPanel.SetActive(true); OptionPanel.SetActive(false); currentMenu = menuState.Options; } public void CreditClick() { MainMenuPanel.SetActive(false); CreditPanel.SetActive(true); currentMenu = menuState.Credits; } public void CreditMenu() { MainMenuPanel.SetActive(true); CreditPanel.SetActive(false); currentMenu = menuState.Main; } public void QuitClick() { Debug.Log("Quit"); Application.Quit(); } private void ShowGameStart() { StartGameButton.SetActive(true); } public void LoadGame() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } private void SetOptions() { audioManager.SetVolume(volumeSlider.value); } private void GetOptions() { volumeSlider.value = audioManager.GetVolume(); } }
using BusVenta; using EntVenta; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Management; using DatVentas; using System.Data; namespace VentasD1002 { public partial class frmLogin : Form { public frmLogin() { InitializeComponent(); } #region variables private string Usuario; string loggedUser; string loggedName; string serialPC; public static int IdCaja; public static int idusuario; string Apertura; string UserLoginNow; string nameUserNow; string userPermision; string BoxPermission; int countMcsxu; List<User> lstLoggedUser; List<OpenCloseBox> lstOpenCloseDetail; #endregion private void Form1_Load(object sender, EventArgs e) { timer1.Start(); DibujarLogin(); panelIniciarSesion.Visible = false; } private void DibujarLogin() { try { User u = new User(); u.Usuario = ""; u.Contraseña = ""; List<User> lstUser = new BusUser().getUsersList(u); foreach (var item in lstUser) { Label label = new Label(); Panel panel = new Panel(); PictureBox picture = new PictureBox(); label.Text = item.Usuario; label.Name = item.Id.ToString(); label.Size = new Size(175, 25); label.Font = new Font("Microsoft Sans Serif", 13); label.FlatStyle = FlatStyle.Flat; label.BackColor = Color.FromArgb(176, 196, 222); label.ForeColor = Color.Black; label.Dock = DockStyle.Bottom; label.TextAlign = ContentAlignment.MiddleCenter; label.Cursor = Cursors.Hand; panel.Size = new Size(90, 90); panel.BorderStyle = BorderStyle.None; panel.Dock = DockStyle.Top; panel.BackColor = Color.FromArgb(176, 196, 222); picture.Size = new Size(80, 80); picture.Dock = DockStyle.Top; picture.BackgroundImage = null; byte[] b = item.Foto; MemoryStream ms = new MemoryStream(b); picture.Image = Image.FromStream(ms); picture.SizeMode = PictureBoxSizeMode.Zoom; picture.Tag = item.Usuario; picture.Cursor = Cursors.Hand; panel.Controls.Add(label); panel.Controls.Add(picture); label.BringToFront(); flowLayoutPanelUsuarios.Controls.Add(panel); label.Click += new EventHandler(myLabelEvent); picture.Click += new EventHandler(myPictureEvent); } } catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); } } private void myPictureEvent(object sender, EventArgs e) { Usuario = ((PictureBox)sender).Tag.ToString(); panelIniciarSesion.Visible = true; ShowPermission(); } private void myLabelEvent(object sender, EventArgs e) { Usuario = ((Label)sender).Text; panelIniciarSesion.Visible = true; //flowLayoutPanelUsuarios.Visible = false; ShowPermission(); } private void btnCambiarUsuario_Click(object sender, EventArgs e) { panelIniciarSesion.Visible = false; txtContraseña.Clear(); } private void tver_Click(object sender, EventArgs e) { txtContraseña.PasswordChar = '\0'; tocultar.Visible = true; tver.Visible = false; } private void tocultar_Click(object sender, EventArgs e) { txtContraseña.PasswordChar = '*'; tocultar.Visible = false; tver.Visible = true; } private void txtContraseña_TextChanged(object sender, EventArgs e) { AccederSistema(); } private void AccederSistema() { int LoggedCount = LoadUser(); try { loggedName = lstLoggedUser.Select(u => u.Nombre).FirstOrDefault(); loggedUser = lstLoggedUser.Select(u => u.Usuario).FirstOrDefault(); idusuario = lstLoggedUser.Select(u => u.Id).FirstOrDefault(); } catch { } if (LoggedCount > 0) { int contadorDCC = ListOpenCloseDetailBox(); // userPermision = lstLoggedUser.Select(x => x.Rol).First(); if (contadorDCC == 0 & userPermision != "VENDEDOR") { AddOpenCloseDetailBox(); Apertura = "NUEVO"; timer2.Start(); } else { if (userPermision != "VENDEDOR") { GetSerialBoxByUser(); try { ListOpenCloseDetailBox(); UserLoginNow = lstOpenCloseDetail.Select(x => x.UsuarioId.Usuario).FirstOrDefault(); nameUserNow = lstOpenCloseDetail.Select(x => x.UsuarioId.Nombre).FirstOrDefault(); } catch (Exception ex) { MessageBox.Show(ex.Message); } if (countMcsxu == 0) { if (UserLoginNow == "Administrador" || Usuario == "Admininistrador" || userPermision == "ADMINISTRADOR") { MessageBox.Show("Continuaras Turno de *" + nameUserNow + " Todos los Registros seran con ese Usuario", "Caja Iniciada", MessageBoxButtons.OK, MessageBoxIcon.Warning); BoxPermission = "Correcto"; } if (loggedName == "Admin" && Usuario == "Admin") { BoxPermission = "Correcto"; } else if (UserLoginNow != Usuario && userPermision !="ADMINISTRADOR") { MessageBox.Show("Para poder continuar con el Turno de *" + nameUserNow + "* ,Inicia sesion con el Usuario " + UserLoginNow + " -ó-el Usuario *admin*", "Caja Iniciada", MessageBoxButtons.OK, MessageBoxIcon.Information); BoxPermission = "Vacio"; } else if (UserLoginNow == Usuario) { BoxPermission = "Correcto"; } } else { BoxPermission = "Correcto"; } if (BoxPermission == "Correcto") { Apertura = "Aperturado"; timer2.Start(); } } else { timer2.Start(); } } } } private void AddOpenCloseDetailBox() { try { int usuarioID = lstLoggedUser.Select(x => x.Id).First(); User u = new User(); u.Id = usuarioID; Box b = new Box(); b.Id = IdCaja; OpenCloseBox open = new OpenCloseBox(); open.FechaInicio = DateTime.Now; open.FechaFin = DateTime.Now; open.FechaCierre = DateTime.Now; open.Ingresos = 0; open.Egresos = 0; open.Saldo = 0; open.UsuarioId = u; open.TotalCalculado = 0; open.TotalReal = 0; open.Estado = true; open.Diferencia = 0; open.CadaId =b; new BusOpenCloseBox().AddOpenCloseBoxDetail(open); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private int ListOpenCloseDetailBox() { int auxcount=0; try { lstOpenCloseDetail = new BusOpenCloseBox().showMovBoxBySerial(serialPC); auxcount = lstOpenCloseDetail.Count; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return auxcount; } private int LoadUser() { int auxCount=0; try { User u = new User(); u.Contraseña = EncriptarTexto.Encriptar(txtContraseña.Text); u.Usuario = Usuario; lstLoggedUser = new BusUser().getUsersList(u); auxCount = lstLoggedUser.Count; } catch (Exception ex) { MessageBox.Show("Error al mostrar el usuario"+ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); } return auxCount; } private int GetSerialBoxByUser() { try { int idUsuario = lstLoggedUser.Select(x => x.Id).First(); countMcsxu = new BusOpenCloseBox().getMovOpenCloseBox(serialPC,idUsuario); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return countMcsxu; } private void timer1_Tick(object sender, EventArgs e) { timer1.Stop(); List<User> lstUsuarios = new BusUser().ListarUsuarios(); int contadorUsuario = lstUsuarios.Count; string INDICADOR = DatUser.AUX_CONEXION; // MessageBox.Show(INDICADOR); if (DatUser.AUX_CONEXION == "CORRECTO" ) { if ( contadorUsuario == 0 || lstUsuarios == null) { Hide(); frmRegistroEmpresa registroEmpresa = new frmRegistroEmpresa(); registroEmpresa.ShowDialog(); this.Dispose(); } } if (DatUser.AUX_CONEXION == "INCORRECTO") { Hide(); frmServidorRemoto servidorRemoto = new frmServidorRemoto(); servidorRemoto.ShowDialog(); this.Dispose(); } try { ManagementObject mos = new ManagementObject(@"Win32_PhysicalMedia='\\.\PHYSICALDRIVE0'"); //foreach (ManagementObject getSerial in mos.Get()) //{ serialPC = mos.Properties["SerialNumber"].Value.ToString().Trim(); IdCaja = new BusBox().showBoxBySerial(serialPC).Id; // } } catch (Exception ex) { MessageBox.Show(ex.Message); } try { Licencia licencia = new BusLicencia().Obtener_LicenciaTemporal(); dtpVencimiento.Value = Convert.ToDateTime( EncriptarTexto.Desencriptar( licencia.FechaVencimiento ) ); string serial = EncriptarTexto.Desencriptar( licencia.Serial ); string estado = EncriptarTexto.Desencriptar( licencia.Estado ); dtpFechaActivacion.Value = Convert.ToDateTime( EncriptarTexto.Desencriptar( licencia.FechaActivacion )); label3.Text = estado; label2.Text = serial; //dtpFechaActivacion.Value = Convert.ToDateTime( fechaActivacion ); // dtpVencimiento.Value = Convert.ToDateTime( VencimientoLicencia ); dtpFechaActivacion.Format = DateTimePickerFormat.Custom; dtpVencimiento.Format = DateTimePickerFormat.Custom; if (estado != "VENCIDO") { string fechaActual =Convert.ToString( DateTime.Now ); DateTime hoy = Convert.ToDateTime(fechaActual.Split(' ')[0]); if ( dtpVencimiento.Value >= hoy) { int mes = dtpFechaActivacion.Value.Month; int mesActual = hoy.Month; if ( mes <= mesActual) { if (estado.Equals("?ACTIVO?")) { lblLicencia.Text = "Licencia activada hasta el : " + dtpVencimiento.Value.ToString("dd/MM/yyyy"); } else if ( estado.Equals("?ACTIVADO PREMIUM?")) { lblLicencia.Text = "Licencia profesional Activada hasta el : "+ dtpVencimiento.Value.ToString("dd/MM/yyyy"); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ShowPermission() { userPermision = new BusUser().ShowPermision(Usuario); } ProgressBar pb = new ProgressBar(); private void timer2_Tick(object sender, EventArgs e) { pb.Maximum = 100; if (pb.Value < 100) { pb.Value = pb.Value + 10; } else { pb.Value = 0; timer2.Stop(); var tipoUsuario = lstLoggedUser.Select(x => x.Rol).First(); if ( tipoUsuario.Equals("ADMINISTRADOR")) { new DatCatGenerico().Editar_InicioSesion( EncriptarTexto.Encriptar(serialPC), idusuario); this.Hide(); frmDashboard dashboard = new frmDashboard(); dashboard.ShowDialog(); Dispose(); } else { if (Apertura == "NUEVO" & userPermision != "VENDEDOR") { new DatCatGenerico().Editar_InicioSesion(EncriptarTexto.Encriptar(serialPC), idusuario); this.Hide(); frmAperturaCaja frm = new frmAperturaCaja(); frm.ShowDialog(); UserLoginNow = null; nameUserNow = null; } else { this.Hide(); new DatCatGenerico().Editar_InicioSesion(EncriptarTexto.Encriptar(serialPC), idusuario); frmMenuPrincipal principal = new frmMenuPrincipal(); principal.ShowDialog(); UserLoginNow = null; nameUserNow = null; } } } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Plus1.Models; namespace Plus1.Areas.Admin.Controllers { [Authorize(Roles = "Admin")] public class AdminSubCategoriesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Admin/AdminSubCategories public ActionResult Index() { var subCategory = db.SubCategory.Include(s => s.Parent); return View(subCategory.ToList()); } // GET: Admin/AdminSubCategories/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SubCategory subCategory = db.SubCategory.Find(id); if (subCategory == null) { return HttpNotFound(); } return View(subCategory); } // GET: Admin/AdminSubCategories/Create public ActionResult Create() { ViewBag.ParentName = new SelectList(db.Category, "Name", "Image"); return View(); } // POST: Admin/AdminSubCategories/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Name,ParentName,Image")] SubCategory subCategory) { if (ModelState.IsValid) { db.SubCategory.Add(subCategory); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ParentName = new SelectList(db.Category, "Name", "Image", subCategory.ParentName); return View(subCategory); } // GET: Admin/AdminSubCategories/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SubCategory subCategory = db.SubCategory.Find(id); if (subCategory == null) { return HttpNotFound(); } ViewBag.ParentName = new SelectList(db.Category, "Name", "Image", subCategory.ParentName); return View(subCategory); } // POST: Admin/AdminSubCategories/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(SubCategory subCategory, HttpPostedFileBase fileUpload) { if (ModelState.IsValid && fileUpload != null && fileUpload.ContentLength > 0) { // var db = new ApplicationDbContext(); string fileGuid = Guid.NewGuid().ToString(); string extension = Path.GetExtension(fileUpload.FileName); string newFilename = fileGuid + extension; string uploadPath = Path.Combine(Server.MapPath("~/Content/uploads/")); fileUpload.SaveAs(Path.Combine(uploadPath, newFilename)); subCategory.Image = newFilename; // db.SaveChanges(); // return RedirectToAction("index"); if (ModelState.IsValid) { db.Entry(subCategory).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } } ViewBag.ParentName = new SelectList(db.Category, "Name", "Image", subCategory.ParentName); return View(subCategory); } // GET: Admin/AdminSubCategories/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SubCategory subCategory = db.SubCategory.Find(id); if (subCategory == null) { return HttpNotFound(); } return View(subCategory); } // POST: Admin/AdminSubCategories/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { SubCategory subCategory = db.SubCategory.Find(id); db.SubCategory.Remove(subCategory); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Collections.Generic; namespace FarmTypeManager { //config.json, used by all players/saves for shared functions public class ModConfig { public bool EnableWhereAmICommand { get; set; } public ModConfig() { EnableWhereAmICommand = true; //should enable the "whereami" command in the SMAPI console } } //per-character configuration file, e.g. PlayerName12345.json; contains most of the mod's functional settings, split up this way to allow for different settings between saves & farm types public class FarmConfig { public bool ForageSpawnEnabled { get; set; } public bool LargeObjectSpawnEnabled { get; set; } public bool OreSpawnEnabled { get; set; } public ForageSettings Forage_Spawn_Settings { get; set; } public LargeObjectSettings Large_Object_Spawn_Settings { get; set; } public OreSettings Ore_Spawn_Settings { get; set; } public int[] QuarryTileIndex { get; set; } public InternalSaveData Internal_Save_Data { get; set; } public FarmConfig() { //basic on/off toggles ForageSpawnEnabled = false; LargeObjectSpawnEnabled = false; OreSpawnEnabled = false; //settings for each generation type (assigned in the constructor for each of these "Settings" objects; see those for details) Forage_Spawn_Settings = new ForageSettings(); Large_Object_Spawn_Settings = new LargeObjectSettings(); Ore_Spawn_Settings = new OreSettings(); //a list of every tilesheet index commonly used by "quarry" tiles on maps, e.g. the vanilla hilltop (mining) farm //these should be compared to [an instance of GameLocation].getTileIndexAt(x, y, "Back") QuarryTileIndex = new int[] { 556, 558, 583, 606, 607, 608, 630, 635, 636, 680, 681, 685 }; //NOTE: swap in the following code to cover more tiles, e.g. the grassy edges of the "quarry" dirt; this tends to cover too much ground and weird spots, though, such as the farm's cave entrance //{ 556, 558, 583, 606, 607, 608, 630, 631, 632, 633, 634, 635, 636, 654, 655, 656, 657, 658, 659, 679, 680, 681, 682, 683, 684, 685, 704, 705, 706, 707 }; //internal save data for things not normally tracked by Stardew Internal_Save_Data = new InternalSaveData(); } } /// <summary>A class containing any per-farm information that needs to be saved by the mod. Not normally intended to be edited by the player.</summary> public class InternalSaveData { //class added in version 1.3; defaults used here to automatically fill in values with SMAPI's json interface public Utility.Weather WeatherForYesterday { get; set; } = Utility.Weather.Sunny; public InternalSaveData() { } public InternalSaveData(Utility.Weather wyesterday, Utility.Weather wtoday) { WeatherForYesterday = wyesterday; //an enum (int) value corresponding to yesterday's weather } } //contains configuration settings for forage item generation behavior public class ForageSettings { public ForageSpawnArea[] Areas { get; set; } public int PercentExtraSpawnsPerForagingLevel { get; set; } public int[] SpringItemIndex { get; set; } public int[] SummerItemIndex { get; set; } public int[] FallItemIndex { get; set; } public int[] WinterItemIndex { get; set; } public int[] CustomTileIndex { get; set; } //default constructor: configure default forage generation settings public ForageSettings() { Areas = new ForageSpawnArea[] { new ForageSpawnArea("Farm", 0, 3, new string[] { "Grass", "Diggable" }, new string[0], new string[0], "High", new ExtraConditions(), null, null, null, null) }; //a set of "SpawnArea" objects, describing where forage items can spawn on each map PercentExtraSpawnsPerForagingLevel = 0; //multiplier to give extra forage per level of foraging skill; default is +0%, since the native game lacks this mechanic //the "parentSheetIndex" values for each type of forage item allowed to spawn in each season (the numbers found in ObjectInformation.xnb) SpringItemIndex = new int[] { 16, 20, 22, 257 }; SummerItemIndex = new int[] { 396, 398, 402, 404 }; FallItemIndex = new int[] { 281, 404, 420, 422 }; WinterItemIndex = new int[0]; CustomTileIndex = new int[0]; //an extra list of tilesheet indices, for use by players who want to make some custom tile detection } } //contains configuration settings for spawning large objects (e.g. stumps and logs) public class LargeObjectSettings { public LargeObjectSpawnArea[] Areas { get; set; } public int[] CustomTileIndex { get; set; } public LargeObjectSettings() { Areas = new LargeObjectSpawnArea[] { new LargeObjectSpawnArea("Farm", 999, 999, new string[0], new string[0], new string[0], "High", new ExtraConditions(), new string[] { "Stump" }, true, 0, "Foraging") }; //a set of "LargeObjectSpawnArea", describing where large objects can spawn on each map CustomTileIndex = new int[0]; //an extra list of tilesheet indices, for use by players who want to make some custom tile detection } } //contains configuration settings for ore generation behavior public class OreSettings { public OreSpawnArea[] Areas { get; set; } public int PercentExtraSpawnsPerMiningLevel { get; set; } public Dictionary<string, int> MiningLevelRequired { get; set; } public Dictionary<string, int> StartingSpawnChance { get; set; } public Dictionary<string, int> LevelTenSpawnChance { get; set; } public int[] CustomTileIndex { get; set; } //default constructor: configure default ore generation settings public OreSettings() { Areas = new OreSpawnArea[] { new OreSpawnArea("Farm", 1, 5, new string[] { "Quarry" }, new string[0], new string[0], "High", new ExtraConditions(), null, null, null) }; //a set of "OreSpawnArea" objects, describing where ore can spawn on each map PercentExtraSpawnsPerMiningLevel = 0; //multiplier to give extra ore per level of mining skill; default is +0%, since the native game lacks this mechanic //mining skill level required to spawn each ore type; defaults are based on the vanilla "hilltop" map settings, though some types didn't spawn at all MiningLevelRequired = new Dictionary<string, int>(); MiningLevelRequired.Add("Stone", 0); MiningLevelRequired.Add("Geode", 0); MiningLevelRequired.Add("FrozenGeode", 5); MiningLevelRequired.Add("MagmaGeode", 8); MiningLevelRequired.Add("Gem", 6); MiningLevelRequired.Add("Copper", 0); MiningLevelRequired.Add("Iron", 4); MiningLevelRequired.Add("Gold", 7); MiningLevelRequired.Add("Iridium", 9); MiningLevelRequired.Add("Mystic", 10); //weighted chance to spawn ore at the minimum required skill level (e.g. by default, iron starts spawning at level 4 mining skill with a 15% chance, but is 0% before that) StartingSpawnChance = new Dictionary<string, int>(); StartingSpawnChance.Add("Stone", 66); StartingSpawnChance.Add("Geode", 8); StartingSpawnChance.Add("FrozenGeode", 4); StartingSpawnChance.Add("MagmaGeode", 2); StartingSpawnChance.Add("Gem", 5); StartingSpawnChance.Add("Copper", 21); StartingSpawnChance.Add("Iron", 15); StartingSpawnChance.Add("Gold", 10); StartingSpawnChance.Add("Iridium", 1); StartingSpawnChance.Add("Mystic", 1); //weighted chance to spawn ore at level 10 mining skill; for any levels in between "starting" and level 10, the odds are gradually adjusted (e.g. by default, stone is 66% at level 0, 57% at level 5, and 48% at level 10) LevelTenSpawnChance = new Dictionary<string, int>(); LevelTenSpawnChance.Add("Stone", 48); LevelTenSpawnChance.Add("Geode", 2); LevelTenSpawnChance.Add("FrozenGeode", 2); LevelTenSpawnChance.Add("MagmaGeode", 2); LevelTenSpawnChance.Add("Gem", 5); LevelTenSpawnChance.Add("Copper", 16); LevelTenSpawnChance.Add("Iron", 13); LevelTenSpawnChance.Add("Gold", 10); LevelTenSpawnChance.Add("Iridium", 1); LevelTenSpawnChance.Add("Mystic", 1); CustomTileIndex = new int[0]; //an extra list of tilesheet indices, for use by players who want to make some custom tile detection } } //a set of variables including a map name, terrain type(s) to auto-detect, and manually defined included/excluded areas for object spawning public class SpawnArea { public string MapName { get; set; } public int MinimumSpawnsPerDay { get; set; } public int MaximumSpawnsPerDay { get; set; } public string[] AutoSpawnTerrainTypes { get; set; } //Valid properties include "Quarry", "Custom", "Diggable", "All", and any tile Type properties ("Grass", "Dirt", "Stone", "Wood") public string[] IncludeAreas { get; set; } public string[] ExcludeAreas { get; set; } public string StrictTileChecking { get; set; } = "High"; //added in version 1.1; default used here to automatically fill it in with SMAPI's json interface public ExtraConditions ExtraConditions { get; set; } = new ExtraConditions(); //added in version 1.3; default used here to automatically fill in values with SMAPI's json interface public SpawnArea() { } public SpawnArea(string name, int min, int max, string[] types, string[] include, string[] exclude, string safety, ExtraConditions extra) { MapName = name; //name of the targeted map, e.g. "Farm" or "BusStop" MinimumSpawnsPerDay = min; //minimum number of items to be spawned each day (before multipliers) MaximumSpawnsPerDay = max; //maximum number of items to be spawned each day (before multipliers) AutoSpawnTerrainTypes = types; //a list of strings describing the terrain on which objects may spawn IncludeAreas = include; //a list of strings describing coordinates for object spawning ExcludeAreas = exclude; //a list of strings describing coordinates *preventing* object spawning StrictTileChecking = safety; //the degree of safety-checking to use before spawning objects on a tile ExtraConditions = extra; //a list of additional conditions that may be used to limit object spawning } } /// <summary>A set of additional requirements needed to spawn objects in a given area.</summary> public class ExtraConditions { //class added in version 1.3; defaults used here to automatically fill in values with SMAPI's json interface public string[] Years { get; set; } = new string[0]; public string[] Seasons { get; set; } = new string[0]; public string[] Days { get; set; } = new string[0]; public string[] WeatherYesterday { get; set; } = new string[0]; public string[] WeatherToday { get; set; } = new string[0]; public string[] WeatherTomorrow { get; set; } = new string[0]; public int? LimitedNumberOfSpawns { get; set; } = null; public ExtraConditions() { } public ExtraConditions(string[] years, string[] seasons, string[] days, string[] wyesterday, string[] wtoday, string[] wtomorrow, int? spawns) { Years = years; //a list of years on which objects are allowed to spawn Seasons = seasons; //a list of seasons in which objects are allowed to spawn Days = days; //a list of days (individual or ranges) on which objects are allowed to spawn WeatherYesterday = wyesterday; //if yesterday's weather is listed here, objects are allowed to spawn WeatherToday = wtoday; //if yesterday's weather is listed here, objects are allowed to spawn WeatherTomorrow = wtomorrow; //if yesterday's weather is listed here, objects are allowed to spawn LimitedNumberOfSpawns = spawns; //a number that will count down each day until 0, preventing any further spawns once that is reached } } //a subclass of "SpawnArea" specifically for forage generation, providing the ability to override each area's seasonal forage items public class ForageSpawnArea : SpawnArea { public int[] SpringItemIndex { get; set; } = null; //added in version 1.2; default used here to automatically fill it in with SMAPI's json interface public int[] SummerItemIndex { get; set; } = null; //"" public int[] FallItemIndex { get; set; } = null; //"" public int[] WinterItemIndex { get; set; } = null; //"" public ForageSpawnArea() :base() { } public ForageSpawnArea(string name, int min, int max, string[] types, string[] include, string[] exclude, string safety, ExtraConditions extra, int[] spring, int[] summer, int[] fall, int[] winter) :base(name, min, max, types, include, exclude, safety, extra) //uses the original "SpawnArea" constructor to fill in the shared fields as usual { SpringItemIndex = spring; SummerItemIndex = summer; FallItemIndex = fall; WinterItemIndex = winter; } } //a subclass of "SpawnArea" specifically for large object generation, including settings for which object types to spawn & a one-time switch to find and respawn pre-existing objects public class LargeObjectSpawnArea : SpawnArea { public string[] ObjectTypes { get; set; } public bool FindExistingObjectLocations { get; set; } public int PercentExtraSpawnsPerSkillLevel { get; set; } public string RelatedSkill { get; set; } public LargeObjectSpawnArea() : base() { } public LargeObjectSpawnArea(string name, int min, int max, string[] types, string[] include, string[] exclude, string safety, ExtraConditions extra, string[] objTypes, bool find, int extraSpawns, string skill) : base(name, min, max, types, include, exclude, safety, extra) //uses the original "SpawnArea" constructor to fill in the shared fields as usual { ObjectTypes = objTypes; FindExistingObjectLocations = find; PercentExtraSpawnsPerSkillLevel = extraSpawns; RelatedSkill = skill; } } //a subclass of "SpawnArea" specifically for ore generation, providing the ability to optionally override each area's skill requirements & spawn chances for ore public class OreSpawnArea : SpawnArea { public Dictionary<string, int> MiningLevelRequired { get; set; } public Dictionary<string, int> StartingSpawnChance { get; set; } public Dictionary<string, int> LevelTenSpawnChance { get; set; } public OreSpawnArea() : base () { } public OreSpawnArea(string name, int min, int max, string[] types, string[] include, string[] exclude, string safety, ExtraConditions extra, Dictionary<string, int> skill, Dictionary<string, int> starting, Dictionary<string, int> levelTen) : base (name, min, max, types, include, exclude, safety, extra) //uses the original "SpawnArea" constructor to fill in the shared fields as usual { MiningLevelRequired = skill; StartingSpawnChance = starting; LevelTenSpawnChance = levelTen; } } }
namespace ApiTemplate.Model.Weathers { public class CurrentWeatherByZipCodeRequestModel { public string ZipCode { get; set; } } }
using LoowooTech.Stock.WorkBench; using System.Collections.Generic; using System.Windows.Forms; using System.Xml; namespace LoowooTech.Stock { internal static class RuleHelper { /// <summary> /// 将配置中的质检规则信息读取到TreeView里 /// </summary> /// <param name="treeView"></param> /// <param name="configNode"></param> public static void LoadRules(TreeView treeView, XmlNode configNode) { treeView.Nodes.Clear(); var node = configNode.SelectSingleNode("Rules"); LoadNode(node, treeView.Nodes, treeView); } /// <summary> /// 递归方法,将配置中的质检规则信息读取到TreeView里 /// </summary> /// <param name="xmlNode"></param> /// <param name="parentSubNodes"></param> /// <param name="treeView"></param> private static void LoadNode(XmlNode xmlNode, TreeNodeCollection parentSubNodes, TreeView treeView) { var ruleNodes = xmlNode.SelectNodes("Rule"); if (ruleNodes.Count > 0) { for (var i = 0; i < ruleNodes.Count; i++) { var node = ruleNodes[i]; var childNode = parentSubNodes.Add(node.Attributes["ID"].Value, string.Format("[{0}]{1}", node.Attributes["ID"].Value, node.Attributes["Title"].Value)); childNode.Tag = node.Attributes["ID"].Value; childNode.ImageIndex = 0; childNode.Checked = true; } } else { var ruleGroupNodes = xmlNode.SelectNodes("Category"); for (var i = 0; i < ruleGroupNodes.Count; i++) { var node = ruleGroupNodes[i]; var childNode = parentSubNodes.Add(node.Attributes["Name"].Value); childNode.Checked = true; childNode.ImageIndex = 3; LoadNode(node, childNode.Nodes, treeView); childNode.Expand(); } } } /// <summary> /// 从treeView1里获取哪些检查规则被选中了 /// </summary> /// <param name="nodes"></param> /// <param name="ids"></param> public static void GetCheckedRuleIDs(TreeNodeCollection nodes, List<int> ids) { foreach(TreeNode node in nodes) { if (node.Checked) { if (node.Nodes.Count == 0 && node.Checked) { ids.Add(int.Parse(node.Tag.ToString())); } else { GetCheckedRuleIDs(node.Nodes, ids); } } } } /// <summary> /// 将质检结果更新到treeView1的质检规则中,通过图标区别规则未检查,通过和未通过 /// </summary> /// <param name="nodes"></param> /// <param name="results"></param> public static void UpdateCheckState(TreeNodeCollection nodes, Dictionary<string, ProgressResultTypeEnum> results) { foreach (TreeNode node in nodes) { if (node.Nodes.Count == 0) { var code = node.Tag.ToString(); if (results.ContainsKey(code)) { node.ImageIndex = results[code] == ProgressResultTypeEnum.Pass ? 1 : 2; } else { node.ImageIndex = 0; } } else { UpdateCheckState(node.Nodes, results); } } } } }
/// <summary> /// Footfall - script to decribe the behaviour of a footfall, the visualisation of a noisy footstep /// </summary> using UnityEngine; using System.Collections; public class Footfall : MonoBehaviour { public float fadeSpeed; public float growSpeed; public float startTime; Color tempColor; SpriteRenderer sRenderer; TimeScaler tScaler; void Awake() { // record birthtime so guard can tell which footstep is the most recent startTime = Time.time; } void Start () { transform.localScale = new Vector3 (0,0,0); sRenderer = GetComponent<SpriteRenderer> (); tScaler = GameObject.Find ("Time Manager").GetComponent<TimeScaler> (); if (tScaler.GetNoiseDampening()) { fadeSpeed = 3.0f; Destroy (gameObject, 1.25f); } else { Destroy (gameObject, 2.5f); } } void Update () { // fade to transparancy tempColor = sRenderer.color; tempColor.a -= (Time.deltaTime * fadeSpeed); sRenderer.color = tempColor; // grow in size transform.localScale = Vector3.Lerp (transform.localScale, new Vector3(1,1,1), Time.deltaTime*growSpeed ); } }
namespace AI2048.AI.Searchers { using System.Collections.Generic; using System.Linq; using AI2048.AI.Searchers.Models; using AI2048.AI.SearchTree; using AI2048.Game; using NodaTime; public class ProbabilityLimitedExpectiMaxer : ISearcher { private const double ProbabilityOf2 = 0.9; private const double ProbabilityOf4 = 0.1; private readonly ISearchTree searchTree; private readonly SearchStatistics searchStatistics; private readonly double minProbability; private readonly int maxSearchDepth; public ProbabilityLimitedExpectiMaxer(ISearchTree searchTree, double minProbability = 0.004, int maxSearchDepth = 6) { this.searchTree = searchTree; this.minProbability = minProbability; this.maxSearchDepth = maxSearchDepth; this.searchStatistics = new SearchStatistics { RootNodeGrandchildren = this.searchTree.RootNode.Children.Values.Sum(c => c.Children.Count()) }; } public SearchResult Search() { var startTime = SystemClock.Instance.Now; var knownPlayerNodesStart = this.searchTree.KnownPlayerNodeCount; var knownComputerNodesStart = this.searchTree.KnownComputerNodeCount; var evaluationResult = this.InitializeEvaluation(); this.searchStatistics.SearchDepth = this.maxSearchDepth; this.searchStatistics.SearchDuration = SystemClock.Instance.Now - startTime; this.searchStatistics.KnownPlayerNodes = this.searchTree.KnownPlayerNodeCount - knownPlayerNodesStart; this.searchStatistics.KnownComputerNodes = this.searchTree.KnownComputerNodeCount - knownComputerNodesStart; var result = new SearchResult { RootGrid = this.searchTree.RootNode.Grid, BestMove = evaluationResult.OrderByDescending(kvp => kvp.Value).Select(kvp => kvp.Key).First(), BestMoveEvaluation = evaluationResult.OrderByDescending(kvp => kvp.Value).Select(kvp => kvp.Value).First(), MoveEvaluations = evaluationResult, SearcherName = nameof(ProbabilityLimitedExpectiMaxer), SearchStatistics = this.searchStatistics }; return result; } private IDictionary<Move, double> InitializeEvaluation() { return this.searchTree.RootNode.Children .ToDictionary( child => child.Key, child => this.GetPositionEvaluation(child.Value, this.maxSearchDepth, 1)); } private double GetPositionEvaluation(IPlayerNode playerNode, int depth, double probability) { this.searchStatistics.NodeCount++; if (playerNode.GameOver || probability < this.minProbability || depth == 0) { this.searchStatistics.TerminalNodeCount++; return playerNode.HeuristicValue; } return playerNode.Children.Values.Max(child => this.GetPositionEvaluation(child, depth, probability)); } private double GetPositionEvaluation(IComputerNode computerNode, int depth, double probability) { this.searchStatistics.NodeCount++; var childrenCount = computerNode.ChildrenWith2.Count(); var resultWith2 = computerNode.ChildrenWith2.Average(child => this.GetPositionEvaluation(child, depth - 1, probability * ProbabilityOf2 / childrenCount)); var resultWith4 = computerNode.ChildrenWith4.Average(child => this.GetPositionEvaluation(child, depth - 1, probability * ProbabilityOf4 / childrenCount)); var result = resultWith2 * ProbabilityOf2 + resultWith4 * ProbabilityOf4; return result; } } }
 namespace _2.RefactorIfStatements { using System; using System.Linq; using _1.CookingProgram; class DoRefactoring { static void Main(string[] args) { //first task IVegetable potato = new Potato(); //... potato.IsPeeled = true; potato.IsGoodToEat = true; if (potato != null) { if(potato.IsPeeled && potato.IsGoodToEat) { Cook(potato); } } //second task int x = 0; int y = 0; int minX = 0; int maxX = 0; int maxY = 0; int minY = 0; bool shoudVisitCell = true; bool isYInRange = minY <= y && y <= maxY; bool isXInRange = minX <= x && x <= maxX; if (isXInRange && (isYInRange && shoudVisitCell)) { VisitCell(); } } private static void VisitCell() { Console.WriteLine("I will visit the cell."); } private static void Cook(IVegetable potato) { Console.WriteLine("Cooking"); } } }
using System.Collections.Generic; using RDotNet; using BSky.Lifetime.Interfaces; namespace BSky.Statistics.Common { public abstract class CommandDispatcher { public abstract DataFrame GetDF(DataSource ds); public List<ServerDataSource> DataSources { get; private set; } public CommandDispatcher() { DataSources = new List<ServerDataSource>(); onLoad(); } public ServerDataSource DataSourceLoad(string sourceName, string filePath) { //Load datasource ServerDataSource ds = new ServerDataSource(this, filePath, sourceName); ds.Load(); this.DataSources.Add(ds); return ds; } public abstract UAReturn DataSourceReadRows(ServerDataSource dataSource, int start, int end); public abstract UAReturn DataSourceReadCell(ServerDataSource dataSource, int row, int col); public abstract UAReturn DataSourceReadRow(ServerDataSource dataSource, int row); //23Jan2014 public abstract UAReturn EmptyDataSourceLoad(ServerDataSource dataSource);//03Jan2014 public abstract UAReturn DataSourceLoad(ServerDataSource dataSource, string sheetname);//, IOpenDataFileOptions odfo=null public abstract UAReturn DataFrameLoad(ServerDataSource dataSource, string dframe); //13Feb2014 public abstract UAReturn GetSQLTablelist(string sqlcomm); //24Nov2015 public abstract UAReturn GetRodbcTables(string fname); //27Jan2014 public abstract UAReturn GetRDataDfObjList(string fname); //23May2018 public abstract object GetDatagridFindResults(string findtext, string[] selectedcols, bool matchcase, string datasetname);//24Jun2016 public abstract object GetAllModels(string classtype);//09Sep2016 public abstract UAReturn DataSourceRefresh(ServerDataSource dataSource);//25Mar2013 public abstract void onLoad(); public virtual UAReturn DataSourceClose(ServerDataSource dataSource) { this.DataSources.Remove(dataSource); return new UAReturn(); } public abstract UAReturn DataSourceSave(ServerDataSource dataSource); public abstract UAReturn Execute(ServerCommand Command); public abstract UAReturn Execute(string CommandScript); public abstract object ExecuteR(ServerCommand Command, bool hasReturn, bool hasUAReturn); public abstract UAReturn DontExecuteJustLogCommand(string CommandScript);//16Aug2016 public abstract UAReturn DatasetSaveas(ServerDataSource dataSource);//Anil public abstract UAReturn CloseDataset(ServerDataSource dataSource);//Anil #region variablegrid public abstract UAReturn editDatasetVarGrid(ServerDataSource dataSource, string colName, string colProp, string newValue, List<string> colLevels);//var grid public abstract UAReturn makeColumnFactor(ServerDataSource dataSource, string colName);//var grid public abstract UAReturn makeColumnString(ServerDataSource dataSource, string colName);//var grid public abstract UAReturn makeColumnNumeric(ServerDataSource dataSource, string colName);//var grid 11Oct2017 public abstract UAReturn addNewColDatagrid(string colName, string rdataType, string dgridval, int rowindex, ServerDataSource dataSource);//add row in vargrid and col in datagrid //15Oct2015 modified public abstract UAReturn removeVarGridCol(string colName, ServerDataSource dataSource);//remove row from variable grid //public abstract UAReturn removeMultipleVarGridCol(string[] colName, ServerDataSource dataSource); //04Aug2016 remove multiple rows from var grid. ie delete multi cols public abstract UAReturn changeColLevels(string colName, List<ValLvlListItem> finalLevelList, ServerDataSource dataSource);//change levels public abstract UAReturn addColLevels(string colName, List<string> finalLevelList, ServerDataSource dataSource);//add levels public abstract UAReturn changeMissing(string colName, string colProp, List<string> newMisVal, string mistype, ServerDataSource dataSource);//change levels public abstract object getColNumFactors(string colName, ServerDataSource dataSource); public abstract UAReturn setScaleToNominalOrOrdinal(string colName, List<FactorMap> fmap, string changeTo, ServerDataSource dataSource); public abstract List<FactorMap> getColFactormap(string colName, ServerDataSource dataSource); public abstract UAReturn setNominalOrOrdinalToScale(string colName, List<FactorMap> fmap, string changeTo, ServerDataSource dataSource); #endregion #region datagrid public abstract UAReturn editDatagridCell(string colName, string celdata, int rowindex, ServerDataSource dataSource);//edit existing data row public abstract UAReturn addNewDataRow(string colName, string celdata, string rowdata, int rowindex, ServerDataSource dataSource);//add new data row public abstract UAReturn removeDatagridRow(int rowindex, ServerDataSource dataSource);//remove data row public abstract UAReturn sortDatagridColumn(string colname, string sortorder, ServerDataSource dataSource);//sort ascending then desending then ascending #endregion //27Oct2016 #region R Object save / Load public abstract UAReturn GetAll_RObjects(); public abstract UAReturn Save_RObjects(string objname, string fullpathfilename); public abstract UAReturn Load_RObjects(string fullpathfilename); #endregion #region Package related public abstract void LoadDefPacakges();//30Mar2015 public abstract UAReturn ShowInstalledPackages(); public abstract UAReturn ShowLoadedPackages(); public abstract UAReturn GetMissingDefRPackages(); public abstract UAReturn InstallLocalPackage(string[] pkgfilenames, bool autoLoad = true, bool overwrite = false);//(string package, string filepath); public abstract UAReturn InstallCRANPackage(string packagename); public abstract UAReturn InstallReqPackageFromCRAN(string packagename);//27Aug2015 //installs the required packge calling one function from BlueSky R pacakge public abstract UAReturn setCRANMirror(); public abstract UAReturn LoadLocalPackage(string package); public abstract UAReturn LoadPackageFromList(string[] packagenames); public abstract UAReturn UnloadPackages(string[] packagenames); public abstract UAReturn UninstallPackages(string[] packagenames); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerScript : MonoBehaviour { bool activated = false; Renderer rend; private void Start() { rend = GetComponent<Renderer>(); } void HitByRayCast() { activated = true; } private void Update() { if (activated && rend.material.color==Color.white) { rend.material.color = Color.yellow; activated = false; } if (activated && rend.material.color == Color.yellow) { rend.material.color = Color.white; activated = false; } } }
using System; using System.Collections.Generic; using System.Text; namespace RPG_Game { interface ICharacter { // methods int Defend(int enemyattackvalue); int Attack(int option); int CalculateMaxMoveValue( int Level); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Drawing; using System.Windows.Forms; namespace TotalCommanderFull { class Program { static void Main(string[] args) { //add images to list: for (int x = 1; x <= 3; x++) { Images.imagesList.Add(new Images(Path.Combine(Application.StartupPath, $"{Images.buttonNames[x - 1]}.png"), new Point(650, 460), new Point(700, 500))); } //start total commander process: Process process = new Process(); process.StartInfo.FileName = @"c:\program files\totalcmd\TOTALCMD64.EXE"; process.Start(); process.WaitForInputIdle(); //recognize image: string buttonName; int repetition = 0; Point imagePosition; while (!Images.RecognizeImage(out buttonName, out imagePosition) && repetition < 30) //3 sec waiting (30x100ms) { repetition++; System.Threading.Thread.Sleep(100); } ClickCorrectButton(buttonName, imagePosition); //next - settings for images, search location, ... - second winform app -> db or file for both programs } private static void ClickCorrectButton(string buttonName, Point imagePosition) { Point lastCursorPosition = Cursor.Position; int xMargin = 110; int yMargin = 32; switch (buttonName) { default: { Console.WriteLine("Žádný image sample nenalezen."); break; } case "one": //potom asi dictionary<string,point> { SendLeftMouse(new Point(imagePosition.X - xMargin, imagePosition.Y + yMargin)); break; } case "two": { SendLeftMouse(new Point(imagePosition.X + xMargin, imagePosition.Y + yMargin)); break; } case "three": { SendLeftMouse(new Point(imagePosition.X + xMargin, imagePosition.Y + yMargin)); break; } } Cursor.Position = lastCursorPosition; } #region HandleMouse [DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); public enum MouseEventFlags { LEFTDOWN = 0x00000002, LEFTUP = 0x00000004, MIDDLEDOWN = 0x00000020, MIDDLEUP = 0x00000040, RIGHTDOWN = 0x00000008, RIGHTUP = 0x00000010 } /// <summary> /// Send left mouse click on selected position. /// </summary> /// <param name="p">Point for position to send left mouse click.</param> public static void SendLeftMouse(Point p) { Cursor.Position = p; LMBclick(); } /// <summary> /// Send left mouse click. /// </summary> public static void LMBclick() { mouse_event((int)MouseEventFlags.LEFTDOWN | (int)MouseEventFlags.LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); } /// <summary> /// Send middle mouse click. /// </summary> public static void MMBclick() { mouse_event((int)MouseEventFlags.MIDDLEDOWN | (int)MouseEventFlags.MIDDLEUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); } /// <summary> /// Send right mouse click. /// </summary> public static void RMBClick() { mouse_event((int)MouseEventFlags.RIGHTDOWN | (int)MouseEventFlags.RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); } #endregion } }
using Anywhere2Go.DataAccess.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.Object { public class InsurerTaskModel { public Anywhere2Go.DataAccess.Entity.Task Task { get; set; } public TaskProcessLog TaskProcessLog { get; set; } public List<APITaskPicture> TaskPictures { get; set; } public List<TaskPicture> TaskPictureList { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Sql; using System.Data.SqlClient; using System.Configuration; using System.Data; using System.IO; using System.Text; namespace ConsoleApp1 { class Employee { /******************************************************************/ /* Constructor */ /******************************************************************/ public Employee(string employeeID, string firstName, string lastName, string payType, double salary, string startDate, string state, double hours) { EmployeeID = employeeID; FirstName = firstName; LastName = lastName; PayType = payType; Salary = salary; StartDate = startDate; State = state; Hours = hours; } public Employee(string employeeID) { string[] lines = System.IO.File.ReadAllLines(System.IO.Path.GetFullPath("../../Files/Employees.txt")); foreach (string line in lines) { string[] emp = line.Split(','); if(emp[0] == employeeID) { EmployeeID = emp[0]; FirstName = emp[1]; LastName = emp[2]; PayType = emp[3]; Salary = Convert.ToDouble(emp[4]); StartDate = emp[5]; State = emp[6]; Hours = Convert.ToDouble(emp[7]); break; } } } /******************************************************************/ /* Attributes */ /******************************************************************/ public string EmployeeID{ get;} public string FirstName { get; } public string LastName { get; } public string PayType { get; } public double Salary { get; } public string StartDate { get; } public string State { get; } public double Hours { get; } /******************************************************************/ /* Functions */ /******************************************************************/ public double getGrossPay() { double GrossPay = 0; if(PayType == "S") { GrossPay = Salary / 26; } else if(PayType == "H") { double ExtraOverTime = 0; double OverTime = 0; double Regular = 0; if (Hours > 90) { ExtraOverTime = Hours - 90; OverTime = Hours - ExtraOverTime - 80; Regular = Hours - ExtraOverTime - OverTime; } else if(Hours > 80 && Hours <= 90) { OverTime = Hours - 80; Regular = Hours - OverTime; } else { Regular = Hours; } GrossPay = (ExtraOverTime * Salary) + (OverTime * Salary) + (Regular * Salary); } return GrossPay; } public double getFederalTax() { double GrossPay = getGrossPay(); double FederalTaxRate = 0.15; double FederalTax = 0; FederalTax = GrossPay * FederalTaxRate; return FederalTax; } public double getStateTax() { double GrossPay = getGrossPay(); double StateTaxRate = 0; double StateTax = 0; if (State == "UT" || State == "WY" || State == "NV") { StateTaxRate = 0.05; } else if (State == "CO" || State == "ID" || State == "AZ" || State == "OR") { StateTaxRate = 0.065; } else if (State == "WA" || State == "NM" || State == "TX") { StateTaxRate = 0.07; } StateTax = GrossPay * StateTaxRate; return StateTax; } public double getNetPay() { double NetPay = 0; double GrossPay = getGrossPay(); double FederalTax = getFederalTax(); double StateTax = getStateTax(); NetPay = GrossPay - FederalTax - StateTax; return NetPay; } public int getNumberOfYearsWorked() { int NumberOfYearsWorked = 0; DateTime start = Convert.ToDateTime(StartDate); DateTime current = start; while(current <= DateTime.Now) { current = current.AddYears(1); if(current <= DateTime.Now) { NumberOfYearsWorked++; } } return NumberOfYearsWorked; } } class Program { static void Main(string[] args) { string[] lines = System.IO.File.ReadAllLines(System.IO.Path.GetFullPath("../../Files/Employees.txt")); List<Employee> AllEmployees = new List<Employee>(); foreach(string line in lines) { string[] emp = line.Split(','); string EmployeeID = emp[0]; string FirstName = emp[1]; string LastName = emp[2]; string PayType = emp[3]; double Salary = Convert.ToDouble(emp[4]); string StartDate = emp[5]; string State = emp[6]; double Hours = Convert.ToDouble(emp[7]); AllEmployees.Add(new Employee(EmployeeID, FirstName, LastName, PayType, Salary, StartDate, State, Hours)); } string input = ""; while (input != "0") { Console.WriteLine("Please Choose From The Following Options"); Console.WriteLine("1 - Calculate pay checks for every line in the text file."); Console.WriteLine("2 - Get A list of the top 15% earners sorted by the number or years worked at the company (highest to lowest), then alphabetically by last name then first."); Console.WriteLine("3 - Get A list of all states with median time worked, median net pay, and total state taxes paid."); Console.WriteLine("4 - Run all Reports."); Console.WriteLine("5 - Get Employee By ID"); Console.WriteLine("0 - To Exit Program."); Console.WriteLine(""); input = Console.ReadLine(); Console.WriteLine(""); if (input == "1") { Console.WriteLine("Generating Report..."); getPayChecks(AllEmployees); Console.WriteLine(""); Console.WriteLine("Report is Saved on Your Desktop!"); Console.WriteLine(""); } else if(input == "2") { Console.WriteLine("Generating Report..."); getTop15Percent(AllEmployees); Console.WriteLine(""); Console.WriteLine("Report is Saved on Your Desktop!"); Console.WriteLine(""); } else if (input == "3") { Console.WriteLine("Generating Report..."); getStateInfo(AllEmployees); Console.WriteLine(""); Console.WriteLine("Report is Saved on Your Desktop!"); Console.WriteLine(""); } else if (input == "4") { Console.WriteLine("Generating Reports..."); getPayChecks(AllEmployees); Console.WriteLine(""); Console.WriteLine("PayChecks Completed..."); Console.WriteLine(""); getTop15Percent(AllEmployees); Console.WriteLine(""); Console.WriteLine("Top15Percent Completed..."); Console.WriteLine(""); getStateInfo(AllEmployees); Console.WriteLine(""); Console.WriteLine("StateInfo Completed..."); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Reports are Saved on Your Desktop!"); Console.WriteLine(""); } else if (input == "5") { Console.WriteLine("What is the Employee ID?"); string id = Console.ReadLine(); Console.WriteLine("Getting Employee..."); Employee employee = getEmployeeByID(id); if(employee.EmployeeID != null) { Console.WriteLine(""); Console.WriteLine("Here Is Some Information On The Employee..."); Console.WriteLine("Employee ID: " + employee.EmployeeID); Console.WriteLine("First Name: " + employee.FirstName); Console.WriteLine("Last Name: " + employee.LastName); Console.WriteLine("Pay Type: " + employee.PayType); Console.WriteLine("Salary: " + employee.Salary.ToString("$#,##0.00")); Console.WriteLine("Start Date: " + employee.StartDate); Console.WriteLine("State of Residence: " + employee.State); Console.WriteLine("Number of Hours Worked in a 2 Week Period: " + employee.Hours.ToString("###0.00")); Console.WriteLine("Gross Pay: " + employee.getGrossPay().ToString("$#,##0.00")); Console.WriteLine("Federal Taxes: " + employee.getFederalTax().ToString("$#,##0.00")); Console.WriteLine("State Taxes: " + employee.getStateTax().ToString("$#,##0.00")); Console.WriteLine("Net Pay: " + employee.getNetPay().ToString("$#,##0.00")); Console.WriteLine(""); } else { Console.WriteLine(""); Console.WriteLine("That Employee Does Not Exists!"); } } else if (input == "0") { Console.WriteLine("Good Bye!"); } else { Console.WriteLine("That Was Not A Valid Response!"); Console.WriteLine(""); } Console.WriteLine("Press Enter To Continue..."); Console.ReadLine(); Console.Clear(); } } static Employee getEmployeeByID(string EmployeeID) { Employee employee = new Employee(EmployeeID); return employee; } static void getPayChecks(List<Employee> AllEmployees) { DataTable dt = new DataTable(); dt.Columns.Add("EmployeeID", Type.GetType("System.String")); dt.Columns.Add("FirstName", Type.GetType("System.String")); dt.Columns.Add("LastName", Type.GetType("System.String")); dt.Columns.Add("GrossPay", Type.GetType("System.Double")); dt.Columns.Add("FederalTax", Type.GetType("System.Double")); dt.Columns.Add("StateTax", Type.GetType("System.Double")); dt.Columns.Add("NetPay", Type.GetType("System.Double")); foreach(Employee employee in AllEmployees) { DataRow dtRow = dt.NewRow(); dtRow["EmployeeID"] = employee.EmployeeID; dtRow["FirstName"] = employee.FirstName; dtRow["LastName"] = employee.LastName; dtRow["GrossPay"] = employee.getGrossPay(); dtRow["FederalTax"] = employee.getFederalTax(); dtRow["StateTax"] = employee.getStateTax(); dtRow["NetPay"] = employee.getNetPay(); dt.Rows.Add(dtRow); } dt.DefaultView.Sort = "GrossPay DESC"; dt = dt.DefaultView.ToTable(); using (StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/PayChecks.txt")) { for (int row = 0; row < dt.Rows.Count; row++) { StringBuilder output = new StringBuilder(); for (int col = 0; col < dt.Columns.Count; col++) { if (col < 3) { output.Append(dt.Rows[row][col].ToString()); } else { output.Append(((double)dt.Rows[row][col]).ToString("$#,##0.00")); } if (col != dt.Columns.Count - 1) { output.Append(", "); } } sw.WriteLine(output.ToString()); output.Clear(); } } } static void getTop15Percent(List<Employee> AllEmployees) { DataTable dt = new DataTable(); dt.Columns.Add("FirstName", Type.GetType("System.String")); dt.Columns.Add("LastName", Type.GetType("System.String")); dt.Columns.Add("NumberOfYearsWorked", Type.GetType("System.Int32")); dt.Columns.Add("GrossPay", Type.GetType("System.Double")); foreach (Employee employee in AllEmployees) { DataRow dtRow = dt.NewRow(); dtRow["FirstName"] = employee.FirstName; dtRow["LastName"] = employee.LastName; dtRow["NumberOfYearsWorked"] = employee.getNumberOfYearsWorked(); dtRow["GrossPay"] = employee.getGrossPay(); dt.Rows.Add(dtRow); } dt.DefaultView.Sort = "GrossPay DESC"; dt = dt.DefaultView.ToTable(); DataTable Top15Percentdt = new DataTable(); Top15Percentdt.Columns.Add("FirstName", Type.GetType("System.String")); Top15Percentdt.Columns.Add("LastName", Type.GetType("System.String")); Top15Percentdt.Columns.Add("NumberOfYearsWorked", Type.GetType("System.Int32")); Top15Percentdt.Columns.Add("GrossPay", Type.GetType("System.Double")); for (int i = 0; i < (dt.Rows.Count * .15); i++) { DataRow dtRow = Top15Percentdt.NewRow(); dtRow["FirstName"] = dt.Rows[i][0]; dtRow["LastName"] = dt.Rows[i][1]; dtRow["NumberOfYearsWorked"] = dt.Rows[i][2]; dtRow["GrossPay"] = dt.Rows[i][3]; Top15Percentdt.Rows.Add(dtRow); } Top15Percentdt.DefaultView.Sort = "NumberOfYearsWorked DESC, LastName ASC, FirstName ASC"; Top15Percentdt = Top15Percentdt.DefaultView.ToTable(); using (StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Top15Percent.txt")) { for (int row = 0; row < Top15Percentdt.Rows.Count; row++) { StringBuilder output = new StringBuilder(); for (int col = 0; col < Top15Percentdt.Columns.Count; col++) { if (col < 3) { output.Append(Top15Percentdt.Rows[row][col].ToString()); } else { output.Append(((double)Top15Percentdt.Rows[row][col]).ToString("$#,##0.00")); } if (col != Top15Percentdt.Columns.Count - 1) { output.Append(", "); } } sw.WriteLine(output.ToString()); output.Clear(); } } } static void getStateInfo(List<Employee> AllEmployees) { List<string> States = getStates(AllEmployees); States = States.OrderBy(x => x).ToList(); using (StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/StateInfo.txt")) { foreach (string State in States) { StringBuilder output = new StringBuilder(); List<Employee> EmployeesInState = AllEmployees.Where(x => x.State == State).ToList(); double MedianTimeWorked = getMedianTimeWorked(EmployeesInState.OrderBy(x => x.Hours).ToList()); double MedianNetPay = getMedianNetPay(EmployeesInState.OrderBy(x => x.getNetPay()).ToList()); double StateTaxes = getStateTaxes(EmployeesInState); output.Append(State + ", " + MedianTimeWorked.ToString("#,##0.00") + ", " + MedianNetPay.ToString("$#,##0.00") + ", " + StateTaxes.ToString("$#,##0.00")); sw.WriteLine(output.ToString()); output.Clear(); } } } static double getMedianTimeWorked(List<Employee> EmployeesInState) { double MedianTimeWorked = 0; List<double> TimeWorked = new List<double>(); foreach(Employee employee in EmployeesInState) { TimeWorked.Add(employee.Hours); } MedianTimeWorked = getMedian(TimeWorked); return MedianTimeWorked; } static double getMedianNetPay(List<Employee> EmployeesInState) { double MedianNetPay = 0; List<double> NetPay = new List<double>(); foreach (Employee employee in EmployeesInState) { NetPay.Add(employee.Hours); } MedianNetPay = getMedian(NetPay); return MedianNetPay; } static double getStateTaxes(List<Employee> EmployeesInState) { double StateTaxes = 0; foreach (Employee employee in EmployeesInState) { StateTaxes += employee.getStateTax(); } return StateTaxes; } static double getMedian(List<double> values) { double Median = 0; if(values.Count % 2 == 0) { Median = (values[(values.Count / 2)] + values[(values.Count / 2) - 1]) / 2; } else { Median = values[(values.Count / 2)]; } return Median; } static List<string> getStates(List<Employee> AllEmployees) { List<string> States = new List<string>(); foreach (Employee employee in AllEmployees) { string State = employee.State; if (!StateExists(States, State)) { States.Add(State); } } return States; } static bool StateExists(List<string> States, string State) { foreach(string state in States) { if(state == State) { return true; } } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GangOfFourDesignPatterns.Behavioral.State { public class StatePrinting : PrinterState { protected int _pages; public StatePrinting(int pages) { _pages = pages; } public override void Cancel() { Console.WriteLine(" StatePrinting cancelled..."); } public override void Execute(Printer printer) { for (int i=0; i< _pages; i++) { Console.WriteLine($" StatePrinting page {i+1}..."); } //only when all pages are done we go to next state printer.PrinterState = new StatePrintEnded(); } } }
using CoreGraphics; using Foundation; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using UIKit; namespace AsNum.XFControls.iOS { [Register("FlipView")] public class FlipView : UIScrollView { public event EventHandler<FlipViewPosChangedEventArgs> PosChanged = null; public UIPageControl PageControl { get; set; } private List<UIView> Views = new List<UIView>(); private nfloat? TargetX = null; public FlipView() : base() { Initialize(); this.SetUp(); } public FlipView(RectangleF bounds) : base(bounds) { Initialize(); this.SetUp(); } void Initialize() { //BackgroundColor = UIColor.Red; } private void SetUp() { //Hide Scroll bar this.ShowsHorizontalScrollIndicator = false; this.ShowsVerticalScrollIndicator = false; //一次翻一页,自动在边界处停止 this.PagingEnabled = true; this.Bounces = false; this.BouncesZoom = false; this.PageControl = new UIPageControl() { CurrentPageIndicatorTintColor = UIColor.White, PageIndicatorTintColor = UIColor.Gray }; //this.AddSubview(this.PageControl); this.Scrolled += FlipView_Scrolled; } void FlipView_Scrolled(object sender, EventArgs e) { var pageWidth = this.Frame.Size.Width; var page = (int)Math.Floor((this.ContentOffset.X - pageWidth / 2) / pageWidth) + 1; this.PageControl.CurrentPage = page; //Debugger.Log(1, "FlipView", page.ToString()); //左右滑动时,不知道目标页是哪个 //只能设置 Next / GoTo 的目标位置 //滚动到目标位置后,把 TargetX 设置为 null //当左右滑动的时候, TargetX 一直是 null,这样就可以判断到底是滑动,还是程序跳转了 if (this.ContentOffset.X == this.TargetX) { this.TargetX = null; } if (TargetX == null) { if (this.PosChanged != null) { this.PosChanged.Invoke(this, new FlipViewPosChangedEventArgs() { Pos = page }); } } } public void SetItems(List<UIView> items) { if (items == null || items.Count == 0) { } else { for (var i = 0; i < items.Count; i++) { var v = new UIView(); var item = items[i]; this.Views.Add(item); v.AddSubview(item); this.AddSubview(v); } this.PageControl.Pages = items.Count; } } public void UpdateLayout(double width, double height) { this.Frame = new CGRect(0, 0, width, height); this.PageControl.Frame = new CGRect(0, height - 20, width, 20); //this.BringSubviewToFront(this.PageControl); this.SetNeedsLayout(); } public override void LayoutSubviews() { base.LayoutSubviews(); var w = this.Frame.Size.Width; var h = this.Frame.Size.Height; for (var i = 0; i < this.Views.Count; i++) { var v = this.Subviews[i]; var rect = new CGRect(w * i, 0, w, h); v.Frame = rect; } this.ContentSize = new CGSize(w * this.Views.Count, h); } public void Next() { var offset = this.ContentOffset; offset.X += this.Frame.Size.Width; if (offset.X >= this.ContentSize.Width) offset.X = 0; this.TargetX = offset.X; this.SetContentOffset(offset, true); } public void Goto(int idx) { var offset = this.ContentOffset; offset.X = this.Frame.Size.Width * idx; if (offset.X >= this.ContentSize.Width) offset.X = 0; this.TargetX = offset.X; this.SetContentOffset(offset, true); } } public class FlipViewPosChangedEventArgs : EventArgs { public int Pos { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; internal class SumOfElements { private static void Main() { string tmpStr = Console.ReadLine(); int[] aInts = tmpStr.Split().Select(s => int.Parse(s)).ToArray(); List<int> lDiffs = new List<int>(); bool isSum = false; for (int i = 0; i < aInts.Length && !isSum; i++) { int sum = 0; for (int j = 0; j < aInts.Length; j++) { if (j != i) { sum += aInts[j]; } if (j == aInts.Length - 1) { if (sum == aInts[i]) { Console.WriteLine("Yes, sum={0}", sum); isSum = true; } else if (j == (aInts.Length - 1)) { lDiffs.Add(Math.Abs(aInts[i] - sum)); } } } } if (!isSum) { int minDiff = int.MaxValue; for (int i = 0; i < lDiffs.Count; i++) { if (lDiffs[i] < minDiff) { minDiff = lDiffs[i]; } } Console.WriteLine("No, diff={0}", minDiff); } } }
using Arda.Common.ViewModels.Main; using System.Collections.Generic; namespace Arda.Common.Interfaces.Kanban { public interface IActivityRepository { // Return a list of all activities. IEnumerable<ActivityViewModel> GetAllActivities(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassLibraryIofly { /// <summary> /// 点 /// </summary> public class PointD { public double X { get; set; } public double Y { get; set; } public PointD(double x, double y) { X = x; Y = y; } public bool isInBox(RectangleD rec) { if (X >= rec.MinX & X <= rec.MaxX & Y >= rec.MinY & Y <= rec.MaxY) return true; else return false; } public double Distance(PointD point) { double distance = Math.Sqrt((X - point.X) * (X - point.X) + (Y - point.Y) * (Y - point.Y)); return distance; } public bool isNearPoint(PointD point, double tolerance) { double distance = Distance(point); if (distance <= tolerance) return true; else return false; } } /// <summary> /// 圆 /// </summary> public class Circle { public PointD center { get; set; } public double R { get; set; } public Circle(PointD ct, double r) { center = ct; R = r; } } /// <summary> /// 矩形 /// </summary> public class RectangleD { public double MinX { get; set; } public double MinY { get; set; } public double MaxX{ get; set; } public double MaxY{ get; set; } public RectangleD(double minX, double minY, double maxX, double maxY) { if (minX > maxX || minY > maxY) { throw new Exception("Invalid Rectangle"); } else { MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY; } } public double Width { get { return MaxX - MinX; } } public double Height { get { return MaxY - MinY; } } } /// <summary> /// 多边形 /// </summary> public class Polygon { public PointD[] points { get; set; } private List<PointD> _points = new List<PointD>(); //顶点集合 public double MinX, MinY, MaxX, MaxY; public Polygon() { } public Polygon(PointD[] pts) { _points.AddRange(pts); points = pts; } /// <summary> /// 获取顶点数目 /// </summary> public Int32 PointCount { get { return _points.Count; } } /// <summary> /// 选择顶点 /// </summary> /// <param name="index"></param> /// <returns></returns> public PointD GetPointD(int index) { return _points[index]; } /// <summary> /// 添加点 /// </summary> /// <param name="point"></param> public void AddPoint(PointD point) { _points.Add(point); } /// <summary> /// 返回外包矩形 /// </summary> /// <returns></returns> public RectangleD GetEnvelope() { double tempMaxx = _points[0].X, tempMinx = _points[0].X; double tempMaxy = _points[0].Y, tempMiny = _points[0].Y; for (int i = 0; i < _points.Count; i++) { if (_points[i].X >= tempMaxx) { tempMaxx = _points[i].X; } if (_points[i].X <= tempMinx) { tempMinx = _points[i].X; } if (_points[i].Y >= tempMaxy) { tempMaxy = _points[i].Y; } if (_points[i].Y <= tempMiny) { tempMiny = _points[i].Y; } } RectangleD envelope = new RectangleD(tempMinx, tempMiny, tempMaxx, tempMaxy); return envelope; } /// <summary> /// 计算并返回面积 /// </summary> /// <returns></returns> public double GetArea() { double allArea = 0; double tempArea = 0; List<PointD> tempPts = new List<PointD>(); int sPointCount = _points.Count; for (int i = 0; i < sPointCount; i++) //以第一个顶点作为原点,更新坐标系方便运算 { PointD tempPt = new PointD(_points[i].X - _points[0].X, _points[i].Y - _points[0].Y); tempPts.Add(tempPt); } for (int i = 1; i < sPointCount - 1; i++) //向量叉乘算面积 { tempArea = 0.5 * (tempPts[i].X * tempPts[i + 1].Y - tempPts[i + 1].X * tempPts[i].Y); allArea += tempArea; } allArea = Math.Abs(allArea); return allArea; } /// <summary> /// 清空 /// </summary> public void Clear() { _points.Clear(); } /// <summary> /// 复制多边形 /// </summary> /// <returns></returns> public Polygon Clone() { Polygon sPolygon = new Polygon(); int sPointCount = _points.Count; for (int i = 0; i < sPointCount; i++) { PointD sPoint = new PointD(_points[i].X, _points[i].Y); sPolygon.AddPoint(sPoint); } return sPolygon; } /// <summary> /// 判断是否在指定矩形内 /// </summary> /// <param name="rec"></param> /// <returns></returns> public bool isInBox(RectangleD rec) { RectangleD envelope = GetEnvelope(); if (envelope.MinX >= rec.MinX & envelope.MaxX <= rec.MaxX & envelope.MinY >= rec.MinY & envelope.MaxY <= rec.MaxY) return true; else return false; } /// <summary> /// 判断是否包含点 /// </summary> /// <param name="polygon"></param> /// <returns></returns> public bool isContainPoint(PointD checkPoint) { List<PointD> polygonPoints = _points; bool inside = false; int pointCount = polygonPoints.Count; PointD p1, p2; for (int i = 0, j = pointCount - 1; i < pointCount; j = i, i++)//第一个点和最后一个点作为第一条线,之后是第一个点和第二个点作为第二条线,之后是第二个点与第三个点,第三个点与第四个点... { p1 = polygonPoints[i]; p2 = polygonPoints[j]; if (checkPoint.Y < p2.Y) {//p2在射线之上 if (p1.Y <= checkPoint.Y) {//p1正好在射线中或者射线下方 if ((checkPoint.Y - p1.Y) * (p2.X - p1.X) > (checkPoint.X - p1.X) * (p2.Y - p1.Y))//斜率判断,在P1和P2之间且在P1P2右侧 { //射线与多边形交点为奇数时则在多边形之内,若为偶数个交点时则在多边形之外。 //由于inside初始值为false,即交点数为零。所以当有第一个交点时,则必为奇数,则在内部,此时为inside=(!inside) //所以当有第二个交点时,则必为偶数,则在外部,此时为inside=(!inside) inside = (!inside); } } } else if (checkPoint.Y < p1.Y) { //p2正好在射线中或者在射线下方,p1在射线上 if ((checkPoint.Y - p1.Y) * (p2.X - p1.X) < (checkPoint.X - p1.X) * (p2.Y - p1.Y))//斜率判断,在P1和P2之间且在P1P2右侧 { inside = (!inside); } } } return inside; } } /// <summary> /// 多个多边形 /// </summary> public class MultiPolygon { public Polygon[] polygons { get; set; } private List<Polygon> _polygons = new List<Polygon>(); //多边形集合 public double MinX, MinY, MaxX, MaxY; public MultiPolygon() { } public MultiPolygon(Polygon[] pgs) { _polygons.AddRange(pgs); polygons = pgs; } /// <summary> /// 返回多边形数目 /// </summary> /// <returns></returns> public Int32 PolygonCount() { return _polygons.Count; } /// <summary> /// 选择多边形 /// </summary> /// <param name="index"></param> /// <returns></returns> public Polygon GetPolygon(int index) { return _polygons[index]; } /// <summary> /// 添加多边形 /// </summary> /// <param name="pg"></param> public void AddPolygon(Polygon pg) { _polygons.Add(pg); } /// <summary> /// 返回外包矩形 /// </summary> /// <returns></returns> public RectangleD GetEnvelope() { int sPolygonCount = _polygons.Count; RectangleD envelope = _polygons[0].GetEnvelope(); for (int i = 0; i < sPolygonCount; i++) { RectangleD tempRec = _polygons[i].GetEnvelope(); if (tempRec.MaxX >= envelope.MaxX) envelope.MaxX = tempRec.MaxX; if (tempRec.MinX <= envelope.MinX) envelope.MinX = tempRec.MinX; if (tempRec.MaxY >= envelope.MaxY) envelope.MaxY = tempRec.MaxY; if (tempRec.MinY <= envelope.MinY) envelope.MinY = tempRec.MinY; } return envelope; } /// <summary> /// 清空 /// </summary> public void Clear() { _polygons.Clear(); } /// <summary> /// 复制 /// </summary> /// <returns></returns> public MultiPolygon Clone() { MultiPolygon multiPolygon = new MultiPolygon(); int sPolygonCount = _polygons.Count; for (int i = 0; i < sPolygonCount; i++) { Polygon sPolygon = _polygons[i].Clone(); multiPolygon.AddPolygon(sPolygon); } return multiPolygon; } /// <summary> /// 判断是否在指定矩形内 /// </summary> /// <param name="rec"></param> /// <returns></returns> public bool isInBox(RectangleD rec) { RectangleD envelope = GetEnvelope(); if (envelope.MinX >= rec.MinX & envelope.MaxX <= rec.MaxX & envelope.MinY >= rec.MinY & envelope.MaxY <= rec.MaxY) return true; else return false; } /// <summary> /// 判断是否包含点 /// </summary> /// <param name="checkPoint"></param> /// <returns></returns> public bool isContainPoint(PointD checkPoint) { bool isContain = false; for(int i=0;i<_polygons.Count;i++) { if(_polygons[i].isContainPoint(checkPoint)==true) { isContain = true; return isContain; } } return isContain; } } /// <summary> /// 线 /// </summary> public class Polyline { public PointD[] points { get; set; } private List<PointD> _points = new List<PointD>(); //顶点集合 public double MinX, MinY, MaxX, MaxY; public Polyline() { } public Polyline(PointD[] pts) { _points.AddRange(pts); points = pts; } /// <summary> /// 获取顶点数目 /// </summary> public Int32 PointCount { get { return _points.Count; } } /// <summary> /// 选择顶点 /// </summary> /// <param name="index"></param> /// <returns></returns> public PointD GetPointD(int index) { return _points[index]; } /// <summary> /// 添加点 /// </summary> /// <param name="point"></param> public void AddPoint(PointD point) { _points.Add(point); } /// <summary> /// 返回外包矩形 /// </summary> /// <returns></returns> public RectangleD GetEnvelope() { double tempMaxx = _points[0].X, tempMinx = _points[0].X; double tempMaxy = _points[0].Y, tempMiny = _points[0].Y; for (int i = 0; i < _points.Count; i++) { if (_points[i].X >= tempMaxx) { tempMaxx = _points[i].X; } if (_points[i].X <= tempMinx) { tempMinx = _points[i].X; } if (_points[i].Y >= tempMaxy) { tempMaxy = _points[i].Y; } if (_points[i].Y <= tempMiny) { tempMiny = _points[i].Y; } } RectangleD envelope = new RectangleD(tempMinx, tempMiny, tempMaxx, tempMaxy); return envelope; } /// <summary> /// 返回线的长度 /// </summary> /// <returns></returns> public double GetLength() { int sPointCount = _points.Count; double tempLen = 0; double allLen = 0; for (int i = 0; i < sPointCount - 1; i++) { tempLen = (_points[i].X - points[i + 1].X) * (_points[i].X - points[i + 1].X) + (_points[i].Y - points[i + 1].Y) * (_points[i].Y - points[i + 1].Y); tempLen = Math.Sqrt(tempLen); allLen += tempLen; } return allLen; } /// <summary> /// 清空 /// </summary> public void Clear() { _points.Clear(); } /// <summary> /// 复制线 /// </summary> /// <returns></returns> public Polyline Clone() { Polyline sPolyline = new Polyline(); int sPointCount = _points.Count; for (int i = 0; i < sPointCount; i++) { PointD sPoint = new PointD(_points[i].X, _points[i].Y); sPolyline.AddPoint(sPoint); } return sPolyline; } /// <summary> /// 判断是否在指定矩形内 /// </summary> /// <param name="rec"></param> /// <returns></returns> public bool isInBox(RectangleD rec) { RectangleD envelope = GetEnvelope(); if (envelope.MinX >= rec.MinX & envelope.MaxX <= rec.MaxX & envelope.MinY >= rec.MinY & envelope.MaxY <= rec.MaxY) return true; else return false; } /// <summary> /// 判断是否邻近点 /// </summary> /// <param name="point"></param> /// <param name="tolerance"></param> /// <returns></returns> public bool isNearPoint(PointD point, double tolerance) { for(int i=0;i<_points.Count-1;i++) { double dis = 0; PointD p1 = _points[i]; PointD p2 = _points[i + 1]; //PointD ac = new PointD(point.X - p1.X, point.Y - p1.Y); //PointD ab = new PointD(p2.X - p1.X, p2.Y - p1.Y); double ab2 = p1.Distance(p2) * p1.Distance(p2); double f = (point.X - p1.X) * (p2.X - p1.X) + (point.Y - p1.Y) * (p2.Y - p1.Y); if(f<0) dis = point.Distance(p1); else if(f>ab2) dis = point.Distance(p2); else dis = f / ab2; if(dis<=tolerance) { return true; } } return false; } } /// <summary> /// 多条线 /// </summary> public class MultiPolyline { public Polyline[] polylines { get; set; } private List<Polyline> _polylines = new List<Polyline>(); //多边形集合 public double MinX, MinY, MaxX, MaxY; public MultiPolyline() { } public MultiPolyline(Polyline[] pls) { _polylines.AddRange(pls); polylines = pls; } /// <summary> /// 返回线的数目 /// </summary> /// <returns></returns> public Int32 PolylineCount() { return _polylines.Count; } /// <summary> /// 选择线 /// </summary> /// <param name="index"></param> /// <returns></returns> public Polyline GetPolyline(int index) { return _polylines[index]; } /// <summary> /// 添加线 /// </summary> /// <param name="pl"></param> public void AddPolyline(Polyline pl) { _polylines.Add(pl); } /// <summary> /// 返回外包矩形 /// </summary> /// <returns></returns> public RectangleD GetEnvelope() { int sPolylineCount = _polylines.Count; RectangleD envelope = _polylines[0].GetEnvelope(); for (int i = 0; i < sPolylineCount; i++) { RectangleD tempRec = _polylines[i].GetEnvelope(); if (tempRec.MaxX >= envelope.MaxX) envelope.MaxX = tempRec.MaxX; if (tempRec.MinX <= envelope.MinX) envelope.MinX = tempRec.MinX; if (tempRec.MaxY >= envelope.MaxY) envelope.MaxY = tempRec.MaxY; if (tempRec.MinY <= envelope.MinY) envelope.MinY = tempRec.MinY; } return envelope; } /// <summary> /// 清空 /// </summary> public void Clear() { _polylines.Clear(); } /// <summary> /// 复制 /// </summary> /// <returns></returns> public MultiPolyline Clone() { MultiPolyline multiPolyline = new MultiPolyline(); int sPolylineCount = _polylines.Count; for (int i = 0; i < sPolylineCount; i++) { Polyline sPolyline = _polylines[i].Clone(); multiPolyline.AddPolyline(sPolyline); } return multiPolyline; } /// <summary> /// 判断是否在指定矩形内 /// </summary> /// <param name="rec"></param> /// <returns></returns> public bool isInBox(RectangleD rec) { RectangleD envelope = GetEnvelope(); if (envelope.MinX >= rec.MinX & envelope.MaxX <= rec.MaxX & envelope.MinY >= rec.MinY & envelope.MaxY <= rec.MaxY) return true; else return false; } /// <summary> /// 判断是否邻近点 /// </summary> /// <param name="point"></param> /// <param name="tolerance"></param> /// <returns></returns> public bool isNearPoint(PointD point, double tolerance) { for(int i=0;i<_polylines.Count;i++) { if (_polylines[i].isNearPoint(point, tolerance) == true) return true; } return false; } } }
using System; using System.Collections.Generic; namespace MyGame { public interface IAmGene { //Important for Universal combinatino of gene types List<int> GeneValue{ get; } bool IsMutated{get;set;} string Name{ get; } IAmGene CombineGenes(IAmGene g); } }
using System; using System.Collections.Generic; using PterodactylEngine; using Xunit; namespace UnitTestEngine { public class TestFlowchart_CombinationsHelper : TheoryData<bool, List<FlowchartNode>, string> { public TestFlowchart_CombinationsHelper() { Add(true, new List<FlowchartNode>{new FlowchartNode("First", null, 0) }, "```mermaid\r\ngraph LR\r\n```"); Add(true, new List<FlowchartNode>{new FlowchartNode("First", 1) }, "```mermaid\r\ngraph LR\r\n```"); Add(true, new List<FlowchartNode> { new FlowchartNode("Second", new List<FlowchartNode>{new FlowchartNode("First", 0)}, 0) }, "```mermaid\r\ngraph LR\r\nFirst --> Second\r\n```"); Add(false, new List<FlowchartNode> { new FlowchartNode("Second", new List<FlowchartNode>{new FlowchartNode("First", 0)}, 0) }, "```mermaid\r\ngraph TD\r\nFirst --> Second\r\n```"); Add(true, new List<FlowchartNode> { new FlowchartNode("Third", new List<FlowchartNode> { new FlowchartNode("Second", new List<FlowchartNode> { new FlowchartNode("First", 1) }, 0) }, 0) }, "```mermaid\r\ngraph LR\r\nFirst(First) --> Second\r\nSecond --> Third\r\n```"); Add(true, new List<FlowchartNode> { new FlowchartNode("Third", new List<FlowchartNode> { new FlowchartNode("First", 0), new FlowchartNode("Second", 0) }, 0) }, "```mermaid\r\ngraph LR\r\nFirst --> Third\r\nSecond --> Third\r\n```"); Add(true, new List<FlowchartNode> //Diamond example { new FlowchartNode("Third1", new List<FlowchartNode>{new FlowchartNode("Second", new List<FlowchartNode>{new FlowchartNode("First", 0)}, 0)}, 0), new FlowchartNode("Third2", new List<FlowchartNode>{new FlowchartNode("Second", new List<FlowchartNode>{new FlowchartNode("First", 0)}, 0)}, 0), }, "```mermaid\r\ngraph LR\r\nFirst --> Second\r\nSecond --> Third1\r\nSecond --> Third2\r\n```"); } } public class TestFlowchart_Combinations { [Theory] [ClassData(typeof(TestFlowchart_CombinationsHelper))] public void CheckReportCreation(bool direction, List<FlowchartNode> lastNodes, string expected) { Flowchart testObject = new Flowchart(direction, lastNodes); string actual = testObject.Create(); Assert.Equal(expected, actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace _2021KozutiEllenorzes9FSchon { class Program { class Adat { //public static List<Adat> ooplista = new List<Adat>(); // oop-s stílus: a lista az nem egy adat, hanem az "Adatság"-nak a tulajdonsága (Adat classé) public DateTime ido; public string rendszam; public Adat(string[] sortömb) { ido = new DateTime(2021,4,4, int.Parse(sortömb[0]), int.Parse(sortömb[1]), int.Parse(sortömb[2])); rendszam = sortömb[3]; // ooplista.Add(this); } } static void Main(string[] args) { List<Adat> lista = new List<Adat>(); using (StreamReader f = new StreamReader("jarmu.txt",Encoding.Default)) { while (!f.EndOfStream) { lista.Add(new Adat(f.ReadLine().Split(' '))); //new Adat(f.ReadLine().Split(' ')); // oop-s stílus } } // Console.WriteLine(Adat.ooplista.Count); // oop-s stílus Console.WriteLine(lista.Count); /* StreamReader f = new StreamReader("jarmu.txt", Encoding.Default); .... f.Close(); */ /* * foreach (string sor in File.ReadAllLines("jarmu.txt", Encoding.Default)) { } */ // 2. feladat: Console.WriteLine($"2. feladat: {lista.Last().ido.Hour+1-lista[0].ido.Hour} óra hosszat dolgoztak az ellenőrök"); // 3. feladat: Console.WriteLine($"3. feladat:"); Console.WriteLine($"{lista[0].ido.Hour} óra: {lista[0].rendszam}"); for (int i = 1; i < lista.Count; i++) { if (lista[i - 1].ido.Hour < lista[i].ido.Hour) { Console.WriteLine($"{lista[i].ido.Hour} óra: {lista[i].rendszam}"); } } // 4. feladat: Dictionary<char, int> szótár = new Dictionary<char, int>(); szótár['B'] = 0; szótár['K'] = 0; szótár['M'] = 0; szótár[' '] = 0; foreach (Adat kocsi in lista) { // if (kocsi.rendszam[0]=='B' || kocsi.rendszam[0]='K' ...) if ("BKM".Contains(kocsi.rendszam[0])) { szótár[kocsi.rendszam[0]]++; } else// személygépkocsi eset { szótár[' ']++; } } Console.WriteLine($" autóbusz: {szótár['B']} db "); Console.WriteLine($" kamion: {szótár['K']} db "); Console.WriteLine($" motor: {szótár['M']} db "); Console.WriteLine($" személygépkocsi: {szótár[' ']} db "); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Placed on the Player GameObject along with Player Controller /// Handles player interactions with the eggs /// Tracks and changes the bools on the eggs held by the player /// </summary> public class PlayerEggHolder : MonoBehaviour { public Egg EggHolder = null; //null if no egg is held by the player public Transform BugTail; //Reference to player controller private PlayerController _pc; private void Start() { //Get the Team ID from the Player Controller at Start _pc = GetComponent<PlayerController>(); } //Get ref to tail transform from the player model index public void GetTailReference() { BugTail = GetComponentInChildren<PlayerModelIndex>().bugTailRef; } private void OnTriggerEnter(Collider other) { // The player is holding an egg if (EggHolder != null) { //Nest if (other.gameObject.CompareTag("Nest")) { // If the Egg is your team if (EggHolder.TeamID == _pc.TeamID) { EggHolder.OutOfNest = false; // The Egg is in the Nest DropEgg(); // Drop the Egg } } //Generic drop location if (other.gameObject.CompareTag("DropTrigger")) { EggHolder.inWhirlpool = true; // The Egg was dropped into the whirlpool DropEgg(); } } // The player moves into an Egg & is not holding an Egg if (other.gameObject.CompareTag("Egg") && EggHolder == null) { Egg eggToPickup = other.gameObject.GetComponent<Egg>(); // If the Egg is your team & outside the nest & is not being held by a player if (eggToPickup.TeamID == _pc.TeamID && eggToPickup.OutOfNest && !eggToPickup.IsHeld ) { PickupEgg(eggToPickup); } // If the Egg is the other team && not in the whirlpool if (eggToPickup.TeamID != _pc.TeamID && !eggToPickup.inWhirlpool) { PickupEgg(eggToPickup); } } } private void OnTriggerExit(Collider other) { // The player moves out of the Nest & is holding an egg if (other.gameObject.CompareTag("Nest") && EggHolder != null) { EggHolder.OutOfNest = true; // The Egg is outside the Nest } // The player moves out of the whirpool area & is holding an egg if (other.gameObject.CompareTag("DropTrigger") && EggHolder != null) { EggHolder.inWhirlpool = false; // The Egg is outside the Whirlpool } } private void PickupEgg(Egg eggToPickup) { if (_pc.CheckState() != PlayerController.MoveState.Dead && !eggToPickup.IsHeld) { EggHolder = eggToPickup; EggHolder.IsHeld = true; EggHolder.GetComponent<Rigidbody>().isKinematic = true; EggHolder.GetComponent<Collider>().isTrigger = true; //Move the egg to the player tail EggHolder.transform.parent = BugTail.transform; EggHolder.transform.localPosition = new Vector3(0,0,-0.4f); } } public void DropEgg() { if (EggHolder != null) { EggHolder.transform.parent = null; EggHolder.GetComponent<Rigidbody>().isKinematic = false; EggHolder.GetComponent<Collider>().isTrigger = false; EggHolder.IsHeld = false; EggHolder = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; using IRAP.Global; namespace IRAP.Client.GUI.MESPDC.Actions { public class PrintWithLabAction : CustomAction, IUDFAction { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private StringBuilder labFileName = new StringBuilder(); private string cnt = "1"; private StringBuilder var0 = new StringBuilder(); private StringBuilder var1 = new StringBuilder(); private StringBuilder var2 = new StringBuilder(); private StringBuilder var3 = new StringBuilder(); private StringBuilder var4 = new StringBuilder(); private StringBuilder var5 = new StringBuilder(); private StringBuilder var6 = new StringBuilder(); private StringBuilder var7 = new StringBuilder(); private StringBuilder var8 = new StringBuilder(); private StringBuilder var9 = new StringBuilder(); private StringBuilder var10 = new StringBuilder(); private StringBuilder var11 = new StringBuilder(); private StringBuilder var12 = new StringBuilder(); private StringBuilder var13 = new StringBuilder(); private StringBuilder var14 = new StringBuilder(); private StringBuilder var15 = new StringBuilder(); private StringBuilder var16 = new StringBuilder(); private StringBuilder var17 = new StringBuilder(); private StringBuilder var18 = new StringBuilder(); private StringBuilder var19 = new StringBuilder(); [DllImport( "PrintLabel.dll", CharSet = CharSet.Ansi, PreserveSig = false, CallingConvention = CallingConvention.StdCall)] private static extern int PrintLabel( StringBuilder fileName, int cnt, StringBuilder var0, StringBuilder var1, StringBuilder var2, StringBuilder var3, StringBuilder var4, StringBuilder var5, StringBuilder var6, StringBuilder var7, StringBuilder var8, StringBuilder var9, StringBuilder var10, StringBuilder var11, StringBuilder var12, StringBuilder var13, StringBuilder var14, StringBuilder var15, StringBuilder var16, StringBuilder var17, StringBuilder var18, StringBuilder var19); [DllImport( "PrintLabel.dll", CharSet = CharSet.Ansi, PreserveSig = false, CallingConvention = CallingConvention.StdCall)] private static extern void ClearApp(); public PrintWithLabAction(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) : base(actionParams, extendAction, ref tag) { if (actionParams.Attributes["Template"] != null) labFileName.Append(actionParams.Attributes["Template"].Value); if (actionParams.Attributes["Cnt"] != null) cnt = actionParams.Attributes["Cnt"].Value; if (actionParams.Attributes["Var0"] != null) var0.Append(actionParams.Attributes["Var0"].Value); if (actionParams.Attributes["Var1"] != null) var1.Append(actionParams.Attributes["Var1"].Value); if (actionParams.Attributes["Var2"] != null) var2.Append(actionParams.Attributes["Var2"].Value); if (actionParams.Attributes["Var3"] != null) var3.Append(actionParams.Attributes["Var3"].Value); if (actionParams.Attributes["Var4"] != null) var4.Append(actionParams.Attributes["Var4"].Value); if (actionParams.Attributes["Var5"] != null) var5.Append(actionParams.Attributes["Var5"].Value); if (actionParams.Attributes["Var6"] != null) var6.Append(actionParams.Attributes["Var6"].Value); if (actionParams.Attributes["Var7"] != null) var7.Append(actionParams.Attributes["Var7"].Value); if (actionParams.Attributes["Var8"] != null) var8.Append(actionParams.Attributes["Var8"].Value); if (actionParams.Attributes["Var9"] != null) var9.Append(actionParams.Attributes["Var9"].Value); if (actionParams.Attributes["Var10"] != null) var10.Append(actionParams.Attributes["Var10"].Value); if (actionParams.Attributes["Var11"] != null) var11.Append(actionParams.Attributes["Var11"].Value); if (actionParams.Attributes["Var12"] != null) var12.Append(actionParams.Attributes["Var12"].Value); if (actionParams.Attributes["Var13"] != null) var13.Append(actionParams.Attributes["Var13"].Value); if (actionParams.Attributes["Var14"] != null) var14.Append(actionParams.Attributes["Var14"].Value); if (actionParams.Attributes["Var15"] != null) var15.Append(actionParams.Attributes["Var15"].Value); if (actionParams.Attributes["Var16"] != null) var16.Append(actionParams.Attributes["Var16"].Value); if (actionParams.Attributes["Var17"] != null) var17.Append(actionParams.Attributes["Var17"].Value); if (actionParams.Attributes["Var18"] != null) var18.Append(actionParams.Attributes["Var18"].Value); if (actionParams.Attributes["Var19"] != null) var19.Append(actionParams.Attributes["Var19"].Value); } public void DoAction() { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { WriteLog.Instance.Write( string.Format( "调用打印动态链接库 PrintLabel.dll,输入参数:" + "Template={0}|Cnt={1}|Ver0={2}|Var1={3}|Var2={4}" + "Var3={5}|Var4={6}|Var5={7}|Var6={8}|Var7={9}|Var8={10}|"+ "Var9={11}|Var10={12}|Var11={13}|Var12={14}|Var13={15}|"+ "Var14={16}|Var15={17}|Var16={18}|Var17={19}|Var18={20|"+ "Var19={21}", labFileName, cnt, var0, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, var14, var15, var16, var17, var18, var19), strProcedureName); PrintLabel( labFileName, Convert.ToInt32(cnt), var0, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, var14, var15, var16, var17, var18, var19); ClearApp(); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "标签打印", MessageBoxButtons.OK, MessageBoxIcon.Error); WriteLog.Instance.Write(error.Message, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } public class PrintWithLabFactory : CustomActionFactory, IUDFActionFactory { public IUDFAction CreateAction(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) { return new PrintWithLabAction(actionParams, extendAction, ref tag); } } }
using EmployeeTaskMonitor.Core.Entities; using EmployeeTaskMonitor.Core.Models; using EmployeeTaskMonitor.Core.RepositoryInterfaces; using EmployeeTaskMonitor.Core.ServiceInterfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AutoMapper; namespace EmployeeTaskMonitor.Infrastructure.Services { public class EmployeeService : IEmployeeService { private readonly IEmployeeRepository _employeeRepository; private readonly IMapper _mapper; public EmployeeService(IEmployeeRepository employeeRepository) { _employeeRepository = employeeRepository; } public async Task<IEnumerable<EmployeeResponseModel>> GetAllEmployees() { var employees = await _employeeRepository.ListAllAsync(); var employeeCardResponseModel = new List<EmployeeResponseModel>(); foreach(var employee in employees) { var employeeCard = new EmployeeResponseModel(); employeeCard.Id = employee.Id; employeeCard.FirstName = employee.FirstName; employeeCard.LastName = employee.LastName; employeeCard.HiredDate = employee.HiredDate; employeeCardResponseModel.Add(employeeCard); } return employeeCardResponseModel; } public async Task<IEnumerable<TaskResponseModel>> GetTasksByEmployeeId(int Id) { //tasks: IEnumerable<Task> var tasks = await _employeeRepository.GetTasksByEmployee(Id); var taskDetails= new List<TaskResponseModel>(); foreach (var task in tasks) { taskDetails.Add(new TaskResponseModel { Id = task.Id, StartTime = task.StartTime, Deadline = task.Deadline, TaskName = task.TaskName, EmployeeId = task.EmployeeId, }); } return taskDetails; } public async Task<EmployeeResponseModel> GetEmployeeById(int id) { var employeeDetails = new EmployeeResponseModel(); var employee = await _employeeRepository.GetByIdAsync(id); employeeDetails.Id = employee.Id; employeeDetails.FirstName = employee.FirstName; employeeDetails.LastName = employee.LastName; employeeDetails.HiredDate = employee.HiredDate; employeeDetails.Tasks = new List<TaskResponseModel>(); foreach(var task in employee.EmployeeTasks) { employeeDetails.Tasks.Add(new TaskResponseModel { Id = task.Id, EmployeeId = task.EmployeeId, StartTime = task.StartTime, Deadline = task.Deadline }); } return employeeDetails; } public async System.Threading.Tasks.Task AddEmployee(EmployeeRequestModel employeeCreateRequest) { var employee = new Employee { Id = employeeCreateRequest.Id, FirstName = employeeCreateRequest.FirstName, LastName = employeeCreateRequest.LastName, HiredDate = employeeCreateRequest.HiredDate }; var createEmployee = await _employeeRepository.AddAsync(employee); } public async System.Threading.Tasks.Task RemoveEmployee(EmployeeRequestModel employeeRequest) { var employees = await _employeeRepository.ListAsync(e => e.Id == employeeRequest.Id); foreach(var employee in employees) { await _employeeRepository.DeleteAsync(employee); } } public async Task<EmployeeResponseModel> UpdateEmployee(EmployeeRequestModel employeeRequest) { var employee = _mapper.Map<Employee>(employeeRequest); var createdEmployee = await _employeeRepository.UpdateAsync(employee); var response = _mapper.Map<EmployeeResponseModel>(employee); return response; } } }
using System.Data.Entity; using Microsoft.AspNet.Identity.EntityFramework; namespace FacebookClone.Models { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public DbSet<Gender> Genders { get; set; } public DbSet<Post> Posts { get; set; } public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { this.Configuration.LazyLoadingEnabled = false; } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<ApplicationUser>() .Property(u => u.Id) .HasColumnName("UserId"); modelBuilder.Entity<ApplicationUser>() .Property(u => u.FirstName) .IsRequired(); modelBuilder.Entity<ApplicationUser>() .Property(u => u.LastName) .IsRequired(); modelBuilder.Entity<ApplicationUser>() .HasOptional(u => u.ProfilePicture) .WithMany() .Map(m => m.MapKey("ProfilePictureId")); modelBuilder.Entity<ApplicationUser>() .HasRequired(u => u.Gender) .WithMany() .WillCascadeOnDelete(false); modelBuilder.Entity<ApplicationUser>() .Property(u => u.DateOfBirth) .HasColumnType("Date"); modelBuilder.Entity<Post>() .HasOptional(p => p.ParentId) .WithMany(p => p.ChildPost) .Map(m => m.MapKey("ParentId")) .WillCascadeOnDelete(false); modelBuilder.Entity<Post>() .HasRequired(p => p.UserId) .WithMany() .Map(m => m.MapKey("UserId")); modelBuilder.Entity<Gender>() .Property(p => p.Name) .IsRequired(); base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using HealthVault.Sample.Xamarin.Core.Services; using Microsoft.HealthVault.Clients; using Microsoft.HealthVault.Connection; using Microsoft.HealthVault.ItemTypes; using Microsoft.HealthVault.Person; using Microsoft.HealthVault.Vocabulary; using NodaTime.Extensions; using Xamarin.Forms; namespace HealthVault.Sample.Xamarin.Core.ViewModels { public class MedicationEditViewModel : ViewModel { private readonly Medication _medication; private readonly IHealthVaultConnection _connection; public MedicationEditViewModel( Medication medication, IHealthVaultConnection connection, INavigationService navigationService) : base(navigationService) { _medication = medication; _connection = connection; DosageType = medication.Dose?.Display ?? ""; Strength = medication.Strength?.Display ?? ""; ReasonForTaking = medication.Indication?.Text ?? ""; DateStarted = DataTypeFormatter.ApproximateDateTimeToDateTime(medication.DateStarted); SaveCommand = new Command(async () => await SaveAsync(medication)); } private IList<VocabularyItem> _ingredientChoices; public IList<VocabularyItem> IngredientChoices { get { return _ingredientChoices; } set { _ingredientChoices = value; OnPropertyChanged(); } } private VocabularyItem _name; public VocabularyItem Name { get { return _name; } set { _name = value; OnPropertyChanged(); } } public string DosageType { get; set; } public string Strength { get; set; } public string TreatmentProvider { get; set; } public string ReasonForTaking { get; set; } public DateTime DateStarted { get; set; } public ICommand SaveCommand { get; } public override async Task OnNavigateToAsync() { await LoadAsync(async () => { IVocabularyClient vocabClient = _connection.CreateVocabularyClient(); var ingredientChoices = new List<VocabularyItem>(); Vocabulary ingredientVocabulary = null; while (ingredientVocabulary == null || ingredientVocabulary.IsTruncated) { string lastCodeValue = null; if (ingredientVocabulary != null) { if (ingredientVocabulary.Values.Count > 0) { lastCodeValue = ingredientVocabulary.Values.Last().Value; } else { break; } } ingredientVocabulary = await vocabClient.GetVocabularyAsync(new VocabularyKey("RxNorm Active Ingredients", "RxNorm", "09AB_091102F", lastCodeValue)); foreach (string key in ingredientVocabulary.Keys) { ingredientChoices.Add(ingredientVocabulary[key]); } } IngredientChoices = ingredientChoices.OrderBy(c => c.DisplayText).ToList(); if (_medication.Name.Count > 0) { Name = IngredientChoices.FirstOrDefault(c => c.Value == _medication.Name[0]?.Value); } await base.OnNavigateToAsync(); }); } private async Task SaveAsync(Medication medication) { UpdateMedication(medication); IThingClient thingClient = _connection.CreateThingClient(); PersonInfo personInfo = await _connection.GetPersonInfoAsync(); await thingClient.UpdateThingsAsync(personInfo.SelectedRecord.Id, new Collection<Medication> { medication }); await NavigationService.NavigateBackAsync(); } private void UpdateMedication(Medication medication) { if (Name != null) { medication.Name = new CodableValue(Name.DisplayText, Name); } bool empty = string.IsNullOrWhiteSpace(DosageType) && medication.Dose == null; if (!empty) { medication.Dose = new GeneralMeasurement(DosageType); } empty = string.IsNullOrWhiteSpace(Strength) && medication.Strength == null; if (!empty) { medication.Strength = new GeneralMeasurement(Strength); } empty = string.IsNullOrWhiteSpace(ReasonForTaking) && medication.Indication == null; if (!empty) { medication.Indication = new CodableValue(ReasonForTaking); } var inputDateEmpty = DateStarted == DataTypeFormatter.EmptyDate; empty = inputDateEmpty && medication.DateStarted == null; if (!empty) { medication.DateStarted = new ApproximateDateTime(DateStarted.ToLocalDateTime()); } } } }
using Antlr4.Runtime; using Antlr4.Runtime.Tree; using MetaDslx.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MetaDslx.Compiler { public class Antlr4TextSpan : TextSpan { public Antlr4TextSpan() : base(0, 0, 0, 0) { } public Antlr4TextSpan(int startLine, int startPosition, int endLine, int endPosition) : base(startLine, startPosition, endLine, endPosition) { } public Antlr4TextSpan(object node) : this() { IToken token = node as IToken; if (token != null) { this.CreateFromToken(token); } else { IParseTree parseTree = node as IParseTree; if (parseTree != null) { ITerminalNode terminal = parseTree as ITerminalNode; if (terminal != null) { this.CreateFromToken(terminal.Symbol); } else { ParserRuleContext prc = parseTree as ParserRuleContext; this.CreateFromRule(prc); } } } } private void CreateFromToken(IToken token) { if (token == null) return; this.StartLine = token.Line; this.StartPosition = token.Column + 1; string text = token.Text; if (!text.Contains('\n')) { this.EndLine = this.StartLine; this.EndPosition = this.StartPosition + token.Text.Length; } else { this.EndLine = token.Line + token.Text.Count(c => c == '\n'); int index = text.LastIndexOf('\n'); this.EndPosition = text.Length - index; } } private void CreateFromRule(ParserRuleContext rule) { if (rule == null) return; this.StartLine = rule.Start.Line; this.StartPosition = rule.Start.Column + 1; this.EndLine = rule.Stop.Line; this.EndPosition = rule.Stop.Column + rule.Stop.Text.Length + 1; } } }
namespace MovieWebApp.Migrations { using System; using System.Data.Entity.Migrations; public partial class InsertSQLMovieValues : DbMigration { public override void Up() { Sql("INSERT INTO Movies (Name, ReleaseDate, NumberInStock,Genre_Id)" + "VALUES ('The Greatest Showman','12/07/2017',75,7);"); Sql("INSERT INTO Movies (Name, ReleaseDate, NumberInStock,Genre_Id)" + "VALUES ('Interstellar','11/07/2014',50,5);"); Sql("INSERT INTO Movies (Name, ReleaseDate, NumberInStock,Genre_Id)" + "VALUES ('Les MisÚrables','12/25/2012',150,7);"); Sql("INSERT INTO Movies (Name, ReleaseDate, NumberInStock,Genre_Id)" + "VALUES ('Silver Linings Playbook','12/25/2012',275,6);"); } public override void Down() { } } }
using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class GridViewController : DemoController { public ActionResult Preview() { return DemoView("Preview", NorthwindDataProvider.GetEmployees()); } public ActionResult PreviewPartial() { return PartialView("PreviewPartial", NorthwindDataProvider.GetEmployees()); } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Npgsql; namespace Lucky13_Milestone2 { /// <summary> /// Interaction logic for BusinessTips.xaml /// </summary> public partial class BusinessTips : Window { Business selectedBusiness; curUserSelected currentUser; public BusinessTips(Business b, curUserSelected user) { InitializeComponent(); this.selectedBusiness = b; currentUser = user; loadBusinessDetails(); addColums2Grid(); addFriendsColums2Grid(); addTips(); loadFriends(); } private string buildConnectionString() { return "Host = localhost; Username = postgres; Database = 415Project; password = 605027"; } private void addColums2Grid() { DataGridTextColumn col1 = new DataGridTextColumn(); col1.Binding = new Binding("date"); col1.Header = "Date"; col1.Width = 170; tipGrid.Columns.Add(col1); DataGridTextColumn col2 = new DataGridTextColumn(); col2.Binding = new Binding("user_name"); col2.Header = "User Name"; col2.Width = 100; tipGrid.Columns.Add(col2); DataGridTextColumn col3 = new DataGridTextColumn(); col3.Binding = new Binding("likes"); col3.Header = "Likes"; col3.Width = 50; tipGrid.Columns.Add(col3); DataGridTextColumn col4 = new DataGridTextColumn(); col4.Binding = new Binding("tipText"); col4.Header = "Text"; col4.Width = 680; tipGrid.Columns.Add(col4); } private void addFriendsColums2Grid() { //DataGridTextColumn col1 = new DataGridTextColumn(); //col1.Binding = new Binding("user_name"); //col1.Header = "User Name"; //col1.Width = 200; //friendDataGrid.Columns.Add(col1); //DataGridTextColumn col2 = new DataGridTextColumn(); //col2.Binding = new Binding("date"); //col2.Header = "Date"; //col2.Width = 150; //friendDataGrid.Columns.Add(col2); //DataGridTextColumn col3 = new DataGridTextColumn(); //col3.Binding = new Binding("tipText"); //col3.Header = "Text"; //col3.Width = 664; //friendDataGrid.Columns.Add(col3); } private void loadBusinessDetails() { busName.Text = this.selectedBusiness.name; } private void loadFriends() { //List<UserTips> tips = new List<UserTips>(); //friendDataGrid.Items.Clear(); //using (var connection = new NpgsqlConnection(buildConnectionString())) //{ // connection.Open(); // using (var cmd = new NpgsqlCommand()) // { // cmd.Connection = connection; // cmd.CommandText = "SELECT tip.tip_text, users.name, tip.year, tip.month, tip.day, tip.hour, tip.minute, tip.second FROM business, tip, users, (SELECT DISTINCT friends.friend_id FROM friends " + // "WHERE friends.user_id = '" + currentUser.userID + "') as fri WHERE fri.friend_id = users.user_id " + // "AND business.business_id = tip.business_id AND users.user_id = tip.user_id AND tip.business_id = '" + this.selectedBusiness.bid + // "' ;"; // ORDER BY tip.tipdate desc;"; // using (var reader = cmd.ExecuteReader()) // { // while (reader.Read()) // { // DateTime dat = convertToDate(reader.GetInt32(3), reader.GetInt32(4), reader.GetInt32(5), reader.GetInt32(6), reader.GetInt32(7), reader.GetInt32(8)); // var data = new UserTips() // { // date = dat, // user_name = reader.GetString(2), // tipText = reader.GetString(1) // }; // tips.Add(data); // } // tips.Sort((x, y) => y.date.CompareTo(x.date)); // foreach (var tip in tips) // { // friendDataGrid.Items.Add(tip); // } // } // } //} } private DateTime convertToDate(int y, int m, int d, int hr, int min, int sec) { string date = y.ToString() + "-" + m.ToString() + "-" + d.ToString() + " " + hr.ToString() + ":" + min.ToString() + ":" + sec.ToString(); return Convert.ToDateTime(date); } private void addTips() { List<UserTips> tips = new List<UserTips>(); tipGrid.Items.Clear(); using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT tip.day, tip.month, tip.year, tip.hour, tip.minute, tip.second, tip.tip_text, tip.likes, users.name FROM tip, users " + "WHERE tip.business_id = '" + this.selectedBusiness.bid + "' and tip.user_id = users.user_id "; // ORDER BY tip.tipdate desc"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) { DateTime dat = convertToDate(reader.GetInt32(2), reader.GetInt32(1), reader.GetInt32(0), reader.GetInt32(3), reader.GetInt32(4), reader.GetInt32(5)); var data = new UserTips() { //day = reader.GetInt32(0), //month = reader.GetInt32(1), //year = reader.GetInt32(2), //minute = reader.GetInt32(4), // 3 = hour //hour = reader.GetInt32(3), // 5 = sec //second = reader.GetInt32(5), // 4 = min date = dat, tipText = reader.GetString(6), likes = reader.GetInt32(7), user_name = reader.GetString(8) }; tips.Add(data); // tipGrid.Items.Add(data); } tips.Sort((x, y) => y.date.CompareTo(x.date)); foreach(var tip in tips) { tipGrid.Items.Add(tip); } } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } private void tipTextBox_TextChanged(object sender, TextChangedEventArgs e) { } private void addTipButton_Click(object sender, RoutedEventArgs e) { if (currentUser.name == null) { MessageBox.Show("Select a user in 'User Information' before adding tips!"); } else if(tipTextBox.Text.Length < 1) { MessageBox.Show("Must insert tip in 'Insert Tip' text box first!"); } else { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { var te = new UserTips() { user_name = currentUser.name, likes = 0, tipText = tipTextBox.Text, day = DateTime.Now.Day, month = DateTime.Now.Month, year = DateTime.Now.Year, hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second }; cmd.Connection = connection; cmd.CommandText = "INSERT INTO tip(user_id, business_id, tip_text, likes, day, month, year, hour, minute, second) VALUES('" + currentUser.userID + "', '" + selectedBusiness.bid + "', '" + te.tipText + "', " + te.likes.ToString() + ", " + te.day.ToString() + ", " + te.month.ToString() + ", " + te.year.ToString() + ", " + te.hour.ToString() + ", " + te.minute.ToString() + ", " + te.second.ToString() + ");"; try { cmd.ExecuteNonQuery(); te.date = new DateTime(te.year, te.month, te.day, te.hour, te.minute, te.second); tipGrid.Items.Insert(0, te); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } tipTextBox.Clear(); } } private void likeTipButton_Click(object sender, RoutedEventArgs e) { int index = tipGrid.SelectedIndex; if (index == -1) index = 0; UserTips tempTip = tipGrid.Items.GetItemAt(index) as UserTips; using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "UPDATE tip SET likes = likes + 1 WHERE tip_text = '" + tempTip.tipText +"';"; cmd.ExecuteNonQuery(); } connection.Close(); } tipGrid.Items.Remove(tempTip); tempTip.likes += 1; tipGrid.Items.Insert(index, tempTip); } private void tipGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { } } }
using System; using System.Linq; namespace _05_Applied_Arithmetics { public class _05_Applied_Arithmetics { public static void Main() { var numbers = Console.ReadLine().Split().Select(int.Parse).ToArray(); var input = Console.ReadLine(); Func<int, int> addOperation = x => x + 1; Func<int, int> multiplyOperation = x => x * 2; Func<int, int> subtractOperation = x => x - 1; while (input != "end") { if (input == "add") { for (int i = 0; i < numbers.Length; i++) numbers[i] = addOperation(numbers[i]); } else if (input == "multiply") { for (int i = 0; i < numbers.Length; i++) numbers[i] = multiplyOperation(numbers[i]); } else if (input == "subtract") { for (int i = 0; i < numbers.Length; i++) numbers[i] = subtractOperation(numbers[i]); } else if (input == "print") Console.WriteLine(string.Join(" ", numbers)); input = Console.ReadLine(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChildBedConfig { class ModConfig { /*****************************/ /** Properties **/ /*****************************/ public List<Farmer> Farmers { get; set; } /*****************************/ /** Public methods **/ /*****************************/ ///<summary>Constructor, set up the example of the config for players to follow</summary> public ModConfig() { Farmer Default = new Farmer(); Farmers = new List<Farmer>(); Farmers.Add(Default); } } /// <summary> /// Class for the farmer -- we have a list of them in the config /// </summary> class Farmer { /*****************************/ /** Properties **/ /*****************************/ ///<summary>Name of the farmer</summary> public string CharacterName { get; set; } ///<summary>Determines whether or not to show the crib</summary> public bool ShowHomeCrib { get; set; } ///<summary>Determines whether or not to show the bed closest to the crib</summary> public bool ShowHomeBed1 { get; set; } ///<summary>Determines whether or not to show the bed furthest from the crib</summary> public bool ShowHomeBed2 { get; set; } //This is all the same as the above, it just affects the cabins public bool ShowCabinCrib { get; set; } public bool ShowCabinBed1 { get; set; } public bool ShowCabinBed2 { get; set; } /*****************************/ /** Public methods **/ /*****************************/ public Farmer() { CharacterName = "NoName"; ShowHomeCrib = true; ShowHomeBed1 = true; ShowHomeBed2 = true; ShowCabinCrib = true; ShowCabinBed1 = true; ShowCabinBed2 = true; } public Farmer(string name, bool showhcrib, bool showhbed1, bool showhbed2, bool showccrib, bool showcbed1, bool showcbed2) { CharacterName = name; ShowHomeCrib = showhcrib; ShowHomeBed1 = showhbed1; ShowHomeBed2 = showhbed2; ShowCabinCrib = showccrib; ShowCabinBed1 = showcbed1; ShowCabinBed2 = showcbed2; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Coldairarrow.Entity.Sto_BaseInfo { /// <summary> /// Sto_MaterialUnit /// </summary> [Table("Sto_MaterialUnit")] public class Sto_MaterialUnit { /// <summary> /// Id /// </summary> [Key] public String Id { get; set; } /// <summary> /// UnitNum /// </summary> public String UnitNum { get; set; } /// <summary> /// Name /// </summary> public String Name { get; set; } } }
using System.Xml.Serialization; using System.Collections.Generic; using System.IO; using System.Web; namespace DevExpress.Web.Demos { [XmlRoot("Demos")] public class DemosModel { static DemosModel _current; static readonly object _currentLock = new object(); public static DemosModel Current { get { lock(_currentLock) { if(_current == null) { using(Stream stream = File.OpenRead(HttpContext.Current.Server.MapPath("~/App_Data/Demos.xml"))) { XmlSerializer serializer = new XmlSerializer(typeof(DemosModel)); _current = (DemosModel)serializer.Deserialize(stream); } foreach(DemoGroupModel group in _current.Groups) { foreach(DemoModel demo in group.Demos) demo.Group = group; } } return _current; } } } bool _isMvc; bool _isMvcRazor; bool _isRootDemo; string _key; string _title; string _seoTitle; bool _ie7CompatModeRequired; bool _supportsTheming = true; List<DemoGroupModel> _groups = new List<DemoGroupModel>(); string _learnMoreUrl; string _downloadUrl; string _buyUrl; string _videosUrl; string _docUrl; List<DemoModel> _highlighledDemos; [XmlAttribute] public bool IsMvc { get { return _isMvc; } set { _isMvc = value; } } [XmlAttribute] public bool IsMvcRazor { get { return _isMvcRazor; } set { _isMvcRazor = value; } } [XmlAttribute] public bool IsRootDemo { get { return _isRootDemo; } set { _isRootDemo = value; } } [XmlAttribute] public string Key { get { if(_key == null) return ""; return _key; } set { _key = value; } } [XmlAttribute] public string Title { get { if(_title == null) return ""; return _title; } set { _title = value; } } [XmlAttribute] public string SeoTitle { get { if(_seoTitle == null) return ""; return _seoTitle; } set { _seoTitle = value; } } [XmlElement] public string LearnMoreUrl { get { if(_learnMoreUrl == null) return ""; return _learnMoreUrl; } set { if(value != null) value = value.Trim(); _learnMoreUrl = value; } } [XmlElement] public string DownloadUrl { get { if(_downloadUrl == null) return ""; return _downloadUrl; } set { if(value != null) value = value.Trim(); _downloadUrl = value; } } [XmlElement] public string BuyUrl { get { if(_buyUrl == null) return ""; return _buyUrl; } set { if(value != null) value = value.Trim(); _buyUrl = value; } } [XmlElement] public string VideosUrl { get { if(_videosUrl == null) return ""; return _videosUrl; } set { if(value != null) value = value.Trim(); _videosUrl = value; } } [XmlElement] public string DocUrl { get { if(_docUrl == null) return ""; return _docUrl; } set { if(value != null) value = value.Trim(); _docUrl = value; } } [XmlElement("DemoGroup")] public List<DemoGroupModel> Groups { get { return _groups; } } [XmlAttribute] public bool IE7CompatModeRequired { get { return _ie7CompatModeRequired; } set { _ie7CompatModeRequired = value; } } [XmlAttribute] public bool SupportsTheming { get { return _supportsTheming; } set { _supportsTheming = value; } } [XmlIgnore] public List<DemoModel> HighlightedDemos { get { if(_highlighledDemos == null) _highlighledDemos = CreateHighlightedDemos(); return _highlighledDemos; } } public DemoGroupModel FindGroup(string key) { key = key.ToLower(); foreach(DemoGroupModel group in Groups) { if(key == group.Key.ToLower()) return group; } return null; } List<DemoModel> CreateHighlightedDemos() { List<DemoModel> result = new List<DemoModel>(); foreach(DemoGroupModel group in Groups) { foreach(DemoModel demo in group.Demos) { if(demo.HighlightedIndex > -1) result.Add(demo); } } result.Sort(CompareHighlightedDemos); return result; } int CompareHighlightedDemos(DemoModel x, DemoModel y) { return Comparer<int>.Default.Compare(x.HighlightedIndex, y.HighlightedIndex); } public string GetSeoTitle() { if(!string.IsNullOrEmpty(SeoTitle)) return SeoTitle; return Title; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task9_Book_Library { public class task9_Book_Library_Modification { public static void Main() { var input = File.ReadAllLines("input.txt"); var newInput = new string[input.Length-2]; for (int i = 1; i < input.Length-1; i++) { newInput[i-1] = input[i]; } var books = new List<Book>(); foreach (var item in newInput) { var line = item.Split().ToArray(); var newBook = new Book(); newBook.Title = line[0]; newBook.Author = line[1]; newBook.Publisher = line[2]; newBook.ReleaseDate = DateTime.ParseExact(line[3], "dd.MM.yyyy", CultureInfo.InvariantCulture); newBook.Isbn = line[4]; newBook.Price = double.Parse(line[5]); books.Add(newBook); } var dateCheck = DateTime.ParseExact(input[input.Length-1], "dd.MM.yyyy", CultureInfo.InvariantCulture); var sortedBook = books.Where(a => a.ReleaseDate > dateCheck).ToList(); if (File.Exists("output.txt")) { File.Delete("output.txt"); } foreach (var item in sortedBook.OrderBy(a => a.ReleaseDate).ThenBy(b => b.Title)) { File.AppendAllText("output.txt", $"{item.Title} -> {item.ReleaseDate:dd.MM.yyyy}{Environment.NewLine}"); } } public class Book { public string Title { get; set; } public string Author { get; set; } public string Publisher { get; set; } public DateTime ReleaseDate { get; set; } public string Isbn { get; set; } public double Price { get; set; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Linq; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public partial class LocationBindingModel { private int? _id; /// <summary> /// Optional. /// </summary> public int? Id { get { return this._id; } set { this._id = value; } } private double? _latitude; /// <summary> /// Optional. /// </summary> public double? Latitude { get { return this._latitude; } set { this._latitude = value; } } private double? _longitude; /// <summary> /// Optional. /// </summary> public double? Longitude { get { return this._longitude; } set { this._longitude = value; } } private string _name; /// <summary> /// Optional. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _type; /// <summary> /// Optional. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the LocationBindingModel class. /// </summary> public LocationBindingModel() { } /// <summary> /// Deserialize the object /// </summary> public virtual void DeserializeJson(JToken inputObject) { if (inputObject != null && inputObject.Type != JTokenType.Null) { JToken idValue = inputObject["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { this.Id = ((int)idValue); } JToken latitudeValue = inputObject["Latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { this.Latitude = ((double)latitudeValue); } JToken longitudeValue = inputObject["Longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { this.Longitude = ((double)longitudeValue); } JToken nameValue = inputObject["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { this.Name = ((string)nameValue); } JToken typeValue = inputObject["Type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { this.Type = ((string)typeValue); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace _4._4_JSON_serialization { class UpdateJson { public void RemoveCarcter() { //Fazer para todo o sudeste string jsonES = File.ReadAllText(@"C:\Users\henri\Documents\Power BI Desktop\mg_map.json"); JObject data = JObject.Parse(jsonES); //var data = (JObject)JsonConvert.DeserializeObject(jsonES); List<string> listCodMun = data.SelectTokens("objects.Export_Output.geometries[*].properties.COD_IBGE").Select(s => (string)s).ToList();//DEU CERTO!!!! //Utilizar um replace para gravar no arquivo, //ja que nao encontrei uma solucao que atualizasse as propriedades do meu json //Alem disso, removi os acentos StringBuilder jsonAux = new StringBuilder(RemoverAcentuacao(jsonES)); foreach (var item in listCodMun) { jsonAux = jsonAux.Replace(item, item.Substring(0, item.Length - 1)); } File.WriteAllText(@"C:\Users\henri\Documents\Power BI Desktop\mg_map.json", jsonAux.ToString()); Console.WriteLine("Gravado com sucesso"); } protected string RemoverAcentuacao(string text) { return new string(text .Normalize(NormalizationForm.FormD) .Where(ch => char.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark) .ToArray()); } } }
using System; namespace Spool.Harlowe { partial class BuiltInMacros { public Number ceil(double x) => new Number(Math.Ceiling(x)); public Number floor(double x) => new Number(Math.Floor(x)); public Number round(double x) => new Number(Math.Round(x)); public Number num(string x) => new Number(double.Parse(x)); public Number number(string x) => num(x); public Number random(double start, double end) => new Number(Context.Random.Next((int)start, (int)end)); public Number random(double end) => random(0, end); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebApplication1.Models; using WebApplication1.Tasks; namespace WebApplication1.Controllers { public class InvoiceController : ApiController { // GET: api/Invoice/5 public Invoice Get(string id) { var task = new LoadInvoiceTask { Status = InvoiceStatus.Posted, Id = id, }.ExecuteMe(); return task.Invoice; } // POST: api/Invoice public PostedInvoiceResult Post([FromBody]Invoice value) { var task = new PostInvoiceTask { In = value, }; task.Execute(); return new PostedInvoiceResult { Success = task.Out, InvoiceId = task.PostedInvoiceId, }; } // PUT: api/Invoice/5 public void Put(int id, [FromBody]Invoice value) { } // DELETE: api/Invoice/5 public void Delete(int id) { } } }
using Alabo.Cache; using Alabo.Extensions; using Alabo.Helpers; using Alabo.Reflections; using Alabo.Web.Mvc.Attributes; using Alabo.Web.Mvc.ViewModel; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using ZKCloud.Open.DynamicExpression; namespace Alabo.Web.ViewFeatures { /// <summary> /// 获取类的属性以及描述信息 /// </summary> public class ClassDescription { /// <summary> /// The cache /// </summary> private static readonly ConcurrentDictionary<Type, ClassDescription> Cache = new ConcurrentDictionary<Type, ClassDescription>(); /// <summary> /// Initializes a new instance of the <see cref="ClassDescription" /> class. /// </summary> public ClassDescription() { ClassPropertyAttribute = new ClassPropertyAttribute(); } /// <summary> /// Initializes a new instance of the <see cref="ClassDescription" /> class. /// </summary> /// <param name="configType">The configuration 类型.</param> public ClassDescription(Type configType) { Init(configType); } public ClassDescription(string fullName) { var configType = fullName.GetTypeByFullName(); Init(configType); } /// <summary> /// 类型 /// </summary> public Type ClassType { get; private set; } /// <summary> /// 类特性 /// </summary> public ClassPropertyAttribute ClassPropertyAttribute { get; private set; } /// <summary> /// 类所有字段,或者所有属性 /// </summary> public PropertyDescription[] Propertys { get; private set; } /// <summary> /// 表格、表单、列快捷操作链接 /// 方法名必须为:ViewLinks() ,或者动态获取不到 /// </summary> public IEnumerable<ViewLink> ViewLinks { get; set; } private Type GetGenericType(Type configType) { if (configType.IsGenericType) { // 如果是泛型类型获取基类类型 var result = configType.GenericTypeArguments[0]; return result; } return configType; } private void Init(Type configType) { var baseType = GetGenericType(configType); var objectCache = Ioc.Resolve<IObjectCache>(); var cacheKey = $"classDescription_{baseType.FullName.Replace(".", "_")}"; if (!objectCache.TryGet(cacheKey, out CacheClassDescription cacheDescription)) { cacheDescription = Create(baseType); if (cacheDescription != null) { objectCache.Set(cacheKey, cacheDescription); } } if (cacheDescription != null) { ClassType = baseType; ClassPropertyAttribute = cacheDescription.ClassPropertyAttribute; Propertys = cacheDescription.Propertys; ViewLinks = cacheDescription.ViewLinks; } } /// <summary> /// Creates the specified configuration 类型. /// </summary> /// <param name="configType">The configuration 类型.</param> public CacheClassDescription Create(Type configType) { var objectCache = Ioc.Resolve<IObjectCache>(); var cacheKey = $"classDescription_{configType.FullName.Replace(".", "_")}"; if (!objectCache.TryGet(cacheKey, out CacheClassDescription cacheDescription)) { var classType = configType ?? throw new ArgumentNullException(nameof(configType)); var classPropertyAttribute = classType.GetTypeInfo().GetAttributes<ClassPropertyAttribute>().FirstOrDefault(); //如果类特性为空,配置特性 if (classPropertyAttribute == null) { var typeName = classType.Name; classPropertyAttribute = new ClassPropertyAttribute(); classPropertyAttribute.Name = typeName; } //字段特性 var propertys = classType.GetProperties().Select(e => new PropertyDescription(e.DeclaringType, e)) .ToArray(); propertys = propertys.OrderBy(r => r.FieldAttribute.SortOrder).ToArray(); //快捷操作链接 var links = new List<ViewLink>(); var linkMethod = configType.GetMethod("ViewLinks"); if (linkMethod != null) { // 使用动态方法获取链接地址 var config = Activator.CreateInstance(configType); var target = new Interpreter().SetVariable("baseViewModel", config); links = (List<ViewLink>)target.Eval("baseViewModel.ViewLinks()"); } cacheDescription = new CacheClassDescription { ClassType = classType, ClassPropertyAttribute = classPropertyAttribute, Propertys = propertys, ViewLinks = links }; objectCache.Set(cacheKey, cacheDescription); } return cacheDescription; } } /// <summary> /// Class CacheClassDescription. /// </summary> public class CacheClassDescription { /// <summary> /// 类型 /// </summary> internal Type ClassType { get; set; } /// <summary> /// 类特性 /// </summary> internal ClassPropertyAttribute ClassPropertyAttribute { get; set; } /// <summary> /// 类所有字段,或者所有属性 /// </summary> internal PropertyDescription[] Propertys { get; set; } /// <summary> /// 表格、表单、列快捷操作链接 /// 方法名必须为:ViewLinks() ,或者动态获取不到 /// </summary> public IEnumerable<ViewLink> ViewLinks { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using WPF.Model; namespace WPF.Data { class RestAPI { HttpClient client; HttpResponseMessage response; public List<Model.Product> Products; public List<Sepet> sepet; public List<Signup> signup; public List<Category> category; public RestAPI() { client = new HttpClient() { BaseAddress = new Uri("https://localhost:44363/") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); GetData(); } public List<Model.Product> GetProducts() { HttpResponseMessage response = client.GetAsync("api/products").Result; if (response.IsSuccessStatusCode) { var items = response.Content.ReadAsAsync<IEnumerable<Model.Product>>().Result; Products = items as List<Model.Product>; } //else //{ // Application.Current.MainPage.DisplayAlert("Error!", "Error Code" + response.StatusCode + // " : Message -" + response.ReasonPhrase, "Ok"); //} return Products; } public List<Sepet> GetSepet() { HttpResponseMessage response = client.GetAsync("api/sepet").Result; if (response.IsSuccessStatusCode) { var items = response.Content.ReadAsAsync<IEnumerable<Sepet>>().Result; sepet = items as List<Sepet>; } return sepet; } public List<Signup> GetSignup() { HttpResponseMessage response = client.GetAsync("api/signup").Result; if (response.IsSuccessStatusCode) { var items = response.Content.ReadAsAsync<IEnumerable<Signup>>().Result; signup = items as List<Signup>; } return signup; } public List<Category> GetCategory() { HttpResponseMessage response = client.GetAsync("api/categories").Result; if (response.IsSuccessStatusCode) { var items = response.Content.ReadAsAsync<IEnumerable<Signup>>().Result; category = items as List<Category>; } return category; } public void PostSepet(Sepet sepet) { string json = JsonConvert.SerializeObject(sepet, Formatting.Indented); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); var result = client.PostAsync("api/sepet", content).Result; } public void PostSiparis(Siparis siparis) { string json = JsonConvert.SerializeObject(siparis, Formatting.Indented); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); var result = client.PostAsync("api/siparis", content).Result; } public void Signup(Signup signup) { string json = JsonConvert.SerializeObject(signup, Formatting.Indented); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); var result = client.PostAsync("api/signup", content).Result; } public void Login(Login login) { string json = JsonConvert.SerializeObject(login, Formatting.Indented); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); var result = client.PostAsync("api/login", content).Result; } public void DeleteSepetItem(int id) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = new HttpResponseMessage(); string deleteUri = "api/sepet/" + id.ToString(); var result = client.DeleteAsync(deleteUri).Result; } private void GetData() { GetProducts(); GetSepet(); } } }
namespace MVVMExample.Models { public class BusinessLogicService { #region Members public int CalculateValue() { return 42; } #endregion } }
using System; namespace Alabo.Extensions { public static class GuidExtensions { /// <summary> /// 用Guid创建Id,去掉分隔符 /// </summary> public static string GuidId() { return Guid.NewGuid().ToString("N"); } /// <summary> /// 判断Guid是否为空 /// </summary> /// <param name="input"></param> public static bool IsNull(this Guid input) { if (input.ToString() == "00000000-0000-0000-0000-000000000000") { return true; } return false; } /// <summary> /// GUID 的比较,已忽略大小写 /// </summary> /// <param name="input"></param> /// <param name="guid"></param> public static bool IsEqual(this Guid input, Guid guid) { return guid.ToString().ToLower() == input.ToString().ToLower(); } /// <summary> /// GUID 是否不一样,已忽略大小写 /// </summary> /// <param name="input"></param> /// <param name="guid"></param> public static bool IsNotEqual(this Guid input, Guid guid) { return guid.ToString().ToLower() != input.ToString().ToLower(); } } }
using Nac.Common; using Nac.Wpf.Common; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; public static class NacWpfUtils { public static T FindAncestor<T>(DependencyObject dependencyObject) where T : class { DependencyObject target = dependencyObject; do { target = VisualTreeHelper.GetParent(target); } while (target != null && !(target is T)); return target as T; } public static T TryFindParent<T>(DependencyObject child) where T : DependencyObject { DependencyObject parentObject = LogicalTreeHelper.GetParent(child); if (parentObject == null) return null; T parent = parentObject as T; if (parent != null) return parent; else return TryFindParent<T>(parentObject); } public static object ResolveItem(object obj) { FrameworkElement fe = obj as FrameworkElement; return fe?.DataContext; } public static void Refresh(this FrameworkElement fe) { //FrameworkElement fe = obj as FrameworkElement; var dataContext = fe.DataContext; if (dataContext != null) { fe.DataContext = null; fe.DataContext = dataContext; } } public static IEnumerable Controls(Visual control, Predicate<object> pred) { int ChildNumber = VisualTreeHelper.GetChildrenCount(control); for (int i = 0; i <= ChildNumber - 1; i++) { Visual v = (Visual)VisualTreeHelper.GetChild(control, i); if (pred(v)) yield return v; if (VisualTreeHelper.GetChildrenCount(v) > 0) { foreach (var child in Controls(v, pred)) yield return child; } } } public class NacWpfWaitCursor : IDisposable { private Cursor _previousCursor; public NacWpfWaitCursor() { _previousCursor = Mouse.OverrideCursor; Mouse.OverrideCursor = Cursors.Wait; } #region IDisposable Members public void Dispose() { Mouse.OverrideCursor = _previousCursor; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Runtime.Remoting.Messaging; namespace CRL.Attribute { [AttributeUsage(AttributeTargets.Class)] public class TableAttribute : System.Attribute { public override string ToString() { return TableName; } /// <summary> /// 表名 /// </summary> public string TableName { get; set; } /// <summary> /// 默认排序 /// </summary> public string DefaultSort { get; set; } /// <summary> /// 自增主键 /// </summary> internal FieldAttribute PrimaryKey { get; set; } /// <summary> /// 对象类型 /// </summary> public Type Type; DBAdapter.DBAdapterBase _DBAdapter; /// <summary> /// 当前数据库适配器 /// </summary> internal DBAdapter.DBAdapterBase DBAdapter { get { if (_DBAdapter == null) { //throw new Exception("dBAdapter尚未初始化"); } return _DBAdapter; } set { _DBAdapter = value; } } /// <summary> /// 所有字段 /// </summary> internal List<FieldAttribute> Fields = new List<FieldAttribute>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HowLeaky.Tools.DataObjects { public class ProfileData { List<int> jdays; Dictionary<string, List<double>> values; /// <summary> /// /// </summary> public ProfileData() { } /// <summary> /// /// </summary> /// <param name="dates"></param> public void AddDateSeries(string dates) { } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void AddValuesSeries(string name, string value) { } /// <summary> /// /// </summary> /// <param name="datakey"></param> /// <param name="dayindex"></param> /// <param name="today"></param> /// <returns></returns> public double GetValueForDayIndex(string datakey, int dayindex, DateTime today) { UpdateDayIndex(dayindex, today); List<double> data = new List<double>(values[datakey]); int count = values.Count; //for (int i = 0; i < count; ++i) //{ // if (dayindex < jdays[0].days) // { // double m, c, denom; // denom = (double)(jdays[0].days); // if (denom != 0) // m = data[0] / denom; // else // return 0; // c = data[0] - m * jdays[0].days; // return (m * dayindex + c); // } // else if (dayindex == jdays[i].days) // return data[i]; // else if (dayindex < jdays[i].days) // { // double m, c, denom; // denom = (jdays[i].days - jdays[i - 1].days); // if (denom != 0) // m = (data[i] - data[i - 1]) / denom; // else // return 0; // c = data[i] - m * jdays[i].days; // return (m * dayindex + c); // } //} return data[count - 1]; } /// <summary> /// /// </summary> /// <param name="dayindex"></param> /// <param name="today"></param> public void UpdateDayIndex(int dayindex, DateTime today) { try { int last = jdays.Count; //if (last >= 0) //{ // int dayno = today.DayOfYear; //CHECK // if (jdays[last] <= days(366)) // dayindex = dayno; // else // { // int nolaps = (int)(jdays[last].days / 366) + 1; // int resetvalue = nolaps * 365; // if (dayindex >= resetvalue && dayno == 1) // dayindex = 1; // else // dayindex++; // } //} } catch (Exception e) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using Fingo.Auth.DbAccess.Context.Interfaces; using Fingo.Auth.DbAccess.Models; using Fingo.Auth.DbAccess.Repository.Implementation.GenericImplementation; using Fingo.Auth.DbAccess.Repository.Interfaces; using Microsoft.EntityFrameworkCore; namespace Fingo.Auth.DbAccess.Repository.Implementation { public class ProjectRepository : GenericRepository<Project> , IProjectRepository { private readonly IAuthServerContext _db; public ProjectRepository(IAuthServerContext context) : base(context) { _db = context; } public IEnumerable<User> GetAllUsersFromProject(int id) { var d = _db.Set<Project>() .Where(m => m.Id == id) .Include(p => p.ProjectUsers).ThenInclude(u => u.User) .FirstOrDefault(); var users = d.ProjectUsers.Select(m => m.User); return users; } public override Project GetById(int id) { var project = _db.Set<Project>() .Where(m => m.Id == id) .Include(m => m.Information) .Include(m => m.ProjectPolicies) .Include(m => m.ProjectCustomData) .ThenInclude(m => m.UserCustomData) .FirstOrDefault(); return project; } public Project GetByIdWithPolicies(int id) { var project = _db.Set<Project>() .Where(m => m.Id == id) .Include(m => m.ProjectPolicies) .ThenInclude(m => m.UserPolicies) .FirstOrDefault(); return project; } public Project GetByIdWithAll(int id) { var project = _db.Set<Project>() .Where(m => m.Id == id) .Include(m => m.Information) .Include(m => m.ProjectPolicies) .Include(m => m.ProjectCustomData) .ThenInclude(m => m.UserCustomData) .Include(m => m.ProjectUsers) .FirstOrDefault(); return project; } public Project GetByGuid(Guid guid) { var project = _db.Set<Project>() .Where(m => m.ProjectGuid == guid) .Include(m => m.Information) .Include(m => m.ProjectCustomData) .ThenInclude(m => m.UserCustomData) .FirstOrDefault(); return project; } public Project GetByIdWithCustomDatas(int projectId) { var project = _db.Set<Project>() .Where(m => m.Id == projectId) .Include(m => m.ProjectCustomData) .ThenInclude(m => m.UserCustomData) .Include(m => m.ProjectUsers) .FirstOrDefault(); return project; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; [Serializable] public struct Vector3Serializer { public float x; public float y; public float z; public void Fill(Vector3 v3) { x = v3.x; y = v3.y; z = v3.z; } public Vector3 V3 { get { return new Vector3(x, y, z); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using Photon.Realtime; using UnityEngine.UI; public class PlayerListing : MonoBehaviour { [SerializeField] private TMP_Text _text = null; public Player _player = null; public RoomInfo _RoomInfo { get; set; } [SerializeField] private RawImage listingBackground = null; [SerializeField] private Color emptyColor = new Color(), fullColor = new Color(), textFullColor = new Color(), textEmptyColor = new Color(); public void SetPlayerInfo(Player player) { _player = player; if (player.IsMasterClient) { _text.text = player.NickName + " [Room Owner]"; } else { _text.text = player.NickName; } _text.color = textFullColor; listingBackground.color = fullColor; } public void ClearListing() { _player = null; _text.text = "Empty"; _text.color = textEmptyColor; listingBackground.color = emptyColor; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Accessor { class Program { static void Main(string[] args) { XX X = new XX(); Accessor acc = new Accessor(); Console.WriteLine(acc.GetDelegate<XX>("X.Y.Z.T")(X)); Console.ReadKey(); } } }
using FluentAssertions; using ModaTime; using NUnit.Framework; using System; using System.Collections; namespace ModaTime.Test { class IsEqualTests { [SetUp] public void Setup() { } [Test, TestCaseSource("Diffdate_TestCases_returnTrue")] public void SourceDate_Later_TargetDate(DateTime source, DateTime target) { var actual = source.IsEqual(target); actual.Should().BeFalse(); } public static IEnumerable Diffdate_TestCases_returnTrue { get { yield return new TestCaseData(new DateTime(2019, 1, 5), new DateTime(2019, 1, 1)); yield return new TestCaseData(new DateTime(2019, 2, 6), new DateTime(2019, 2, 2)); yield return new TestCaseData(new DateTime(2019, 3, 7), new DateTime(2019, 3, 3)); yield return new TestCaseData(new DateTime(2019, 4, 8), new DateTime(2019, 4, 4)); yield return new TestCaseData(new DateTime(2019, 5, 9), new DateTime(2019, 5, 5)); yield return new TestCaseData(new DateTime(2020, 6, 10), new DateTime(2019, 6, 6)); } } [Test, TestCaseSource("Diffdate_TestCases_returnFalse")] public void SourceDate_Earlier_TargetDate(DateTime source, DateTime target) { var actual = source.IsEqual(target); actual.Should().BeFalse(); } public static IEnumerable Diffdate_TestCases_returnFalse { get { yield return new TestCaseData(new DateTime(2019, 7, 1), new DateTime(2019, 7, 7)); yield return new TestCaseData(new DateTime(2019, 8, 1), new DateTime(2019, 8, 8)); yield return new TestCaseData(new DateTime(2019, 9, 1), new DateTime(2019, 9, 9)); yield return new TestCaseData(new DateTime(2019, 10, 1), new DateTime(2019, 10, 10)); yield return new TestCaseData(new DateTime(2019, 11, 1), new DateTime(2019, 11, 11)); yield return new TestCaseData(new DateTime(2019, 12, 1), new DateTime(2019, 12, 12)); } } [Test, TestCaseSource("Samedate_TestCases")] public void SameDate(DateTime source, DateTime target) { var actual = source.IsEqual(target); actual.Should().BeTrue(); } public static IEnumerable Samedate_TestCases { get { yield return new TestCaseData(new DateTime(2019, 7, 1), new DateTime(2019, 7, 1)); yield return new TestCaseData(new DateTime(2019, 8, 1), new DateTime(2019, 8, 1)); yield return new TestCaseData(new DateTime(2019, 9, 1), new DateTime(2019, 9, 1)); yield return new TestCaseData(new DateTime(2019, 10, 1), new DateTime(2019, 10, 1)); yield return new TestCaseData(new DateTime(2019, 11, 1), new DateTime(2019, 11, 1)); yield return new TestCaseData(new DateTime(2019, 12, 1), new DateTime(2019, 12, 1)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using bellyful_proj.Models; using bellyful_proj_v._0._2.Data; namespace bellyful_proj_v._0._2.Controllers { public class RecipientsController : Controller { private readonly ApplicationDbContext _context; public RecipientsController(ApplicationDbContext context) { _context = context; } // GET: Recipients public async Task<IActionResult> Index() { var applicationDbContext = _context.Recipient.Include(r => r.DietaryRequirementNavigation).Include(r => r.NearestBranchNavigation).Include(r => r.ReferralReasonNavigation).Include(r => r.Referrer); return View(await applicationDbContext.ToListAsync()); } // GET: Recipients/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var recipient = await _context.Recipient .Include(r => r.DietaryRequirementNavigation) .Include(r => r.NearestBranchNavigation) .Include(r => r.ReferralReasonNavigation) .Include(r => r.Referrer) .FirstOrDefaultAsync(m => m.RecipientId == id); if (recipient == null) { return NotFound(); } return View(recipient); } // GET: Recipients/Create public IActionResult Create() { ViewData["DietaryRequirement"] = new SelectList(_context.DietaryRequirement, "DietaryRequirementId", "DietaryName"); ViewData["NearestBranch"] = new SelectList(_context.Branch, "BranchId", "Name"); ViewData["ReferralReason"] = new SelectList(_context.ReferralReason, "ReferralReasonId", "ReferralReasonId"); ViewData["ReferrerId"] = new SelectList(_context.Referrer, "ReferrerId", "FirstName"); return View(); } // POST: Recipients/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("RecipientId,FirstName,LastName,AddressNumStreet,TownCity,Postcode,PhoneNumber,Email,DogOnProperty,NearestBranch,ReferralReason,OtherReferralInfo,AdultsNum,Under5ChildrenNum,_510ChildrenNum,_1117ChildrenNum,DietaryRequirement,OtherAllergyInfo,AdditionalInfo,ReferrerId,CreatedDate")] Recipient recipient) { if (ModelState.IsValid) { _context.Add(recipient); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["DietaryRequirement"] = new SelectList(_context.DietaryRequirement, "DietaryRequirementId", "DietaryName", recipient.DietaryRequirement); ViewData["NearestBranch"] = new SelectList(_context.Branch, "BranchId", "Name", recipient.NearestBranch); ViewData["ReferralReason"] = new SelectList(_context.ReferralReason, "ReferralReasonId", "ReferralReasonId", recipient.ReferralReason); ViewData["ReferrerId"] = new SelectList(_context.Referrer, "ReferrerId", "FirstName", recipient.ReferrerId); return View(recipient); } // GET: Recipients/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var recipient = await _context.Recipient.FindAsync(id); if (recipient == null) { return NotFound(); } ViewData["DietaryRequirement"] = new SelectList(_context.DietaryRequirement, "DietaryRequirementId", "DietaryName", recipient.DietaryRequirement); ViewData["NearestBranch"] = new SelectList(_context.Branch, "BranchId", "Name", recipient.NearestBranch); ViewData["ReferralReason"] = new SelectList(_context.ReferralReason, "ReferralReasonId", "ReferralReasonId", recipient.ReferralReason); ViewData["ReferrerId"] = new SelectList(_context.Referrer, "ReferrerId", "FirstName", recipient.ReferrerId); return View(recipient); } // POST: Recipients/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("RecipientId,FirstName,LastName,AddressNumStreet,TownCity,Postcode,PhoneNumber,Email,DogOnProperty,NearestBranch,ReferralReason,OtherReferralInfo,AdultsNum,Under5ChildrenNum,_510ChildrenNum,_1117ChildrenNum,DietaryRequirement,OtherAllergyInfo,AdditionalInfo,ReferrerId,CreatedDate")] Recipient recipient) { if (id != recipient.RecipientId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(recipient); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RecipientExists(recipient.RecipientId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["DietaryRequirement"] = new SelectList(_context.DietaryRequirement, "DietaryRequirementId", "DietaryName", recipient.DietaryRequirement); ViewData["NearestBranch"] = new SelectList(_context.Branch, "BranchId", "Name", recipient.NearestBranch); ViewData["ReferralReason"] = new SelectList(_context.ReferralReason, "ReferralReasonId", "ReferralReasonId", recipient.ReferralReason); ViewData["ReferrerId"] = new SelectList(_context.Referrer, "ReferrerId", "FirstName", recipient.ReferrerId); return View(recipient); } // GET: Recipients/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var recipient = await _context.Recipient .Include(r => r.DietaryRequirementNavigation) .Include(r => r.NearestBranchNavigation) .Include(r => r.ReferralReasonNavigation) .Include(r => r.Referrer) .FirstOrDefaultAsync(m => m.RecipientId == id); if (recipient == null) { return NotFound(); } return View(recipient); } // POST: Recipients/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var recipient = await _context.Recipient.FindAsync(id); _context.Recipient.Remove(recipient); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool RecipientExists(int id) { return _context.Recipient.Any(e => e.RecipientId == id); } } }
using System; using System.Collections.Generic; using System.Text; namespace UDemyCSharpIntermediate { class Stack { private readonly List<object> _stack = new List<object>(); public Stack() { _stack = new List<object>(); } public void Push (object obj) { if(obj == null) { throw new InvalidOperationException("Cannot Push null value on the stack."); } _stack.Add(obj); } public object Pop() { if(_stack.Count == 0) { throw new InvalidOperationException("Cannot Pop when stack is empty."); } var lastIndex = _stack.Count - 1; var obj = _stack[lastIndex]; _stack.RemoveAt(lastIndex); return obj; } public void Clear() { _stack.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Conarte.Entities { public partial class Fotografia { public void SomeMethod() { this.Autor.Activo = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WarehouseManagement.Cryptography { internal class LoginInfo { internal static readonly string Login = "admin"; internal static readonly string Password = "21232f297a57a5a743894a0e4a801fc3"; } }
using Xunit; namespace Rhino.Mocks.Tests { using Exceptions; public class DotNet35Tests { [Fact] public void NaturalSyntaxForCallingMethods() { IDemo demo = MockRepository.GenerateStrictMock<IDemo>(); demo.Expect(x => x.VoidNoArgs()); demo.VoidNoArgs(); demo.VerifyAllExpectations(); } [Fact] public void NaturalSyntaxForCallingMethods_WithArguments() { IDemo demo = MockRepository.GenerateStrictMock<IDemo>(); demo.Expect(x => x.VoidStringArg("blah")); demo.VoidStringArg("blah"); demo.VerifyAllExpectations(); } [Fact] public void NaturalSyntaxForCallingMethods_WithArguments_WhenNotCalled_WouldFailVerification() { IDemo demo = MockRepository.GenerateStrictMock<IDemo>(); demo.Expect(x => x.VoidStringArg("blah")); Throws.Exception<ExpectationViolationException>("IDemo.VoidStringArg(\"blah\"); Expected #1, Actual #0.",demo.VerifyAllExpectations); } [Fact] public void NaturalSyntaxForCallingMethods_WithArguments_WhenCalledWithDifferentArgument() { IDemo demo = MockRepository.GenerateStrictMock<IDemo>(); demo.Expect(x => x.VoidStringArg("blah")); Throws.Exception<ExpectationViolationException>(@"IDemo.VoidStringArg(""arg""); Expected #0, Actual #1. IDemo.VoidStringArg(""blah""); Expected #1, Actual #0.", () => demo.VoidStringArg("arg")); } [Fact] public void CanCallMethodWithParameters_WithoutSpecifyingParameters_WillAcceptAnyParameter() { IDemo demo = MockRepository.GenerateStrictMock<IDemo>(); demo.Expect(x => x.VoidStringArg("blah")).IgnoreArguments(); demo.VoidStringArg("asd"); demo.VerifyAllExpectations(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CEMAPI.Models { public class ContactDetailsToGenerateSAPCutomerId { public int ContactID { get; set; } public string SAPCustomerID { get; set; } public string CompanyCode { get; set; } public string CustomerName { get; set; } public string Salutation { get; set; } public string ProjectCode { get; set; } public string ProjectSAPCode { get; set; } public string UnitCode { get; set; } public string MobileNo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace trade.client.Marketdata { public enum OrderSide { Undefined, Buy, Sell, Cancel } public enum OrderType { Undefined, ETF_CREATE_OR_REDEEM, /* ETF 申赎*/ LIMIT_PRICE, /* 限价 */ MARKET_IMMEDIATE_OTHER_CANCEL, /* 深圳 即成剩撤 */ MARKET_FIVE_LEVEL_CANCEL, /* 深圳 五档即成剩撤 */ MARKET_ALL_OR_CANCEL, /* 深圳 全成全撤 */ MARKET_OUR_BEST, /* 深圳 本方最优价格 */ MARKET_COUNTERPARTY_BEST, /* 深圳 对方最有价格 */ } public enum Exchange { Undefined, Sh, Sz, } public enum StockType { Stock, ETF, LOF, Repo, } public class SecurityId { private Dictionary<Exchange, string> exchanges = new Dictionary<Exchange, string>() { {Exchange.Sh, "SH"}, {Exchange.Sz, "SZ"} }; public SecurityId(string code, Exchange exchange) { Value = string.Format("{0}.{1}", code, exchanges[exchange]); Code = code; Exchange = exchange; } public string Value { get; private set; } public string Code { get; private set; } public Exchange Exchange { get; private set; } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is SecurityId)) return false; return Value.Equals(((SecurityId)obj).Value); } public override int GetHashCode() { return Value.GetHashCode(); } public override string ToString() { return Value; } } public abstract class Security { public SecurityId SecurityId { set; get; } } public class Stock : Security { public string Name { set; get; } public string PinYin { set; get; } public StockType Type { set; get; } } public class StockQuote : Security { public int TradingDay { set; get; } public int Time { set; get; } public int Status { set; get; } /** 前收 **/ public decimal PreClose { set; get; } /** 开盘价 **/ public decimal Open { set; get; } /** 最高价 **/ public decimal High { set; get; } /** 最低价 **/ public decimal Low { set; get; } /** 最新价 **/ public decimal Match { set; get; } public decimal[] AskPrice { set; get; } public decimal[] AskVol { set; get; } public decimal[] BidPrice { set; get; } public decimal[] BidVol { set; get; } /** 成交笔数 **/ public int NumTrades { set; get; } /** 成交总量 **/ public decimal Volume { set; get; } /** 成交总金额 **/ public decimal Turnover { set; get; } /** 委托买入总量 **/ public decimal TotalBidVol { set; get; } /** 委托卖出总量 **/ public decimal TotalAskVol { set; get; } /** 加权平均委买价格 **/ public decimal WeightedAvgBidPrice { set; get; } /** 加权平均委卖价格 **/ public decimal WeightedAvgAskPrice { set; get; } /** 净值 **/ public decimal IOPV { set; get; } /** 到期收益率 **/ public decimal YieldToMaturity { set; get; } /** 涨停价 **/ public decimal HighLimited { set; get; } /** 跌停价 **/ public decimal LowLimited { set; get; } } public class Transaction : Security { /** 发生日期 **/ public int ActionDay { set; get; } public int Time { set; get; } /** 成交编号 **/ public int Index { set; get; } /** 成交价格 **/ public decimal Price { set; get; } /** 成交数量 **/ public decimal Volume { set; get; } /** 成交金额 **/ public decimal Turnover { set; get; } /** 买卖方向 **/ public OrderSide OrderSide { set; get; } /** 卖方委托号 **/ public int AskOrderId { set; get; } /** 买方委托号 **/ public int BidOrderId { set; get; } } public class Order : Security { /** 发生日期 **/ public int ActionDay { set; get; } /** 发生时间 **/ public int Time { set; get; } /** 委托号 **/ public int OrderId { set; get; } /** 委托价格 **/ public decimal Price { set; get; } /** 委托数量 **/ public decimal Volume { set; get; } /** 委托方向 **/ public OrderSide OrderSide { set; get; } /** 订单类别 **/ public OrderType OrderType { set; get; } } public class OrderQueue : Security { /** 发生日期 **/ public int ActionDay { set; get; } /** 发生时间 **/ public int Time { set; get; } /** 委托类别 **/ public OrderSide OrderSide { set; get; } /** 委托价格 **/ public decimal Price { set; get; } /** 订单数量 **/ public int Orders { set; get; } /** 明细个数 **/ public int ABItems { set; get; } /** 订单明细 **/ public int[] ABVolume { set; get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.DecimalToBinary { public class ConvertDecimal { static int decimalNum; static int current; static string finalNum; static string inBinary; public static void Main() { /* Write a program to convert decimal numbers to their binary representation. */ //read input Console.Write("Enter decimal number : "); decimalNum = int.Parse(Console.ReadLine()); //store the result finalNum = ""; FindInBinary(); } public static void FindInBinary() { //find binary representation while (decimalNum != 0) { current = decimalNum / 2; finalNum += (decimalNum % 2).ToString(); decimalNum = current; } PrintResult(); } public static void PrintResult() { // Reversing to print the result inBinary = ""; for (int i = finalNum.Length - 1; i >= 0; i--) { inBinary = inBinary + finalNum[i]; } Console.WriteLine("In binary: {0}", inBinary); } } }
using System.Collections.Generic; using SecureNetRestApiSDK.Api.Models; using SNET.Core; namespace SecureNetRestApiSDK.Api.Requests { public class CreateCustomerRequest : SecureNetRequest { #region Properties public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string EmailAddress { get; set; } public object SendEmailReceipts { get; set; } public string Notes { get; set; } public object Address { get; set; } public string Company { get; set; } public List<UserDefinedField> UserDefinedFields { get; set; } public DeveloperApplication DeveloperApplication { get; set; } #endregion #region Methods public override string GetUri() { return "api/Customers"; } public override HttpMethodEnum GetMethod() { return HttpMethodEnum.POST; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SeleniumHarness { public static class EmailLog { public static void send() { string fileText = File.ReadAllText(Globals.Instance.fileName); string email = Globals.Instance.email; Mail.send(fileText, email); } } }
using System; using System.Collections.Generic; namespace AMS.Models { public partial class PayScales { public long Id { get; set; } public long DesignationId { get; set; } public decimal Amount { get; set; } public virtual Designations Designation { get; set; } } }
using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Van; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main; using Tests.Pages.Van.Main.Common; using Tests.Pages.Van.Main.Common.DefaultPage; namespace Tests.Projects.Van.ProfileDropdownMenu { public class VanUserSection { private Driver _driver; [SetUp] public void SetUp() { //start browser _driver = new Driver(); } /// <summary> /// Logs in with VAN username and Password and verifies user's full name is displayed on top navagation bar /// verifies clicking on that bar opens up profile menu /// Clicks on each of the options under VAN account section and verifies the corresponding pages opens correctly or perform some actions /// Logs out and make sure the session is logging the user out seccesfully /// </summary> [Ignore("In testing now")] [Test] [Category("van"), Category("van_actionid"), Category("van_login")] public void VanUserSectionTest() { var user = new VanTestUser { UserName = "SajAutotest5", Password = "numero3tres", CommitteeId = "Sajani Test Committee", PinCode = "1212" }; //Logs in with VAN user SajAutotest5 var login = new LoginPage(_driver); login.Login(user); // Clicks on name on top navigation bar, Profile dropdown opens up and clicks on MyInfo link var profileMenuDropdown = new ProfileMenuDropdown(_driver); profileMenuDropdown.ClickProfileMenuDropdownName(); profileMenuDropdown.ClickMyContactInfoLink(); //Clicks on Profile menu dropdown from My Contact Info page and then clicks on Change Password link profileMenuDropdown.ClickProfileMenuDropdownName(); profileMenuDropdown.ClickChangePasswordLink(); //Clicks on Profile menu dropdown from Change Password page and then clicks on Change PIN link profileMenuDropdown.ClickProfileMenuDropdownName(); profileMenuDropdown.ClickChangePinLink(); //Clicks on Profile menu dropdown from Change PIN page and then clicks on MyPaymentOptions link profileMenuDropdown.ClickProfileMenuDropdownName(); profileMenuDropdown.ClickMyPaymentOptionsLink(); //Clicks on Profile Menu Dropdown from My Parment Options page and clicks on Logout link profileMenuDropdown.ClickProfileMenuDropdownName(); profileMenuDropdown.ClickLogOutLink(); } [TearDown] public void TearDown() { _driver.BrowserQuit(); } } }
using AlgorithmProblems.Arrays.ArraysHelper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Sorting { public class RadixSort { /// <summary> /// Counting sort is a good way to achieve linear running time. /// But if the range is n^2 then running time also becomes n^2 /// We can use Radix Sort to achieve a better running time /// /// Steps: 1. Get the maximum value of digits that needs to be considered for all elements from the inputArr /// 2. Do the count sort for all digitpositions starting from the LSB /// 3. if the array has integers<0 then we need to reverse that part of the array /// /// The running time of Radix Sort is O(d*(n+b)), where d is the max number of digits that needs to be considered /// and b is the base in which all the numbers in inputArr is defined, and n is the size of inputArr /// d = logb(K) where K is the max possible value /// so running time is O((n+b)logb(K)) /// K<=n^c where c is const /// so running time is O(nlogb(n)). This becomes linear when n==b /// so if we set the base as n, we get the time complexity as O(n) /// </summary> /// <param name="inputArr"></param> /// <returns></returns> public int[] Sort(int[] inputArr) { // Get the maximum value of digits that needs to be considered for all elements from the inputArr int maxVal = GetMaxDigits(inputArr); // Do the count sort for all digitpositions starting from the LSB for(int i = 0; i<maxVal; i++) { inputArr = CountingSortSubroutine(inputArr, i); } // if the array has integers<0 then we need to reverse that part of the array int maxNegIndex = 0; for(int i =0; i<inputArr.Length; i++) { if(inputArr[i]>=0) { break; } maxNegIndex = i; } for(int i=0; i<=Math.Floor(maxNegIndex/2.0); i++) { int temp = inputArr[i]; inputArr[i] = inputArr[maxNegIndex - i]; inputArr[maxNegIndex - i] = temp; } return inputArr; } /// <summary> /// This is the CountingSort subroutine /// Here we specify the digit position where 0 -> LSB /// and all the elements in the array will be sorted based on the digit at this position /// </summary> /// <param name="inputArr">inputArr which needs to be sorted based on the digit at digitPosition</param> /// <param name="digitPosition"></param> /// <returns></returns> private int[] CountingSortSubroutine(int[] inputArr, int digitPosition) { if (inputArr == null || inputArr.Length == 0) { // Error check throw new ArgumentException("the input array is empty"); } //The range is from -1 to 9 int min = -1; int max = 9; //2. Create an array(countArr) of size equal to the range of the elements in the input array int[] countArr = new int[max - min + 1]; for (int i = 0; i < inputArr.Length; i++) { //3. Whenever we encounter an element in the inputarray increment the element in countArr at the correct index int intVal = GetElementAtPosition(inputArr[i], digitPosition); ++countArr[intVal - (min)]; } //4. Do a cummulative addition on the whole countArr for (int i = 1; i < countArr.Length; i++) { countArr[i] += countArr[i - 1]; } //5. After that scan the input array and foreach element find the value in countArr(which will be the index in the sorted arr) int[] sortedArr = new int[inputArr.Length]; for (int i = inputArr.Length-1; i >=0; i--) { int intVal = GetElementAtPosition(inputArr[i], digitPosition); if (countArr[intVal - min] != 0) { sortedArr[countArr[intVal - (min)] - 1] = inputArr[i]; //6. Decrement the count of the element after adding it to the sorted array --countArr[intVal - (min)]; } else { // this is not a valid countArr throw new Exception("this is not a valid countArr"); } } return sortedArr; } /// <summary> /// Returns the value in the integer at the position calculated from the LSB /// </summary> /// <param name="val"></param> /// <param name="position">position calculated from the LSB</param> /// <returns>Returns the value in the integer at the position calculated from the LSB</returns> private int GetElementAtPosition(int val, int position) { string value = val.ToString(); char charToReturn; if (position <= value.Length-1) { charToReturn = value[value.Length-1 - position]; } else { // if the position for which we need to find the character is out of bounds // then we should return '-' if the integer is less than 0 or else // '0' should be returned of the integer is greater than 0 if(value[0] == '-') { charToReturn = '-'; } else { charToReturn = '0'; } } return (charToReturn == '-') ? -1 : int.Parse(charToReturn.ToString()); } /// <summary> /// Gets the maximum digits which needs to be taken into account /// for example if the max value in the array is 598 hence the max digits is 3 /// we also need to take care of the min value in array /// if -598 is the min value in the array then the max digits is 4 /// </summary> /// <param name="arr"></param> /// <returns></returns> private int GetMaxDigits(int[] arr) { int maxValue = 0; int minValue = 0; for(int i=0; i<arr.Length; i++) { if (maxValue < arr[i]) { maxValue = arr[i]; } if(minValue > arr[i]) { minValue = arr[i]; } } return (minValue.ToString().Length>maxValue.ToString().Length)? minValue.ToString().Length: maxValue.ToString().Length; } public static void TestRadixSort() { RadixSort rs = new RadixSort(); int[] arr = ArrayHelper.CreateArray(10, 10); Console.WriteLine("The unsorted array is as shown below:"); ArrayHelper.PrintArray(arr); arr = rs.Sort(arr); Console.WriteLine("The sorted array is as shown below:"); ArrayHelper.PrintArray(arr); arr = ArrayHelper.CreateArray(10, -5, 10); Console.WriteLine("The unsorted array is as shown below:"); ArrayHelper.PrintArray(arr); arr = rs.Sort(arr); Console.WriteLine("The sorted array is as shown below:"); ArrayHelper.PrintArray(arr); arr = ArrayHelper.CreateArray(10, -50, 100); Console.WriteLine("The unsorted array is as shown below:"); ArrayHelper.PrintArray(arr); arr = rs.Sort(arr); Console.WriteLine("The sorted array is as shown below:"); ArrayHelper.PrintArray(arr); } } }
using System; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Data.Json; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace MVVMJSON { public sealed partial class BattlePage : Page { private Player _player; // reads in vars from Player class private Enemy _enemy; // reads in vars from Enemy class public BattlePage() { this.InitializeComponent(); _player = new Player(); // creates new instance from the player class _enemy = new Enemy(); // creates new instance from the enemy class // PLAYER STARTING STATS _player.CurrentHP = 20; _player.Potions = 1; _player.Experience = 0; _player.Level = 0; _player.ExpNeeded = 100; _player.CurrentAttack = 4; _player.DefEnemies = 0; // ENEMY STARTING STATS _enemy.CurrentEnemyHP = 0; _enemy.CurrentEnemyAttack = 0; // Player Stats Displayed txtCurrentHP.Text = _player.CurrentHP.ToString(); txtPotions.Text = _player.Potions.ToString(); txtEXP_Points.Text = _player.Experience.ToString(); txtLevel.Text = _player.Level.ToString(); txtExpNeeded.Text = _player.ExpNeeded.ToString(); txtCurrentAttack.Text = _player.CurrentAttack.ToString(); // Enemy Stats Displayed txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); // Randomly selects an enemy to start with at the start of the game Random rand = new Random(); int dice = rand.Next(1, 4); // chooses between cases 1 through 4 switch (dice) { case 1: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/Ahriman_398.png")); _enemy.CurrentEnemyAttack = 1; _enemy.CurrentEnemyHP = 4; txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); break; case 2: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/FF_Cactuar_4581.png")); _enemy.CurrentEnemyAttack = 2; _enemy.CurrentEnemyHP = 6; txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); break; case 3: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/a6wjm.jpg")); _enemy.CurrentEnemyAttack = 3; _enemy.CurrentEnemyHP = 8; txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); break; case 4: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/87-Mantisant.png")); _enemy.CurrentEnemyAttack = 4; _enemy.CurrentEnemyHP = 10; break; } } /* public static async Task LoadLocalData() { var file = await Package.Current.InstalledLocation.GetFileAsync("Data/myEnemy.txt"); var result = await FileIO.ReadTextAsync(file); var jEnemyList = JsonArray.Parse(result); CreateEnemyList(jEnemyList); } private static void CreateEnemyList(JsonArray jEnemyList) { foreach (var item in jEnemyList) { var oneEnemy = item.GetObject(); myEnemy nEnemy = new myEnemy(); foreach (var key in oneEnemy.Keys) { IJsonValue value; if (!oneEnemy.TryGetValue(key, out value)) continue; switch (key) { case "breed": nEnemy.enemy = value.GetString(); break; case "category": nEnemy.health = value.GetNumber(); break; case "grooming": nEnemy.attack = value.GetNumber(); break; case "image": nEnemy.image = value.GetString(); break; } // end switch } // end foreach(var key in oneDog.Keys ) //eEnemyList.Add(nEnemy); } // end foreach (var item in jDogList) } protected override void OnNavigatedTo(NavigationEventArgs e) { //await LoadLocalData(); GridViewEnemy.ItemsSource = eEnemyList; } */ // functionality of game when the BATTLE button is clicked on private async void btnBattle_Click(object sender, RoutedEventArgs e) { _enemy.CurrentEnemyHP = _enemy.CurrentEnemyHP - _player.CurrentAttack; // takes away enemy's health equal to player's attack txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); // display new health stat _player.CurrentHP = _player.CurrentHP - _enemy.CurrentEnemyAttack; // takes away player's health equal to enemy's attack txtCurrentHP.Text = _player.CurrentHP.ToString(); // displays new health stat if (_enemy.CurrentEnemyHP <= 0) // if enemy health is 0 { var dialog = new Windows.UI.Popups.MessageDialog("You defeated the enemy!" + " Now on to the next one!" + " You obtained a potion ingredient. 100 Exp earned!"); var result = await dialog.ShowAsync(); // display text in dialog box _player.DefEnemies = _player.DefEnemies + 1; // defeated enemy stat increases by one _player.Potions = _player.Potions + 0.2; // player's potion value goes up by a bit txtPotions.Text = _player.Potions.ToString(); // displays new potion value _enemy.CurrentEnemyHP = _enemy.CurrentEnemyAttack + 6; // enemy attacks goes up by the enemy's attack plus 6 _player.Experience = _player.Experience + 100; // experience increases by 100 // displays new stat values txtEXP_Points.Text = _player.Experience.ToString(); txtCurrentHP.Text = _player.CurrentHP.ToString(); txtCurrentEnemyHP.Text = _enemy.CurrentEnemyHP.ToString(); txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); txtEXP_Points.Text = _player.Experience.ToString(); // randomly selects enemy once again after the previous enemy is defeated Random rand = new Random(); int dice = rand.Next(1, 4); switch (dice) { case 1: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/Ahriman_398.png")); _enemy.CurrentEnemyAttack++; // increments the enemy attack so that it is stronger the next time txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); break; case 2: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/FF_Cactuar_4581.png")); _enemy.CurrentEnemyAttack++; txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); break; case 3: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/a6wjm.jpg")); _enemy.CurrentEnemyAttack++; txtCurrentEnemyAttack.Text = _enemy.CurrentEnemyAttack.ToString(); break; case 4: imgEnemy.Source = new BitmapImage(new Uri("ms-appx:/Images/EnemyImages/87-Mantisant.png")); break; } } if (_player.CurrentHP <= 0) // if the player is defeated and health hits 0 { var dialog = new Windows.UI.Popups.MessageDialog("You Have Been Slain. To Bad! The good news is you defeated " + _player.DefEnemies + " enemies! :D"); var result = await dialog.ShowAsync(); Frame.Navigate(typeof(MainPage)); // displays the above message and sends the player back to the home page of the app } } // button to level up the player private async void btnLevelUp_Click(object sender, RoutedEventArgs e) { // if experience is more than what is required if (_player.Experience >= _player.ExpNeeded) { // takes away req experience from current experience _player.Experience = _player.Experience - _player.ExpNeeded; txtEXP_Points.Text = _player.Experience.ToString(); // req exp for next time increases by 100 _player.ExpNeeded = _player.ExpNeeded + 100; txtExpNeeded.Text = _player.ExpNeeded.ToString(); // player level increments by one _player.Level++; txtLevel.Text = _player.Level.ToString(); // increases attack of player by 2 _player.CurrentAttack = _player.CurrentAttack + 2; txtCurrentAttack.Text = _player.CurrentAttack.ToString(); // current player's hp increases by its base plus 5 more for every level they are _player.CurrentHP = 20 + (5 * _player.Level); var dialog = new Windows.UI.Popups.MessageDialog("You have leveled up to Level " + _player.Level + " Your Attack is now " + _player.CurrentAttack + " and Health is now at " + _player.CurrentHP); var result = await dialog.ShowAsync(); // displays message to confirm that the player has leveled up txtCurrentHP.Text = _player.CurrentHP.ToString(); } else { var dialog = new Windows.UI.Popups.MessageDialog("You need more experience!"); var result = await dialog.ShowAsync(); // displays message to say you don't have enough exp } } private async void btnPotion_Click(object sender, RoutedEventArgs e) { if (_player.Potions <= 0.99) // when you have less than 1 potion in your inventoru { var dialog = new Windows.UI.Popups.MessageDialog("You have no potions in your inventory"); var result = await dialog.ShowAsync(); // message is displayed saying that you don't have any } else { var dialog = new Windows.UI.Popups.MessageDialog("You have increased your health by 20"); var result = await dialog.ShowAsync(); // message is displayed saying you have increase your health _player.CurrentHP = _player.CurrentHP + 20; // health increases by 20 txtCurrentHP.Text = _player.CurrentHP.ToString(); if(_player.CurrentHP >= 20) // if health goes above 20 { _player.CurrentHP = 20 + (5 * _player.DefEnemies); // health = 20 plus 5 for every level the player is txtCurrentHP.Text = _player.CurrentHP.ToString(); } txtCurrentHP.Text = _player.CurrentHP.ToString(); // updates player's stat _player.Potions = _player.Potions - 1; // takes away a potion txtPotions.Text = _player.Potions.ToString(); } } private void btnSaveGame_Click(object sender, RoutedEventArgs e) { //Player playerdata = new Player(); //playerdata.CURRENT_HP = txtCurrentHP.Text; //SaveToXml.SaveData(playerdata, "save.xml"); } } }
using System.Collections.Generic; namespace Calculator.Domain { public class Calculator { private readonly List<int> operands = new List<int>(); public int Result { get; set; } public void Push(int number) { operands.Add(number); } internal void Add() { Result = operands[0] + operands[1]; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace SecureNetRestApiSDK.Api.Models { public class VaultCustomer { #region Properties [JsonProperty("customerId")] public string CustomerId { get; set; } [JsonProperty("address")] public Address Address { get; set; } [JsonProperty("firstName")] public string FirstName { get; set; } [JsonProperty("lastName")] public string LastName { get; set; } [JsonProperty("phoneNumber")] public string PhoneNumber { get; set; } [JsonProperty("emailAddress")] public string EmailAddress { get; set; } [JsonProperty("sendEmailReceipts")] public bool SendEmailReceipts { get; set; } [JsonProperty("company")] public string Company { get; set; } [JsonProperty("notes")] public string Notes { get; set; } [JsonProperty("userDefinedFields")] public List<UserDefinedField> UserDefinedFields { get; set; } [JsonProperty("paymentMethods")] public List<PaymentMethod> PaymentMethods { get; set; } [JsonProperty("primaryPaymentMethodId")] public string PrimaryPaymentMethodId { get; set; } [JsonProperty("variablePaymentPlans")] public List<VariablePaymentPlan> VariablePaymentPlans { get; set; } [JsonProperty("recurringPaymentPlans")] public List<RecurringPaymentPlan> RecurringPaymentPlans { get; set; } [JsonProperty("installmentPaymentPlans")] public List<InstallmentPaymentPlan> InstallmentPaymentPlans { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Java.Lang; using SQLite; namespace Packaged_Database { public class SQlightDB_Class { static object locker = new object(); private string mdbPath; public SQlightDB_Class(string dbName) { //Creating db if it doesnt already exist mdbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),dbName); var db = new SQLiteConnection(mdbPath); db.CreateTable<Chord> (); } public string path { get { return mdbPath; } set { mdbPath = value; } } public IEnumerable<Chord> GetChords(string Chord_group_cat) { // Should only get chords that match the Chord_group_category // pass to this func var db = new SQLiteConnection(path); lock (locker) { return (from i in db.Table<Chord>() where i.Name.Equals(Chord_group_cat) select i).ToList(); } } public IEnumerable<Chord> GetChords() { var db = new SQLiteConnection(path); lock (locker) { return (from i in db.Table<Chord>() select i).ToList(); } } public Chord GetChord(int id) { var db = new SQLiteConnection(path); lock (locker) { return db.Table<Chord>().FirstOrDefault(x => x.ID == id); } } public int SaveChord(Chord item) { var db = new SQLiteConnection(path); lock (locker) { if (item.ID != 0) { db.Update(item); return item.ID; } else { return db.Insert(item); } } } public int DeleteChord(Chord chord) { var db = new SQLiteConnection(path); lock (locker) { return db.Delete<Chord>(chord.ID); } } public void PrintDataBase() { lock (locker) { using (var db = new SQLite.SQLiteConnection(mdbPath)) { Console.WriteLine("PRINTING DATABASE IF POSSIBLE"); var table = db.Table<Chord>(); foreach (var s in table) { Console.WriteLine(s.ID + " " + s.Name); } } } } } }
using Project_Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project_BLL.Managers { public class TagManager:ManagerBase<Tag> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using WindowsFormsApplication2; using System.IO; /// <summary> /// ZjkDaochu 的摘要说明 /// </summary> public class ZjkDaochu : System.Web.UI.Page { SqlServerDataBase sdb = new SqlServerDataBase(); public ZjkDaochu() { } private DataView dataView(String sql) { DataSet ds = new DataSet(); ds = sdb.Select(sql, null); return ds.Tables[0].DefaultView; } public void SaveToWord(string id, string Saveasfilename) { string strfilename = Server.MapPath("~/Word文档/专家表(空).docx"); string sql = "select * from zjk where zjID='" + id + "'"; DataView dv = dataView(sql); foreach (DataRowView drv in dv) { string zjxm = drv["zjxm"].ToString(); string gzdw = drv["gzdw"].ToString(); string xb = drv["xb"].ToString(); string zjlx = drv["zjlx"].ToString(); string csny = drv["csny"].ToString(); string bxcsly1 = drv["xcsly1"].ToString(); string xlxw = drv["xlxw"].ToString(); string byxx = drv["byxx"].ToString(); string bghm = drv["bghm"].ToString(); string sjh = drv["sjh"].ToString(); string email = drv["email"].ToString(); string xkzy = drv["xkzy"].ToString(); string zjcs = drv["zjcs"].ToString(); zjlx = zjlx.Replace("a", "培训专家 "); zjlx = zjlx.Replace("b", "技术专家 "); zjlx = zjlx.Replace("c", "工程专家 "); zjlx = zjlx.Replace("d", "评审专家 "); string xcsly1 = ""; DataSet ds = new DataSet(); sql = "select value from xueke2 where id='" + bxcsly1 + "'"; ds = sdb.Select(sql, null); if (ds.Tables[0].Rows.Count > 0) { xcsly1 = ds.Tables[0].Rows[0][0].ToString(); if (xcsly1 == "--请选择--") { xcsly1 = ""; } } WordTableRead wr = new WordTableRead(strfilename); wr.Open(); int len = 0; wr.WriteWord(1, 1, 2, zjxm, len); wr.WriteWord(1, 1, 4, gzdw, len); wr.WriteWord(1, 2, 2, xb, len); wr.WriteWord(1, 2, 4, zjlx, len); wr.WriteWord(1, 3, 2, csny, len); wr.WriteWord(1, 3, 4, zjcs, len); wr.WriteWord(1, 4, 2, xlxw, len); wr.WriteWord(1, 4, 4, byxx, len); wr.WriteWord(1, 5, 2, bghm, len); wr.WriteWord(1, 5, 4, sjh, len); wr.WriteWord(1, 6, 2, email, len); wr.WriteWord(1, 6, 4, xkzy, len); wr.WriteWord(1, 7, 2, xcsly1, len); wr.SaveasWord(Saveasfilename); wr.Close(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DialogText { public const string YES = "Yes"; public const string NO = "NO"; public const string CURRENTCY = "dollars"; public const string GR_hello = "Hello"; public const string GR_g_m = "Good Morning"; public const string GR_g_a = "Good Afternoon"; public const string GR_g_e = "Good Evening"; public const string G_i_want = "I want to by "; public const string G_show_price = "How much is it?"; public const string G_i_need= "I need"; public const string G_show_my_money = "How much i have?"; public const string GR_h_a = "How are you?"; public const string A_g = "I am great today."; public const string A_f = "I am fine."; public const string A_n = "Have a nice day."; public const string A_expensive = "Oh that is very expensive. "; public const string G_have_fun = "Have fun shopping today. "; public const string A_total = "Your total is"; public const string Q_all = "Would that be all?"; public const string Q_mean = "What does that mean?"; public const string A_under = "I understand."; public const string Q_repeat = "Can you please repeat?"; public const string A_finish = "I am finished shopping. "; public const string A_scan = "Let me scan your items."; public const string Q_still_buy = "Would you still like to buy it?."; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameplayCanvas : MonoBehaviour { [SerializeField] private List<AbilityButton> _AbilityButtons = new List<AbilityButton>(); void Start() { } void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestingBlazor.Data.Models { public class Product:IDbObject { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public IDbObject MakeNew() { throw new NotImplementedException(); } public void UpdateFrom(IDbObject obj) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using Castle.Windsor; namespace com.Sconit.Service { public interface IReportMgr { List<object> GetRealTimeLocationDetail(string procedureName, SqlParameter[] parameters); List<object> GetHistoryInvAjaxPageData(string procedureName, SqlParameter[] parameters); List<object> GetInventoryAgeAjaxPageData(string procedureName, SqlParameter[] parameters); List<object> GetReportTransceiversAjaxPageData(string procedureName, SqlParameter[] parameters); List<object> GetAuditInspectionPageData(string procedureName, SqlParameter[] parameters);//GetAuditInspectionPageData List<object> GetHuAjaxPageData(string procedureName, SqlParameter[] parameters); } }
using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities.TV { /// <summary> /// Class Episode /// </summary> public class Episode : Video, IHasTrailers, IHasLookupInfo<EpisodeInfo>, IHasSeries { public Episode() { RemoteTrailers = EmptyMediaUrlArray; LocalTrailerIds = new Guid[] {}; RemoteTrailerIds = new Guid[] {}; } public Guid[] LocalTrailerIds { get; set; } public Guid[] RemoteTrailerIds { get; set; } public MediaUrl[] RemoteTrailers { get; set; } /// <summary> /// Gets the season in which it aired. /// </summary> /// <value>The aired season.</value> public int? AirsBeforeSeasonNumber { get; set; } public int? AirsAfterSeasonNumber { get; set; } public int? AirsBeforeEpisodeNumber { get; set; } /// <summary> /// This is the ending episode number for double episodes. /// </summary> /// <value>The index number.</value> public int? IndexNumberEnd { get; set; } public string FindSeriesSortName() { var series = Series; return series == null ? SeriesName : series.SortName; } [IgnoreDataMember] protected override bool SupportsOwnedItems { get { return IsStacked || MediaSourceCount > 1; } } [IgnoreDataMember] public override bool SupportsInheritedParentImages { get { return true; } } [IgnoreDataMember] public override bool SupportsPeople { get { return true; } } [IgnoreDataMember] public int? AiredSeasonNumber { get { return AirsAfterSeasonNumber ?? AirsBeforeSeasonNumber ?? ParentIndexNumber; } } [IgnoreDataMember] public override Folder LatestItemsIndexContainer { get { return Series; } } [IgnoreDataMember] public override Guid? DisplayParentId { get { return SeasonId; } } [IgnoreDataMember] protected override bool EnableDefaultVideoUserDataKeys { get { return false; } } public override double? GetDefaultPrimaryImageAspectRatio() { // hack for tv plugins if (SourceType == SourceType.Channel) { return null; } double value = 16; value /= 9; return value; } public override List<string> GetUserDataKeys() { var list = base.GetUserDataKeys(); var series = Series; if (series != null && ParentIndexNumber.HasValue && IndexNumber.HasValue) { var seriesUserDataKeys = series.GetUserDataKeys(); var take = seriesUserDataKeys.Count; if (seriesUserDataKeys.Count > 1) { take--; } list.InsertRange(0, seriesUserDataKeys.Take(take).Select(i => i + ParentIndexNumber.Value.ToString("000") + IndexNumber.Value.ToString("000"))); } return list; } /// <summary> /// This Episode's Series Instance /// </summary> /// <value>The series.</value> [IgnoreDataMember] public Series Series { get { var seriesId = SeriesId ?? FindSeriesId(); return seriesId.HasValue ? (LibraryManager.GetItemById(seriesId.Value) as Series) : null; } } [IgnoreDataMember] public Season Season { get { var seasonId = SeasonId ?? FindSeasonId(); return seasonId.HasValue ? (LibraryManager.GetItemById(seasonId.Value) as Season) : null; } } [IgnoreDataMember] public bool IsInSeasonFolder { get { return FindParent<Season>() != null; } } [IgnoreDataMember] public string SeriesPresentationUniqueKey { get; set; } [IgnoreDataMember] public string SeriesName { get; set; } [IgnoreDataMember] public string SeasonName { get; set; } public string FindSeriesPresentationUniqueKey() { var series = Series; return series == null ? null : series.PresentationUniqueKey; } public string FindSeasonName() { var season = Season; if (season == null) { if (ParentIndexNumber.HasValue) { return "Season " + ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture); } return "Season Unknown"; } return season.Name; } public string FindSeriesName() { var series = Series; return series == null ? SeriesName : series.Name; } public Guid? FindSeasonId() { var season = FindParent<Season>(); // Episodes directly in series folder if (season == null) { var series = Series; if (series != null && ParentIndexNumber.HasValue) { var findNumber = ParentIndexNumber.Value; season = series.Children .OfType<Season>() .FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == findNumber); } } return season == null ? (Guid?)null : season.Id; } /// <summary> /// Creates the name of the sort. /// </summary> /// <returns>System.String.</returns> protected override string CreateSortName() { return (ParentIndexNumber != null ? ParentIndexNumber.Value.ToString("000 - ") : "") + (IndexNumber != null ? IndexNumber.Value.ToString("0000 - ") : "") + Name; } /// <summary> /// Determines whether [contains episode number] [the specified number]. /// </summary> /// <param name="number">The number.</param> /// <returns><c>true</c> if [contains episode number] [the specified number]; otherwise, <c>false</c>.</returns> public bool ContainsEpisodeNumber(int number) { if (IndexNumber.HasValue) { if (IndexNumberEnd.HasValue) { return number >= IndexNumber.Value && number <= IndexNumberEnd.Value; } return IndexNumber.Value == number; } return false; } [IgnoreDataMember] public override bool SupportsRemoteImageDownloading { get { if (IsMissingEpisode) { return false; } return true; } } [IgnoreDataMember] public bool IsMissingEpisode { get { return LocationType == LocationType.Virtual; } } [IgnoreDataMember] public Guid? SeasonId { get; set; } [IgnoreDataMember] public Guid? SeriesId { get; set; } public Guid? FindSeriesId() { var series = FindParent<Series>(); return series == null ? (Guid?)null : series.Id; } public override IEnumerable<Guid> GetAncestorIds() { var list = base.GetAncestorIds().ToList(); var seasonId = SeasonId; if (seasonId.HasValue && !list.Contains(seasonId.Value)) { list.Add(seasonId.Value); } return list; } public override IEnumerable<FileSystemMetadata> GetDeletePaths() { return new[] { new FileSystemMetadata { FullName = Path, IsDirectory = IsFolder } }.Concat(GetLocalMetadataFilesToDelete()); } public override UnratedItem GetBlockUnratedType() { return UnratedItem.Series; } public EpisodeInfo GetLookupInfo() { var id = GetItemLookupInfo<EpisodeInfo>(); var series = Series; if (series != null) { id.SeriesProviderIds = series.ProviderIds; id.SeriesDisplayOrder = series.DisplayOrder; } id.IsMissingEpisode = IsMissingEpisode; id.IndexNumberEnd = IndexNumberEnd; return id; } public override bool BeforeMetadataRefresh(bool replaceAllMetdata) { var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); if (!IsLocked) { if (SourceType == SourceType.Library) { try { if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetdata)) { hasChanges = true; } } catch (Exception ex) { Logger.ErrorException("Error in FillMissingEpisodeNumbersFromPath. Episode: {0}", ex, Path ?? Name ?? Id.ToString()); } } } return hasChanges; } } }
namespace MySurveys.Web.Areas.Surveys.ViewModels.Details { using Models; using MvcTemplate.Web.Infrastructure.Mapping; public class PossibleAnswerViewModel : IMapFrom<PossibleAnswer> { public int Id { get; set; } public string Content { get; set; } } }
//public class HintCommandInterceptor : DbCommandInterceptor //{ // public override InterceptionResult ReaderExecuting( // DbCommand command, // CommandEventData eventData, // InterceptionResult result) // { // // Manipulate the command text, etc. here... // command.CommandText += " OPTION (OPTIMIZE FOR UNKNOWN)"; // return result; // } //} //services.AddDbContext(b => b // .UseSqlServer(connectionString) // .AddInterceptors(new HintCommandInterceptor()));
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.Models; using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Extensions; using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.ServiceBus; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement; using OrchardCore.Title.Models; namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.ServiceBus.Converters { public static class Helper { public static async Task<IEnumerable<ContentItem>> GetContentItemsAsync(dynamic contentPicker, IContentManager contentManager) { if (contentPicker != null) { var contentItemIds = (JArray)contentPicker.ContentItemIds; if (contentItemIds.Any()) { var idList = contentItemIds.Select(c => c.Value<string>()); var contentItems = await contentManager.GetAsync(idList); return contentItems; } } return Enumerable.Empty<ContentItem>(); } public static async Task<IEnumerable<string>> GetContentItemNamesAsync(dynamic contentPicker, IContentManager contentManager) { IList<string> contentItemNames = new List<string>(); if (contentPicker != null) { var contentItemIds = (JArray)contentPicker.ContentItemIds; if (contentItemIds.Any()) { var idList = contentItemIds.Select(c => c.Value<string>()); var contentItems = await contentManager.GetAsync(idList); foreach (var item in contentItems) { contentItemNames.Add(item.ContentItem.DisplayText); } return contentItemNames; } } return Enumerable.Empty<string>(); } public static async Task<IEnumerable<string>> GetRelatedSkillsAsync(dynamic contentPicker, IContentManager contentManager) { IList<string> contentItemNames = new List<string>(); if (contentPicker != null) { var contentItemIds = (JArray)contentPicker.ContentItemIds; if (contentItemIds.Any()) { var idList = contentItemIds.Select(c => c.Value<string>()); var contentItems = await contentManager.GetAsync(idList); foreach (var item in contentItems) { contentItemNames.Add(((string)item.ContentItem.Content.SOCSkillsMatrix.RelatedSkill.Text).GetSlugValue()); } return contentItemNames; } } return Enumerable.Empty<string>(); } public static IEnumerable<Classification> MapClassificationData(IEnumerable<ContentItem> contentItems) => contentItems?.Select(contentItem => new Classification { Id = contentItem.As<GraphSyncPart>().ExtractGuid(), Title = contentItem.As<TitlePart>().Title, Description = GetClassificationDescriptionText(contentItem), Url = GetClassificationURLText(contentItem) }) ?? Enumerable.Empty<Classification>(); private static string GetClassificationDescriptionText(ContentItem contentItem) => contentItem.ContentType switch { ContentTypes.HiddenAlternativeTitle => contentItem.Content.HiddenAlternativeTitle.Description.Text, ContentTypes.JobProfileSpecialism => contentItem.Content.JobProfileSpecialism.Description.Text, ContentTypes.WorkingHoursDetail => contentItem.Content.WorkingHoursDetail.Description.Text, ContentTypes.WorkingPatterns => contentItem.Content.WorkingPatterns.Description.Text, ContentTypes.WorkingPatternDetail => contentItem.Content.WorkingPatternDetail.Description.Text, _ => string.Empty, }; private static string GetClassificationURLText(ContentItem contentItem) => contentItem.ContentType switch { ContentTypes.ApprenticeshipStandard => contentItem.Content.ApprenticeshipStandard.LARScode.Text, ContentTypes.WorkingPatternDetail => contentItem.As<TitlePart>().Title.GetSlugValue(), ContentTypes.WorkingHoursDetail => contentItem.As<TitlePart>().Title.GetSlugValue(), ContentTypes.WorkingPatterns => contentItem.As<TitlePart>().Title.GetSlugValue(), _ => string.Empty, }; } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// An `AtomFunction&lt;int, int&gt;` that clamps the value using a min and a max value and returns it. /// </summary> [EditorIcon("atom-icon-sand")] [CreateAssetMenu(menuName = "Unity Atoms/Functions/Transformers/Clamp Int (int => int)", fileName = "ClampInt")] public class ClampInt : IntIntFunction, IIsValid { /// <summary> /// The minimum value. /// </summary> public IntReference Min; /// <summary> /// The maximum value. /// </summary> public IntReference Max; public override int Call(int value) { if (!IsValid()) { throw new Exception("Min value must be less than or equal to Max value."); } return Mathf.Clamp(value, Min.Value, Max.Value); } public bool IsValid() { return Min.Value <= Max.Value; } } }
using System; using System.Collections.Generic; using Zesty.Core.Entities; namespace Zesty.Core { public interface IStorage { void AddAccessFailure(string ipAddress); int CountAccessFailure(string ipAddress, DateTime start); void SetDomain(Guid userid, Guid domainid); void SaveBearer(Guid userid, string token); string GetSecret(string bearer); void Remove(User user, Authorization authorization); void Add(User user, Authorization authorization); void Update(Entities.User user); Entities.User GetUser(string user); List<Entities.User> Users(); void HardDeleteUser(Guid userId); void DeleteUser(Guid userId); Guid Add(Entities.User user); void Add(Entities.Domain domain); void Add(Entities.Role role); void AuthorizeResource(Guid resourceId, Guid roleId); void DeauthorizeResource(Guid resourceId, Guid roleId); List<Entities.Resource> GetResources(); List<Entities.Resource> GetAllResources(); List<Entities.Resource> GetResources(Guid roleId); List<Entities.Role> GetRoles(); void ChangePassword(Guid id, string oldPassword, string password); List<SettingValue> GetSettingsValues(); void SetProperty(string name, string value, Entities.User user); Dictionary<string, string> GetClientSettings(); Guid SetResetToken(string email); bool ResetPassword(Guid resetToken, string password); User GetUserByResetToken(Guid resetToken); List<Translation> GetTranslations(string language); List<Language> GetLanguages(); List<Resource> GetResources(string username, Guid domainId); void SaveToken(Entities.User user, string sessionId, string tokenValue, bool reusable); bool CanAccess(string path, Entities.User user, string method = null); bool IsValid(Guid userId, string sessionId, string tokenValue); bool RequireToken(string path, string method = null); bool IsPublicResource(string path, string method = null); void Save(Entities.HistoryItem resource); string GetType(string resourceName); Entities.User Login(string username, string password); Dictionary<string, string> LoadProperties(Entities.User user); List<Entities.Domain> GetDomains(string username); List<Entities.Domain> GetDomainsList(); List<Entities.Role> GetRoles(string username, Guid domainId); bool ChangePassword(string username, string currentPassword, string newPassword); bool HasTwoFactorAuthentication(Guid domain); bool OneTimePasswordExists(string user, Guid domain, string value); void OneTimePasswordAdd(Guid user, Guid domain, string value); void OneTimePasswordDelete(Guid user, Guid domain); } }
using UnityEngine; //using UnityEngine.Purchasing; using System; using Mio.Utils.MessageBus; using Mio.Utils; namespace Mio.TileMaster { public enum StorePackage { SmallDiamond, MediumDiamond, BigDiamond, RemoveAds } public class IAPManager : MonoSingleton<IAPManager> /*,IStoreListener*/ { //public static IStoreController m_StoreController; //// Reference to the Purchasing system. //private static IExtensionProvider m_StoreExtensionProvider; // Product identifiers for all products capable of being purchased: // "convenience" general identifiers for use with Purchasing, // and their store-specific identifier counterparts // for use with and outside of Unity Purchasing. // Define store-specific identifiers also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.) public const string DIAMOND_PACKAGE_TIER_1 = "tier1DiamondPackage"; public const string DIAMOND_PACKAGE_TIER_2 = "tier2DiamondPackage"; public const string DIAMOND_PACKAGE_TIER_3 = "tier3DiamondPackage"; public const string REMOVE_ADS = "removeAds"; public bool IsInitialized () { // Only say we are initialized if both the Purchasing references are set. //return m_StoreController != null && m_StoreExtensionProvider != null; return false; } public void Initialize () { // If we have already connected to Purchasing ... if (IsInitialized()) { // ... we are done here. return; } // Create a builder, first passing in a suite of Unity provided stores. // var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()); // // Add a product to sell by its identifier, associating the general identifier with its store-specific identifiers. // builder.AddProduct(DIAMOND_PACKAGE_TIER_1, ProductType.Consumable, new IDs() { { kProductNameAppleDiamondPackageTier1, AppleAppStore.Name }, { kProductNamePlayStoreDiamondPackageTier1, GooglePlay.Name } }); // builder.AddProduct(DIAMOND_PACKAGE_TIER_2, ProductType.Consumable, new IDs() { { kProductNameAppleDiamondPackageTier2, AppleAppStore.Name }, { kProductNamePlayStoreDiamondPackageTier2, GooglePlay.Name } }); // builder.AddProduct(DIAMOND_PACKAGE_TIER_3, ProductType.Consumable, new IDs() { { kProductNameAppleDiamondPackageTier3, AppleAppStore.Name }, { kProductNamePlayStoreDiamondPackageTier3, GooglePlay.Name } }); // builder.AddProduct(REMOVE_ADS, ProductType.NonConsumable, new IDs() { { kProductNameAppleRemoveAds, AppleAppStore.Name }, { kProductNamePlayStoreRemoveAds, GooglePlay.Name } }); // //Debug.Log("init remove ads item"); // // Kick off the remainder of the set-up with an asynchronous call, // // passing the configuration and this class' instance. // // Expect a response either in OnInitialized or OnInitializeFailed. //UnityPurchasing.Initialize(this,builder); // show or hide ads } /// <summary> /// Restore purchases previously made by this customer. /// Some platforms automatically restore purchases. /// Apple currently requires explicit purchase restoration for IAP. /// </summary> public void RestorePurchases (bool autoRestore = false) { // If Purchasing has not yet been set up ... // if (!IsInitialized()) { // // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization. // Debug.Log("RestorePurchases FAIL. Not initialized."); //SceneManager.Instance.SetLoadingVisible(false); // return; // } // // If we are running on an Apple device ... // if (Application.platform == RuntimePlatform.IPhonePlayer || // Application.platform == RuntimePlatform.OSXPlayer) { // // ... begin restoring purchases // Debug.Log("RestorePurchases started ..."); // // Fetch the Apple store-specific subsystem. // var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>(); // // Begin the asynchronous process of restoring purchases. Expect a confirmation response in the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore. // apple.RestoreTransactions((result) => { // // The first phase of restoration. If no more responses are received on ProcessPurchase then no purchases are available to be restored. // Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore."); // if(!autoRestore){ // MessageBus.Annouce(new Message(MessageBusType.OnCompletedRestoreApple, result)); // } // if(result) // { // PlayerPrefs.SetInt (VIP_LOCAL,1); // } // }); // } // // Otherwise ... // else { // // We are not running on an Apple device. No work is necessary to restore purchases. // Debug.Log("RestorePurchases FAIL. Not supported on this platform."); //SceneManager.Instance.SetLoadingVisible(false); // } } public void BuySmallDiamondPackage () { BuyProductID(DIAMOND_PACKAGE_TIER_1); } public void BuyMediumDiamondPackage () { BuyProductID(DIAMOND_PACKAGE_TIER_2); } public void BuyBigDiamondPackage () { BuyProductID(DIAMOND_PACKAGE_TIER_3); } public void BuyRemoveAdsPackage () { BuyProductID(REMOVE_ADS); } void BuyProductID (string productId) { // If the stores throw an unexpected exception, use try..catch to protect logic here. //try { // // If Purchasing has been initialized ... // if (IsInitialized()) { // // ... look up the Product reference with the general product identifier and the Purchasing system's products collection. // Product product = m_StoreController.products.WithID(productId); // // If the look up found a product for this device's store and that product is ready to be sold ... // if (product != null && product.availableToPurchase) { // Debug.Log(string.Format("Purchasing product asynchronously: '{0}'", product.definition.id)); // // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously. // m_StoreController.InitiatePurchase(product); // } // // Otherwise ... // else { // // ... report the product look-up failure situation // Debug.Log(string.Format("BuyProductID: FAIL. Not purchasing {0}, either is not found or is not available for purchase", productId)); // } // } // // Otherwise ... // else { // // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or retrying initialization. // Debug.Log("BuyProductID FAIL. Not initialized."); // } //} //// Complete the unexpected exception handling ... //catch (Exception e) { // // ... by reporting any unexpected exception for later diagnosis. // Debug.Log("BuyProductID: FAIL. Exception during purchase. " + e); //} } private void GetIAPInfor () { // set price for ItemHitBuilder store location //if (m_StoreController != null) { // AdHelper.Instance.SetNoAds(m_StoreController.products.all[(int)StorePackage.RemoveAds].hasReceipt); // //Debug.Log("get list store started"); // //string currencyCode = m_StoreController.products.WithID(DIAMOND_PACKAGE_TIER_1).metadata.isoCurrencyCode; // GameManager.Instance.GameConfigs.iap_prices = new System.Collections.Generic.List<string>(); // GameManager.Instance.GameConfigs.iap_prices.Insert(0, m_StoreController.products.WithID(DIAMOND_PACKAGE_TIER_1).metadata.localizedPriceString); // GameManager.Instance.GameConfigs.iap_prices.Insert(1, m_StoreController.products.WithID(DIAMOND_PACKAGE_TIER_2).metadata.localizedPriceString); // GameManager.Instance.GameConfigs.iap_prices.Insert(2, m_StoreController.products.WithID(DIAMOND_PACKAGE_TIER_3).metadata.localizedPriceString); // GameManager.Instance.GameConfigs.iap_prices.Insert(3, m_StoreController.products.WithID(REMOVE_ADS).metadata.localizedPriceString); // //Debug.Log("get list store completed"); // //foreach (var product in IAPManager.m_StoreController.products.all) // //{ // // //Debug.Log(product.metadata.localizedPriceString); // // GameManager.Instance.GameConfigs.iap_prices.Add(product.metadata.localizedPriceString); // //} //} } #region Implement IStore Listener // public void OnInitialized (IStoreController controller, IExtensionProvider extensions) { // // Purchasing has succeeded initializing. Collect our Purchasing references. // //Debug.Log("OnInitialized: PASS"); // // Overall Purchasing system, configured with products for this application. // m_StoreController = controller; // // Store specific subsystem, for accessing device-specific store features. // m_StoreExtensionProvider = extensions; // GetIAPInfor(); // } // public void OnInitializeFailed (InitializationFailureReason error) { // // Purchasing set-up has not succeeded. Check error for reason. // Debug.Log("OnInitializeFailed InitializationFailureReason:" + error); // MessageBus.Annouce(new Message(MessageBusType.IAPManagerInitializeFailed, error.ToString())); // } // public void OnPurchaseFailed (Product p, PurchaseFailureReason pfr) { // // A product purchase attempt did not succeed. Check failureReason for more detail. // string failedMessage = string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", p.definition.storeSpecificId, pfr); // Debug.Log(failedMessage); // MessageBus.Annouce(new Message(MessageBusType.PurchaseFailed, failedMessage)); // } // public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs args) { // // A consumable product has been purchased by this user. // string productPurchased = args.purchasedProduct.definition.id; // if (String.Equals(productPurchased, DIAMOND_PACKAGE_TIER_1, StringComparison.Ordinal)) { // Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", productPurchased)); // AnalyticsHelper.Instance.LogBuyMarketItem(DIAMOND_PACKAGE_TIER_1, "Diamond Package", "Small Diamond Package"); // MessageBus.Annouce(new Message(MessageBusType.ProductPurchased, StorePackage.SmallDiamond)); // } // else if (String.Equals(productPurchased, DIAMOND_PACKAGE_TIER_2, StringComparison.Ordinal)) { // Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", productPurchased)); // AnalyticsHelper.Instance.LogBuyMarketItem(DIAMOND_PACKAGE_TIER_2, "Diamond Package", "Diamond Package"); // MessageBus.Annouce(new Message(MessageBusType.ProductPurchased, StorePackage.MediumDiamond)); // } // else if (String.Equals(productPurchased, DIAMOND_PACKAGE_TIER_3, StringComparison.Ordinal)) { // Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", productPurchased)); // AnalyticsHelper.Instance.LogBuyMarketItem(DIAMOND_PACKAGE_TIER_3, "Diamond Package", "Big Diamond Package"); // MessageBus.Annouce(new Message(MessageBusType.ProductPurchased, StorePackage.BigDiamond)); // } // else if (String.Equals(productPurchased, REMOVE_ADS, StringComparison.Ordinal)) { // Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", productPurchased)); // AnalyticsHelper.Instance.LogBuyMarketItem(REMOVE_ADS, "removeads Package", "removeAds Package"); // MessageBus.Annouce(new Message(MessageBusType.ProductPurchased, StorePackage.RemoveAds)); //PlayerPrefs.SetInt (VIP_LOCAL,1); // } // else { // Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", productPurchased)); // MessageBus.Annouce(new Message(MessageBusType.PurchaseFailed, productPurchased)); // } // // Return a flag indicating wither this product has completely been received, // //or if the application needs to be reminded of this purchase at next app launch. // //Is useful when saving purchased products to the cloud, and when that save is delayed. // return PurchaseProcessingResult.Complete; // } #endregion } }
using Demo.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Windows; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using System.Threading.Tasks; using EASendMailRT; // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237 namespace Demo { /// <summary> /// A basic page that provides characteristics common to most applications. /// </summary> public sealed partial class PayTicket : Page { private NavigationHelper navigationHelper; private ObservableDictionary defaultViewModel = new ObservableDictionary(); /// <summary> /// This can be changed to a strongly typed view model. /// </summary> public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } /// <summary> /// NavigationHelper is used on each page to aid in navigation and /// process lifetime management /// </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } public PayTicket() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += navigationHelper_LoadState; this.navigationHelper.SaveState += navigationHelper_SaveState; } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void navigationHelper_SaveState(object sender, SaveStateEventArgs e) { } #region NavigationHelper registration /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// /// Page specific logic should be placed in event handlers for the /// <see cref="GridCS.Common.NavigationHelper.LoadState"/> /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. protected override void OnNavigatedTo(NavigationEventArgs e) { navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { navigationHelper.OnNavigatedFrom(e); } #endregion private void Confirm_Ticket_Click(object sender, RoutedEventArgs e) { Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=", ""); GuidString = GuidString.Replace("+", ""); } private void combBoxSeats_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cb = (ComboBox)sender; string item = cb.SelectedItem as string; switch (item) { case "1 seat": txtTotalPrice.Text = (Data.price * 1).ToString() + " YUANS"; break; case "2 seats": txtTotalPrice.Text = (Data.price * 2).ToString() + " YUANS"; break; case "3 seats": txtTotalPrice.Text = (Data.price * 3).ToString() + " YUANS"; break; case "4 seats": txtTotalPrice.Text = (Data.price * 4).ToString() + " YUANS"; break; case "5 seats": txtTotalPrice.Text = (Data.price * 5).ToString() + " YUANS"; break; default: txtTotalPrice.Text = "Please, choose seats"; break; } } private async void btnSenda_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtName.Text)) { txtName.Focus(FocusState.Programmatic); return; } btnSend.IsEnabled = false; await Send_Email(); btnSend.IsEnabled = true; } private async Task Send_Email() { String Result = ""; string email = txtBoxEmail.Text; string name = txtName.Text; string seats = combBoxSeats.SelectedItem as string; if (seats != null) { Random rd = new Random(); int number = rd.Next(100000, 999999); try { SmtpMail oMail = new SmtpMail("TryIt"); SmtpClient oSmtp = new SmtpClient(); oMail.From = new MailAddress("trainscheduleconfirmation@gmail.com"); oMail.To.Add(new MailAddress(email)); oMail.Subject = "Train confirmation: " + number; oMail.TextBody = "Dear " + name + "," + Environment.NewLine + "your order was confirmed." + Environment.NewLine + Environment.NewLine + "Please, save your confirmation number: " + number; SmtpServer oServer = new SmtpServer("smtp.gmail.com"); oServer.User = "trainscheduleconfirmation@gmail.com"; oServer.Password = "abc123456789def"; oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; await oSmtp.SendMailAsync(oServer, oMail); Result = "Thank You!" + Environment.NewLine + "Your order has been successfully completed. You should receive a confirmation email shortly!"; } catch { Result = String.Format("Please, write your email."); } Windows.UI.Popups.MessageDialog dlg = new Windows.UI.Popups.MessageDialog(Result); await dlg.ShowAsync(); } } private void AppBarButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(MainPage)); } } }
// //----------------------------------------------------------------------------- // // <copyright file="GCCollectStrategy.cs" company="DCOM Engineering, LLC"> // // Copyright (c) DCOM Engineering, LLC. All rights reserved. // // </copyright> // //----------------------------------------------------------------------------- namespace NET_GC { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; public class GCCollectStrategy : Strategy { public override IEnumerable<DebugAllocationData> Run() { long beforeGC = Environment.WorkingSet; yield return new DebugAllocationData(beforeGC, beforeGC, beforeGC); GC.Collect(); GC.WaitForPendingFinalizers(); long afterGC = Environment.WorkingSet; yield return new DebugAllocationData(beforeGC, beforeGC, afterGC); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace Miniprojet.Connection { public partial class Login : Form { public Login() { InitializeComponent(); } public static string User_name; private void button1_Click_1(object sender, EventArgs e) { try { ManipulationBD.ConnectionDataBase(); string UserName = user.Text; string Password = pwd.Text; User_name = user.Text; MySqlCommand cmd = new MySqlCommand(" Select * from compte where User_name = ? And Pwd = ? ", ManipulationBD.Cnn); MySqlParameter P1 = new MySqlParameter("P1", user.Text); cmd.Parameters.Add(P1); MySqlParameter P2 = new MySqlParameter("P2", pwd.Text); cmd.Parameters.Add(P2); MySqlDataReader dr = cmd.ExecuteReader(); if (dr != null) { while (dr.Read()) { if ((string)dr["type_cmp"] == "Administrateur") { Administrateur.Administrateur a = new Administrateur.Administrateur(); a.Show(); this.Hide(); } else { Agent.Agent a = new Agent.Agent(); this.Hide(); a.Show(); } } } } catch(Exception Ex) { MessageBox.Show(Ex.Message); } finally { ManipulationBD.DecoonectionDataBase(); } } private void textBox2_Click(object sender, EventArgs e) { pwd.Clear(); pwd.PasswordChar = '*'; pwd.BackColor = Color.WhiteSmoke; } private void User_Click(object sender, EventArgs e) { user.Clear(); user.BackColor = Color.WhiteSmoke; } } }
using System.Collections.Generic; public class ExpenseRequest { public List<Expense> expenses { set; get; } }
using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace GeneratorApp { public class GenerateAppService { public void CreateAppService(string fileName, string modelName, IEnumerable<ModelProperty> modelProperties) { try { if (File.Exists(fileName)) { MessageBox.Show("Check file already exists"); return; } // Create a new file using (var sw = File.CreateText(fileName)) { sw.WriteLine("using Abp.Application.Services;"); sw.WriteLine("using Abp.Domain.Repositories;"); sw.WriteLine("using Abp.ObjectMapping;"); sw.WriteLine("using System.Collections.Generic;"); sw.WriteLine("using System.Linq;"); sw.WriteLine("using HRIS.Extensions;"); sw.WriteLine("using HRIS.WebQueryModel;"); sw.WriteLine("using Microsoft.EntityFrameworkCore;"); sw.WriteLine("using System;"); sw.WriteLine("using System.Linq.Expressions;"); sw.WriteLine("using System.Threading.Tasks;"); sw.WriteLine(""); sw.WriteLine("namespace HRIS.Setup." + modelName + ""); sw.WriteLine("{"); sw.WriteLine("[RemoteService(false)]"); sw.WriteLine("public class " + modelName + "AppService : ApplicationService, I" + modelName + "AppService"); sw.WriteLine("{"); sw.WriteLine("private readonly IObjectMapper _objectMapper;"); sw.WriteLine("private readonly IRepository<Entities.Setup." + modelName + "> _" + modelName.ToLower() + "Repository;"); sw.WriteLine(""); sw.WriteLine("public " + modelName + "AppService(IObjectMapper objectMapper,IRepository<Entities.Setup." + modelName + "> " + modelName.ToLower() + "Repository)"); sw.WriteLine("{"); sw.WriteLine("_objectMapper = objectMapper;"); sw.WriteLine("_" + modelName.ToLower() + "Repository = " + modelName.ToLower() + "Repository;"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("public async Task<" + modelName + "Dto> Create(" + modelName + "Dto " + modelName.ToLower() + ")"); sw.WriteLine("{"); sw.WriteLine("var " + modelName.ToLower() + "Obj = _objectMapper.Map<Entities.Setup." + modelName + ">(" + modelName.ToLower() + ");"); sw.WriteLine("" + modelName.ToLower() + "Obj.TenantId = 2;"); sw.WriteLine("return _objectMapper.Map<" + modelName + "Dto>(await _" + modelName.ToLower() + "Repository.InsertAsync(" + modelName.ToLower() + "Obj));"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("public async Task<" + modelName + "Dto> GetById(int id)"); sw.WriteLine("{"); sw.WriteLine("var result = await _" + modelName.ToLower() + "Repository"); //sw.WriteLine(".GetAllList()"); sw.WriteLine(".FirstOrDefaultAsync(w => w.Id == id && w.IsDeleted == false);"); sw.WriteLine(""); sw.WriteLine("return _objectMapper.Map<" + modelName + "Dto>(result);"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("public async Task<QueryResult<" + modelName + "Dto>> GetAll(IQueryObject queryObject)"); sw.WriteLine("{"); sw.WriteLine("var result = new QueryResult<" + modelName + "Dto>();"); sw.WriteLine("var query = _" + modelName.ToLower() + "Repository"); sw.WriteLine(".GetAll()"); sw.WriteLine(".Where(w => w.IsDeleted == false).AsQueryable();"); sw.WriteLine(""); sw.WriteLine("var columnsMap = new Dictionary<string, Expression<Func<Entities.Setup." + modelName + ", object>>>"); sw.WriteLine("{"); foreach (var item in modelProperties) { sw.WriteLine("[\"" + item.PropertyName + "\"] = v => v." + item.PropertyName + ","); } sw.WriteLine("};"); sw.WriteLine("query = query.ApplyOrdering(queryObject, columnsMap);"); sw.WriteLine(""); sw.WriteLine("result.TotalItems = await query.CountAsync();"); sw.WriteLine(""); sw.WriteLine("query = query.ApplyPaging(queryObject);"); sw.WriteLine(""); sw.WriteLine("result.Items = _objectMapper.Map<IEnumerable<" + modelName + "Dto>>(await query.ToListAsync());"); sw.WriteLine(""); sw.WriteLine("return result;"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("public async Task<" + modelName + "Dto> Update(" + modelName + "Dto " + modelName.ToLower() + ")"); sw.WriteLine("{"); sw.WriteLine("var result = _objectMapper.Map<Entities.Setup." + modelName + ">(" + modelName.ToLower() + ");"); sw.WriteLine("return _objectMapper.Map<" + modelName + "Dto>(await _" + modelName.ToLower() + "Repository.UpdateAsync(result));"); sw.WriteLine("}"); sw.WriteLine(""); //sw.WriteLine("public void Delete(" + modelName + "Dto " + modelName.ToLower() + ")"); //sw.WriteLine("{"); //sw.WriteLine("_" + modelName.ToLower() + "Repository.Delete(_objectMapper.Map<Entities.Setup." + modelName + ">(" + modelName.ToLower() + "));"); //sw.WriteLine("}"); sw.WriteLine("public async Task DeleteById(int id)"); sw.WriteLine("{"); sw.WriteLine("await _" + modelName.ToLower() + "Repository.DeleteAsync(id);"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("}");// end class sw.WriteLine("}");//end namespace } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace MetaDslx.Core { [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class NameAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class TypeAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class ScopeEntryAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class ScopeAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class ImportedScopeAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class ImportedEntryAttribute : Attribute { } [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class InheritedScopeAttribute : Attribute { } public static class MetaExtensions { public static bool IsMetaScope(this ModelObject symbol) { if (symbol == null) return false; if (symbol.GetType().IsMetaScope()) return true; foreach (var intf in symbol.GetType().GetInterfaces()) { if (intf.IsMetaScope()) return true; } return false; } public static bool IsMetaScope(this Type symbolType) { if (symbolType == null) return false; var attributes = symbolType.GetCustomAttributes(typeof(ScopeAttribute), true); return attributes.Length > 0; } public static bool IsMetaType(this ModelObject symbol) { if (symbol == null) return false; if (symbol.GetType().IsMetaType()) return true; foreach (var intf in symbol.GetType().GetInterfaces()) { if (intf.IsMetaType()) return true; } return false; } public static bool IsMetaType(this Type symbolType) { if (symbolType == null) return false; var attributes = symbolType.GetCustomAttributes(typeof(TypeAttribute), true); return attributes.Length > 0; } public static bool IsMetaName(this ModelProperty property) { if (property == null) return false; return property.Annotations.Any(a => a is NameAttribute); } } public class MetaBuiltInTypes { private static List<MetaType> types; public static IEnumerable<MetaType> Types { get { if (MetaBuiltInTypes.types == null) { MetaBuiltInTypes.types = new List<MetaType>(); if (MetaBuiltInTypes.types.Count == 0 && MetaInstance.Object != null) { MetaBuiltInTypes.types.Add(MetaInstance.Object); MetaBuiltInTypes.types.Add(MetaInstance.String); MetaBuiltInTypes.types.Add(MetaInstance.Int); MetaBuiltInTypes.types.Add(MetaInstance.Long); MetaBuiltInTypes.types.Add(MetaInstance.Float); MetaBuiltInTypes.types.Add(MetaInstance.Double); MetaBuiltInTypes.types.Add(MetaInstance.Byte); MetaBuiltInTypes.types.Add(MetaInstance.Bool); MetaBuiltInTypes.types.Add(MetaInstance.Void); MetaBuiltInTypes.types.Add(MetaInstance.ModelObject); MetaBuiltInTypes.types.Add(MetaInstance.DefinitionList); MetaBuiltInTypes.types.Add(MetaInstance.ModelObjectList); } } return MetaBuiltInTypes.types; } } } public class MetaBuiltInFunctions { private static List<MetaFunction> functions; public static IEnumerable<MetaFunction> Functions { get { if (MetaBuiltInFunctions.functions == null) { MetaBuiltInFunctions.functions = new List<MetaFunction>(); if (MetaBuiltInFunctions.functions.Count == 0 && MetaInstance.TypeOf != null) { MetaBuiltInFunctions.functions.Add(MetaInstance.TypeOf); MetaBuiltInFunctions.functions.Add(MetaInstance.GetValueType); MetaBuiltInFunctions.functions.Add(MetaInstance.GetReturnType); MetaBuiltInFunctions.functions.Add(MetaInstance.CurrentType); MetaBuiltInFunctions.functions.Add(MetaInstance.TypeCheck); MetaBuiltInFunctions.functions.Add(MetaInstance.Balance); MetaBuiltInFunctions.functions.Add(MetaInstance.Resolve1); MetaBuiltInFunctions.functions.Add(MetaInstance.Resolve2); MetaBuiltInFunctions.functions.Add(MetaInstance.ResolveName1); MetaBuiltInFunctions.functions.Add(MetaInstance.ResolveName2); MetaBuiltInFunctions.functions.Add(MetaInstance.ResolveType1); MetaBuiltInFunctions.functions.Add(MetaInstance.ResolveType2); MetaBuiltInFunctions.functions.Add(MetaInstance.ToDefinitionList); MetaBuiltInFunctions.functions.Add(MetaInstance.Bind1); MetaBuiltInFunctions.functions.Add(MetaInstance.Bind2); } } return MetaBuiltInFunctions.functions; } } } public static class MetaScopeEntryProperties { public static readonly ModelProperty SymbolTreeNodesProperty = ModelProperty.Register("SymbolTreeNodes", typeof(IList<object>), typeof(MetaScopeEntryProperties)); public static readonly ModelProperty NameTreeNodesProperty = ModelProperty.Register("NameTreeNodes", typeof(IList<object>), typeof(MetaScopeEntryProperties)); public static readonly ModelProperty CanMergeProperty = ModelProperty.Register("CanMerge", typeof(bool), typeof(MetaScopeEntryProperties)); } [Scope] public class RootScope : ModelObject { public RootScope() { this.MSet(RootScope.BuiltInEntriesProperty, new ModelList<ModelObject>(this, RootScope.BuiltInEntriesProperty)); this.MSet(RootScope.EntriesProperty, new ModelList<ModelObject>(this, RootScope.EntriesProperty)); } public void AddMetaBuiltInEntries() { foreach (var type in MetaBuiltInTypes.Types) { this.BuiltInEntries.Add((ModelObject)type); } foreach (var func in MetaBuiltInFunctions.Functions) { this.BuiltInEntries.Add((ModelObject)func); } } [ScopeEntry] public static readonly ModelProperty BuiltInEntriesProperty = ModelProperty.Register("BuiltInEntries", typeof(IList<ModelObject>), typeof(RootScope)); [Containment] [ScopeEntry] public static readonly ModelProperty EntriesProperty = ModelProperty.Register("Entries", typeof(IList<ModelObject>), typeof(RootScope)); public IList<ModelObject> BuiltInEntries { get { return (IList<ModelObject>)this.MGet(RootScope.BuiltInEntriesProperty); } } public IList<ModelObject> Entries { get { return (IList<ModelObject>)this.MGet(RootScope.EntriesProperty); } } } internal class MetaImplementation : MetaImplementationBase { public override IList<string> MetaDocumentedElement_GetDocumentationLines(MetaDocumentedElement @this) { List<string> result = new List<string>(); if (@this.Documentation == null) return result; MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(@this.Documentation); writer.Flush(); stream.Position = 0; StringBuilder sb = new StringBuilder(); using (StreamReader reader = new StreamReader(stream)) { while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line != null) { result.Add(line); } } } return result; } public override void MetaFunction(MetaFunction @this) { base.MetaFunction(@this); MetaFunctionType type = MetaFactory.Instance.CreateMetaFunctionType(); ((ModelObject)type).MUnSet(MetaDescriptor.MetaFunctionType.ParameterTypesProperty); ((ModelObject)type).MLazySet(MetaDescriptor.MetaFunctionType.ParameterTypesProperty, new Lazy<object>(() => new ModelMultiList<MetaType>((ModelObject)type, MetaDescriptor.MetaFunctionType.ParameterTypesProperty, @this.Parameters.Select(p => new Lazy<object>(() => p.Type))), LazyThreadSafetyMode.PublicationOnly)); ((ModelObject)type).MLazySet(MetaDescriptor.MetaFunctionType.ReturnTypeProperty, new Lazy<object>(() => @this.ReturnType, LazyThreadSafetyMode.PublicationOnly)); ((ModelObject)@this).MSet(MetaDescriptor.MetaFunction.TypeProperty, type); //((ModelObject)type).MLazySet(MetaDescriptor.MetaFunctionType.ReturnTypeProperty, new Lazy<object>(() => @this.ReturnType, LazyThreadSafetyMode.PublicationOnly)); } public override void MetaUnaryExpression(MetaUnaryExpression @this) { base.MetaUnaryExpression(@this); ((ModelObject)@this).MLazyAdd(MetaDescriptor.MetaBoundExpression.ArgumentsProperty, new Lazy<object>(() => @this.Expression, LazyThreadSafetyMode.PublicationOnly)); } public override void MetaBinaryExpression(MetaBinaryExpression @this) { base.MetaBinaryExpression(@this); ((ModelObject)@this).MLazyAdd(MetaDescriptor.MetaBoundExpression.ArgumentsProperty, new Lazy<object>(() => @this.Left, LazyThreadSafetyMode.PublicationOnly)); ((ModelObject)@this).MLazyAdd(MetaDescriptor.MetaBoundExpression.ArgumentsProperty, new Lazy<object>(() => @this.Right, LazyThreadSafetyMode.PublicationOnly)); } public override void MetaNewCollectionExpression(MetaNewCollectionExpression @this) { base.MetaNewCollectionExpression(@this); ((ModelObject)@this).MLazySetChild(MetaDescriptor.MetaNewCollectionExpression.ValuesProperty, MetaDescriptor.MetaExpression.ExpectedTypeProperty, new Lazy<object>(() => @this.TypeReference.InnerType, LazyThreadSafetyMode.PublicationOnly)); } public override IList<MetaOperation> MetaClass_GetAllOperations(MetaClass @this) { List<MetaOperation> result = new List<MetaOperation>(); foreach (var oper in @this.Operations) { result.Add(oper); } foreach (var cls in @this.GetAllSuperClasses()) { foreach (var oper in cls.Operations) { result.Add(oper); } } return result; } public override IList<MetaProperty> MetaClass_GetAllProperties(MetaClass @this) { List<MetaProperty> result = new List<MetaProperty>(); foreach (var prop in @this.Properties) { result.Add(prop); } foreach (var cls in @this.GetAllSuperClasses()) { foreach (var prop in cls.Properties) { result.Add(prop); } } return result; } public override IList<MetaClass> MetaClass_GetAllSuperClasses(MetaClass @this) { List<MetaClass> result = new List<MetaClass>(); foreach (var super in @this.SuperClasses) { ICollection<MetaClass> allSupers = super.GetAllSuperClasses(); if (!result.Contains(super)) { result.Add(super); } foreach (var superSuper in allSupers) { if (!result.Contains(superSuper)) { result.Add(superSuper); } } } return result; } public override IList<MetaProperty> MetaClass_GetAllImplementedProperties(MetaClass @this) { IList<MetaProperty> props = @this.GetAllProperties(); int i = props.Count - 1; while (i >= 0) { string name = props[i].Name; MetaProperty prop = props.First(p => p.Name == name); if (prop != props[i]) { props.RemoveAt(i); } --i; } return props; } public override IList<MetaOperation> MetaClass_GetAllImplementedOperations(MetaClass @this) { IList<MetaOperation> ops = @this.GetAllOperations(); int i = ops.Count - 1; while (i >= 0) { string name = ops[i].Name; MetaOperation op = ops.First(o => o.Name == name); if (op != ops[i]) { ops.RemoveAt(i); } --i; } return ops; } } internal static class MetaModelExtensions { public static bool HasSameMetaModel(this ModelObject @this, ModelObject mobj) { if (@this == null || @this.MMetaModel == null) return false; if (mobj == null || mobj.MMetaModel == null) return false; return @this.MMetaModel == mobj.MMetaModel; } public static Dictionary<ModelObject, string> GetNamedModelObjects(this MetaModel model) { return ((ModelObject)model).MModel.GetNamedModelObjects(); } public static Dictionary<ModelObject, string> GetNamedModelObjects(this Model model) { Dictionary<ModelObject, string> result = new Dictionary<ModelObject, string>(); int tmpCounter = 0; foreach (var item in model.Instances) { string name = null; MetaProperty prop = item as MetaProperty; if (prop != null) { name = prop.Class.BuiltInName() + "_" + prop.Name + "Property"; } else { MetaDeclaration decl = item as MetaDeclaration; if (decl != null && !(decl is MetaConstant)) { name = decl.BuiltInName(); } } if (name == null) { ++tmpCounter; name = "__tmp" + tmpCounter; } result.Add(item, name); } return result; } public static string CSharpName(this MetaNamespace @this) { if (@this == null) return string.Empty; string result = @this.Name; MetaNamespace parent = ((ModelObject)@this).MParent as MetaNamespace; while (parent != null) { result = parent.Name + "." + result; parent = ((ModelObject)parent).MParent as MetaNamespace; } return result; } public static string CSharpName(this MetaModel @this) { if (@this == null) return string.Empty; return @this.Name; } public static string CSharpFullName(this MetaModel @this) { if (@this == null) return string.Empty; string nsName = @this.Namespace.CSharpName(); if (!string.IsNullOrEmpty(nsName)) return "global::" + nsName + "." + @this.Name; else return "global::" + @this.Name; } public static string CSharpName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { string innerName = null; if (((ModelObject)collection.InnerType).HasSameMetaModel((ModelObject)@this)) innerName = collection.InnerType.CSharpName(); else innerName = collection.InnerType.CSharpFullName(); switch (collection.Kind) { case MetaCollectionKind.Set: return "global::MetaDslx.Core.ModelSet<" + innerName + ">"; case MetaCollectionKind.List: return "global::MetaDslx.Core.ModelList<" + innerName + ">"; case MetaCollectionKind.MultiSet: return "global::MetaDslx.Core.ModelMultiSet<" + innerName + ">"; case MetaCollectionKind.MultiList: return "global::MetaDslx.Core.ModelMultiList<" + innerName + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (((ModelObject)nullable.InnerType).HasSameMetaModel((ModelObject)@this)) innerName = nullable.InnerType.CSharpName(); else innerName = nullable.InnerType.CSharpFullName(); return innerName + "?"; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToCSharpType(); } return ((MetaNamedElement)@this).Name; } public static string ToCSharpType(this MetaPrimitiveType @this) { if (@this.Name == "DefinitionList") return "global::MetaDslx.Core.BindingInfo"; return @this.Name; } public static string CSharpFullName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { string innerName = collection.InnerType.CSharpFullName(); switch (collection.Kind) { case MetaCollectionKind.Set: return "global::MetaDslx.Core.ModelSet<" + innerName + ">"; case MetaCollectionKind.List: return "global::MetaDslx.Core.ModelList<" + innerName + ">"; case MetaCollectionKind.MultiSet: return "global::MetaDslx.Core.ModelMultiSet<" + innerName + ">"; case MetaCollectionKind.MultiList: return "global::MetaDslx.Core.ModelMultiList<" + innerName + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = nullable.InnerType.CSharpFullName(); return innerName + "?"; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToCSharpType(); } MetaDeclaration decl = @this as MetaDeclaration; string nsName = string.Empty; if (decl != null) { nsName = decl.Namespace.CSharpName(); if (!string.IsNullOrEmpty(nsName)) return "global::" + nsName + "." + @this.CSharpName(); else return @this.CSharpName(); } else { return @this.CSharpName(); } } public static string CSharpDescriptorName(this MetaModel @this) { return @this.CSharpName() + "Descriptor"; } public static string CSharpFullDescriptorName(this MetaModel @this) { return @this.CSharpFullName() + "Descriptor"; } public static string CSharpInstancesName(this MetaModel @this) { return @this.CSharpName() + "Instance"; } public static string CSharpFullInstancesName(this MetaModel @this) { return @this.CSharpFullName() + "Instance"; } public static string CSharpFactoryName(this MetaModel @this) { return @this.CSharpName() + "Factory"; } public static string CSharpFullFactoryName(this MetaModel @this) { return @this.CSharpFullName() + "Factory"; } public static string CSharpFullImplementationName(this MetaModel @this) { return @this.CSharpFullName() + "ImplementationProvider.Implementation"; } public static string GetCSharpValue(this MetaExpression @this) { MetaConstantExpression mce = @this as MetaConstantExpression; if (mce != null) { if (mce.Value != null) return mce.Value.ToString(); else return string.Empty; } else { return string.Empty; } } public static string BuiltInName(this MetaDeclaration @this) { foreach (var annot in @this.Annotations) { if (annot.Name == "BuiltInName") { foreach (var prop in annot.Properties) { if (prop.Name == "Name") { return prop.Value.GetCSharpValue(); } } } } return @this.Name; } public static string CSharpFullFactoryMethodName(this MetaClass @this) { return @this.Model.CSharpFullFactoryName() + ".Instance.Create" + @this.CSharpName(); } public static string CSharpDescriptorName(this MetaDeclaration @this) { return @this.BuiltInName(); } public static string CSharpDescriptorName(this MetaProperty @this) { return @this.Name + "Property"; } public static string CSharpFullDescriptorName(this MetaDeclaration @this) { return @this.Model.CSharpFullDescriptorName() + "." + @this.CSharpDescriptorName(); } public static string CSharpFullDescriptorName(this MetaProperty @this) { return @this.Class.CSharpFullDescriptorName() + "." + @this.CSharpDescriptorName(); } public static string CSharpInstanceName(this MetaDeclaration @this) { return @this.BuiltInName(); } public static string CSharpInstanceName(this MetaProperty @this) { return @this.Class.CSharpName() + "_" + @this.Name + "Property"; } public static string CSharpFullInstanceName(this MetaModel @this) { return @this.CSharpFullInstancesName() + ".Meta"; } public static string CSharpFullInstanceName(this MetaDeclaration @this) { return @this.Model.CSharpFullInstancesName() + "." + @this.CSharpInstanceName(); } public static string CSharpFullInstanceName(this MetaProperty @this) { return @this.Class.Model.CSharpFullInstancesName() + "." + @this.CSharpInstanceName(); } public static string CSharpImplName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { switch (collection.Kind) { case MetaCollectionKind.Set: case MetaCollectionKind.MultiSet: return "global::System.Collections.Generic.ICollection<" + collection.InnerType.CSharpImplName() + ">"; case MetaCollectionKind.List: case MetaCollectionKind.MultiList: return "global::System.Collections.Generic.IList<" + collection.InnerType.CSharpImplName() + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { return nullable.InnerType.CSharpImplName() + "?"; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToCSharpType(); } return ((MetaNamedElement)@this).Name + "Impl"; } public static string CSharpFullPublicName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { switch (collection.Kind) { case MetaCollectionKind.Set: case MetaCollectionKind.MultiSet: return "global::System.Collections.Generic.ICollection<" + collection.InnerType.CSharpFullPublicName() + ">"; case MetaCollectionKind.List: case MetaCollectionKind.MultiList: return "global::System.Collections.Generic.IList<" + collection.InnerType.CSharpFullPublicName() + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { return nullable.InnerType.CSharpFullPublicName() + "?"; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToCSharpType(); } return @this.CSharpFullName(); } public static ModelObject GetRootNamespace(this ModelObject mobj) { if (mobj == null) return mobj; while (mobj.MParent != null && mobj.MParent is MetaNamespace) mobj = mobj.MParent; return mobj; } public static List<string> GetAllSuperPropertyNames(this MetaClass @this) { return GetAllSuperProperties(@this).Select(p => p.Name).ToList(); } public static List<MetaProperty> GetAllSuperProperties(this MetaClass @this) { List<MetaProperty> result = new List<MetaProperty>(); foreach (var super in @this.GetAllSuperClasses(false)) { foreach (var prop in super.Properties) { result.Add(prop); } } return result; } public static List<MetaClass> GetAllSuperClasses(this MetaClass @this, bool includeSelf) { if (@this == null) return new List<MetaClass>(); List<MetaClass> result = new List<MetaClass>(@this.GetAllSuperClasses()); if (includeSelf) { result.Add(@this); } return result; } public static bool ContainedBySingleOpposite(this ModelObject mobj, ModelProperty mobjProperty, ModelObject value) { foreach (var op in mobjProperty.OppositeProperties) { if (!op.IsCollection) { object ov = value.MGet(op); if (ov == mobj) return true; } } return false; } } internal static class MetaModelJavaExtensions { public static string ToCamelCase(this string name) { if (string.IsNullOrEmpty(name)) return name; else return name[0].ToString().ToLower() + name.Substring(1); } public static string JavaName(this MetaNamespace @this) { return @this.CSharpName().ToLower(); } public static string JavaName(this MetaModel @this) { if (@this == null) return string.Empty; return @this.Name; } public static string JavaFullName(this MetaModel @this) { if (@this == null) return string.Empty; string nsName = @this.Namespace.JavaName(); if (!string.IsNullOrEmpty(nsName)) return nsName + "." + @this.Name; else return @this.Name; } public static string JavaName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { string innerName = null; if (((ModelObject)collection.InnerType).HasSameMetaModel((ModelObject)@this)) innerName = collection.InnerType.JavaName(); else innerName = collection.InnerType.JavaFullName(); switch (collection.Kind) { case MetaCollectionKind.Set: return "metadslx.core.ModelSet<" + innerName + ">"; case MetaCollectionKind.List: return "metadslx.core.ModelList<" + innerName + ">"; case MetaCollectionKind.MultiSet: return "metadslx.core.ModelMultiSet<" + innerName + ">"; case MetaCollectionKind.MultiList: return "metadslx.core.ModelMultiList<" + innerName + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (nullable.InnerType is MetaPrimitiveType) { innerName = ((MetaPrimitiveType)nullable.InnerType).ToJavaNullableType(); } else { if (((ModelObject)nullable.InnerType).HasSameMetaModel((ModelObject)@this)) innerName = nullable.InnerType.JavaName(); else innerName = nullable.InnerType.JavaFullName(); } return innerName; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToJavaType(); } return ((MetaNamedElement)@this).Name; } public static string ToJavaType(this MetaPrimitiveType @this) { if (@this.Name == "bool") return "boolean"; if (@this.Name == "object") return "Object"; if (@this.Name == "string") return "String"; if (@this.Name == "DefinitionList") return "metadslx.core.BindingInfo"; return @this.Name; } public static string ToJavaNullableType(this MetaPrimitiveType @this) { switch (@this.Name) { case "object": return "Object"; case "string": return "String"; case "int": return "Integer"; case "long": return "Long"; case "float": return "Float"; case "double": return "Double"; case "byte": return "Byte"; case "bool": return "Boolean"; case "void": return "Void"; } return null; } public static string JavaDefaultValue(this MetaPrimitiveType @this) { switch (@this.Name) { case "object": return "null"; case "string": return "null"; case "int": return "0"; case "long": return "0"; case "float": return "0"; case "double": return "0"; case "byte": return "0"; case "bool": return "false"; case "void": return ""; } return "null"; } public static string JavaDefaultValue(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { return "null"; } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { return "null"; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.JavaDefaultValue(); } return "null"; } public static string JavaNonGenericFullName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { switch (collection.Kind) { case MetaCollectionKind.Set: return "metadslx.core.ModelSet"; case MetaCollectionKind.List: return "metadslx.core.ModelList"; case MetaCollectionKind.MultiSet: return "metadslx.core.ModelMultiSet"; case MetaCollectionKind.MultiList: return "metadslx.core.ModelMultiList"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (nullable.InnerType is MetaPrimitiveType) { innerName = ((MetaPrimitiveType)nullable.InnerType).ToJavaNullableType(); } else { innerName = nullable.InnerType.JavaNonGenericFullName(); } return innerName; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToJavaType(); } MetaDeclaration decl = @this as MetaDeclaration; string nsName = string.Empty; if (decl != null) { nsName = decl.Namespace.JavaName(); if (!string.IsNullOrEmpty(nsName)) return nsName + "." + @this.JavaName(); else return @this.JavaName(); } else { return @this.JavaName(); } } public static string JavaFullName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { string innerName = collection.InnerType.JavaFullName(); switch (collection.Kind) { case MetaCollectionKind.Set: return "metadslx.core.ModelSet<" + innerName + ">"; case MetaCollectionKind.List: return "metadslx.core.ModelList<" + innerName + ">"; case MetaCollectionKind.MultiSet: return "metadslx.core.ModelMultiSet<" + innerName + ">"; case MetaCollectionKind.MultiList: return "metadslx.core.ModelMultiList<" + innerName + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (nullable.InnerType is MetaPrimitiveType) { innerName = ((MetaPrimitiveType)nullable.InnerType).ToJavaNullableType(); } else { innerName = nullable.InnerType.JavaFullName(); } return innerName; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToJavaType(); } MetaDeclaration decl = @this as MetaDeclaration; string nsName = string.Empty; if (decl != null) { nsName = decl.Namespace.JavaName(); if (!string.IsNullOrEmpty(nsName)) return nsName + "." + @this.JavaName(); else return @this.JavaName(); } else { return @this.JavaName(); } } public static string JavaImplName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { switch (collection.Kind) { case MetaCollectionKind.Set: case MetaCollectionKind.MultiSet: return "java.util.Collection<" + collection.InnerType.JavaImplName() + ">"; case MetaCollectionKind.List: case MetaCollectionKind.MultiList: return "java.util.List<" + collection.InnerType.JavaImplName() + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (nullable.InnerType is MetaPrimitiveType) { innerName = ((MetaPrimitiveType)nullable.InnerType).ToJavaNullableType(); } else { innerName = nullable.InnerType.JavaImplName(); } return innerName; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToJavaType(); } return ((MetaNamedElement)@this).Name + "Impl"; } public static string JavaFullPublicName(this MetaType @this) { if (@this == null) return string.Empty; MetaCollectionType collection = @this as MetaCollectionType; if (collection != null) { switch (collection.Kind) { case MetaCollectionKind.Set: case MetaCollectionKind.MultiSet: return "java.util.Collection<" + collection.InnerType.JavaFullPublicName() + ">"; case MetaCollectionKind.List: case MetaCollectionKind.MultiList: return "java.util.List<" + collection.InnerType.JavaFullPublicName() + ">"; default: return null; } } MetaNullableType nullable = @this as MetaNullableType; if (nullable != null) { string innerName = null; if (nullable.InnerType is MetaPrimitiveType) { innerName = ((MetaPrimitiveType)nullable.InnerType).ToJavaNullableType(); } else { innerName = nullable.InnerType.JavaFullPublicName(); } return innerName; } MetaPrimitiveType primitive = @this as MetaPrimitiveType; if (primitive != null) { return primitive.ToJavaType(); } return @this.JavaFullName(); } public static string JavaDescriptorName(this MetaModel @this) { return @this.JavaName() + "Descriptor"; } public static string JavaFullDescriptorName(this MetaModel @this) { return @this.JavaFullName() + "Descriptor"; } public static string JavaInstancesName(this MetaModel @this) { return @this.JavaName() + "Instance"; } public static string JavaFullInstancesName(this MetaModel @this) { return @this.JavaFullName() + "Instance"; } public static string JavaFactoryName(this MetaModel @this) { return @this.JavaName() + "Factory"; } public static string JavaFullFactoryName(this MetaModel @this) { return @this.JavaFullName() + "Factory"; } public static string JavaFullImplementationName(this MetaModel @this) { return @this.JavaFullName() + "ImplementationProvider.implementation()"; } public static string GetJavaValue(this MetaExpression @this) { MetaConstantExpression mce = @this as MetaConstantExpression; if (mce != null) { if (mce.Value != null) return mce.Value.ToString(); else return string.Empty; } else { return string.Empty; } } public static string JavaFullFactoryMethodName(this MetaClass @this) { return @this.Model.JavaFullFactoryName() + ".instance().create" + @this.JavaName(); } public static string JavaDescriptorName(this MetaDeclaration @this) { return @this.BuiltInName(); } public static string JavaDescriptorName(this MetaProperty @this) { return @this.Name + "Property"; } public static string JavaFullDescriptorName(this MetaDeclaration @this) { return @this.Model.JavaFullDescriptorName() + "." + @this.JavaDescriptorName(); } public static string JavaFullDescriptorName(this MetaProperty @this) { return @this.Class.JavaFullDescriptorName() + "." + @this.JavaDescriptorName(); } public static string JavaInstanceName(this MetaDeclaration @this) { return @this.BuiltInName(); } public static string JavaInstanceName(this MetaProperty @this) { return @this.Class.JavaName() + "_" + @this.Name + "Property"; } public static string JavaFullInstanceName(this MetaModel @this) { return @this.JavaFullInstancesName() + ".Meta"; } public static string JavaFullInstanceName(this MetaDeclaration @this) { return @this.Model.JavaFullInstancesName() + "." + @this.JavaInstanceName(); } public static string JavaFullInstanceName(this MetaProperty @this) { return @this.Class.Model.JavaFullInstancesName() + "." + @this.JavaInstanceName(); } public static string JavaFullDeclaredName(this ModelProperty property) { string nsName = property.DeclaringType.Namespace; string localName = property.DeclaringType.FullName.Substring(nsName.Length + 1).Replace("+", "."); return nsName.ToLower() + "." + localName + "." + property.DeclaredName; } public static string JavaEnumValueOf(this object enm) { string nsName = enm.GetType().Namespace; string localName = enm.GetType().FullName.Substring(nsName.Length + 1).Replace("+", "."); return nsName.ToLower() + "." + localName + "." + enm.ToString(); } public static string SafeJavaName(this string name) { if (name == "getClass") return "getClass_"; return name; } } }
namespace Uintra.Infrastructure.Providers { public class DateTimeFormatProvider : IDateTimeFormatProvider { public string TimeFormat { get; set; } = "HH:mm"; public string EventDetailsDateFormat { get; set; } = "MMM d, yyyy"; public string EventDetailsDateTimeFormat { get; set; } = "MMM d, yyyy h.mm"; public string EventDetailsTimeFormat { get; set; } = "h.mm tt"; public string EventDetailsTimeWithoutMinutesFormat { get; set; } = "h tt"; public string DateFormat { get; set; } = "MMM dd, yyyy"; public string DateTimeFormat { get; set; } = "MMM dd, yyyy HH:mm"; public string DateTimeValuePickerFormat { get; set; } = "yyyy-MM-ddTHH:mm"; public string DatePickerFormat { get; set; } = "d.m.Y"; public string DateTimePickerFormat { get; set; } = "d.m.Y H:i"; } }
using Microsoft.EntityFrameworkCore; using Abp.Zero.EntityFrameworkCore; using dgPower.KMS.Authorization.Roles; using dgPower.KMS.Authorization.Users; using dgPower.KMS.MultiTenancy; namespace dgPower.KMS.EntityFrameworkCore { public class KMSDbContext : AbpZeroDbContext<Tenant, Role, User, KMSDbContext> { /* Define a DbSet for each entity of the application */ public KMSDbContext(DbContextOptions<KMSDbContext> options) : base(options) { } } }