text
stringlengths
13
6.01M
namespace MundoMascotaRosario.Migrations { using System; using System.Data.Entity.Migrations; public partial class correccionmenu : DbMigration { public override void Up() { AddColumn("dbo.Menu", "PadreId", c => c.Int(nullable: false)); DropColumn("dbo.Menu", "FatherId"); } public override void Down() { AddColumn("dbo.Menu", "FatherId", c => c.Int(nullable: false)); DropColumn("dbo.Menu", "PadreId"); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Docller.Core.Common; using Docller.Core.Models; using Microsoft.Practices.EnterpriseLibrary.Data; namespace Docller.Core.Repository.Mappers.StoredProcMappers { public class FileHistoryMapper : IResultSetMapper<FileHistory> { private readonly IRowMapper<File> _fileMapper; private readonly IRowMapper<FileVersion> _fileVersion; private readonly IRowMapper<Transmittal> _transmittaMapper; public FileHistoryMapper() { this._fileMapper = MapBuilder<File>.MapNoProperties() .MapByName(x=>x.FileId) .MapByName(x => x.FileName) .MapByName(x=>x.FileExtension) .Build(); this._fileVersion = MapBuilder<FileVersion>.MapNoProperties() .MapByName(x => x.FileName) .MapByName(x => x.Title) .MapByName(x => x.CreatedDate) .MapByName(x => x.RevisionNumber) .MapByName(x => x.Revision) .MapByName(x => x.VersionPath) .Map(x => x.Status).ToColumn("StatusText") .Map(x => x.CreatedBy) .WithFunc( record => new User() { FirstName = record.GetString(7), LastName = record.GetString(8) }) .MapByName(x => x.TransmittalId) .Map(x => x.Attachments).WithFunc(delegate(IDataRecord record) { if (!record.IsDBNull(10)) { return new List<FileAttachmentVersion>() { new FileAttachmentVersion() { FileName = record.GetString(10), FileExtension = record.GetString(11) } }; } return null; }) .Build(); _transmittaMapper = MapBuilder<Transmittal>.MapNoProperties() .MapByName(x => x.TransmittalId) .MapByName(x => x.TransmittalNumber) .MapByName(x => x.Subject) .MapByName(x => x.CreatedDate) .Map(x => x.TransmittalStatus) .WithFunc( r => new Status() { StatusText = r.GetNullableString(4) }) .Map(x => x.CreatedBy) .WithFunc( record => new User() {FirstName = record.GetString(5), LastName = record.GetString(6)}) .Build(); } public IEnumerable<FileHistory> MapSet(IDataReader reader) { FileHistory history = new FileHistory() ; using (reader) { if(reader.Read()) { history.File = _fileMapper.MapRow(reader); history.File.Versions = new List<FileVersion>(); } if (reader.NextResult()) { List<Transmittal> transmittals = new List<Transmittal>(); while (reader.Read()) { transmittals.Add(this._transmittaMapper.MapRow(reader)); } history.Transmittals = transmittals; } if (reader.NextResult()) { while (reader.Read()) { history.File.Versions.Add(_fileVersion.MapRow(reader)); } } } return new List<FileHistory>() {history}; } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace UPDServer { public struct Received { public IPEndPoint Sender; public string Message; } class Program { static Player p1 = new Player(""); //Add parameters later static Universe universe = new Universe(); static void Main(string[] args) { //create a new server var server = new UdpListener(); //create universe Random rnd = new Random(); Dictionary<string, IPEndPoint> connections = new Dictionary<string, IPEndPoint>(); Dictionary<string, Player> players = new Dictionary<string, Player>(); // List<Weapons> rounds = new List<Weapons>(); bool sectorChanged = false; Console.WriteLine("============================================= Server"); string[] parts; //start listening for messages and copy the messages back to the client Task.Factory.StartNew(async () => { while (true) { var received = await server.Receive(); string msg = received.Message.ToString(); parts = msg.Split(':'); fixParts(parts); Console.WriteLine(msg + " -- " + received.Sender.Address.MapToIPv4().ToString()); // Only add new connections to the list of clients if (!connections.ContainsKey(received.Sender.Address.MapToIPv4().ToString())) { connections.Add(received.Sender.Address.MapToIPv4().ToString(), received.Sender); p1 = new Player(""); //add parameters later p1.Sector = rnd.Next(0, 255); p1.Column = rnd.Next(0, 9); p1.Row = rnd.Next(0, 9); p1.Name = Environment.UserName; players.Add(received.Sender.Address.MapToIPv4().ToString(), p1); p1.SectorStr = numToSectorID(p1.Sector); p1.Connection = received.Sender; server.Reply(String.Format("connected:true:{0}:{1}:{2}", p1.SectorStr, p1.Column, p1.Row), received.Sender); Galaxy sector = universe.getGalaxy(p1.SectorStr); sector.updatePlayer(p1.Name, (p1.Row*10+p1.Column%10)); server.Reply(String.Format("si:{0}:{1}:{2}:{3}", sector.StarLocations, sector.PlanetLocations, sector.BlackholeLocations, sector.getPlayersLocs()), received.Sender); universe.updateWeps(); } string ret = "[Connected Users]"; if (received.Message.Equals("list")) { foreach (string s in connections.Keys) ret += "\n>> " + s; server.Reply(ret + "\n*****************", received.Sender); } else { //Okay, send message to everyone // foreach (IPEndPoint ep in connections.Values) // server.Reply("[" + received.Sender.Address.ToString() + "] says: " + received.Message, ep); } if (received.Message == "quit") { connections.Remove(received.Sender.Address.ToString()); // Remove the IP Address from the list of connections } else { foreach (Player player in players.Values) { Galaxy playersSector = universe.getGalaxy(player.SectorStr); server.Reply(String.Format("ni:{0}:{1}:{2}", playersSector.PlanetLocations, playersSector.getPlayersLocs(), playersSector.getWeaponLocations()), player.Connection); } Player p; players.TryGetValue(received.Sender.Address.MapToIPv4().ToString(), out p); // set clients health fuel phasors torpedos and sheilds server.Reply(String.Format("setup:{0}:{1}:{2}:{3}:{4}", p.Health, p.FuelPods, p.Phasors, p.Torpedoes, p.shields), received.Sender); /* for (int i = 0; i < universe.getGalaxy(p.SectorStr).getWeaponCount(); i++) { //universe.updateWeps(); universe.getGalaxy(p.SectorStr).moveBullet(); }*/ if (p.IsAlive == true) { if (parts[0].Equals("mov")) { if (p.FuelPods != 0) { p.FuelPods--; server.Reply(String.Format("update:fuelpods:{0}", p.FuelPods), received.Sender); if (parts[1].Equals("n")) p.Row--; else if (parts[1].Equals("s")) p.Row++; else if (parts[1].Equals("e")) p.Column++; else if (parts[1].Equals("w")) p.Column--; Galaxy sector = universe.getGalaxy(p.SectorStr); //Checks for moving to different sector if (p.Row == -1) { p.Sector -= 16; p.SectorStr = numToSectorID(p.Sector); p.Row = 9; sectorChanged = true; Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); } else if (p.Row == 10) { p.Sector += 16; p.SectorStr = numToSectorID(p.Sector); p.Row = 0; sectorChanged = true; Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); } else if (p.Column == -1) { p.Sector--; p.SectorStr = numToSectorID(p.Sector); p.Column = 9; sectorChanged = true; Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); } else if (p.Column == 10) { p.Sector++; p.SectorStr = numToSectorID(p.Sector); p.Column = 0; sectorChanged = true; Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); } if (!sectorChanged) { // sector is of type Galaxy sector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); server.Reply(String.Format("ni:{0}:{1}:{2}", sector.PlanetLocations, sector.getPlayersLocs(), sector.getWeaponLocations()), received.Sender); } server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.SectorStr, p.Column, p.Row, parts[1], p.FuelPods), received.Sender); Char cellAction = onSpecialCell(p); sector = universe.getGalaxy(p.SectorStr); switch (cellAction) { case 's': //Player is on a star p.Health = 0; p.IsAlive = false; server.Reply(String.Format("update:health:{0}", p.Health), received.Sender); server.Reply("dead:", received.Sender); break; case 'p'://Player is on a planet p.Health = 100; p.shields = 15; p.Phasors = 50; p.Torpedoes = 10; p.FuelPods = 50; server.Reply(String.Format("update:health:{0}", p.Health), received.Sender); server.Reply(String.Format("update:shields:{0}", p.shields), received.Sender); server.Reply(String.Format("update:phasors:{0}", p.Phasors), received.Sender); server.Reply(String.Format("update:torpedos:{0}", p.Torpedoes), received.Sender); server.Reply(String.Format("update:fuelpods:{0}", p.FuelPods), received.Sender); server.Reply("You landed on a Planet", received.Sender); sector.removePlanet(p.Row * 10 + p.Column % 10); break; case 't': //Player found treasure Random r = new Random(); int x = r.Next(0, 5); if (x == 0) // health regeneration { p.Health = 100; server.Reply("you Regenerated Health", received.Sender); server.Reply(String.Format("update:health:{0}", p.Health), received.Sender); } else if (x == 1) // shields regenerated { p.shields = 15; server.Reply("you Found Shields", received.Sender); server.Reply(String.Format("update:shields:{0}", p.shields), received.Sender); } else if (x == 2) // more phasor ammo { p.Phasors = 50; server.Reply("you found more Phasor Ammo", received.Sender); server.Reply(String.Format("update:phasors:{0}", p.Phasors), received.Sender); } else if (x == 3) // torpedos replenished { p.Health = 10; server.Reply("you Found torpedo ammo", received.Sender); server.Reply(String.Format("update:torpedo:{0}", p.Torpedoes), received.Sender); } else if (x == 4) // fuelpods refilled { p.FuelPods = 50; server.Reply("you Found Fuelpods", received.Sender); server.Reply(String.Format("update:fuel:{0}", p.FuelPods), received.Sender); } break; case 'b': sector = universe.getGalaxy(p.SectorStr); p.Sector = rnd.Next(0, 255); p.SectorStr = numToSectorID(p.Sector); p.Column = rnd.Next(0, 9); p.Row = rnd.Next(0, 9); Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.SectorStr, p.Column, p.Row, p.Oriantation, p.FuelPods), received.Sender); server.Reply("you went through a blackhole", received.Sender); sectorChanged = true; break; } } else { server.Reply("Out of fuel!", received.Sender); server.Reply(String.Format("update:fuelpods:{0}", p.FuelPods), received.Sender); //server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.SectorStr, p.Column, p.Row, parts[1], p.FuelPods), received.Sender); } } else if (parts[0].Equals("q")) { if (parts[1].Equals("p")) server.Reply("Phasors equipped!", received.Sender); else server.Reply("Torpedos equipped!", received.Sender); } else if (parts[0].Equals("damage")) { int damage = 0; Int32.TryParse(parts[1], out damage); p.Health -= damage; } else if (parts[0].Equals("r")) { if (parts[1].Equals("n")) { p.Oriantation = 'n'; server.Reply(String.Format("or:{0}", parts[1]), received.Sender); } else if (parts[1].Equals("s")) { p.Oriantation = 's'; server.Reply(String.Format("or:{0}", parts[1]), received.Sender); } else if (parts[1].Equals("e")) { p.Oriantation = 'e'; server.Reply(String.Format("or:{0}", parts[1]), received.Sender); } else if (parts[1].Equals("w")) { p.Oriantation = 'w'; server.Reply(String.Format("or:{0}", parts[1]), received.Sender); } } else if (parts[0].Equals("s")) { if (parts[1].Equals("2")) { server.Reply("Out of Sheilds", received.Sender); } else if (parts[1].Equals("1")) { if (p.shields > 0) { p.shields--; server.Reply(String.Format("update:shields:{0}", p.shields), received.Sender); p.ShieldOn = true; server.Reply(String.Format("sh:{0}", parts[1]), received.Sender); } else { server.Reply("Out of Shields", received.Sender); server.Reply(String.Format("sh:{0}", 2), received.Sender); } } else if (parts[1].Equals("0")) { p.ShieldOn = false; server.Reply(String.Format("sh:{0}", parts[1]), received.Sender); } } else if (parts[0].Equals("v")) { string rply = "unv:"; char sec = 'a'; while (sec != 'q') { for (int i = 0; i < 16; i++) { rply += universe.getGalaxy(sec + "" + i).getPlayerCount() + ":"; } sec++; } server.Reply(rply, received.Sender); } else if (parts[0].Equals("f")) { if (parts[1].Equals("p")) { //Add code for handelig shooting phasors if (p.Phasors != 0 && p.ShieldOn == false) { //server.Reply(String.Format("sh:{0}", parts[1]), received.Sender); Galaxy sector = universe.getGalaxy(p.SectorStr); sector.addWeapon('p', p.Column, p.Row, p.Oriantation, p.SectorStr); // rounds.Add(new Weapons('p', p.Column, p.Row, p.Oriantation, p.SectorStr)); p.Phasors--; server.Reply(String.Format("update:weaponAngle:{0}", p.Oriantation), received.Sender); server.Reply(String.Format("update:weaponLoc:{0}:{1}", p.Column, p.Row), received.Sender); server.Reply(String.Format("update:phasors:{0}", p.Phasors), received.Sender); server.Reply(String.Format("ni:{0}:{1}:{2}", sector.PlanetLocations, sector.getPlayersLocs(), sector.getWeaponLocations()), received.Sender); } else if (p.ShieldOn == true) { server.Reply("Can't shoot with shields on", received.Sender); } else { server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.Sector, p.Column, p.Row, parts[1], p.Phasors), received.Sender); server.Reply(String.Format("Out of Phasors"), received.Sender); } } else if (parts[1].Equals("t")) { //Add code for handeling shooting torpedo if (p.Torpedoes > 0 && p.ShieldOn == false) { Galaxy sector = universe.getGalaxy(p.SectorStr); sector.addWeapon('t', p.Column, p.Row, p.Oriantation, p.SectorStr); p.Torpedoes--; server.Reply(String.Format("update:torpedos:{0}", p.Torpedoes), received.Sender); server.Reply(String.Format("ni:{0}:{1}:{2}", sector.PlanetLocations, sector.getPlayersLocs(), sector.getWeaponLocations()), received.Sender); } else if(p.ShieldOn == true) { server.Reply("Can't shoot with shields on", received.Sender); } else { server.Reply("Out of Torpedos!", received.Sender); server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.Sector, p.Column, p.Row, parts[1], p.Torpedoes), received.Sender); } server.Reply(String.Format("sh:{0}", parts[1]), received.Sender); } } else if (parts[0].Equals("h")) { if (p.FuelPods >= 5) { Galaxy sector = universe.getGalaxy(p.SectorStr); p.Sector = rnd.Next(0, 255); p.SectorStr = numToSectorID(p.Sector); p.Column = rnd.Next(0, 9); p.Row = rnd.Next(0, 9); p.FuelPods -= 5; server.Reply(String.Format("update:fuelpods:{0}", p.FuelPods), received.Sender); Galaxy newSector = universe.getGalaxy(p.SectorStr); sector.removePlayer(p.Name); newSector.updatePlayer(p.Name, (p.Row * 10 + p.Column % 10)); server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.SectorStr, p.Column, p.Row, p.Oriantation, p.FuelPods), received.Sender); sectorChanged = true; } else { server.Reply("Not enough fuel", received.Sender); server.Reply(String.Format("loc:{0}:{1}:{2}:{3}:{4}", p.Sector, p.Column, p.Row, p.Oriantation, p.FuelPods), received.Sender); } } if (sectorChanged) { p.SectorStr = numToSectorID(p.Sector); Galaxy sector = universe.getGalaxy(p.SectorStr); server.Reply(String.Format("si:{0}:{1}:{2}:{3}", sector.StarLocations, sector.PlanetLocations, sector.BlackholeLocations, sector.getPlayersLocs()), received.Sender); sectorChanged = false; } } else { server.Reply("You Are Dead!", received.Sender); } } } }); // Endless loop for user's to send messages to Client string read; do { read = Console.ReadLine(); foreach (IPEndPoint ep in connections.Values) server.Reply(read, ep); } while (read != "quit"); } private static void fixParts(string[] parts) { for (int i = 0; i < parts.Length; i++) parts[i] = parts[i].Trim().ToLower(); } private static string numToSectorID(int x) { Char col = (Char)((x % 16) + 97); return col.ToString() + (x / 16).ToString(); } private static Char onSpecialCell(Player p) { Galaxy sector = universe.getGalaxy(p.SectorStr); int playerCell = (p.Row * 10) + (p.Column % 10); return sector.GetCell(playerCell); } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OnlineQuiz.Models; using System; using System.Collections.Generic; using System.Linq; namespace OnlineQuiz.Controllers { [ApiController] [Route("api/[controller]")] public class QuestionController : ControllerBase { private readonly ILogger<QuestionController> _logger; private readonly CoreDbContext _context; public QuestionController(ILogger<QuestionController> logger, CoreDbContext context) { _context = context; _logger = logger; } [HttpGet] public IEnumerable<Question> GetAll() { try { return _context.Question.ToList(); } catch (System.Exception) { throw; } } [HttpPost] public JsonResult Post([FromBody] Question question) { try { question.Active = true; question.CreatedBy = ""; // need to add username question.CreatedDate = DateTime.Now; _context.Question.Add(question); _context.SaveChanges(); return new JsonResult("Question Added Successfully"); } catch (Exception) { throw; } } public JsonResult Put([FromBody] Question questionNew) { try { var questionOld = _context.Question.FirstOrDefault(x => x.QuestionId == questionNew.QuestionId); if (questionOld != null) { questionOld.Question1 = questionNew.Question1; questionOld.Option1 = questionNew.Option1; questionOld.Option2 = questionNew.Option2; questionOld.Option3 = questionNew.Option3; questionOld.Option4 = questionNew.Option4; questionOld.Answer = questionNew.Answer; questionOld.Complexity = questionNew.Complexity; questionOld.Active = true; _context.Question.Update(questionOld); _context.SaveChanges(); return new JsonResult("Question Updated Successfully"); } return new JsonResult("Please enter valid id"); } catch (Exception) { throw; } } [HttpDelete("{id}")] public JsonResult Delete(int id) { try { var question = _context.Question.FirstOrDefault(x => x.QuestionId == id); if (question != null) { _context.Question.Remove(question); _context.SaveChanges(); return new JsonResult("Question Deleted Successfully"); } return new JsonResult("Please enter valid id"); } catch (Exception) { throw; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; public class PlaneDetectionController : MonoBehaviour { public ARPlaneManager arPlaneManager; void Start() { DelegatesHandler.GameStart += DisableAllPlanes; } void DisableAllPlanes() { foreach (var plane in arPlaneManager.trackables) plane.gameObject.SetActive(false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Password { class Program { static void Main(string[] args) { string password = Console.ReadLine(); int lowerCaseCount = 0; int upperCaseCount = 0; int digitsCount = 0; for (int i = 0; i < password.Length; i++) { if (password[i] >= 'A' && password[i] <= 'Z') { upperCaseCount++; } else if (password[i] >= 'a' && password[i] <= 'z') { lowerCaseCount++; } else if (password[i] >= '1' && password[i] <= '9') { digitsCount++; } } if (lowerCaseCount > 0 && upperCaseCount > 0 && digitsCount > 0 && password.Length >= 8) { Console.WriteLine("YES"); Console.WriteLine("{0} {1}", lowerCaseCount, upperCaseCount); } else { Console.WriteLine("NO"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace NSTOX.BODataProcessor.Model { [Serializable] public class SalesTransactionDetailItem { public long ItemID { get; set; } public int MerchandiseHierarchy { get; set; } public double Quantity { get; set; } public double UnitSalesPrice { get; set; } public double UnitCostPrice { get; set; } public double ExtendedAmount { get; set; } public double TaxAmount { get; set; } [XmlIgnore] public double ExtendedCost { get { return Quantity * UnitCostPrice; } } [XmlIgnore] public double SellMargin { get { return UnitSalesPrice == 0 ? 0 : (UnitSalesPrice - UnitCostPrice) / UnitSalesPrice; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class page : MonoBehaviour { public Sprite page2; public bool next; void Start() { } // Update is called once per frame void Update() { if (next == true) { this.GetComponent<SpriteRenderer>().sprite = page2; } } }
using System; namespace PatronBridge { public abstract class Expendedora { //Abstracion que encapsula la interfaz IBebida protected IBebida Bebida; protected Expendedora(IBebida bebida) { this.Bebida = bebida; } public string mostrarAdvertencia() { return Bebida.MostrarAdvertencia(); } public abstract string mostrarDatosExp(); } }
using DAL.Basics; using DAL.RawMaterial; using DAL.Stock; using Model; using Model.Basics; using Model.RawMaterial; using Model.Stock; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; using Comp; using Model.APIModels.Result; using Model.APIModels.Parameter; namespace CateringWebAPI.Controllers { public class StockController : ApiController { D_Indblog dIndblog = new D_Indblog(); //数据推送日志 D_InDbInfo dInDbInfo = new D_InDbInfo(); //入库记录 D_Balance dBalance = new D_Balance(); //库存结余 D_ClassInfo dClassInfo = new D_ClassInfo(); //班组管理 D_RawMaterialArea dRawMaterialArea = new D_RawMaterialArea();//原料品号 D_RawMaterial dRawMaterial = new D_RawMaterial();//原料数据 D_Units dUnits = new D_Units();//入库单位 D_RawMaterialUnit dRawMaterialUnit = new D_RawMaterialUnit();//原料品号规格单位 private bool IsV(List<E_Indblog> list, out string msg) { //数据验证 foreach (var item in list) { //验证品号 E_RawMaterialArea eRawMaterialArea = dRawMaterialArea.GetList(new E_RawMaterialArea() { indbid = item.materialcode }).FirstOrDefault(); if (eRawMaterialArea == null) { msg = $"品号:{item.materialcode}不存在"; return false; } item.rawid = eRawMaterialArea.rawid;//对应的原料ID赋值 //验证班组 E_ClassInfo eClassInfo = dClassInfo.GetList(new E_ClassInfo() { CName = item.customername }).FirstOrDefault(); if (eClassInfo == null) { msg = $"班组:{item.customername}不存在"; return false; } //验证入库记录单位名称对应的单位ID E_Units eUnits = dUnits.GetList(new E_Units() { uname = item.minunit.ToLower() }).FirstOrDefault(); if (eUnits == null) { msg = $"不存在该入库单位:{item.minunit.ToLower()}"; return false; } List<E_RawMaterialUnit> RawMaterialUnitList = dRawMaterialUnit.GetList(new E_RawMaterialUnit() { rawareaid = eRawMaterialArea.id }); E_RawMaterialUnit indbunit = RawMaterialUnitList.Where(p => p.unitid == eUnits.id).FirstOrDefault(); if (indbunit == null) { msg = $"入库单位在原料规格单位中未找到(原料ID:{eRawMaterialArea.id} 品号:{item.materialcode} 单位名称:{eUnits.uname} 单位对应标识:{eUnits.id})!"; return false; } //获取原料数据 E_RawMaterial eRawMaterial = dRawMaterial.GetRawMaterial(item.rawid); E_RawMaterialUnit rawunit = RawMaterialUnitList.Where(p => p.unitid == eRawMaterial.indbunitid).FirstOrDefault(); if (rawunit == null) { msg = $"原料入库单位在品号规格单位中不存在(原料ID:{eRawMaterial.id} 原料名称:{eRawMaterial.RAWName}品号:{item.materialcode} 单位名称:{eUnits.uname} 单位对应标识:{eRawMaterial.indbunitid}),请联系餐理臣系统管理员进行修复!"; return false; } } msg = ""; return true; } /// <summary> /// 同步销货单 /// </summary> /// <param name="model"></param> /// <returns></returns> public E_SaleOutResult SyncSalesBill(E_Indblog model) { E_SaleOutResult response = new E_SaleOutResult(); string msg = ""; //获取对应品号 E_RawMaterialArea eRawMaterialArea = dRawMaterialArea.GetList(new E_RawMaterialArea() { indbid = model.materialcode }).FirstOrDefault(); if (eRawMaterialArea == null) { response.code = 4; response.msg = $"品号:{model.materialcode}不存在"; return response; } model.rawid = eRawMaterialArea.rawid; //插入入库数据 E_InDbInfo eInDbInfo = this.AddInDbInfo(model, out msg); if (eInDbInfo == null) { response.code = 4; response.msg = msg; return response; } eInDbInfo.rawareaid = eRawMaterialArea.id; //更新库存结余 bool result = this.UpBalance(eInDbInfo, out msg); if (!result) { response.code = 4; response.msg = msg; return response; } //插入数据推送日志 dIndblog.Add(model); return response; } /// <summary> /// 销货单导入,入库记录 /// </summary> /// <param name="value"></param> [Route("stock/impindb")] [HttpPost,HttpGet] public IHttpActionResult ImpinDB() { //var str = HttpContext.Current.Request["paramstr"]; //HttpContext.Current.Response.Write(str); //HttpContext.Current.Response.End(); //return Ok(); E_SaleOutResult response = new E_SaleOutResult(); var paramstr = HttpContext.Current.Request["paramstr"]; if (paramstr == null) { response.msg = "参数:paramstr 不能为空!"; response.code = 3; return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } E_Indblog model = JsonConvert.DeserializeObject<E_Indblog>(paramstr); //初始化处理数据 List<E_Indblog> list = model.jksaleoutdetaillist; foreach (var item in list) { item.customercode = model.customercode; item.customername = model.customername; item.kdordernum = model.kdordernum; item.orderdate = model.orderdate; item.ordernum = model.ordernum; item.saleoutid = model.saleoutid; } //全局校验 string msg = ""; if (!IsV(list, out msg)) { response.msg = msg; response.code = 4; return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } //同步销货单 foreach (var item in list) { response = SyncSalesBill(item); if (response.code == 4) { return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } } return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } /// <summary> /// 同步销货单 /// </summary> /// <returns></returns> [Route("stock/syncimpindb")] [HttpPost] public IHttpActionResult SyncIndlog([FromBody] E_getSaleOutList model) { var url = System.Configuration.ConfigurationSettings.AppSettings["GetSaleOutList"].ToString(); var data = $"beginDate={(model.beginDate != null ? model.beginDate.ToString() : "")}&endDate={(model.endDate != null ? model.endDate.ToString() : "")}&customerCode={model.customerCode}"; var result = HttpRequestUtls.Post(url, data); List<E_Indblog> list = JsonConvert.DeserializeObject<List<E_Indblog>>(result); E_SaleOutResult response = new E_SaleOutResult(); //全局校验 string msg = ""; if (!IsV(list, out msg)) { response.msg = msg; response.code = 4; return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } //同步销货单 foreach (var item in list) { response = SyncSalesBill(item); if (response.code == 4) { return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } } return Json(response, new JsonSerializerSettings() { }, Encoding.UTF8); } /// <summary> /// 构建入库记录 /// </summary> private E_InDbInfo AddInDbInfo(E_Indblog model, out string msg) { //构建 入库记录 msg = ""; E_InDbInfo eInDbInfo = new E_InDbInfo(); eInDbInfo.id = dInDbInfo.GetMaxId(); //获取对应班组 E_ClassInfo eClassInfo = dClassInfo.GetList(new E_ClassInfo() { CName = model.customername }).FirstOrDefault(); if (eClassInfo == null) { msg = $"班组:{model.customername}不存在"; return null; } eInDbInfo.GroupID = eClassInfo.AreaID; eInDbInfo.ClassID = eClassInfo.id; eInDbInfo.DBID = 1; eInDbInfo.RAWID = model.rawid; eInDbInfo.IntDate = DateTime.Now; eInDbInfo.PiaoDate = model.orderdate; eInDbInfo.RAW = model.materialname; eInDbInfo.Specifications = model.spec; eInDbInfo.AmountMoney = Convert.ToDouble(model.saleamount); eInDbInfo.Back = model.remark; eInDbInfo.InDBid = model.materialcode; //获取对应原料 E_RawMaterial eRawMaterial = dRawMaterial.GetRawMaterial(Convert.ToInt32(model.rawid)); eInDbInfo.RAWTID = eRawMaterial.typeid; eInDbInfo.RAWIDS = eRawMaterial.infotypeid; eInDbInfo.Number = model.quantity; eInDbInfo.CMP = model.minunit; eInDbInfo.Price = model.salePrice; eInDbInfo.isstatistics = 0; //计算总重量、总数量 //eInDbInfo.Weight = weight.ToString(); //eInDbInfo.SumNumber = weight * guige; dInDbInfo.Add(eInDbInfo); return eInDbInfo; } /// <summary> /// 更新库存结余 /// </summary> private bool UpBalance(E_InDbInfo eInDbInfo, out string msg) { bool result = true; msg = ""; /* 1、通过入库记录,查找对应单位ID; 2、通过品号,查找所有规格单位; 3、查找原料统一标准单位; 4、将入库记录的单位,换算成原料单位,重新计算入库数量 5、获取上一条该品号结余信息,并修改结余记录,重新计算库存量,以及库存结余单价 */ //品号对应的规格单位集合 List<E_RawMaterialUnit> RawMaterialUnitList = dRawMaterialUnit.GetList(new E_RawMaterialUnit() { rawareaid = eInDbInfo.rawareaid }); //入库记录单位名称对应的单位ID E_Units eUnits = dUnits.GetList(new E_Units() { uname = eInDbInfo.CMP.ToLower() }).FirstOrDefault(); if (eUnits == null) { msg = $"不存在该入库单位:{eInDbInfo.CMP.ToLower()}"; return false; } E_RawMaterialUnit indbunit = RawMaterialUnitList.Where(p => p.unitid == eUnits.id).FirstOrDefault(); if (indbunit == null) { msg = $"入库单位在原料规格单位中未找到!"; return false; } //获取原料数据 E_RawMaterial eRawMaterial = dRawMaterial.GetRawMaterial(eInDbInfo.RAWID); E_RawMaterialUnit rawunit = RawMaterialUnitList.Where(p => p.unitid == eRawMaterial.indbunitid).FirstOrDefault(); if (rawunit == null) { msg = $"原料入库单位在品号规格单位中不存在,请联系餐理臣系统管理员进行修复!"; return false; } //通过换算比例,计算实际入库量 double trueinnumber = Convert.ToDouble(eInDbInfo.Number) / Convert.ToDouble(indbunit.number) * Convert.ToDouble(rawunit.number); double trueprice = Convert.ToDouble(eInDbInfo.Number) * Convert.ToDouble(eInDbInfo.Price) / trueinnumber; E_Balance eBalance = new E_Balance(); eBalance.RawID = eInDbInfo.RAWID; eBalance.InDBId = eInDbInfo.InDBid; eBalance.ClassID = eInDbInfo.ClassID; eBalance.AddDate = DateTime.Now; eBalance.ChangeNumber = trueinnumber; eBalance.ChangePrice = trueprice; eBalance.ChangeType = 0; //0:入库 1:出库 eBalance.ChangeID = eInDbInfo.id; //获取上次该品号入库数据 E_Balance eOldBalance = dBalance.GetList(new E_Balance() { pagesize = 1, pageindex = 1, InDBId = eInDbInfo.InDBid }).FirstOrDefault(); if (eOldBalance != null) { eBalance.PrePrice = eOldBalance.Price; eBalance.PreBalance = eOldBalance.Balance; eBalance.Balance = trueinnumber + eOldBalance.Balance; eBalance.Price = (eOldBalance.Balance * eOldBalance.Price + trueinnumber * trueprice) / eBalance.Balance; } else { eBalance.PrePrice = trueprice; eBalance.PreBalance = 0; eBalance.Balance = trueinnumber; eBalance.Price = trueprice; } dBalance.Add(eBalance); return result; } [Route("stock/test")] [HttpGet, HttpPost] public IHttpActionResult Test() { var url = System.Configuration.ConfigurationManager.AppSettings["impindburl"].ToString(); E_Indblog eIndblog = new E_Indblog(); eIndblog.customercode = "1205"; eIndblog.customername = "QK18 - 1"; eIndblog.kdordernum = "KD201802054828"; eIndblog.orderdate = Convert.ToDateTime("2018-02-09"); eIndblog.ordernum = "XH201802092506"; eIndblog.saleoutid = "000294cd-ca16-41be-bd36-b5ba5592241a"; List<E_Indblog> list = new List<E_Indblog>(); list.Add(new E_Indblog() { materialcode = "", materialid = "59925529-8d4c-11e7-971f-00ffb9f6df09", materialname = "", minunit = "", orderquantity = "4.000000", quantity = "2.000000", remark = "", saleamount = "171.60", saleoutdetailid = "01a4a8ed-b12d-44a1-840a-fbf9c96e5c27", salePrice = "85.80", spec = "" }); list.Add(new E_Indblog() { materialcode = "", materialid = "59925529-8d4c-11e7-971f-00ffb9f6df09", materialname = "", minunit = "", orderquantity = "4.000000", quantity = "4.000000", remark = "", saleamount = "198.60", saleoutdetailid = "219bc2c2-9507-4853-9fc3-524efaf3eaf2", salePrice = "49.50", spec = "" }); list.Add(new E_Indblog() { materialcode = "", materialid = "59925529-8d4c-11e7-971f-00ffb9f6df09", materialname = "", minunit = "", orderquantity = "4.000000", quantity = "4.000000", remark = "", saleamount = "198.60", saleoutdetailid = "219bc2c2-9507-4853-9fc3-524efaf3eaf2", salePrice = "49.50", spec = "" }); eIndblog.jksaleoutdetaillist = list; var postData = $"paramstr={JsonConvert.SerializeObject(eIndblog)}"; HttpContext.Current.Response.Write(HttpRequestUtls.Post(url, postData)); HttpContext.Current.Response.End(); return Ok(); } } }
using CreamBell_DMS_WebApps.App_Code; using Elmah; using System; using System.Data; using System.Data.SqlClient; using System.Web; using System.Web.UI; namespace CreamBell_DMS_WebApps { public partial class Login : System.Web.UI.Page { SqlConnection conn = null; SqlCommand cmd = null; SqlDataReader RD; string DataAreaID = System.Configuration.ConfigurationManager.AppSettings["DataAreaId"].ToString(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { txtUserName.Focus(); Session[SessionKeys.MENU] = null; BtnLogin.Attributes.Add("onclick", "return ValidateLogin();"); Session.Clear(); } } // protected void BtnLogin_Click(object sender, EventArgs e) // { // //Response.Redirect("frmStockLocationTransfer.aspx"); // try // { // CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); // conn = obj.GetConnection(); // string query = "Select User_Code,User_Name,User_Password,State,User_Type,Site_Code from [ax].[ACXUSERMASTER] A where User_Code=@User_Code and User_Password = @User_Password and A.Site_Code=(select SITEID from AX.INVENTSITE where SITEID =A.Site_Code)"; // cmd = new SqlCommand(); // cmd.Connection = conn; // cmd.CommandTimeout = 0; // cmd.CommandType = CommandType.Text; // cmd.CommandText = query; // cmd.Parameters.Add(new SqlParameter("@User_Code", txtUserName.Text.Trim())); // cmd.Parameters.Add(new SqlParameter("@User_Password", txtPassword.Text.Trim())); // RD = cmd.ExecuteReader(); // if (RD.HasRows == false) // { // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Login Failed !');", true); // txtPassword.Text = string.Empty; // txtUserName.Focus(); // } // else // { // RD.Read(); // Session["USERID"] = RD["User_Code"].ToString(); // Session["USERNAME"] = RD["User_Name"].ToString(); // Session["SITELOCATION"] = RD["State"].ToString(); // Session["LOGINTYPE"] = RD["User_Type"].ToString(); // Session["SiteCode"] = RD["Site_Code"].ToString(); // Session["DATAAREAID"] = DataAreaID; // RD.Close(); // UpdateLoginTime(); // try // { // Session["ISDISTRIBUTOR"] = "N"; // CreamBell_DMS_WebApps.App_Code.Global baseObj = new Global(); // string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'"; // object objcheckSitecode = baseObj.GetScalarValue(sqlstr); // if (objcheckSitecode == null) // { // Session["ISDISTRIBUTOR"] = "Y"; // } // } // catch // { } // //Response.Redirect("frmCustomerPartyMaster.aspx"); //// Response.Redirect("Home.aspx"); // Server.Transfer("Home.aspx",false); // //Response.Redirect("frmPurchaseInvoiceReceipt.aspx"); // //Response.Redirect("frmPurchaseReturn.aspx"); // //Response.Redirect("ReportSalesInvoice.aspx"); // } // if (RD.IsClosed == false) // { // RD.Close(); // } // if (conn.State == ConnectionState.Open) // { // conn.Close(); // conn.Dispose(); // } // } // catch (System.Data.SqlClient.SqlException sqlex) // { // if (sqlex.Message.ToString().IndexOf("The server was not found or was not accessible.") > 0) // { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('Connection not established with server. Please check the network connection.');", true); return; } // else // { // ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('" + sqlex.Message.ToString().Replace("'","''") + "');", true); return; // } // } // catch (Exception ex) // { // if (ex.Message.ToString().IndexOf("The timeout period elapsed prior to obtaining a connection from the pool.") > 0) // { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('Connection not established with server. Please check the network connection.');", true); return; } // else // { // ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('" + ex.Message.ToString().Replace("'", "''") + "');", true); return; // } // } // } private void UpdateLoginTime() { string dt = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss"); CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); string updateQuery = "Update [ax].[ACXUSERMASTER] Set LastLoginDatetime ='" + dt + "' where User_Code ='" + Session[SessionKeys.USERID].ToString() + "'"; obj.ExecuteCommand(updateQuery); } protected void BtnLogin_Click1(object sender, ImageClickEventArgs e) { //Response.Redirect("frmStockLocationTransfer.aspx"); try { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); conn = obj.GetConnection(); string query = "Acx_getUserCredentials"; //string query = "ACX_GetLoginDetails"; cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandTimeout = 0; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = query; cmd.Parameters.Add(new SqlParameter("@User_Code", txtUserName.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@User_Password", txtPassword.Text.Trim())); RD = cmd.ExecuteReader(); if (RD.HasRows == false) { this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Login Failed !');", true); txtPassword.Text = string.Empty; txtUserName.Focus(); } else { RD.Read(); Session[SessionKeys.USERID] = RD["User_Code"].ToString(); Session[SessionKeys.USERNAME] = RD["User_Name"].ToString(); Session[SessionKeys.NAME] = RD["NAME"].ToString(); Session[SessionKeys.SITEADDRESS] = RD["SITEADDRESS"].ToString(); Session[SessionKeys.SITELOCATION] = RD["State"].ToString(); Session[SessionKeys.STATECODE] = RD["STATECODE"].ToString(); Session[SessionKeys.SCHSTATE] = RD["SCHSTATE"].ToString(); Session[SessionKeys.UNIONTERRITORY] = RD["UNIONTERRITORY"].ToString(); Session[SessionKeys.SITEGSTINNO] = RD["GSTINNO"].ToString(); Session[SessionKeys.SITEGSTINREGDATE] = RD["GSTREGISTRATIONDATE"].ToString(); Session[SessionKeys.SITECOMPOSITIONSCHEME] = RD["COMPOSITIONSCHEME"]; Session[SessionKeys.LOGINTYPE] = RD["User_Type"].ToString(); Session[SessionKeys.SITECODE] = RD["Site_Code"].ToString(); Session[SessionKeys.DATAAREAID] = DataAreaID; RD.Close(); Global.strSessionID = HttpContext.Current.Session.SessionID; if (Convert.ToString(Session[SessionKeys.LOGINTYPE]) == "0") { string query1 = "select MainWarehouse from ax.inventsite where siteid='" + Session[SessionKeys.SITECODE].ToString() + "'"; string MainWarehouse = obj.GetScalarValue(query1); if (MainWarehouse.Trim().Length > 0) { Session[SessionKeys.TRANSLOCATION] = MainWarehouse; } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('Main Warehouse setup not defined.');", true); return; } } //UpdateLoginTime(); try { Session[SessionKeys.ISDISTRIBUTOR] = "N"; CreamBell_DMS_WebApps.App_Code.Global baseObj = new Global(); string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session[SessionKeys.SITECODE].ToString() + "'"; object objcheckSitecode = baseObj.GetScalarValue(sqlstr); if (objcheckSitecode == null) { Session[SessionKeys.ISDISTRIBUTOR] = "Y"; } // Pcs Billing Applicable Session["ApplicableOnState"] = "N"; sqlstr = "EXEC [dbo].[ACX_USP_PCSBillingApplicable] '" + Session[SessionKeys.SCHSTATE].ToString() + "',''"; objcheckSitecode = baseObj.GetScalarValue(sqlstr); if (objcheckSitecode == null) { Session[SessionKeys.APPLICABLEONSTATE] = "N";// objcheckSitecode.ToString(); } else { Session[SessionKeys.APPLICABLEONSTATE] = "Y"; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } //Response.Redirect("frmCustomerPartyMaster.aspx"); // Response.Redirect("Home.aspx"); // Server.Transfer("Home.aspx", false); Response.Redirect("frmDashboard.aspx", false); // HttpContext.Current.RewritePath("frmDashboard.aspx"); //Response.Redirect("~/frmDashboard.aspx", false); // HttpContext.Current.RewritePath("frmDashboard.aspx"); //Response.Redirect("frmPurchaseInvoiceReceipt.aspx"); //Response.Redirect("frmPurchaseReturn.aspx"); //Response.Redirect("ReportSalesInvoice.aspx"); } if (RD.IsClosed == false) { RD.Close(); } if (conn.State == ConnectionState.Open) { conn.Close(); conn.Dispose(); } } catch (System.Data.SqlClient.SqlException sqlex) { ErrorSignal.FromCurrentContext().Raise(sqlex); if (sqlex.Message.ToString().IndexOf("The server was not found or was not accessible.") > 0) { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('Connection not established with server. Please check the network connection.');", true); return; } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('" + sqlex.Message.ToString().Replace("'", "''") + "');", true); return; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); if (ex.Message.ToString().IndexOf("The timeout period elapsed prior to obtaining a connection from the pool.") > 0) { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('Connection not established with server. Please check the network connection.');", true); return; } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "Error", "alert('" + ex.Message.ToString().Replace("'", "''") + "');", true); return; } } } } }
using Grpc.Core; using GrpcServer.Models; using GrpcServer.Protos; using GrpcServer.Repository; using GrpcServer.Repository.DBModels; using Microsoft.AspNetCore.Authorization; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Threading.Tasks; namespace GrpcServer.Services { public class SalesService : sales.salesBase { private DBContext db; public IConfiguration Configuration { get; } private readonly ILogger<salesModel> _logger; List<salesModel> sales; salesModel lastSale = new salesModel(); public SalesService(ILogger<salesModel> logger, DBContext db, IConfiguration configuration) { this.db = db; sales = new List<salesModel>(); Configuration = configuration; _logger = logger; } private void streamON(object sender, SqlNotificationEventArgs e) { var connection = new SqlConnection(Configuration.GetConnectionString("grpcDBConn")); connection.Open(); using (SqlCommand command = new SqlCommand(@"Select [id] from [dbo].[sales] where id > @saleID", connection)) { command.Notification = null; command.Parameters.AddWithValue("@saleID", lastSale.saleID); SqlDependency dependency = new SqlDependency(command); SqlDataReader reader = command.ExecuteReader(); reader.Close(); dependency.OnChange += new OnChangeEventHandler((sender, e) => streamON(sender, e)); var queryEF = (from s in db.Sales join c in db.Customers on s.CustomerId equals c.Id join p in db.Products on s.ProductId equals p.Id where s.Id > lastSale.saleID select new { ID = s.Id, cName = c.Name, pName = p.Pname, Date = s.SaleDate, Price = p.Price }).ToList(); //while(await reader.ReadAsync()) foreach (var item in queryEF) { sales.Add(new salesModel { saleID = item.ID, customerName = item.cName, productName = item.pName, date = item.Date.ToString(), price = item.Price.ToString() }); } } } [Authorize] public override async Task getSalesInRealTime(Google.Protobuf.WellKnownTypes.Empty request, IServerStreamWriter<salesResponse> responseStream, ServerCallContext context) { SqlDependency.Start(Configuration.GetConnectionString("grpcDBConn")); var connection = new SqlConnection(Configuration.GetConnectionString("grpcDBConn")); connection.Open(); string query = @"Select [id] from [dbo].[sales]"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Notification = null; SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler((sender, e) => streamON(sender, e)); SqlDataReader reader = await command.ExecuteReaderAsync(); await reader.CloseAsync(); var queryEF = (from s in db.Sales join c in db.Customers on s.CustomerId equals c.Id join p in db.Products on s.ProductId equals p.Id select new { ID = s.Id, cName = c.Name, pName = p.Pname, Date = s.SaleDate, Price = p.Price }).ToList(); foreach(var item in queryEF) { sales.Add(new salesModel { saleID=item.ID, customerName = item.cName, productName = item.pName, date = item.Date.ToString(), price = item.Price.ToString() }); } try { while (true) { if (sales.Count > 0) { foreach (var item in sales.ToList()) { await responseStream.WriteAsync(new salesResponse { Customer = item.customerName, Product = item.productName, Price = item.price, Date = item.date}); } lastSale = sales.Where(x => x.saleID == sales.Max(x => x.saleID)).FirstOrDefault(); sales.Clear(); dependency.OnChange -= new OnChangeEventHandler((sender, e) => streamON(sender, e)); } await Task.Delay(3000); } } catch(Exception ex) { Console.WriteLine(ex.Message); } } } } }
using System.Diagnostics; using System.Windows; using System.Windows.Media; namespace BimPlusDemo.Controls { public class IntegerTextBox : CultureInfoTextBox { public IntegerTextBox() { TextAlignment = TextAlignment.Right; LostFocus += IntegerTextBox_LostFocus; GotFocus += IntegerTextBox_GotFocus; } ~IntegerTextBox() { LostFocus -= IntegerTextBox_LostFocus; GotFocus -= IntegerTextBox_GotFocus; Trace.WriteLine("destructor IntegerTextBox"); } private void IntegerTextBox_LostFocus(object sender, RoutedEventArgs e) { TextAlignment = TextAlignment.Right; if (!string.IsNullOrEmpty(Text)) { if (!int.TryParse(Text, out var value)) { Background = new SolidColorBrush { Color = Colors.Red }; return; } string valueString = value.ToString(); Text = ToText(value, true); if (int.TryParse(valueString, out var newValue)) IntValue = newValue; } else { Text = null; IntValue = null; } Background = null; } private void IntegerTextBox_GotFocus(object sender, RoutedEventArgs e) { TextAlignment = TextAlignment.Left; if (IntValue != null) Text = ToText(IntValue, false); } #region properties public static readonly DependencyProperty IntProperty = DependencyProperty.Register("IntValue", typeof(int?), typeof(IntegerTextBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback( (s, a) => { IntegerTextBox control = s as IntegerTextBox; if (a != null) control.Text = control.ToText(a.NewValue as int?, true); }))); public int? IntValue { get { object value = GetValue(IntProperty); if (value is int) return (int)value; else return null; } set { SetValue(IntProperty, value); Text = ToText(value, true); } } #endregion properties #region private methods private string ToText(int? intValue, bool withGroupSeparator) { if (intValue == null) return null; double value = (double)intValue; var result = value.ToString(withGroupSeparator ? "N0" : "F0", CultureInfo); return result; } #endregion private methods #region virtual methods protected override void CultureInfoChanged() { if (!IsFocused) { Text = ToText(IntValue, true); } } #endregion virtual methods } }
using System; using System.IO; using System.Net; namespace Emanate.Core.Input.TeamCity { public class TeamCityConnection : ITeamCityConnection { private readonly Uri baseUri; private readonly NetworkCredential networkCredential; private readonly bool isGuestAuthentication; public TeamCityConnection(TeamCityConfiguration configuration) { var rawUri = configuration.Uri ?? "http://localhost"; baseUri = new Uri(rawUri); isGuestAuthentication = configuration.IsUsingGuestAuthentication; if (!isGuestAuthentication) { var userName = configuration.UserName; var password = configuration.Password; networkCredential = new NetworkCredential(userName, password); } } public string GetProjects() { var uri = CreateUri("/httpAuth/app/rest/projects"); return Request(uri); } public string GetProject(string projectId) { var buildUri = CreateUri(string.Format("/httpAuth/app/rest/projects/id:{0}", projectId)); return Request(buildUri); } public string GetBuild(string buildId) { return GetBuilds(buildId, 1); } public string GetBuilds(string buildId, int count) { var resultUri = CreateUri(string.Format("httpAuth/app/rest/builds?locator=running:all,buildType:(id:{0}),count:" + count, buildId)); return Request(resultUri); } private Uri CreateUri(string relativeUrl) { return new Uri(baseUri, relativeUrl.TrimStart('/')); } private string Request(Uri uri) { var webRequest = CreateWebRequest(uri); webRequest.Accept = "application/xml"; using (var webResponse = webRequest.GetResponse()) using (var stream = webResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) return reader.ReadToEnd(); } private HttpWebRequest CreateWebRequest(Uri uri) { var webRequest = (HttpWebRequest)WebRequest.Create(uri); if (!isGuestAuthentication) webRequest.Credentials = networkCredential; webRequest.Proxy = null; return (webRequest); } } }
using Photon.Pun; using System.Collections; using TMPro; using UnityEngine; namespace Source.Code.MyPhoton { public class NickNameSetter : MonoBehaviour { [SerializeField] private float blinkPeriod = 0.2f; [SerializeField] private int blinkCounts = 7; [SerializeField] private TMP_InputField inputField; [SerializeField] private TextMeshProUGUI placeholderTMP; [SerializeField] private int maxSymbols = 15; private string currentNick = ""; private const string ppNickNameKey = "PlayerNickName"; private void Awake() { if (PlayerPrefs.HasKey(ppNickNameKey)) { currentNick = PlayerPrefs.GetString(ppNickNameKey); inputField.text = currentNick; PhotonNetwork.NickName = currentNick; } } public void OnInputFieldChanging(string textInInputField) { if (textInInputField.Length > maxSymbols) { inputField.text = currentNick; } else { currentNick = textInInputField; } } public void OnInputFieldChangingEnded(string textInInputField) { PhotonNetwork.NickName = currentNick; PlayerPrefs.SetString(ppNickNameKey, currentNick); } public bool IsNicknameEmpty() { bool isEmpty = currentNick == ""; if (isEmpty) { StartCoroutine(Blink(placeholderTMP, blinkPeriod, blinkCounts)); } return isEmpty; } private IEnumerator Blink(TextMeshProUGUI tmp, float period, int count) { var waiter = new WaitForSeconds(period); for (int i = 0; i < count; i++) { tmp.color = i % 2 == 0 ? Color.red : Color.black; yield return waiter; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ChessDotNetBackend; namespace ChessWinForms { public partial class ChessBoard2D : UserControl, IPieceVisitor, IUserInterface { private int m_width = 400; private Brush m_darkBrush; private Brush m_lightBrush; private Pen m_selectionPen = new Pen(Color.Red, 3); private Pen m_highlightPen = new Pen(Color.White, 2); private Board m_board; private Brush m_whiteBrush = new SolidBrush(Color.White); private Brush m_blackBrush = new SolidBrush(Color.Black); private Square m_selectedSquare = new Square(-1, -1); private List<Square> m_highlightedSquares = new List<Square>(); private IPiece m_selectedPiece; private int SquareWidth => m_width / 8; public ChessBoard2D() { InitializeComponent(); m_darkBrush = new SolidBrush(Color.FromArgb(0x70, 0x70, 0x70)); m_lightBrush = new SolidBrush(Color.FromArgb(0xa0, 0xa0, 0xa0)); } public Board Board { set { m_board = value; this.Invalidate(); } } bool m_thinking; public bool MachineThinking { get => m_thinking; set { m_thinking = value; Invalidate(); } } private void ChessBoard2D_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; if (m_board != null) { bool dark = false; for (var x = 0; x < 8; x++) { dark = !dark; for (var y = 0; y < 8; y++) { dark = !dark; Brush brush; if (dark) { brush = m_darkBrush; } else { brush = m_lightBrush; } e.Graphics.FillRectangle(brush, x * m_width / 8, y * m_width / 8, m_width / 8, m_width / 8); } } e.Graphics.DrawRectangle(Pens.Black, 0, 0, m_width, m_width); foreach (var piece in m_board.Pieces) { piece.Accept(this, e.Graphics); } if (m_selectedSquare.InBounds) { e.Graphics.DrawRectangle(m_selectionPen, m_selectedSquare.x * SquareWidth, m_selectedSquare.y * SquareWidth, SquareWidth, SquareWidth); } foreach (var square in m_highlightedSquares) { e.Graphics.DrawRectangle(m_highlightPen, square.x * SquareWidth, square.y * SquareWidth, SquareWidth, SquareWidth); } } if (m_thinking) { e.Graphics.FillRectangle(m_translucentBrush, 0, 0, m_width, m_width); } } Brush m_translucentBrush = new SolidBrush(Color.FromArgb(120, 0, 0, 0)); public void Update(Board newBoard) { m_board = newBoard; BoardUpdated(this, new BoardUpdateEventArgs(m_board)); Invalidate(); } #region piece drawing public void Visit(Pawn piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); g.FillEllipse(brush, pt.X - squareWidth / 5, pt.Y - squareWidth / 5, 2 * squareWidth / 5, 2 * squareWidth / 5); } public void Visit(Rook piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); g.FillRectangle(brush, pt.X - squareWidth / 7, pt.Y - squareWidth / 4, 2 * squareWidth / 7, 2 * squareWidth / 4); g.FillRectangle(brush, pt.X - squareWidth / 5, pt.Y - squareWidth / 4, 2 * squareWidth / 5, squareWidth / 8); g.FillRectangle(brush, pt.X - squareWidth / 5, pt.Y + squareWidth / 4 - squareWidth / 8, 2 * squareWidth / 5, squareWidth / 8); } public void Visit(Knight piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); g.FillRectangle(brush, pt.X - squareWidth / 5, pt.Y - squareWidth / 4, 2 * squareWidth / 7, 2 * squareWidth / 4); g.FillRectangle(brush, pt.X - squareWidth / 5, pt.Y - squareWidth / 4, 2 * squareWidth / 5, 2 * squareWidth / 8); } public void Visit(Bishop piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); PointF[] pts = new PointF[] { new PointF( pt.X - squareWidth / 5, pt.Y + squareWidth / 4 ), new PointF(pt.X+squareWidth/5,pt.Y+squareWidth/4), new PointF(pt.X,pt.Y-squareWidth/4) }; g.FillPolygon(brush, pts); } public void Visit(Queen piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); PointF[] pts = new PointF[] { new PointF( pt.X-squareWidth/3.5f,pt.Y+squareWidth/7), new PointF(pt.X+squareWidth/3.5f,pt.Y+squareWidth/7), new PointF(pt.X,pt.Y-squareWidth/3) }; g.FillPolygon(brush, pts); pts = new PointF[] { new PointF( pt.X-squareWidth/3.5f,pt.Y-squareWidth/7), new PointF(pt.X+squareWidth/3.5f,pt.Y-squareWidth/7), new PointF(pt.X,pt.Y+squareWidth/3) }; g.FillPolygon(brush, pts); } public void Visit(King piece, object data) { int squareWidth = m_width / 8; Graphics g = data as Graphics; drawPiecePreamble(piece, out Brush brush, out PointF pt); g.FillRectangle(brush, pt.X - squareWidth / 7, pt.Y - squareWidth / 3.5f, 2 * squareWidth / 7, 2 * squareWidth / 3.5f); g.FillRectangle(brush, pt.X - squareWidth / 3.5f, pt.Y - squareWidth / 7, 2 * squareWidth / 3.5f, 2 * squareWidth / 7); } void drawPiecePreamble(IPiece piece, out Brush brush, out PointF pt) { int squareWidth = m_width / 8; brush = piece.White ? m_whiteBrush : m_blackBrush; pt = new Point(piece.CurrentPosition.x * squareWidth + squareWidth / 2, piece.CurrentPosition.y * squareWidth + squareWidth / 2); } #endregion private void ChessBoard2D_MouseClick(object sender, MouseEventArgs e) { if (m_thinking) { return; } double squareWidth = m_width / 8; int x = (int)Math.Floor(e.X / squareWidth); int y = (int)Math.Floor(e.Y / squareWidth); SquareClicked(new Square(x, y)); } private void SquareClicked(Square clickedSquare) { if (!clickedSquare.InBounds) { return; } m_selectedSquare = new Square(-1, -1); m_highlightedSquares.Clear(); IPiece clickedPiece = m_board.GetPieceOnSquare(clickedSquare); if (m_selectedPiece == null) { if (clickedPiece != null) { if (clickedPiece.White == m_board.WhitesTurn) { m_selectedPiece = clickedPiece; m_selectedSquare = clickedSquare; } if (m_selectedPiece != null) { m_highlightedSquares.AddRange(clickedPiece.GetAllMoves(m_board)); } } } else { if (m_selectedPiece.IsMoveValid(m_board, clickedSquare)) { m_board = m_board.MovePiece(m_selectedPiece, clickedSquare); BoardUpdated(this, new BoardUpdateEventArgs(m_board)); } m_selectedPiece = null; } Invalidate(); } public event EventHandler<BoardUpdateEventArgs> BoardUpdated; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Effigy.Entity.Entity { public class MenuDetails { public int MenuId { get; set; } public string MenuText { get; set; } public string MenuDesc { get; set; } public string NavigateURL { get; set; } public Nullable<int> ParentID { get; set; } public string ParentMenu { get; set; } public Nullable<int> OrderNo { get; set; } public Nullable<int> ApplicationID { get; set; } public Nullable<bool> IsActive { get; set; } } }
using WinterIsComing.Core.Exceptions; using WinterIsComing.Models.Units; namespace WinterIsComing.Core { using System; using Contracts; using Models; public static class UnitFactory { public static IUnit Create(UnitType type, string name, int x, int y) { switch (type) { case UnitType.IceGiant: return new IceGiant(x,y,name); case UnitType.Mage: return new Mage(x, y, name); case UnitType.Warrior: return new Warrior(x,y,name); default: throw new GameException(String.Format("{0} - unknown type of unit", type.ToString())); } } } }
using SuperMario.Collision; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SuperMario.Entities.Mario.MarioCondition { public class SmallMario : MarioConditionState { public SmallMario(IPlayerTexturePack playerTexturePack) : base(playerTexturePack) {} public override void ActivateAbility(bool use, Direction direction, GameTime currentGameTime) { } protected override Entity RunningLeft { get { if (RunningLeftValue == null) RunningLeftValue = new RunningSmallMario(ScreenLocation, TexturePack.RunningLeft); RunningLeftValue.SetScreenLocation(ScreenLocation); return RunningLeftValue; } } protected override Entity RunningRight { get { if (RunningRightValue == null) RunningRightValue = new RunningSmallMario(ScreenLocation, TexturePack.RunningRight); RunningRightValue.SetScreenLocation(ScreenLocation); return RunningRightValue; } } public override PlayerCondition PlayerConditionType => PlayerCondition.Small; } public class RunningSmallMario : AnimatedEntity { Texture2D texture; Rectangle currentAnimationRectangle; int numberOfFrames = 3; public RunningSmallMario(Vector2 screenLocation, Texture2D texture) : base(screenLocation, 1000000) { this.texture = texture; currentAnimationRectangle = new Rectangle(0, 0, texture.Width / numberOfFrames, texture.Height); } public override ISprite FirstSprite => new Sprite(texture, new Rectangle(0, 0, texture.Width / numberOfFrames, texture.Height)); public override ISprite NextSprite { get { currentAnimationRectangle.X += texture.Width / numberOfFrames; if (currentAnimationRectangle.X == texture.Width) currentAnimationRectangle.X = 0; return new Sprite(texture, currentAnimationRectangle); } } public override void Collide(Entity entity, RectangleCollisions collisions) { } } }
using iText; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Filter; using iText.Kernel.Pdf.Canvas.Parser.Listener; using Parser_Console.Classes; using Parser_Console.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Parser_Console { public static class DebugFunctions { public static void ScanDocument(string path) { DocumentCollection c = new DocumentCollection(); c.AddDocument(path); } public static void strDiff(string s1, string s2) { char[] a1 = s1.ToCharArray(); char[] a2 = s2.ToCharArray(); int d = 0; for (int i = 0; i < a1.Length; i++) { if(a1[i] == a2[i]) { d++; } else { char c1 = a1[i]; char c2 = a2[i]; } } } public static void CopyToDebugFolder(List<IDocument> collection,string folderName) { var copyFolder = @"T:\ToolboxStorage\Testing\Documents\" + folderName + @"\"; foreach (var item in collection) { File.Copy(item.FilePath, copyFolder + System.IO.Path.GetFileName(item.FilePath)); } } public static void LocScan(string path) { PdfReader reader = new PdfReader(path); PdfDocument doc = new PdfDocument(reader); for (int i = 1; i <= doc.GetNumberOfPages(); i++) { PdfPage d = doc.GetPage(i); string full = PdfTextExtractor.GetTextFromPage(d, new LocationTextExtractionStrategy()); Rectangle t = d.GetPageSize(); Rectangle z = d.GetPageSize(); //z.SetY(-450); z.SetHeight(15); z.SetWidth(200); z.SetY(375); TextRegionEventFilter filter = new TextRegionEventFilter(z); FilteredTextEventListener list = new FilteredTextEventListener(new LocationTextExtractionStrategy(), filter); string half = PdfTextExtractor.GetTextFromPage(d, list); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace _11_Poisonous_Plants { public class _11_Poisonous_Plants { public static void Main() { var plantsNumber = int.Parse(Console.ReadLine()); var plants = Console.ReadLine().Split().Select(int.Parse).ToArray(); var daysPlantDie = new int[plantsNumber]; var previousPlant = new Stack<int>(); previousPlant.Push(0); for (int i = 1; i < plantsNumber; i++) { int lastDay = 0; while (previousPlant.Count() > 0 && plants[previousPlant.Peek()] >= plants[i]) { lastDay = Math.Max(lastDay, daysPlantDie[previousPlant.Pop()]); } if (previousPlant.Count() > 0) { daysPlantDie[i] = lastDay + 1; } previousPlant.Push(i); } Console.WriteLine(daysPlantDie.Max()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Xml; public partial class mont2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn1_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =1", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void btn2_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =2", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbl4_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =4", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt11_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =11", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbl3_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =3", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt5_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =5", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt6_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =6", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt7_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =7", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt8_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =8", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt9_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =9", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } protected void lbt10_Click(object sender, EventArgs e) { XmlReader xmlFile; xmlFile = XmlReader.Create(Server.MapPath("~/montdata.xml"), new XmlReaderSettings());//xml dosyasına ulaştık DataSet ds = new DataSet(); DataView dv; ds.ReadXml(xmlFile); dv = new DataView(ds.Tables[0], "resimid =10", "resim1", DataViewRowState.CurrentRows); Session["Resim"] = dv; Response.Redirect("~/xmlgelen2.aspx"); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using MultiplechoiseSystem.DTO; namespace MultiplechoiseSystem.DAO { class UserDAO { private static UserDAO instance; public static UserDAO Instance { get { if (instance == null) instance = new UserDAO(); return UserDAO.instance; } private set { UserDAO.instance = value; } } private UserDAO() { } public bool getUser(string username, string password) { string query= $"select * from SYSTEMUSER JOIN ACCOUNT on userID=uID JOIN DEPARTMENT on DEPARTMENT.Dcode= SYSTEMUSER.Dcode where Username='{username}' and AccountPassword='{password}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); if (result.Rows.Count != 0) { DataRow r = result.Rows[0]; UserDTO.Instance.sex = r["Sex"].ToString().Trim(); UserDTO.Instance.UserType = r["UserType"].ToString().Trim(); UserDTO.Instance.DepartmentCode = r["Dcode"].ToString().Trim(); UserDTO.Instance.userID = r["uID"].ToString().Trim().Trim(); UserDTO.Instance.DepartmentName = r["Dname"].ToString().Trim(); UserDTO.Instance.Username = username; UserDTO.Instance.password = password; try { UserDTO.Instance.FirstName = r["FirstName"].ToString().Trim(); UserDTO.Instance.LastName = r["LastName"].ToString().Trim(); UserDTO.Instance.Address = r["UserAddress"].ToString().Trim(); UserDTO.Instance.DateOfBirth = (DateTime)r["DateOfBirth"]; } catch(Exception e) { } return true; } return false; } public List<CourseDTO> getCourse() { List<CourseDTO> lst = new List<CourseDTO>(); string query = $"SELECT * FROM COURSE JOIN STUDY ON COURSEID= STUDY.idCourse JOIN SYSTEMUSER on uid=IDheader WHERE idUSER= '{UserDTO.Instance.userID}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach(DataRow i in result.Rows ) { CourseDTO t = new CourseDTO(); t.CourseID = i["courseID"].ToString().Trim(); t.CourseName = i["coursename"].ToString().Trim(); t.idheader = i["idheader"].ToString().Trim(); t.idmanager = i["idmnglecturer"].ToString().Trim(); t.LecturerName = i["firstname"].ToString().Trim() + " " + i["lastname"].ToString().Trim(); lst.Add(t); } return lst; } public List<CourseDTO> getCourseTeacher() { List<CourseDTO> lst = new List<CourseDTO>(); string query = $"SELECT * FROM COURSE JOIN STUDY ON COURSEID= STUDY.idCourse JOIN SYSTEMUSER on uid=IDheader WHERE idUSER= '{UserDTO.Instance.userID}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach (DataRow i in result.Rows) { CourseDTO t = new CourseDTO(); t.CourseID = i["courseID"].ToString().Trim(); t.CourseName = i["coursename"].ToString().Trim(); t.idheader = i["idheader"].ToString().Trim(); t.idmanager = i["idmnglecturer"].ToString().Trim(); t.LecturerName = i["firstname"].ToString().Trim() + " " + i["lastname"].ToString().Trim(); lst.Add(t); } return lst; } public List<CourseDTO> getCourseTeachByTeacher() { List<CourseDTO> lst = new List<CourseDTO>(); string query = $"SELECT * FROM COURSE JOIN TEACH ON COURSE.courseID= TEACH.courseID JOIN SYSTEMUSER on uid=IDheader WHERE userID= '{UserDTO.Instance.userID}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach (DataRow i in result.Rows) { CourseDTO t = new CourseDTO(); t.CourseID = i["courseID"].ToString().Trim(); t.CourseName = i["coursename"].ToString().Trim(); t.idheader = i["idheader"].ToString().Trim(); t.idmanager = i["idmnglecturer"].ToString().Trim(); t.LecturerName = i["firstname"].ToString().Trim() + " " + i["lastname"].ToString().Trim(); lst.Add(t); } return lst; } public List<CourseDTO> getCourseOfManager() { List<CourseDTO> lst = new List<CourseDTO>(); string query = $"select * from course join systemuser on uId=IDmngLecturer where IDmngLecturer='{UserDTO.Instance.userID}'"; DataTable result = DataProvider.Instance.ExecuteQuery(query); foreach (DataRow i in result.Rows) { CourseDTO t = new CourseDTO(); t.CourseID = i["courseID"].ToString().Trim(); t.CourseName = i["coursename"].ToString().Trim(); t.idheader = i["idheader"].ToString().Trim(); t.idmanager = i["idmnglecturer"].ToString().Trim(); t.LecturerName = i["firstname"].ToString().Trim() + " " + i["lastname"].ToString().Trim(); lst.Add(t); } return lst; } } }
using Terraria.ModLoader; using Terraria.ID; namespace Intalium.Items.Tools { public class PickaxeOfTerraria : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Pickaxe of Terraria"); } public override void SetDefaults() { item.value = 250000; item.useStyle = 1; item.useAnimation = 12; item.useTime = 3; item.useTurn = true; item.autoReuse = true; item.rare = 8; item.width = 80; item.height = 80; item.UseSound = SoundID.Item1; item.damage = 240; item.knockBack = 8; item.melee = true; item.scale = 1.4f; item.pick = 375; item.tileBoost = 8; item.crit = 12; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "PreUltimatePickaxe", 1); recipe.AddIngredient(null, "UltimatePickaxe", 1); recipe.AddIngredient(null, "UltimateAlloyPickaxe", 1); recipe.AddIngredient(null, "Shine", 15); recipe.AddIngredient(ItemID.PixieDust, 25); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); } } }
using NfePlusAlpha.Domain.Entities; using NfePlusAlpha.Services.Correios.wsCorreios; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NfePlusAlpha.Application.ViewModel { public class ClienteViewModel : ViewModelBase { #region CONSTRUTOR public ClienteViewModel() { this.objCliente = new tbCliente(); this.blnCodigoEnabled = true; } #endregion CONSTRUTOR #region PROPRIEDADES public tbCliente objCliente { get; set; } public int cli_codigo { get { return this.objCliente.cli_codigo; } set { this.objCliente.cli_codigo = value; RaisePropertyChanged("cli_codigo"); } } [Required(ErrorMessage = "CPF/CNPJ obrigatório.")] public string cli_cpfCnpj { get { return this.objCliente.cli_cpfCnpj; } set { this.objCliente.cli_cpfCnpj = value; RaisePropertyChanged("cli_cpfCnpj"); } } [Required(ErrorMessage = "Nome/Razao Social obrigatório.")] public string cli_nome { get { return this.objCliente.cli_nome; } set { this.objCliente.cli_nome = value; RaisePropertyChanged("cli_nome"); } } public string cli_fantasia { get { return this.objCliente.cli_fantasia; } set { this.objCliente.cli_fantasia = value; RaisePropertyChanged("cli_fantasia"); } } public string cli_rgIe { get { return this.objCliente.cli_rgIe; } set { this.objCliente.cli_rgIe = value; RaisePropertyChanged("cli_rgIe"); } } [Required(ErrorMessage = "Email obrigatório.")] public string cli_email { get { return this.objCliente.cli_email; } set { this.objCliente.cli_email = value; RaisePropertyChanged("cli_email"); ClearError("cli_email"); try { Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "cli_email" }); } catch { SetError("cli_email", "Campo obrigatório"); } } } [Required(ErrorMessage = "CEP obrigatório.")] public string cli_enderecoCep { get { return this.objCliente.cli_enderecoCep; } set { try { //HttpWebRequest httpRequisicao = (HttpWebRequest)WebRequest.Create("http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do?Metodo=listaLogradouro&CEP=" + value + "&TipoConsulta=cep"); //HttpWebResponse httpResposta = (HttpWebResponse)httpRequisicao.GetResponse(); //int intCont; //byte[] bytBuffer = new byte[1000]; //StringBuilder strResposta = new StringBuilder(); //string strTemp; //Stream stream = httpResposta.GetResponseStream(); //do //{ // intCont = stream.Read(bytBuffer, 0, bytBuffer.Length); // strTemp = Encoding.Default.GetString(bytBuffer, 0, intCont).Trim(); strResposta.Append(strTemp); //} while (intCont > 0); //string strHtmlPagina = strResposta.ToString(); //if (strHtmlPagina.IndexOf("<font color=\"black\">CEP NAO ENCONTRADO</font>") < 0) //{ // this.cli_enderecoLogradouro = Regex.Match(strHtmlPagina, "<td width=\"268\" style=\"padding: 2px\">(.*)</td>").Groups[1].Value; // this.cli_enderecoBairro = Regex.Matches(strHtmlPagina, "<td width=\"140\" style=\"padding: 2px\">(.*)</td>")[0].Groups[1].Value; // //this.end_cidade = Regex.Matches(strHtmlPagina, "<td width=\"140\" style=\"padding: 2px\">(.*)</td>")[1].Groups[1].Value; // //this.end_uf = Regex.Match(strHtmlPagina, "<td width=\"25\" style=\"padding: 2px\">(.*)</td>").Groups[1].Value; //} AtendeClienteClient objConsultaCep = new AtendeClienteClient("AtendeClientePort"); var resultado = objConsultaCep.consultaCEP(value); if (resultado != null) { this.cli_enderecoLogradouro = resultado.end; this.cli_enderecoComplemento = resultado.complemento; this.cli_enderecoBairro = resultado.bairro; //txtCidade.Text = resultado.cidade; //txtEstado.Text = resultado.uf; } } catch { } finally { this.objCliente.cli_enderecoCep = value; RaisePropertyChanged("cli_enderecoCep"); } } } [Required(ErrorMessage = "Logradouro obrigatório.")] public string cli_enderecoLogradouro { get { return this.objCliente.cli_enderecoLogradouro; } set { this.objCliente.cli_enderecoLogradouro = value; RaisePropertyChanged("cli_enderecoLogradouro"); } } [Required(ErrorMessage = "Número obrigatório.")] public string cli_enderecoNumero { get { return this.objCliente.cli_enderecoNumero; } set { this.objCliente.cli_enderecoNumero = value; RaisePropertyChanged("cli_enderecoNumero"); } } public string cli_enderecoComplemento { get { return this.objCliente.cli_enderecoComplemento; } set { this.objCliente.cli_enderecoComplemento = value; RaisePropertyChanged("cli_enderecoComplemento"); } } [Required(ErrorMessage = "Bairro obrigatório.")] public string cli_enderecoBairro { get { return this.objCliente.cli_enderecoBairro; } set { this.objCliente.cli_enderecoBairro = value; RaisePropertyChanged("cli_enderecoBairro"); } } //[Required(ErrorMessage = "UF obrigatório.")] //public string end_uf //{ // get { return this.objEndereco.end_uf; } // set // { // this.objEndereco.end_uf = value; // RaisePropertyChanged("end_uf"); // } //} //[Required(ErrorMessage = "Cidade obrigatório.")] //public string end_cidade //{ // get { return this.objEndereco.end_cidade; } // set // { // this.objEndereco.end_cidade = value; // RaisePropertyChanged("end_cidade"); // } //} [Required(ErrorMessage = "Telefone obrigatório.")] public string cli_telefone { get { return this.objCliente.cli_telefone; } set { this.objCliente.cli_telefone = value; RaisePropertyChanged("cli_telefone"); } } public string cli_celular { get { return this.objCliente.cli_celular; } set { this.objCliente.cli_celular = value; RaisePropertyChanged("cli_celular"); } } private bool _blnCodigoEnabled; public bool blnCodigoEnabled { get { return _blnCodigoEnabled; } set { _blnCodigoEnabled = value; RaisePropertyChanged("blnCodigoEnabled"); } } #endregion PROPRIEDADES #region METODOS public void Salvar(out string strMensagem) { strMensagem = string.Empty; this.AtualizaErrosViewModel(); if (!this.HasErrors) { //ConsultPostosRetorno objRetorno; //using (Pessoa objBll = new Pessoa()) //{ // objRetorno = objBll.Salvar(this.objCliente); //} //if (objRetorno.blnTemErro) // strMensagem = objRetorno.strMsgErro; //else // RaisePropertyChanged("pes_id"); } } public void Excluir(out string strMensagem) { strMensagem = string.Empty; //ConsultPostosRetorno objRetorno; //using (Pessoa objBll = new Pessoa()) //{ // objRetorno = objBll.ExcluirPessoa(this.objCliente.pes_id); //} //if (objRetorno.blnTemErro) // strMensagem = objRetorno.strMsgErro; } //public tbCliente ObterPessoa(int intCodigo, enDirecao? enDirecao) //{ // tbPessoa objPessoa = null; // ConsultPostosRetorno objRetorno; // using (Pessoa objBll = new Pessoa()) // { // objRetorno = objBll.RetornaPessoa(intCodigo, "", enDirecao); // } // if (!objRetorno.blnTemErro && objRetorno.objRetorno != null) // { // objPessoa = (tbPessoa)objRetorno.objRetorno; // } // return objPessoa; //} public void AtualizaErrosViewModel() { //this.pes_email = this.objCliente.pes_email; } #endregion METODOS } }
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Parts { public interface ITermPartGraphSyncer : IContentPartGraphSyncer { } }
using System; using System.Collections.Generic; using System.Drawing; namespace SharpMap.UI.Tools { public class LegendToolItem { #region fields private bool centered; private Bitmap symbol; private IList<LegendToolItem> items = new List<LegendToolItem>(); private LegendToolItem parent; private Size padding; private Graphics graphics; private Font font; #endregion public LegendToolItem() { } public LegendToolItem(Bitmap symbol, string text, bool centered, LegendToolItem parent) { this.centered = centered; this.symbol = symbol; Text = text; this.parent = parent; } #region properties (getters & setters) public IList<LegendToolItem> Items { get { return items; } } public Bitmap Symbol { set { symbol = value; } get { return symbol; } } internal string Text { get; set; } public bool Centered { get { return centered; } } public LegendToolItem Parent { get { return parent; } set { parent = value; } } public Graphics Graphics { get { if (parent == null) return graphics; return parent.Graphics; } set { graphics = value; } } public Font Font { get { if (parent == null) return font; return parent.Font; } set { font = value; } } public Size Padding { get { if (parent == null) return padding; return parent.Padding; } set { padding = value; } } /// <summary> /// Compute size of this LegendToolItem only (i.e. excluding any children) /// </summary> public SizeF InternalSize { get { SizeF internalSize = new SizeF(0, 0); List<SizeF> sizes = new List<SizeF>(); if (symbol != null) sizes.Add(symbol.Size); if (Text != null) sizes.Add(Graphics.MeasureString(Text, Font)); if (Text != null && symbol != null) sizes.Add(Padding); foreach (SizeF size in sizes) { internalSize.Width += size.Width; } internalSize.Height = MaxHeight(sizes.ToArray()).Height; return internalSize; } } public SizeF Size { get { SizeF maxWidthSize = InternalSize; foreach (var item in items) { maxWidthSize.Width = MaxWidth(maxWidthSize, item.Size).Width; } SizeF heightSize = InternalSize; heightSize.Height += Padding.Height; foreach (var item in items) { heightSize.Height += item.Size.Height; } return new SizeF(maxWidthSize.Width, heightSize.Height); } } public int Depth { get { int maxDepth = -1; foreach(var child in Items) { int childDepth = child.Depth; if (childDepth > maxDepth) maxDepth = childDepth; } return maxDepth + 1; } } public LegendToolItem Root { get { if (Parent != null) { return Parent.Root; } return this; } } #endregion public LegendToolItem AddItem(string text) { var newToolItem = new LegendToolItem(null, text, false, this); items.Add(newToolItem); return newToolItem; } public LegendToolItem AddItem(string text, bool centeredParam) { var newToolItem = new LegendToolItem(null, text, centeredParam, this); items.Add(newToolItem); return newToolItem; } public LegendToolItem AddItem(Bitmap symbolBitmap, string text) { var newToolItem = new LegendToolItem(symbolBitmap, text, false, this); items.Add(newToolItem); return newToolItem; } public LegendToolItem InsertItem(LegendToolItem predecessor, string itemText) { var newToolItem = new LegendToolItem(null, itemText, false, this); int index = items.IndexOf(predecessor); if ((index + 1) < items.Count) { items.Insert(index + 1, newToolItem); } else { items.Add(newToolItem); } return newToolItem; } /// <summary> /// returns new Size with Height 0 and the maximum width of both passed in sizes /// </summary> /// <param name="size1"></param> /// <param name="size2"></param> /// <returns></returns> private static SizeF MaxWidth(SizeF size1, SizeF size2) { return new SizeF(Math.Max(size1.Width, size2.Width), 0); } /// <summary> /// returns new Size with Width 0 and the maximum height of both passed in sizes /// </summary> /// <param name="size1"></param> /// <param name="size2"></param> /// <returns></returns> private static SizeF MaxHeight(SizeF size1, SizeF size2) { return new SizeF(0, Math.Max(size1.Height, size2.Height)); } /// <summary> /// returns new Size with Width 0 and the maximum height of both passed in sizes /// </summary> /// <param name="sizes"></param> /// <returns></returns> private static SizeF MaxHeight(params SizeF[] sizes) { var maxHeight = new SizeF(0, 0); foreach (var size in sizes) { maxHeight = MaxHeight(maxHeight, size); } return maxHeight; } } }
using UnityEngine; using System.Collections; public class summonLS : MonoBehaviour { public float lifeSpan = 15.0f; public int Combo = 0; private randomInst Inter; private addForce Spd; // Use this for initialization void Start () { Inter = GameObject.Find ("keys").GetComponent<randomInst> (); } // Update is called once per frame void Update () { lifeSpan -= 0.5f * Time.deltaTime; if (lifeSpan <= 0) { Debug.Log ("death"); } } void OnTriggerEnter(Collider other) { Inter.keySpeed = 2.0f; Inter.interval = 2.5f; Combo = 0; lifeSpan -= 5.0f; Destroy (other.gameObject); Debug.Log ("collide"); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using KulujenSeuranta.Models; using KulujenSeuranta.ViewModels; using KulujenSeuranta.Interfaces; using KulujenSeuranta.Services; using DotNet.Highcharts; namespace KulujenSeuranta.Controllers { public class StatisticsController : Controller { // GET: Statistics [Authorize(Roles = "canRead")] public ActionResult Index() { IPaymentService paymentService = new PaymentService(); var statisticsViewModel = new StatisticsViewModel(paymentService); statisticsViewModel.SearchDate = new SearchDate { UserInputDate = DateTime.Now.Month + "-" + DateTime.Now.Year }; return View("MonthlyView", statisticsViewModel); } [Authorize(Roles = "canRead")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index([Bind(Include = "SearchDate")] StatisticsViewModel statisticsViewModel) { if (statisticsViewModel.SearchDate.UserInputDate == null) { return View(statisticsViewModel); } return View("MonthlyView", statisticsViewModel); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StatePointAI : MonoBehaviour { #region class variables [SerializeField] public float health = 100f; [SerializeField] public float maxHealth = 100f; [SerializeField] private float regenHealthValue = 15f; [SerializeField] private float damage = 20f; [SerializeField] private float speed = 5f; [SerializeField] private float minDistance = 0.5f; [SerializeField] private float minDamageDistance = 1f; [SerializeField] private float minChaseDistance = 5f; [SerializeField] private int index = 0; [SerializeField] private float waitTime = 1f; [SerializeField] private GameObject player; [SerializeField] private GameObject[] waypoint; private SpriteRenderer sPRenderer; public enum State { patrol, chase, flee, wait } public State state; #endregion private void Start() { sPRenderer = GetComponent<SpriteRenderer>(); NextState(); } private void Update() { CheckTakeDamage(health, damage); CheckHealthRegen(health, regenHealthValue); } #region AI States private IEnumerator patrolState() { Debug.Log("Patrol : Enter"); while (state == State.patrol) { if (sPRenderer.color != new Color(0, 1, 1)) { Color patrolColour = new Color(0, 1, 1); sPRenderer.color = patrolColour; } // cannot see player then patrol if (!CanSeePlayer()) { Patrol(speed); yield return 0; } else // can see player then chase or flee { if (EnoughHealth()) { state = State.chase; } else { state = State.flee; } } } Debug.Log("Patrol : Exit"); NextState(); } private IEnumerator chaseState() { Debug.Log("Chase : Enter"); while (state == State.chase) { if (sPRenderer.color != new Color(1, 0.2f, 0)) { Color chaseColour = new Color(1, 0.2f, 0); sPRenderer.color = chaseColour; } if (EnoughHealth()) { // chase player ChasePlayer(speed * 1.5f); yield return 0; } else // i dont have enough health, can i see player, if so then flee { if (CanSeePlayer()) { state = State.flee; } } // cannot see player then wait if (!CanSeePlayer()) { state = State.wait; } else { if (!EnoughHealth()) { state = State.flee; } } yield return 0; } Debug.Log("Chase : Exit"); NextState(); } private IEnumerator fleeState() { if (sPRenderer.color != new Color(1, 1, 1)) { Color fleeColour = new Color(1, 1, 1); sPRenderer.color = fleeColour; } Debug.Log("Flee : Enter"); while (state == State.flee) { //flee FleePlayer(speed); yield return 0; // can i see the player, if not patrol if (!CanSeePlayer()) { state = State.patrol; } else// i can see the player, do i have enough health, if so then chase { if (EnoughHealth()) { state = State.chase; } yield return 0; } } Debug.Log("Flee : Exit"); NextState(); } private IEnumerator waitState() { if (sPRenderer.color != new Color(0, 0, 1)) { Color waitColour = new Color(0, 0, 1); sPRenderer.color = waitColour; } Debug.Log("Wait : Enter"); Vector3 positionAtStartWaitTime = transform.position; // set wait start time float waitStartTime = Time.time; while (state == State.wait) { // stop moving Stop(positionAtStartWaitTime); // health greater than 25%, check for chase or patrol if (EnoughHealth()) { // wait for seconds if (Time.time > waitStartTime + waitTime) { // cannot see player then patrol if (!CanSeePlayer()) { state = State.patrol; } } else if (CanSeePlayer()) // can see player then chase { state = State.chase; } } else // health less than 25%, flee { state = State.flee; } yield return 0; } Debug.Log("Wait : Exit"); NextState(); } private void NextState() { //work out the name of the method we want to run string methodName = state.ToString() + "State"; //if our current state is "walk" then this returns "walkState" //give us a variable so we an run a method using its name System.Reflection.MethodInfo info = GetType().GetMethod(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //Run our method StartCoroutine((IEnumerator)info.Invoke(this, null)); //Using StartCoroutine() means we can leave and come back to the method that is running //All Coroutines must return IEnumerator }//from StateMachine #endregion #region Moving Methods /// <summary> /// can I see the player /// </summary> /// <returns></returns> private bool CanSeePlayer() { if (Vector2.Distance(player.transform.position, transform.position) > minChaseDistance) { return false; } return true; } /// <summary> /// do I have enough health /// </summary> private bool EnoughHealth() { if (health > maxHealth * 0.25f) { return true; } else { return false; } } /// <summary> /// Follows a set path of waypoints /// </summary> /// <param name="_patrolSpeed">movment speed</param> void Patrol(float _patrolSpeed) { float distance = Vector2.Distance(transform.position, waypoint[index].transform.position); if (distance < minDistance) { //index = Random.Range(0, waypoint.Length); index++; } if (index >= waypoint.Length) { index = 0; } MoveAi(waypoint[index].transform.position, _patrolSpeed); } /// <summary> /// move to players position /// </summary> /// <param name="_chaseSpeed">speed to chase player</param> public void ChasePlayer(float _chaseSpeed) { MoveAi(player.transform.position, _chaseSpeed); } /// <summary> /// move away from player /// </summary> /// <param name="_fleeSpeed">speed to move at</param> public void FleePlayer(float _fleeSpeed) { // find the heading towards the player Vector3 heading = player.transform.position - transform.position; // find its magnitude float distance = heading.magnitude; // normalise the vector Vector3 direction = heading.normalized; // depending on the distance to the player move in the opposite direction at a faster or slower speed if (distance < 1f) { Vector3 position = transform.position; position += -(direction) * _fleeSpeed * 10f * Time.deltaTime; position.z = 0; transform.position = position; } else if (distance < 10f) { Vector3 position = transform.position; position += -(direction) * _fleeSpeed * 3.5f * Time.deltaTime; position.z = 0; transform.position = position; } else { Vector3 position = transform.position; position += -(direction) * _fleeSpeed * 1.5f * Time.deltaTime; position.z = 0; transform.position = position; } } /// <summary> /// move towards a certain position /// </summary> /// <param name="targetPosition">where to move to</param> /// <param name="_moveSpeed">how fast to move there</param> void MoveAi(Vector2 targetPosition, float _moveSpeed) { transform.position = Vector2.MoveTowards(transform.position, targetPosition, _moveSpeed * Time.deltaTime); } /// <summary> /// stay at the same position /// </summary> /// <param name="_positionAtStartWaitTime">where to stay</param> private void Stop(Vector3 _positionAtStartWaitTime) { if (transform.position != _positionAtStartWaitTime) { transform.position = _positionAtStartWaitTime; } } /// <summary> /// take damage /// </summary> /// <param name="_health">current health</param> /// <param name="_damage">amount of damage to take</param> public void CheckTakeDamage(float _health, float _damage) { if (health > 0) { if (Vector2.Distance(player.transform.position, transform.position) < minDamageDistance) { _health -= _damage * Time.deltaTime; health = _health; } } else if (health < 0) { health = 0; } else { return; } } /// <summary> /// regenerate health /// </summary> /// <param name="_health">current health</param> /// <param name="_regenAmount">how much to regenerate by</param> public void CheckHealthRegen(float _health, float _regenAmount) { if (!CanSeePlayer()) { if (_health < maxHealth) { _health += _regenAmount * Time.deltaTime; health = _health; } else if (_health > maxHealth) { health = maxHealth; } } } #endregion }
using JT808.Protocol.Attributes; using JT808.Protocol.Formatters; using JT808.Protocol.MessagePack; namespace JT808.Protocol.MessageBody { /// <summary> /// 位置汇报方案,0:根据 ACC 状态; 1:根据登录状态和 ACC 状态,先判断登录状态,若登录再根据 ACC 状态 /// </summary> public class JT808_0x8103_0x0021 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0021> { public override uint ParamId { get; set; } = 0x0021; /// <summary> /// 数据 长度 /// </summary> public override byte ParamLength { get; set; } = 4; /// <summary> /// 位置汇报方案,0:根据 ACC 状态; 1:根据登录状态和 ACC 状态,先判断登录状态,若登录再根据 ACC 状态 /// </summary> public uint ParamValue { get; set; } public JT808_0x8103_0x0021 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_0x8103_0x0021 jT808_0x8103_0x0021 = new JT808_0x8103_0x0021(); jT808_0x8103_0x0021.ParamId = reader.ReadUInt32(); jT808_0x8103_0x0021.ParamLength = reader.ReadByte(); jT808_0x8103_0x0021.ParamValue = reader.ReadUInt32(); return jT808_0x8103_0x0021; } public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0021 value, IJT808Config config) { writer.WriteUInt32(value.ParamId); writer.WriteByte(value.ParamLength); writer.WriteUInt32(value.ParamValue); } } }
namespace CWI.Desafio2.Domain.Entities.Enums { public enum PropertyType { Invalid, Cpf, Cnpj, SaleId } }
namespace Airelax.Application.Houses.Dtos.Response { public class HonorDto { public int Type { get; set; } public string Description { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace FactionCombinationAnalysis.FactionCombine { public static class Consts { public const int CombineMax = 5; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace MainWebApplication.Models { public class ServicesUUID : Dictionary<string, Guid> { private ServicesUUID() { base["MyService"] = new Guid("94ec923e-b5a6-11eb-8529-0242ac130003"); // 4fafc201-1fb5-459e-8fcc-c5c9c331914b } private static ServicesUUID instance; private static object instanceLock = new object(); public static ServicesUUID Instance { get { if (instance == null) { lock (instanceLock) { if (instance == null) { instance = new ServicesUUID(); } } } return instance; } } } public class CharacteristicsUUID : Dictionary<string, Guid> { public CharacteristicsUUID():base() { //base.["Tempreture"] = new Guid("94ec96e4-b5a6-11eb-8529-0242ac130003"); // beb5483e-36e1-4688-b7f5-ea07361b26a8 //this.["HumidityGround"] = new Guid("94ec97de-b5a6-11eb-8529-0242ac130003"); // beb5483e-36e1-4688-b7f5-ea07361b26a9 //this.["HumidityAir"] = new Guid("94ec989c-b5a6-11eb-8529-0242ac130003"); // beb5483e-36e1-4688-b7f5-ea07361b26aa //this.["Voltage"] = new Guid("94ec9964-b5a6-11eb-8529-0242ac130003");// beb5483e-36e1-4688-b7f5-ea07361b26ab //this.["Test"] = new Guid("94ec9a22-b5a6-11eb-8529-0242ac130003"); // beb5483e-36e1-4688-b7f5-ea07361b26ac //this.["Pressure"] = new Guid("94ec9cac-b5a6-11eb-8529-0242ac130003"); // beb5483e-36e1-4688-b7f5-ea07361b26ad } private static CharacteristicsUUID instance; private static object instanceLock = new object(); public static CharacteristicsUUID Instance { get { if (instance == null) { lock (instanceLock) { if (instance == null) { instance = new CharacteristicsUUID(); } } } return instance; } } } }
using Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Data.Mappings { public class ProfileFeatureMap : IEntityTypeConfiguration<ProfileFeature> { public void Configure(EntityTypeBuilder<ProfileFeature> builder) { // Primary Key builder.HasKey(x => new { x.ProfileId, x.FeatureId }); // Properties builder.Property(x => x.ProfileId) .IsRequired(); builder.Property(x => x.FeatureId) .IsRequired(); // Table & Column Mappings builder.ToTable("ProfileFeature"); builder.Property(x => x.ProfileId).HasColumnName("ProfileId"); builder.Property(x => x.FeatureId).HasColumnName("FeatureId"); // Relationships builder.HasOne(x => x.Profile) .WithMany(x => x.ProfileFeatures) .HasForeignKey(x => x.ProfileId); builder.HasOne(x => x.Feature) .WithMany(x => x.ProfileFeatures) .HasForeignKey(x => x.FeatureId); // Ignores } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem213 : ProblemBase { private Square[,] _grid; private decimal[,] _counts; public override string ProblemName { get { return "213: Flea Circus"; } } public override string GetAnswer() { int size = 30; InitializeGrid(size); return ""; } private void InitializeGrid(int size) { _grid = new Square[size, size]; _counts = new decimal[size, size]; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { _grid[x, y] = new Square(); _grid[x, y].AtLeastOne = 1; _grid[x, y].None = 0; _counts[x, y] += (x > 0 ? 1 : 0); _counts[x, y] += (x < size - 1 ? 1 : 0); _counts[x, y] += (y > 0 ? 1 : 0); _counts[x, y] += (y < size - 1 ? 1 : 0); } } } private void Bong(int size) { var newGrid = new Square[size, size]; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { } } } private class Square { public decimal AtLeastOne { get; set; } public decimal None { get; set; } } } }
using MediatR; using AspNetCoreGettingStarted.Data; using AspNetCoreGettingStarted.Model; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using AspNetCoreGettingStarted.Features.Core; using System.Threading; //https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads namespace AspNetCoreGettingStarted.Features.DigitalAssets { public class AddOrUpdateDigitalAssetCommand { public class Request : BaseAuthenticatedRequest, IRequest<Response> { public DigitalAssetApiModel DigitalAsset { get; set; } } public class Response { } public class AddOrUpdateDigitalAssetHandler : IRequestHandler<Request, Response> { public AddOrUpdateDigitalAssetHandler(IAspNetCoreGettingStartedContext context, ICache cache) { _context = context; _cache = cache; } public async Task<Response> Handle(Request request, CancellationToken cancellationToken) { var entity = await _context.DigitalAssets .SingleOrDefaultAsync(x => x.DigitalAssetId == request.DigitalAsset.DigitalAssetId && x.IsDeleted == false); if (entity == null) _context.DigitalAssets.Add(entity = new DigitalAsset()); entity.Name = request.DigitalAsset.Name; entity.Folder = request.DigitalAsset.Folder; await _context.SaveChangesAsync(); _cache.Remove(DigitalAssetsCacheKeyFactory.Get(request.TenantId)); return new Response() { }; } private readonly IAspNetCoreGettingStartedContext _context; private readonly ICache _cache; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.IO; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using System.Windows.Forms; namespace Проверка { public partial class MobForm : Form { Searchmobs Mob_Like; Searchmobs Mob_dislike; public MobForm(string MobType) { InitializeComponent(); Text = MobType; label2.Text = MobType; string category = "Враждебные мобы"; for (int i = 0; i < Mobs.mob_list.Count; i++) { if (MobType == Mobs.mob_list[i].name) { Mob_Like = Mobs.mob_list[i]; Mob_dislike = Mobs.mob_list[i]; category = Mobs.mob_list[i].category; } } try { label3.Text = File.ReadAllText("../../" + category + "/" + MobType + ".txt"); label1.Text = File.ReadAllText("../../" + category + "/" + MobType + "2.txt"); } catch (Exception) { } try { pictureBox1.Load("../../" + category + "/" + MobType + ".gif"); } catch (Exception) { pictureBox1.Load("../../" + category + "/" + MobType + ".png"); } if (Mobs.Mob_like.Contains(Mob_Like)) { label4.Text = "1"; } else { label4.Text = "0"; } } private void pictureBox2_Click(object sender, EventArgs e) { //Нашли нужного if (!Mobs.Mob_like.Contains(Mob_Like)) { //Добавляем в список лайкнутых Mobs.Mob_like.Add(Mob_Like); label4.Text = "1"; } else { Mobs.Mob_like.Remove(Mob_Like); MessageBox.Show("Вы отменили лайк"); label4.Text = "0"; } } private void pictureBox3_Click(object sender, EventArgs e) { if (label5.Text == "0") { label5.Text = "1"; } else { MessageBox.Show("Вы отменили дизлайк"); label5.Text = "0"; } } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterCreation { public class Character { public Race RaceType { get; set; } public List<Stat> Stats { get; set; } public int HitPoints { get; set; } public double CarryWeight { get; set; } public int characterLevel { get; set; } public int movementSpeed { get; set; } public List<Skill> Skills { get; set; } public int ProficiencyBonus { get; set; } public int WalkingSpeed { get; set; } public int ArmorClass { get; set; } public int Initiative { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HotelManagement.BusinessObject; namespace HotelManagement.DataObject { public class DanhSachSuDungDichVuInFo { private string m_MaSuDungDVu; public string MaSuDungDV { get { return m_MaSuDungDVu; } set { m_MaSuDungDVu = value; } } private string m_MaDichVu; public string MaDichVu { get { return m_MaDichVu; } set { m_MaDichVu = value; } } private int m_SoLuong; public int SoLuong { get { return m_SoLuong; } set { m_SoLuong = value; } } } }
using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.Object; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace Claimdi.WCF.Public { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMaster" in both code and config file together. [ServiceContract] public interface IMaster { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/sync", ResponseFormat = WebMessageFormat.Json)] BaseResult<SyncMasterDataResponse> Sync(SyncMasterDataRequest request); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/templateNaResults", ResponseFormat = WebMessageFormat.Json)] BaseResult<TemplateNaResultResponse> TemplateNaResult(); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/checkservicedatabase", ResponseFormat = WebMessageFormat.Json)] string CheckServiceDatabase(); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/amphurByProvinceCode/{provinceCode}", ResponseFormat = WebMessageFormat.Json)] BaseResult<SyncAmphurDataResponse> Amphur(string provinceCode); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/districtByAmphurCode/{amphurCode}", ResponseFormat = WebMessageFormat.Json)] BaseResult<SyncDistrictsDataResponse> District(string amphurCode); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; /// <summary> /// リザルト画面 /// </summary> public class ResultManager : SingletonMonoBehaviour<ResultManager> { [SerializeField] RectTransform[] uiRectTransforms = new RectTransform[3]; int selectIndex = 0; Vector3 initScale = new Vector3(); Vector3 incrementScale = new Vector3(); [SerializeField] Vector3 maxScale = new Vector3(); float scaleTime = 0.0f; [SerializeField] GameObject[] playerNumberUis = new GameObject[4]; private bool push = false; bool isEndResultAnimation = false; [SerializeField] GameObject resultBombObject = null; //ポイントを格納 public static int[] resultPoints = new int[4]; public ResultBlockMeshCombine blockMap = new ResultBlockMeshCombine(); GameObject[] players; [SerializeField] GameObject uiCanvas = null; [SerializeField] ParticleSystem[] winEffects; [SerializeField] GameObject cameraObject = null; [SerializeField] Transform playerEndTransform = null; #if UNITY_EDITOR [SerializeField] bool isDebug = false; [SerializeField] int winPlayerDebug = 0; #endif GameObject fieldObjectParent; void Start() { #if UNITY_EDITOR if (isDebug) { resultPoints[winPlayerDebug] = int.MaxValue; } #endif BgmManager.Instance.Stop(); fieldObjectParent = new GameObject("FieldObjectTemp"); //マップ生成 BlockCreater.GetInstance().CreateField("Result", fieldObjectParent.transform, blockMap, cameraObject, BlockCreater.SceneEnum.Result); fieldObjectParent.isStatic = true; blockMap.BlockIsSurroundUpdate(); blockMap.BlockRendererOff(); GameObject parent = new GameObject("FieldObject"); blockMap.Initialize(parent); players = new GameObject[4]; //プレイヤーを取得 for (int i = 0; i < players.Length; ++i) { //参加していなかったら何もしない if (!BlockCreater.GetInstance().isPlays[i]) continue; players[i] = GameObject.FindGameObjectWithTag("Player" + (i + 1).ToString()); players[i].GetComponent<Player>().enabled = false; } //プレイヤーを地面につける Physics.autoSimulation = false; Physics.Simulate(10.0f); Physics.autoSimulation = true; //UIの表示 foreach (var ui in playerNumberUis) ui.SetActive(false); uiCanvas.SetActive(false); initScale = uiRectTransforms[0].localScale; //リザルトのアニメーション開始 StartCoroutine(ResultAnimation()); } void Update() { blockMap.CreateMesh(); if (push) return; if (!Fade.Instance.IsEnd) return; if (!isEndResultAnimation) return; SelectUpdate(); if (SwitchInput.GetButtonDown(0, SwitchButton.Ok) && !push) { push = true; string sceneName = ""; switch (selectIndex) { case 0: sceneName = "Field"; break; case 1: sceneName = "Select"; break; case 2: sceneName = "Title"; break; } //フェード開始 StartCoroutine(Loadscene(sceneName)); //プッシュの音を鳴らす SoundManager.Instance.Push(); } } void SelectUpdate() { int prevIndex = selectIndex; if (SwitchInput.GetButtonDown(0, SwitchButton.StickRight)) { ++selectIndex; } else if (SwitchInput.GetButtonDown(0, SwitchButton.StickLeft)) { --selectIndex; } selectIndex = Mathf.Clamp(selectIndex, 0, uiRectTransforms.Length - 1); if (prevIndex != selectIndex) { uiRectTransforms[prevIndex].localScale = initScale; SoundManager.Instance.Stick(); incrementScale.Set(0, 0, 0); scaleTime = 0.0f; } scaleTime += Time.deltaTime * 6; incrementScale = (maxScale - initScale) * ((Mathf.Sin(scaleTime) + 1) / 2); uiRectTransforms[selectIndex].localScale = initScale + incrementScale; } private IEnumerator Loadscene(string sceneName) { Fade.Instance.FadeIn(1.0f); while (!Fade.Instance.IsEnd) yield return null; SceneManager.LoadScene(sceneName); } IEnumerator ResultAnimation() { //フェード Fade.Instance.FadeOut(1.0f); while (!Fade.Instance.IsEnd) yield return null; BgmManager.Instance.Play(BgmEnum.DRUM_ROLL, false); bool[] isEnd = new bool[4]; int playerNum = 0; for (int i = 0; i < isEnd.Length; ++i) { //参加していなかったら既に終了しておく isEnd[i] = !BlockCreater.GetInstance().isPlays[i]; //プレイ人数の加算 if (BlockCreater.GetInstance().isPlays[i]) ++playerNum; } List<int> bombPlayerNumbers = new List<int>(); //負けたプレイヤーを順位の低い順番に爆弾で落としていく for (int i = 0; i < playerNum - 1; ++i) { int minPoint = int.MaxValue; int minPlayer = int.MaxValue; //一番点数が低いプレイヤーを探す for (int j = 0; j < isEnd.Length; ++j) { if (isEnd[j]) continue; if (resultPoints[j] < minPoint) { minPoint = resultPoints[j]; minPlayer = j; } } isEnd[minPlayer] = true; bombPlayerNumbers.Add(minPlayer); //yield return StartCoroutine(BombAnimation(minPlayer)); } yield return StartCoroutine(BombAnimation(bombPlayerNumbers)); int winPlayerNumber = 0; //勝ったプレイヤーの番号を探す for (int i = 0; i < isEnd.Length; ++i) { if (!isEnd[i]) { winPlayerNumber = i; break; } } var resultWinPlayerAnimation = players[winPlayerNumber].AddComponent<ResultWinPlayerAnimation>(); fieldObjectParent.SetActive(false); BgmManager.Instance.Play(BgmEnum.RESULT, true, 0.1f); StartCoroutine(BgmVolumeGradation(0.02f)); //勝ったプレイヤーのアニメーション yield return StartCoroutine(resultWinPlayerAnimation.WinPlayerAnimation(winPlayerNumber)); float time = 0; Vector3 InitPosition = players[winPlayerNumber].transform.position; Quaternion InitRotation = players[winPlayerNumber].transform.rotation; while (time <= 1.0f) { time += Time.deltaTime; //終了位置に移動する players[winPlayerNumber].transform.SetPositionAndRotation (Vector3.Lerp(InitPosition, playerEndTransform.position, time), Quaternion.Slerp(InitRotation, playerEndTransform.rotation, time)); yield return null; } //UIの表示 uiCanvas.SetActive(true); playerNumberUis[winPlayerNumber].SetActive(true); //エフェクトの開始 foreach (var effect in winEffects) { effect.Play(); } isEndResultAnimation = true; } /// <summary> /// 爆弾が降ってくるアニメーション /// </summary> /// <param name="index">降らせるプレイヤーのインデックス</param> IEnumerator BombAnimation(List<int> indexs) { float volume = BgmManager.Instance.GetVolume(); while (volume > 0.5f) { volume -= 0.01f; BgmManager.Instance.SetVolume(volume); yield return null; } List<GameObject> bombs = new List<GameObject>(); foreach (var index in indexs) { Vector3 pos = players[index].transform.position; //爆弾の高さ pos.y = 20; bombs.Add(Instantiate(resultBombObject, pos, Quaternion.identity)); //while (bomb != null) yield return null; Destroy(players[index], 3); } bool allBombDestroy = false; while (!allBombDestroy) { volume -= 0.01f; BgmManager.Instance.SetVolume(volume); allBombDestroy = true; foreach (var bomb in bombs) { if (bomb != null) { allBombDestroy = false; break; } } yield return null; } yield return new WaitForSeconds(1); } IEnumerator BgmVolumeGradation(float gradationSpeed) { float volume = BgmManager.Instance.GetVolume(); while (volume < 0.8f) { volume += gradationSpeed; BgmManager.Instance.SetVolume(volume); yield return null; } } }
using System; using UIKit; using Aquamonix.Mobile.IOS.UI; using Aquamonix.Mobile.Lib.Utilities; namespace Aquamonix.Mobile.IOS.Views { public class AquamonixLabel : UILabel { public AquamonixLabel() : base() { ExceptionUtility.Try(() => { this.LineBreakMode = UILineBreakMode.TailTruncation; }); } public AquamonixLabel(FontWithColor fontWithColor) : this() { ExceptionUtility.Try(() => { this.SetFontAndColor(fontWithColor); }); } public void EnforceMaxWidth(int maxWidth) { ExceptionUtility.Try(() => { this.EnforceMaxWidth((nfloat)maxWidth); }); } public void EnforceMaxWidth(nfloat maxWidth) { ExceptionUtility.Try(() => { if (this.Frame.Width > maxWidth) this.SetFrameWidth(maxWidth); }); } public void EnforceMaxXCoordinate(int maxX) { this.EnforceMaxXCoordinate((nfloat)maxX); } public void EnforceMaxXCoordinate(nfloat maxX) { this.EnforceMaxWidth(maxX - this.Frame.X); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InvoiceNet.Data { public class SqlDataReader : IDataReader { IDataReader m_dataReader; #region Properties public object this[string name] { get { return m_dataReader[name]; } } public object this[int i] { get { return m_dataReader[i]; } } public int Depth { get { return m_dataReader.Depth; } } public int FieldCount { get { return m_dataReader.FieldCount; } } public bool IsClosed { get { return m_dataReader.IsClosed; } } public int RecordsAffected { get { return m_dataReader.RecordsAffected; } } #endregion #region Methods public void Close() { m_dataReader.Close(); } public void Dispose() { if (m_dataReader != null) { if (!m_dataReader.IsClosed) { m_dataReader.Close(); } m_dataReader.Dispose(); m_dataReader = null; } } public bool GetBoolean(int i) { return m_dataReader.GetBoolean(i); } public bool GetBoolean(String name) { return GetBoolean(GetOrdinal(name)); } public byte GetByte(int i) { return m_dataReader.GetByte(i); } public byte GetByte(String name) { return GetByte(GetOrdinal(name)); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { return m_dataReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length); } public long GetBytes(String name, long fieldOffset, byte[] buffer, int bufferoffset, int length) { return GetBytes(GetOrdinal(name), fieldOffset, buffer, bufferoffset, length); } public char GetChar(int i) { return m_dataReader.GetChar(i); } public char GetChar(String name) { return GetChar(GetOrdinal(name)); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { return m_dataReader.GetChars(i, fieldoffset, buffer, bufferoffset, length); } public long GetChars(String name, long fieldoffset, char[] buffer, int bufferoffset, int length) { return GetChars(GetOrdinal(name), fieldoffset, buffer, bufferoffset, length); } public IDataReader GetData(int i) { return m_dataReader.GetData(i); } public IDataReader GetData(String name) { return GetData(GetOrdinal(name)); } public string GetDataTypeName(int i) { return m_dataReader.GetDataTypeName(i); } public string GetDataTypeName(String name) { return GetDataTypeName(GetOrdinal(name)); } public DateTime GetDateTime(int i) { return m_dataReader.GetDateTime(i); } public DateTime GetDateTime(String name) { return GetDateTime(GetOrdinal(name)); } public decimal GetDecimal(int i) { return m_dataReader.GetDecimal(i); } public decimal GetDecimal(String name) { return GetDecimal(GetOrdinal(name)); } public double GetDouble(int i) { return m_dataReader.GetDouble(i); } public double GetDouble(String name) { return GetDouble(GetOrdinal(name)); } public Type GetFieldType(int i) { return m_dataReader.GetFieldType(i); } public Type GetFieldType(String name) { return GetFieldType(GetOrdinal(name)); } public float GetFloat(int i) { return m_dataReader.GetFloat(i); } public float GetFloat(String name) { return GetFloat(GetOrdinal(name)); } public Guid GetGuid(int i) { return m_dataReader.GetGuid(i); } public Guid GetGuid(String name) { return GetGuid(GetOrdinal(name)); } public short GetInt16(int i) { return m_dataReader.GetInt16(i); } public short GetInt16(String name) { return GetInt16(GetOrdinal(name)); } public int GetInt32(int i) { return m_dataReader.GetInt32(i); } public int GetInt32(String name) { return GetInt32(GetOrdinal(name)); } public long GetInt64(int i) { return m_dataReader.GetInt64(i); } public long GetInt64(String name) { return GetInt64(GetOrdinal(name)); } public UInt16 GetUInt16(int i) { return Convert.ToUInt16(m_dataReader.GetValue(i)); } public UInt16 GetUInt16(String name) { return GetUInt16(GetOrdinal(name)); } public UInt32 GetUInt32(int i) { return Convert.ToUInt32(m_dataReader.GetValue(i)); } public UInt32 GetUInt32(String name) { return GetUInt32(GetOrdinal(name)); } public UInt64 GetUInt64(int i) { return Convert.ToUInt64(m_dataReader.GetValue(i)); } public UInt64 GetUInt64(String name) { return GetUInt64(GetOrdinal(name)); } public string GetName(int i) { return m_dataReader.GetName(i); } public int GetOrdinal(string name) { return m_dataReader.GetOrdinal(name); } public DataTable GetSchemaTable() { return m_dataReader.GetSchemaTable(); } public string GetString(int i) { return m_dataReader.GetString(i); } public string GetString(String name) { return GetString(GetOrdinal(name)); } public object GetValue(int i) { return m_dataReader.GetValue(i); } public object GetValue(String name) { return GetValue(GetOrdinal(name)); } public int GetValues(object[] values) { return m_dataReader.GetValues(values); } public bool IsDBNull(int i) { return m_dataReader.IsDBNull(i); } public bool IsDBNull(String name) { return IsDBNull(GetOrdinal(name)); } public bool NextResult() { return m_dataReader.NextResult(); } public bool Read() { return m_dataReader.Read(); } #endregion #region Constructor internal SqlDataReader(IDataReader dataReader) { m_dataReader = dataReader; } #endregion } }
// Copyright (c) Bruno Brant. All rights reserved. namespace RestLittle.UI.Models { /// <summary> /// The status of the user. /// </summary> public enum UserStatus { /// <summary> /// User has been working for more than the max. time. /// </summary> Tired, /// <summary> /// User is rested and is active. /// </summary> Working, /// <summary> /// User is resting (away from the computer). /// </summary> Resting, } }
namespace Ingen.Network { public interface ICryptoService { byte[] Encrypt(byte[] input); byte[] Decrypt(byte[] input); } }
namespace WinAppDriver { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; internal class Server { private static ILogger logger = Logger.GetLogger("WinAppDriver"); private RequestManager requestManager; public Server(RequestManager requestManager) { this.requestManager = requestManager; } public void Start() { var listener = new HttpListener(); listener.Prefixes.Add("http://+:4444/wd/hub/"); listener.Start(); logger.Info("WinAppDriver started on 0.0.0.0:4444 "); while (true) { var context = listener.GetContext(); var request = context.Request; var response = context.Response; this.HandleRequest(request, response); } } private void HandleRequest(HttpListenerRequest request, HttpListenerResponse response) { string method = request.HttpMethod; string path = request.Url.AbsolutePath; string body = new StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd(); logger.Debug("Request: {0} {1}\n{2}", method, path, body); ISession session = null; try { object result = this.requestManager.Handle(method, path, body, out session); this.ResponseResult(method, path, result, session, response); } catch (Exception ex) { logger.Error("Error occurred.", ex); this.ResponseException(method, path, ex, session, response); } } private void ResponseException( string method, string path, Exception ex, ISession session, HttpListenerResponse response) { string body = null; var httpStatus = HttpStatusCode.InternalServerError; string contentType = "application/json"; if (ex is FailedCommandException) { var message = new Dictionary<string, object> { { "sessionId", (session != null ? session.ID : null) }, { "status", ((FailedCommandException)ex).Code }, { "value", new Dictionary<string, object> { { "message", ex.Message } // TODO stack trace } } }; body = JsonConvert.SerializeObject(message); } else { httpStatus = HttpStatusCode.BadRequest; contentType = "text/plain"; body = ex.ToString(); } this.WriteResponse(response, httpStatus, contentType, body); } private void ResponseResult( string method, string path, object result, ISession session, HttpListenerResponse response) { var message = new Dictionary<string, object> { { "sessionId", (session != null ? session.ID : null) }, { "status", 0 }, { "value", result } }; string json = JsonConvert.SerializeObject(message); this.WriteResponse(response, HttpStatusCode.OK, "application/json", json); } private void WriteResponse( HttpListenerResponse response, HttpStatusCode httpStatus, string contentType, string body) { string bodyHead = body.Length > 200 ? body.Substring(0, 200) : body; logger.Debug("Response (Status: {0}, ContentType: {1}):\n{2}", httpStatus, contentType, bodyHead); response.StatusCode = (int)httpStatus; response.ContentType = contentType; response.ContentEncoding = Encoding.UTF8; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(body); response.ContentLength64 = buffer.Length; var output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtleManager_vsNPC : MonoBehaviour { // 外部から設定される public int[] playerChoicedHand = new int[3]; public int enemyChoicedHand; // 勝ち負け int[] WoL = new int[3]; GameObject[] playerHand = new GameObject[3]; GameObject enemyHand; void Start(){ // 両ハンドのオブジェクトを取得 for (int i=0; i<3; i++){ playerHand[i] = GameObject.Find("player"+ (i+1).ToString() +"Hand"); } enemyHand = GameObject.Find("enemyHand"); } // スタートの掛け声 void priming(){ // 画面中央に"じゃんけん"と表示 } // NPCの出手を決める void enemyRandomHand(){ // enemyの手をランダムで決める int h = Random.Range(1, 4); enemyChoicedHand = h; } // 全員の手を画面上に表示する void displayHands(){ } // 手の勝ち負けを判定する void WoLJudge(){ } // ダメージ計算 void damageCulc(){ float originalDmg; int dmg; for (int i=0; i<3; i++){ if (WoL[i] == 0){ break; } // 攻撃側と防御側のコンポーネント取得 CharaSet atkSide; CharaSet defSide; int handType; if (WoL[i] == 1){ atkSide = GameObject.Find("Player"+ (i+1).ToString()).GetComponent<CharaSet>(); defSide = GameObject.Find("Enemy").GetComponent<CharaSet>(); handType = playerChoicedHand[i]; } else { atkSide = GameObject.Find("Enemy").GetComponent<CharaSet>(); defSide = GameObject.Find("Player"+ (i+1).ToString()).GetComponent<CharaSet>(); handType = enemyChoicedHand; } // 必要数値の設定 int atkType = atkSide.type; int defType = defSide.type; int atk = atkSide.status[handType]; int pow = atkSide.skillpows[handType]; int rand = Random.Range(85, 101); int def = defSide.status[handType]; // 基本ダメージ originalDmg = atk**2 * pow * rand / (atk+def) / 10000.0f; // タイプ一致ボーナス if (atkType == handType){ originalDmg *= 1.2f; } // 弱点・耐性ボーナス int chemi = judgingDeadlock(atkType, defType); if (chemi == 1){ originalDmg *= 1.5f; } else if (chemi == 2){ originalDmg *= 0.8f; } // 小数点以下切り捨て dmg = (int)originalDmg; } } // 3すくみのa目線の勝ち負け判定(勝ち=1,負け=2,あいこ=0) int judgingDeadlock(int a, int b){ if (a == b){ return 0; } else if (a==1 && b==3){ // aがグー、bがパー return 2; } else if (a==3 && b==1){ // aがパー、bがグー return 1; } else if (a < b){ return 1; } else { return 2; } } public void judgement(){ // 頭上にタイプ画像を表示する //playerHand.GetComponent<Image>().sprite; //enemyHand.GetComponent<Image>().sprite; // 1秒待機 StartCoroutine ("waitSeconds", 1); // 中央に向かって移動スタート StartCoroutine ("movingHand"); } IEnumerator movingHand(){ // 両ハンドを中央に向かって動かす Vector2 pos; for (int i=0; i<80; i++){ pos = playerHand.transform.position; pos.x += 1; playerHand.transform.position = pos; pos = enemyHand.transform.position; pos.x -= 1; enemyHand.transform.position = pos; yield return 0; } // 勝負の判定 int judge; if (playerChoicedType == enemyChoicedType){ // あいこ judge = 0; } else if (playerChoicedType == 1 && enemyChoicedType == 3){ // プレイヤーがグー、エネミーがパー judge = 2; } else if (playerChoicedType == 3 && enemyChoicedType == 1){ // プレイヤーがパー、エネミーがグー judge = 1; } else if (playerChoicedType < enemyChoicedType){ // プレイヤーの勝ち judge = 1; } else { // プレイヤーの負け judge = 2; } // 勝ち負けによる処理 switch (judge) { case 1: // 勝ち // enemyHandを爆発させる enemyHand.GetComponent<Image>().sprite = GameObject.Find("bomb").GetComponent<SpriteRenderer>().sprite; for (int i=0; i<20; i++){ // playerHandをさらに動かす pos = playerHand.transform.position; pos.x += 1; playerHand.transform.position = pos; yield return 0; } // enemyHandのイメージを消す enemyHand.GetComponent<Image>().sprite = null; break; case 2: // 負け // playerHandを爆発させる playerHand.GetComponent<Image>().sprite = GameObject.Find("bomb").GetComponent<SpriteRenderer>().sprite; for (int i=0; i<20; i++){ // enemyHandをさらに動かす pos = enemyHand.transform.position; pos.x -= 1; enemyHand.transform.position = pos; yield return 0; } // playerHandのイメージを消す playerHand.GetComponent<Image>().sprite = null; break; case 0: // あいこ break; } } IEnumerator waitSeconds(float s){ yield return new WaitForSeconds (s); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data; using System.Reflection; namespace Rwd.Framework.IO { public static class File { /// <summary> /// Converts datatable to CSV file /// </summary> /// <param name="dt"></param> /// <param name="filePath"></param> public static void CreateCSVFile(DataTable dt, string filePath) { // Create the CSV file to which grid data will be exported. StreamWriter sw = new StreamWriter(filePath, false); // First we will write the headers. //DataTable dt = m_dsProducts.Tables[0]; int iColCount = dt.Columns.Count; for (int i = 0; i < iColCount; i++) { sw.Write(dt.Columns[i]); if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); // Now write all the rows. foreach (DataRow dr in dt.Rows) { for (int i = 0; i < iColCount; i++) { if (!Convert.IsDBNull(dr[i])) { sw.Write(dr[i].ToString()); } if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); } sw.Close(); } /// <summary> /// Converts IList to CSV file /// </summary> /// <param name="list"></param> /// <param name="filePath"></param> public static void CreateCSVFile<T>(IList<T> list, string filePath) { Type itemType = typeof(T); var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .OrderBy(p => p.Name); using (var writer = new StreamWriter(filePath)) { writer.WriteLine(string.Join(",", props.Select(p => p.Name))); foreach (var item in list) writer.WriteLine(string.Join(",", item.GetType().GetProperties().OrderBy(p => p.Name).Select(p => p.GetValue(item, null)))); } } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <returns></returns> public static byte[] ConvertStreamToByteArray(System.IO.Stream stream) { long originalPosition = 0; if (stream.CanSeek) { originalPosition = stream.Position; stream.Position = 0; } try { byte[] readBuffer = new byte[4096]; int totalBytesRead = 0; int bytesRead; while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += bytesRead; if (totalBytesRead == readBuffer.Length) { int nextByte = stream.ReadByte(); if (nextByte != -1) { byte[] temp = new byte[readBuffer.Length * 2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); readBuffer = temp; totalBytesRead++; } } } byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { if (stream.CanSeek) { stream.Position = originalPosition; } } } } }
using System; using System.Buffers; using System.Collections.Generic; using System.Text; using ByteData = System.Collections.Generic.List<System.ArraySegment<byte>>; namespace SAAS.FrameWork.Util.Pool { public class DataPool { #region Bytes public static byte[] BytesGet(int minimumLength) { //return new byte[minimumLength]; return ArrayPool<byte>.Shared.Rent(minimumLength); } public static void BytesReturn(byte[] data) { //return; ArrayPool<byte>.Shared.Return(data); } #endregion #region ArraySegmentByte public static ArraySegment<byte> ArraySegmentByteGet(int length) { return new ArraySegment<byte>(BytesGet(length), 0, length); } //public static void ArraySegmentByteReturn(ArraySegment<byte> data) //{ // BytesReturn(data.Array); //} #endregion #region ByteData public static ByteData ByteDataGet() { //return new ByteData(); return ObjectPool<ByteData>.Shared.Pop(); } internal static void ByteDataReturn(ByteData data) { //return; ObjectPool<ByteData>.Shared.Push(data); } #endregion } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.Rewards.Domain.Enums { /// <summary> /// 分润价格类型 /// </summary> [ClassProperty(Name = "分润价格类型")] public enum PriceType { /// <summary> /// 售价 /// </summary> [Display(Name = "销售价(商品Sku销售价)")] [LabelCssClass(BadgeColorCalss.Warning)] Price = 0, /// <summary> /// 分润 /// </summary> [Display(Name = "分润价(商品sku分润价)")] [LabelCssClass(BadgeColorCalss.Warning)] FenRun = 1, /// <summary> /// 商品数 /// </summary> [Display(Name = "商品数(订单商品总数)")] [LabelCssClass(BadgeColorCalss.Warning)] ProductNum = 3, /// <summary> /// 订单数 /// </summary> [Display(Name = "订单数(通常基数为1)")] [LabelCssClass(BadgeColorCalss.Warning)] OrderNum = 4, /// <summary> /// 虚拟资产服务费 /// 订单使用虚拟资产支付时候,产生的现金服务费,服务费比例在货币类型管理处设置 /// </summary> [Display(Name = "虚拟资产服务费")] [LabelCssClass(BadgeColorCalss.Warning)] OrderFeeAmount = 5 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConchScript : MonoBehaviour { public GameObject anchor; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public GameObject GetAnchor() { return anchor; } }
using System; using UnityEngine; using UnityEngine.UI; namespace RPG.Resources { public class HealthDisplay : MonoBehaviour { Health health; private Text healthText; private void Awake() { health = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>(); healthText = GetComponent<Text>(); } private void Update() { healthText.text = string.Format("{0:0.0}%",health.GetPercentage()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace Sharp.Pipeline.Example { public static class ConsoleHelp { public static void Help(IEnumerable<MethodInfo> methods) { Console.WriteLine("Valid Commands"); foreach (var m in methods) { var attribs = (DescriptionAttribute[])m.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attribs != null && attribs.Length > 0) { Console.ForegroundColor = ConsoleColor.Green; Console.Write(m.Name); ParameterInfo[] parm = m.GetParameters(); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("("); for (int i = 0; i < parm.Length; i++) { if (i > 0) Console.Write(", "); Console.Write("({0}){1}", parm[i].ParameterType.Name, parm[i].Name); } Console.Write(")"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\n\t{0}", attribs[0].Description); } } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2021 { public class Problem04 : AdventOfCodeBase { private List<int> _randoms; private List<int[,]> _boards; private List<bool[,]> _finals; private Dictionary<int, List<Func<int>>> _hash; public override string ProblemName { get { return "Advent of Code 2021: 04"; } } public override string GetAnswer() { GetRandomsAndBoards(Input()); return Answer2().ToString(); } private int Answer1() { InitializeFinals(); BuildHash(); FindFirstBoard(); return Score(); } private int Answer2() { InitializeFinals(); BuildHash(); FindLastBoard(); return Score(); } private void FindFirstBoard() { bool stop = false; foreach (var random in _randoms) { _lastRandom = random; var changed = new List<int>(); _hash[random].ForEach(x => { changed.Add(x()); }); foreach (var x in changed) { stop = CheckBoard(x); if (stop) { break; } } if (stop) { break; } } } private void FindLastBoard() { var winners = new HashSet<int>(); bool stop = false; foreach (var random in _randoms) { _lastRandom = random; var changed = new List<int>(); _hash[random].ForEach(x => { changed.Add(x()); }); foreach (var x in changed) { if (!winners.Contains(x)) { var result = CheckBoard(x); if (result) { winners.Add(x); if (winners.Count == _boards.Count) { stop = true; break; } } } } if (stop) { break; } } } private int _winner; private int _lastRandom; private bool CheckBoard(int index) { var final = _finals[index]; var counts = new int[10]; for (int count = 0; count <= 4; count++) { if (final[0, count]) counts[0]++; if (final[1, count]) counts[1]++; if (final[2, count]) counts[2]++; if (final[3, count]) counts[3]++; if (final[4, count]) counts[4]++; if (final[count, 0]) counts[5]++; if (final[count, 1]) counts[6]++; if (final[count, 2]) counts[7]++; if (final[count, 3]) counts[8]++; if (final[count, 4]) counts[9]++; } foreach (var count in counts) { if (count == 5) { _winner = index; return true; } } return false; } private int Score() { var board = _boards[_winner]; var final = _finals[_winner]; int sum = 0; for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { if (!final[x, y]) { sum += board[x, y]; } } } return sum * _lastRandom; } private void InitializeFinals() { _finals = new List<bool[,]>(); _boards.ForEach(x => _finals.Add(new bool[5, 5])); } private void BuildHash() { _hash = new Dictionary<int, List<Func<int>>>(); foreach (var num in _randoms) { if (!_hash.ContainsKey(num)) { var hash = new List<Func<int>>(); for (int boardIndex = 0; boardIndex < _boards.Count; boardIndex++) { var board = _boards[boardIndex]; for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { if (board[x, y] == num) { int result = boardIndex; int subX = x; int subY = y; hash.Add(() => { _finals[result][subX, subY] = true; return result; }); } } } } _hash.Add(num, hash); } } } private void GetRandomsAndBoards(List<string> input) { _randoms = input[0].Split(',').Select(x => Convert.ToInt32(x)).ToList(); _boards = new List<int[,]>(); int index = 2; do { var board = new int[5, 5]; for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { var split = Convert.ToInt32(new string(new char[2] { input[index][x * 3], input[index][x * 3 + 1] })); board[x, y] = split; } index++; } _boards.Add(board); index++; } while (index < input.Count); } private List<string> Input_Test1() { return new List<string>() { "7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1", "", "22 13 17 11 0", " 8 2 23 4 24", "21 9 14 16 7", " 6 10 3 18 5", " 1 12 20 15 19", "", " 3 15 0 2 22", " 9 18 13 17 5", "19 8 7 25 23", "20 11 10 24 4", "14 21 16 12 6", "", "14 21 17 24 4", "10 16 15 9 19", "18 8 23 26 20", "22 11 13 6 5", " 2 0 12 3 7" }; } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Imaging; namespace HabMap.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Dummy columns for layers 0 and 1: ColumnDefinition column1CloneForLayer0; public MainWindow() { InitializeComponent(); // Initialize the dummy columns used when docking: column1CloneForLayer0 = new ColumnDefinition(); column1CloneForLayer0.SharedSizeGroup = "column1"; } // Toggle between docked and undocked states (Pane 1) public void SolutionExplorerPin_Click(object sender, RoutedEventArgs e) { if (SolutionExplorerButton.Visibility == Visibility.Collapsed) UndockPane(); else DockPane(); } // Show Pane 1 when hovering over its button public void SolutionExplorerButton_MouseEnter(object sender, RoutedEventArgs e) { layer1.Visibility = Visibility.Visible; } // Hide any undocked panes when the mouse enters Layer 0 public void layer0_MouseEnter(object sender, RoutedEventArgs e) { if (SolutionExplorerButton.Visibility == Visibility.Visible) layer1.Visibility = Visibility.Collapsed; } // Docks a pane, which hides the corresponding pane button public void DockPane() { SolutionExplorerButton.Visibility = Visibility.Collapsed; // Add the cloned column to layer 0: layer0.ColumnDefinitions.Add(column1CloneForLayer0); } // Undocks a pane, which reveals the corresponding pane button public void UndockPane() { layer1.Visibility = Visibility.Collapsed; SolutionExplorerButton.Visibility = Visibility.Visible; // Remove the cloned columns from layers 0 and 1: layer0.ColumnDefinitions.Remove(column1CloneForLayer0); } private void TabablzControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { MessageBox.Show("Testing"); } } }
namespace Forca.Repositorio.Migrations { using System; using System.Data.Entity.Migrations; public partial class RetirandoEntidadeRanking : DbMigration { public override void Up() { DropForeignKey("dbo.Ranking", "Jogador_Id", "dbo.Jogador"); DropIndex("dbo.Ranking", new[] { "Jogador_Id" }); AddColumn("dbo.Jogador", "Dificuldade", c => c.Int(nullable: false)); DropTable("dbo.Ranking"); } public override void Down() { CreateTable( "dbo.Ranking", c => new { Id = c.Int(nullable: false, identity: true), Pontos = c.Int(nullable: false), Dificuldade = c.Int(nullable: false), Jogador_Id = c.Int(), }) .PrimaryKey(t => t.Id); DropColumn("dbo.Jogador", "Dificuldade"); CreateIndex("dbo.Ranking", "Jogador_Id"); AddForeignKey("dbo.Ranking", "Jogador_Id", "dbo.Jogador", "Id"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Demon : MonoBehaviour { public Transform attackPos; public LayerMask whatIsEnemies; public Animator attackAnim; [Space] [Header("Demon status :")] public static bool IsDead; public int enemyHandled; private float timeBtwAttack; [Space] [Header("Demon attributes :")] public float attackSpeed; public float attackRange; public int damage; public float healthPoints; public int enemyThatDemonCanHandle = 3; public float defense; public float hpRegenBy2Seconds; [Space] [Header("Unity Stuff :")] public Image hpBar; private float startingHp; private bool isCoroutineExecuting = false; public GameObject blood; public bool isAttacking = false; // Start is called before the first frame update void Start() { enemyHandled = 0; IsDead = false; startingHp = healthPoints; attackAnim.SetFloat("attackSpeed", attackSpeed); } // Update is called once per frame void Update() { Regenaration(); if (Input.GetKeyDown(KeyCode.Space)){ //attack if (timeBtwAttack == 0) { StartCoroutine(Attack(1 / attackSpeed)); } } if(healthPoints <= 0) //if the demon/player is dead --> GameOver { IsDead = true; } } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(attackPos.position, attackRange); } private IEnumerator Attack(float startTimeBtwAttack) { if (isCoroutineExecuting) { yield break; } isCoroutineExecuting = true; timeBtwAttack = startTimeBtwAttack; attackAnim.SetTrigger("attack"); isAttacking = true; Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies); for (int i = 0; i < enemiesToDamage.Length; i++) { enemiesToDamage[i].GetComponentInParent<Enemy>().TakeDamage(damage); } yield return new WaitForSeconds(startTimeBtwAttack); isAttacking = false; isCoroutineExecuting = false; timeBtwAttack = 0; } public void TakeDamage(float damage) { float realDamage = damage - defense; if(realDamage < 0) { realDamage = 0; } healthPoints -= realDamage; GameObject _blood = (GameObject)Instantiate(blood, transform.position, transform.rotation); Destroy(_blood, 2); hpBar.fillAmount = healthPoints / startingHp; } public void Regenaration() { if(healthPoints < startingHp) { healthPoints += hpRegenBy2Seconds * Time.deltaTime * 0.5f; hpBar.fillAmount = healthPoints / startingHp; } } }
using System; using System.Collections.Generic; using System.Net; using System.Text; namespace FiiiChain.DataAgent { public class P2PNode { public string IP { get; set; } public int Port { get; set; } public bool IsConnected { get; set; } public long LatestHeartbeat { get; set; } public long ConnectedTime { get; set; } public bool IsTrackerServer { get; set; } } }
// <copyright file="DependencyMocker.cs" company="Morten Larsen"> // Copyright (c) Morten Larsen. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // </copyright> using System.IO.Abstractions; using System.Net; using System.Net.Http; using System.Threading; using Microsoft.AspNetCore.Hosting; using Moq; namespace AspNetWebpack.AssetHelpers.Testing { /// <summary> /// Static functions for mocking common dependencies. /// </summary> public static class DependencyMocker { /// <summary> /// Mock IWebHostEnvironment. /// </summary> /// <param name="environmentName">The environment name.</param> /// <returns>The WebHostEnvironment object.</returns> public static Mock<IWebHostEnvironment> GetWebHostEnvironment(string environmentName) { var webHostEnvironmentMock = new Mock<IWebHostEnvironment>(); webHostEnvironmentMock .SetupGet(x => x.EnvironmentName) .Returns(environmentName); webHostEnvironmentMock .SetupGet(x => x.WebRootPath) .Returns(TestValues.WebRootPath); return webHostEnvironmentMock; } /// <summary> /// Mock IFileSystem. /// </summary> /// <param name="fileContent">The response content of ReadAllText.</param> /// <returns>The FileSystem object.</returns> public static Mock<IFileSystem> GetFileSystem(string fileContent) { var fileSystemMock = new Mock<IFileSystem>(); fileSystemMock .Setup(x => x.File.ReadAllTextAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .ReturnsAsync(fileContent); return fileSystemMock; } /// <summary> /// Mock IHttpClientFactory. /// </summary> /// <param name="httpStatusCode">The response status code.</param> /// <param name="content">The response content.</param> /// <param name="json">If the response should be json.</param> /// <returns>The HttpClientFactory object.</returns> public static Mock<IHttpClientFactory> GetHttpClientFactory(HttpStatusCode httpStatusCode, string content = "", bool json = false) { var httpClientFactory = new Mock<IHttpClientFactory>(); httpClientFactory .Setup(x => x.CreateClient(It.IsAny<string>())) .Returns<string>(_ => new HttpClient(new HttpMessageHandlerStub(httpStatusCode, content, json))); return httpClientFactory; } /// <summary> /// Mock ISharedSettings. /// </summary> /// <param name="environmentName">The environment name.</param> /// <returns>The SharedSettings object.</returns> public static Mock<ISharedSettings> GetSharedSettings(string environmentName) { var isDevelopment = environmentName == TestValues.Development; var sharedSettings = new Mock<ISharedSettings>(); sharedSettings .SetupGet(x => x.DevelopmentMode) .Returns(isDevelopment); sharedSettings .SetupGet(x => x.AssetsDirectoryPath) .Returns(isDevelopment ? "https://domain/assets/" : "/Some/Path/To/Assets/"); sharedSettings .SetupGet(x => x.AssetsWebPath) .Returns(TestValues.AssetsWebPath); sharedSettings .SetupGet(x => x.ManifestPath) .Returns(isDevelopment ? "https://domain/manifest.json" : "/Some/Path/To/Manifest.json"); return sharedSettings; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Projeto.Models; namespace Projeto.Data.Maps { public class ClienteMap : IEntityTypeConfiguration<Cliente> { public void Configure(EntityTypeBuilder<Cliente> builder) { builder.ToTable("Cliente"); builder.Property(x => x.Id); builder.Property(x => x.Nome) .IsRequired() .HasMaxLength(120) .HasColumnType("varchar(120)"); builder.Property(x => x.Cpf) .IsRequired() .HasMaxLength(11) .HasColumnType("char(11)"); builder.Property(x => x.DataNascimento) .HasColumnType("date"); builder.HasKey(x => x.Id); } } }
 using AutoMapper; using CarRental.API.BL.Models.Prices; using CarRental.API.DAL.DataServices.Prices; using CarRental.API.DAL.Entities; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace CarRental.API.BL.Services.Prices { public class PriceService : IPriceService { private readonly IMapper _mapper; private readonly IPriceDataService _priceDataService; public PriceService(IMapper mapper, IPriceDataService priceDataService) { _mapper = mapper; _priceDataService = priceDataService; } public async Task<IEnumerable<PriceModel>> GetAllAsync() { var prices = await _priceDataService.GetAllAsync(); return _mapper.Map<IEnumerable<PriceModel>>(prices); } public async Task<IEnumerable<DetailedPrices>> GetDetailedPrices() { var prices = await _priceDataService.GetDetailedPrices(); return _mapper.Map<IEnumerable<DetailedPrices>>(prices); } public async Task<PriceModel> GetAsync(Guid id) { var price = await _priceDataService.GetAsync(id); return _mapper.Map<PriceModel>(price); } public async Task<IEnumerable<CarPrice>> GetCarPriceAsync(Guid id) { var price = await _priceDataService.GetCarPriceAsync(id); return _mapper.Map<IEnumerable<CarPrice>>(price); } public async Task<PriceItem> CreateAsync(CreatePriceModel item) { var price = _mapper.Map<PriceItem>(item); return await _priceDataService.CreateAsync(price); } public async Task<PriceItem> UpsertAsync(PriceModel item) { var price = _mapper.Map<PriceItem>(item); return await _priceDataService.UpsertAsync(price); } public async Task<PriceItem> DeleteAsync(Guid id) { return await _priceDataService.DeleteAsync(id); } } }
using gView.Core.Framework.Exceptions; using gView.Framework.Security; using gView.Security.Framework; using gView.Server.AppCode; using gView.Server.Extensions; using gView.Server.Services.MapServer; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace gView.Server.Services.Security { public class LoginManager { private readonly MapServiceManager _mapServerService; private readonly EncryptionCertificateService _encryptionCertService; public LoginManager(MapServiceManager mapServerService, EncryptionCertificateService encryptionCertService) { _mapServerService = mapServerService; _encryptionCertService = encryptionCertService; } #region Manager Logins public AuthToken GetManagerAuthToken(string username, string password, int exipreMinutes = 30, bool createIfFirst = false) { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/manage"); if (createIfFirst && di.GetFiles().Count() == 0) { CreateLogin(di.FullName, username.ToLower(), password); _encryptionCertService.GetCertificate("crypto0"); // Create the Service if not exits } return CreateAuthToken(di.FullName, username, password, AppCode.AuthToken.AuthTypes.Manage, exipreMinutes); } public bool HasManagerLogin() { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/manage"); return di.Exists && di.GetFiles("*.lgn").Length > 0; } public IEnumerable<string> GetMangeUserNames() { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/manage"); if (di.Exists) { return di.GetFiles("*.lgn").Select(f => f.Name.Substring(0, f.Name.Length - f.Extension.Length)); } return new string[0]; } #endregion #region Token Logins public void CreateTokenLogin(string username, string password) { if (GetManageAndTokenUsernames().Where(u => username.Equals(u, StringComparison.InvariantCultureIgnoreCase)).Count() > 0) { throw new MapServerException("User '" + username + "' already exists"); } var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/token"); var fi = new FileInfo(di.FullName + "/" + username + ".lgn"); if (fi.Exists) { throw new MapServerException("User '" + username + "' already exists"); } CreateLogin(di.FullName, username, password); } public void ChangeTokenUserPassword(string username, string newPassword) { newPassword.ValidatePassword(); var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/token"); var fi = new FileInfo(di.FullName + "/" + username + ".lgn"); if (!fi.Exists) { throw new MapServerException("User '" + username + "' do not exists"); } var hashedPassword = SecureCrypto.Hash64(newPassword, username); File.WriteAllText(fi.FullName, hashedPassword); } public IEnumerable<string> GetTokenUsernames() { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/token"); if (di.Exists) { return di.GetFiles("*.lgn").Select(f => f.Name.Substring(0, f.Name.Length - f.Extension.Length)); } return new string[0]; } public AuthToken GetAuthToken(string username, string password, int expireMinutes = 30) { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/token"); return CreateAuthToken(di.FullName, username, password, AppCode.AuthToken.AuthTypes.Tokenuser, expireMinutes); } public AuthToken CreateUserAuthTokenWithoutPasswordCheck(string username, int expireMinutes = 30) { var di = new DirectoryInfo(_mapServerService.Options.LoginManagerRootPath + "/token"); return CreateAuthTokenWithoutPasswordCheck(di.FullName, username, AppCode.AuthToken.AuthTypes.Tokenuser, expireMinutes); } #endregion public IEnumerable<string> GetManageAndTokenUsernames() { List<string> names = new List<string>(); names.AddRange(GetMangeUserNames()); names.AddRange(GetTokenUsernames()); return names; } #region Request public string LoginUsername(HttpRequest request) { try { return LoginAuthToken(request).Username; } catch (Exception) { return String.Empty; } } public bool IsManageUser(HttpRequest request) { try { var loginAuthToken = LoginAuthToken(request); return loginAuthToken != null && loginAuthToken.AuthType == AuthToken.AuthTypes.Manage; } catch (Exception) { return false; } } public AuthToken LoginAuthToken(HttpRequest request) { AuthToken authToken = null; try { #region From Token string token = request.Query["token"]; if (String.IsNullOrWhiteSpace(token) && request.HasFormContentType) { try { token = request.Form["token"]; } catch { } } if (!String.IsNullOrEmpty(token)) { return authToken = _encryptionCertService.FromToken(token); } #endregion #region From Cookie string cookie = request.Cookies[Globals.AuthCookieName]; if (!String.IsNullOrWhiteSpace(cookie)) { try { return authToken = _encryptionCertService.FromToken(cookie); } catch (System.Security.Cryptography.CryptographicException) { return authToken = new AuthToken() { Username = String.Empty }; } } #endregion #region Authorization Header if (!String.IsNullOrEmpty(request.Headers["Authorization"])) { var userPwd = request.Headers["Authorization"].ToString().FromAuthorizationHeader(); var path = _mapServerService.Options.LoginManagerRootPath + "/token"; return authToken = CreateAuthToken(path, userPwd.username, userPwd.password, AuthToken.AuthTypes.Tokenuser); } #endregion return authToken = new AuthToken() { Username = String.Empty }; } finally { if (authToken == null || authToken.IsExpired) { throw new InvalidTokenException(); } } } public AuthToken GetAuthToken(HttpRequest request) { return LoginAuthToken(request); } #endregion #region Helper private AuthToken CreateAuthToken(string path, string username, string password, AuthToken.AuthTypes authType, int expireMiniutes = 30) { var fi = new FileInfo(path + "/" + username + ".lgn"); if (fi.Exists) { if (SecureCrypto.VerifyPassword(password, File.ReadAllText(fi.FullName), username)) { return new AuthToken(username, authType, new DateTimeOffset(DateTime.UtcNow.Ticks, new TimeSpan(0, 30, 0))); } } return null; } private AuthToken CreateAuthTokenWithoutPasswordCheck(string path, string username, AuthToken.AuthTypes authType, int expireMiniutes = 30) { var fi = new FileInfo(path + "/" + username + ".lgn"); if (fi.Exists) { return new AuthToken(username, authType, new DateTimeOffset(DateTime.UtcNow.Ticks, new TimeSpan(0, 30, 0))); } return null; } private void CreateLogin(string path, string username, string password) { username.ValidateUsername(); password.ValidatePassword(); var hashedPassword = SecureCrypto.Hash64(password, username); File.WriteAllText(path + "/" + username + ".lgn", hashedPassword); } #endregion } }
using ApplicationCore.Entities; using AutoMapper; using Web.ViewModels; namespace Web.Mapping { public class ProductProfile : Profile { public ProductProfile() { CreateMap<Product, ProductListItemVM>() .ForMember(dest => dest.Price, opt => opt.MapFrom(o => o.Price.ToString("C"))); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotNetBrightener.LinQToSqlBuilder.Adapter; using DotNetBrightener.LinQToSqlBuilder.Resolver.ExpressionTree; namespace DotNetBrightener.LinQToSqlBuilder.Resolver { /// <summary> /// Provides methods to perform resolution to SQL expressions for INSERT INTO query from given lambda expressions /// </summary> partial class LambdaResolver { /// <summary> /// Prepares an INSERT INTO method which expression to copy values from another table /// </summary> /// <typeparam name="T">The type of entity that associates to the table to insert record(s) to</typeparam> /// <param name="expression">The expression that generates the record to insert</param> public void Insert<T>(Expression<Func<T, T>> expression) { Insert<T>(expression.Body); } /// <summary> /// Prepares an INSERT INTO method which expression to copy values from another table /// </summary> /// <typeparam name="T">The type of entity that associates to the table to insert record(s) to</typeparam> /// <param name="expression">The expression that generates the record(s) to insert</param> public void Insert<T>(Expression<Func<T, IEnumerable<T>>> expression) { Insert<T>(expression.Body); } /// <summary> /// Performs an INSERT INTO method which expression to copy values from another table /// </summary> /// <typeparam name="TFrom">The type of entity associated to the source table</typeparam> /// <typeparam name="TTo">The type of entity associated to the destination table</typeparam> /// <param name="expression">The expression of taking values from TFrom and assigning to TTo</param> public void Insert<TFrom, TTo>(Expression<Func<TFrom, TTo>> expression) { Insert<TTo, TFrom>(expression.Body); } /// <summary> /// Append OUTPUT to the insert statement to get the output identity of the inserted record. /// </summary> /// <typeparam name="TEntity">The type of the inserting entity</typeparam> public void OutputInsertIdentity<TEntity>() { if (Builder.Operation != SqlOperations.Insert) throw new InvalidOperationException($"Cannot OUTPUT identity for the SQL statement that is not insert"); var fieldName = ""; var keyProp = typeof(TEntity).GetProperties() .FirstOrDefault(_ => _.GetCustomAttribute<KeyAttribute>() != null); if (keyProp == null) { keyProp = typeof(TEntity).GetProperty("Id"); } fieldName = keyProp?.Name; if (!string.IsNullOrEmpty(fieldName)) Builder.OutputInsertIdentity(fieldName); } private void Insert<T>(Expression expression) { var type = expression.GetType(); switch (expression.NodeType) { case ExpressionType.MemberInit: if (!(expression is MemberInitExpression memberInitExpression)) throw new ArgumentException("Invalid expression"); foreach (var memberBinding in memberInitExpression.Bindings) { if (memberBinding is MemberAssignment assignment) { Insert<T>(assignment); } } break; case ExpressionType.NewArrayInit: if (!(expression is NewArrayExpression newArrayExpression)) { throw new ArgumentException($"Invalid expression"); } foreach (var recordInitExpression in newArrayExpression.Expressions) { Builder.NextInsertRecord(); Insert<T>(recordInitExpression); } break; default: throw new ArgumentException("Invalid expression"); } } private void Insert<T>(MemberAssignment assignmentExpression) { var type = assignmentExpression.Expression.GetType(); if (assignmentExpression.Expression is ConstantExpression constantExpression) { var columnName = GetColumnName(assignmentExpression); var expressionValue = GetExpressionValue(constantExpression); Builder.AssignInsertField(columnName, expressionValue); return; } if (assignmentExpression.Expression is UnaryExpression unaryExpression) { var columnName = GetColumnName(assignmentExpression); var expressionValue = GetExpressionValue(unaryExpression); Builder.AssignInsertField(columnName, expressionValue); return; } if (assignmentExpression.Expression is MemberExpression memberExpression) { } else { } } private void Insert<TTo, TFrom>(Expression expression) { switch (expression.NodeType) { case ExpressionType.MemberInit: if (!(expression is MemberInitExpression memberInitExpression)) throw new ArgumentException("Invalid expression"); foreach (var memberBinding in memberInitExpression.Bindings) { if (memberBinding is MemberAssignment assignment) { Insert<TTo, TFrom>(assignment); } } break; default: throw new ArgumentException("Invalid expression"); } } private void Insert<TTo, TFrom>(MemberAssignment assignmentExpression) { var type = assignmentExpression.Expression.GetType(); if (assignmentExpression.Expression is ConstantExpression constantExpression) { var columnName = GetColumnName(assignmentExpression); var expressionValue = GetExpressionValue(constantExpression); Builder.AssignInsertField(columnName, expressionValue); return; } if (assignmentExpression.Expression is UnaryExpression unaryExpression) { var columnName = GetColumnName(assignmentExpression); var expressionValue = GetExpressionValue(unaryExpression); Builder.AssignInsertField(columnName, expressionValue); return; } if (assignmentExpression.Expression is MemberExpression memberExpression) { var columnName = GetColumnName(assignmentExpression); var node = ResolveQuery(memberExpression); BuildInsertAssignmentSql(columnName, (dynamic)node); return; } else { } } void BuildInsertAssignmentSql(string columnName, MemberNode sourceNode) { Builder.AssignInsertFieldFromSource(columnName, sourceNode.TableName, sourceNode.FieldName, _operationDictionary[ExpressionType.Equal]); } void BuildInsertAssignmentSql(string columnName, Node sourceNode) { throw new ArgumentException($"Unsupported resolution of Node type"); } } }
using Tweetinvi.Core.Injectinvi; using Tweetinvi.Core.Web; using Tweetinvi.Factories.Properties; using Tweetinvi.Models.DTO; namespace Tweetinvi.Factories { public interface IMessageFactoryQueryExecutor { // Get Existing Message IMessageDTO GetExistingMessage(long messageId); // Create Message IMessageDTO CreateMessage(string text, IUserDTO recipientDTO); } public class MessageFactoryQueryExecutor : IMessageFactoryQueryExecutor { private readonly ITwitterAccessor _twitterAccessor; private readonly IFactory<IMessageDTO> _messageDTOUnityFactory; public MessageFactoryQueryExecutor(ITwitterAccessor twitterAccessor, IFactory<IMessageDTO> messageDTOUnityFactory) { _twitterAccessor = twitterAccessor; _messageDTOUnityFactory = messageDTOUnityFactory; } // Get existing message public IMessageDTO GetExistingMessage(long messageId) { string query = string.Format(Resources.Message_GetMessageFromId, messageId); return _twitterAccessor.ExecuteGETQuery<IMessageDTO>(query); } // Create Message public IMessageDTO CreateMessage(string text, IUserDTO recipientDTO) { var messageDTO = _messageDTOUnityFactory.Create(); messageDTO.Text = text; messageDTO.Recipient = recipientDTO; return messageDTO; } } }
using System; using System.IO; using System.Security; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace ManagedUtilities { public class Crypto { public string EncryptString(string stringToEncrypt, string strKey) { byte[] key = { }; byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 }; try { key = Encoding.UTF8.GetBytes(strKey); DESCryptoServiceProvider desProvidr = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt); MemoryStream ms = new MemoryStream(); CryptoStream csstreamdata = new CryptoStream(ms, desProvidr.CreateEncryptor(key, IV), CryptoStreamMode.Write); csstreamdata.Write(inputByteArray, 0, inputByteArray.Length); csstreamdata.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { throw ex; } } public string DecryptString(string stringToDecrypt, string strKey) { byte[] key = { }; byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 }; stringToDecrypt = stringToDecrypt.Replace(" ", "+"); byte[] inputByteArray = new byte[stringToDecrypt.Length]; try { key = Encoding.UTF8.GetBytes(strKey); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(stringToDecrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { throw ex; } } public string TestCrypto(string testString, string key) { string strEncrypt = string.Empty; string strDecrypt = string.Empty; strEncrypt = EncryptString(testString, key); strDecrypt = DecryptString(strEncrypt, key); return strDecrypt; } public static void Main(String[] args) { //Console.Write(new Crypto().EncryptString("THIS IS A TEST", "M^K#Y$35")); Console.Write(new Crypto().DecryptString("uYWu53kY1J/+a9SxRFovL1IyPWAbu95MczJYsvtdvo5men4/a5M40TG/BO+kgbib7T3Kx3Xvy6zMs2ryoqPYU+9cYB0UVR09JK6zzv5QrSM/iofUlERgKyrg3HLzA42CNtkwBbJ+cQsE7AsoB9I2CnIMAPm0wcQu/yvK5GHjUoY+2dgDeG712kfQ65NTrCnADDLd5rQZyXwogLHvUSw9Cu9MFhpF2xn+bR51x0xV+KGP5smCkSZdO3RiBbnbBeu3L+ZNFRNmogKhEbFdSY6UJBLdKxj2viVJz84rMBZcj/g=", "M^K#Y$35")); Thread.Sleep(10000); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; using UnityEngine.SceneManagement; public enum MissionType { Hits, Hoops, } public class MissionController : MonoBehaviour { [SerializeField] private Missions missionSystem; private MissionComponent missionScript; [SerializeField] public Queue<MissionType> missions; [SerializeField] private GameObject[] resetObjects; // Start is called before the first frame update void Start() { missions = new Queue<MissionType>(); missions.Enqueue(MissionType.Hits); missions.Enqueue(MissionType.Hoops); UpdateMission(); resetObjects = new GameObject[2]; resetObjects[0] = GameObject.Find("ball"); resetObjects[1] = GameObject.Find("Player"); } void UpdateMission() { Debug.Log(missions.Count); switch (missions.Peek()) { case MissionType.Hits: missionScript = this.gameObject.AddComponent<Hits>(); break; case MissionType.Hoops: missionScript = this.gameObject.AddComponent<Hoops>(); break; } } public void FinishMission(bool succeeded, float time, int hits) { if (missions.Count > 0) { missionSystem.missionsFinished.Add(new Mission(missions.Peek(), succeeded, time, hits)); missions.Dequeue(); Destroy(missionScript); ResetObjects(); if (missions.Count > 0) { UpdateMission(); } else { SceneManager.LoadScene("Results"); } } } public void FinishMission(bool succeeded, float time) { if (missions.Count > 0) { missionSystem.missionsFinished.Add(new Mission(missions.Peek(), succeeded, time)); missions.Dequeue(); Destroy(missionScript); ResetObjects(); if (missions.Count > 0) { UpdateMission(); } else { SceneManager.LoadScene("Results"); } } } void ResetObjects() { if (resetObjects != null) { foreach (var obj in resetObjects) { obj.GetComponent<ResetScript>().ResetPosition(); } } GameObject.Find("Main Camera").GetComponent<CameraScript>().GoToPlayer(); GameObject.Find("Player").GetComponent<Animator>().Play("Idle"); } }
namespace sc80wffmex.GlassStructure { using System; using System.Collections.Specialized; using Glass.Mapper.Sc; using Sitecore.Mvc.Presentation; using Sitecore.Web; public class ContextSitecoreContext : IControllerSitecoreContext { private readonly ISitecoreContext _sitecoreContext; public ContextSitecoreContext(ISitecoreContext sitecoreContext) { this._sitecoreContext = sitecoreContext; } public T GetDataSource<T>() where T : class { string dataSource = RenderingContext.CurrentOrNull.Rendering.DataSource; if (String.IsNullOrEmpty(dataSource)) { return this._sitecoreContext.GetCurrentItem<T>(); //default(T); } if (dataSource.StartsWith("query:")) { string query = dataSource.Remove(0, 6); var item = PageContext.Current.Item.Axes.SelectSingleItem(query); if (item != null) return item.GlassCast<T>(); else return this._sitecoreContext.GetCurrentItem<T>(); //default(T); } else { Guid dataSourceId; return Guid.TryParse(dataSource, out dataSourceId) ? this._sitecoreContext.GetItem<T>(dataSourceId) : this._sitecoreContext.GetItem<T>(dataSource); } } public NameValueCollection GetRenderingParameters() { NameValueCollection parameters = WebUtil.ParseUrlParameters(RenderingContext.CurrentOrNull.Rendering["Parameters"]); if (parameters == null) { return null; } return parameters; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using CodingTest; namespace UnitTest { [TestClass] public class ValidBaseTest : ValidBase { public ValidBaseTest() : base("") { } /// <summary> /// Ensure HasValidChars method returns true when presented with /// a valid alphanumerric string. /// </summary> [TestMethod] public void ValidAlphaNumericChars() { Assert.IsTrue(HasValidChars("ajsdhjhdbj231235443bsjhbcjhb", true)); } /// <summary> /// Ensure HasValidChars method returns false when presented with /// an invalid alphanumerric string. /// </summary> [TestMethod] public void InvalidAlphaNumericChars() { Assert.IsFalse(HasValidChars("\\!£$%^@~{}:?>><)(**:-)(}-:", true)); } /// <summary> /// Ensure HasValidChars method returns true when presented with /// a valid numeric string. /// </summary> [TestMethod] public void ValidNumericChars() { Assert.IsTrue(HasValidChars("1234.56789", false)); } /// <summary> /// Ensure HasValidChars method returns true when presented with /// an invalid numerric string. /// </summary> [TestMethod] public void InvalidNumericChars() { Assert.IsFalse(HasValidChars("thisshouldfail-asithasinvalidchars.", false)); } } }
using System; using Microsoft.EntityFrameworkCore; namespace Orders.Models { public class OrdersContext : DbContext { public OrdersContext(DbContextOptions options) : base(options) { } public DbSet<Order> Orders { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Management_Plus { public partial class Claculator : Form { public Claculator() { InitializeComponent(); this.ControlBox = false; this.WindowState = FormWindowState.Normal; } private void Claculator_Load(object sender, EventArgs e) { this.WindowState = FormWindowState.Normal; this.TopMost = true; this.BringToFront(); this.KeyPreview = true; this.KeyDown += new KeyEventHandler(Claculator_KeyDown); } void Claculator_KeyDown(object sender, KeyEventArgs e) { } Double result = 0; String operation = ""; bool enter_value = false; private void Add_Click(object sender, EventArgs e) { } private void Number_Only(object sender, EventArgs e) { if (textBox1.Text.Length <= 13) { Button b = (Button)sender; if (textBox1.Text.Length >= 9) { textBox1.Font = new Font("Verdana", 15); } else { textBox1.Font = new Font("Verdana", 26); } if ((textBox1.Text == "0") || (enter_value)) textBox1.Text = ""; enter_value = false; if (b.Text == ".") { if (!textBox1.Text.Contains(".")) { textBox1.Text += b.Text; } } else { textBox1.Text += b.Text; } } } private void operator_Click(object sender, EventArgs e) { Button b = (Button)sender; if (textBox1.Text.Length >= 9) { textBox1.Font = new Font("Verdana", 15); } else { textBox1.Font = new Font("Verdana", 26); } if (result != 0) { Equal.PerformClick(); enter_value = true; operation = b.Text; lblshow.Text = result + " " + operation; } if (textBox1.Text.EndsWith(".")) { textBox1.Text += 0; } operation = b.Text; try { result = Double.Parse(textBox1.Text); } catch (Exception) { MessageBox.Show("First Enter any Number For Claculate ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information); } textBox1.Text = ""; lblshow.Text = System.Convert.ToString(result) + " " + operation; } private void Equal_Click(object sender, EventArgs e) { if (textBox1.Text.Length >= 9) { textBox1.Font = new Font("Verdana", 15); } else { textBox1.Font = new Font("Verdana", 26); } lblshow.Text = ""; if (textBox1.Text != "") { switch (operation) { case "+": textBox1.Text = (result + Double.Parse(textBox1.Text)).ToString(); break; case "-": textBox1.Text = (result - Double.Parse(textBox1.Text)).ToString(); break; case "*": textBox1.Text = (result * Double.Parse(textBox1.Text)).ToString(); break; case "/": textBox1.Text = (result / Double.Parse(textBox1.Text)).ToString(); break; default: break; } if (textBox1.Text.EndsWith(".")) { textBox1.Text += "0"; } result = Double.Parse(textBox1.Text); operation = ""; } else { textBox1.Text = result.ToString(); result = 0; } } private void bt_Clear_Click(object sender, EventArgs e) { lblshow.Text = "0"; textBox1.Text = "0"; result = 0; } private void bt_Remove_Click(object sender, EventArgs e) { if (textBox1.Text.Length >= 9) { textBox1.Font = new Font("Verdana", 15); } else { textBox1.Font = new Font("Verdana", 26); } if (textBox1.Text.Length > 0) { textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1); } if (textBox1.Text == "") { textBox1.Text = "0"; } } private void Mod_Click(object sender, EventArgs e) { this.Hide(); } private void Claculator_KeyDown_1(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.NumPad0) { this.Num0.PerformClick(); } else if (e.KeyCode == Keys.NumPad1) { this.Num1.PerformClick(); } else if (e.KeyCode == Keys.NumPad2) { this.Num2.PerformClick(); } else if (e.KeyCode == Keys.NumPad3) { this.Num3.PerformClick(); } else if (e.KeyCode == Keys.NumPad4) { this.Num4.PerformClick(); } else if (e.KeyCode == Keys.NumPad5) { this.Num5.PerformClick(); } else if (e.KeyCode == Keys.NumPad6) { this.Num6.PerformClick(); } else if (e.KeyCode == Keys.NumPad7) { this.Num7.PerformClick(); } else if (e.KeyCode == Keys.NumPad8) { this.Num8.PerformClick(); } else if (e.KeyCode == Keys.NumPad9) { this.Num9.PerformClick(); } else if (e.KeyCode == Keys.Back) { this.bt_Remove.PerformClick(); } else if (e.KeyCode == Keys.C) { this.bt_Clear.PerformClick(); } else if (e.KeyCode == Keys.Divide) { this.Divide.PerformClick(); } else if (e.KeyCode == Keys.Subtract) { this.Sup.PerformClick(); } else if (e.KeyCode == Keys.Insert) { this.Equal.PerformClick(); } else if (e.KeyCode == Keys.Add) { this.Add.PerformClick(); } else if (e.KeyCode == Keys.Escape) { base.Hide(); } else if (e.KeyCode == Keys.F9) { base.Hide(); } } } }
using UnityEngine; using System.Collections; public class BoostDesc { public Sprite buttonSprite; public Sprite introScreenSprite; public float effectiveTime; public string boostName; public TipConfig tipConfig; public BoostDesc(string boostName, string buttonImageName, string introScreenImageName, float effectiveTime, TipConfig tipConfig) { string path; path = "Textures/Boosts/" + buttonImageName; this.buttonSprite = Resources.Load<UnityEngine.Sprite>(path); path = "Textures/BoostIntros/" + introScreenImageName; this.introScreenSprite = Resources.Load<UnityEngine.Sprite>(path); this.effectiveTime = effectiveTime; this.boostName = boostName; this.tipConfig = tipConfig; } }
using BradescoPGP.Repositorio; using BradescoPGP.Web.Areas.Portabilidade.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace BradescoPGP.Web.Areas.Portabilidade.Servicos { public class UsuarioService : IUsuarioService { private readonly PGPEntities _context; public HashSet<Solicitacao> Solicitacao { get; } public UsuarioService(DbContext context) { _context = context as PGPEntities; } //public Usuario() //{ // this.Solicitacao = new HashSet<Solicitacao>(); //} public Usuario ObterUsuario(string matricula) { return _context.Usuario.FirstOrDefault(u => u.Matricula == matricula); } public string ObterNomeUsuario(string matricula) { return _context.Usuario.FirstOrDefault(u => u.Matricula == matricula)?.Nome; } public List<Usuario> ObterTodosUsuarios() { return _context.Usuario.ToList(); } } }
using System.Windows.Controls; namespace WPF.NewClientl.UI.Dialogs { /// <summary> /// SiginStatisticsDialog.xaml 的交互逻辑 /// </summary> public partial class ControlCenterDialog : UserControl { public ControlCenterDialog() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Machine.Specifications; using Moq; using MvcContrib.TestHelper; using ScoreSquid.Web.Controllers; using ScoreSquid.Web.Models; using ScoreSquid.Web.Tasks; using ScoreSquid.Web.Tests.Builders; namespace ScoreSquid.Web.Tests.Controllers { public class PredictionControllerTests { private static PredictionController controller; private static Mock<IPlayerTasks> mockPlayerTasks; Establish context = () => { var controllerBuilder = new TestControllerBuilder(); mockPlayerTasks = new Mock<IPlayerTasks>(); controller = new PredictionController(mockPlayerTasks.Object); controllerBuilder.InitializeController(controller); }; } [Subject(typeof(PredictionController), "LandingPageTests")] public class When_first_landing_on_the_predictions_page : PlayerControllerTests { private Machine.Specifications.It should_fetch_the_fixtures_for_the_logged_in_player = () => { var miniLeague = new MiniLeague(); var fixtures = miniLeague.MiniLeagueFixtures = new Collection<MiniLeagueFixture>(); fixtures.Add(new MiniLeagueFixture { MiniLeague = miniLeague, Fixtures = new Collection<Fixture> { new Fixture { HomeTeam = new Team { Division = new Division().BuildDefault() } } }}); var loggedInUser = new Player { MiniLeague = miniLeague }; }; } }
using System; using UBaseline.Shared.Node; using Uintra.Core.Search.Entities; namespace Uintra.Core.Search.Converters.SearchDocumentPanelConverter { public interface ISearchDocumentPanelConverter { Type Type { get; } SearchablePanel Convert(INodeViewModel panel); } public interface ISearchDocumentPanelConverter<in TPanel> : ISearchDocumentPanelConverter where TPanel : INodeViewModel { } }
using Crystal.Plot2D.Common; using System; using System.ComponentModel; using System.Globalization; using System.Windows; using System.Windows.Markup; namespace Crystal.Plot2D { /// <summary> /// Describes a rectangle in viewport or data coordinates. /// </summary> [Serializable] [ValueSerializer(typeof(DataRectSerializer))] [TypeConverter(typeof(DataRectConverter))] public struct DataRect : IEquatable<DataRect>, IFormattable { #region Ctors /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="rect"> /// Source rect. /// </param> public DataRect(Rect rect) { xMin = rect.X; yMin = rect.Y; width = rect.Width; height = rect.Height; } /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="size"> /// The size. /// </param> public DataRect(Size size) { if (size.IsEmpty) { this = emptyRect; } else { xMin = yMin = 0.0; width = size.Width; height = size.Height; } } /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="location">The location.</param> /// <param name="size">The size.</param> public DataRect(Point location, Size size) { if (size.IsEmpty) { this = emptyRect; } else { xMin = location.X; yMin = location.Y; width = size.Width; height = size.Height; } } /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="point1">The point1.</param> /// <param name="point2">The point2.</param> public DataRect(Point point1, Point point2) { xMin = Math.Min(point1.X, point2.X); yMin = Math.Min(point1.Y, point2.Y); width = Math.Max((double)(Math.Max(point1.X, point2.X) - xMin), 0); height = Math.Max((double)(Math.Max(point1.Y, point2.Y) - yMin), 0); } /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="point">The point.</param> /// <param name="vector">The vector.</param> public DataRect(Point point, Vector vector) : this(point, point + vector) { } /// <summary> /// Initializes a new instance of the <see cref="DataRect"/> struct. /// </summary> /// <param name="xMin">The minimal x.</param> /// <param name="yMin">The minimal y.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public DataRect(double xMin, double yMin, double width, double height) { if ((width < 0) || (height < 0)) { throw new ArgumentException(Strings.Exceptions.WidthAndHeightCannotBeNegative); } this.xMin = xMin; this.yMin = yMin; this.width = width; this.height = height; } #endregion #region Static /// <summary> /// Creates the DataRect from minimal and maximal 'x' and 'y' coordinates. /// </summary> /// <param name="xMin">The x min.</param> /// <param name="yMin">The y min.</param> /// <param name="xMax">The x max.</param> /// <param name="yMax">The y max.</param> /// <returns></returns> public static DataRect Create(double xMin, double yMin, double xMax, double yMax) => new(xMin, yMin, xMax - xMin, yMax - yMin); public static DataRect FromPoints(double x1, double y1, double x2, double y2) => new(new Point(x1, y1), new Point(x2, y2)); public static DataRect FromCenterSize(Point center, double width, double height) => new(center.X - width / 2, center.Y - height / 2, width, height); public static DataRect FromCenterSize(Point center, Size size) => FromCenterSize(center, size.Width, size.Height); public static DataRect Intersect(DataRect rect1, DataRect rect2) { rect1.Intersect(rect2); return rect1; } public static implicit operator DataRect(Rect rect) => new(rect); #endregion public Rect ToRect() => new(xMin, yMin, width, height); public void Intersect(DataRect rect) { if (!IntersectsWith(rect)) { this = Empty; return; } DataRect res = new(); double x = Math.Max(XMin, rect.XMin); double y = Math.Max(YMin, rect.YMin); res.width = Math.Max(Math.Min(XMax, rect.XMax) - x, 0.0); res.height = Math.Max(Math.Min(YMax, rect.YMax) - y, 0.0); res.xMin = x; res.yMin = y; this = res; } public bool IntersectsWith(DataRect rect) { if (IsEmpty || rect.IsEmpty) { return false; } return ((((rect.XMin <= XMax) && (rect.XMax >= XMin)) && (rect.YMax >= YMin)) && (rect.YMin <= YMax)); } private double xMin; private double yMin; private double width; private double height; /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty => width < 0; /// <summary> /// Gets the bottom. /// </summary> /// <value> /// The bottom. /// </value> public double YMin { get { return yMin; } set { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } yMin = value; } } /// <summary> /// Gets the maximal y value. /// </summary> /// <value> /// The top. /// </value> public double YMax => IsEmpty ? double.PositiveInfinity : yMin + height; /// <summary> /// Gets the minimal x value. /// </summary> /// <value> /// The left. /// </value> public double XMin { get { return xMin; } set { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } xMin = value; } } /// <summary> /// Gets the maximal x value. /// </summary> /// <value> /// The right. /// </value> public double XMax => IsEmpty ? double.PositiveInfinity : xMin + width; /// <summary> /// Gets or sets the location. /// </summary> /// <value> /// The location. /// </value> public Point Location { get => new(xMin, yMin); set { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } xMin = value.X; yMin = value.Y; } } public Point XMaxYMax => new(XMax, YMax); public Point XMinYMin => new(xMin, yMin); /// <summary> /// Gets or sets the size. /// </summary> /// <value>The size.</value> public Size Size { get { return IsEmpty ? Size.Empty : new Size(width, height); } set { if (value.IsEmpty) { this = emptyRect; } else { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } width = value.Width; height = value.Height; } } } public double Width { get { return width; } set { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } if (value < 0) { throw new ArgumentOutOfRangeException(Strings.Exceptions.DataRectSizeCannotBeNegative); } width = value; } } public double Height { get { return height; } set { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } if (value < 0) { throw new ArgumentOutOfRangeException(Strings.Exceptions.DataRectSizeCannotBeNegative); } height = value; } } private static readonly DataRect emptyRect = CreateEmptyRect(); public static DataRect Empty { get { return emptyRect; } } private static DataRect CreateEmptyRect() { DataRect rect = new(); rect.xMin = double.PositiveInfinity; rect.yMin = double.PositiveInfinity; rect.width = double.NegativeInfinity; rect.height = double.NegativeInfinity; return rect; } public static DataRect Infinite { get; } = new DataRect(double.MinValue / 2, double.MinValue / 2, double.MaxValue, double.MaxValue); #region Object overrides /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns> /// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is DataRect)) { return false; } DataRect other = (DataRect)obj; return Equals(other); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { if (IsEmpty) { return 0; } return xMin.GetHashCode() ^ width.GetHashCode() ^ yMin.GetHashCode() ^ height.GetHashCode(); } /// <summary> /// Returns the fully qualified type name of this instance. /// </summary> /// <returns> /// A <see cref="T:System.String"/> containing a fully qualified type name. /// </returns> public override string ToString() { if (IsEmpty) { return "Empty"; } return string.Format("({0};{1}) -> {2}*{3}", xMin, yMin, width, height); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="rect1">The rect1.</param> /// <param name="rect2">The rect2.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(DataRect rect1, DataRect rect2) { return rect1.Equals(rect2); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="rect1">The rect1.</param> /// <param name="rect2">The rect2.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(DataRect rect1, DataRect rect2) { return !rect1.Equals(rect2); } public static bool EqualEps(DataRect rect1, DataRect rect2, double eps) { double width = Math.Min(rect1.Width, rect2.Width); double height = Math.Min(rect1.Height, rect2.Height); return Math.Abs(rect1.XMin - rect2.XMin) < width * eps && Math.Abs(rect1.XMax - rect2.XMax) < width * eps && Math.Abs(rect1.YMin - rect2.YMin) < height * eps && Math.Abs(rect1.YMax - rect2.YMax) < height * eps; } #endregion #region IEquatable<DataRect> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(DataRect other) { if (IsEmpty) { return other.IsEmpty; } return xMin == other.xMin && width == other.width && yMin == other.yMin && height == other.height; } #endregion /// <summary> /// Determines whether this DataRect contains point with specified coordinates. /// </summary> /// <param name="x">The x coordinate of point.</param> /// <param name="y">The y coordinate of point.</param> /// <returns> /// <c>true</c> if contains point with specified coordinates; otherwise, <c>false</c>. /// </returns> public bool Contains(double x, double y) { if (IsEmpty) { return false; } return x >= xMin && x <= XMax && y >= yMin && y <= YMax; } public bool Contains(Point point) { return Contains(point.X, point.Y); } public bool Contains(DataRect rect) { if (IsEmpty || rect.IsEmpty) { return false; } return xMin <= rect.xMin && yMin <= rect.yMin && XMax >= rect.XMax && YMax >= rect.YMax; } public void Offset(Vector offsetVector) { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } xMin += offsetVector.X; yMin += offsetVector.Y; } public void Offset(double offsetX, double offsetY) { if (IsEmpty) { throw new InvalidOperationException(Strings.Exceptions.CannotModifyEmptyDataRect); } xMin += offsetX; yMin += offsetY; } public static DataRect Offset(DataRect rect, double offsetX, double offsetY) { rect.Offset(offsetX, offsetY); return rect; } internal void UnionFinite(DataRect rect) { if (!rect.IsEmpty) { if (rect.xMin.IsInfinite()) { rect.xMin = 0; } if (rect.yMin.IsInfinite()) { rect.yMin = 0; } if (rect.width.IsInfinite()) { rect.width = 0; } if (rect.height.IsInfinite()) { rect.height = 0; } } Union(rect); } public void Union(DataRect rect) { if (IsEmpty) { this = rect; return; } else if (!rect.IsEmpty) { double minX = Math.Min(xMin, rect.xMin); double minY = Math.Min(yMin, rect.yMin); if (rect.width == double.PositiveInfinity || width == double.PositiveInfinity) { width = double.PositiveInfinity; } else { double maxX = Math.Max(XMax, rect.XMax); width = Math.Max(maxX - minX, 0.0); } if (rect.height == double.PositiveInfinity || height == double.PositiveInfinity) { height = double.PositiveInfinity; } else { double maxY = Math.Max(YMax, rect.YMax); height = Math.Max(maxY - minY, 0.0); } xMin = minX; yMin = minY; } } public void Union(Point point) { Union(new DataRect(point, point)); } public static DataRect Union(DataRect rect, Point point) { rect.Union(point); return rect; } public static DataRect Union(DataRect rect1, DataRect rect2) { rect1.Union(rect2); return rect1; } internal string ConvertToString(string format, IFormatProvider provider) { if (IsEmpty) { return "Empty"; } char listSeparator = TokenizerHelper.GetNumericListSeparator(provider); return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", listSeparator, xMin, yMin, width, height); } /// <summary> /// Parses the specified string as a DataRect. /// </summary> /// <remarks> /// There are three possible string patterns, that are recognized as string representation of DataRect: /// 1) Literal string "Empty" - represents an DataRect.Empty rect; /// 2) String in format "d,d,d,d", where d is a floating-point number with '.' as decimal separator - is considered as a string /// of "XMin,YMin,Width,Height"; /// 3) String in format "d,d d,d", where d is a floating-point number with '.' as decimal separator - is considered as a string /// of "XMin,YMin XMax,YMax". /// </remarks> /// <param name="source">The source.</param> /// <returns>DataRect, parsed from the given input string.</returns> public static DataRect Parse(string source) { DataRect rect; IFormatProvider cultureInfo = CultureInfo.GetCultureInfo("en-us"); if (source == "Empty") { rect = Empty; } else { // format X,Y,Width,Height string[] values = source.Split(','); if (values.Length == 4) { rect = new DataRect( Convert.ToDouble(values[0], cultureInfo), Convert.ToDouble(values[1], cultureInfo), Convert.ToDouble(values[2], cultureInfo), Convert.ToDouble(values[3], cultureInfo) ); } else { // format XMin, YMin - XMax, YMax values = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); rect = Create( Convert.ToDouble(values[0], cultureInfo), Convert.ToDouble(values[1], cultureInfo), Convert.ToDouble(values[2], cultureInfo), Convert.ToDouble(values[3], cultureInfo) ); } } return rect; } #region IFormattable Members string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ConvertToString(format, formatProvider); } #endregion } }
namespace Visitor { public class UnSubscribeOperation : IOperation { public void apply(EmailNotification notification) { System.Console.WriteLine($"User email address {notification.EmailAddress} UnSubscribed to Email notification"); } public void apply(BannerNotification notification) { System.Console.WriteLine($"User {notification.PhoneModel} UnSubscribed to banner notification"); } public void apply(SmsNotification notification) { System.Console.WriteLine($"User phone number {notification.PhoneNumber} UnSubscribed to SMS notification"); } } }
#region using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using System.Globalization; using System.Collections; using System.IO; using Wpro.GSM.TelerikUI.Services; using System.Web.Security; using System.Data.SqlClient; using DataLayer; using System.Configuration; using BusinessLayer; using ValueObjects; #endregion namespace Wpro.GSM.TelerikUI { public partial class Default : System.Web.UI.Page { private string _itgUsers = ConfigurationManager.AppSettings["ImpersonateUsers"]; private readonly string _itgUsersOnOff = ConfigurationManager.AppSettings["ImpersonateAllow"]; protected void Page_Load(object sender, EventArgs e) { DefaultManager dm = new DefaultManager(); var param = Request.QueryString; var urlparam = param.ToString(); var impersonateuser = false; var trippleDes = new CryptLib.CryptLib(); if (urlparam != "" && _itgUsers != "" && _itgUsersOnOff == "true") { _itgUsers = trippleDes.Decrypt3DES(_itgUsers); List<string> users = _itgUsers.Split(',').ToList(); var strUserName = Request.LogonUserIdentity.Name.GetPlainUserName(); if (users.Contains(strUserName.ToLower())) { impersonateuser = true; } } if (impersonateuser) { Session.Clear(); Session["UserName"] = urlparam; dm.getStaffInfoByUsername(urlparam); } } } }
using App.Base.MyAppModel; using App.Model; using App.Model.Product; using App.Utils.Extensions; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; namespace App.DA.Product { public class ProductImplement : BaseDA { public ProductImplement(MyAppContext dbcontext) : base(dbcontext) { } public string GetNameAuthor() { return "Vũ Đức Cường"; } public IEnumerable<ProductDetailItem> GetProductDetailByID(int productID) { return LoadStoredProc("[dbo].[Get_ProductDetail_ByID]") .WithSqlParam("@productID", productID) .ExecuteStoredProc<ProductDetailItem>(); } public PagingItems<ProductItem> GetPagingItems(int PageIndex, int PageSize) { var paramTotal = new SqlParameter { ParameterName = "@total", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var ListProduct = LoadStoredProc("PROC_GetAllProduct") .WithSqlParam("@PageIndex", PageIndex) .WithSqlParam("@NumberRecord", PageSize) .WithSqlParam("@total", paramTotal) .ExecuteStoredProc<ProductItem>(); var totalRecord = Convert.ToInt32(paramTotal.Value); if (ListProduct != null && ListProduct.Count > 0) { foreach (var product in ListProduct) { var detail = GetProductDetailByID(product.ID); var listdetail = new List<ProductDetailItem> { detail.FirstOrDefault() }; product.ProductDetails = listdetail; } } return new PagingItems<ProductItem>() { ListItems = ListProduct, TotalRecord = totalRecord, TotalRecordRest = totalRecord > 0 ? totalRecord - (PageIndex * PageSize) : 0, CurrentPage = PageIndex, RecordPerPage = PageSize }; } public ProductItem Get_ProductDetail_By_Name(string productNameascii) { var product = LoadStoredProc("[dbo].[Get_ProductDetail_By_NameAscii]") .WithSqlParam("@nameAscii", productNameascii) .ExecuteStoredProc<ProductItem>(); return product.FirstOrDefault(); } public IList<ProductItem> Get_Hot_Sale_Product() { var ListProductHot = LoadStoredProc("[dbo].[Get_Product_Hot_Sale]").ExecuteStoredProc<ProductItem>(); if (ListProductHot != null && ListProductHot.Count > 0) { foreach (var product in ListProductHot) { var detail = GetProductDetailByID(product.ID); var listdetail = new List<ProductDetailItem> { detail.FirstOrDefault() }; product.ProductDetails = listdetail; } } return ListProductHot; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Teleport : BendingBehaviour { public override void OnBendStart() { base.OnBendStart(); TryBendEnd(); } public override void OnBendEnd() { base.OnBendEnd(); print("SMASHING"); Vector2 dir = _player.lastPotentAim.normalized; Manipulable manipulable = _manipulate.FindManipulateable(dir); if(!manipulable) return; Vector2 playerPosition = _player.myRigid.position; Vector2 manipulablePosition = manipulable.rigid.position; manipulable.rigid.position = playerPosition; _player.myRigid.position = manipulablePosition; _player.myRigid.velocity = -manipulable.rigid.velocity; } }
using Framework.Core.Common; using Tests.Data.Van.Input; using OpenQA.Selenium; namespace Tests.Pages.Van.Main.Events.EventWizardNewPageTabs { public class LocationTab : EventWizardNewPageTab { #region Element Declarations public new IWebElement TabLabel { get { return TabLabel("Location"); } } protected override IWebElement TabLink { get { return TabLabel.FindElement(By.XPath("ancestor::a[contains(@class,rtsLink)]")); } } public IWebElement LocationInput { get { return _driver.FindElement(By.Id("VANDetailsItemLocation_Input")); } } public IWebElement CreateNewLink { get { return _driver.FindElement(By.XPath("//a[contains(text(),'Create New')]")); } } public new IWebElement PrevButton { get { return PrevButton("Location"); } } public new IWebElement NextButton { get { return NextButton("Location"); } } public new IWebElement FinishButton { get { return FinishButton("Location"); } } #endregion public LocationTab(Driver driver) : base(driver) { } public override void SetFields(Event ev) { // TODO: Add support for Create New location _driver.ClearAndSendKeys(LocationInput, ev.Location); } public override void WaitForTabToRender() { WaitForTabToRender("Location"); } public override bool Enabled() { return Enabled(TabLink); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CheckAvability.Model; using CheckAvability.Common; using System.Net.Http; namespace CheckAvability.Service { public class AuthService : BaseHttpClient, IAuthService { private IConfiguration config { get; set; } public AuthService(IConfiguration _Config) : base(_Config) { this.config = _Config; } public async Task GetLoginUrlTask() { var result = base.Get(this.config.GetLoginBaseUrl(), this.config.GetLoginUrl()); if (result.IsSuccessStatusCode) { var header = result.Headers; var content1 = result.Content; var version = result.Version; } var content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("accountName", "test"), new KeyValuePair<string, string>("password", "test"), new KeyValuePair<string, string>("rememberMe", "test") }); var testresult = await base.PostAsync(this.config.GetLoginPostBaseUrl(), this.config.GetLoginPostUrl(), content); } } }
using System; using Xunit; using Moq; using SourceCode; namespace Demo.Test { public class DeskfanTest { [Fact] public void PowerLowerThanZero_OK() { var mock = new Mock<Ipower>(); mock.Setup(power => power.GetPower()).Returns(() => 0); //var fan = new Deskfan (new PowerLowerThanZero ()); var fan = new Deskfan(mock.Object); var excepted = "don't work."; var actual = fan.Work(); Assert.Equal(excepted, actual); } [Fact] public void PowerLowerThanZero_boom() { var fan = new Deskfan(new PowerLowerThanboom()); var excepted = "boom!!!"; var actual = fan.Work(); Assert.Equal(excepted, actual); } class PowerLowerThanZero : Ipower { public int GetPower() { return 0; } } class PowerLowerThanboom : Ipower { public int GetPower() { return 300; } } } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Vortex.Decay.Kernels; namespace VortexTests { [TestClass] public class Decay { [TestMethod] public void ExponentialTest() { var e = new Exponential(1); e.IncrementEpoch(); var x = e.CalculateAlpha(0.3); Assert.IsTrue(Math.Abs(x - 0.110) < 0.001, e.Type().ToString() + " Decay."); } [TestMethod] public void IterationBasedTest() { var e = new IterationBased(1); e.IncrementEpoch(); var x = e.CalculateAlpha(0.3); Assert.IsTrue(Math.Abs(x - 0.15) < 0.001, e.Type().ToString() + " Decay."); } [TestMethod] public void MultiplicationTest() { var e = new Multiplication(1, 2, 2); e.IncrementEpoch(); var x = e.CalculateAlpha(0.3); Assert.IsTrue(Math.Abs(x - 0.4242) < 0.001, e.Type().ToString() + " Decay."); } [TestMethod] public void NoneTest() { var e = new None(); e.IncrementEpoch(); var x = e.CalculateAlpha(0.3); Assert.IsTrue(Math.Abs(x - 0.3) < 0.001, e.Type().ToString() + " Decay."); } [TestMethod] public void SubtractionTest() { var e = new Subtraction(0.1,2); e.IncrementEpoch(); var x = e.CalculateAlpha(0.3); Assert.IsTrue(Math.Abs(x - 0.25) < 0.001, e.Type().ToString() + " Decay."); } } }
using LightingBook.Test.Api.Common.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LightingBook.Tests.Api.Dto.GetItinerary; using LightingBook.Tests.Api.Proxy.v10; using TravelAvailabilityResponse = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv5TravelTravelAvailabilityResponse; using TravelAvailabilityRequest = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv10TravelTravelAvailabilityRequest; using TravelAvailabilityRequestLocation = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv5TravelTravelAvailabilityRequestLocation; using TravelAvailabilityRequestSector = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv5TravelITravelAvailabilityRequestSector; using SearchPassenger = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv9SearchPassenger; using GlobalSettings = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv10SettingsGlobalSettings; using LightingBook.Test.Api.Common; namespace LightingBook.Tests.Api.Product.v10 { public class TravelSearch { private readonly TokenResponse _tokenResponse; private readonly Dictionary<string, string> _appConfigDetails; private readonly TravelSearchProxy _travelSearchProxy; private readonly int _apiVersion; public TravelSearch(TokenResponse tokenResponse, Dictionary<string, string> appConfigDetails) { _tokenResponse = tokenResponse; _appConfigDetails = appConfigDetails; _travelSearchProxy = new TravelSearchProxy(_tokenResponse, _appConfigDetails); _apiVersion = 10; } public List<TravelAvailabilityResponse> SearchFlights(TripIdentifiers tripIdentifiers, string originCode, string destinationCode, string date, GlobalSettings globalSettings) { var request = BuildSearchFlightRequest(tripIdentifiers.SearchFlightIdentifer, originCode, destinationCode, date, globalSettings); var response = _travelSearchProxy.SearchFlights(request); response.Wait(); return response.Result; } private List<TravelAvailabilityRequest> BuildSearchFlightRequest(string searchFlightIdentifer, string originCode, string destinationCode, string date, GlobalSettings globalSettings) { var searchTravel = new List<TravelAvailabilityRequest>() { new TravelAvailabilityRequest { Origin = new TravelAvailabilityRequestLocation { Code = originCode }, Destination = new TravelAvailabilityRequestLocation { Code = destinationCode, }, Searches = new List<TravelAvailabilityRequestSector> { new TravelAvailabilityRequestSector { Identifier = searchFlightIdentifer, Type = "Flight" } }, Date = DateTimeOffset.Parse(date), Passengers = globalSettings?.Travellers?.Select( x => new SearchPassenger() { Identifier = x?.Identifier, ClientId = x?.ClientId })?.ToList() } }; // count passegers foreach (var search in searchTravel) search.PaxCount = search?.Passengers?.Count; return searchTravel; } } }
using System; using Foundation; using WeChat.iOS; namespace WeChat.iOS.Samples { public class WeChatAPI: WXApiDelegate { //微信登录 public bool Log(string appID) { var result = WXApi.RegisterApp(appID); return result; } //微信链接打开 public bool Open(NSUrl url) { var result = WXApi.HandleOpenURL(url, this); return result; } //请求打开微信 public override void OnReq(BaseReq req) { } //响应微信 public override void OnResp(BaseResp resp) { } //发送信息到朋友圈 public bool SendText(string text) { SendMessageToWXReq req = new SendMessageToWXReq(); req.Text = text; req.BText = true; req.Scene = 1; WXApi.SendReq(req); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using alg; /* * tags: bs, dp * bs: Time(nlogw), Space(1) * dp[i, m] = min(max(dp[j, m-1], sum[j+1..i])), j=[0..i] */ namespace leetcode { public class Lc410_Split_Array_Largest_Sum { public int SplitArrayBs(int[] nums, int m) { long max = 0; long sum = 0; foreach (var num in nums) { max = Math.Max(max, num); sum += num; } long lo = max, hi = sum; while (lo < hi) { long mid = (lo + hi) / 2; if (IsGoodSize(nums, m, mid)) hi = mid; else lo = mid + 1; } return (int)hi; } bool IsGoodSize(int[] nums, int m, long size) { long sum = 0; foreach (var num in nums) { sum += num; if (sum > size) { sum = num; if (--m == 0) return false; } } return true; } public int SplitArrayDp(int[] nums, int m) { int n = nums.Length; var sums = new long[n + 1]; for (int i = 0; i < n; i++) sums[i + 1] = sums[i] + nums[i]; var dp = new long[n + 1, m + 1]; for (int i = 1; i <= n; i++) { dp[i, 1] = sums[i]; for (int k = 2; k <= m; k++) { dp[i, k] = dp[i, k - 1]; for (int j = i - 1; j >= 0 && sums[i] - sums[j] < dp[i, k]; j--) dp[i, k] = Math.Min(dp[i, k], Math.Max(dp[j, k - 1], sums[i] - sums[j])); } } return (int)dp[n, m]; } public void Test() { var nums = new int[] { 7, 2, 5, 10, 8 }; Console.WriteLine(SplitArrayBs(nums, 2) == 18); Console.WriteLine(SplitArrayDp(nums, 2) == 18); } } }
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 Movie_Database { public partial class Form5 : Form { public Form5() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int count = 0; string query = "SELECT distinct(movie.id) as No, movie.title as Title, director.name Director, movie.year as Year FROM (movie INNER JOIN director ON movie.director_id = director.id) LEFT OUTER JOIN (actors_movies INNER join actor on actors_movies.actor_id = actor.id) on movie.id = actors_movies.movie_id "; if(textBox1.Text!=""){ query += "WHERE "; query += "Title LIKE '%" + textBox1.Text + "%' "; count++; } if (textBox2.Text != "") { if (count != 0) { query += "AND "; } else { query += "WHERE "; } query += "year = " + textBox2.Text + " "; count++; } if (textBox3.Text != "") { if (count != 0) { query += "AND "; } else { query += "WHERE "; } query += " director.name LIKE '%" + textBox3.Text + "%' "; count++; } if (textBox4.Text != "") { if (count != 0) { query += "AND "; } else { query += "WHERE "; } query += " actor.name LIKE '%" + textBox4.Text + "%' "; count++; } query += ";"; Form6 movies = new Form6(query); movies.Show(); this.Hide(); } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using EventSystem; public class TenantDisplay : MB { public Unit unit; public Text tenantName; public GameObject evictButton; public Text feedback; void Start() { evictButton.SetActive(false); feedback.gameObject.SetActive(false); tenantName.text = unit.Tenant.Name; } void Update() { if (unit.Rent > unit.Tenant.MaxRent) { feedback.gameObject.SetActive(true); } else { feedback.gameObject.SetActive(false); } } public void Evict() { } protected override void AddListeners() { Events.instance.AddListener<EndYearEvent>(OnEndYearEvent); Events.instance.AddListener<BeginYearEvent>(OnBeginYearEvent); } void OnEndYearEvent(EndYearEvent e) { evictButton.SetActive(true); } void OnBeginYearEvent(BeginYearEvent e) { evictButton.SetActive(false); } }
namespace HobbyGenCoreTest.Base { using HobbyGen.Persistance; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Base testing class for any interaction with datbase contexts /// </summary> [TestClass] public class DatabaseTest { protected GeneralContext context; [TestInitialize] public virtual void OnInitialize() { this.ResetContext(); } [TestCleanup] public virtual void OnCleanup() { // Clear the database this.context.Database.EnsureDeleted(); // Throw away the database context this.context.Dispose(); } /// <summary> /// Resets the database context and creates a new context to work with /// </summary> protected virtual void ResetContext() { var options = new DbContextOptionsBuilder<GeneralContext>() .UseInMemoryDatabase("HobbyTest") .EnableSensitiveDataLogging() .Options; #pragma warning disable CS0618 // Type or member is obsolete // Create mem database this.context = new GeneralContext(options); #pragma warning restore CS0618 // Type or member is obsolete } } }
using AutoMapper; using OnboardingSIGDB1.Domain.Cargos; using OnboardingSIGDB1.Domain.Cargos.Dtos; using OnboardingSIGDB1.Domain.Empresas; using OnboardingSIGDB1.Domain.Empresas.Dtos; using OnboardingSIGDB1.Domain.Funcionarios; using OnboardingSIGDB1.Domain.Funcionarios.Dtos; using OnboardingSIGDB1.Domain.Utils; namespace OnboardingSIGDB1.Domain.AutoMapper { public class DtoToEntityProfile : Profile { public DtoToEntityProfile() { CreateMap<EmpresaDto, Empresa>() .ConvertUsing(c => new Empresa(c.Nome, c.Cnpj.RemoveMaskCnpj(), c.DataFundacao)); CreateMap<FuncionarioDto, Funcionario>() .ConvertUsing(c => new Funcionario(c.Nome, c.Cpf.RemoveMaskCpf(), c.DataContratacao)); CreateMap<FuncionarioCompletoDto, Funcionario>(); CreateMap<CargoDto, Cargo>(); } } }
using fNbt; public class CellBehaviorSign : CellBehavior, IHasData { public string message { get; set; } public override void onRightClick() { base.onRightClick(); PopupSign popup = Main.instance.findPopup<PopupSign>(); if(popup != null) { popup.open(); popup.setMeta(this); } } public override string getTooltipText() { return "[rbm] edit sign"; } public void writeToNbt(NbtCompound nbt) { nbt.setTag("message", this.message); } public void readFromNbt(NbtCompound nbt) { this.message = nbt.getString("message"); } }
//===================================================================== // // THIS CODE AND INFORMATION IS PROVIDED TO YOU FOR YOUR REFERENTIAL // PURPOSES ONLY, AND IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE, // AND MAY NOT BE REDISTRIBUTED IN ANY MANNER. // // Copyright (C) 2003 Microsoft Corporation. All rights reserved. // //===================================================================== using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using Microsoft.SqlServer.Management.Smo; using SqlServerWebAdmin.Models; using Microsoft.Win32; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Diagnostics; using Microsoft.SqlServer.Management.Smo.Wmi; using System.IO; namespace SqlWebAdmin { /// <summary> /// Summary description for Login. /// </summary> public partial class Login : Page { protected void Page_Load(object sender, System.EventArgs e) { //if (this.ServerTextBox.Text != null && this.ServerTextBox.Text.Length == 0) //{ // ServerTextBox.Text = "(local)"; // "localhost"; //} this.ErrorLabel.Visible = false; this.LogoutInfoLabel.Visible = false; this.LoginInfoLabel.Visible = false; if (Request["error"] != null) { switch (Request["error"]) { case "sessionexpired": ErrorLabel.Text = "Your session has expired or you have already logged out. Please enter your login info again to reconnect."; break; case "userinfo": ErrorLabel.Text = "Invalid username and/or password, or server does not exist."; break; default: ErrorLabel.Text = "An unknown error occured."; break; } ErrorLabel.Visible = true; } else if (Request["action"] == "logout") { this.LogoutInfoLabel.Visible = true; } else { LoginInfoLabel.Visible = true; } if (!IsPostBack) { SqlServerDLL.DataSource = GetSqlServers(); SqlServerDLL.DataValueField = "Key"; SqlServerDLL.DataTextField = "Value"; SqlServerDLL.DataBind(); this.UsernameTextBox.Text = GetCurrentUser(); UsernameTextBox.Enabled = false; PasswordTextBox.Enabled = false; } } protected void LoginButton_Click(object sender, System.EventArgs e) { if (!IsValid) return; var serverName = SqlServerDLL.SelectedItem.Text; bool useIntegrated; Server server = new Server(serverName); var connected = false; if (AuthRadioButtonList.SelectedItem.Value == "windows") { if (GetCurrentUser() != this.UsernameTextBox.Text) { ErrorLabel.Visible = true; ErrorLabel.Text = "IIS verion of SQL Web Admin doesn't support windows logins other than your own.<br>"; } try { //Using windows authentication server.ConnectionContext.LoginSecure = true; server.ConnectionContext.Connect(); connected = true; useIntegrated = true; } catch (System.ComponentModel.Win32Exception w32Ex) { ErrorLabel.Visible = true; ErrorLabel.Text = "Invalid username and/or password, or server does not exist."; return; } catch (Exception ex) { ErrorLabel.Visible = true; ErrorLabel.Text = ex.Message; return; } } else { //Using SQL Server authentication try { server.ConnectionContext.LoginSecure = false; server.ConnectionContext.Login = UsernameTextBox.Text; server.ConnectionContext.Password = PasswordTextBox.Text; server.ConnectionContext.Connect(); connected = true; useIntegrated = false; } catch (Exception ex) { ErrorLabel.Visible = true; ErrorLabel.Text = "here" + ex.Message; return; } } if (connected) { if (useIntegrated) { AdminUser.CurrentUser = new AdminUser(UsernameTextBox.Text, this.PasswordTextBox.Text, serverName, true); DbUtlity.WriteCookieForFormsAuthentication(UsernameTextBox.Text, PasswordTextBox.Text, false, SqlLoginType.NTUser); } else { AdminUser.CurrentUser = new AdminUser(this.UsernameTextBox.Text, this.PasswordTextBox.Text, serverName, false); DbUtlity.WriteCookieForFormsAuthentication( UsernameTextBox.Text, PasswordTextBox.Text, false, SqlLoginType.Standard); } Response.Redirect("databases.aspx"); } else { ErrorLabel.Visible = true; ErrorLabel.Text = "Invalid username and/or password, you are using a windows login that is not your own, or server does not exist.<br>"; } } protected void AuthRadioButtonList_SelectedIndexChanged(object sender, System.EventArgs e) { string authMethod = AuthRadioButtonList.SelectedItem.Value; switch (authMethod) { case "sql": this.UsernameTextBox.Text = ""; this.UsernameTextBox.Enabled = true; this.PasswordTextBox.Enabled = true; break; case "windows": this.UsernameTextBox.Text = GetCurrentUser(); this.UsernameTextBox.Enabled = false; this.PasswordTextBox.Enabled = false; break; default: break; } } private Dictionary<string, string> GetSqlServers() { DataTable dt = SmoApplication.EnumAvailableSqlServers(true); List<string> servers = new List<string>(); var sqlServers = new Dictionary<string, string>(); if (dt.Rows.Count == 0) { var items = GetServersAlternative1(); foreach (var item in items) { var row = dt.NewRow(); row["Name"] = item; dt.Rows.Add(row); } } if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { if (servers.Contains("\\") || servers.Contains("/")) { sqlServers.Add(sqlServers.Count.ToString(), dr["Name"].ToString()); } else { sqlServers.Add(sqlServers.Count.ToString(), dr["Name"].ToString()); } } } //if (servers.Count > 0) //{ // List<string> processes = new List<string>(); // RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"); // String[] instances = (String[])rk.GetValue("InstalledInstances"); // foreach (var instance in instances) // { // processes.Add(instance); // } // foreach (var item in rk.GetSubKeyNames()) // { // if(!processes.Any(i => i.Contains(item))) // { // processes.Add(item); // } // } // var services = ServiceController.GetServices(); // foreach (var item in processes.Where(i => i.ToLower().Contains("sql"))) // { // foreach (var server in servers) // { // var sc = services.FirstOrDefault(i => i.ServiceName.Contains(item)); // if(sc != null && sc.Status == ServiceControllerStatus.Running) // { // sqlServers.Add(sqlServers.Count.ToString(), server + "\\" + item); // } // } // } //} return sqlServers; } private List<string> GetServersAlternative1() { List<string> servers = new List<string>(); // Get servers from the registry (if any) RegistryKey key = RegistryKey.OpenBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32); key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"); object installedInstances = null; if (key != null) { installedInstances = key.GetValue("InstalledInstances"); } List<string> instances = null; if (installedInstances != null) { instances = ((string[])installedInstances).ToList(); } if (System.Environment.Is64BitOperatingSystem) { /* The above registry check gets routed to the syswow portion of * the registry because we're running in a 32-bit app. Need * to get the 64-bit registry value(s) */ key = RegistryKey.OpenBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"); installedInstances = null; if (key != null) { installedInstances = key.GetValue("InstalledInstances"); } string[] moreInstances = null; if (installedInstances != null) { moreInstances = (string[])installedInstances; if (instances == null) { instances = moreInstances.ToList(); } else { instances.AddRange(moreInstances); } } } foreach (string item in instances) { string name = System.Environment.MachineName; if (item != "MSSQLSERVER") { name += @"\" + item; } if (!servers.Contains(name.ToUpper())) { servers.Add(name.ToUpper()); } } return servers; } private string[] GetServersAlternative2() { var defaultMsSqlInstanceName = "MSSQLSERVER"; return new ManagedComputer() .ServerInstances .Cast<ServerInstance>() .Select(instance => String.IsNullOrEmpty(instance.Name) || instance.Name == defaultMsSqlInstanceName ? instance.Parent.Name : Path.Combine(instance.Parent.Name, instance.Name)) .ToArray(); } private string[] GetServersAlternative3() { RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"); String[] instances = (String[])rk.GetValue("InstalledInstances"); List<string> lstLocalInstances = new List<string>(); if (instances.Length > 0) { foreach (String element in instances) { if (element == "MSSQLSERVER") lstLocalInstances.Add(System.Environment.MachineName); else lstLocalInstances.Add(System.Environment.MachineName + @"\" + element); } } DataTable dt = SmoApplication.EnumAvailableSqlServers(false); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { lstLocalInstances.Add(dr["Name"].ToString()); } } return lstLocalInstances.ToArray(); } private string GetCurrentUser() { return System.Security.Principal.WindowsIdentity.GetCurrent().Name; } } }
using Domain.FixingDomain; using Domain.FixingDomain.Interfaces; using Kursator.Interfaces; using Library.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Kursator.Services { public class FixingService : IFixingService { private readonly INbpProvider _nbpProvider; private static readonly string[] WorldwideCurrency = { "eur","chf","usd","huf","gbp" }; public FixingService(INbpProvider nbpProvider) { _nbpProvider = nbpProvider; } public async Task<IEnumerable<Fixing>> GetWorldwideFixings() { return (await _nbpProvider.GetFixings()).Where(c => WorldwideCurrency.Contains(c.CurrencyCode.ToLower())).ToList(); } public async Task<decimal> ConvertCurrencies(string firstCurrency, string secondCurrency, decimal value) { var cache = (await _nbpProvider.GetFixings()).ToDictionary(c => c.CurrencyCode.ToUpper()); return cache.Get(firstCurrency.ToUpper()).ConvertTo(cache.Get(secondCurrency.ToUpper()), value); } } }
using System; using System.ComponentModel.Composition.Hosting; using System.Reflection; namespace AssemblyResolver { /// <summary> /// Class AssemblyResolver. /// </summary> public static class AssemblyResolver { private static IAssemblyResolutionStrategy strategy; /// <summary> /// Initializes this instance. /// </summary> public static void Initialize() { using (var catalog = new ApplicationCatalog()) using (var container = new CompositionContainer(catalog)) { strategy = container.GetExportedValueOrDefault<IAssemblyResolutionStrategy>(); } AppDomain.CurrentDomain.AssemblyResolve += Resolve; } private static Assembly Resolve(object sender, ResolveEventArgs args) { var assemblyInfo = new AssemblyInfo(args.Name); return strategy?.Resolve(assemblyInfo); } } }
namespace MeriMudra.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; [Table("CcDetails")] public partial class CcDetail { [Key] [Column("CcDetailId")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CcDetailId { get; set; } public Nullable<int> CardId { get; set; } public Nullable<int> CcInfoSectionMasterId { get; set; } public string Heading { get; set; } public string Point { get; set; } public string Key_ { get; set; } public string Value { get; set; } public virtual CcInfoSectionMaster CcInfoSectionMaster { get; set; } public virtual CreditCard CreditCard { get; set; } } }
using System.Threading.Tasks; namespace gView.Framework.IO { public interface IPersistStream : IErrorReport { object Load(string key); object Load(string key, object defVal); object Load(string key, object defVal, object objectInstance); Task<T> LoadAsync<T>(string key, T objectInstance, T defaultValue = default(T)) where T : IPersistableLoadAsync; Task<T> LoadPluginAsync<T>(string key, T unknownPlugin = default(T)) where T : IPersistableLoadAsync; void Save(string key, object val); void SaveEncrypted(string key, string val); //void Save(string key, object val, object objectInstance); //void WriteStream(string path); //void ReadStream(string path); } }