text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Threading; using Microsoft.Extensions.Configuration; using MySql.Data.MySqlClient; using OnlyOrm.Exceptions; namespace OnlyOrm.Pool { /// <summary> /// 数据库连接池,暂时不启用 /// </summary> internal static class ConnectionPool { private static int _poolSize { get; set; } private static string _conectStr { get; set; } private static string _sqlType { get; set; } private static List<MySqlConnection> _connections = new List<MySqlConnection>(); private static object _lockObj = new object(); static ConnectionPool() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); _conectStr = config["OnlyOrm:ConnectString"]; _sqlType = config["OnlyOrm:Type"]; _poolSize = int.Parse(config["OnlyOrm:ConnectionPoolSize"]); } public static MySqlConnection GetConnection() { lock (_lockObj) { if (_connections.Count > 0) { Console.WriteLine("使用第0个链接"); var tempConnection = _connections[0]; _connections.RemoveAt(0); return tempConnection; } var conn = CreateConnection(); Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}open:目前一共有{_connections.Count}个链接"); return conn; } } static MySqlConnection CreateConnection() { MySqlConnection conn = new MySqlConnection(_conectStr); conn.Open(); return conn; } public static void CloseConnection(MySqlConnection con) { lock (_lockObj) { if (null == con) return; if (con.State != ConnectionState.Closed) { if (_connections.Count < _poolSize) { _connections.Add(con); Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}close:目前一共有{_connections.Count}个链接"); } } } } } }
using System; using DevExpress.Xpo; using DevExpress.Data.Filtering; using System.Collections.Generic; using System.ComponentModel; namespace prjQLNK.QLNK { public partial class NHANKHAU { public NHANKHAU(Session session) : base(session) { } public override void AfterConstruction() { base.AfterConstruction(); MAKHAISINH = AutoFormat.LayMaTuDong<NHANKHAU>(Session, "MAKHAISINH", "{0:d8}"); SOHOKHAU = Bientoancuc.sohokhau; } } }
using UnityEngine; using System.Collections; public class BallController : MonoBehaviour { public float ballForce = 500.0f; bool ballInPlay; Rigidbody rd; // Use this for initialization void Start () { rd = GetComponent<Rigidbody> (); ballInPlay = false; } // Update is called once per frame void Update () { if (Input.GetButtonDown ("Fire1") && !ballInPlay) { transform.parent = null; ballInPlay = true; rd.isKinematic = false; rd.AddForce(new Vector3(ballForce,ballForce,0)); } } }
using Jell.DataLogger.Shared.Utilities; namespace Jell.DataLogger.Core.Models { public class SensorRecording { public SensorRecording(int ADCvalue) { ADC = ADCvalue; Voltage = SensorConversion.ADCtoV(ADCvalue); ParValue = SensorConversion.VtoPAR(Voltage); } public int ADC { get; } public double Voltage { get; } public double ParValue { get; } } }
using System.Collections.Generic; namespace OCP.Dashboard.Service { /** * Interface IEventsService * * The Service is provided by the Dashboard app. The method in this interface * are used by the IDashboardManager when creating push event. * * @since 15.0.0 * * @package OCP\Dashboard\Service */ public interface IEventsService { /** * Create an event for a widget and an array of users. * * @see IDashboardManager::createUsersEvent * * @since 15.0.0 * * @param string widgetId * @param array users * @param array payload * @param string uniqueId */ void createUsersEvent(string widgetId, IList<string> users, IList<string> payload, string uniqueId); /** * Create an event for a widget and an array of groups. * * @see IDashboardManager::createGroupsEvent * * @since 15.0.0 * * @param string widgetId * @param array groups * @param array payload * @param string uniqueId */ void createGroupsEvent(string widgetId, IList<string> groups, IList<string> payload, string uniqueId); /** * Create a global event for all users that use a specific widget. * * @see IDashboardManager::createGlobalEvent * * @since 15.0.0 * * @param string widgetId * @param array payload * @param string uniqueId */ void createGlobalEvent(string widgetId, IList<string> payload, string uniqueId); } }
using System; namespace TSORT { class Program { static void Main() { GetInput(); BinarySearchTree.PrintTree(); } static void GetInput() { var numberOfNumbers = Convert.ToInt16(Console.ReadLine()); for (var i = 0; i < numberOfNumbers; i++) { BinarySearchTree.Insert(Convert.ToInt16(Console.ReadLine())); } } } public class BinarySearchTree { private static Node _root; public static void Insert(int data) { if (_root == null) { _root = new Node { Data = data }; } else { Insert(_root, data); } } private static void Insert(Node subTree, int data) { if (data <= subTree.Data) { if (subTree.Left == null) { subTree.Left = new Node { Data = data }; } else { Insert(subTree.Left, data); } } else { if (subTree.Right == null) { subTree.Right = new Node { Data = data }; } else { Insert(subTree.Right, data); } } } public static void PrintTree() { if (_root != null) { PrintTree(_root); } } private static void PrintTree(Node subTree) { if (subTree.Left != null) { PrintTree(subTree.Left); } Console.WriteLine(subTree.Data); if (subTree.Right != null) { PrintTree(subTree.Right); } } } public class Node { public int Data { get; set; } public Node Left { get; set; } public Node Right { get; set; } } }
using System.Collections.Generic; using DDDStore.Domain.Entities; namespace DDDStore.Domain.Interfaces.Services.Department { public interface ISalesService { /* * - Precisa ter acesso a todo o histórico de vendas, não apenas a última. * - Precisa saber para cada venda, qual endereço utilizar. (O cliente pode cadastrar quantos endereços quiser). * - Precisa ter acesso ao mês de aniversário para incluir desconto especial. * - Precisa ter acesso ao nível do programa de fidelidade para incluir o desconto, e aplicar os pontos. (cada $1 equivale a 1 ponto). */ IEnumerable<Order> LoadSalesHistory(int customerId); void IncludeSpecialDiscount(int customerId, int orderId, int discount); void AddPointsToCustomer(int customerId, int points); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class Arena : MonoBehaviour { public float height = 10; public GameObject wallL, wallR, wallU; void Start() { wallL.transform.localScale = new Vector3(2,height,1); wallL.transform.localPosition = new Vector2(-3.5f,(height-10)/2); wallR.transform.localScale = new Vector3(2,height,1); wallR.transform.localPosition = new Vector2(3.5f,(height-10)/2); wallU.transform.position = new Vector3(0,(height/2) + 0.5f + (height-10)/2,0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace eIDEAS.Models.Enums { public enum RoleEnum { Admin=1, DivisionManager=2, UnitManager=3 } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using InjecaoDeDependecias.Models; using Microsoft.AspNetCore.Server.IIS.Core; namespace InjecaoDeDependecias.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IPedidoRepository _pedidoRepository; public HomeController(ILogger<HomeController> logger, IPedidoRepository pedidoRepository) { _logger = logger; _pedidoRepository = pedidoRepository; } public IActionResult Index() { try { var pedido = _pedidoRepository.ObterPedido(); _logger.LogInformation("Deu certo..."); } catch (Exception erro) { _logger.LogError("O Erro ocorreu aqui..."+ $"{erro.StackTrace.LastIndexOf(":line")}"); throw erro; } return View(); } //outra forma de injeçao de dependecia //nao recomendado e utilizado apenas quando nao se pode mexer no construtor da classe public IActionResult Privacy([FromServices]IPedidoRepository pedido) { var pedidorepositorio = pedido.ObterPedido(); return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Game.AI.Health { public class HealthBar : MonoBehaviour { [SerializeField] Image HealthBarFill; public int hp; int MaxBotHp = 100; void Start() { hp = MaxBotHp; } void Update() { HealthBarFill.fillAmount = hp / MaxBotHp; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace BrustShotAndShowApp.ViewModels { public class PhotosViewModel : INotifyPropertyChanged { private double number = 0.0f; public List<ImageSource> ImageList = new List<ImageSource>(); public double Number { get { return number; } set { if (value != number) { if (value < -0.40f) { number = -0.40f; } else if (value > 0.40f) { number = 0.40f; } else { number = Math.Round(value, 2); } OnPropertyChanged(nameof(Number)); } } } private ImageSource image; public ImageSource Image { get { return image; } set { image = value; } } private int index = 0; public int Index { get { return index; } set { index = value; OnPropertyChanged(nameof(Index)); } } void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AI_Behaviour_Tree_Editor { public partial class Form1 : Form { private Point m_imageLocation = new Point(13, 5); private Point m_imageHitArea = new Point(13, 2); Image CloseImage; public Form1() { InitializeComponent(); } private void Form1_Load_1(object sender, EventArgs e) { tabControl1.TabPages.Clear(); tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed; tabControl1.DrawItem += tabControl1_DrawItem; CloseImage = AI_Behaviour_Tree_Editor.Properties.Resources.close; tabControl1.Padding = new Point(10, 3); } private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { try { Image img = new Bitmap(CloseImage); Rectangle r = e.Bounds; r = this.tabControl1.GetTabRect(e.Index); r.Offset(2, 2); string title = this.tabControl1.TabPages[e.Index].Text; Font f = this.Font; Brush titleBrush = new SolidBrush(Color.Black); e.Graphics.DrawString(title, f, titleBrush, new PointF(r.X, r.Y)); if (tabControl1.TabCount >= 0) { e.Graphics.DrawImage(img, new Point(r.X + (this.tabControl1.GetTabRect(e.Index).Width - m_imageLocation.X), m_imageLocation.Y)); } } catch (Exception) { } } private void tabControl1_MouseClick_1(object sender, MouseEventArgs e) { TabControl tc = (TabControl)sender; Point p = e.Location; int m_tabWidth = 0; m_tabWidth = this.tabControl1.GetTabRect(tc.SelectedIndex).Width - (m_imageHitArea.X); Rectangle r = this.tabControl1.GetTabRect(tc.SelectedIndex); r.Offset(m_tabWidth, m_imageHitArea.Y); r.Width = 16; r.Height = 16; if (tabControl1.SelectedIndex >= 0) { if (r.Contains(p)) { TabPage tabP = (TabPage)tc.TabPages[tc.SelectedIndex]; tc.TabPages.Remove(tabP); } } } // New file button private void newFileToolStripMenuItem_Click(object sender, EventArgs e) { TabPage tpage = new TabPage("new tab " + (tabControl1.TabCount + 1).ToString()); tabControl1.TabPages.Add(tpage); } private void saveFileToolStripMenuItem_Click(object sender, EventArgs e) { } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game.Mono; [Attribute38("TGTFood")] public class TGTFood : MonoBehaviour { public TGTFood(IntPtr address) : this(address, "TGTFood") { } public TGTFood(IntPtr address, string className) : base(address, className) { } public void BellAnimation() { base.method_8("BellAnimation", Array.Empty<object>()); } public void HandleHits() { base.method_8("HandleHits", Array.Empty<object>()); } public bool IsOver(GameObject go) { object[] objArray1 = new object[] { go }; return base.method_11<bool>("IsOver", objArray1); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public FoodItem m_CurrentFoodItem { get { return base.method_3<FoodItem>("m_CurrentFoodItem"); } } public FoodItem m_Drink { get { return base.method_3<FoodItem>("m_Drink"); } } public List<FoodItem> m_Food { get { Class267<FoodItem> class2 = base.method_3<Class267<FoodItem>>("m_Food"); if (class2 != null) { return class2.method_25(); } return null; } } public bool m_isAnimating { get { return base.method_2<bool>("m_isAnimating"); } } public int m_lastFoodIdx { get { return base.method_2<int>("m_lastFoodIdx"); } } public float m_NewFoodDelay { get { return base.method_2<float>("m_NewFoodDelay"); } } public bool m_Phone { get { return base.method_2<bool>("m_Phone"); } } public float m_phoneNextCheckTime { get { return base.method_2<float>("m_phoneNextCheckTime"); } } public int m_StartingFoodIndex { get { return base.method_2<int>("m_StartingFoodIndex"); } } public GameObject m_Triangle { get { return base.method_3<GameObject>("m_Triangle"); } } public string m_TriangleSoundPrefab { get { return base.method_4("m_TriangleSoundPrefab"); } } [Attribute38("TGTFood.FoodItem")] public class FoodItem : MonoClass { public FoodItem(IntPtr address) : this(address, "FoodItem") { } public FoodItem(IntPtr address, string className) : base(address, className) { } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Item", menuName = "Item Data", order = 51)] public class Inventory : ScriptableObject { public int ID; public string Name; public int Rank; public int UnitPrice; public string Desception; public string Category; public Sprite Image; private int inventoryCount; public Inventory(int ID, int count) { this.ID = ID; this.inventoryCount= count; } public void SetInventoryItem(Inventory inv) { // to fill all the information to the item list from this.Name = inv.Name; this.Rank = inv.Rank; this.UnitPrice = inv.UnitPrice; this.Desception = inv.Desception; this.Category = inv.Category; this.Image = inv.Image; } public int GetInventoryCount() { return inventoryCount; } public void SetInventoryCount(int value) { inventoryCount = value; } public void SellItem(int value) { inventoryCount -= value; } }
using System; namespace CSsharp.DesignPatterns.Memento { class Program { static void Main(string[] args) { /* * Memento Design Pattern Behavioral'dir * Behavioral nesnelerin çalışma zamanına ait davranışlarını değiştiren bir patterndir. * Nesnelerin hallerini tutmaya ihtiyaç duyduğumuzda * Nesnelerin farklı halleri arasında geçiş yapabilmemiz gerektiği durumlarda */ //Memento Instance Setting setting = new Setting() { UserName = "Mkimyonsen", FirstName = "Mert", LastName = "Kimyonşen", RememberMe = true, LastEdited = DateTime.Now }; Console.WriteLine(setting.ToString()); SettingCareTaker history = new SettingCareTaker(); //backup history.SettingMemento = setting.CreateMemento(); setting.UserName = "hkimyonsen"; setting.LastEdited = DateTime.Now.AddDays(2.0); Console.WriteLine(setting.ToString()); setting.LastEdited = DateTime.Now.AddDays(5); setting.BackUp(history.SettingMemento); Console.WriteLine(setting.ToString()); Console.ReadLine(); } internal class Setting { public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool RememberMe { get; set; } public DateTime LastEdited { get; set; } public SettingMemento CreateMemento() { return new SettingMemento() { UserName = this.UserName, FirstName = this.FirstName, LastName = this.LastName, RememberMe = this.RememberMe, LastEdited = this.LastEdited }; } public void BackUp(SettingMemento memento) { this.UserName = memento.UserName; this.FirstName = memento.FirstName; this.LastName = memento.LastName; this.RememberMe = memento.RememberMe; } public override string ToString() { return $"{this.UserName} {this.FirstName} {this.LastName} {this.RememberMe} last edited: {this.LastEdited}"; } } internal class SettingMemento { public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool RememberMe { get; set; } public DateTime LastEdited { get; set; } } internal class SettingCareTaker { public SettingMemento SettingMemento { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace robotsVDinosResubmit { public class Weapon { public string type; public int attackPower; } }
using DemoDotNet.Taxas.Core; using Xbehave; using Xunit; namespace DemoDotNet.Taxas.Testes { public class TaxaJurosTestes { [Scenario] public void ConsultaDeveRetornarValorFixo(TaxaJurosConsulta consulta, TaxaJurosValorFixoHandler handler, decimal resultado) { "Dada uma consulta de juros sem parâmetros" .x(() => consulta = new TaxaJurosConsulta()); "E um handler de valor fixo" .x(() => handler = new TaxaJurosValorFixoHandler()); "Quando realizarmos a consulta" .x(async () => resultado = await handler.Handle(consulta, default)); "Então a taxa de juros deve ser 0.01" .x(() => Assert.Equal(0.01m, resultado)); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using PlayTennis.Model; namespace PlayTennis.Dal.Mapper { public class AppointmentConfiguration : EntityTypeConfiguration<Appointment>, IEntityMapper { public AppointmentConfiguration() { this.HasRequired(p => p.Initiator).WithMany(p => p.InitiatorAppointments).HasForeignKey(p => p.InitiatorId).WillCascadeOnDelete(false); this.HasRequired(p => p.Invitee).WithMany(p => p.InviteeAppointments).HasForeignKey(p => p.InviteeId).WillCascadeOnDelete(false); } public void RegistTo(System.Data.Entity.ModelConfiguration.Configuration.ConfigurationRegistrar configurationRegistrar) { configurationRegistrar.Add(this); } } }
using UnityEngine; using System.Collections; using DG.Tweening; using com.flashunity.realms.sprites; using com.flashunity.realms.tiles; namespace com.flashunity.realms.person { public class Person : MonoBehaviour { private int state = PersonStates.WAIT; public float TweenDuration = 0.5f; public Transform Tiles; public Cell cell = new Cell();//transform.localPosition); void Start() { ActiveChildName = "Front"; } void Update() { UpdateInput(); } private void UpdateInput() { if (state == PersonStates.WAIT) { if (Input.GetKey(KeyCode.RightArrow)) { Walk(new Cell(1, 0)); return; } if (Input.GetKey(KeyCode.LeftArrow)) { Walk(new Cell(- 1, 0)); return; } if (Input.GetKey(KeyCode.UpArrow)) { Walk(new Cell(0, 1)); return; } if (Input.GetKey(KeyCode.DownArrow)) { Walk(new Cell(0, - 1)); return; } AnimationEnabled = false; } } private string ActiveChildName { set { for (int i=0; i<transform.childCount; i++) { Transform child = transform.GetChild(i); child.gameObject.SetActive(child.name == value); } } } private Transform ActiveChild { get { for (int i=0; i<transform.childCount; i++) { Transform child = transform.GetChild(i); if (child.gameObject.activeSelf) { return child; } } return null; } } private bool AnimationEnabled { set { Transform child = ActiveChild; if (child) { SpritesAnim spritesAnim = child.gameObject.GetComponent("SpritesAnim") as SpritesAnim; spritesAnim.AnimationEnabled = value; } } } /* private Vector3 Direction { set { if (value.x > 0) { ActiveChildName = "Right"; return; } if (value.x < 0) { ActiveChildName = "Left"; return; } if (value.y > 0) { ActiveChildName = "Back"; return; } if (value.y < 0) { ActiveChildName = "Front"; return; } } } */ /* public int GetCellX() { return (int)(transform.localPosition.x / 16); } public int GetCellY() { return (int)(transform.localPosition.y / 16); } */ private void Walk(Cell directionCell) { // Vector3 cellPosition = cell.SetPosition(transform.localPosition); // Vector3 cellDirection = new Vector3(Mathf.Round(transform.localPosition.x), Mathf.Round(transform.localPosition.y), Mathf.Round(transform.localPosition.z)); // Vector3 positionRound = new Vector3(Mathf.Round(transform.localPosition.x), Mathf.Round(transform.localPosition.y), Mathf.Round(transform.localPosition.z)); // Cell cell cell.Vector3 = transform.localPosition; Cell toCell = new Cell(cell + directionCell); // cellDirection = cell + vector; Transform tile = GetTile(toCell); // Debug.Log("tile: " + tile); // return; ActiveChildName = directionCell.Direction; // Direction = cellDirection - cell;//transform.localPosition; if (tile) { Tile tileScript = tile.GetComponent("Tile") as Tile; if (tileScript.Walkable) { state = PersonStates.WALK; AnimationEnabled = true; Vector3 toPosition = new Vector3(toCell.Vector3.x, toCell.Vector3.y, transform.localPosition.z); // Tween(toCell.Vector3); Tween(toPosition); } else { AnimationEnabled = false; } } else { AnimationEnabled = false; } } private Transform GetTile(Cell cell) { // Debug.Log("cell: " + cell); if (Tiles) { for (int i=0; i<Tiles.childCount; i++) { Transform tile = Tiles.GetChild(i); Tile tileScript = tile.GetComponent("Tile") as Tile; // if (tileScript == null) // { // Debug.Log("tile" + tile); //Debug.Log("tileScript.cell: " + tileScript.cell); // } //Debug.Log("tileScript.cell: " + tileScript.cell); /* if (tileScript == null || tileScript.cell == null) { Debug.Log("tileScript.cell: " + tileScript.cell); } */ if (cell != null && tileScript != null && tileScript.cell == cell) { return tile; } } } return null; } // private bool Walkable(Tra) private void Tween(Vector3 position) { // Vector3 dPosition = position - transform.localPosition; // // Direction = dPosition; // DOTween.Kill (transform); // position.z = -100; transform.DOLocalMove(position, TweenDuration).SetEase(Ease.Linear).OnComplete(OnEndTween); } private void OnEndTween() { state = PersonStates.WAIT; } } }
using UnityEditor; using UnityEngine; namespace CoreEditor { [CustomEditor(typeof(Material))] [CanEditMultipleObjects] public class MaterialPrivatePartsInspector : MaterialEditor { const string Tooltip = @"Default = -1 Background = 1000 Geometry = 2000 AlphaTest = 2450 Transparent = 3000 Overlay = 4000"; SerializedProperty mCustomRenderQueue; public override void OnEnable () { base.OnEnable(); mCustomRenderQueue = serializedObject.FindProperty ("m_CustomRenderQueue"); } public override void OnInspectorGUI() { serializedObject.Update(); base.OnInspectorGUI(); EditorGUILayout.PropertyField( mCustomRenderQueue, new GUIContent( "Custom Render Queue *", Tooltip ) ); serializedObject.ApplyModifiedProperties(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* Brett Clark * January 18, 2016 * Change Request * Class declaration, variable declaration * Function declaration */ namespace PalmBusinessLayer { public class Dashboard { public void RequestChangeRequest() { } public void RequestChangeRequestForm() { } public void DeleteChangeRequest() { } string loggedOnRole; int loggedOnUserID; public string LoggedOnRole { get { return loggedOnRole; } set { loggedOnRole = value; } } public int LoggedOnUserID { get { return loggedOnUserID; } set { loggedOnUserID = value; } } } }
namespace Plus.HabboHotel.Talents { public class TalentTrackSubLevel { public int Level { get; set; } public string Badge { get; set; } public int RequiredProgress { get; set; } public TalentTrackSubLevel(int level, string badge, int requiredProgress) { Level = level; Badge = badge; RequiredProgress = requiredProgress; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace csharp_demo.AS2 { public class Product { public int id; public string name; public double price; public int qty; public string image; public string desc; public List<string> gallery; public Product() { } public Product(int id, string name, double price, int qty, string image, string desc, List<string> gallery) { this.id = id; this.name = name; this.price = price; this.qty = qty; this.image = image; this.desc = desc; this.gallery = gallery; } public void GetInfo() { Console.WriteLine("ID: " + id); Console.WriteLine("Name: " + name); Console.WriteLine("Price: " + price); Console.WriteLine("Qty: " + qty); Console.WriteLine("Image: " + image); Console.WriteLine("Desc: " + desc); foreach (string img in gallery) { Console.WriteLine("Gallery: " + img); } } public bool CheckQty() { if (this.qty > 0) { return true; } return false; } public void AddImageToGallery(string image) { if (gallery.Count >= 10) { Console.WriteLine("Nhieu anh qua roi, xoa bot di"); return; } gallery.Add(image); Console.WriteLine("them anh thanh cong"); } public void DeleteImageFromGallery(string image) { if (gallery.Count < 1) { Console.WriteLine("Khong co anh nao de xoa"); return; } Console.WriteLine("Nhap vi tri anh muon xoa"); int index = Convert.ToInt32(Console.ReadLine()); gallery.RemoveAt(index); } } }
using System; namespace Les2Online { class Program { static void Main(string[] args) { int i = 0; Calculator calc = new Calculator(); float circumference = calc.CircumferenceCircle(10f); Console.WriteLine("circ: " + circumference); } } class Calculator { float pi = 3.14f; public void Add(int a, int b) { int c = a + b; Console.WriteLine("a + b = " + c); } public int Multiply(int a, int b) { int c = a * b; Console.WriteLine("a * b = " + c); return c; } public float CircumferenceCircle(float radius) { return radius * radius * pi; } } }
using System.Threading; using System.Threading.Tasks; namespace Mitheti.Core.Services { public interface IWatcherService { Task RunAsync(CancellationToken token); } }
using System; using System.Threading.Tasks; using durable_functions_sample.Shared; using Octokit; namespace durable_functions_sample { public class Github { public static async Task CreateRepoAsync(string repoName) { await SharedServices.GitHubClient.Repository.Create(new NewRepository(repoName)); } public static async Task<(int issueNumber, string issueUrl)> CreateIssueAsync(string text, string repoName) { var createIssue = new NewIssue(text.Length > 150 ? text.Substring(0, 150) : text) { Body = text }; var issue = await SharedServices.GitHubClient.Issue.Create( Environment.GetEnvironmentVariable("GuthubOwner"), repoName, createIssue); return (issue.Number, issue.HtmlUrl); } public static async Task<Issue> AddLabelAsync(int issueNumber, string repoName, string label) { var owner = Environment.GetEnvironmentVariable("GuthubOwner"); var issue = await SharedServices.GitHubClient.Issue.Get(owner, repoName, issueNumber); var issueUpdate = issue.ToUpdate(); issueUpdate.AddLabel(label); return await SharedServices.GitHubClient.Issue.Update( owner, repoName, issue.Number, issueUpdate); } } }
using System; using System.Collections.Generic; using Grimoire.Game.Data; using Grimoire.Tools; namespace Grimoire.Game { public enum LockActions { LoadShop, LoadEnhShop, LoadHairShop, EquipItem, UnequipItem, BuyItem, SellItem, GetMapItem, TryQuestComplete, AcceptQuest, DoIA, Rest, Who, Transfer } public static class World { public static event Action<InventoryItem> ItemDropped; public static event Action<ShopInfo> ShopLoaded; public static List<ShopInfo> LoadedShops = new List<ShopInfo>(); public static DropStack DropStack = new DropStack(); public static void OnItemDropped(InventoryItem drop) => ItemDropped?.Invoke(drop); public static void OnShopLoaded(ShopInfo shopInfo) { ShopLoaded?.Invoke(shopInfo); LoadedShops.Add(shopInfo); } private static readonly Dictionary<LockActions, string> LockedActions = new Dictionary<LockActions, string>(14) { {LockActions.LoadShop, "loadShop"}, {LockActions.LoadEnhShop, "loadEnhShop"}, {LockActions.LoadHairShop, "loadHairShop"}, {LockActions.EquipItem, "equipItem"}, {LockActions.UnequipItem, "unequipItem"}, {LockActions.BuyItem, "buyItem"}, {LockActions.SellItem, "sellItem"}, {LockActions.GetMapItem, "getMapItem"}, {LockActions.TryQuestComplete, "tryQuestComplete"}, {LockActions.AcceptQuest, "acceptQuest"}, {LockActions.DoIA, "doIA"}, {LockActions.Rest, "rest"}, {LockActions.Who, "who"}, {LockActions.Transfer, "tfer"} }; public static List<Monster> AvailableMonsters => Flash.Call<List<Monster>>("GetMonstersInCell"); public static List<Monster> VisibleMonsters => Flash.Call<List<Monster>>("GetVisibleMonstersInCell"); public static bool IsMapLoading => !Flash.Call<bool>("MapLoadComplete"); public static List<string> PlayersInMap => Flash.Call<List<string>>("PlayersInMap"); public static List<InventoryItem> ItemTree => Flash.Call<List<InventoryItem>>("GetItemTree"); public static bool IsActionAvailable(LockActions action) => Flash.Call<bool>("IsActionAvailable", LockedActions[action]); public static void SetSpawnPoint() => Flash.Call("SetSpawnPoint"); public static bool IsMonsterAvailable(string name) => Flash.Call<bool>("IsMonsterAvailable", name); public static string[] Cells => Flash.Call<string[]>("GetCells"); public static int RoomId => Flash.Call<int>("RoomId"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace FinalProject { public partial class UserControlContact : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected void btnContact_Click(object sender, EventArgs e) { Server.Transfer("~/Contact.aspx"); } } }
using Klimatkollen.Data; using Klimatkollen.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Klimatkollen.Components { public class SeeObservationsViewComponent : ViewComponent { private readonly IRepository db; public SeeObservationsViewComponent(IRepository repository) { db = repository; } public async Task<IViewComponentResult> InvokeAsync() { var list = db.GetNews(); List<News> sorted = new List<News>(); for (int i = 0; i < list.Count; i++) { if (i == 0 || i == 1 || i == 2) { sorted.Add(list[i]); } else { break; } } return View(sorted); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; using WS_PosData_PMKT.Models; using System.Configuration; using System.Data.SqlClient; using System.Data; using WS_PosData_PMKT.Models.Object; using WS_PosData_PMKT.Models.Response; using WS_PosData_PMKT.Models.Request; using WS_PosData_PMKT.Helpers; using WS_PosData_PMKT.Models.Base; using System.IO; using System.Globalization; namespace WS_PosData_PMKT { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] // NOTA: puede usar el comando "Rename" del menú "Refactorizar" para cambiar el nombre de clase "WS_PosData_PMKT" en el código, en svc y en el archivo de configuración. // NOTE: para iniciar el Cliente de prueba WCF para probar este servicio, seleccione WS_PosData_PMKT.svc o WS_PosData_PMKT.svc.cs en el Explorador de soluciones e inicie la depuración. public class WS_PosData_PMKT : IWS_PosData_PMKT { private string dbConnection = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString.ToString(); #region WSMETODS public UserDataResponse AutenticateUser(LoginUserRequest request) { UserDataResponse userresponse = new UserDataResponse(); GeneralDataUser datauser = new GeneralDataUser(); Crypto crypto = new Crypto(); DataTable dt = new DataTable(); try { crypto.Cypher(ref request, 2); string email = request.Email; string psw = request.Password; dt = ValidateUser(email, psw); if (dt != null && dt.Rows.Count > 0) { if (dt.Rows[0]["nPER_estatus"].ToString() == "True") { if (dt.Rows[0]["Licencia"].ToString() == "1") { DataTable dt2 = GetGeneralDataUser(dt.Rows[0]["nPER_clave"].ToString()); datauser.IdUser = Convert.ToInt32(dt2.Rows[0]["nPER_clave"].ToString()); datauser.NameEmployee = dt2.Rows[0]["cPER_nombres"].ToString(); datauser.LastName = dt2.Rows[0]["cPER_apellidopaterno"].ToString(); datauser.MothersLastName = dt2.Rows[0]["cPER_apellidomaterno"].ToString(); datauser.IdStaffType = dt2.Rows[0]["nTIP_clave"].ToString(); datauser.NameStaffType = dt2.Rows[0]["cTIP_nombre"].ToString(); datauser.Email = dt2.Rows[0]["cPER_cuentacorreo"].ToString(); userresponse.DataUser = datauser; userresponse.Message = "Proceso exitoso"; userresponse.Success = true; } else { userresponse.Code = "A003"; userresponse.Message = "Cuenta sin licencia."; userresponse.Success = false; } } else { userresponse.Code = "A002"; userresponse.Message = "Cuenta no activa."; userresponse.Success = false; } } else { userresponse.Code = "A001"; userresponse.Message = "Error de credenciales: la cuenta de usuario y/o la contraseña son incorrectos."; userresponse.Success = false; } } catch (Exception ex) { userresponse.Code = "A000"; userresponse.Success = false; userresponse.Message = ex.StackTrace + ". " + ex.Message; } return userresponse; } public ListPromosResponse AvailablePromosUser(string user) { ListPromosResponse listPromos = new ListPromosResponse(); List<InfoPromosUser> lstipu = new List<InfoPromosUser>(); List<Events> lstep = new List<Events>(); DataTable dt = new DataTable(); bool baddesign = false; try { dt = GetListPromosUser(user); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow p in dt.Rows) { DataTable dtep = GetEventsForPromo(p["cPRO_clave"].ToString()); if (dtep != null && dtep.Rows.Count > 0) // verificar si la promo tiene eventos asociados { lstep.Clear(); foreach (DataRow e in dtep.Rows) { lstep.Add(new Events { IdTypeEvent = e["nTIM_clave"].ToString(), NameTypeEvent = e["cTIM_nombre"].ToString() }); } lstipu.Add(new InfoPromosUser { IdClient = p["cCLI_clave"].ToString(), NameClient = p["cCLI_nombre"].ToString(), IdPromo = p["cPRO_clave"].ToString(), NamePromo = p["cPRO_nombre"].ToString(), AvailableEvents = lstep, ValidateCheckIn = Convert.ToBoolean(p["bPRO_validarcheckin"].ToString()), URLReceptionData = p["cPRO_evidenciafotografica"].ToString() }); } else { baddesign = true; } } if (baddesign) { listPromos.Code = "P002"; listPromos.Message = "Error general de Promoción: Promoción mal diseñada."; listPromos.Success = false; } else { listPromos.AvailablePromosUser = lstipu; listPromos.Message = "Proceso exitoso"; listPromos.Success = true; } } else { listPromos.Code = "P001"; listPromos.Message = "Cuenta sin Promociones."; listPromos.Success = false; } } catch (Exception ex) { listPromos.Code = "A000"; listPromos.Success = false; listPromos.Message = ex.StackTrace + ". " + ex.Message; } return listPromos; } public DetailEventsPromoResponse DetailEventsPromo(string IdPromo) { DetailEventsPromoResponse detaileventsresponse = new DetailEventsPromoResponse(); DetailEventsPromo detailevent = new Models.Object.DetailEventsPromo(); detailevent.ListNoVisitMotive = new List<NoVisitMotive>(); detailevent.ListSurvey = new List<Survey>(); detailevent.ListTypeEvidence = new List<PhotographicEvidence>(); detailevent.ListProductsByCategory = new List<Products>(); detailevent.ListKPI = new List<KPI>(); detailevent.ListUbication = new List<UbicationProduct>(); detailevent.ListTypeMaterial = new List<TypeMaterial>(); int countEmptyTables = 0; try { DataTable dt = GetModulesPromo(IdPromo); DataSet ds = GetDataDetailPromo(IdPromo); foreach (DataRow te in dt.Rows) { int i = int.Parse(te["nTIM_clave"].ToString()); switch (i) { case 1: if (ds.Tables[0].Rows.Count == 0) { countEmptyTables += 1; } else { detailevent.ListNoVisitMotive = FillListNoVisit(ds.Tables[0]); } break; case 3: if (ds.Tables[1].Rows.Count == 0) { countEmptyTables += 1; } else { detailevent.ListSurvey = FillListSurvey(ds.Tables[1]); } break; case 4: if (ds.Tables[2].Rows.Count == 0) { countEmptyTables += 1; } else { detailevent.ListTypeEvidence = FillTypeEvidence(ds.Tables[2]); } break; case 5: if (ds.Tables[3].Rows.Count == 0) { countEmptyTables += 1; } if (ds.Tables[6].Rows.Count == 0) { countEmptyTables += 1; } else { detailevent.ListProductsByCategory = FillListProducts(ds.Tables[3]); detailevent.ListKPI = FillListKPI(ds.Tables[6]); } break; case 6: for (int n = 3; n < ds.Tables.Count; n++) { if (ds.Tables[i].Rows.Count == 0) { countEmptyTables += 1; } } detailevent.ListProductsByCategory = new List<Products>(); detailevent.ListProductsByCategory = FillListProducts(ds.Tables[3]); detailevent.ListUbication = FillListUbication(ds.Tables[5]); break; case 7: if (ds.Tables[4].Rows.Count == 0) { countEmptyTables += 1; } else { detailevent.ListTypeMaterial = FillListMaterial(ds.Tables[4]); } break; default: break; } } detaileventsresponse.DetailEvents = detailevent; detaileventsresponse.Message = "Proceso Exitoso."; detaileventsresponse.Success = true; if (ds.Tables.Count == countEmptyTables) { detaileventsresponse.Code = "MS001"; detaileventsresponse.Message = "Estructura de datos vacía"; detaileventsresponse.Success = true; } } catch (Exception ex) { detaileventsresponse.Code = "P002"; detaileventsresponse.Message = "Error general de Promoción: Promoción mal diseñada. " + ex.StackTrace; detaileventsresponse.Success = false; } return detaileventsresponse; } public DataRoutePromoResponse DataRoutePromo(string Email, string IdPromo, string IdDay) { DataRoutePromoResponse routeResponse = new DataRoutePromoResponse(); GeneralDataRoute dataroute = new GeneralDataRoute(); List<InfoRoutesPromo> lstruta = new List<InfoRoutesPromo>(); List<InfoRoutesPromo> lstOutRoute = new List<InfoRoutesPromo>(); List<InfoRoutesPromo> lstVisited = new List<InfoRoutesPromo>(); try { DataSet ds = GetDataRoute(Email, IdPromo, Convert.ToInt32(IdDay)); if (ds.Tables[0].Rows.Count > 0) { dataroute.IdRoute = ds.Tables[0].Rows[0]["cRUT_clave"].ToString(); dataroute.NameRoute = ds.Tables[0].Rows[0]["cRUT_nombre"].ToString(); dataroute.IdRegion = ds.Tables[0].Rows[0]["cREG_clave"].ToString(); dataroute.NameRegion = ds.Tables[0].Rows[0]["cREG_nombre"].ToString(); dataroute.IdCity = ds.Tables[0].Rows[0]["cCIU_clave"].ToString(); dataroute.NameCity = ds.Tables[0].Rows[0]["cCIU_nombre"].ToString(); dataroute.NameSupervisor = ds.Tables[0].Rows[0]["Supervisor"].ToString(); if (ds.Tables[1].Rows.Count > 0) { foreach (DataRow r in ds.Tables[1].Rows) { lstruta.Add(new InfoRoutesPromo { IdCity = r["cCIU_clave"].ToString(), IdRegion = r["cREG_clave"].ToString(), IdStore = r["cTIE_clave"].ToString(), NameCity = r["cCIU_nombre"].ToString(), NameRegion = r["cREG_nombre"].ToString(), NameStore = r["cTIE_nombre"].ToString(), Latitude = r["cTIE_latitud"].ToString(), Longitude = r["cTIE_longitud"].ToString(), CheckInRange = r["nTIE_rangocheckin"].ToString() }); } dataroute.ListScheduledRoute = lstruta; routeResponse.Success = true; routeResponse.Message = "Proceso exitoso."; } else { /* routeResponse.Code = "MS001"; routeResponse.Success = true; routeResponse.Message = "Estructura de datos vacía.";*/ DataTable dt = GetMotiveNoStores(Email, IdPromo, Convert.ToInt32(IdDay)); routeResponse.Code = dt.Rows[0]["cVAR_clave"].ToString() == "WSTextoRutaConcluida" ? "MS002" : "MS001"; routeResponse.Success = true; routeResponse.Message = dt.Rows[0]["cVAR_valor"].ToString(); } if (ds.Tables[2].Rows.Count > 0) { foreach (DataRow r in ds.Tables[2].Rows) { lstOutRoute.Add(new InfoRoutesPromo { IdCity = r["cCIU_clave"].ToString(), IdRegion = r["cREG_clave"].ToString(), IdStore = r["cTIE_clave"].ToString(), NameCity = r["cCIU_nombre"].ToString(), NameRegion = r["cREG_nombre"].ToString(), NameStore = r["cTIE_nombre"].ToString(), Latitude = r["cTIE_latitud"].ToString(), Longitude = r["cTIE_longitud"].ToString(), CheckInRange = r["nTIE_rangocheckin"].ToString() }); } dataroute.ListScopePromoRoute = lstOutRoute; } if (ds.Tables[3].Rows.Count > 0) { foreach (DataRow r in ds.Tables[3].Rows) { lstVisited.Add(new InfoRoutesPromo { IdCity = r["cCIU_clave"].ToString(), IdRegion = r["cREG_clave"].ToString(), IdStore = r["cTIE_clave"].ToString(), NameCity = r["cCIU_nombre"].ToString(), NameRegion = r["cREG_nombre"].ToString(), NameStore = r["cTIE_nombre"].ToString(), Latitude = r["cTIE_latitud"].ToString(), Longitude = r["cTIE_longitud"].ToString(), CheckInRange = r["nTIE_rangocheckin"].ToString() }); } dataroute.ListVisitedStores = lstVisited; } routeResponse.DataRoute = dataroute; } else { routeResponse.Code = "R001"; routeResponse.Success = false; routeResponse.Message = "Sin asignación de Ruta: la cuenta de usuario no tiene asociada una ruta."; } } catch (Exception ex) { routeResponse.Code = "P002"; routeResponse.Success = false; routeResponse.Message = "Error general de Promoción: Promoción mal diseñada. " + ex.StackTrace + ex.Message; } return routeResponse; } public LoginUserRequest ObtieneDatosEmcriptados() { LoginUserRequest response = new LoginUserRequest() { Email = "aperez@miportal-promarket.mx", Password = "26202", getfechaactual = DateTime.Now }; Crypto c = new Crypto(); c.Cypher(response, 1); return response; } public ResponseBase RegisterCheckin(RegisterCheckinRequest request) { ResponseBase response = new ResponseBase(); try { if (request.IdMotive != null) { SaveMotiveNoVisit(request); } else { SaveCheckinData(request); } response.Code = "S001"; response.Message = "Sincronización exitosa."; response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } public ResponseBase RegisterCheckout(RegisterCheckoutRequest request) { ResponseBase response = new ResponseBase(); try { SaveCheckoutData(request); response.Code = "S001"; response.Message = "Sincronización exitosa."; response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } public ResponseBase RegisterSurvey(RegisterSurveyRequest request) { ResponseBase response = new ResponseBase(); try { SaveSurveyData(request); response.Code = "S001"; response.Message = "Sincronización exitosa." + request.DateTimeStartEvent.ToString(); response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } public ResponseBase ResetPassword(string Email) { ResponseBase response = new ResponseBase(); try { if (ValidateEmail(Email) == true) { GenerateSendPassword(Email); response.Message = "Proceso Exitoso."; response.Success = true; } else { response.Code = "A001"; response.Message = "Error de credenciales: la cuenta de usuario y/o la contraseña son incorrectos."; response.Success = false; } } catch (Exception ex) { response.Code = "A000"; response.Success = false; response.Message = ex.StackTrace + ". " + ex.Message; } return response; } public ResponseBase RegisterSale(RegisterSalesRequest request) { ResponseBase response = new ResponseBase(); try { string idsync = request.IdSync; string idstore = request.IdStore; DateTime startdate = request.StartEventDate; DateTime enddate = request.StartEventDate; foreach (DataProductKPI pkpi in request.ListProductsKPI) { SaveSaleData(idsync, idstore, pkpi, startdate, enddate); } response.Code = "S001"; response.Message = "Sincronización exitosa."; response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } public ResponseBase RegisterAudit(RegisterAuditRequest request) { ResponseBase response = new ResponseBase(); try { string idsync = request.IdSync; string idstore = request.IdStore; DateTime startdate = request.StartEventDate; DateTime enddate = request.StartEventDate; foreach (DataProductAudit pa in request.ListProductsAudit) { SaveAuditData(idsync, idstore, pa, startdate, enddate); } response.Code = "S001"; response.Message = "Sincronización exitosa. "; response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } public ResponseBase RegisterPlacement(RegisterPlacementRequest request) { ResponseBase response = new ResponseBase(); try { string idsync = request.IdSync; string idstore = request.IdStore; DateTime startdate = request.StartEventDate; DateTime enddate = request.StartEventDate; foreach (DataMaterialPlacement mp in request.ListMaterialPlacement) { SavePlacementData(idsync, idstore, mp, startdate, enddate); } response.Code = "S001"; response.Message = "Sincronización exitosa."; response.Success = true; } catch (Exception ex) { response.Code = "S002"; response.Message = "Error de sincronización: No se pudo realizar el proceso de sincronización. " + ex.StackTrace + ex.Message; response.Success = false; } return response; } #endregion #region HELPERMETODS private DataTable ValidateUser(string email, string psw) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "ValidateUser")); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", email)); command.Parameters.Add(new SqlParameter("cPER_contrasena", psw)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); }; } catch (Exception ex) { throw ex; } return dt; } private DataTable GetGeneralDataUser(string user) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "GetGeneralDataUser")); command.Parameters.Add(new SqlParameter("nPER_clave", user)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); }; } catch (Exception ex) { throw ex; } return dt; } private DataTable GetListPromosUser(string user) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "GetListPromosUser")); command.Parameters.Add(new SqlParameter("nPER_clave", user)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); }; } catch (Exception ex) { throw ex; } return dt; } private DataTable GetEventsForPromo(string p) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "GetEventsForPromo")); command.Parameters.Add(new SqlParameter("cPRO_clave", p)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); }; } catch (Exception ex) { throw ex; } return dt; } private DataTable GetModulesPromo(string p) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "ActiveModulesPromo")); command.Parameters.Add(new SqlParameter("cPRO_clave", p)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(dt); }; } catch (Exception ex) { throw ex; } return dt; } private DataSet GetDataDetailPromo(string idPromo) { DataSet ds = new DataSet(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "DetailEvents")); command.Parameters.Add(new SqlParameter("cPRO_clave", idPromo)); SqlDataAdapter da = new SqlDataAdapter(command); da.Fill(ds); } } catch (Exception ex) { throw ex; } return ds; } private List<KPI> FillListKPI(DataTable dataTable) { List<KPI> lstKPI = new List<KPI>(); try { foreach (DataRow r in dataTable.Rows) { lstKPI.Add(new KPI { IdKPI = r["cKPI_clave"].ToString(), NameKPI = r["cKPI_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstKPI; } private List<UbicationProduct> FillListUbication(DataTable dataTable) { List<UbicationProduct> lstUbication = new List<UbicationProduct>(); try { foreach (DataRow r in dataTable.Rows) { lstUbication.Add(new UbicationProduct { IdUbication = r["cUPR_clave"].ToString(), NameUbication = r["cUPR_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstUbication; } private List<TypeMaterial> FillListMaterial(DataTable dataTable) { List<TypeMaterial> lstMaterial = new List<TypeMaterial>(); try { foreach (DataRow r in dataTable.Rows) { lstMaterial.Add(new TypeMaterial { IdTypeMaterial = r["cTIM_clave"].ToString(), NameTypeMaterial = r["cTIM_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstMaterial; } private List<Products> FillListProducts(DataTable dataTable) { List<Products> lstProducts = new List<Products>(); try { foreach (DataRow r in dataTable.Rows) { lstProducts.Add(new Products { IdCategory = r["cCAP_clavecategoria"].ToString(), NameCategory = r["cCAP_nombre"].ToString(), IdProduct = r["cPRD_claveproducto"].ToString(), NameProduct = r["cPRD_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstProducts; } private List<PhotographicEvidence> FillTypeEvidence(DataTable dataTable) { List<PhotographicEvidence> lstEvidence = new List<PhotographicEvidence>(); try { foreach (DataRow r in dataTable.Rows) { lstEvidence.Add(new PhotographicEvidence { IdTypeEvidence = r["nTEF_clave"].ToString(), NameTypeEvidence = r["cTEF_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstEvidence; } private List<Survey> FillListSurvey(DataTable dataTable) { List<Survey> lstSurvey = new List<Survey>(); try { foreach (DataRow r in dataTable.Rows) { lstSurvey.Add(new Survey { IdSurvey = r["cENC_clave"].ToString(), NameSurvey = r["cENC_nombre"].ToString(), Question1 = r["cENC_pregunta1"].ToString(), Question2 = r["cENC_pregunta2"].ToString(), Question3 = r["cENC_pregunta3"].ToString(), Question4 = r["cENC_pregunta4"].ToString(), Question5 = r["cENC_pregunta5"].ToString(), Question6 = r["cENC_pregunta6"].ToString(), Question7 = r["cENC_pregunta7"].ToString(), Question8 = r["cENC_pregunta8"].ToString(), Question9 = r["cENC_pregunta9"].ToString(), Question10 = r["cENC_pregunta10"].ToString(), Question11 = r["cENC_pregunta11"].ToString(), Question12 = r["cENC_pregunta12"].ToString(), Question13 = r["cENC_pregunta13"].ToString(), Question14 = r["cENC_pregunta14"].ToString(), Question15 = r["cENC_pregunta15"].ToString() }); } } catch (Exception ex) { throw ex; } return lstSurvey; } private List<NoVisitMotive> FillListNoVisit(DataTable dataTable) { List<NoVisitMotive> lstNoVisit = new List<NoVisitMotive>(); try { foreach (DataRow r in dataTable.Rows) { lstNoVisit.Add(new NoVisitMotive { IdMotive = r["cMNV_clave"].ToString(), NameMotive = r["cMNV_nombre"].ToString() }); } } catch (Exception ex) { throw ex; } return lstNoVisit; } private DataSet GetDataRoute(string email, string idPromo, int idDay) { DataSet ds = new DataSet(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "DataRoute")); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", email)); command.Parameters.Add(new SqlParameter("cPRO_clave", idPromo)); command.Parameters.Add(new SqlParameter("nDIP_clave", idDay)); SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(ds); } } catch (Exception ex) { throw ex; } return ds; } private void SaveCheckinData(RegisterCheckinRequest request) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveCheckinData")); command.Parameters.Add(new SqlParameter("nSIN_clave", request.IdSync)); command.Parameters.Add(new SqlParameter("cRUT_clave", request.IdRoute)); command.Parameters.Add(new SqlParameter("cPRO_clave", request.IdPromo)); command.Parameters.Add(new SqlParameter("nDIP_clave", request.IdDay)); command.Parameters.Add(new SqlParameter("cTIE_clave", request.IdStore)); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", request.Email)); command.Parameters.Add(new SqlParameter("cMNV_clave", request.IdMotive)); command.Parameters.Add(new SqlParameter("bSIN_checkin", request.ValidCheckin)); command.Parameters.Add(new SqlParameter("cSIN_checkinlatitud", request.Latitude)); command.Parameters.Add(new SqlParameter("cSIN_checkinlongitud", request.Longitude)); command.Parameters.Add(new SqlParameter("dSIN_checkinfecha", request.DateCheckin.ToString("yyyy-MM-dd"))); command.Parameters.Add(new SqlParameter("dSIN_checkinhora", request.TimeCheckin.ToString("HH:mm:s"))); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private void SaveMotiveNoVisit(RegisterCheckinRequest request) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveMotiveNoVisit")); command.Parameters.Add(new SqlParameter("nSIN_clave", request.IdSync)); command.Parameters.Add(new SqlParameter("cRUT_clave", request.IdRoute)); command.Parameters.Add(new SqlParameter("cPRO_clave", request.IdPromo)); command.Parameters.Add(new SqlParameter("nDIP_clave", request.IdDay)); command.Parameters.Add(new SqlParameter("cTIE_clave", request.IdStore)); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", request.Email)); command.Parameters.Add(new SqlParameter("cMNV_clave", request.IdMotive)); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private void SaveCheckoutData(RegisterCheckoutRequest request) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveCheckoutData")); command.Parameters.Add(new SqlParameter("nSIN_clave", request.IdSync)); command.Parameters.Add(new SqlParameter("cSIN_checkoutobservaciones", request.CommentsCheckout)); command.Parameters.Add(new SqlParameter("bSIN_checkout", request.ValidCheckout)); command.Parameters.Add(new SqlParameter("cSIN_checkoutlatitud", request.Latitude)); command.Parameters.Add(new SqlParameter("cSIN_checkoutlongitud", request.Longitude)); command.Parameters.Add(new SqlParameter("dSIN_checkoutfecha", request.DateCheckout.ToString("yyyy-MM-dd"))); command.Parameters.Add(new SqlParameter("dSIN_checkouthora", request.TimeCheckout.ToString("HH:mm:s"))); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private void SaveSurveyData(RegisterSurveyRequest request) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveSurveyData")); command.Parameters.Add(new SqlParameter("nSIN_clave", request.IdSync)); command.Parameters.Add(new SqlParameter("cTIE_clave", request.IdStore)); command.Parameters.Add(new SqlParameter("cENC_clave", request.IdSurvey)); command.Parameters.Add(new SqlParameter("cENC_comentarios", request.CommentsCheckout)); command.Parameters.Add(new SqlParameter("dENC_horainicio", request.DateTimeStartEvent.ToString("MM/dd/yyyy hh:mm:ss"))); command.Parameters.Add(new SqlParameter("dENC_horatermino", request.DateTimeEndEvent.ToString("MM/dd/yyyy hh:mm:ss"))); //command.Parameters.Add(new SqlParameter("dENC_horainicio", request.DateTimeStartEvent)); //command.Parameters.Add(new SqlParameter("dENC_horatermino", request.DateTimeEndEvent)); command.Parameters.Add(new SqlParameter("bENC_respuesta1", request.Answer1)); command.Parameters.Add(new SqlParameter("bENC_respuesta2", request.Answer2)); command.Parameters.Add(new SqlParameter("bENC_respuesta3", request.Answer3)); command.Parameters.Add(new SqlParameter("bENC_respuesta4", request.Answer4)); command.Parameters.Add(new SqlParameter("bENC_respuesta5", request.Answer5)); command.Parameters.Add(new SqlParameter("bENC_respuesta6", request.Answer6)); command.Parameters.Add(new SqlParameter("bENC_respuesta7", request.Answer7)); command.Parameters.Add(new SqlParameter("bENC_respuesta8", request.Answer8)); command.Parameters.Add(new SqlParameter("bENC_respuesta9", request.Answer9)); command.Parameters.Add(new SqlParameter("bENC_respuesta10", request.Answer10)); command.Parameters.Add(new SqlParameter("bENC_respuesta11", request.Answer11)); command.Parameters.Add(new SqlParameter("bENC_respuesta12", request.Answer12)); command.Parameters.Add(new SqlParameter("bENC_respuesta13", request.Answer13)); command.Parameters.Add(new SqlParameter("bENC_respuesta14", request.Answer14)); command.Parameters.Add(new SqlParameter("bENC_respuesta15", request.Answer15)); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private bool ValidateEmail(string email) { bool valid = false; object user = string.Empty; try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "ValidateEmail")); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", email)); user = command.ExecuteScalar(); }; if (!string.IsNullOrEmpty(user.ToString())) { valid = true; } } catch (Exception ex) { throw ex; } return valid; } private void GenerateSendPassword(string email) { int length = 5; var sb = new StringBuilder(length); while (sb.Length < length) { var tmp = System.Web.Security.Membership.GeneratePassword(length, 0); foreach (var c in tmp) { if (char.IsDigit(c)) { sb.Append(c); if (sb.Length == length) { break; } } } } try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "UpdateSendPassword")); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", email)); command.Parameters.Add(new SqlParameter("cPER_contrasena", sb.ToString())); command.ExecuteNonQuery(); }; } catch (Exception ex) { throw ex; } } private DataTable GetMotiveNoStores(string email, string idPromo, int idDay) { DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "MensajeRutaDelDia")); command.Parameters.Add(new SqlParameter("cPER_cuentacorreo", email)); command.Parameters.Add(new SqlParameter("cPRO_clave", idPromo)); command.Parameters.Add(new SqlParameter("nDIP_clave", idDay)); SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(dt); } } catch (Exception ex) { throw ex; } return dt; } private void SaveSaleData(string idsync, string idstore, DataProductKPI pkpi, DateTime startdate, DateTime enddate) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveSale")); command.Parameters.Add(new SqlParameter("nSIN_clave", idsync)); command.Parameters.Add(new SqlParameter("cTIE_clave", idstore)); command.Parameters.Add(new SqlParameter("dVEN_horainicio", startdate)); command.Parameters.Add(new SqlParameter("dVEN_horatermino", enddate)); command.Parameters.Add(new SqlParameter("cCAP_clavecategoria", pkpi.IdCategory)); command.Parameters.Add(new SqlParameter("cKPI_clave", pkpi.IdKPI)); command.Parameters.Add(new SqlParameter("cPRD_claveproducto", pkpi.IdProduct)); command.Parameters.Add(new SqlParameter("cVEN_valor", pkpi.KPIValue)); command.Parameters.Add(new SqlParameter("cVEN_observaciones", pkpi.ObservationsSale)); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private void SaveAuditData(string idsync, string idstore, DataProductAudit pa, DateTime startdate, DateTime enddate) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SaveAudit")); command.Parameters.Add(new SqlParameter("nSIN_clave", idsync)); command.Parameters.Add(new SqlParameter("cTIE_clave", idstore)); command.Parameters.Add(new SqlParameter("dAUD_horainicio", startdate)); command.Parameters.Add(new SqlParameter("dAUD_horatermino", enddate)); command.Parameters.Add(new SqlParameter("cCAP_clavecategoria", pa.IdCategory)); command.Parameters.Add(new SqlParameter("cPRD_claveproducto", pa.IdProduct)); command.Parameters.Add(new SqlParameter("nAUD_inventario", pa.FinalInventory)); command.Parameters.Add(new SqlParameter("nAUD_frente", pa.Front)); command.Parameters.Add(new SqlParameter("cUPR_clave", pa.IdUbication)); command.Parameters.Add(new SqlParameter("nAUD_posicion", pa.Position)); command.Parameters.Add(new SqlParameter("nAUD_precio", pa.Price)); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } private void SavePlacementData(string idsync, string idstore, DataMaterialPlacement mp, DateTime startdate, DateTime enddate) { try { using (SqlConnection connection = new SqlConnection(dbConnection)) { connection.Open(); SqlCommand command = new SqlCommand("spWS_PosData_PMKTData", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("Action", "SavePlacement")); command.Parameters.Add(new SqlParameter("nSIN_clave", idsync)); command.Parameters.Add(new SqlParameter("cTIE_clave", idstore)); command.Parameters.Add(new SqlParameter("dCOL_horainicio", startdate)); command.Parameters.Add(new SqlParameter("dCOL_horatermino", enddate)); command.Parameters.Add(new SqlParameter("cTIM_clave", mp.IdTypeMaterial)); command.Parameters.Add(new SqlParameter("nCOL_nuevo", string.IsNullOrEmpty(mp.New)?"0": mp.New)); command.Parameters.Add(new SqlParameter("nCOL_cantidad", string.IsNullOrEmpty(mp.Amount) ? "0" : mp.Amount)); command.ExecuteNonQuery(); } } catch (Exception ex) { throw ex; } } #endregion } }
namespace RealEstate.EnumType.Models { using System.ComponentModel; public enum OrderStatus { [Description("Đang Giao Dịch")] InProcess = 0, [Description("Đã Xong")] Done = 1, [Description("Đã Hủy")] Cancel = 2, } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; namespace SampleBrowser { public class GridGettingStarted :SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public GridGettingStarted () { this.SfGrid = new SfDataGrid (); this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.ItemsSource = new GridGettingStartedViewModel().OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.AlternatingRowColor = UIColor.FromRGB (219, 219, 219); this.control = this; this.AddSubview (this.SfGrid); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Index") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 20; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextMargin = 30; e.Column.TextAlignment = UITextAlignment.Left; } } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } } }
/* * Copyright 2014 Technische Universitšt Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using JetBrains.Application; using KaVE.Commons.Utils.CodeCompletion; using KaVE.Commons.Utils.IO; using KaVE.RS.Commons.CodeCompletion; using KaVE.RS.Commons.Settings; using KaVE.RS.Commons.Settings.KaVE.RS.Commons.Settings; namespace KaVE.RS.Commons.Injectables { [ShellComponent] public class InjectablePBNRecommenderStore : SmilePBNRecommenderStore { public InjectablePBNRecommenderStore(IIoUtils io, ISettingsStore store, TypePathUtil typePathUtil) : base(store.GetSettings<ModelStoreSettings>().ModelStorePath, io, typePathUtil) { store.SettingsChanged += (sender, args) => { if (args.SettingsType == typeof(ModelStoreSettings)) { BasePath = store.GetSettings<ModelStoreSettings>().ModelStorePath; } }; } } }
namespace HCL.Academy.Model { public class RoleTrainingRequest :RequestBase { public int ItemId { get; set; } public int TrainingId { get; set; } public int RoleId { get; set; } public bool IsMandatory { get; set; } } }
using FluentValidation; using Publicon.Infrastructure.Commands.Models.User; namespace Publicon.Api.Validators.User { public class RefreshTokenCommandValidator : AbstractValidator<RefreshTokenCommand> { public RefreshTokenCommandValidator() { RuleFor(p => p.RefreshToken) .NotEmpty() .NotNull(); } } }
using System.Collections.Generic; using System.Linq; namespace StreetFinder.AbbreviationsFilter { public class AbbreviationTokenExpander { private readonly List<string> _tokensList = new List<string>(); private int _index = -1; private string lastToken; readonly AbbreviationsEngine _abbreviationsEngine = new AbbreviationsEngine(); public void Add(string token) { List<string> abbreviations; _tokensList.Add(token); if (token.EndsWith("str")) { if (_abbreviationsEngine.HasAbbreviationsOrIsAbbreviation("str", out abbreviations)) { foreach (var abbreviation in abbreviations) { _tokensList.Add(abbreviation); } } } if (_abbreviationsEngine.HasAbbreviationsOrIsAbbreviation(token, out abbreviations)) { foreach (var abbreviation in abbreviations) { _tokensList.Add(abbreviation); } } } public bool NextElement() { _index++; if (_tokensList.Count <= 0 || _index >= _tokensList.Count) { return false; } return true; } public string ElementAt(int position) { if (_tokensList.Count <= 0 || position >= _tokensList.Count || position < 0) { return null; } return _tokensList.ElementAt(position); } public string CurrentElement() { if (_tokensList.Count <= 0 || _index >= _tokensList.Count) { return null; } return _tokensList.ElementAt(_index); } public int Count() { return _tokensList.Count; } } }
using Checkout.Payment.Command.Application.Models; using Checkout.Payment.Command.Seedwork.Extensions; using System; using System.Threading.Tasks; namespace Checkout.Payment.Command.Application.Interfaces { public interface IPaymentService { Task<ITryResult<CreatePaymentResponseModel>> TryCreatePaymentAsync(int merchantId, CreatePaymentRequestModel requestModel); Task<ITryResult<bool>> TryUpdatePaymentAsync(Guid paymentId, UpdatePaymentRequestModel requestModel); } }
/* VIA https://github.com/SLaks/Minimatch The MIT License (MIT) Copyright (c) 2014 SLaks Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Xunit; // ReSharper disable once CheckNamespace namespace Minimatch.Tests { public class BasicTests { private static readonly List<Tuple<string, string>> actualRegexes = new List<Tuple<string, string>>(); private static void TestCase(string pattern, IList<string> expected, Options? options = null, IEnumerable<string>? input = null) { input ??= Files; Assert.Equal( string.Join(Environment.NewLine, expected.OrderBy(s => s)), string.Join(Environment.NewLine, Minimatcher.Filter(input, pattern, options).OrderBy(s => s)) ); var regex = Minimatcher.CreateRegex(pattern, options); actualRegexes.Add(Tuple.Create(pattern, regex == null ? "false" : "/" + regex + "/" + ( regex.Options == RegexOptions.IgnoreCase ? "i" : "" ))); } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void AssertRegexes(params string[] expectedRegexes) { Assert.Equal(expectedRegexes.Length, actualRegexes.Count); for (var i = 0; i < actualRegexes.Count; i++) { Assert.Equal(expectedRegexes[i], actualRegexes[i].Item2); } } private static void AddFiles(params string[] entries) => Files.AddRange(entries); private static void ReplaceFiles(params string[] entries) { Files.Clear(); Files.AddRange(entries); } private static readonly List<string> Files = new List<string>(); public BasicTests() { ReplaceFiles( "a", "b", "c", "d", "abc" , "abd", "abe", "bb", "bcd" , "ca", "cb", "dd", "de" , "bdir/", "bdir/cfile" ); actualRegexes.Clear(); } [Fact] public void BashCookBook() { //"http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test" TestCase("a*", new[] { "a", "abc", "abd", "abe" }); TestCase("X*", new[] { "X*" }, new Options { NoNull = true }); // allow null glob expansion TestCase("X*", new string[0]); // isaacs: Slightly different than bash/sh/ksh // \\* is not un-escaped to literal "*" in a failed match, // but it does make it get treated as a literal star TestCase("\\*", new[] { "\\*" }, new Options { NoNull = true }); TestCase("\\**", new[] { "\\**" }, new Options { NoNull = true }); TestCase("\\*\\*", new[] { "\\*\\*" }, new Options { NoNull = true }); TestCase("b*/", new[] { "bdir/" }); TestCase("c*", new[] { "c", "ca", "cb" }); TestCase("**", Files); TestCase("\\.\\./*/", new[] { "\\.\\./*/" }, new Options { NoNull = true }); TestCase("s/\\..*//", new[] { "s/\\..*//" }, new Options { NoNull = true }); AssertRegexes( "/^(?:(?=.)a[^/]*?)$/", "/^(?:(?=.)X[^/]*?)$/", "/^(?:(?=.)X[^/]*?)$/", "/^(?:\\*)$/", "/^(?:(?=.)\\*[^/]*?)$/", "/^(?:\\*\\*)$/", "/^(?:(?=.)b[^/]*?\\/)$/", "/^(?:(?=.)c[^/]*?)$/", "/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/", "/^(?:\\.\\.\\/(?!\\.)(?=.)[^/]*?\\/)$/", "/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/" ); } [Fact] public void LegendaryLarryCrashesBashes() { TestCase( "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\\1/" }, new Options { NoNull = true } ); TestCase( "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" , new[] { "/^root:/{s/^[^:]*:[^:]*:([^:]*).*$/\u0001/" }, new Options { NoNull = true } ); AssertRegexes( "/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/", "/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/" ); } [Fact] public void CharacterClasses() { TestCase("[a-c]b*", new[] { "abc", "abd", "abe", "bb", "cb" }); TestCase( "[a-y]*[^c]", new[] { "abd", "abe", "bb", "bcd", "bdir/", "ca", "cb", "dd", "de" } ); TestCase("a*[^c]", new[] { "abd", "abe" }); AddFiles("a-b", "aXb"); TestCase("a[X-]b", new[] { "a-b", "aXb" }); AddFiles(".x", ".y"); TestCase("[^a-c]*", new[] { "d", "dd", "de" }); AddFiles("a*b/", "a*b/ooo"); TestCase("a\\*b/*", new[] { "a*b/ooo" }); TestCase("a\\*?/*", new[] { "a*b/ooo" }); TestCase("*\\\\!*", new string[0], new Options(), new[] { "echo !7" }); TestCase("*\\!*", new[] { "echo !7" }, null, new[] { "echo !7" }); TestCase("*.\\*", new[] { "r.*" }, null, new[] { "r.*" }); TestCase("a[b]c", new[] { "abc" }); TestCase("a[\\b]c", new[] { "abc" }); TestCase("a?c", new[] { "abc" }); TestCase("a\\*c", new string[0], new Options(), new[] { "abc" }); TestCase("", new[] { "" }, new Options(), new[] { "" }); AssertRegexes( "/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/", "/^(?:(?!\\.)(?=.)[a-y][^/]*?[^c])$/", "/^(?:(?=.)a[^/]*?[^c])$/", "/^(?:(?=.)a[X-]b)$/", "/^(?:(?!\\.)(?=.)[^a-c][^/]*?)$/", "/^(?:a\\*b\\/(?!\\.)(?=.)[^/]*?)$/", "/^(?:(?=.)a\\*[^/]\\/(?!\\.)(?=.)[^/]*?)$/", "/^(?:(?!\\.)(?=.)[^/]*?\\\\\\![^/]*?)$/", "/^(?:(?!\\.)(?=.)[^/]*?\\![^/]*?)$/", "/^(?:(?!\\.)(?=.)[^/]*?\\.\\*)$/", "/^(?:(?=.)a[b]c)$/", "/^(?:(?=.)a[b]c)$/", "/^(?:(?=.)a[^/]c)$/", "/^(?:a\\*c)$/", "false" ); } [Fact] public void AppleBash() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo"); //http://www.opensource.apple.com/source/bash/bash-23/bash/tests/glob-test" AddFiles("man/", "man/man1/", "man/man1/bash.1"); TestCase("*/man*/bash.*", new[] { "man/man1/bash.1" }); TestCase("man/man1/bash.1", new[] { "man/man1/bash.1" }); TestCase("a***c", new[] { "abc" }, null, new[] { "abc" }); TestCase("a*****?c", new[] { "abc" }, null, new[] { "abc" }); TestCase("?*****??", new[] { "abc" }, null, new[] { "abc" }); TestCase("*****??", new[] { "abc" }, null, new[] { "abc" }); TestCase("?*****?c", new[] { "abc" }, null, new[] { "abc" }); TestCase("?***?****c", new[] { "abc" }, null, new[] { "abc" }); TestCase("?***?****?", new[] { "abc" }, null, new[] { "abc" }); TestCase("?***?****", new[] { "abc" }, null, new[] { "abc" }); TestCase("*******c", new[] { "abc" }, null, new[] { "abc" }); TestCase("*******?", new[] { "abc" }, null, new[] { "abc" }); TestCase("a*cd**?**??k", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("a**?**cd**?**??k", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("a**?**cd**?**??k***", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("a**?**cd**?**??***k", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("a**?**cd**?**??***k**", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("a****c**?**??*****", new[] { "abcdecdhjk" }, null, new[] { "abcdecdhjk" }); TestCase("[-abc]", new[] { "-" }, null, new[] { "-" }); TestCase("[abc-]", new[] { "-" }, null, new[] { "-" }); TestCase("\\", new[] { "\\" }, null, new[] { "\\" }); TestCase("[\\\\]", new[] { "\\" }, null, new[] { "\\" }); TestCase("[[]", new[] { "[" }, null, new[] { "[" }); TestCase("[", new[] { "[" }, null, new[] { "[" }); // a right bracket shall lose its special meaning and // represent itself in a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 TestCase("[*", new[] { "[abc" }, null, new[] { "[abc" }); TestCase("[]]", new[] { "]" }, null, new[] { "]" }); TestCase("[]-]", new[] { "]" }, null, new[] { "]" }); TestCase(@"[a-\z]", new[] { "p" }, null, new[] { "p" }); TestCase("??**********?****?", new string[0], new Options(), new[] { "abc" }); TestCase("??**********?****c", new string[0], new Options(), new[] { "abc" }); TestCase("?************c****?****", new string[0], new Options(), new[] { "abc" }); TestCase("*c*?**", new string[0], new Options(), new[] { "abc" }); TestCase("a*****c*?**", new string[0], new Options(), new[] { "abc" }); TestCase("a********???*******", new string[0], new Options(), new[] { "abc" }); TestCase("[]", new string[0], new Options(), new[] { "a" }); TestCase("[abc", new string[0], new Options(), new[] { "[" }); AssertRegexes( "/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/", "/^(?:man\\/man1\\/bash\\.1)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/]*?c)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/", "/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/", "/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c)$/", "/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/])$/", "/^(?:(?=.)a[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k[^/]*?[^/]*?[^/]*?)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k[^/]*?[^/]*?)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/", "/^(?:(?!\\.)(?=.)[-abc])$/", "/^(?:(?!\\.)(?=.)[abc-])$/", "/^(?:\\\\)$/", "/^(?:(?!\\.)(?=.)[\\\\])$/", "/^(?:(?!\\.)(?=.)[\\[])$/", "/^(?:\\[)$/", "/^(?:(?=.)\\[(?!\\.)(?=.)[^/]*?)$/", "/^(?:(?!\\.)(?=.)[\\]])$/", "/^(?:(?!\\.)(?=.)[\\]-])$/", "/^(?:(?!\\.)(?=.)[a-z])$/", "/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/", "/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/", "/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/", "/^(?:(?!\\.)(?=.)[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/", "/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/", "/^(?:\\[])$/", "/^(?:\\[abc)$/" ); } [Fact] public void NoCase() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); TestCase( "XYZ", new[] { "xYz" }, new Options { NoCase = true, /*null = true*/ } , new[] { "xYz", "ABC", "IjK" } ); TestCase( "ab*", new[] { "ABC" }, new Options { NoCase = true, /*null = true*/ } , new[] { "xYz", "ABC", "IjK" } ); TestCase( "[ia]?[ck]", new[] { "ABC", "IjK" }, new Options { NoCase = true, /*null = true*/ } , new[] { "xYz", "ABC", "IjK" } ); AssertRegexes( "/^(?:(?=.)XYZ)$/i", "/^(?:(?=.)ab[^/]*?)$/i", "/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i" ); } [Fact] public void OneStar_TwoStar() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); // [ pattern, new [] { matches }, MM opts, files, TAP opts] TestCase("{/*,*}", new string[0], new Options(), new[] { "/asdf/asdf/asdf" }); TestCase("{/?,*}", new[] { "/a", "bb" }, new Options(), new[] { "/a", "/b/b", "/a/b/c", "bb" }); AssertRegexes( "/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/", "/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/" ); } [Fact] public void DotMatching() { AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); //"Dots should not match unless requested" TestCase("**", new[] { "a/b" }, new Options(), new[] { "a/b", "a/.d", ".a/.d" }); // .. and . can only match patterns starting with ., // even when options.Dot is set. ReplaceFiles("a/./b", "a/../b", "a/c/b", "a/.d/b"); TestCase("a/*/b", new[] { "a/c/b", "a/.d/b" }, new Options { Dot = true }); TestCase("a/.*/b", new[] { "a/./b", "a/../b", "a/.d/b" }, new Options { Dot = true }); TestCase("a/*/b", new[] { "a/c/b" }, new Options { Dot = false }); TestCase("a/.*/b", new[] { "a/./b", "a/../b", "a/.d/b" }, new Options { Dot = false }); // this also tests that changing the options needs // to change the cache key, even if the pattern is // the same! TestCase( "**", new[] { "a/b", "a/.d", ".a/.d" }, new Options { Dot = true } , new[] { ".a/.d", "a/.d", "a/b" } ); AssertRegexes( "/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/", "/^(?:a\\/(?!(?:^|\\/)\\.{1,2}(?:$|\\/))(?=.)[^/]*?\\/b)$/", "/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/", "/^(?:a\\/(?!\\.)(?=.)[^/]*?\\/b)$/", "/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/", "/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/" ); } [Fact] public void ParenSlashes() { //AddFiles("a-b", "aXb", ".x", ".y", "a*b/", "a*b/ooo", "man/", "man/man1/", "man/man1/bash.1"); //"paren sets cannot contain slashes" TestCase("*(a/b)", new[] { "*(a/b)" }, new Options { NoNull = true }, new[] { "a/b" }); // brace sets trump all else. // // invalid glob pattern. fails on bash4 and bsdglob. // however, in this implementation, it's easier just // to do the intuitive thing, and let brace-expansion // actually come before parsing any extglob patterns, // like the documentation seems to say. // // XXX: if anyone complains about this, either fix it // or tell them to grow up and stop complaining. // // bash/bsdglob says this: // , new [] { "*(a|{b),c)}", ["*(a|{b),c)}" }, new Options {}, new [] { "a", "ab", "ac", "ad" }); // but we do this instead: TestCase("*(a|{b),c)}", new[] { "a", "ab", "ac" }, new Options(), new[] { "a", "ab", "ac", "ad" }); // test partial parsing in the presence of comment/negation chars TestCase("[!a*", new[] { "[!ab" }, new Options(), new[] { "[!ab", "[ab" }); TestCase("[#a*", new[] { "[#ab" }, new Options(), new[] { "[#ab", "[ab" }); // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. TestCase( "+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" , new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g" } , new Options(), new[] { "+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c" } ); // crazy nested {,,} and *(||) tests. ReplaceFiles( "a", "b", "c", "d" , "ab", "ac", "ad" , "bc", "cb" , "bc,d", "c,db", "c,d" , "d)", "(b|c", "*(b|c" , "b|c", "b|cc", "cb|c" , "x(a|b|c)", "x(a|c)" , "(a|b|c)", "(a|c)" ); TestCase("*(a|{b,c})", new[] { "a", "b", "c", "ab", "ac" }); TestCase("{a,*(b|c,d)}", new[] { "a", "(b|c", "*(b|c", "d)" }); // a // *(b|c) // *(b|d) TestCase("{a,*(b|{c,d})}", new[] { "a", "b", "bc", "cb", "c", "d" }); TestCase("*(a|{b|c,c})", new[] { "a", "b", "c", "ab", "ac", "bc", "cb" }); // test various flag settings. TestCase( "*(a|{b|c,c})", new[] { "x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)" } , new Options { NoExt = true } ); TestCase( "a?b", new[] { "x/y/acb", "acb/" }, new Options { MatchBase = true } , new[] { "x/y/acb", "acb/", "acb/d/e", "x/y/acb/d" } ); TestCase("#*", new[] { "#a", "#b" }, new Options { NoComment = true }, new[] { "#a", "#b", "c#d" }); AssertRegexes( "/^(?:(?!\\.)(?=.)[^/]*?\\(a\\/b\\))$/", "/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/", "/^(?:(?=.)\\[(?=.)\\!a[^/]*?)$/", "/^(?:(?=.)\\[(?=.)#a[^/]*?)$/", "/^(?:(?=.)\\+\\(a\\|[^/]*?\\|c\\\\\\\\\\|d\\\\\\\\\\|e\\\\\\\\\\\\\\\\\\|f\\\\\\\\\\\\\\\\\\|g)$/", "/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/", "/^(?:a|(?!\\.)(?=.)[^/]*?\\(b\\|c|d\\))$/", "/^(?:a|(?!\\.)(?=.)(?:b|c)*|(?!\\.)(?=.)(?:b|d)*)$/", "/^(?:(?!\\.)(?=.)(?:a|b|c)*|(?!\\.)(?=.)(?:a|c)*)$/", "/^(?:(?!\\.)(?=.)[^/]*?\\(a\\|b\\|c\\)|(?!\\.)(?=.)[^/]*?\\(a\\|c\\))$/", "/^(?:(?=.)a[^/]b)$/", "/^(?:(?=.)#[^/]*?)$/" ); } [Fact] public void NegationTests() { // begin channelling Boole and deMorgan... ReplaceFiles("d", "e", "!ab", "!abc", "a!b", "\\!a"); // anything that is NOT a* matches. TestCase("!a*", new[] { "\\!a", "d", "e", "!ab", "!abc" }); // anything that IS !a* matches. TestCase("!a*", new[] { "!ab", "!abc" }, new Options { NoNegate = true }); // anything that IS a* matches TestCase("!!a*", new[] { "a!b" }); // anything that is NOT !a* matches TestCase("!\\!a*", new[] { "a!b", "d", "e", "\\!a" }); // negation nestled within a pattern ReplaceFiles( "foo.js" , "foo.bar" // can't match this one without negative lookbehind. , "foo.js.js" , "blar.js" , "foo." , "boo.js.boo" ); TestCase("*.!(js)", new[] { "foo.bar", "foo.", "boo.js.boo" }); // https://github.com/isaacs/minimatch/issues/5 ReplaceFiles( "a/b/.x/c" , "a/b/.x/c/d" , "a/b/.x/c/d/e" , "a/b/.x" , "a/b/.x/" , "a/.x/b" , ".x" , ".x/" , ".x/a" , ".x/a/b" , "a/.x/b/.x/c" , ".x/.x" ); TestCase("**/.x/**", new[] { ".x/", ".x/a", ".x/a/b", "a/.x/b", "a/b/.x/", "a/b/.x/c", "a/b/.x/c/d", "a/b/.x/c/d/e" }); AssertRegexes( "/^(?!^(?:(?=.)a[^/]*?)$).*$/", "/^(?:(?=.)\\!a[^/]*?)$/", "/^(?:(?=.)a[^/]*?)$/", "/^(?!^(?:(?=.)\\!a[^/]*?)$).*$/", "/^(?:(?!\\.)(?=.)[^/]*?\\.(?:(?!js)[^/]*?))$/", "/^(?:(?:(?!(?:\\/|^)\\.).)*?\\/\\.x\\/(?:(?!(?:\\/|^)\\.).)*?)$/" ); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ForwardMovement : MonoBehaviour { //private CharacterController controller; private Vector3 direction; private Rigidbody rb; public static float forwardSpeed = 10f; // Start is called before the first frame update void Start() { //controller = GetComponent<CharacterController>(); rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update() { //direction.z = forwardSpeed; } private void FixedUpdate() { //controller.Move(direction * Time.fixedDeltaTime); rb.MovePosition(transform.position + transform.forward * Time.fixedDeltaTime * forwardSpeed); } public void ReloadLevel() { Time.timeScale = 1; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace console { public class _020_MultiplyStrings { /// <summary> /// Given two numbers represented as strings, return multiplication of the numbers as a string. /// Note: The numbers can be arbitrarily large and are non-negative. /// </summary> /// <param name="s1">1st string</param> /// <param name="s2">2nd string</param> /// <returns>result</returns> public string MultiplyStrings(string s1, string s2) { if (!(VerifyString(s1) && VerifyString(s2))) return string.Empty; string res = string.Empty; char[] c1 = s1.ToCharArray(); Reverse(c1); char[] c2 = s2.ToCharArray(); Reverse(c2); int tmp, mult, carry = 0; int[] result = new int[c1.Length + c2.Length + 1]; for (int i = 0; i < c1.Length; i++) { int a = c1[i] - '0'; for (int j =0 ; j < c2.Length ; j++) { int b = c2[j] - '0'; mult = (a * b + carry) % 10; carry = (a * b + carry) / 10; tmp = mult + result[i + j]; result[i + j] = tmp % 10; carry += tmp / 10; } if (carry > 0) { tmp = result[i + c2.Length] + carry; result[i + c2.Length] = tmp % 10; carry = tmp / 10; result[i + c2.Length+1] = carry; carry = 0; } } StringBuilder sb = new StringBuilder(); if (result[result.Length - 1] != 0) sb.Append(result[result.Length - 1].ToString()); for (int i = result.Length - 2; i >= 0; i--) { sb.Append(result[i].ToString()); } return sb.ToString(); } /// <summary> /// verify a string is all numberic. /// </summary> /// <param name="s"></param> /// <returns></returns> private bool VerifyString(string s) { if (s.Length == 0) return false; foreach (char c in s) { if (c < '0' || c > '9') return false; } return true; } /// <summary> /// reverse a char array /// </summary> /// <param name="c"></param> private void Reverse(char[] c) { char tmp; for (int i = 0; i < c.Length / 2; i++) { tmp = c[i]; c[i] = c[c.Length-1 - i]; c[c.Length - 1 - i] = tmp; } } } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Web; namespace GetLabourManager.Configuration { public class BranchConfiguration:EntityTypeConfiguration<Branch> { public BranchConfiguration() { Property(x => x.Name).IsRequired().HasMaxLength(50); } } }
using ETModel; using System.Threading.Tasks; namespace ETHotfix { public static class GameRoomFactory { public static async Task<GameRoom> Create(M2S_StartGame m2S_StartGame) { try { GameRoom gameRoom = ComponentFactory.Create<GameRoom>(); //添加玩家 foreach (var playerInfo in m2S_StartGame.MatchPlayerInfos) { gameRoom.PlayerDic[playerInfo.SeatIndex] = await ChessPlayerFactory.Create(playerInfo, gameRoom); } await gameRoom.AddComponent<MailBoxComponent>().AddLocation(); return gameRoom; } catch (System.Exception ex) { Log.Error(ex); throw; } } } }
namespace Umbraco.Core.Components { [RuntimeLevel(MinLevel = RuntimeLevel.Run)] public class ManifestWatcherComposer : ICoreComposer { public void Compose(Composition composition) { composition.Components().Append<ManifestWatcherComponent>(); } } }
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; using System.Web; using System.Net.Mail; namespace ProyectoIngegradoBackEnd { public partial class FormBackEnd : Form { public FormBackEnd() { InitializeComponent(); } private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView2.SelectedRows[0].Cells[0].Value.ToString(); ListaProductos.Rows.Clear(); ActualizarProductos(Id); ConexionBD.CerrarConexion(); } private void dataGridView3_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView3.SelectedRows[0].Cells[0].Value.ToString(); ListaProductos.Rows.Clear(); ActualizarProductos(Id); ConexionBD.CerrarConexion(); } private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { ConexionBD.AbrirConexion(); var x = dataGridView1.SelectedRows; string Id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); ListaProductos.Rows.Clear(); ActualizarProductos(Id); ConexionBD.CerrarConexion(); } private void aceptarMesa_Click(object sender, EventArgs e) { ConexionBD.CerrarConexion(); ConexionBD.AbrirConexion(); string email = dataGridView5.SelectedRows[0].Cells[4].Value.ToString(); string Idstr = dataGridView5.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("select correo from ReservaMesa where id ='{0}'", Idstr); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); reader.Read(); string correo = reader.GetString(0); reader.Close(); string correoProp = "barvaderenterprise@gmail.com"; string contraseña = "paco123T"; string mensaje = "Tu reserva ha sido aprobada"; MailMessage mail = new MailMessage(correoProp, correo, "Reserva numero #" + Idstr + "", mensaje); SmtpClient client = new SmtpClient("smtp.gmail.com"); client.Port = 587; client.Credentials = new System.Net.NetworkCredential(correoProp, contraseña); client.EnableSsl = true; client.Send(mail); MessageBox.Show("Email Enviado"); string consulta2 = string.Format("delete from ReservaMesa where id ='{0}'", Idstr); MySqlCommand comando2 = new MySqlCommand(consulta2, ConexionBD.Conexion); comando2.ExecuteNonQuery(); dataGridView5.Rows.Clear(); ActualizarEmpleados(); ConexionBD.CerrarConexion(); } public string getid() { string id = ""; return id; } public void ActualizarEmpleados() { String consulta = "SELECT id,dia,hora,numComensales,correo FROM ReservaMesa"; MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows == true) { int count = 0; while (reader.Read()) { if (reader.GetString(4) != "") { dataGridView5.Rows.Add(); dataGridView5.Rows[count].Cells[0].Value = (reader.GetInt32(0)); dataGridView5.Rows[count].Cells[1].Value = (reader.GetDateTime(1)); dataGridView5.Rows[count].Cells[2].Value = (reader.GetString(2)); dataGridView5.Rows[count].Cells[3].Value = (reader.GetInt32(3)); dataGridView5.Rows[count].Cells[4].Value = (reader.GetString(4)); count++; } } } reader.Close(); } public void actualizarPorhacer() { String consulta = "SELECT id,hora,precio FROM Pedidos where proceso='Por Hacer'"; MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows == true) { int count = 0; while (reader.Read()) { if (reader.GetString(1) != "") { dataGridView1.Rows.Add(); dataGridView1.Rows[count].Cells[0].Value = (reader.GetInt32(0)); dataGridView1.Rows[count].Cells[1].Value = (reader.GetString(1)); dataGridView1.Rows[count].Cells[2].Value = (reader.GetDouble(2)); count++; } } } reader.Close(); } public void actualizarHaciendo() { String consulta = "SELECT id,hora,precio FROM Pedidos where proceso='Haciendo'"; MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows == true) { int count = 0; while (reader.Read()) { if (reader.GetString(1)!="") { dataGridView2.Rows.Add(); dataGridView2.Rows[count].Cells[0].Value = (reader.GetInt32(0)); dataGridView2.Rows[count].Cells[1].Value = (reader.GetString(1)); dataGridView2.Rows[count].Cells[2].Value = (reader.GetDouble(2)); count++; } } } reader.Close(); } public void actualizarHecho() { String consulta = "SELECT id,hora,precio FROM Pedidos where proceso='Hecho'"; MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows==true) { int count = 0; while (reader.Read()) { if (reader.GetString(1) != "") { dataGridView3.Rows.Add(); dataGridView3.Rows[count].Cells[0].Value = (reader.GetInt32(0)); dataGridView3.Rows[count].Cells[1].Value = (reader.GetString(1)); dataGridView3.Rows[count].Cells[2].Value = (reader.GetDouble(2)); count++; } } } reader.Close(); } public void ActualizarProductos(string Id) { String consulta = string.Format("Select nombre,descripcion,cantidad from articulospedido inner join Articulos on articulospedido.idarticulo= Articulos.id where idpedido ='{0}'", Id); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); if (reader.HasRows == true) { int count = 0; while (reader.Read()) { if (reader.GetString(1) != "") { ListaProductos.Rows.Add(); ListaProductos.Rows[count].Cells[0].Value = (reader.GetString(0)); ListaProductos.Rows[count].Cells[1].Value = (reader.GetString(1)); ListaProductos.Rows[count].Cells[2].Value = (reader.GetInt32(2)); count++; } } } reader.Close(); } private void rechazarMesa_Click(object sender, EventArgs e) { ConexionBD.CerrarConexion(); ConexionBD.AbrirConexion(); string email = dataGridView5.SelectedRows[0].Cells[4].Value.ToString(); string Idstr = dataGridView5.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("select correo from ReservaMesa where id ='{0}'", Idstr); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); MySqlDataReader reader = comando.ExecuteReader(); reader.Read(); string correo = reader.GetString(0); reader.Close(); string correoProp = "barvaderenterprise@gmail.com"; string contraseña = "paco123T"; string mensaje = "Tu reserva ha sido rechazada"; MailMessage mail = new MailMessage(correoProp, correo, "Reserva numero #" + Idstr + "", mensaje); SmtpClient client = new SmtpClient("smtp.gmail.com"); client.Port = 587; client.Credentials = new System.Net.NetworkCredential(correoProp, contraseña); client.EnableSsl = true; client.Send(mail); MessageBox.Show("Email Enviado"); string consulta2 = string.Format("delete from ReservaMesa where id ='{0}'", Idstr); MySqlCommand comando2 = new MySqlCommand(consulta2, ConexionBD.Conexion); comando2.ExecuteNonQuery(); dataGridView5.Rows.Clear(); ActualizarEmpleados(); ConexionBD.CerrarConexion(); } private void FormBackEnd_Load(object sender, EventArgs e) { if (ConexionBD.Conexion != null) { ConexionBD.AbrirConexion(); ActualizarEmpleados(); actualizarPorhacer(); actualizarHaciendo(); actualizarHecho(); ConexionBD.CerrarConexion(); } } private void aHaciendo_Click(object sender, EventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("Update Pedidos set proceso='Haciendo' where id ='{0}'", Id); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); comando.ExecuteNonQuery(); dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); dataGridView3.Rows.Clear(); actualizarHaciendo(); actualizarPorhacer(); actualizarHecho(); ConexionBD.CerrarConexion(); } private void aHecho_Click(object sender, EventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView2.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("Update Pedidos set proceso='Hecho' where id ='{0}'", Id); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); comando.ExecuteNonQuery(); dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); dataGridView3.Rows.Clear(); actualizarHaciendo(); actualizarPorhacer(); actualizarHecho(); ConexionBD.CerrarConexion(); } private void volverHaciendo_Click(object sender, EventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView3.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("Update Pedidos set proceso='Haciendo' where id ='{0}'", Id); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); comando.ExecuteNonQuery(); dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); dataGridView3.Rows.Clear(); actualizarHaciendo(); actualizarPorhacer(); actualizarHecho(); ConexionBD.CerrarConexion(); } private void volverPorHacer_Click(object sender, EventArgs e) { ConexionBD.AbrirConexion(); string Id = dataGridView2.SelectedRows[0].Cells[0].Value.ToString(); string consulta = string.Format("Update Pedidos set proceso='Por Hacer' where id ='{0}'", Id); MySqlCommand comando = new MySqlCommand(consulta, ConexionBD.Conexion); comando.ExecuteNonQuery(); dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); dataGridView3.Rows.Clear(); actualizarHaciendo(); actualizarPorhacer(); actualizarHecho(); ConexionBD.CerrarConexion(); } private void timer1_Tick(object sender, EventArgs e) { ConexionBD.AbrirConexion(); dataGridView1.Rows.Clear(); dataGridView2.Rows.Clear(); dataGridView3.Rows.Clear(); dataGridView5.Rows.Clear(); ListaProductos.Rows.Clear(); actualizarHaciendo(); ActualizarEmpleados(); actualizarPorhacer(); actualizarHecho(); ConexionBD.CerrarConexion(); } } }
using CourseProject.Model; using CourseProject.Other; using CourseProject.Repositories; using CourseProject.View; using CourseProject_WPF_.Repositories; using System.Collections.ObjectModel; using System.ComponentModel; namespace CourseProject.ViewModel { public class AdminControlViewModel : INotifyPropertyChanged { private AdminPageState _state; EfUserRepository userRepository = new EfUserRepository(); EFItemsRepository _shopItemsRepository = new EFItemsRepository(); ObservableCollection<User> tmpUsers = new ObservableCollection<User>(); ObservableCollection<Item> tmpAnnouncements = new ObservableCollection<Item>(); ObservableCollection<object> tmp = new ObservableCollection<object>(); object selectedItem; string message; public AdminPageState State { get => _state; set { if (_state == value) { return; } _state = value; OnPropertyChanged(nameof(State)); } } public object SelectedItem { get { return selectedItem; } set { if (value != null) selectedItem = value; OnPropertyChanged("SelectedItem"); } } public string Message { get { return message; } set { message = value; OnPropertyChanged("Message"); } } public ObservableCollection<User> Users { get { selectedItem = null; return tmpUsers; } } public ObservableCollection<Item> Items { get { selectedItem = null; return tmpAnnouncements; } } public AdminControlViewModel(ViewWindow viewWindow) { this.viewWindow = viewWindow; update(); } public void update() { tmpUsers.Clear(); tmpAnnouncements.Clear(); foreach (User user in userRepository.GetAll()) { if (user.Id != UserViewModel.User.Id) tmpUsers.Add(user); } foreach (Item announcement in _shopItemsRepository.getAll()) tmpAnnouncements.Add(announcement); } public void accept() { if (State == AdminPageState.Items) { var addButtonDialogWindow = new AddWindow(); addButtonDialogWindow.ShowDialog(); } else switch (SelectedItem) { case User _ when UserViewModel.isAdmin(): { if ((SelectedItem as User)?.Privilege?.Equals("admin") == true) userRepository.ChangePrivilege((SelectedItem as User), "user"); else if (((User)SelectedItem).Privilege?.Equals("user") == true) userRepository.ChangePrivilege((SelectedItem as User), "admin"); var alertWindow = new AlertWindow( $"Пользователь {(SelectedItem as User).FirstName} {(SelectedItem as User).SecondName} теперь {(SelectedItem as User).Privilege}"); alertWindow.ShowDialog(); break; } case User _: { var alertWindow = new AlertWindow("У вас недостаточно прав для совершения данного действия"); alertWindow.ShowDialog(); break; } default: { AlertWindow alertWindow = new AlertWindow($"Выберите объект"); alertWindow.ShowDialog(); break; } } update(); } void DeleteUser(User user) { userRepository.Delete(user); } public void Delete() { if (SelectedItem is User) { if (UserViewModel.isAdmin()) { DialogWindow dialogWindow = new DialogWindow(); dialogWindow.DataContext = this; Message = $"Уверены, что хотите удалить пользователя {(SelectedItem as User).FirstName} {(SelectedItem as User).SecondName}?"; dialogWindow.ShowDialog(); if (dialogWindow.DialogResult == true) DeleteUser(SelectedItem as User); } else { AlertWindow alertWindow = new AlertWindow("У вас недостаточно прав для совершения данного действия"); alertWindow.ShowDialog(); } } else if (SelectedItem is Item) { DialogWindow dialogWindow = new DialogWindow(); dialogWindow.DataContext = this; Message = $"Уверены, что хотите удалить товар \"{(SelectedItem as Item).Name}\" ?"; dialogWindow.ShowDialog(); if (dialogWindow.DialogResult == true) _shopItemsRepository.delete(SelectedItem as Item); } else { AlertWindow alertWindow = new AlertWindow($"Выберите объект"); alertWindow.ShowDialog(); } update(); } private ViewWindow viewWindow; private ChangeWindow ChangeWindow; public void ShowInfo() { if (SelectedItem == null) { return; } if (State == AdminPageState.Items) { viewWindow.DataContext = SelectedItem; viewWindow.Show(); return; } } public void Change() { if (SelectedItem == null) { return; } if (State == AdminPageState.Items) { ChangeWindow = new ChangeWindow(SelectedItem as Item); ChangeWindow.DataContext = SelectedItem; ChangeWindow.Show(); return; } } public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FibMVC; using FibMVC.Biz; namespace FibMVC.Controllers { public class FibController : Controller { // GET: Fib public ViewResult test() { return View(); } public PartialViewResult fib() { ViewData["Fib"] = Biz.CalcFib.Fib(); return PartialView(ViewData["Fib"]); } //ViewData["FibInput"] = Biz.CalcFib.Fib(s); [HttpGet] public ViewResult FibInput() { return View(); } [HttpPost] public ViewResult FibInput(CalcFib c) { ViewData["list"] = Biz.CalcFib.d; return View("Results", c); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Lab7_Collection.Classes { public class Deck<T> : IEnumerable { T[] items = new T[5]; int count; public int GetCount() { return count; } /// <summary> /// Adds a card to the deck /// </summary> /// <param name="item"></param> public void AddCard(T item) { if (count == items.Length) { Array.Resize(ref items, items.Length + 1); } items[count++] = item; } /// <summary> /// Takes in a intger for a index spot, then removes a card at that location in the Deck /// </summary> /// <param name="num"></param> /// <returns>true or false depending on successful card removal</returns> public bool RemoveCard(int num) { try { if (num <= 0) { return false; } int i; for (i = 0; i < count; i++) { if (i >= num) { items[i] = items[i + 1]; } } if (num > i) { return false; } Array.Resize(ref items, items.Length - 1); count--; return true; } catch(IndexOutOfRangeException) { return false; } } /// <summary> /// Contract with the Interface being allowing us to use foreach over our deck /// </summary> /// <returns>a card</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < count; i++) { yield return items[i]; } } /// <summary> /// GetEnumerator unwanted little brother /// </summary> /// <returns>calls big brother</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using Android.App; using Android.OS; using Android.Views; using Android.Widget; using JKMAndroidApp.Common; using JKMPCL.Model; using JKMPCL.Services; using System; using System.Linq; using System.Collections.Generic; using static JKMPCL.Services.UtilityPCL; using JKMAndroidApp.activity; using System.Threading.Tasks; using System.Net; using JKMPCL.Services.Payment; using System.Text.RegularExpressions; using Android.Content; namespace JKMAndroidApp.fragment { public class FragmentDeposit : Android.Support.V4.App.Fragment { View view; TextView tvtitleDiscriptions, tvDisplayDepositAmount, tvCVV, tvDepositAmount, tvExpYear, tvExpMonth, tvNameofCardHolder, tvCardNumber, tvback, tvNext; EditText txtNameofCardHolder, txtCardNumber, txtCVV; Spinner spinnerExpMonth, spinnerExpYear; ImageView imgCard; LinearLayout linearLayoutEdit, linearLayoutBack; RelativeLayout paymentControl; ImageButton btnBack; FrameLayout framlayEnable; CheckBox depositCheckBox; AlertDialog.Builder dialogue; AlertDialog alert; List<MonthYearModel> monthList, yearList; CardType cardType; private EstimateModel estimateModel; private bool isFormatCardNumber = true; Payment paymentGateway; public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.Inflate(Resource.Layout.LayoutFragmentDeposit, container, false); estimateModel = DTOConsumer.dtoEstimateData.FirstOrDefault(rc => rc.MoveNumber == UIHelper.SelectedMoveNumber); UIReferencesPaymentControl(); UIReferences(); PopulateData(); UIClickEvents(); monthList = BindMonthList(); yearList = BindYearList(); BindSpinerMonth(); BindSpinerYear(); view.Invalidate(); return view; } public override void OnResume() { UIReferencesPaymentControl(); UIReferences(); PopulateData(); base.OnResume(); } /// Method Name : SetNextFragmentClick /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Use for move next fragment /// Revision : /// </summary> private void SetNextFragmentClick() { tvNext.Click += TvNext_ClickAsync; } private async void TvNext_ClickAsync(object sender, EventArgs e) { if (!depositCheckBox.Checked) { string errormessage = Validation(); if (string.IsNullOrEmpty(errormessage)) { APIResponse<PaymentTransactonModel> paymentTransacton = await ProcessPaymentTransactionAsync(); if (paymentTransacton.STATUS) { estimateModel.IsDepositPaidByCheck = false; estimateModel.PaymentStatus = true; StartActivity(new Intent(Activity, typeof(ActivityMoveConfirmed))); } else { dialogue = new AlertDialog.Builder(new ContextThemeWrapper(Activity, Resource.Style.AlertDialogCustom)); alert = dialogue.Create(); alert.SetMessage(StringResource.msgPaymentFailMessage); alert.SetButton(StringResource.msgOK, (c, ev) => { alert.Dispose(); }); alert.Show(); } } else { AlertMessage(errormessage); } } else { estimateModel.IsDepositPaidByCheck = true; StartActivity(new Intent(Activity, typeof(ActivityMoveConfirmed))); } } /// Method Name : SetBackFragmentClick /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Use for move back fragment /// Revision : /// </summary> private void SetBackFragmentClick() { btnBack.Click += MTextViewBack_Click; linearLayoutBack.Click += MTextViewBack_Click; } /// Method Name : SetBackFragmentClick /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Use for move back fragment /// Revision : /// </summary> private void MTextViewBack_Click(object sender, EventArgs e) { ClearData(); tvback.Text =StringResource.wizBtnBack; tvNext.Text = StringResource.msgbtnSubmitPayment; ((ActivityEstimateViewPager)Activity).FragmentBack(); } /// </summary> /// Method Name : UIReferences /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Finds Control /// Revision : /// </summary> private void UIReferences() { tvtitleDiscriptions = view.FindViewById<TextView>(Resource.Id.tvtitleDiscriptions); tvDepositAmount = view.FindViewById<TextView>(Resource.Id.tvDepositAmount); tvDisplayDepositAmount = view.FindViewById<TextView>(Resource.Id.tvDisplayDepositAmount); linearLayoutBack = view.FindViewById<LinearLayout>(Resource.Id.linearLayoutBack); btnBack = view.FindViewById<ImageButton>(Resource.Id.btnBack); tvback = view.FindViewById<TextView>(Resource.Id.tvback); tvNext = view.FindViewById<TextView>(Resource.Id.tvNext); depositCheckBox = view.FindViewById<CheckBox>(Resource.Id.depositCheckBox); } /// </summary> /// Method Name : UIReferencesPaymentControl /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Finds Control /// Revision : /// </summary> private void UIReferencesPaymentControl() { paymentControl = (RelativeLayout)view.FindViewById(Resource.Id.paymentControl); tvExpMonth = paymentControl.FindViewById<TextView>(Resource.Id.tvExpMonth); spinnerExpMonth = paymentControl.FindViewById<Spinner>(Resource.Id.spinnerExpMonth); tvExpYear = paymentControl.FindViewById<TextView>(Resource.Id.tvExpYear); spinnerExpYear = paymentControl.FindViewById<Spinner>(Resource.Id.spinnerExpYear); tvNameofCardHolder = paymentControl.FindViewById<TextView>(Resource.Id.tvNameofCardHolder); txtNameofCardHolder = paymentControl.FindViewById<EditText>(Resource.Id.txtNameofCardHolder); tvCardNumber = paymentControl.FindViewById<TextView>(Resource.Id.tvCardNumber); txtCardNumber = paymentControl.FindViewById<EditText>(Resource.Id.txtCardNumber); tvCVV = paymentControl.FindViewById<TextView>(Resource.Id.tvCVV); txtCVV = paymentControl.FindViewById<EditText>(Resource.Id.txtCVV); imgCard = paymentControl.FindViewById<ImageView>(Resource.Id.imgCard); linearLayoutEdit = paymentControl.FindViewById<LinearLayout>(Resource.Id.linearLayoutPayment); framlayEnable = paymentControl.FindViewById<FrameLayout>(Resource.Id.framlayEnable); } /// </summary> /// Method Name : UIClickEvents /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Set control events /// Revision : /// </summary> private void UIClickEvents() { SetNextFragmentClick(); SetBackFragmentClick(); TextViewCardNumberTextChange(); depositCheckBox.CheckedChange += DepositCheckBox_CheckedChange; txtCardNumber.KeyPress += TxtCardNumber_KeyPress; } /// </summary> /// Method Name : PaymentTransaction /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Set payment details /// Revision : /// </summary> public PaymentGatewayModel PaymentTransactionAsync() { PaymentGatewayModel paymentModel = new PaymentGatewayModel(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; string expiryYear = spinnerExpYear.SelectedItem.ToString().Substring(2, 2); paymentModel.CardExpiryDate = spinnerExpMonth.SelectedItem.ToString() + expiryYear; paymentModel.CreditCardNumber = txtCardNumber.Text.Replace("-","").Trim(); paymentModel.CVVNo = Convert.ToInt32(txtCVV.Text.Trim()); if (estimateModel != null) { paymentModel.TransactionAmout = Convert.ToDouble(estimateModel.Deposit); } PaymentGatewayModel payment = FillCustomerData(paymentModel); if (payment != null) { paymentModel = payment; } return paymentModel; } /// </summary> /// Method Name : PaymentTransaction /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Set payment details /// Revision : /// </summary> public async Task<APIResponse<PaymentTransactonModel>> ProcessPaymentTransactionAsync() { paymentGateway = new Payment(); APIResponse<PaymentTransactonModel> paymentTransacton = new APIResponse<PaymentTransactonModel>(); PaymentGatewayModel paymentModel = PaymentTransactionAsync(); if (paymentModel != null) { paymentTransacton = await paymentGateway.ProcessPaymentTransaction(paymentModel); if (paymentTransacton.STATUS) { estimateModel.TransactionId = paymentTransacton.DATA.TransactionID; estimateModel.PaymentStatus = true; estimateModel.IsDepositPaid = true; await CallPostPaymentTransaction(paymentTransacton, estimateModel); } else { estimateModel.PaymentStatus = false; } } return paymentTransacton; } /// <summary> /// Method Name : CallPostPaymentTransaction /// Author : Hiren Patel /// Creation Date : 15 Feb 2018 /// Purpose : Calls the post payment transaction. /// Revision : /// </summary> /// <returns>The post payment transaction.</returns> /// <param name="paymentTransactonModel">Payment transacton model.</param> /// <param name="estimateModel">Estimate model.</param> private async Task CallPostPaymentTransaction(APIResponse<PaymentTransactonModel> paymentTransactonModel, EstimateModel estimateModel) { paymentGateway = new Payment(); APIResponse<PaymentModel> serviceResponse = new APIResponse<PaymentModel>() { STATUS = false }; string errorMessage = string.Empty; try { List<PaymentModel> paymentModelList = new List<PaymentModel>(); PaymentModel paymentModel = new PaymentModel(); paymentModel.MoveID = estimateModel.MoveId; paymentModel.TransactionNumber = paymentTransactonModel.DATA.TransactionID; if (!IsNullOrEmptyOrWhiteSpace(estimateModel.Deposit)) { paymentModel.TransactionAmount = RemoveCurrencyFormat(estimateModel.Deposit); } paymentModel.TransactionDate = UtilityPCL.DisplayDateFormatForEstimate(DateTime.Now, string.Empty); paymentModel.CustomerID = LoginCustomerData.CustomerId; paymentModelList.Add(paymentModel); serviceResponse = await paymentGateway.PostPaymentTransaction(paymentModelList); } catch (Exception error) { errorMessage = error.Message; } finally { if (!string.IsNullOrEmpty(errorMessage)) { AlertMessage(errorMessage); } } } /// </summary> /// Method Name : FillCustomerData /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Set customer details /// Revision : /// </summary> private PaymentGatewayModel FillCustomerData(PaymentGatewayModel paymentModel) { if (LoginCustomerData != null) { String firstName = string.Empty; String lastName = string.Empty; if (!string.IsNullOrEmpty(txtNameofCardHolder.Text.Trim())) { string[] customerName = txtNameofCardHolder.Text.Trim().Split(' '); if (customerName.Length > 1) { firstName = customerName[0]; lastName = customerName[1]; } } paymentModel.CustomerID = LoginCustomerData.CustomerId; paymentModel.FirstName = firstName; paymentModel.LastName = lastName; paymentModel.EmailID = LoginCustomerData.EmailId; } return paymentModel; } /// </summary> /// Event Name : DepositCheckBox_CheckedChange /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Set enable disable payment control /// Revision : /// </summary> private void DepositCheckBox_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (depositCheckBox.Checked) { framlayEnable.Visibility = ViewStates.Visible; framlayEnable.Clickable = true; txtNameofCardHolder.SetCursorVisible(false); txtCardNumber.SetCursorVisible(false); ClearData(); } else { txtCardNumber.SetCursorVisible(true); txtNameofCardHolder.SetCursorVisible(true); framlayEnable.Visibility = ViewStates.Gone; framlayEnable.Clickable = false; } } /// Method Name : BindSpinerMonth /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Use fort bind month /// Revision : /// </summary> private void BindSpinerMonth() { List<String> valutionList = MonthList(); if (valutionList.Count > 0) { var monthAdapter = new ArrayAdapter<string>(Activity, Android.Resource.Layout.SimpleSpinnerItem, valutionList); monthAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinnerExpMonth.Adapter = monthAdapter; string currentMonth = DateTime.Now.Month.ToString("00"); MonthYearModel monthYearModel = monthList.FirstOrDefault(rc => rc.Month == currentMonth); if (monthYearModel.Monthindex == 0) { spinnerExpMonth.SetSelection(monthYearModel.Monthindex); } else spinnerExpMonth.SetSelection(monthYearModel.Monthindex - 1); } } /// Method Name : BindSpiner /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Use fort bind year /// Revision : /// </summary> private void BindSpinerYear() { List<String> valutionList = YearList(); if (valutionList.Count > 0) { var yearAdapter = new ArrayAdapter<string>(Activity, Android.Resource.Layout.SimpleSpinnerItem, valutionList); yearAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinnerExpYear.Adapter = yearAdapter; } } /// </summary> /// Method Name : TextViewCardNumberTextChange /// Author : Sanket Prajapati /// Creation Date : 31 jan 2018 /// Purpose : Use for check card type /// Revision : /// </summary> private void TextViewCardNumberTextChange() { txtCardNumber.TextChanged += delegate { if (!string.IsNullOrEmpty(txtCardNumber.Text.Trim()) && txtCardNumber.Text.Length >= 4) { SetCardType(); if (isFormatCardNumber) { SetCardFormat(); } else { txtCardNumber.SetSelection(txtCardNumber.Text.Length); } } else { imgCard.SetImageResource(Resource.Drawable.icon_payment_active); } }; } /// <summary> /// Method Name : SetCardType /// Author : Vivek Bhavsar /// Creation Date : 28 Feb 2018 /// Purpose : check card type based on card number /// Revision : /// </summary> private void SetCardType() { cardType = GetCardType(txtCardNumber.Text); switch (cardType) { case CardType.MasterCard: imgCard.SetImageResource(Resource.Drawable.icon_master); break; case CardType.VISA: imgCard.SetImageResource(Resource.Drawable.icon_visa); break; default: imgCard.SetImageResource(Resource.Drawable.icon_payment_active); break; } } /// <summary> /// Method Name : TxtCardNumber_KeyPress /// Author : Vivek Bhavsar /// Creation Date : 28 Feb 2018 /// Purpose : to set flag isFormatCardNumber on erase number & to manage SetCardFormat() functionality /// Revision : /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TxtCardNumber_KeyPress(object sender, View.KeyEventArgs e) { e.Handled = false; if (e.KeyCode == Keycode.Del || e.KeyCode == Keycode.Back) { isFormatCardNumber = false; } else { isFormatCardNumber = true; } } /// <summary> /// Method Name : SetCardFormat /// Author : Vivek Bhavsar /// Creation Date : 28 Feb 2018 /// Purpose : add "-" after each 4 digit in credit card number /// Revision : /// </summary> public void SetCardFormat() { try { if (txtCardNumber.Text.Length < 16 && isFormatCardNumber) { string cardNumber = txtCardNumber.Text.Replace("-", "").Trim(); string finalCardNumber = string.Empty; for (int i = 0; i < cardNumber.Length; i++) { if (i % 4 == 0 && i > 0) { finalCardNumber += "-"; finalCardNumber += cardNumber[i].ToString(); isFormatCardNumber = false; } else { finalCardNumber += cardNumber[i].ToString(); } } //assign value to txtCardNumber only in case of isFormatCardNumber is false other wise it will looped infinite and application will crash if (!isFormatCardNumber) { txtCardNumber.Text += "-"; int position = txtCardNumber.Text.Length; txtCardNumber.SetSelection(position); txtCardNumber.Text = finalCardNumber; } } } catch { //To be implemented later } } /// <summary> /// Method Name : ApplyFont /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Apply font all control /// Revision : /// </summary> public void ApplyFont() { UIHelper.SetTextViewFont(tvtitleDiscriptions, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvDisplayDepositAmount, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvCVV, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvNameofCardHolder, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvCardNumber, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvExpMonth, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvExpYear, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvback, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvNext, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetEditTextFont(txtNameofCardHolder, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetEditTextFont(txtCardNumber, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetEditTextFont(txtCVV, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); } /// <summary> /// Method Name : AlertMessage /// Author : Sanket prajapati /// Creation Date : 5 Jan 2018 /// Purpose : Show alert message /// Revision : /// </summary> public void AlertMessage(String StrErrorMessage) { dialogue = new AlertDialog.Builder(new ContextThemeWrapper(Activity, Resource.Style.AlertDialogCustom)); alert = dialogue.Create(); alert.SetMessage(StrErrorMessage); alert.SetButton(StringResource.msgOK, (c, ev) => { alert.Dispose(); }); alert.Show(); } /// <summary> /// Method Name : Validation /// Author : Sanket Prajapati /// Creation Date : 13 jan 2018 /// Purpose : Use for validation /// Revision : /// </summary> private string Validation() { MonthYearModel yearValue = yearList.FirstOrDefault(rc => rc.Year == spinnerExpYear.SelectedItem.ToString()); MonthYearModel monthValue = monthList.FirstOrDefault(rc => rc.Month == spinnerExpMonth.SelectedItem.ToString()); string errormessage = string.Empty; CardTypeInfoModel cardTypeInfoModel = UtilityPCL.GetCardTypes().FirstOrDefault(rc => rc.CardType == cardType); if (string.IsNullOrEmpty(txtNameofCardHolder.Text)) { errormessage = StringResource.msgNameofCardholderisRequired; } else if (!string.IsNullOrEmpty(txtNameofCardHolder.Text.Trim())) { errormessage = ValidFullName(); if (string.IsNullOrEmpty(errormessage)) { if (string.IsNullOrEmpty(txtCardNumber.Text)) { errormessage = StringResource.msgCardNumberIsRequired; } else { errormessage = validExpDateAndCardnumber(yearValue, monthValue, cardTypeInfoModel); } } } return errormessage; } private string ValidFullName() { string errormessage = string.Empty; if (!string.IsNullOrEmpty(txtNameofCardHolder.Text.Trim())) { string[] customerName = txtNameofCardHolder.Text.Trim().Split(' '); if (customerName.Length <= 1) { errormessage = StringResource.msgFullNameRequired; } } return errormessage; } /// <summary> /// Method Name : Validation /// Author : Sanket Prajapati /// Creation Date : 13 jan 2018 /// Purpose : Use for validation /// Revision : /// </summary> private string validExpDateAndCardnumber(MonthYearModel yearValue, MonthYearModel monthValue, CardTypeInfoModel cardTypeInfoModel) { string errormessage = string.Empty; int month = DateTime.Now.Month; int year = DateTime.Now.Year; string cardNumber = txtCardNumber.Text.Replace("-", "").Trim(); if (cardTypeInfoModel == null || (cardTypeInfoModel.CardNumberLength != cardNumber.Length)) { errormessage = StringResource.msgInvalidCard; } else if (year > yearValue.Yearindex || (year == yearValue.Yearindex && month > monthValue.Monthindex)) { errormessage = StringResource.msgExpiredateValidation; } else if (string.IsNullOrEmpty(txtCVV.Text)) { errormessage = StringResource.msgCVVIsRequired; } return errormessage; } /// <summary> /// Method Name : ClearData /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Clear payment data /// Revision : /// </summary> private void ClearData() { if (!string.IsNullOrEmpty(txtNameofCardHolder.Text.Trim())) { txtNameofCardHolder.Text = string.Empty; } if (!string.IsNullOrEmpty(txtCVV.Text.Trim())) { txtCVV.Text = string.Empty; } if (!string.IsNullOrEmpty(txtCardNumber.Text.Trim())) { txtCardNumber.Text = string.Empty; } BindSpinerMonth(); BindSpinerYear(); } /// <summary> /// Method Name : PopulateData /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : fill Estimate Data /// Revision : /// </summary> public void PopulateData() { if (estimateModel != null && string.IsNullOrEmpty(estimateModel.message)) { tvDisplayDepositAmount.Text = CurrencyFormat(estimateModel.DepositValue); if (!estimateModel.IsDepositPaid) { estimateModel.Deposit = CurrencyFormat(estimateModel.DepositValue); } } } } }
using iCopy.ExternalServices.Mail; using Microsoft.Extensions.DependencyInjection; namespace iCopy.ExternalServices { public static class ExternalServicesRegister { public static IServiceCollection AddExternalServices(this IServiceCollection services) { services.AddScoped<IMailService, MailService>(); return services; } } }
using System; using System.Collections; using System.Collections.Generic; namespace dnaStrings { class Program { static void Main(string[] args) { string dna = "ATCG"; Console.WriteLine("DNA string is "+ dna); Console.WriteLine(" The complementary side is: " + MakeComplement(dna)); List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 }; } public static string MakeComplement(string dna) { string result = ""; //char[] dnaArr = dna.ToCharArr(); for(int i = 0; i < dna.Length; i++) { switch(dna[i]) { case 'A': result += 'T'; break; case 'T': result += 'A'; break; case 'C': result += 'G'; break; case 'G': result += 'C'; break; default: break; } } return result; } } }
using System.Data; using MySql.Data.MySqlClient; namespace OrekiLibraryManage { static class Oreki { public static string ConStr = "server=115.159.157.220;uid=Oreki;pwd=6434;database=teamz"; public static void ShowInput(string title, string hint) { var inputbox = new Inputbox { Text = title }; inputbox.label1.Text = hint; inputbox.ShowDialog(); //return inputbox.textBox1.Text; } public static string Temp; public static string Group; public static int OkCancel = 0; public static MySqlConnection Connection = new MySqlConnection(Oreki.ConStr); public static NewUser NewUser = new NewUser(); public static Main Main = new Main(); public static string Bookbarcode = ""; public static void SqlCon() { if (Connection.State == ConnectionState.Open) Connection.Close(); Connection.Open(); } public static void ChkCon() { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace ProjectEuler { public class OneThousandDigitFibonacciNumber : ISolution { public void Run() { var numberOfDigits = 1000; Result = FibonacciSequence().TakeWhile(x => x.ToString().Length < numberOfDigits).Count() + 1; } public object Result { get; private set; } public static IEnumerable<BigInteger> FibonacciSequence() { var a = new BigInteger(1); var b = new BigInteger(1); yield return a; yield return b; while (true) { var c = a + b; yield return c; a = b; b = c; } } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace ProductTest.Migrations { public partial class initialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "BooleanTests", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Active = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BooleanTests", x => x.Id); }); migrationBuilder.CreateTable( name: "Patterns", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), BrandTitle = table.Column<string>(nullable: false), Title = table.Column<string>(nullable: false), Overview = table.Column<string>(nullable: true), SalesHookLine = table.Column<string>(nullable: true), Features = table.Column<string>(nullable: true), Images = table.Column<string>(nullable: true), Active = table.Column<bool>(nullable: true), Synonyms = table.Column<bool>(nullable: true), Performance = table.Column<bool>(nullable: true), LowerNoise = table.Column<bool>(nullable: true), HigherMileage = table.Column<bool>(nullable: true), UltraHighPerformance = table.Column<bool>(nullable: true), Eco = table.Column<bool>(nullable: true), SemiSlick = table.Column<bool>(nullable: true), Touring = table.Column<bool>(nullable: true), AllSeason = table.Column<bool>(nullable: true), HighwayTerrain = table.Column<bool>(nullable: true), AllTerrain = table.Column<bool>(nullable: true), HeavyAllTerrain = table.Column<bool>(nullable: true), MudTerrain = table.Column<bool>(nullable: true), TreadType = table.Column<bool>(nullable: true), QualityCategory = table.Column<bool>(nullable: true), ColourSmoke = table.Column<bool>(nullable: true), Segment = table.Column<bool>(nullable: true), Key = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Patterns", x => x.Id); }); migrationBuilder.CreateTable( name: "Skus", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), BrandTitle = table.Column<string>(nullable: false), PatternTitle = table.Column<string>(nullable: false), Sku = table.Column<string>(nullable: false), Width = table.Column<int>(nullable: true), AspectRatio = table.Column<int>(nullable: true), RimSize = table.Column<int>(nullable: true), LoadRating1 = table.Column<int>(nullable: true), LoadRating2 = table.Column<int>(nullable: true), Speed = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Active = table.Column<bool>(nullable: true), Homologation1 = table.Column<string>(nullable: true), Homologation2 = table.Column<string>(nullable: true), RunFlat = table.Column<bool>(nullable: true), MOE = table.Column<bool>(nullable: true), SUV = table.Column<bool>(nullable: true), Seal = table.Column<bool>(nullable: true), NoiseCancelling = table.Column<bool>(nullable: true), LightTruck = table.Column<bool>(nullable: true), Commercial = table.Column<bool>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Skus", x => x.Id); }); migrationBuilder.CreateTable( name: "Tests", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Age = table.Column<int>(nullable: false), Year = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tests", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BooleanTests"); migrationBuilder.DropTable( name: "Patterns"); migrationBuilder.DropTable( name: "Skus"); migrationBuilder.DropTable( name: "Tests"); } } }
using System; using System.Windows.Forms; using TutteeFrame2.View; namespace TutteeFrame2 { static class Program { // Support forced run one instance of app only //const UInt32 SWP_NOSIZE = 0x0001; //const UInt32 SWP_NOMOVE = 0x0002; //const UInt32 SWP_SHOWWINDOW = 0x0040; //private static bool isNew; //[DllImport("user32.dll")] //public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); //[DllImport("user32.dll")] //private static extern bool SetForegroundWindow(IntPtr hWnd); //[DllImport("user32.dll")] //[return: MarshalAs(UnmanagedType.Bool)] //static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); ///// <summary> /// The main entry point for the application. /// </summary> /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); HomeView homeView = new HomeView(); LoginView loginView = new LoginView(homeView); SplashView splashView = new SplashView(); splashView.ShowDialog(); loginView.ShowDialog(); if (loginView.DialogResult == DialogResult.OK) Application.Run(homeView); else Application.Exit(); return; // Forced run one instance of app only //using (var m = new Mutex(true, "TutteeFrame", out isNew)) //{ // //If application owns the mutex, continue the execution // if (isNew) // { // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new HomeView()); // } // //else show user message that application is running and set focus to that application window // else // { // MessageBox.Show("Phần mềm đã đang chạy."); // Process current = Process.GetCurrentProcess(); // foreach (Process process in Process.GetProcessesByName(current.ProcessName)) // { // if (process.Id != current.Id) // { // ShowWindow(process.MainWindowHandle, 9); // SetForegroundWindow(process.MainWindowHandle); // break; // } // } // } //} } } }
#region namespace using EMAAR.ECM.Foundation.ORM.Models.sitecore.templates.Project.ECM.Page_Types.Mediacenter; #endregion namespace EMAAR.ECM.Feature.Listing.Interface { /// <summary> /// This is used to get the Media page with all necessary components(Top 3 News,Events,Downloads,I,age Gallery and Video gallery) /// </summary> public interface IMediacenterRepositories { #region method /// <summary> /// This is used to get the Media page with all necessary components(Top 3 News,Events,Downloads,I,age Gallery and Video gallery) /// </summary> /// <returns>Mediacenter page</returns> IMediacenterViewmodel GetMediacenterPage(); #endregion } }
 using System.Collections.Generic; using Service; using MKService.MessageHandlers; using MKService.Queries; using MKService.QueryFactories; namespace MKService.QueryHandlers { /// <summary> /// The query handler collection factory. /// </summary> /// <seealso cref="MKService.QueryHandlers.IQueryHandlerCollectionFactory"/> internal class QueryHandlerCollectionFactory : IQueryHandlerCollectionFactory { /// <summary> /// The message handler resolver. /// </summary> private readonly IServerMessageHandlerResolver messageHandlerResolver; /// <summary> /// The query factory resolver. /// </summary> private readonly IQueryFactoryResolver queryFactoryResolver; /// <summary> /// Initializes a new instance of the <see cref="QueryHandlerCollectionFactory" /> class. /// </summary> /// <param name="queryFactoryResolver">The model factory resolver.</param> /// <param name="messageHandlerResolver">The message handler resolver.</param> public QueryHandlerCollectionFactory( IQueryFactoryResolver queryFactoryResolver, IServerMessageHandlerResolver messageHandlerResolver) { this.queryFactoryResolver = queryFactoryResolver; this.messageHandlerResolver = messageHandlerResolver; } /// <summary> /// Creates a list of query handlers. /// </summary> /// <param name="queryContract">The query contract.</param> /// <param name="commandContract">The command contract.</param> /// <param name="rootHandler">The root query handler.</param> /// <returns>A list of query handlers.</returns> public IList<IQueryHandler> Create( IQueryContract queryContract, ICommandContract commandContract, IQueryHandler rootHandler) { var result = new List<IQueryHandler> { new SessionTimeQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<SessionTimeQuery>().Create(), this.messageHandlerResolver), new MageKnightQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<MageKnightQuery>().Create(), this.messageHandlerResolver), new UserQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<UserQuery>().Create(), this.messageHandlerResolver), new DialQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<DialQuery>().Create(), this.messageHandlerResolver), new ClickQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<ClickQuery>().Create(), this.messageHandlerResolver), new StatQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<StatQuery>().Create(), this.messageHandlerResolver), new UserCollectionQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<UserCollectionQuery>().Create(), this.messageHandlerResolver), new GameQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<GameQuery>().Create(), this.messageHandlerResolver), new GamesQueryHandler( queryContract, commandContract, rootHandler, this.queryFactoryResolver.GetFactory<GamesQuery>().Create(), this.messageHandlerResolver), }; return result; } } }
using Application.Contract.Responses; using Application.CQRS.Commands; using Application.CQRS.Handlers.Commands; using Application.CQRS.Handlers.Queries; using Application.CQRS.Pipelines; using Application.CQRS.Queries; using Application.Maping; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; namespace Application { public static class ConfigurationStartup { public static void ConfigureApplicationServices(this IServiceCollection services) { services.AddSingleton<IMapper, Mapper>(); services.AddTransient<IRequestHandler<GetAllCryptoCurrencies, List<CryptoCurrencyResponse>>, GetAllCryptoCurrenciesHandler>(); services.AddTransient<IRequestHandler<GetCryptoCurrencyRawDataQuery, CryptoCurrencyRawResponse>, GetCryptoCurrencyRawDataHandler>(); services.AddTransient<IRequestHandler<AddCryptoCurrencyCommand, ValidateableResponse<CryptoCurrencyRawResponse>>, AddCryptoCurrencyHandler>(); services.AddTransient<IRequestHandler<RemoveCryptoCurrencyCommand, ValidateableResponse<CryptoCurrencyDeleteResponse>>, RemoveCryptoCurrencyHandler>(); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); services.AddValidatorsFromAssembly(typeof(ConfigurationStartup).Assembly); } } }
using System; using Xunit; using Microsoft.AspNetCore.TestHost; //TestServer //add NU Package using System.Net.Http; //HttpClient using Microsoft.Extensions.Configuration; //ConfigurationBuilder using Microsoft.AspNetCore.Hosting; //WebHostBuilder using System.Threading.Tasks; //Tasks using System.Net; namespace WebInv.Server.Test { public class UnitTest101: IDisposable { private readonly TestServer server; private readonly HttpClient client; public UnitTest101() { var webBuilder = new WebHostBuilder(); webBuilder.UseContentRoot("/"); webBuilder.UseEnvironment("TEST123"); webBuilder.UseConfiguration(new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build() ); webBuilder.UseStartup<Startup>(); server = new TestServer(webBuilder); this.client = this.server.CreateClient(); } [Fact] public async void InvStore_Get_ReturnsAllStores() { HttpResponseMessage response = await this.server.CreateRequest("/api/InvStores").SendAsync("GET"); string resultstring = await response.Content.ReadAsStringAsync(); Assert.Contains("Cebu-Banilad", resultstring); Assert.Contains("Davao Bajada", resultstring); } [Fact] public async Task InvStore_Get_ReturnsAllStores_method2() { //var url = "https://localhost:44359/api/InvStores"; var result = await this.client.GetAsync("/api/InvStores"); //webapi: api/InvStores; page: /StoreList var resultstring = await result.Content.ReadAsStringAsync(); Assert.Contains("Cebu-Banilad", resultstring); Assert.Contains("Davao Bajada", resultstring); } [Theory] [InlineData(1, "Cebu-Banilad")] [InlineData(2, "Davao Bajada")] [InlineData(3, "Gensan")] [InlineData(4, "Cagayan")] [InlineData(5, "Makati")] public async Task InvStore_GetById_ReturnsAStore(int id, string keyword) { var result = await this.client.GetAsync("/api/InvStores/" + id.ToString()); var resultstring = await result.Content.ReadAsStringAsync(); Assert.Contains(keyword, resultstring); } public void Dispose() { client.Dispose(); server.Dispose(); } } }
namespace Logic.TechnologyClasses { public class ResearchCenter { private readonly ResearchArchive archive; private readonly ResearchLabs labs; private readonly AvailableResearch available; } }
using System; using System.Collections.Generic; using ETravel.Coffee.DataAccess.Entities; using ETravel.Coffee.DataAccess.Interfaces; using NHibernate.Criterion; namespace ETravel.Coffee.DataAccess.Repositories { public class OrderItemsRepository : Repository, IOrderItemsRepository { public IList<OrderItem> ForOrderId(Guid orderId) { return Session .CreateCriteria<OrderItem>() .Add(Restrictions.Eq("OrderId", orderId)).List<OrderItem>(); } public OrderItem GetById(Guid id) { return Session.Get<OrderItem>(id); } public void Save(OrderItem item) { Session.Save(item); Session.Flush(); } public void Update(OrderItem item) { Session.Update(item); Session.Flush(); } public void Delete(Guid id) { Session.Delete(GetById(id)); Session.Flush(); } } }
using StudyEspanol.Data.Managers; using StudyEspanol.Data.Models; namespace StudyEspanol.UI.Screens { public partial class VocabQuizScreen { #region Const Fields public const string VOCAB_QUIZ_SCREEN = "vocab_quiz_screen"; #endregion #region Fields TranslateDirection translationDirection; #endregion #region Initialization protected override void Initialization() { base.Initialization(); QuizManager.Instance.AddQuizWords(WordsManager.Instance.WordsToQuizWords(translationDirection)); } #endregion } }
using UnityEngine; using System; public class AudioManager : MonoBehaviour { public static AudioManager audioManagerInstance; public AudioSource sfxSource; public AudioSource musicSource; public Sound[] sounds; void Awake() { if (audioManagerInstance == null) { audioManagerInstance = this; } else { Destroy(gameObject); return; } DontDestroyOnLoad(gameObject); } public void PlaySFX(string name) { Sound sound = Array.Find(sounds, s => s.name == name); if (sound == null) { Debug.LogWarning("Sound '" + name + "' not found"); return; } sfxSource.clip = sound.clip; sfxSource.volume = sound.volume; sfxSource.pitch = sound.pitch; sfxSource.loop = sound.loop; sfxSource.PlayOneShot(sound.clip, sound.volume); } public void PlayMusic(string name) { Sound sound = Array.Find(sounds, s => s.name == name); if (sound == null) { Debug.LogWarning("Music '" + name + "' not found"); return; } musicSource.clip = sound.clip; musicSource.volume = sound.volume; musicSource.pitch = sound.pitch; musicSource.loop = sound.loop; musicSource.Play(); } [ContextMenu("Sort Sounds By Name")] void DoSortSounds() { System.Array.Sort(sounds, (a, b) => a.name.CompareTo(b.name)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Admission의 요약 설명입니다. /// </summary> public class Admission { public int brch_id { get; set; } public int std_id { get; set; } public int cors_id { get; set; } public int pbt_ref_id { get; set; } public int aevt_id { get; set; } public int aevts_seq { get; set; } public string schedule_date { get; set; } public string schedule_time { get; set; } public string rec_level { get; set; } public string clevel_name { get; set; } public string astd_proc_result { get; set; } public string astd_notice_result { get; set; } public string astd_note { get; set; } public string final_code_id { get; set; } public int evaluator_stf_id { get; set; } } public class ClassSearch { public int stf_id { get; set; } public int brch_id { get; set; } public int bsem_id { get; set; } public int cls_id { get; set; } public string cls_name { get; set; } public string classdate { get; set; } public string classdatetime { get; set; } public int cjrn_id { get; set; } public int cjsec_section_type { get; set; } public int cors_id { get; set; } public string brch_schl_type { get; set; } public int room_id { get; set; } public string ctdtl_start_time_type { get; set; } }
namespace NetComModels.Messages { public class BeginMsg : Msg { public string Msg { get; set; } public BeginMsg() : this("") { } public BeginMsg(string msg) : base(MsgType.Begin) { Msg = msg; } } }
using Business.Interfaces; using System; using System.Collections; using System.Collections.Generic; namespace Business.Stack { /// <summary> /// Represents the stack collection based on the linked list. /// </summary> /// <owner>Anton Petrenko</owner> public sealed class LinkedListStack<T> : ICustomCollection<T> { /// <summary> /// Holds the stack collection to work with. /// </summary> /// <owner>Anton Petrenko</owner> private readonly LinkedList<T> stack = new LinkedList<T>(); /// <summary> /// Adds an element to the end of the collection. /// </summary> /// <owner>Anton Petrenko</owner> /// <param name="element">The element to add.</param> public void Add(T element) { this.stack.AddLast(element); } /// <summary> /// Clears this collection instance. /// </summary> /// <owner>Anton Petrenko</owner> public void Clear() { this.stack.Clear(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <owner>Anton Petrenko</owner> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator<T> GetEnumerator() { return stack.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <owner>Anton Petrenko</owner> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return stack.GetEnumerator(); } /// <summary> /// Removes the last element from the collection. /// </summary> /// <owner>Anton Petrenko</owner> /// <returns>The last element from the end of the collection.</returns> public T Remove() { if (this.stack.Count == 0) throw new InvalidOperationException("There is no items in collection."); T itemToReturn = this.stack.Last.Value; this.stack.RemoveLast(); return itemToReturn; } /// <summary> /// Returns the last element that is at the end of the collection, but does not remove it. /// </summary> /// <owner>Anton Petrenko</owner> /// <returns>The last element that is at the end of the collection.</returns> public T ShowCurrent() { if (this.stack.Count == 0) throw new InvalidOperationException("There is no items in collection."); return this.stack.Last.Value; } } }
using System; using System.Collections.Generic; using System.Linq; namespace PmSoft { public class PagedList<T> : List<T>, IPagedList<T> { public PagedList(IEnumerable<T> allItems, int pageIndex, int pageSize) { PageSize = pageSize; var items = allItems as IList<T> ?? allItems.ToList(); TotalItemCount = items.Count(); CurrentPageIndex = pageIndex; AddRange(items.Skip(StartItemIndex - 1).Take(pageSize)); } public PagedList(IEnumerable<T> currentPageItems, int pageIndex, int pageSize, long totalItemCount) { AddRange(currentPageItems); TotalItemCount = totalItemCount; CurrentPageIndex = pageIndex; PageSize = pageSize; } public PagedList(IQueryable<T> allItems, int pageIndex, int pageSize) { int startIndex = (pageIndex - 1) * pageSize; AddRange(allItems.Skip(startIndex).Take(pageSize)); TotalItemCount = allItems.Count(); CurrentPageIndex = pageIndex; PageSize = pageSize; } public PagedList(IQueryable<T> currentPageItems, int pageIndex, int pageSize, int totalItemCount) { AddRange(currentPageItems); TotalItemCount = totalItemCount; CurrentPageIndex = pageIndex; PageSize = pageSize; } public int CurrentPageIndex { get; set; } public int PageSize { get; set; } public long TotalItemCount { get; set; } public int TotalPageCount { get { return (int)Math.Ceiling(TotalItemCount / (double)PageSize); } } public int StartItemIndex { get { return (CurrentPageIndex - 1) * PageSize + 1; } } public int EndItemIndex { get { return (int)(TotalItemCount > CurrentPageIndex * PageSize ? CurrentPageIndex * PageSize : TotalItemCount); } } public double Duration { get; set; } } }
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Zhouli.BLL.Interface; using Zhouli.Common.ResultModel; using Zhouli.DAL.Interface; using Zhouli.DbEntity.Models; using Zhouli.DbEntity.Views; using Zhouli.Dto.ModelDto; using Zhouli.Enum; namespace Zhouli.BLL.Implements { public class SysRoleBLL : BaseBLL<SysRole>, ISysRoleBLL { private readonly ISysRoleDAL sysRoleDAL; private readonly ISysUserDAL sysUserDAL; private readonly ISysUrRelatedDAL sysUrRelatedDAL; private readonly ISysUserGroupDAL sysUserGroupDAL; private readonly ISysUgrRelatedDAL sysUgrRelatedDAL; /// <summary> /// 用于实例化父级,sysRoleDAL /// </summary> /// <param name="sysRoleDAL"></param> public SysRoleBLL(ISysRoleDAL sysRoleDAL, ISysUserDAL sysUserDAL, ISysUrRelatedDAL sysUrRelatedDAL, ISysUserGroupDAL sysUserGroupDAL, ISysUgrRelatedDAL sysUgrRelatedDAL) : base(sysRoleDAL) { this.sysRoleDAL = sysRoleDAL; this.sysUserDAL = sysUserDAL; this.sysUrRelatedDAL = sysUrRelatedDAL; this.sysUserGroupDAL = sysUserGroupDAL; this.sysUgrRelatedDAL = sysUgrRelatedDAL; } #region 删除角色(批量删除) /// <summary> /// 删除用户(批量删除) /// </summary> /// <param name="roleId"></param> /// <returns></returns> public HandleResult<bool> DelRole(IEnumerable<string> roleId) { var handleResult = new HandleResult<bool>(); //查出需要删除的角色 var sysRoles = sysRoleDAL.GetModels(t => roleId.Any(a => a.Equals(t.RoleId))); foreach (var item in sysRoles) { //逻辑删除角色 item.DeleteSign = (int)DeleteSign.Sign_Undeleted; item.DeleteTime = DateTime.Now; sysRoleDAL.Update(item); } //最后一起提交数据库 bool bResult = sysRoleDAL.SaveChanges(); handleResult.Result = bResult; handleResult.Msg = bResult ? "删除成功" : "删除失败"; return handleResult; } #endregion #region 获取角色列表 /// <summary> /// 获取角色列表 /// </summary> /// <param name="page">第几页</param> /// <param name="limit">页容量</param> /// <param name="searchstr">搜索内容</param> /// <returns></returns> public HandleResult<PageModel> GetRoleList(string page, string limit, string searchstr) { var query = sysRoleDAL.GetModelsByPage(Convert.ToInt32(limit), Convert.ToInt32(page), false, t => t.CreateTime, t => t.RoleName.Contains(searchstr) || string.IsNullOrEmpty(searchstr) && t.DeleteSign.Equals((int)DeleteSign.Sing_Deleted)); return new HandleResult<PageModel> { Data = new PageModel { RowCount = query.Count(), Data = Mapper.Map<List<SysRole>>(query.ToList()) } }; } #endregion #region 为角色添加功能菜单 /// <summary> /// 为角色添加功能菜单 /// </summary> /// <param name="roleId"></param> /// <param name="menuDtos"></param> /// <returns></returns> public HandleResult<bool> AddRoleMenu(string roleId, List<SysMenuDto> menuDtos) { return new HandleResult<bool> { Result = sysRoleDAL.AddRoleMenu(roleId, Mapper.Map<List<SysMenu>>(menuDtos)) }; } #endregion #region 获取角色所分配的用户 /// <summary> /// 获取角色所分配的用户 /// </summary> /// <param name="roleId"></param> /// <returns></returns> public HandleResult<PageModel> GetRoleUserList(string roleId, string page, string limit, string searchstr) { var handleResult = new HandleResult<PageModel>(); var PageModel = new PageModel(); var urRelateds = sysUrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId)).ToList(); //构建条件 Expression<Func<SysUser, bool>> expression = t => (string.IsNullOrEmpty(searchstr) || t.UserName.Contains(searchstr) || t.UserNikeName.Contains(searchstr) || t.UserPhone.Contains(searchstr) || t.UserQq.Contains(searchstr) || t.UserWx.Contains(searchstr) || t.UserEmail.Contains(searchstr)) && t.DeleteSign.Equals((int)DeleteSign.Sing_Deleted) && urRelateds.Any(x => x.UserId == t.UserId); PageModel.RowCount = sysUserDAL.GetCount(expression); var list = sysUserDAL.GetModelsByPage(Convert.ToInt32(limit), Convert.ToInt32(page), false, t => t.CreateTime, expression).ToList(); PageModel.Data = Mapper.Map<List<SysUserDto>>(list); handleResult.Data = PageModel; return handleResult; } #endregion #region 为角色分配用户 /// <summary> /// 为角色分配用户 /// </summary> /// <param name="roleId"></param> /// <param name="userIds"></param> /// <returns></returns> public HandleResult<bool> AssignmentRoleUser(string roleId, List<string> userIds) { //删除用户角色关联表的角色ID var listSysUrRelateds = sysUrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId)); if (listSysUrRelateds.Count() > 0) sysUrRelatedDAL.Delete(listSysUrRelateds); foreach (var item in userIds) { sysUrRelatedDAL.Add(new SysUrRelated { UserId = item.ToString(), RoleId = roleId.ToString() }); } bool bReuslt = sysUrRelatedDAL.SaveChanges(); return new HandleResult<bool> { Msg = bReuslt ? "分配成功" : "分配失败", Result = bReuslt }; } #endregion #region 取消用户角色 /// <summary> /// 取消用户角色 /// </summary> /// <param name="roleId"></param> /// <param name="userIds"></param> /// <returns></returns> public HandleResult<bool> CancelUserAssignment(string roleId, List<string> userIds) { var melSysUrRelateds = sysUrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId) && userIds.Any(a => a.Equals(t.UserId))); sysUrRelatedDAL.Delete(melSysUrRelateds); bool bReuslt = sysUrRelatedDAL.SaveChanges(); return new HandleResult<bool> { Msg = bReuslt ? "取消授权成功" : "取消授权失败", Result = bReuslt }; } #endregion #region 获取角色所分配的用户组 /// <summary> /// 获取角色所分配的用户组 /// </summary> /// <param name="roleId"></param> /// <returns></returns> public HandleResult<PageModel> GetRoleUserGroupList(string roleId, string page, string limit, string searchstr) { var handleResult = new HandleResult<PageModel>(); var PageModel = new PageModel(); var urRelateds = sysUgrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId)); Expression<Func<SysUserGroup, bool>> expression = t => (string.IsNullOrEmpty(searchstr) || t.UserGroupName.Contains(searchstr)) && t.DeleteSign.Equals((int)DeleteSign.Sing_Deleted) && urRelateds.Any(x => x.UserGroupId == t.UserGroupId); PageModel.RowCount = sysUserGroupDAL.GetCount(expression); var list = sysUserGroupDAL.GetModelsByPage(Convert.ToInt32(limit), Convert.ToInt32(page), false, t => t.CreateTime, expression); PageModel.Data = Mapper.Map<List<SysUserGroupDto>>(list); handleResult.Data = PageModel; return handleResult; } #endregion #region 为角色分配用户组 /// <summary> /// 为角色分配用户组 /// </summary> /// <param name="roleId"></param> /// <param name="userGroupIds"></param> /// <returns></returns> public HandleResult<bool> AssignmentRoleUserGroup(string roleId, List<string> userGroupIds) { var sysUgrRelateds = sysUgrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId)); sysUgrRelatedDAL.Delete(sysUgrRelateds); foreach (var item in userGroupIds) { sysUgrRelatedDAL.Add(new SysUgrRelated { UserGroupId = item.ToString(), RoleId = roleId.ToString() }); } bool bReuslt = sysUgrRelatedDAL.SaveChanges(); return new HandleResult<bool> { Msg = bReuslt ? "分配成功" : "分配失败", Result = bReuslt }; } #endregion #region 取消用户组角色 /// <summary> /// 取消用户组角色 /// </summary> /// <param name="roleId"></param> /// <param name="userGroupIds"></param> /// <returns></returns> public HandleResult<bool> CancelUserGroupAssignment(string roleId, List<string> userGroupIds) { var sysUgrRelateds = sysUgrRelatedDAL.GetModels(t => t.RoleId.Equals(roleId) && userGroupIds.Any(a => a.Equals(t.UserGroupId))); sysUgrRelatedDAL.Delete(sysUgrRelateds); bool bReuslt = sysUgrRelatedDAL.SaveChanges(); return new HandleResult<bool> { Msg = bReuslt ? "取消授权成功" : "取消授权失败", Result = bReuslt }; } #endregion } }
using System.Collections; using System.Threading; namespace GServer { public class Coroutine { private IEnumerator mIterator; public int session { get { return (int)mIterator.Current; } } public Coroutine(IEnumerator iterator) { mIterator = iterator; if (mIterator != null) { mIterator.MoveNext(); } } public void Resume(object result) { Thread.SetData(Thread.GetNamedDataSlot("slot"), result); if (mIterator != null) { mIterator.MoveNext(); } } } }
using System; using System.Collections.Generic; using System.Text; using ENTITY; //<summary> //Summary description for PayHeadInfo //</summary> namespace ENTITY { public class PayHeadInfo { public decimal PayHeadId { get; set; } public string PayHeadName { get; set; } public string Type { get; set; } public string Narration { get; set; } public DateTime ExtraDate { get; set; } public string Extra1 { get; set; } public string Extra2 { get; set; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Web.UI; using DotNetNuke.Entities.Modules; namespace DotNetNuke.UI.Modules { public interface IModuleControlFactory { Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc); Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration); ModuleControlBase CreateModuleControl(ModuleInfo moduleConfiguration); Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CAR_Web_Project.Entity; namespace CAR_Web_Project.Page { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["user"] != null) Response.Redirect("MyCAR/OwnedCAR.aspx"); } protected void On_ButtonLogin_Click(object sender, EventArgs e) { User user = Entity.User.Get_ByUsername(TextBox_Username.Text); if (user.ID < 0 || user.Password != TextBox_Password.Text) Response.Redirect("LoginError.aspx"); else { Session.Add("user", user); Response.Redirect("MyCAR/OwnedCAR.aspx"); } } protected void On_ButtonRegister_Click(object sender, EventArgs e) { if (TextBox_Username.Text == "" || TextBox_Password.Text == "") return; if (Entity.User.Get_ByUsername(TextBox_Username.Text).ID >= 0) Response.Redirect("RegistError.aspx"); else { Entity.User user = new User(); user.Username = TextBox_Username.Text; user.Password = TextBox_Password.Text; user.ID = Entity.User.Add(user); Session["user"] = user; } } } }
using System; using System.IO; using Microsoft.Dynamics365.UIAutomation.Browser; using OpenQA.Selenium; using TechTalk.SpecFlow; using Vantage.Automation.VaultUITest.Context; namespace Vantage.Automation.VaultUITest.Helpers { public class EntityCreator { private readonly UIContext _uiContext; private readonly FieldSetter _fieldSetter; public EntityCreator(UIContext context, ScenarioContext scenarioContext) { _uiContext = context; _fieldSetter = new FieldSetter(_uiContext, scenarioContext); } public void GenerateAgreement(string agreementName, string accountName, string agreementPackage = null) { _uiContext.XrmApp.Navigation.OpenSubArea("Agreements"); _uiContext.XrmApp.CommandBar.ClickCommand("New"); _fieldSetter.FillInField("Agreement Name", agreementName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Vault Account", accountName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); if (!string.IsNullOrEmpty(agreementPackage)) { _fieldSetter.FillInField("Agreement Package", agreementPackage); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } _uiContext.XrmApp.CommandBar.ClickCommand("Save & Close"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } public void GenerateAccount(string accountName, string subscriptionLevel, string parentAccount = null) { _uiContext.XrmApp.Navigation.OpenSubArea("Accounts"); _uiContext.XrmApp.CommandBar.ClickCommand("New"); _fieldSetter.FillInField("Account Name", accountName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Subscription Level", subscriptionLevel); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); if (!string.IsNullOrEmpty(parentAccount)) { _fieldSetter.FillInField("Parent Account", parentAccount); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } _uiContext.XrmApp.CommandBar.ClickCommand("Save & Close"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } public void GenerateAgreementPackage(string agreementPackageName, string accountName) { _uiContext.XrmApp.Navigation.OpenSubArea("Agreement Packages"); _uiContext.XrmApp.CommandBar.ClickCommand("New"); _fieldSetter.FillInField("Name", agreementPackageName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Vault Account", accountName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Data Retention Years", "1"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _uiContext.XrmApp.CommandBar.ClickCommand("Save & Close"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } public void GenerateAgreementFile(string agreementFileName, string agreementPackageName, string agreementName, int numberFiles=0) { _uiContext.XrmApp.Navigation.OpenSubArea("Agreement Files"); _uiContext.XrmApp.CommandBar.ClickCommand("New"); _uiContext.XrmApp.Entity.SelectTab("Overview"); _fieldSetter.FillInField("Agreement", agreementName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Name", agreementFileName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("File Type", "Ancillary Document"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Agreement Package", agreementPackageName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); if (numberFiles > 0) { _uiContext.XrmApp.CommandBar.ClickCommand("Save"); var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData"); FileUtility.CreateDirectoryIfNotExists(directory); for (int i = 0; i < numberFiles; i++) { var path = Path.Combine(directory, $"file_{DateTime.Now.Ticks}.txt"); FileUtility.CreateFileOfSize(path, 1024); var fileInput = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath("//input[@type='file']")); fileInput.SendKeys(path); _uiContext.XrmApp.ThinkTime(5000); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _uiContext.XrmApp.Entity.SelectTab("Overview"); } } _uiContext.XrmApp.CommandBar.ClickCommand("Save & Close"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } public void GenerateClause(string clauseName, string agreementName, string agreementPackageName, string agreementFileName) { _uiContext.XrmApp.Navigation.OpenSubArea("Clauses"); _uiContext.XrmApp.CommandBar.ClickCommand("New"); _fieldSetter.FillInField("Clause Text", clauseName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Agreement", agreementName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Agreement Package", agreementPackageName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Agreement File", agreementFileName); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _fieldSetter.FillInField("Clause Type", "Deliverable"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); _uiContext.XrmApp.CommandBar.ClickCommand("Save & Close"); _uiContext.WebClient.Browser.Driver.WaitForTransaction(); } } }
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.Security; using System.Web.SessionState; using UrbanScience.Si2.Mvc.InjectableServices; namespace UrbanScience.Si2.Website.Module.InactiveCustomer.Handlers.PartsOpportunity { public class CriteriaFullObject { public List<CriteriaObject> RegionList { get; set; } public List<CriteriaObject> ZoneList { get; set; } public List<CriteriaObject> DistrictList { get; set; } public List<CriteriaObject> BACList { get; set; } } public class CriteriaObject { public string DropDownListToPopulate { get; set; } public string GeographyName { get; set; } public int GeographyTypeId { get; set; } public int FeatureID { get; set; } public int ChildID { get; set; } public int selected { get; set; } } /// <summary> /// Summary description for GetAllCriteria /// </summary> public class GetAllCriteria : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { int UserId; if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { UserId = (int)Membership.GetUser().ProviderUserKey; } else { return; } var RegionID = HttpContext.Current.Request.QueryString["RegionID"]; var ZoneID = HttpContext.Current.Request.QueryString["ZoneID"]; var DistrictID = HttpContext.Current.Request.QueryString["DistrictID"]; var DealerGeographyOnly = HttpContext.Current.Request.QueryString["DealerGeographyOnly"]; using (var connection = DatabaseProvider.GetDataConnection()) { List<CriteriaObject> result = connection.Query<CriteriaObject>("GetAllGeographyCriteriaForUserWithSelections", new { userid = UserId, RegionID = RegionID, ZoneID = ZoneID, DistrictID = DistrictID, DealerGeographyOnly = DealerGeographyOnly }, commandType: CommandType.StoredProcedure).ToList(); context.Response.ContentType = "application/json"; CriteriaFullObject CriteriaFullObject = new CriteriaFullObject(); CriteriaFullObject.RegionList = result.Where(s => s.DropDownListToPopulate == "REGION").OrderByDescending(t => t.GeographyTypeId).ThenBy(x => x.ChildID).ToList(); CriteriaFullObject.ZoneList = result.Where(s => s.DropDownListToPopulate == "ZONE" ).OrderByDescending(t => t.GeographyTypeId).ThenBy(x => x.ChildID).ToList(); CriteriaFullObject.DistrictList = result.Where(s => s.DropDownListToPopulate == "DISTRICT").OrderByDescending(t => t.GeographyTypeId).ThenBy(x => x.ChildID).ToList(); CriteriaFullObject.BACList = result.Where(s => s.DropDownListToPopulate == "AGSSA").OrderByDescending(t => t.GeographyTypeId).ThenBy(x => x.ChildID).ToList(); context.Response.Write(new JavaScriptSerializer().Serialize(CriteriaFullObject)); } //context.Response.ContentType = "text/plain"; } public bool IsReusable { get { return false; } } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { internal class MarkedStringConverter : JsonConverter<MarkedString> { public override void WriteJson(JsonWriter writer, MarkedString value, JsonSerializer serializer) { if (string.IsNullOrWhiteSpace(value.Language)) { writer.WriteValue(value.Value); } else { writer.WriteStartObject(); writer.WritePropertyName("language"); writer.WriteValue(value.Language); writer.WritePropertyName("value"); writer.WriteValue(value.Value); writer.WriteEndObject(); } } public override MarkedString ReadJson(JsonReader reader, Type objectType, MarkedString existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject) { var result = JObject.Load(reader); return new MarkedString(result["language"]?.Value<string>(), result["value"].Value<string>()); } if (reader.TokenType == JsonToken.String) { return new MarkedString((reader.Value as string)!); } return ""; } public override bool CanRead => true; } }
#region Copyright, Author Details and Related Context //<notice lastUpdateOn="12/20/2015"> // <solution>KozasAnt</solution> // <assembly>KozasAnt.Engine</assembly> // <description>A modern take on Koza's connonical "Ant Foraging for Food on a Grid" problem that leverages Roslyn</description> // <copyright> // Copyright (C) 2015 Louis S. Berman // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <author> // <fullName>Louis S. Berman</fullName> // <email>louis@squideyes.com</email> // <website>http://squideyes.com</website> // </author> //</notice> #endregion using System; namespace KozasAnt.Engine { public class KnownAs : Cohort, IComparable<KnownAs>, IEquatable<KnownAs> { public new static class Limits { public static class EntityId { public const int MinValue = 0; public const int MaxValue = 9999; } } public KnownAs(Cohort cohort, int entityId) : base(cohort.CohortId) { EntityId = entityId; } public int EntityId { get; } public int CompareTo(KnownAs other) { if (CohortId == other.CohortId) return EntityId.CompareTo(other.EntityId); else return CohortId.CompareTo(other.CohortId); } public bool Equals(KnownAs other) { return GetHashCode() == other.GetHashCode(); } public override bool Equals(object @object) { if (!(@object is KnownAs)) return false; return GetHashCode().Equals(((KnownAs)@object).GetHashCode()); } public override int GetHashCode() { return (CohortId * 10000) + EntityId; } public override string ToString() { return $"Cohort{CohortId:0000}_Entity{EntityId:0000}"; } } }
using System.Windows.Controls; namespace Emanate.Extensibility { public class ConfigurationEditor : UserControl { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New ShopItem", menuName = "Custom/ShopItem")] public class ShopItem : ScriptableObject { public int Price; public string Name; public string Description; public ScriptableObject Item; public bool Available; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Globalization; using System.Diagnostics; using POG.Utils; namespace POG.Forum { public class LobbyReaderEstonia : LobbyReader { public LobbyReaderEstonia(ConnectionSettings connectionSettings, Action<Action> synchronousInvoker) : base(connectionSettings, synchronousInvoker) { ParseItemTime = Misc.ParseItemTimeEstonia; } protected override void ParseLobbyPage(string url, string doc, out DateTimeOffset serverTime, ref List<ForumThread> threadList) { Int32 threadId = VBulletinForum.ThreadIdFromUrl(url); var html = new HtmlAgilityPack.HtmlDocument(); html.LoadHtml(doc); HtmlAgilityPack.HtmlNode root = html.DocumentNode; serverTime = DateTime.Now; HtmlAgilityPack.HtmlNode timeNode = root.SelectNodes("//div[@id='footer_time']").Last(); if (timeNode != null) { String timeText = timeNode.InnerText; serverTime = Utils.Misc.ParsePageTime(timeText, DateTime.UtcNow); } HtmlAgilityPack.HtmlNodeCollection threads = root.SelectNodes("//tbody[contains(@id, 'threadbits_forum_')]/tr"); if (threads == null) { return; } foreach (HtmlAgilityPack.HtmlNode thread in threads) { ForumThread t = HtmlToThread(threadId, thread, serverTime); if (t != null) { threadList.Add(t); } } } } public class LobbyReader { #region fields readonly ConnectionSettings _connectionSettings; Action<Action> _synchronousInvoker; protected Misc.ParseItemTimeDelegate ParseItemTime = Misc.ParseItemTimeEnglish; #endregion #region constructors public LobbyReader(ConnectionSettings connectionSettings, Action<Action> synchronousInvoker) { _connectionSettings = connectionSettings; _synchronousInvoker = synchronousInvoker; } private LobbyReader() { } #endregion #region public methods public void ReadLobby(String url, Int32 pageStart, Int32 pageEnd, Boolean recentFirst) { Task t = new Task(() => GetPages(url, pageStart, pageEnd, recentFirst)); t.Start(); } #endregion #region public events public event EventHandler<LobbyPageCompleteEventArgs> LobbyPageCompleteEvent; #endregion #region event helpers virtual internal void OnLobbyPageComplete(String url, Int32 page, DateTimeOffset ts, Boolean recentFirst, List<ForumThread> threads) { try { var handler = LobbyPageCompleteEvent; if (handler != null) { _synchronousInvoker.Invoke( () => handler(this, new LobbyPageCompleteEventArgs(url, page, ts, recentFirst, threads)) ); } } catch { } } #endregion #region private methods void GetPages(String url, Int32 pageStart, Int32 pageEnd, Boolean recentFirst) { // beginning of time: // http://forumserver.twoplustwo.com/59/puzzles-other-games/?pp=25&sort=dateline&order=asc&daysprune=-1 // http://forumserver.twoplustwo.com/59/puzzles-other-games/index2.html?sort=dateline&order=asc&daysprune=-1 // normal: // http://forumserver.twoplustwo.com/59/puzzles-other-games/ // http://forumserver.twoplustwo.com/59/puzzles-other-games/index2.html Parallel.For(pageStart, pageEnd + 1, (Int32 page) => { GetPage(url, page, recentFirst); }); } void GetPage(String url, Int32 pageNumber, Boolean recentFirst) { if (pageNumber > 1) { url += "index" + pageNumber + ".html"; } if (!recentFirst) { url += "?sort=dateline&order=asc&daysprune=-1"; } string doc = null; for (int i = 0; i < 10; i++) { ConnectionSettings cs = _connectionSettings.Clone(); cs.Url = url; doc = HtmlHelper.GetUrlResponseString(cs); if (doc != null) { break; } else { Trace.TraceInformation("*** Error fetching page " + pageNumber.ToString()); } } List<ForumThread> threadList = new List<ForumThread>(); if (doc == null) { OnLobbyPageComplete(url, pageNumber, DateTime.Now, recentFirst, threadList); return; } DateTimeOffset ts; ParseLobbyPage(url, doc, out ts, ref threadList); OnLobbyPageComplete(url, pageNumber, ts, recentFirst, threadList); } protected virtual void ParseLobbyPage(string url, string doc, out DateTimeOffset serverTime, ref List<ForumThread> threadList) { Int32 threadId = VBulletinForum.ThreadIdFromUrl(url); var html = new HtmlAgilityPack.HtmlDocument(); html.LoadHtml(doc); HtmlAgilityPack.HtmlNode root = html.DocumentNode; serverTime = DateTime.Now; //(//div[class="smallfont", align="center'])[last()] All times are GMT ... The time is now <span class="time">time</span>"." HtmlAgilityPack.HtmlNode timeNode = root.SelectNodes("//div[@class='smallfont'][@align='center']").Last(); if (timeNode != null) { String timeText = timeNode.InnerText; serverTime = Utils.Misc.ParsePageTime(timeText, DateTime.UtcNow); } HtmlAgilityPack.HtmlNodeCollection threads = root.SelectNodes("//tbody[contains(@id, 'threadbits_forum_')]/tr"); if (threads == null) { return; } String urlBase = url.Substring(0, url.LastIndexOf('/') + 1); foreach (HtmlAgilityPack.HtmlNode thread in threads) { ForumThread t = HtmlToThread(threadId, thread, serverTime); if (t != null) { if (!t.URL.StartsWith("http")) t.URL = urlBase + t.URL; threadList.Add(t); } } } protected ForumThread HtmlToThread(int threadId, HtmlAgilityPack.HtmlNode thread, DateTimeOffset pageTime) { ForumThread ft = new ForumThread(); // td[1] = thread status icon HtmlAgilityPack.HtmlNode node = thread.SelectSingleNode("td[1]/img"); Boolean locked = false; if (node != null) { String img = node.Attributes["src"].Value; if(img.Contains("lock")) { locked = true; } } ft.Locked = locked; // td[2]/img = thread icon node = thread.SelectSingleNode("td[2]/img"); String threadIcon = String.Empty; if (node != null) { threadIcon = node.Attributes["alt"].Value; ft.ThreadIconText = threadIcon; } // td[3] = title area // div[1]/a[id like thread_title_] Title, link String threadURL = String.Empty; String threadTitle = String.Empty; node = thread.SelectSingleNode("td[3]/div[1]/a[contains(@id, 'thread_title_')]"); if (node != null) { threadTitle = HtmlAgilityPack.HtmlEntity.DeEntitize(node.InnerText); threadURL = HtmlAgilityPack.HtmlEntity.DeEntitize(node.Attributes["href"].Value); ft.Title = threadTitle; ft.URL = threadURL; ft.ThreadId = Misc.TidFromURL(ft.URL); } // div[2]/span OP name node = thread.SelectSingleNode("td[3]/div[2]/span[@style='cursor:pointer']"); if (node != null) { Int32 opId = -1; String threadOP = HtmlAgilityPack.HtmlEntity.DeEntitize(node.InnerText); String profile = node.Attributes["onclick"].Value; if (profile != string.Empty) { opId = Misc.ParseMemberId(profile); } ft.OP = new Poster(threadOP, opId); } // td[4] = last post area // title=Replies: x, Views: Y String lastPostTime = String.Empty; String lastPoster = String.Empty; node = thread.SelectSingleNode("td[4]/div"); if (node != null) { String lastInfo = HtmlAgilityPack.HtmlEntity.DeEntitize(node.InnerText.Trim()); String[] lines = lastInfo.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); if (lines.Count() >= 2) { lastPostTime = lines[0].Trim(); DateTimeOffset dtLastPost = ParseItemTime(pageTime, lastPostTime); lastPoster = lines[1].Trim().Substring(3); ft.LastPostTime = dtLastPost.ToUniversalTime(); } Int32 lastId = -1; node = node.SelectSingleNode("a[1]"); if (node != null) { String profile = node.Attributes["href"].Value; lastId = Misc.ParseMemberId(profile); } ft.LastPoster = new Poster(lastPoster, lastId); } String sReplies = String.Empty; node = thread.SelectSingleNode("td[5]/a"); if (node != null) { sReplies = node.InnerText; Int32 replies; if(Int32.TryParse(sReplies, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out replies)) { ft.ReplyCount = replies; } } String sViews = String.Empty; node = thread.SelectSingleNode("td[6]"); if (node != null) { sViews = node.InnerText; Int32 views; if (Int32.TryParse(sViews, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out views)) { ft.Views = views; } } return ft; } #endregion } public class LobbyPageCompleteEventArgs : EventArgs { public String URL { get; private set; } public Int32 Page { get; private set; } public Boolean RecentFirst { get; private set; } public DateTimeOffset TimeStamp { get; private set; } public List<ForumThread> Threads { get; private set; } public LobbyPageCompleteEventArgs(String url, Int32 page, DateTimeOffset ts, Boolean recentFirst, List<ForumThread> threads) { URL = url; Page = page; TimeStamp = ts; RecentFirst = recentFirst; Threads = threads; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ERP_Palmeiras_RH.Models { public partial class Cargo { public override String ToString() { return this.Nome; } } }
/** File Created May 5th 2017 - File name = NPC.cs Author: Gabriel Gaudreau Project: ShootingRangeGame */ using System; using UnityEngine; public class NPC : MonoBehaviour, IShootable { private float hp, deadTimer, speed, nearRadius, currRotVel, currVel, maxRotAcc, maxRotVel, currAcc, maxFleeVel, firstTimer, maxDMG, eyeDMG, headDMG, coreDMG, bodyDMG; private CircularPathNode target = null; private Vector3 direction; private bool firstTarget, dead, firstDead; private MeshRenderer[] meshes; private ParticleSystem[] particleSystems; private Collider[] colliders; [SerializeField] GameObject deadDummy; /// <summary> /// Initializes different variables to different values /// </summary> void Start() { hp = 200; eyeDMG = maxDMG = 75; headDMG = coreDMG = 50; bodyDMG = 25; speed = 0.2f; nearRadius = 0.5f; maxRotVel = 1.5f; currAcc = 1f; maxFleeVel = 2.0f; maxRotAcc = 0.01f; firstTimer = 1.5f; firstTarget = true; firstDead = true; deadTimer = 25.0f; meshes = GetComponentsInChildren<MeshRenderer>(); particleSystems = GetComponentsInChildren<ParticleSystem>(); colliders = GetComponentsInChildren<Collider>(); } /// <summary> /// This method will hide the NPC object in the game, including meshes, particle systems and colliders. /// </summary> private void HideMesh() { foreach (MeshRenderer m in meshes) { m.enabled = false; } foreach (ParticleSystem ps in particleSystems) { ps.Stop(); } foreach (Collider c in colliders) { c.enabled = false; } } /// <summary> /// This method will show the NPC object in the game, including meshes, particle systems and colliders. /// </summary> private void ShowMesh() { foreach (MeshRenderer m in meshes) { m.enabled = true; } foreach (ParticleSystem ps in particleSystems) { ps.Play(); } foreach (Collider c in colliders) { c.enabled = true; } } /// <summary> /// Update function, runs every frame, finds the npc's target node and moves to that until /// when it is close enough to his target, he will find the next node in his path and move to that node. /// Also handles what the NPC does while it is dead. Keeps moving, but hides meshes and disables colliders. /// This way, the NPCs keep an equal interval between them. /// </summary> void FixedUpdate() { if (!GameManager.gm.IsGamePaused()) { //Timer for first node rotation by npc firstTimer -= Time.deltaTime; if (firstTimer < 0.0f) { firstTarget = false; } //only happens once, can't be run in start. try awake? if (target == null) { target = FindClosestNode(); } //Move until close enough to target, then find next node Move(target.WorldPos, firstTarget); if (Vector3.Distance(target.WorldPos, transform.position) < nearRadius) { target = target.Next; } if (dead) { deadTimer -= Time.deltaTime; if (firstDead) { // Only executes the first frame the NPC is dead firstDead = false; HideMesh(); } if (deadTimer < 0) { // NPC is now alive again deadTimer = 25.0f; hp = 200; ShowMesh(); firstDead = true; dead = false; } } } } /// <summary> /// Method from the IShootable interface, called when the target is hit by a projectile. /// </summary> /// <param name="objectHit">name of the object hit.</param> void IShootable.GotShot(string objectHit) { /** eye - 75hp - 75pts head - 50hp - 50pts core - 50hp - 50pts body - 25hp - 25pts */ if (!dead) { if (objectHit == "Eye") { hp -= eyeDMG; GameManager.gm.AddScore(eyeDMG, maxDMG); } else if (objectHit == "Head") { hp -= headDMG; GameManager.gm.AddScore(headDMG, maxDMG); } else if (objectHit == "PowerSourceCore") { hp -= coreDMG; GameManager.gm.AddScore(coreDMG, maxDMG); } else { // Body includes everything that isn't eye, head or core. hp -= bodyDMG; GameManager.gm.AddScore(bodyDMG, maxDMG); } if (hp <= 0) { // NPC dies. dead = true; Instantiate(deadDummy, transform.position, transform.rotation); } } } /// <summary> /// Movement behavior, calculates rotation speed and lerps to the target rotation and moves the npc forward /// </summary> /// <param name="targetPos">The position of the next node in the path.</param> /// <param name="startNode">Bool to tell the method if the position passed in is the position of the first node.</param> private void Move(Vector3 targetPos, bool firstTime) { //Rotation calculations direction = (targetPos - transform.position).normalized; currRotVel = Mathf.Min(currRotVel + maxRotAcc, maxRotVel); currVel = Mathf.Min(currVel + currAcc, maxFleeVel); Quaternion targetRotation = Quaternion.LookRotation(direction); transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, currRotVel * 5 * Time.deltaTime); //Forward movement if (firstTime) { // x / 75 is to slow down the speed of the npc, allowing the rotation to complete transform.position += transform.forward * speed / 75; } else { //basic speed. transform.position += transform.forward * speed; } } /// <summary> /// Finds the closest node to the current position of the NPC /// </summary> /// <returns>Returns a CircularPathNode</returns> CircularPathNode FindClosestNode() { //dummy variable to save closest node CircularPathNode closestNode = null; float minDistance = Mathf.Infinity; for (int i = 0; i < CircularPath.instance.Nodes.Length; i++) { //check distance vs minDistance if (Vector3.Distance(CircularPath.instance.Nodes[i].WorldPos, transform.position) < minDistance) { minDistance = Vector3.Distance(CircularPath.instance.Nodes[i].WorldPos, transform.position); closestNode = CircularPath.instance.Nodes[i]; } } //return next since the npc will always spawn on the same position as a node return closestNode.Next; } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Data.SqlClient; namespace GeorgePairs { public partial class Register : Window { public Register() { WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; InitializeComponent(); } private void btnExit_Click(object sender, RoutedEventArgs e) { Close(); } private void btnToLogin_Click(object sender, RoutedEventArgs e) { Login log = new Login(); App.Current.MainWindow = log; this.Close(); log.Show(); } private void btnToMain_Click(object sender, RoutedEventArgs e) { MainWindow main = new MainWindow(); App.Current.MainWindow = main; this.Close(); main.Show(); } private void MinimizeButton_Click(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } private void MaximizeButton_Click(object sender, RoutedEventArgs e) { AdjustWindowSize(); } private void AdjustWindowSize() { if (this.WindowState == WindowState.Maximized) { this.WindowState = WindowState.Normal; } else { this.WindowState = WindowState.Maximized; } } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); this.DragMove(); } String imagePathForDb; SqlConnection con = new SqlConnection(HIDE); private void btnImg1_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/1.png"; } private void btnImg2_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/2.png"; } private void btnImg3_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/3.png"; } private void btnImg4_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/4.png"; } private void btnImg5_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/5.png"; } private void btnImg6_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/6.png"; } private void btnImg7_Click(object sender, RoutedEventArgs e) { imagePathForDb = "/imagini/7.png"; } private void btnRegSucces_Click(object sender, RoutedEventArgs e) { if (!String.IsNullOrEmpty(tbxUsername.Text) && !String.IsNullOrEmpty(tbxParola.Password) && !String.IsNullOrEmpty(imagePathForDb)) { try { con.Open(); String query = "INSERT into players(username,password,avatar) VALUES('" + tbxUsername.Text + "','" + tbxParola.Password + "','" + imagePathForDb + "')"; SqlDataAdapter sda = new SqlDataAdapter(query, con); sda.SelectCommand.ExecuteNonQuery(); con.Close(); LabelSucces.Content = "Contul s-a creat cu succes!"; LabelError.Content = ""; } catch { LabelError.Content = "E R O A R E!"; } } else { LabelError.Content = "Completeaza campurile si selecteaza avatarul!"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using EnglishHubRepository; using Microsoft.Extensions.Options; using EnglishHubApi.Models; namespace EnglishHubApi.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class AnswerController : ControllerBase { private IAnswerRepository answerRepository; public AnswerController(IAnswerRepository _answerRepository, IOptions<Settings> settings) { this.answerRepository = _answerRepository; } // GET api/values [HttpGet] public ActionResult<IEnumerable<AnswerEntity>> GetAll() { var result = answerRepository.GetAll().Result; return result; } // GET api/values/5 [HttpPost] public async Task<IActionResult> Add([FromBody]AnswerEntity answer) { var result = await answerRepository.Add(answer); return Ok(result); } public Task<List<AnswerEntity>> GetResults() { return answerRepository.GetResults(); } [HttpPost] public async Task<IActionResult> AddMany([FromBody]List<AnswerEntity> answers) { var result = await answerRepository.AddMany(answers); return Ok(result); } } }
using PDV.DAO.Atributos; namespace PDV.DAO.Entidades { public class IntegracaoFiscal { [CampoTabela("IDINTEGRACAOFISCAL")] public decimal IDIntegracaoFiscal { get; set; } [CampoTabela("IDCFOP")] public decimal IDCFOP { get; set; } [CampoTabela("IDTIPOOPERACAO")] public decimal IDTipoOperacao { get; set; } [CampoTabela("IDPORTARIA")] public decimal? IDPortaria { get; set; } [CampoTabela("IDCSTICMS")] public decimal IDCSTIcms { get; set; } [CampoTabela("IDCSTIPI")] public decimal IDCSTIpi { get; set; } [CampoTabela("IDCSTPIS")] public decimal IDCSTPis { get; set; } [CampoTabela("IDCSTCOFINS")] public decimal IDCSTCofins { get; set; } [CampoTabela("DESCRICAO")] public string Descricao { get; set; } [CampoTabela("SEQUENCIA")] public decimal Sequencia { get; set; } = 1; [CampoTabela("ICMS")] public decimal ICMS { get; set; } [CampoTabela("ICMS_IPI")] public decimal ICMS_IPI { get; set; } [CampoTabela("ICMS_ST")] public decimal ICMS_ST { get; set; } [CampoTabela("ICMS_RED")] public decimal ICMS_RED { get; set; } [CampoTabela("ICMS_REDST")] public decimal ICMS_REDST { get; set; } [CampoTabela("ICMS_DIFERENCIADO")] public decimal ICMS_DIFERENCIADO { get; set; } [CampoTabela("ICMS_CDIFERENCIADO")] public decimal ICMS_CDIFERENCIADO { get; set; } [CampoTabela("ICMS_ST_DIFERENCIADO")] public decimal ICMS_ST_DIFERENCIADO { get; set; } [CampoTabela("ICMS_ST_CDIFERENCIADO")] public decimal ICMS_ST_CDIFERENCIADO { get; set; } [CampoTabela("ICMS_DIF")] public decimal ICMS_DIF { get; set; } [CampoTabela("ESTOQUE")] public decimal Estoque { get; set; } [CampoTabela("FINANCEIRO")] public decimal Financeiro { get; set; } [CampoTabela("IPI")] public decimal IPI { get; set; } public static readonly int IntegracaoNFCe = 1; public static readonly int IntegracaoNFe = 2; public IntegracaoFiscal() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForumPoster.Entity { public class Account { private string _Content; public string Content { get { if (string.IsNullOrEmpty(_Content)) { //_Content = new DataAccess().GetContent(); return ""; } return _Content; } set { _Content = value; } } public string Username { get; set; } public string Password { get; set; } private string _Address; public string Address { get { if (string.IsNullOrEmpty(_Address)) { _Address = ""; } return _Address; } set { _Address = value; } } public string Session { get; set; } } public enum AccountColumn { username, password, address, session } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Image_processing.Processing { public class BlackWhiteProcess : Process { public override void Draw(Bitmap bitmap, int delta) { return; } public override void Processing(Bitmap bitmap, int x, int y) { if (x >= bitmap.Width || y >= bitmap.Height) return; Color color = bitmap.GetPixel(x, y); int[] RGB = new int[] { color.R, color.G, color.B }; int s = (int)RGB.Average(); color = Color.FromArgb(s, s, s); bitmap.SetPixel(x, y, color); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Caliburn.Micro; using Frontend.Core.Logging; namespace Frontend.Core.Converting.Operations { public class OperationProcessor : DispatcherObject, IOperationProcessor { private readonly IEventAggregator eventAggregator; private readonly Dictionary<OperationResultState, Action<OperationResult, IOperationViewModel>> resultHandlershandle; public OperationProcessor(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; resultHandlershandle = new Dictionary<OperationResultState, Action<OperationResult, IOperationViewModel>> { {OperationResultState.Success, HandleSuccess}, {OperationResultState.Warning, HandleWarning}, {OperationResultState.Error, HandleErrors}, {OperationResultState.Canceled, HandleCancellation} }; } public Task<AggregateOperationsResult> ProcessQueue(IEnumerable<IOperationViewModel> operations, CancellationToken token) { foreach (var operation in operations) { // Check if previous previousOperation failed. var previousOperation = GetPreviousItem(operations, operation); if (token.IsCancellationRequested || !this.CanContinue(previousOperation)) { break; } operation.State = OperationState.InProgress; eventAggregator.PublishOnUIThread(new LogEntry(operation.Description, LogEntrySeverity.Info, LogEntrySource.UI)); var result = new OperationResult(); try { token.ThrowIfCancellationRequested(); result = operation.Process(); LogResultMessages(result); resultHandlershandle[result.State](result, operation); } catch (OperationCanceledException) { resultHandlershandle[OperationResultState.Canceled](result, operation); } catch (Exception e) { eventAggregator.PublishOnUIThread( new LogEntry(string.Format("Unhandled exception occurred: {0}", e.Message), LogEntrySeverity.Error, LogEntrySource.UI)); } } return Task.FromResult(CalculateResult(operations)); } private static IOperationViewModel GetPreviousItem(IEnumerable<IOperationViewModel> operations, IOperationViewModel currentOperation) { // Todo: Redo this as extension method? var currentIndex = operations.ToList().IndexOf(currentOperation); var previousOperation = operations.ElementAt(currentIndex == 0 ? currentIndex : currentIndex - 1); return previousOperation; } private bool CanContinue(IOperationViewModel previousOperation) { var statesToContinueFrom = new List<OperationState>() { OperationState.CompleteWithWarnings, OperationState.Success, OperationState.NotStarted }; return statesToContinueFrom.Contains(previousOperation.State); } private AggregateOperationsResult CalculateResult(IEnumerable<IOperationViewModel> operations) { var operationStates = from operation in operations select operation.State; if (operationStates.Contains(OperationState.Failed)) { return AggregateOperationsResult.Failed; } if (operationStates.Contains(OperationState.Cancelled)) { return AggregateOperationsResult.Canceled; } return AggregateOperationsResult.CompletedSuccessfully; } private void HandleCancellation(OperationResult result, IOperationViewModel operation) { eventAggregator.PublishOnUIThread( new LogEntry(string.Format("Operation {0} canceled.", operation.Description), LogEntrySeverity.Warning, LogEntrySource.UI)); } private void HandleSuccess(OperationResult result, IOperationViewModel operation) { operation.State = OperationState.Success; eventAggregator.PublishOnUIThread( new LogEntry(string.Format("{0} completed successfully.", operation.Description), LogEntrySeverity.Info, LogEntrySource.UI)); } private void HandleWarning(OperationResult result, IOperationViewModel operation) { operation.State = OperationState.CompleteWithWarnings; eventAggregator.PublishOnUIThread( new LogEntry(string.Format("{0} completed with warnings!", operation.Description), LogEntrySeverity.Warning, LogEntrySource.UI)); } private void HandleErrors(OperationResult result, IOperationViewModel operation) { operation.State = OperationState.Failed; eventAggregator.PublishOnUIThread(new LogEntry(string.Format("{0} failed!", operation.Description), LogEntrySeverity.Error, LogEntrySource.UI)); } private void LogResultMessages(OperationResult result) { const int maxEntriesToShow = 1500; if (result.LogEntries.Count <= maxEntriesToShow) { this.PublishLogEntries(result.LogEntries); } else { var lastEntries = result.LogEntries.AsEnumerable<LogEntry>().Skip(Math.Max(0, result.LogEntries.Count - maxEntriesToShow)); this.PublishLogEntries(lastEntries); eventAggregator.PublishOnUIThread(new LogEntry("The converter returned " + result.LogEntries.Count + " lines.", LogEntrySeverity.Warning, LogEntrySource.UI)); eventAggregator.PublishOnUIThread(new LogEntry("Only showing the last " + maxEntriesToShow, LogEntrySeverity.Warning, LogEntrySource.UI)); } } private void PublishLogEntries(IEnumerable<LogEntry> logEntries) { foreach (var logEntry in logEntries) { eventAggregator.PublishOnUIThread(logEntry); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Threading; using KT.Logger.ObserverPattern; namespace KT.Logger { internal class Queue : Subject { private static ConcurrentQueue<Entry> _queue; private static bool _queueIsWrited; internal void Init() { _queue = new ConcurrentQueue<Entry>(); } internal void AddEntry(Entry ent) { _queue.Enqueue(ent); Notify(); } private void Notify() { if (_queue.Count >= QueueCapacity && !_queueIsWrited) { (new Thread(FreeQueue)).Start(); } } private void FreeQueue() { _queueIsWrited = true; var entries = new List<Entry>(); for (int i = 0; i < QueueCapacity; i++) { Entry ent; if (_queue.TryDequeue(out ent)) { entries.Add(ent); } } Notify(entries); _queueIsWrited = false; } private static int? _queueCapacity; public static int QueueCapacity { get { if (_queueCapacity == null) { _queueCapacity = Convert.ToInt32(ConfigurationManager.AppSettings["_queueCapacity"]); } return _queueCapacity.Value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace SME.NET.Controllers { [Route("[controller]")] public class HealthController : Controller { public IActionResult Index() { return View(); } [HttpGet] public string checkHealth() { return "healthy"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; namespace Service { public class MapServiceStartTraversingFromOceans : AMapServiceTemplate { //mapServiceDFS, BFS and DFSTurnStackUpsideDown are slow they have O(n^2) complexity. //so let's try doing it bettr. We will start traversing from oceans with opposite condition - water can flow only to higher fields. //The set of sources is the intersec of both sets. //In this case it doesn't matter that we will use DFS or BFS for traverse. public MapServiceStartTraversingFromOceans(IMap map):base(map){} protected override bool CheckFlowBetweenCells(IMapCell from, IMapCell to) { return to.Heigh >= from.Heigh; } public override IServiceResult FindAllRiverSourcesWhichFlowToBothOceans() { IEnumerable<IMapCell> cellsReachablefromPacific=GetAllReachableCells(_map.GetCell(0, 0)); IEnumerable<IMapCell> cellsReachablefromAtlantic=GetAllReachableCells(_map.GetCell(_map.SizeY - 1, _map.SizeX - 1)); return new ServiceResult(cellsReachablefromPacific.Intersect(cellsReachablefromAtlantic),cellsReachablefromPacific.Count()+cellsReachablefromAtlantic.Count()); } private IEnumerable<IMapCell> GetAllReachableCells(IMapCell fromCell) { Queue<IMapCell> q = new Queue<IMapCell>(); ICollection<IMapCell> visitedCells = new HashSet<IMapCell>(); IMapCell cell = fromCell; q.Enqueue(cell); while (q.Count > 0) { visitedCells.Add(cell); IEnumerable<IMapCell> possibleNeighbours = GetPossibleNeighbours(cell, visitedCells); possibleNeighbours.ToList().ForEach(pn => q.Enqueue(pn)); cell = q.Dequeue(); } return visitedCells; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using VocabularyApi.Models; namespace VocabularyApi.Dtos.Training { public class QuestionWithOptionsDto : QuestionDto { public QuestionWithOptionsDto(UserVocabularyWordDto userWord, int number, List<string> options) : base(userWord, number) { Options = options; } public List<string> Options { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using K_Systems.Data.Core.Domain; namespace K_Systems.Data.Core.Repositories { public interface ICourseRepository : IRepository<Course> { IEnumerable<Course> GetByName(string search, int items, string sortBy, string order, int page, out int totalPages); object GetNames(string term); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using nguoiduado.Models; using DevExpress.Web.Mvc; namespace nguoiduado.Controllers { public class DanhMucDiaPhuongController : Controller { public ActionResult Index() { // DXCOMMENT: Pass a data model for GridView return View(); } nguoiduado.Models.nguoiduado_dbEntities db = new nguoiduado.Models.nguoiduado_dbEntities(); [ValidateInput(false)] public ActionResult GridView2Partial() { var model = db.TBL_DiaPhuong; return PartialView("_GridView2Partial", model.ToList()); } [HttpPost, ValidateInput(false)] public ActionResult GridView2PartialAddNew(nguoiduado.Models.TBL_DiaPhuong item) { var model = db.TBL_DiaPhuong; if (ModelState.IsValid) { try { model.Add(item); db.SaveChanges(); } catch (Exception e) { ViewData["EditError"] = e.Message; } } else ViewData["EditError"] = "Please, correct all errors."; return PartialView("_GridView2Partial", model.ToList()); } [HttpPost, ValidateInput(false)] public ActionResult GridView2PartialUpdate(nguoiduado.Models.TBL_DiaPhuong item) { var model = db.TBL_DiaPhuong; if (ModelState.IsValid) { try { var modelItem = model.FirstOrDefault(it => it.MaDiaPhuong == item.MaDiaPhuong); if (modelItem != null) { this.UpdateModel(modelItem); db.SaveChanges(); } } catch (Exception e) { ViewData["EditError"] = e.Message; } } else ViewData["EditError"] = "Please, correct all errors."; return PartialView("_GridView2Partial", model.ToList()); } [HttpPost, ValidateInput(false)] public ActionResult GridView2PartialDelete(System.Decimal MaDiaPhuong) { var model = db.TBL_DiaPhuong; if (MaDiaPhuong != null) { try { var item = model.FirstOrDefault(it => it.MaDiaPhuong == MaDiaPhuong); if (item != null) model.Remove(item); db.SaveChanges(); } catch (Exception e) { ViewData["EditError"] = e.Message; } } return PartialView("_GridView2Partial", model.ToList()); } } }
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; namespace BPiaoBao.Web.SupplierManager.Controllers.Helpers { public class ImportExcel { /// <summary> /// Excel文档流是否有数据 /// </summary> /// <param name="excelFileStream">Excel文档流</param> /// <returns></returns> public static bool HasData(Stream excelFileStream) { return HasData(excelFileStream, 0); } /// <summary> /// Excel文档流是否有数据 /// </summary> /// <param name="excelFileStream">Excel文档流</param> /// <param name="sheetIndex">表索引号,如第一个表为0</param> /// <returns></returns> public static bool HasData(Stream excelFileStream, int sheetIndex) { using (excelFileStream) { IWorkbook workbook = new HSSFWorkbook(excelFileStream); if (workbook.NumberOfSheets > 0) { if (sheetIndex < workbook.NumberOfSheets) { ISheet sheet = workbook.GetSheetAt(sheetIndex); return sheet.PhysicalNumberOfRows > 0; } } } return false; } private static string GetCellValue(ICell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.BLANK: return string.Empty; case CellType.BOOLEAN: return cell.BooleanCellValue.ToString(); case CellType.ERROR: return cell.ErrorCellValue.ToString(); case CellType.FORMULA: try { HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook); e.EvaluateInCell(cell); return cell.ToString(); } catch { return cell.NumericCellValue.ToString(); } case CellType.STRING: return string.IsNullOrWhiteSpace(cell.StringCellValue) ? string.Empty : cell.StringCellValue.Trim(); case CellType.NUMERIC: if (DateUtil.IsCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值 return cell.DateCellValue.ToString(); } else { // 纯数字 return cell.NumericCellValue.ToString(); } case CellType.Unknown: default: return cell.ToString(); } } /// <summary> /// 写入到datatable /// </summary> /// <param name="excelFileStream"></param> /// <returns></returns> public static DataTable RenderFromExcel(Stream excelFileStream) { using (excelFileStream) { IWorkbook workbook = new HSSFWorkbook(excelFileStream); ISheet sheet = workbook.GetSheetAt(0); //excel数据表 DataTable table = new DataTable(); //标题行 IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; int rowCount = sheet.LastRowNum; //加入标题 for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue.Trim()); table.Columns.Add(column); } for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = table.NewRow(); if (row != null) { for (int j = 0; j < cellCount; j++) { // if (row.GetCell(j) != null) dataRow[j] = GetCellValue(row.GetCell(j)); } } table.Rows.Add(dataRow); } return table; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Theater { class DB_connection { public static string connectionString = @"Data Source=STASIAV570\SQLEXPRESS;Initial Catalog=DB_Theater;Integrated Security=True;Pooling=False"; public static string current_directory = Environment.CurrentDirectory + "\\"; } }
using System; using System.Diagnostics; namespace Rebus.Tests { public static class TestExtensions { public static void Times(this int count, Action action) { for (var counter = 0; counter < count; counter++) { action(); } } [DebuggerStepThrough] public static TimeSpan Milliseconds(this int seconds) { return TimeSpan.FromMilliseconds(seconds); } [DebuggerStepThrough] public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } [DebuggerStepThrough] public static TimeSpan Seconds(this double seconds) { return TimeSpan.FromSeconds(seconds); } [DebuggerStepThrough] public static TimeSpan ElapsedSince(this DateTime someTime, DateTime somePastTime) { return someTime - somePastTime; } } }
using UnityEngine; using System.Collections; public class MouseBagDropper : MonoBehaviour { private enum security_status_type { Clear, Alarmed, Error, Pending, Unscanned } private float lastbagdrop = 0; private float delay =0.1f; public float baglength = 28f; public float bagwidth = 16f; public float bagheight = 12f; public float bagalarmed = 10; public float bagerror = 5; public float bagpending = 5; public float bagclear = 80; private float dropheight = 0.1f; private float bag_static_friction = 0f;//0.1f; private float bag_dynamic_friction = 0f;//0.1f; private int multiply=0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey (KeyCode.B)){ multiply = 0; DropBag(); } if (Input.GetKey (KeyCode.N)){ multiply = 10; DropBag(); } } void DropBag(){ Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast (ray, out hit, 10000)) { //Debug.DrawLine (ray.origin, hit.point); if((Time.time - lastbagdrop) > delay) { lastbagdrop = Time.time; if(hit.collider.gameObject.name == "Conveyor Belt"||hit.collider.gameObject.name == "Conveyer Belt") { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.position = new Vector3(hit.point.x, hit.point.y + cube.transform.localScale.y/2 -0.001f+dropheight, hit.point.z); cube.transform.localScale = new Vector3 (bagwidth/12f, bagheight/12f, baglength/12f); cube.transform.rotation = hit.collider.gameObject.transform.rotation; cube.transform.Rotate(new Vector3(0,1,0),90f); cube.transform.Rotate(new Vector3(0,0,1),90f); //cube.transform.rotation = new Quaternion(1,1,1,1); //cube.transform.localRotation = new Quaternion(-hit.collider.gameObject.transform.rotation.y,hit.collider.gameObject.transform.rotation.z,-hit.collider.gameObject.transform.rotation.x,1); //cube.transform.rotation = hit.collider.gameObject.transform.rotation; //cube.transform.rota //cube.transform.rotation.SetFromToRotation(new Vector3(1,1,1),new Vector3(1,1,2)); cube.AddComponent<Rigidbody>(); // cube.rigidbody.constraints = RigidbodyConstraints.FreezePositionY; //if(constrainY) //{ // cube.rigidbody.constraints = RigidbodyConstraints.FreezePositionY; //} cube.GetComponent<Rigidbody>().angularDrag = Mathf.Infinity; //cube.rigidbody.mass = 10; cube.GetComponent<Collider>().material.dynamicFriction = bag_dynamic_friction; cube.GetComponent<Collider>().material.staticFriction = bag_static_friction; cube.gameObject.AddComponent<Bag>(); cube.gameObject.AddComponent<BagDrag>();//DragRigidbody>();BagDrag // Sets the IATA tag if(CommunicationMaster.IATA_tags.Count>0) { cube.gameObject.GetComponent<Bag>().setIATA(CommunicationMaster.IATA_tags[0].ToString());//CommunicationMaster.IATA_tags. .ElementAt(0); CommunicationMaster.IATA_tags.RemoveAt(0); } cube.name = cube.gameObject.GetComponent<Bag>().getIATA() + " "+Random.Range(0,10000).ToString(); /* float chosentype = Random.Range(0,bagalarmed+bagpending+bagerror+bagclear); if(chosentype <bagalarmed) { cube.gameObject.GetComponent<Bag>().security_status = (int)security_status_type.Alarmed; } else if(chosentype <bagalarmed+bagpending) { cube.gameObject.GetComponent<Bag>().security_status = (int)security_status_type.Pending; } else if(chosentype <bagalarmed+bagpending+bagerror) { cube.gameObject.GetComponent<Bag>().security_status = (int)security_status_type.Error; } else { cube.gameObject.GetComponent<Bag>().security_status = (int)security_status_type.Clear; } */ Debug.Log ("Dropped bag : " + hit.collider.gameObject.name); for(int i=0;i<multiply;i++) { Instantiate(cube); } } } } } }
using ISP._2_after; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ISP { public class BookStats { } public class Library { List<Book> _books = new List<Book>(); public List<Book> getBooks() { return _books; } public void addBook(Book book) { _books.Add(book); } } }
using System; using System.Collections.Generic; using System.Text; namespace Main.SimUDuck { class FlyWithWings : IFlyBehavior { public void fly() { Console.WriteLine(Constant.Fly); } } }
namespace bookstore.Models { public class OrderDetailRecord { public virtual int Id { get; set; } public virtual int OrderRecord_Id { get; set; } public virtual int BookId { get; set; } public virtual int Quantity { get; set; } public virtual decimal UnitPrice { get; set; } public virtual decimal VatRate { get; set; } public decimal UnitVat() { return UnitPrice * VatRate; } public decimal Vat() { return UnitVat() * Quantity; } public decimal SubTotal() { return UnitPrice * Quantity; } public decimal Total() { return SubTotal() + Vat(); } } }