text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Domain.Entity; using LiteDB; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BackEndJCDV.Controllers { [Authorize("Bearer")] [Produces("application/json")] [Route("api/[controller]")] public class UsuariosController : Controller { private IConfiguration _config; private string DATABASE_PATH; const string COLLECTION_USUARIOS_NAME = "usuarios"; public UsuariosController(IConfiguration Configuration) { _config = Configuration; DATABASE_PATH = _config["DataBasePath"]; if (string.IsNullOrEmpty(DATABASE_PATH)) DATABASE_PATH = Directory.GetCurrentDirectory() + "\\Data\\Banco.db"; } [HttpGet("{id}/Location")] public IActionResult PatchLocation(Guid id) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { var usuario = db.SingleById<Usuario>(id, COLLECTION_USUARIOS_NAME); if (usuario == null) return NotFound(); var location = usuario.Location; return Ok(location); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [HttpPatch("{id}/Location")] public IActionResult PatchLocation(Guid id, [FromBody]Location location) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { var usuario = db.SingleById<Usuario>(id, COLLECTION_USUARIOS_NAME); if (usuario == null) return NotFound(); usuario.Location = location; db.Update<Usuario>(usuario, COLLECTION_USUARIOS_NAME); return Ok(); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [HttpGet] public IActionResult Get() { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { var usuarios = db.Query<Usuario>(COLLECTION_USUARIOS_NAME).ToList(); return Ok(usuarios); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [HttpGet("{id}")] public IActionResult Get(Guid id) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { var usuario = db.Query<Usuario>(COLLECTION_USUARIOS_NAME) .Where(x => x.Id == id).SingleOrDefault(); if (usuario == null) return NotFound(id); return Ok(usuario); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [AllowAnonymous] [HttpPost] public IActionResult Post([FromBody]Usuario usuario) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { if (!ModelState.IsValid) return BadRequest(usuario); usuario.Id = db.Insert<Usuario>(usuario, COLLECTION_USUARIOS_NAME).AsGuid; return Ok(usuario); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [HttpPut("{id}")] public IActionResult Put(Guid id, [FromBody]Usuario usuario) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { if (!ModelState.IsValid) return BadRequest(usuario); var usuarioDb = db.Query<Usuario>(COLLECTION_USUARIOS_NAME) .Where(x => x.Id == id).SingleOrDefault(); if (usuarioDb == null) return NotFound(id); //desconsidero o id do body usuario.Id = id; db.Update<Usuario>(usuario, COLLECTION_USUARIOS_NAME); return Ok(usuario); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } [HttpDelete("{id}")] public IActionResult Delete(Guid id) { try { using (var db = new LiteRepository(new LiteDatabase(DATABASE_PATH))) { var success = db.Delete<Usuario>(id, COLLECTION_USUARIOS_NAME); if (success) return Ok(); return NotFound(); } } catch (Exception ex) { return StatusCode(500, ex.Message); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Vector vector1 = new Vector { 29, 50 }; Vector vector2 = new Vector { 47, 91 }; Vector loss1 = new Vector(); loss1 = Vector.Loss1(vector1, vector2); } }
using BP12.Events; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DChild.Gameplay.Objects { public interface ISpawnable { event EventAction<SpawnableEventArgs> Pool; void SpawnAt(Vector2 position, Quaternion rotation); void ForcePool(); Type GetType(); GameObject gameObject { get; } } public struct SpawnableEventArgs : IEventActionArgs { public ISpawnable spawnable { get; } public SpawnableEventArgs(ISpawnable spawnable) : this() { this.spawnable = spawnable; } } }
namespace FamilyAccounting.Web.Models { public class CategoryViewModel { public int Id { get; set; } public string Description { get; set; } public bool Type { get; set; } //0 - income, 1 - expense public decimal Amount { get; set; } } }
using System.Collections.Generic; using KellermanSoftware.CompareNetObjects; using NHibernate.Envers; using NHibernate.Envers.Query; using Profiling2.Domain.Contracts.Queries.Audit; using Profiling2.Domain.Prf.Persons; using Profiling2.Domain.Prf.Responsibility; namespace Profiling2.Infrastructure.Queries.Audit { public class PersonResponsibilityRevisionsQuery : NHibernateAuditQuery, IPersonAuditable<PersonResponsibility> { public new CompareLogic CompareLogic { get { base.CompareLogic.Config.MembersToInclude.AddRange(new List<string>() { "PersonResponsibility", "Person", "Event", "PersonResponsibilityType", "Commentary", "Archive", "Notes" }); return base.CompareLogic; } } public IList<object[]> GetRawRevisions(Person person) { return AuditReaderFactory.Get(Session).CreateQuery() .ForRevisionsOfEntity(typeof(PersonResponsibility), false, true) .Add(AuditEntity.Property("Person").Eq(person)) .GetResultList<object[]>(); } } }
using ConnelHooley.DirectoryBackupService.S3.Models; using DirectoryBackupService.Shared.Models; using Topshelf.HostConfigurators; namespace ConnelHooley.DirectoryBackupService.S3 { internal static class S3SettingsParser { public static (SourceSettings, AwsDestinationSettings) Parse(HostConfigurator x) { string sourceDirectoryPath = string.Empty; int sourceBufferSecs = 2; string awsBucketName = string.Empty; string awsBucketRegion = string.Empty; string awsAccessKeyId = string.Empty; string awsSecretkey = string.Empty; x.AddCommandLineDefinition(nameof(sourceDirectoryPath), v => sourceDirectoryPath = v); x.AddCommandLineDefinition(nameof(sourceBufferSecs), v => sourceBufferSecs = int.Parse(v)); x.AddCommandLineDefinition(nameof(awsBucketName), v => awsBucketName = v); x.AddCommandLineDefinition(nameof(awsBucketRegion), v => awsBucketRegion = v); x.AddCommandLineDefinition(nameof(awsAccessKeyId), v => awsAccessKeyId = v); x.AddCommandLineDefinition(nameof(awsSecretkey), v => awsSecretkey = v); x.ApplyCommandLine(); var sourceSettings = new SourceSettings(sourceDirectoryPath, sourceBufferSecs); var destinationSettings = new AwsDestinationSettings( awsBucketName, awsBucketRegion, awsAccessKeyId, awsSecretkey); return (sourceSettings, destinationSettings); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtomArea : MonoBehaviour { RectTransform grid; public static ButtomArea instance; private void Awake() { instance = this; } // Start is called before the first frame update void Start() { EventCenter.GetInstance().AddEventListener(EventDic.PlayerModelUpdate, Init); //Init(); } public void Init() { try { grid = GameObject.Find("EqpGrid").GetComponent<RectTransform>(); var tempInt = grid.childCount <= 4 ? 0 : grid.childCount - 4; //设置grid高度 grid.offsetMin = new Vector2(instance.GetComponent<RectTransform>().offsetMin.x, -222f * tempInt); for (int i = 0; i < CharaSettingSys.instance.equipmentList.Count; i++) { grid.transform.GetChild(i).gameObject.GetComponent<GridItem>().Init(CharaSettingSys.instance.equipmentList[i]); } } catch { } //跟新每个grid信息 //if(grid.childCount<=4 //throw new NotImplementedException(); } private void OnDestroy() { EventCenter.GetInstance().RemoveEventListener(EventDic.PlayerModelUpdate, Init); instance = null; } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Dynamic_Programming { /// <summary> /// Find the longest substring of even size with the sum of digits on the right and left as equal /// </summary> public class LongestSubStringWithEqualSum { /// <summary> /// We can solve this problem using the dynamic programming approach /// M[i,j] -> stores the (sum of LHS from i to i+j/2) - (sum of RHS from i+j/2+1 to j) /// /// M[i,j] = arr[i] - arr[j] + M[i+1,j-1] for even number of digits from i to j /// = infinity for odd number of digits from i to j /// /// We need to find the place where M[i,j] = 0 for j-i is the max /// </summary> /// <param name="inputStr"></param> /// <returns></returns> public static string GetLongestSubStringWithEqualSum(string inputStr) { int startIndex = -1; int endIndex = -1; int[,] longestSubStringMat = new int[inputStr.Length, inputStr.Length]; for(int k=1; k<inputStr.Length; k++) { for(int i = 0; i<inputStr.Length; i++) { int j = i + k; if(j>i && i<inputStr.Length && j<inputStr.Length) // as longestSubStringMat[i,j] gives the sum of LHS - Sum of RHS, hence j should be > i { if((j-i+1) %2 == 0) { // for even number of digits between i and j longestSubStringMat[i, j] = GetDigit(inputStr, i) - GetDigit(inputStr, j) +( (i + 1 < j - 1 && i+1<inputStr.Length && j-1>=0) ? longestSubStringMat[i + 1, j - 1] : 0); if(longestSubStringMat[i,j] == 0) { // we have found a case where the sum on LHS and RHS is same if(startIndex ==-1 ||endIndex == -1 || endIndex-startIndex<j-i) { startIndex = i; endIndex = j; } } } } } } return (startIndex == -1 || endIndex == -1) ? "" : inputStr.Substring(startIndex, endIndex - startIndex + 1); } public static int GetDigit(string inputStr, int index) { if(index<0 || index>=inputStr.Length) { // error condition throw new ArgumentException("index value is out of bounds"); } return int.Parse(inputStr[index].ToString()); } public static void TestLongestSubStringWithEqualSum() { Console.WriteLine("The longest substring with equal sum for {0} is {1}", "80532", GetLongestSubStringWithEqualSum("80532")); Console.WriteLine("The longest substring with equal sum for {0} is {1}", "6680532", GetLongestSubStringWithEqualSum("6680532")); Console.WriteLine("The longest substring with equal sum for {0} is {1}", "802882532", GetLongestSubStringWithEqualSum("802882532")); Console.WriteLine("The longest substring with equal sum for {0} is {1}", "371532", GetLongestSubStringWithEqualSum("371532")); Console.WriteLine("The longest substring with equal sum for {0} is {1}", "4480532", GetLongestSubStringWithEqualSum("4480532")); Console.WriteLine("The longest substring with equal sum for {0} is {1}", "213456789", GetLongestSubStringWithEqualSum("213456789")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data; using System.Data.SqlClient; /// <summary> /// FileUtil 的摘要说明 /// </summary> public class FileUtil : System.Web.UI.Page { SqlServerDataBase sdb = new SqlServerDataBase(); private string errMsg; public FileUtil() { } /// <summary> /// 公开属性errMsg,返回错误信息 /// </summary> public string ErrMsg { get { return errMsg; } } /// <summary> /// 上传文件 /// </summary> /// <param name="upload">FileUpload控件</param> /// <param name="fileType">允许的文件类型,无要求则为null</param> /// <param name="delFilePath">删除的文件的完整路径</param> /// <returns></returns> public string fileUpload(FileUpload upload, String[] fileType, string delFileID) { string fileID = ""; if (upload.HasFile)//判断文件是否为空 { if (upload.PostedFile.ContentLength == 0) { // 文件被打开 errMsg = "请关闭本地打开的文件后再上传"; throw new Exception("请关闭本地打开的文件后再上传求"); } else if (!IsAllowedExtension(upload, fileType)) { // 文件类型不符合 errMsg = "文件类型不符合要求"; throw new Exception("文件类型不符合要求"); } else { try { string fileName = Path.GetFileName(upload.PostedFile.FileName); //获取文件名和扩展名 string type = Path.GetExtension(upload.PostedFile.FileName).ToLower(); //获取扩展名 fileID = System.Guid.NewGuid().ToString("N");//声称文件名,防止重复 DateTime time = System.DateTime.Now; // 文件上传时间 string newPath = time.ToString("yyyyMMdd"); string path = "/files/" + newPath + "/"; // 相对路径 string fullPath = Server.MapPath("~" + path);//文件的上传路径 if (!Directory.Exists(fullPath))//判断上传文件夹是否存在,若不存在,则创建 { Directory.CreateDirectory(fullPath);//创建文件夹 } string saveFileName = fullPath + fileID + type; upload.PostedFile.SaveAs(saveFileName); sdb.Insert("insert into files(fileID,fileName,fileType,path,time) values('" + fileID + "','" + fileName + "','" + type + "','" + path + "','" + time + "')", null); if (!string.IsNullOrEmpty(sdb.ErrorMessage)) { errMsg = sdb.ErrorMessage.Replace("'", "*"); throw new Exception(sdb.ErrorMessage.Replace("'", "*")); } // 删除文件 delFile(delFileID); } catch (Exception ex) { errMsg = ex.Message.Replace("'", "*"); throw new Exception(errMsg); } } } return fileID; } /// <summary> /// 文件下载 /// </summary> /// <param name="filePath"></param> /// <param name="outFileName"></param> /// <returns></returns> public bool fileDownload(string fileID) { bool ret = false; HttpResponse res = HttpContext.Current.Response; try { MyFile file = getFileByFileID(fileID); //以字符流的形式下载文件 //FileStream fs = new FileStream(file.realPath, FileMode.Open); //byte[] bytes = new byte[(int)fs.Length]; //fs.Read(bytes, 0, bytes.Length); //fs.Close(); //res.ContentType = "application/octet-stream"; //res.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.fileName, System.Text.Encoding.UTF8)); //res.BinaryWrite(bytes); //res.Flush(); //res.End(); // 分块下载 //System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.realPath); //if (fileInfo.Exists == true) //{ // const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 // byte[] buffer = new byte[ChunkSize]; // res.Clear(); // System.IO.FileStream iStream = System.IO.File.OpenRead(file.realPath); // long dataLengthToRead = iStream.Length;//获取下载的文件总大小 // res.ContentType = "application/octet-stream"; // res.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.fileName)); // while (dataLengthToRead > 0 && res.IsClientConnected) // { // int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 // res.OutputStream.Write(buffer, 0, lengthRead); // res.Flush(); // dataLengthToRead = dataLengthToRead - lengthRead; // } // res.Close(); //} // TransmitFile下载 //res.ContentType = "application/x-zip-compressed"; //res.AddHeader("Content-Disposition", "attachment;filename=" + file.fileName); //res.TransmitFile(file.realPath); //res.Flush(); //res.End(); FileInfo fileInfo = new FileInfo(file.realPath); res.Clear(); res.Charset = "utf-8"; res.ContentEncoding = System.Text.Encoding.UTF8; res.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.fileName)); res.AppendHeader("Content-Length", fileInfo.Length.ToString()); res.ContentType = "Session/x-bittorrent"; res.WriteFile(fileInfo.FullName); res.End(); ret = true; } catch (Exception ex) { ret = false; errMsg = ex.Message.Replace("'", "*"); throw new Exception(errMsg); } return ret; } /// <summary> /// 删除数据库记录以及服务器文件 /// </summary> /// <param name="delFilePath"></param> /// <returns></returns> public bool delFile(string fileID) { bool ret = true; if (string.IsNullOrEmpty(fileID)) { ret = false; } else { try { // 删除服务器文件 MyFile file = getFileByFileID(fileID); string fullPath = file.realPath; if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (Exception ex) { ret = false; errMsg = ex.Message.Replace("'", "*"); throw new Exception(errMsg); } // 删除数据库记录 //int start = delFilePath.LastIndexOf("\\") + 1; //int end = delFilePath.LastIndexOf("."); try { //string delFileID = delFilePath.Substring(start, end - start); sdb.Delete("delete from files where fileID = '" + fileID + "'", null); if (!string.IsNullOrEmpty(sdb.ErrorMessage)) { errMsg = sdb.ErrorMessage.Replace("'", "*"); ; throw new Exception(errMsg); } } catch (Exception ex) { ret = false; errMsg = ex.Message.Replace("'", "*"); throw new Exception(errMsg); } } return ret; } public MyFile getFileByFileID(string fileID) { MyFile file = new MyFile(); try { DataSet ds = sdb.Select("select * from files where fileID = '" + fileID + "'", null); DataRow row = ds.Tables[0].Rows[0]; file.fileID = row["fileID"].ToString(); file.fileName = row["fileName"].ToString(); file.fileType = row["fileType"].ToString(); file.path = row["path"].ToString(); file.realPath = Server.MapPath("~" + file.path + file.fileID + file.fileType); file.time = (DateTime)row["time"]; } catch (Exception ex) { errMsg = ex.Message.Replace("'", "*"); throw new Exception(errMsg); } return file; } /// <summary> /// 检测真实文件类型函数 /// </summary> /// <param name="postFile"></param> /// <param name="fileType"> /// 实例:String[] fileType = { "255216", "7173" }; /// 文件扩展名说明: /// 4946/104116 txt /// 7173 gif /// 255216 jpg /// 13780 png /// 6677 bmp /// 239187 txt,aspx,asp,sql /// 208207 xls.doc.ppt /// 6063 xml /// 6033 htm,html /// 4742 js /// 8075 xlsx,zip,pptx,mmap,zip /// 8297 rar /// 01 accdb,mdb /// 7790 exe,dll /// 5666 psd /// 255254 rdp /// 10056 bt种子 /// 64101 bat /// 4059 sgf /// </param> /// <returns></returns> public bool IsAllowedExtension(FileUpload upload, String[] fileType) { bool ret = false; if (fileType == null) { ret = true; } else { try { //byte[] fileByte = new byte[2];//contentLength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。 //Stream stream = upload.PostedFile.InputStream; //stream.Read(fileByte, 0, 2);//contentLength,还是取前两位 //stream.Close(); //string fileFlag = ""; //if (fileByte != null && fileByte.Length > 0)//图片数据是否为空 //{ // fileFlag = fileByte[0].ToString() + fileByte[1].ToString(); //} //if (fileType.Contains(fileFlag)) //{ // ret = true; //} string type = Path.GetExtension(upload.PostedFile.FileName); //获取扩展名 type = type.Substring(1); if (fileType.Contains(type)) { ret = true; } } catch (Exception ex) { errMsg = ex.Message; throw new Exception(errMsg); } } return ret; } //public enum FileExtension //{ // JPG = 255216, // GIF = 7173, // BMP = 6677, // PNG = 13780, // COM = 7790, // EXE = 7790, // DLL = 7790, // RAR = 8297, // ZIP = 8075, // XML = 6063, // HTML = 6033, // ASPX = 239187, // CS = 117115, // JS = 119105, // TXT = 210187, // SQL = 255254, // BAT = 64101, // BTSEED = 10056, // RDP = 255254, // PSD = 5666, // PDF = 3780, // CHM = 7384, // LOG = 70105, // REG = 8269, // HLP = 6395, // DOC = 208207, // XLS = 208207, // DOCX = 208207, // XLSX = 208207, //} }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class EditorsController : DemoController { [HttpGet] public ActionResult RadioButtonList() { ViewData["Options"] = new CheckListDemoOptions(); return DemoView("RadioButtonList"); } [HttpPost] public ActionResult RadioButtonList([Bind]CheckListDemoOptions options) { ViewData["Options"] = options; return DemoView("RadioButtonList"); } } }
using GatewayEDI.Logging.Resolver; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using GatewayEDI.Logging; namespace GatewayEDI.Logging.UnitTests { /// <summary> ///This is a test class for NamedFactoryResolverTest and is intended ///to contain all NamedFactoryResolverTest Unit Tests ///</summary> [TestClass()] public class NamedFactoryResolverTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for NamedFactoryResolver Constructor ///</summary> [TestMethod()] public void NamedFactoryResolverConstructorTest() { NamedFactoryResolver target = new NamedFactoryResolver(); Assert.Inconclusive("TODO: Implement code to verify target"); } /// <summary> ///A test for ContainsFactory ///</summary> [TestMethod()] public void ContainsFactoryTest() { NamedFactoryResolver target = new NamedFactoryResolver(); // TODO: Initialize to an appropriate value string name = string.Empty; // TODO: Initialize to an appropriate value bool expected = false; // TODO: Initialize to an appropriate value bool actual; actual = target.ContainsFactory(name); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } /// <summary> ///A test for DeregisterFactory ///</summary> [TestMethod()] public void DeregisterFactoryTest() { NamedFactoryResolver target = new NamedFactoryResolver(); // TODO: Initialize to an appropriate value string name = string.Empty; // TODO: Initialize to an appropriate value bool expected = false; // TODO: Initialize to an appropriate value bool actual; actual = target.DeregisterFactory(name); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } /// <summary> ///A test for GetFactory ///</summary> [TestMethod()] public void GetFactoryTest() { NamedFactoryResolver target = new NamedFactoryResolver(); // TODO: Initialize to an appropriate value string logName = string.Empty; // TODO: Initialize to an appropriate value ILogFactory expected = null; // TODO: Initialize to an appropriate value ILogFactory actual; actual = target.GetFactory(logName); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } /// <summary> ///A test for RegisterFactory ///</summary> [TestMethod()] public void RegisterFactoryTest() { NamedFactoryResolver target = new NamedFactoryResolver(); // TODO: Initialize to an appropriate value string name = string.Empty; // TODO: Initialize to an appropriate value ILogFactory factory = null; // TODO: Initialize to an appropriate value target.RegisterFactory(name, factory); Assert.Inconclusive("A method that does not return a value cannot be verified."); } } }
using System.Collections.Generic; namespace Tests.Data.Van.Input { public class Event { #region Name Tab Input public string EventType = ""; public bool EventTypeIsRepeating = true; public string LongName = ""; public string ShortName = ""; public string Program = ""; public string ProgramType = ""; public string DateFrom = ""; public string TimeFrom = ""; public string DateTo = ""; public string TimeTo = ""; public string Description = ""; #endregion #region Shifts Tab Input public bool EventTypeHasShifts = true; /* Shift Start and End Times MUST be added to their respective lists in order. * Additionally, NumberOfShifts = ShiftStartTimeList.Count = ShiftEndTimeList.Count * Otherwise, tests where NumberOfShifts > 1 WILL FAIL. * * If NumberOfShifts = 1, this section will be skipped. */ public int NumberOfShifts = 1; public List<string> ShiftStartTimeList = new List<string>(); public List<string> ShiftEndTimeList = new List<string>(); #endregion #region Repeat Tab Input public Dictionary<string, bool> RepeatRadioButtonDictionary = new Dictionary<string, bool> { { "Never", true }, { "Daily", false }, { "Weekly", false }, { "Monthly", false } }; // Daily Repeating Fields public int NumberOfDays = 0; // Weekly Repeating Fields public string NumberOfWeeks = ""; public bool Sunday = false; public bool Monday = false; public bool Tuesday = false; public bool Wednesday = false; public bool Thursday = false; public bool Friday = false; public bool Saturday = false; // Monthly Repeating Fields public Dictionary<string, bool> RepeatByEveryRadioButtonDictionary = new Dictionary<string, bool> { { "RepeatByDate", false }, { "RepeatByDay", false } }; public string MonthDate = ""; public string MonthDateFrequency = ""; public string MonthWeek = ""; public string MonthDay = ""; public string MonthDayFrequency = ""; // Bottom Repeating Fields public Dictionary<string, bool> EndAfterRadioButtonDictionary = new Dictionary<string, bool> { { "AfterDate", false }, { "AfterOccurrence", false } }; public string AfterDateDate = ""; public string AfterNumberOfOccurrences = ""; #endregion #region Location Tab Input public bool ChangeLocation = false; public string Location = ""; #endregion #region Roles Tab Input public bool UncheckAll = false; public List<string> RolesList = new List<string>(); #endregion #region Sharing Tab Input public Dictionary<string, bool> EditableRadioButtonDictionary = new Dictionary<string, bool> { { "OtherUsersCanEdit", false }, { "OnlyICanEdit", false } }; #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Day3 { class Program { static void Main() { var lines = File.ReadAllLines("Sample.txt"); var route1 = BuildLines(lines[0].Split(',')); var route2 = BuildLines(lines[1].Split(',')); var intersections = new List<(int x, int y)>(); var distances = new List<int>(); foreach (var line in route1) { foreach (var line2 in route2) { if (line.DoLinesCross(line2, out var intersection, out var distanceTravelled)) { intersections.Add(intersection); distances.Add(distanceTravelled); } } } var part1 = intersections .Select(pt => Math.Abs(pt.x) + Math.Abs(pt.y)) .OrderBy(d => d) .First(); var part2 = distances.Min(); } private static List<Line> BuildLines(string[] moves) { var lines = new List<Line>(); var totalDistance = 0; (int x, int y) point = (0, 0); foreach (var move in moves) { var direction = move[0]; var distance = int.Parse(move.Substring(1)); var newPoint = direction switch { 'R' => (point.x + distance, point.y), 'L' => (point.x - distance, point.y), 'U' => (point.x, point.y + distance), _ => (point.x, point.y - distance), }; lines.Add(new Line(totalDistance, point, newPoint)); point = newPoint; totalDistance += distance; } return lines; } } }
using System; using System.Collections.Generic; namespace Piovra; public class Batch<T> : IDisposable where T : IDisposable { public IEnumerable<T> Items { get; } Batch(IEnumerable<T> items) => Items = items; public static Batch<T> New(IEnumerable<T> items) => new(items); public void Dispose() { Items.Foreach(x => x?.Dispose()); GC.SuppressFinalize(this); } }
using NeuralNetLibrary.components; using System; using System.Collections; using System.IO; namespace DigitRecognition { class SemeionDataHolder : DataHolder { private string path = "data/semeion.data"; public SemeionDataHolder() : base(16, 16) { } public override void Load() { Items.Clear(); using (StreamReader reader = new StreamReader(path)) { String line; while ((line = reader.ReadLine()) != null) { String[] parts = line.Split(' '); BitArray inputs = new BitArray(256); BitArray outputs = new BitArray(10); for (int i = 0; i < 256; i++) inputs[i] = (Double.Parse(parts[i].Replace('.', ',')) == 1); for (int i = 0; i < 10; i++) outputs[i] = (Double.Parse(parts[256 + i].Replace('.', ',')) == 1); Items.Add(new DataItem(inputs, outputs)); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.Sconit.PrintModel.INV; namespace com.Sconit.Utility.Report.Operator { public class RepBarCodePurchase2DOperator : RepTemplate2 { public RepBarCodePurchase2DOperator() { //明细部分的行数 this.pageDetailRowCount = 9; //列数 1起始 this.columnCount = 5; this.rowCount = 9; //报表头的行数 1起始 this.leftColumnHeadCount = 0; //报表尾的行数 1起始 this.bottomRowCount = 0; this.headRowCount = 0; } /** * 需要拷贝的数据与合并单元格操作 * * Param pageIndex 页号 */ public override void CopyPageValues(int pageIndex) { this.SetMergedRegionColumn(pageIndex, 0, 3, 0, 4); this.SetMergedRegionColumn(pageIndex, 1, 3, 1, 4); this.SetMergedRegionColumn(pageIndex, 4, 3, 4, 4); this.SetMergedRegionColumn(pageIndex, 3, 3, 3, 4); this.SetMergedRegionColumn(pageIndex, 5, 0, 5, 2); this.SetMergedRegionColumn(pageIndex, 6, 1, 6, 4); this.SetMergedRegionColumn(pageIndex, 7, 1, 7, 4); this.SetMergedRegionColumn(pageIndex, 8, 4, 8, 4); this.SetColumnCell(pageIndex, 0, 2, "供应商"); this.SetColumnCell(pageIndex, 1, 2, "物料"); this.SetColumnCell(pageIndex, 2, 2, "数量"); this.SetColumnCell(pageIndex, 3, 2, "参考号"); this.SetColumnCell(pageIndex, 4, 2, "FIFO期限"); this.SetColumnCell(pageIndex, 5, 3, "供应商批号"); this.SetColumnCell(pageIndex, 6, 0, "制造\r\n日期"); this.SetColumnCell(pageIndex, 7, 0, "物料描述"); this.SetColumnCell(pageIndex, 8, 0, "打印人"); this.SetColumnCell(pageIndex, 8, 2, "打印时间"); } /** * 填充报表 * * Param list [0]huDetailList */ protected override bool FillValuesImpl(String templateFileName, IList<object> list) { try { IList<PrintHu> huList = null; if (list[0].GetType() == typeof(PrintHu)) { huList = new List<PrintHu>(); huList.Add((PrintHu)list[0]); } else if (list[0].GetType() == typeof(List<PrintHu>)) { huList = (IList<PrintHu>)list[0]; } else { return false; } string userName = ""; if (list.Count == 2) { userName = (string)list[1]; } this.sheet.DisplayGridlines = false; this.sheet.IsPrintGridlines = false; //this.sheet.DisplayGuts = false; int count = 0; foreach (PrintHu hu in huList) { count++; } if (count == 0) return false; this.barCodeFontName = this.GetBarcodeFontName(6, 0); //加页删页 //纵向打印 this.CopyPageCloumn(count, columnCount, 1); int pageIndex = 1; foreach (PrintHu hu in huList) { this.Fill2DBarCodeImage(pageIndex, 0, 0, 1, 3, hu.HuId); //code供应商 this.SetColumnCell(pageIndex, 0, 3, string.Format("{0} {1}", hu.ManufactureParty, hu.ManufacturePartyDescription)); //物料代码 this.SetColumnCell(pageIndex, 1, 3, hu.Item); //数量+单位 this.SetColumnCell(pageIndex, 2, 3, string.Format("{0} {1}", hu.Qty.ToString("0.###"), hu.Uom)); //送货单,如果是克隆条码,则显示参考条码号 if (!string.IsNullOrWhiteSpace(hu.RefHu)) { this.SetColumnCell(pageIndex, 2, 4, hu.RefHu); } else { this.SetColumnCell(pageIndex, 2, 4, hu.IpNo); } //参考物料号 this.SetColumnCell(pageIndex, 3, 3, string.Format("{0}/{1}", hu.ReferenceItemCode,hu.Remark)); //fifo时间 this.SetColumnCell(pageIndex, 4, 3, hu.ExpireDate != null ? hu.ExpireDate.Value.ToString("yyyy-MM-dd") : string.Empty); // 条码号 this.SetColumnCell(pageIndex, 5, 0, hu.HuId); //供应商批号 this.SetColumnCell(pageIndex, 5, 4, hu.SupplierLotNo); //制造时间 this.SetColumnCell(pageIndex, 6, 1, hu.LotNo); //描述 this.SetColumnCell(pageIndex, 7, 1, hu.ItemDescription); //打印人 this.SetColumnCell(pageIndex, 8, 1, userName); // 打印时间 this.SetColumnCell(pageIndex, 8, 3, DateTime.Now.ToString("yyyy-MM-dd HH:mm")); pageIndex++; } } catch (Exception e) { return false; } return true; } } }
using System; using Elrond.Dotnet.Sdk.Manager; using Elrond.Dotnet.Sdk.Provider; using Microsoft.Extensions.DependencyInjection; namespace Elrond.Dotnet.Sdk { public static class Extension { public enum Network { MainNet, TestNet, DevNet } public static IServiceCollection AddElrondProvider(this IServiceCollection services, Network network) { var configuration = new ElrondNetworkConfiguration(network); services.AddSingleton(configuration); services.AddHttpClient<IElrondProvider, ElrondProvider>(client => { client.BaseAddress = configuration.GatewayUri; }); services.AddTransient<IEsdtTokenManager, EsdtTokenManager>(); return services; } public class ElrondNetworkConfiguration { public Network Network { get; } public ElrondNetworkConfiguration(Network network) { Network = network; switch (network) { case Network.MainNet: GatewayUri = new Uri("https://gateway.elrond.com"); ApiUri = new Uri("https://api.elrond.com"); ExplorerUri = new Uri("https://explorer.elrond.com/"); break; case Network.TestNet: GatewayUri = new Uri("https://testnet-gateway.elrond.com"); ApiUri = new Uri("https://testnet-api.elrond.com"); ExplorerUri = new Uri("https://testnet-explorer.elrond.com/"); break; case Network.DevNet: GatewayUri = new Uri("https://devnet-gateway.elrond.com"); ApiUri = new Uri("https://devnet-api.elrond.com"); ExplorerUri = new Uri("https://devnet-explorer.elrond.com/"); break; default: throw new ArgumentOutOfRangeException(nameof(network), network, null); } } public Uri GatewayUri { get; } public Uri ApiUri { get; } public Uri ExplorerUri { get; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ActivateFireworks : MonoBehaviour { [SerializeField] private GameObject fireworks; private void OnTriggerEnter(Collider other) { fireworks.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telerik.OpenAccess; namespace Sparda.Core.Services { public class Table { private const string ITrackingGroup = "ITracking"; private static readonly List<string> ITrackingMembers = new List<string>() { "CreatedBy", "ModifiedBy", "CreatedAt", "ModifiedAt" }; private bool? _hasITracking; #region • Properties • public string Id { get; set; } public string Name { get; set; } public string TableName { get; set; } public string QueryInterceptor { get; set; } public OptimisticConcurrencyControlStrategy? OptimisticConcurrencyControlStrategy { get; set; } public List<Column> Columns { get; set; } public Schema Schema { get; set; } #endregion #region • Methods • public Column CreateColumn(string name) { var column = this.Columns.FirstOrDefault(c => c.Name == name); if (column == null && !string.IsNullOrEmpty(name)) { column = new Column() { Name = name, Table = this }; this.Columns.Add(column); } return column; } #endregion public override string ToString() { var identity = this.Columns.FirstOrDefault(); return string.Format("{0} {1}", this.Name, identity != null ? identity.Name : "no identity found"); } public bool HasITracking { get { if (!this._hasITracking.HasValue) { if (this.Columns.Any(c => c.Group == Table.ITrackingGroup)) { var list1 = Table.ITrackingMembers; var list2 = this.Columns.Where(c => !c.IsNavigationProperty).Select(c => c.GetPropertyName()).ToList(); var allOfList1IsInList2 = list1.Intersect(list2).Count() == list1.Count(); if (allOfList1IsInList2) { this._hasITracking = true; } else { this._hasITracking = false; } } else { this._hasITracking = false; } } return this._hasITracking.Value; } } public bool IsPartOfITracking(Column col) { if (col != null) { return this.HasITracking && col.Group == Table.ITrackingGroup && Table.ITrackingMembers.Contains(col.GetPropertyName()); } return false; } } }
using DamianTourBackend.Api.Helpers; using DamianTourBackend.Application.Payment; using DamianTourBackend.Application; using DamianTourBackend.Application.RouteRegistration; using DamianTourBackend.Core.Interfaces; using FluentValidation; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System; using System.Linq; using System.Threading.Tasks; using DamianTourBackend.Application.Helpers; using DamianTourBackend.Infrastructure.Mailer; namespace DamianTourBackend.Api.Controllers { [Route("api/[controller]")] [ApiController] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [ApiConventionType(typeof(DefaultApiConventions))] [Produces("application/json")] public class RouteRegistrationController : ControllerBase { private readonly IUserRepository _userRepository; private readonly IRouteRepository _routeRepository; private readonly IRegistrationRepository _registrationRepository; private readonly IValidator<RouteRegistrationDTO> _routeRegistrationDTOValidator; private readonly IMailService _mailService; private readonly IConfiguration _config; private readonly UserManager<AppUser> _userManager; public RouteRegistrationController( IUserRepository userRepository, IRouteRepository routeRepository, IRegistrationRepository registrationRepository, UserManager<AppUser> userManager, IMailService mailService, IValidator<RouteRegistrationDTO> routeRegistrationDTOValidator, IConfiguration config ) { _userRepository = userRepository; _routeRepository = routeRepository; _registrationRepository = registrationRepository; _routeRegistrationDTOValidator = routeRegistrationDTOValidator; _mailService = mailService; _config = config; _userManager = userManager; } /// <summary> /// Creates a new RouteRegistration for the current user using RouteRegistrationDTO /// </summary> /// <param name="registrationDTO">RouteRegistrationDTO containing the id of the chosen route, and shirtsize</param> /// <returns>ok with the registration or Unauthorized if user isn't logged in, or BadRequest if user/registration isn't valid</returns> [HttpPost("")] public IActionResult Post(RouteRegistrationDTO registrationDTO) { if (!User.Identity.IsAuthenticated) return Unauthorized(); var validation = _routeRegistrationDTOValidator.Validate(registrationDTO); if (!validation.IsValid) return BadRequest(validation); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest(); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest(); var route = _routeRepository.GetBy(registrationDTO.RouteId); if (route == null) return NotFound("Chosen route could not be found."); if (DateCheckHelper.CheckBeforeToday(route.Date)) return BadRequest("You cannot register for a route in the past."); var last = _registrationRepository.GetLast(mailAdress); if (last != null) { var lastRouteDate = _routeRepository.GetBy(last.RouteId).Date; if (DateCheckHelper.CheckAfterOrEqualsToday(lastRouteDate)) return BadRequest("You are already registered for a route this year."); } var registration = registrationDTO.MapToRegistration(user, route); _registrationRepository.Add(registration, mailAdress); _userRepository.Update(user); var mailDTO = (user, route).MapToDTO(); _mailService.SendRegistrationConfirmation(mailDTO); return Ok(registration); } /// <summary> /// Deletes a RouteRegistration with the given id /// </summary> /// <param name="id">Guid id of the registration to be deleted</param> /// <returns>Ok with registration that got deleted, or Unauthorized if user isn't logged in or BadRequest if user/registration is invalid</returns> [HttpDelete("")] public async Task<IActionResult> DeleteAsync(Guid id) { if (!User.Identity.IsAuthenticated) return Unauthorized(); AppUser appUser = await _userManager.FindByNameAsync(User.Identity.Name); if (!appUser.Claims.Any(c => c.ClaimValue.Equals("admin"))) return Unauthorized("You do not have the required permission to do that!"); string email = User.Identity.Name; if (email == null) return BadRequest(); var user = _userRepository.GetBy(email); if (user == null) return BadRequest(); var registration = _registrationRepository.GetBy(id, email); if (registration == null) return BadRequest(); try { _registrationRepository.Delete(registration, email); } catch (Exception) { return BadRequest(); } return Ok(registration); } [HttpPost("RegistrationIsPaid")] public IActionResult RegistrationIsPaid(string registrationId, string email) { var id = Guid.Parse(registrationId); var user = _userRepository.GetBy(email); if (user == null) return BadRequest(); var registration = _registrationRepository.GetBy(id, email); if (registration == null) return BadRequest(); registration.Paid = true; _registrationRepository.Update(registration, email); return Ok(); } /// <summary> /// Returns all RouteRegistrations from current user /// </summary> /// <returns>Ok with all Registrations from current user</returns> [HttpGet("GetAll")] public IActionResult GetAllAsync() { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); var all = _registrationRepository.GetAllFromUser(mailAdress); if (all == null || !all.Any()) return NotFound("No registrations found"); return Ok(all); } /// <summary> /// Returns the last registration from the current user /// </summary> /// <returns>Ok with last registration</returns> [HttpGet("GetLast")] public IActionResult GetLast() { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); var last = _registrationRepository.GetLast(mailAdress); if (last == null) return NotFound("No registration found"); return Ok(last); } /// <summary> /// Looks for registrations in the future /// </summary> /// <returns>Ok with boolean if user has future registrations</returns> [HttpGet("CheckCurrentRegistered")] public IActionResult CheckCurrentRegistered() { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string mailAdress = User.Identity.Name; if (mailAdress == null) return BadRequest("User not found"); var user = _userRepository.GetBy(mailAdress); if (user == null) return BadRequest("User not found"); var registration = _registrationRepository.GetLast(mailAdress); if (registration == null) return Ok(false); var route = _routeRepository.GetBy(registration.RouteId); if (route == null) return NotFound("No route found"); return Ok(DateCheckHelper.CheckAfterOrEqualsToday(route.Date)); } [HttpGet("GeneratePaymentData/{language}")] public IActionResult GeneratePaymentData(string language) { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string email = User.Identity.Name; var user = _userRepository.GetBy(email); if (user == null) return BadRequest("No user found"); var registration = _registrationRepository.GetLast(email); if (registration == null) return BadRequest("No registration found"); if (registration.Paid) return BadRequest("You have already paid for this registration"); var route = _routeRepository.GetBy(registration.RouteId); var paymentDTO = RegistrationPaymentMapper.DTOFrom(user, route, registration, language, _config); return Ok(paymentDTO); } [HttpPost("ControlPaymentResponse")] public IActionResult ControlPaymentResponse(PaymentResponseDTO dto) { if (!User.Identity.IsAuthenticated) return Unauthorized("You need to be logged in to perform this action"); string email = User.Identity.Name; var user = _userRepository.GetBy(email); if (user == null) return BadRequest("User not found"); var registration = _registrationRepository.GetLast(email); if (registration == null) return BadRequest("No registration found"); if (registration.Paid) return BadRequest("You have already paid for this registration"); var valid = EncoderHelper.ControlShaSign(_config, dto); registration.Paid = valid; _registrationRepository.Update(registration, email); var route = _routeRepository.GetBy(registration.RouteId); return Ok(new { TourName = route.TourName, Valid = valid }); } } }
using System.Data.Entity.ModelConfiguration; using ReactMusicStore.Core.Domain.Entities; namespace ReactMusicStore.Core.Data.Context.Mapping { public class CartMap : EntityTypeConfiguration<Cart> { public CartMap() { // Primary Key HasKey(t => t.RecordId); // Properties Property(t => t.Id) .IsRequired(); Property(t => t.AlbumId) .IsRequired(); Property(t => t.Count) .IsRequired(); Property(t => t.DateCreated) .IsRequired(); Ignore(t => t.ValidationResult); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DatabaseLoader : MonoBehaviour { public static CarriageImageDatabase Database = null; [RuntimeInitializeOnLoadMethod] private static void LoadAssets() { Database = CarriageImageDatabase.Instance; Debug.Assert(Database != null, "Database could not load"); Debug.Log("LOADING CarriageImageDatabase: " + Database); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MessageBox : MonoBehaviour { public GameObject messageBg; public Text messageBox; private Image bg; public float messageTime = 3f; private float clearTimer = 0f; private bool textCleared = true; void Start() { messageBox = GetComponent<Text>(); bg = messageBg.GetComponent<Image>(); //ClearMessage(); } public void DisplayMessage(string message, float duration) { if (messageBox == null) messageBox = GetComponent<Text>(); messageBox.text = message.ToString(); clearTimer = duration; textCleared = false; } void Update() { clearTimer -= Time.deltaTime; if (clearTimer <= 0 && textCleared == false) { ClearMessage(); } bg.enabled = !textCleared; } void ClearMessage() { messageBox.text = ""; textCleared = true; } }
using System.Threading.Tasks; namespace Union.Gateway.Abstractions { public interface IUnionMsgProducer { /// <summary> /// /// </summary> /// <param name="terminalNo">设备终端号</param> /// <param name="data">808 hex data</param> ValueTask ProduceAsync(string terminalNo, byte[] data); } }
using Sentry.Extensibility; using Sentry.Internal.Extensions; namespace Sentry; /// <summary> /// Instruction Address Adjustments /// </summary> public enum InstructionAddressAdjustment { /// <summary> /// Symbolicator will use the `"all_but_first"` strategy **unless** the event has a crashing `signal` /// attribute and the Stack Trace has a `registers` map, and the instruction pointer register (`rip` / `pc`) /// does not match the first frame. In that case, `"all"` frames will be adjusted. /// </summary> Auto, /// <summary> /// All frames of the stack trace will be adjusted, subtracting one instruction with (or `1`) from the /// incoming `instruction_addr` before symbolication. /// </summary> All, /// <summary> /// All frames but the first (in callee to caller / child to parent direction) should be adjusted. /// </summary> AllButFirst, /// <summary> /// No adjustment will be applied whatsoever. /// </summary> None } /// <summary> /// Sentry Stacktrace interface. /// </summary> /// <remarks> /// A stacktrace contains a list of frames, each with various bits (most optional) describing the context of that frame. /// Frames should be sorted from oldest to newest. /// </remarks> /// <see href="https://develop.sentry.dev/sdk/event-payloads/stacktrace/"/> public class SentryStackTrace : IJsonSerializable { internal IList<SentryStackFrame>? InternalFrames { get; private set; } /// <summary> /// The list of frames in the stack. /// </summary> /// <remarks> /// The list of frames should be ordered by the oldest call first. /// </remarks> public IList<SentryStackFrame> Frames { get => InternalFrames ??= new List<SentryStackFrame>(); set => InternalFrames = value; } /// <summary> /// The optional instruction address adjustment. /// </summary> /// <remarks> /// Tells the symbolicator if and what adjustment for is needed. /// </remarks> public InstructionAddressAdjustment? AddressAdjustment { get; set; } /// <inheritdoc /> public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? logger) { writer.WriteStartObject(); writer.WriteArrayIfNotEmpty("frames", InternalFrames, logger); if (AddressAdjustment is { } instructionAddressAdjustment) { var adjustmentType = instructionAddressAdjustment switch { InstructionAddressAdjustment.Auto => "auto", InstructionAddressAdjustment.All => "all", InstructionAddressAdjustment.AllButFirst => "all_but_first", InstructionAddressAdjustment.None => "none", _ => "auto" }; writer.WriteString("instruction_addr_adjustment", adjustmentType); } writer.WriteEndObject(); } /// <summary> /// Parses from JSON. /// </summary> public static SentryStackTrace FromJson(JsonElement json) { var frames = json .GetPropertyOrNull("frames") ?.EnumerateArray() .Select(SentryStackFrame.FromJson) .ToArray(); var instructionAddressAdjustment = json .GetPropertyOrNull("instruction_addr_adjustment") ?.ToString() ?.ParseEnum<InstructionAddressAdjustment>(); return new SentryStackTrace { InternalFrames = frames, AddressAdjustment = instructionAddressAdjustment }; } }
// ************************************************** // // Copyright (c) 2020 Shinichi Hasebe // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // // ************************************************** using UnityEngine; using UnityEngine.Events; public class UserNearDetector : MonoBehaviour { public Camera targetCamera; public float detectDistance = 4.0f; public bool manageRenderer = true; public bool manageCollider = true; public UnityEvent onUserDetect; public UnityEvent onUserLost; private Renderer[] renderers; private Collider[] colliders; private bool isDetected; // Start is called before the first frame update void Start() { // RendererとColliderを取得 renderers = GetComponentsInChildren<Renderer>(); colliders = GetComponentsInChildren<Collider>(); // RendererとColliderを無効化 UpdateState(false); } // Update is called once per frame void Update() { if(targetCamera != null) { float distance = Vector3.Distance(targetCamera.transform.position, this.gameObject.transform.position); if (distance <= detectDistance && !isDetected) { UpdateState(true); onUserDetect?.Invoke(); } else if(distance > detectDistance && isDetected) { UpdateState(false); onUserLost?.Invoke(); } } } private void UpdateState(bool state) { isDetected = state; if (manageRenderer) { foreach (Renderer renderer in renderers) { renderer.enabled = state; } } if (manageCollider) { foreach (Collider collider in colliders) { collider.enabled = state; } } } }
namespace MassEffect.GameObjects.Projectiles { class PenetrationShell : Projectile { public PenetrationShell(int damage) : base(damage) { } public override void Hit(Interfaces.IStarship targetShip) { targetShip.Shields -= this.Damage; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using testMonogame.Interfaces; namespace testMonogame { class ItemSelectionScreen { const int menuX = 130; const int menuY = 0; Dictionary<String, Rectangle> mapSourceRects = new Dictionary<string, Rectangle>(); Dictionary<String, Rectangle> mapDestRects = new Dictionary<string, Rectangle>(); Rectangle menuSourceRect = new Rectangle(0, 0, 256, 176); Rectangle menuDestRect = new Rectangle(menuX, menuY, 256*2, 176*2); Rectangle hideSourceRectangle = new Rectangle(0, 0, 20, 20); Rectangle mapDestRect = new Rectangle(menuX+(47 * 2), menuY+(111 * 2), 40, 40); Rectangle compassDestRect = new Rectangle(menuX+(44 * 2), menuY+(152 * 2), 40, 40); //inventory Rectangle selectedItemDest = new Rectangle(menuX+67 * 2,menuY+ 47 * 2, 16, 32); Rectangle boomerangSource = new Rectangle(267, 67, 8, 16); Rectangle bombSource = new Rectangle(276, 67, 8, 16); Rectangle arrowSource = new Rectangle(285, 67, 8, 16); Rectangle bowSource = new Rectangle(294, 67, 8, 16); Rectangle selectedBox = new Rectangle(267, 84, 16, 16); List<String> inventory; String selectedItem; bool mapShown; bool compassShown; Texture2D texture; public ItemSelectionScreen(Texture2D sprite) { inventory = new List<String>(); texture = sprite; mapShown = false; compassShown = true; setUpDestRects(); setUpSourceRects(sprite); } void setUpSourceRects(Texture2D sprite) { Rectangle r1 = new Rectangle(283, 8, 8, 8); Rectangle r2 = new Rectangle(291, 8, 8, 8); Rectangle r4 = new Rectangle(291, 16, 8, 8); Rectangle r5 = new Rectangle(307, 16, 8, 8); Rectangle r6 = new Rectangle(315, 16, 8, 8); Rectangle r7 = new Rectangle(275, 24, 8, 8); Rectangle r8 = new Rectangle(283, 24, 8, 8); Rectangle r9 = new Rectangle(291, 24, 8, 8); Rectangle r10 = new Rectangle(299, 24, 8, 8); Rectangle r11 = new Rectangle(307, 24, 8, 8); Rectangle r12 = new Rectangle(283, 32, 8, 8); Rectangle r13 = new Rectangle(291, 32, 8, 8); Rectangle r14 = new Rectangle(299, 32, 8, 8); Rectangle r15 = new Rectangle(291, 40, 8, 8); Rectangle r16 = new Rectangle(283, 48, 8, 8); Rectangle r17 = new Rectangle(291, 48, 8, 8); Rectangle r18 = new Rectangle(299, 48, 8, 8); mapSourceRects.Add("Room1", r1); mapSourceRects.Add("Room2", r2); mapSourceRects.Add("Room4", r4); mapSourceRects.Add("Room5", r5); mapSourceRects.Add("Room6", r6); mapSourceRects.Add("Room7", r7); mapSourceRects.Add("Room8", r8); mapSourceRects.Add("Room9", r9); mapSourceRects.Add("Room10", r10); mapSourceRects.Add("Room11", r11); mapSourceRects.Add("Room12", r12); mapSourceRects.Add("Room13", r13); mapSourceRects.Add("Room14", r14); mapSourceRects.Add("Room15", r15); mapSourceRects.Add("Room16", r16); mapSourceRects.Add("Room17", r17); mapSourceRects.Add("Room18", r18); } void setUpDestRects() { int gridwidth = 16; int gridX = 128 * 2; int gridY = 96 * 2; Rectangle r1 = new Rectangle(menuX + gridX + (gridwidth * 2), menuY + gridY + (gridwidth * 1), 16, 16); Rectangle r2 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 1), 16, 16); Rectangle r4 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 2), 16, 16); Rectangle r5 = new Rectangle(menuX + gridX + (gridwidth * 5), menuY + gridY + (gridwidth * 2), 16, 16); Rectangle r6 = new Rectangle(menuX + gridX + (gridwidth * 6), menuY + gridY + (gridwidth * 2), 16, 16); Rectangle r7 = new Rectangle(menuX + gridX + (gridwidth * 1), menuY + gridY + (gridwidth * 3), 16, 16); Rectangle r8 = new Rectangle(menuX + gridX + (gridwidth * 2), menuY + gridY + (gridwidth * 3), 16, 16); Rectangle r9 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 3), 16, 16); Rectangle r10 = new Rectangle(menuX + gridX + (gridwidth * 4), menuY + gridY + (gridwidth * 3), 16, 16); Rectangle r11 = new Rectangle(menuX + gridX + (gridwidth * 5), menuY + gridY + (gridwidth * 3), 16, 16); Rectangle r12 = new Rectangle(menuX + gridX + (gridwidth * 2), menuY + gridY + (gridwidth * 4), 16, 16); Rectangle r13 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 4), 16, 16); Rectangle r14 = new Rectangle(menuX + gridX + (gridwidth * 4), menuY + gridY + (gridwidth * 4), 16, 16); Rectangle r15 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 5), 16, 16); Rectangle r16 = new Rectangle(menuX + gridX + (gridwidth * 2), menuY + gridY + (gridwidth * 6), 16, 16); Rectangle r17 = new Rectangle(menuX + gridX + (gridwidth * 3), menuY + gridY + (gridwidth * 6), 16, 16); Rectangle r18 = new Rectangle(menuX + gridX + (gridwidth * 4), menuY + gridY + (gridwidth * 6), 16, 16); mapDestRects.Add("Room1", r1); mapDestRects.Add("Room2", r2); mapDestRects.Add("Room4", r4); mapDestRects.Add("Room5", r5); mapDestRects.Add("Room6", r6); mapDestRects.Add("Room7", r7); mapDestRects.Add("Room8", r8); mapDestRects.Add("Room9", r9); mapDestRects.Add("Room10", r10); mapDestRects.Add("Room11", r11); mapDestRects.Add("Room12", r12); mapDestRects.Add("Room13", r13); mapDestRects.Add("Room14", r14); mapDestRects.Add("Room15", r15); mapDestRects.Add("Room16", r16); mapDestRects.Add("Room17", r17); mapDestRects.Add("Room18", r18); } public void Draw(SpriteBatch spriteBatch, Dictionary<String,IRoom>.KeyCollection roomKeys) { spriteBatch.Draw(texture, menuDestRect, menuSourceRect, Color.White); if (!mapShown) spriteBatch.Draw(texture, mapDestRect, hideSourceRectangle, Color.Black); if (!compassShown) spriteBatch.Draw(texture, compassDestRect, hideSourceRectangle, Color.Black); //String[] TestRooms = { "Room1", "Room2", "Room4", "Room5", "Room6", //"Room7","Room8","Room9","Room10","Room11","Room12","Room13","Room14","Room15","Room16","Room17","Room18"}; foreach (String key in roomKeys) { //room 3 does not have a room on this map if(key!="Room3") spriteBatch.Draw(texture, mapDestRects[key], mapSourceRects[key], Color.White); } spriteBatch.Draw(texture, selectedItemDest, getItemSourceRect(selectedItem), Color.White); int currentDestX=menuX+131*2; int currentDestY=menuY+47*2; foreach(String item in inventory) { //Debug.WriteLine(item); spriteBatch.Draw(texture, new Rectangle(currentDestX, currentDestY, 16, 32), getItemSourceRect(item), Color.White); if (item.Equals(selectedItem)) spriteBatch.Draw(texture, new Rectangle(currentDestX - 8, currentDestY, 32, 32), selectedBox, Color.White); currentDestX += 48; if (currentDestX>menuX+204*2) { currentDestX= menuX + 131 * 2; currentDestY += 32; } } } Rectangle getItemSourceRect(String s) { Rectangle r; switch (s) { case "Bomb": r = bombSource; break; case "Arrow": r = arrowSource; break; case "Bow": r = bowSource; break; case "Boomerang": r = boomerangSource; break; default: r = hideSourceRectangle; break; } return r; } public void Update(GameManager game) { IPlayer p = game.getPlayer(); inventory = p.GetInventory(); selectedItem = p.GetSelectedItem(); mapShown = p.Map; compassShown = p.Compass; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PauseMenu : MonoBehaviour { private static bool m_gameIsPaused = false; private static bool m_gameIsEnded = false; public GameObject pauseMenuUi; // Start is called before the first frame update void Start() { m_gameIsPaused = false; m_gameIsEnded = false; } // Update is called once per frame void Update() { if (!IsGameEnded()) { if (Input.GetKeyDown(KeyCode.Escape)) { FindObjectOfType<AudioManager>().Play("EscPressed"); if (IsGamePaused()) { Resume(); } else { Pause(); } } } } public static bool IsGamePaused() { return m_gameIsPaused; } public static bool IsGameEnded() { return m_gameIsEnded; } public static void EndGame() { m_gameIsPaused = true; m_gameIsEnded = true; Time.timeScale = 0f; } public void Resume() { pauseMenuUi.SetActive(false); Time.timeScale = 1f; m_gameIsPaused = false; FindObjectOfType<AudioManager>().PlayBackgroundMusic(); } public void Pause() { pauseMenuUi.SetActive(true); Time.timeScale = 0f; // Choose something from 0f - 1f for slow motion, or over 1f for speed up m_gameIsPaused = true; FindObjectOfType<AudioManager>().PauseBackgroundMusic(); } public static void Restart() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); Time.timeScale = 1f; m_gameIsPaused = false; FindObjectOfType<AudioManager>().StopBackgroundMusic(); FindObjectOfType<AudioManager>().PlayBackgroundMusic(); } public static void Exit() { SceneManager.LoadScene("Menu"); Time.timeScale = 1f; m_gameIsPaused = false; } }
using System; using KeepTeamAutotests; using KeepTeamAutotests.Model; using NUnit.Framework; using System.Collections.Generic; using Newtonsoft.Json; using System.IO; using KeepTeamAutotests.AppLogic; namespace KeepTeamTests { [TestFixture()] public class EditKPITests : InternalPageTests { [SetUp] public void Login() { app.userHelper .loginAs(app.userHelper.getUserByRole("pKPIRW")); } [Test, TestCaseSource(typeof(FileHelper), "kpi")] public void Edit_KPI(KPI kpi) { app.kpiHelper.openFirstKPI(); //Очистка значений попапа app.kpiHelper.clearKPIPopup(); //Редактирование KPI app.kpiHelper.editKPI(kpi); //создание тестового KPI для сравнения KPI testKPI = app.kpiHelper.getKPIPopup(); //Проверка соответствия двух отпусков. Assert.IsTrue(app.kpiHelper.CompareKPI(kpi, testKPI)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryProject { abstract class UserInterface { public static void ManageOrganisation(Organisation company) { bool exit = false; do { Console.Clear(); Console.WriteLine("Press 1 to print information for all registered factories"); Console.WriteLine("Press 2 to print information for all registered stores"); Console.WriteLine("Press 3 to print information for all registered contracts"); Console.WriteLine("Press 4 to print information for all registered Suppliers"); Console.WriteLine("Press any other key to go back to main Menu"); string userChoice = Console.ReadLine(); switch (userChoice) { case "1": foreach (var factory in company.Factories) { Console.WriteLine(factory); } break; case "2": foreach (var store in company.Stores) { Console.WriteLine(store); } break; case "3": foreach (var contract in company.ContractsConducted) { Console.WriteLine(contract); } break; case "4": foreach (var supplier in company.Suppliers) { Console.WriteLine(supplier); } break; default: exit = true; break; } Console.ReadKey(); } while (!exit); } public static void ManageFactory(Organisation company) { bool exit = false; do { Console.Clear(); Factory relatedFactory = SelectFatory(company); Console.WriteLine("Press 1 to print full factory info"); Console.WriteLine("Press 2 to print all orders? conducted from factory"); Console.WriteLine("Press 3 to force factory resupply"); Console.WriteLine("Press 4 to force chocolate production"); Console.WriteLine("Press any other key to go back to MainMenu"); string userChoice = Console.ReadLine(); switch (userChoice) { case "1": Console.WriteLine(relatedFactory); break; case "2": foreach (var order in relatedFactory.OrdersConducted) { Console.WriteLine(order); } break; case "3": relatedFactory.Resupply(); break; case "4": relatedFactory.ProduceChocolate(50, 50, 50, 50, 50); break; default: exit = true; break; } Console.ReadKey(); } while (!exit); } public static void ManageStore(Organisation company) { bool exit = false; do { Console.Clear(); Store relatedStore = SelectStore(company); Console.WriteLine("Press 1 to print full store info"); Console.WriteLine("Press 2 to print transactions conducted from store"); Console.WriteLine("Press 3 to force store resupply from random factory"); Console.WriteLine("Press 4 print all employees"); Console.WriteLine("Press any other key to go back to MainMenu"); string userChoice = Console.ReadLine(); switch (userChoice) { case "1": Console.WriteLine(relatedStore); break; case "2": foreach (var transaction in relatedStore.Transactions) { Console.WriteLine(transaction); } break; case "3": relatedStore.ResupplyChocolate(company.Factories[0]); break; case "4": foreach (var employee in relatedStore.Employees) { Console.WriteLine(employee); } break; default: exit = true; break; } Console.ReadKey(); } while (!exit); } public static void ManageCustomer(Organisation company) { bool exit = false; do { Console.Clear(); Customer relatedCustomer = SelectCustomer(company); Console.WriteLine("Press 1 to print all customer's transactions"); Console.WriteLine("Press 2 to place a new order"); Console.WriteLine("Press any other key to go back to MainMenu"); string userChoice = Console.ReadLine(); switch (userChoice) { case "1": foreach (var order in relatedCustomer.ChocoOrders) { Console.WriteLine(order); } break; case "2": PlaceOrder(relatedCustomer, company); break; default: exit = true; break; } Console.ReadKey(); } while (!exit); } public static Factory SelectFatory(Organisation company) { bool isNumber = false; int relatedFactoryIndex; do { Console.Clear(); for (int i = 0; i < company.Factories.Count; i++) { Console.WriteLine($"{i}. {company.Factories[i]}"); } Console.WriteLine("Please type the index of the factory you want to work with"); string userChoice = Console.ReadLine(); isNumber = int.TryParse(userChoice, out relatedFactoryIndex); } while (!isNumber); return company.Factories[relatedFactoryIndex]; } public static Store SelectStore(Organisation company) { bool isNumber = false; int relatedStoreIndex; do { Console.Clear(); for (int i = 0; i < company.Stores.Count; i++) { Console.WriteLine($"{i}. {company.Stores[i]}"); } Console.WriteLine("Please type the index of the store you want to work with"); string userChoice = Console.ReadLine(); isNumber = int.TryParse(userChoice, out relatedStoreIndex); } while (!isNumber); return company.Stores[relatedStoreIndex]; } public static Customer SelectCustomer(Organisation company) { bool isNumber = false; int relatedCustomerIndex; List<Customer> customersBufferList = new List<Customer>(); do { Console.Clear(); foreach (var store in company.Stores) { foreach (var customer in store.Customers) { customersBufferList.Add(customer); } } for (int i = 0; i < customersBufferList.Count; i++) { Console.WriteLine($"{i}. {customersBufferList[i]}"); } Console.WriteLine("Please type the index of the custommer you want to work with"); string userChoice = Console.ReadLine(); isNumber = int.TryParse(userChoice, out relatedCustomerIndex); } while (!isNumber); return customersBufferList[relatedCustomerIndex]; } public static void PlaceOrder(Customer customer, Organisation company) { Console.WriteLine("How mayn dark chocolates do you want to buy?"); int dark = int.Parse(Console.ReadLine()); Console.WriteLine("How mayn dark chocolates do you want to buy?"); int white = int.Parse(Console.ReadLine()); Console.WriteLine("How mayn dark chocolates do you want to buy?"); int milk = int.Parse(Console.ReadLine()); Console.WriteLine("How mayn dark chocolates do you want to buy?"); int peanut = int.Parse(Console.ReadLine()); Console.WriteLine("How mayn dark chocolates do you want to buy?"); int almond = int.Parse(Console.ReadLine()); List<Chocolate> desiredChocolates = customer.CreateOrder(dark, white, milk, peanut, almond); Console.Clear(); Store storeToBuyFrom = SelectStore(company); storeToBuyFrom.SellChocolateOrder(desiredChocolates, customer); } } }
namespace VehicleInventory.Services { internal class VehicleInstock { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Facade { class Program { static void Main(string[] args) { Factura f = new Factura() {Destinatario = DestinoFactura.Contabilidad}; LegacyFacade l = new LegacyFacade(); l.CalcularFechaPago(f); Console.WriteLine("La fecha de pago de la factura para contabilidad es {0}", f.FechaPago.ToShortDateString()); Console.ReadKey(); } } }
using System.Collections.Generic; namespace Union.Gateway.Traffic { /// <summary> /// 流量统计服务 /// </summary> public interface IUnionTraffic { long Get(string key); long Increment(string terminalNo, string field, int len); List<(string, long)> GetAll(); } }
using ParrisConnection.ServiceLayer.Data; using System.Collections.Generic; namespace ParrisConnection.ServiceLayer.Models { public class WallViewModel { public int Id { get; set; } public IEnumerable<StatusData> Statuses { get; set; } } }
using NGeoNames.Entities; namespace NGeoNames.Parsers { /// <summary> /// Provides methods for parsing an <see cref="AlternateName"/> object from a string-array. /// </summary> public class AlternateNameParser : BaseParser<AlternateName> { /// <summary> /// Gets wether the file/stream has (or is expected to have) comments (lines starting with "#"). /// </summary> public override bool HasComments { get { return false; } } /// <summary> /// Gets the number of lines to skip when parsing the file/stream (e.g. 'headers' etc.). /// </summary> public override int SkipLines { get { return 0; } } /// <summary> /// Gets the number of fields the file/stream is expected to have; anything else will cause a <see cref="ParserException"/>. /// </summary> public override int ExpectedNumberOfFields { get { return 8; } } /// <summary> /// Parses the specified data into an <see cref="AlternateName"/> object. /// </summary> /// <param name="fields">The fields/data representing an <see cref="AlternateName"/> to parse.</param> /// <returns>Returns a new <see cref="AlternateName"/> object.</returns> public override AlternateName Parse(string[] fields) { return new AlternateName { Id = int.Parse(fields[0]), GeoNameId = int.Parse(fields[1]), ISOLanguage = fields[2].Length <= 3 ? fields[2] : null, Type = fields[2].Length <= 3 ? null : fields[2], Name = fields[3], IsPreferredName = Bool2String(fields[4]), IsShortName = Bool2String(fields[5]), IsColloquial = Bool2String(fields[6]), IsHistoric = Bool2String(fields[7]) }; } private static bool Bool2String(string value) { return value.Equals("1"); } } }
using System.Windows.Input; using ApartmentApps.Client; using ApartmentApps.Client.Models; namespace ResidentAppCross.ViewModels.Screens { public enum CreditCardType { Visa = 0, MasterCard = 1, Discovery = 2, AmericanExpress = 3, } public class AddCreditCardPaymentOptionViewModel : ViewModelBase { private IApartmentAppsAPIService _service; private AddCreditCardBindingModel _addCreditCardModel; private string _friendlyName; private string _month; private string _year; private string _accountHolderName; private string _cardNumber; private int _cardType; private string _cvcCode; private string[] _cardTypes; public string FriendlyName { get { return _friendlyName; } set { SetProperty(ref _friendlyName, value); } } public string Month { get { return _month; } set { SetProperty(ref _month, value); } } public string Year { get { return _year; } set { SetProperty(ref _year, value); } } public string AccountHolderName { get { return _accountHolderName; } set { SetProperty(ref _accountHolderName, value); } } public string CvcCode { get { return _cvcCode; } set { SetProperty(ref _cvcCode, value); } } public string CardNumber { get { return _cardNumber; } set { SetProperty(ref _cardNumber, value); } } public string[] CardTypes { get { if (_cardTypes == null) { _cardTypes = new[] { "Visa", "MasterCard", "Discovery", "American Express" }; } return _cardTypes; } set { _cardTypes = value; } } public int CardType { get { return _cardType; } set { SetProperty(ref _cardType, value); } } public AddCreditCardPaymentOptionViewModel(IApartmentAppsAPIService service) { _service = service; } public ICommand AddCreditCardCommand { get { return this.TaskCommand(async context => { await _service.Payments.AddCreditCardAsync(new AddCreditCardBindingModel() { AccountHolderName = AccountHolderName, CardNumber = CardNumber, CardType = CardType, ExpirationMonth = Month, ExpirationYear = Year, FriendlyName = FriendlyName, }); }).OnStart("Adding new payment option...").OnComplete("New credit card added!", ()=>this.Close(this)); } } } public class AddBankAccountPaymentOptionViewModel : ViewModelBase { private IApartmentAppsAPIService _service; private AddBankAccountBindingModel _addBankAccountModel; private string _friendlyName; private string _accountHolderName; private string _accountNumber; private string _routingNumber; private bool _isSavings; public AddBankAccountPaymentOptionViewModel(IApartmentAppsAPIService service) { _service = service; } public string FriendlyName { get { return _friendlyName; } set { SetProperty(ref _friendlyName,value); } } public string AccountHolderName { get { return _accountHolderName; } set { SetProperty(ref _accountHolderName, value); } } public string AccountNumber { get { return _accountNumber; } set { SetProperty(ref _accountNumber, value); } } public string RoutingNumber { get { return _routingNumber; } set { SetProperty(ref _routingNumber, value); } } public bool IsSavings { get { return _isSavings; } set { SetProperty(ref _isSavings, value); } } public ICommand AddBankAccountCommand { get { return this.TaskCommand(async context => { await _service.Payments.AddBankAccountWithOperationResponseAsync(new AddBankAccountBindingModel() { FriendlyName = FriendlyName, AccountNumber = AccountNumber, AccountHolderName = AccountHolderName, IsSavings = IsSavings, RoutingNumber = RoutingNumber }); }).OnStart("Adding new payment option...").OnComplete("New bank account added!", ()=>this.Close(this)); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController : MonoBehaviour { public float speed; public float distanse; public LayerMask whatIsCollision; public bool deathTrigger = false; public GameObject deathAnim; private bool movingRight = true; public Transform collisionDetection; void Update() { if (deathTrigger == false) { transform.Translate(Vector2.right * speed * Time.deltaTime); RaycastHit2D collisionInfo = Physics2D.Raycast(collisionDetection.position, Vector2.right, distanse, whatIsCollision); RaycastHit2D collisionBottom = Physics2D.Raycast(collisionDetection.position, Vector2.down, distanse, whatIsCollision); // Debug.Log("Right "+ collisionInfo.collider); // Debug.Log("Down " + collisionBottom.collider); if(collisionInfo.collider == true || collisionBottom.collider == false) { if(movingRight == true) { transform.eulerAngles = new Vector3(0,-180,0); movingRight = false; } else { transform.eulerAngles = new Vector3(0,0,0); movingRight = true; } } }else { gameObject.transform.GetChild(2).gameObject.GetComponent<BoxCollider2D>().enabled = false; gameObject.transform.GetChild(1).gameObject.GetComponent<BoxCollider2D>().enabled = false; gameObject.GetComponent<Animator>().SetTrigger("EnemyDead"); } } // private void OnDestroy() { // Instantiate(deathAnim, new Vector2(transform.position.x, transform.position.y - 0.02f), Quaternion.identity); // Destroy(deathAnim, 10f); // } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MDM { /// <summary> /// 工序生产防错规则 /// </summary> public class PokaYokeRule { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 防错规则叶标识 /// </summary> public int T230LeafID { get; set; } /// <summary> /// 防错规则编号 /// </summary> public string T230Code { get; set; } /// <summary> /// 防错规则名称 /// </summary> public string T230Name { get; set; } /// <summary> /// 防错控制级别 /// </summary> public int ControlLevel { get; set; } /// <summary> /// 低限控制值 /// </summary> public long ControlLimit_Low { get; set; } /// <summary> /// 高限控制值 /// </summary> public long ControlLimit_High { get; set; } /// <summary> /// 计量单位 /// </summary> public string UnitOfMeasure { get; set; } /// <summary> /// 是否来自模板(供参考) /// </summary> public bool Reference { get; set; } public PokaYokeRule Clone() { return MemberwiseClone() as PokaYokeRule; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.Serialization; namespace JenkinsBuildNotifier.Entities { [DataContract] internal sealed class ProjectModel { [DataMember] public string description { get; set; } [DataMember] public string displayName { get; set; } [DataMember] public string name { get; set; } [DataMember] public Uri url { get; set; } [DataMember] public bool buildable { get; set; } [DataMember] public List<BuildModel> builds { get; set; } [DataMember(Name = "color")] private string _color { get { return this.color.Name.ToLowerInvariant(); } set { this.color = Color.FromName(value); } } public Color color { get; set; } [DataMember] public bool inQueue { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace CollectionHierarchy { class MyList : AddRemoveCollection { public int Used => BaseList.Count; public override string Remove() { var first = BaseList[0]; BaseList.RemoveAt(0); return first; } } }
using UnityEngine; public class BallController : MonoBehaviour { private GameObject player1; [SerializeField] private float ballSpeed = 5f; [SerializeField] private float ballMaxSpeed = 10f; [SerializeField] private float ballAccelaration = 1f; private Rigidbody2D rb; // Properties public float BallSpeed { get { return ballSpeed; } set { ballSpeed = value; } } //Executes at the start of the game private void Start() { player1 = GameObject.Find("Player1"); rb = GetComponent<Rigidbody2D>(); rb.velocity = new Vector2(player1.transform.position.x, ballSpeed * -1); } private void Update() { } //Check where the ball hits the paddle float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) { // ascii art: // || 1 <- Left side of racket // || // || 0 <- Middle of the racket // || // || -1 <- Right side of racket return (ballPos.x - racketPos.x) / racketHeight; } //Collision code void OnCollisionEnter2D(Collision2D col) { // Hit the left Racket? if (col.gameObject.name == "Player1") { AccelarateBall(); // Calculate hit Factor float x = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.x); // Calculate direction, make length=1 via .normalized Vector2 dir = new Vector2(x, (float)0.5).normalized; // Set Velocity with dir * speed GetComponent<Rigidbody2D>().velocity = dir * ballSpeed; } // Hit the right Racket? if (col.gameObject.name == "Player2") { AccelarateBall(); // Calculate hit Factor float x = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.x); // Calculate direction, make length=1 via .normalized Vector2 dir = new Vector2(x, (float)-0.5).normalized; // Set Velocity with dir * speed GetComponent<Rigidbody2D>().velocity = dir * ballSpeed; } } public void AccelarateBall() { ballSpeed += ballAccelaration; if (ballSpeed > ballMaxSpeed) ballSpeed = ballMaxSpeed; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.CustomRangeException { class MainProgram { static void Main() { //int example Console.WriteLine("Enter a number between [1..100]."); TryIntRange(); //DateTime example Console.WriteLine("Enter date between [1.1.1980 … 31.12.2013]"); TryDateRange(); } private static void TryDateRange() { var startDate = new DateTime(1980, 1, 1); var endDate = new DateTime(2013, 12, 31); try { DateTime userDate = DateTime.Parse(Console.ReadLine()); if (userDate < startDate || userDate > endDate) { throw new InvalidRangeException<DateTime>("Date is not in range {0}...{1}", startDate, endDate); } else { Console.WriteLine("Correct input!"); } } catch (InvalidRangeException<DateTime> ire) { Console.WriteLine("<!> InvalidRangeException catched:"); Console.WriteLine("DateTime {0} is not in defined range of [{1}:{2}].", ire.Start.ToShortDateString(), ire.End.ToShortDateString()); } } private static void TryIntRange() { const int start = 0; const int end = 100; int userInput = byte.Parse(Console.ReadLine());; try { if (userInput < start || userInput > end) { throw new InvalidRangeException<int>("The number is not i range [{0}....{1}]}", start, end); } else { Console.WriteLine("Correct input!"); } } catch(InvalidRangeException<int> ire) { Console.WriteLine("InvalidRangeException!"); Console.WriteLine("The number {0} is not i range [{1}....{2}]}", userInput, ire.Start, ire.End); } } } }
using System; namespace Uintra.Features.Comments.Models { public class CommentEditDto { public Guid Id { get; } public string Text { get; } public int? LinkPreviewId { get; } public CommentEditDto(Guid id, string text, int? linkPreviewId) { Id = id; Text = text; LinkPreviewId = linkPreviewId; } } }
using System; using Uintra.Features.Comments.Models; namespace Uintra.Features.Comments.CommandBus.Commands { public class AddCommentCommand : CommentCommand { public CommentCreateDto CreateDto { get; } public AddCommentCommand(Guid targetId, Enum targetType, CommentCreateDto createDto) : base(targetId, targetType) { CreateDto = createDto; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TestTutorial101 { public partial class ContactUs : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Submit_Click(object sender, EventArgs e) { Send_mails sm = new Send_mails(); if (sm.SendMailEmail(txtName.Value, txtEmail.Value, txtMessage.Value, txtMobile.Value, "Enquiry from Site", Server.MapPath("~/Mail/mail.htm"))) { lblMsg.Text = "Your Enquiry Sucessfully Submitted"; lblMsg.ForeColor = System.Drawing.Color.Green; txtEmail.Value = ""; txtMessage.Value = ""; txtMobile.Value = ""; txtName.Value = ""; } } } }
using System; class Module{ public const int third = 15; public static int four = 99; public int five = 100; public int Sum(int first, int second, int argThird){ //third = argThird; four = argThird; return first + second + third + four; } } class StaticModule{ public static int ten = 10; public static int Increment(){ ten += 5; return ten; } public int PrintStaticMember(){ return ten; } } class Program{ static void Main(string[] args){ /* Module obj = new Module(); Console.WriteLine(obj.Sum(15, 20, 20)); Module obj2 = new Module(); Console.WriteLine(obj2.Sum(15,25,25)); Console.WriteLine(Module.four); */ Console.WriteLine(StaticModule.ten); Console.WriteLine(StaticModule.Increment()); // Console.WriteLine(StaticModule.ten); // NonStaticModule nsm = new NonStaticModule(); // Console.WriteLine(nsm.ten); // Console.WriteLine(nsm.Increment()); // Console.WriteLine(nsm.ten); StaticModule sm = new StaticModule(); Console.WriteLine(sm.PrintStaticMember()); // NonStaticModule nsm2 = new NonStaticModule(); // Console.WriteLine(nsm2.ten); } } class NonStaticModule{ public int ten = 10; public int Increment(){ ten += 5; return ten; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using AxisPosCore; using KartObjects; using AxisPosCore; namespace AxisPosUtil { public partial class frmMain : Form,IDateView { AxisPosPresenter presenter; public frmMain() { InitializeComponent(); presenter = new AxisPosPresenter(this); InitView(); } const int WM_NCHITTEST = 0x0084; const int HTCAPTION = 2; protected override void WndProc(ref Message m) { if (m.Msg == WM_NCHITTEST) { m.Result = (IntPtr)HTCAPTION; return; } base.WndProc (ref m); } private void frmMain_MouseDown(object sender, MouseEventArgs e) { } private void frmMain_MouseMove(object sender, MouseEventArgs e) { } private void btnHide_Click(object sender, EventArgs e) { MinimizeWindow(); } private void MinimizeWindow() { this.WindowState = FormWindowState.Minimized; } private void btnImport_Click(object sender, EventArgs e) { tcMain.SelectedIndex = 0; } private void btnRests_Click(object sender, EventArgs e) { if (cbAssort.SelectedValue != null) { tcMain.SelectedIndex = 1; RestReport r = new RestReport(); r.ExecReport((long)cbAssort.SelectedValue); dgvRestReport.DataSource = r.GetRecords(); } } private void btnSettings_Click(object sender, EventArgs e) { tcMain.SelectedIndex = 2; } private void tcMain_Click(object sender, EventArgs e) { } public void RefreshView() { throw new NotImplementedException(); } public void InitView() { presenter.DemandTime = dateTimePicker1.Value; presenter.ViewLoad(); cbGoods.DataSource = DataDictionary.SGoods; } private void btnHide_MouseClick(object sender, MouseEventArgs e) { } private void toolStripMenuItem1_Click(object sender, EventArgs e) { MinimizeWindow(); } private void закрытьToolStripMenuItem_Click(object sender, EventArgs e) { presenter.SaveData(); this.Close(); } private void SaveBcToolStripMenuItem_Click(object sender, EventArgs e) { presenter.SaveBC(); } private void cbGoods_SelectedIndexChanged(object sender, EventArgs e) { cbAssort.Text = ""; cbBarcodes.Text = ""; if (cbGoods.SelectedValue != null) { DataDictionary.FilterAssortment((long)cbGoods.SelectedValue); cbAssort.DataSource = DataDictionary.SFilteredAssortment; } } private void cbAssort_SelectedIndexChanged(object sender, EventArgs e) { cbBarcodes.Text = ""; DataDictionary.FilterBarcodes((long)cbAssort.SelectedValue); cbBarcodes.DataSource = DataDictionary.SFilteredBarcodes; } private void cbReceipt_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (isBarcode(cbReceipt.Text)) { cbGoods.DataSource = DataDictionary.SGoods; cbGoods.SelectedValue = DataDictionary.GetIdGoodByBarcode(cbReceipt.Text); cbAssort.SelectedValue = DataDictionary.GetIdAssortByBarcode(cbReceipt.Text); } else { DataDictionary.FilterAssortment(cbReceipt.Text); cbGoods.DataSource = DataDictionary.SFilteredGoods; } } } /// <summary> /// Соответствие введенной строки штрихкоду /// </summary> /// <param name="p"></param> /// <returns></returns> private bool isBarcode(string p) { long v; return long.TryParse(p, out v); } private void frmMain_Activated(object sender, EventArgs e) { if (cbParseLogOnActivate.Checked) { List<string> sl = presenter.getCurrentBarcodesList(); if (sl != null) { cbReceipt.Items.Clear(); foreach (string s in sl) { cbReceipt.Items.Add(s); } } } } private void cbReceipt_SelectedIndexChanged(object sender, EventArgs e) { cbGoods.SelectedValue = DataDictionary.GetIdGoodByBarcode(cbReceipt.Text); cbAssort.SelectedValue = DataDictionary.GetIdAssortByBarcode(cbReceipt.Text); } private void cbControlBox_CheckedChanged(object sender, EventArgs e) { this.ControlBox = cbControlBox.Checked; if (cbControlBox.Checked) this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; else this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { } private void получитьШкЧекаToolStripMenuItem_Click(object sender, EventArgs e) { List<string> sl = presenter.getCurrentBarcodesList(); if (sl != null) { cbReceipt.Items.Clear(); foreach (string s in sl) { cbReceipt.Items.Add(s); } } } private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { presenter.DemandTime = dateTimePicker1.Value; } private void cbExecDemandJob_CheckedChanged(object sender, EventArgs e) { presenter.ExecDemandJob = cbExecDemandJob.Checked; } private void dtReceipts_ValueChanged(object sender, EventArgs e) { } public void InvokeSetDtValue(DateTime dt) { dtReceipts.Value = dt; } public delegate void dlgSetDtValue(DateTime dt); public DateTime ReceiptsDate { get { return dtReceipts.Value; } set { if (dtReceipts.InvokeRequired) { Invoke(new dlgSetDtValue(InvokeSetDtValue),value); } else dtReceipts.Value = value; } } private void dtReceipts_ChangeUICues(object sender, UICuesEventArgs e) { } private void dtReceipts_Validated(object sender, EventArgs e) { } private void cbDateReceipts_CheckedChanged(object sender, EventArgs e) { presenter.LoadReceipts = cbDateReceipts.Checked; if (cbDateReceipts.Checked) { presenter.ReceiptsDate = dtReceipts.Value; } } public void DataContext_RemoteEvent(object sender, params object[] args) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; namespace LucaasBetterBot { internal class Global { public static string Token { get; internal set; } public static char Prefix { get; set; } public static ulong ModeratorRoleID { get; internal set; } public static bool AutoSlowmodeToggle { get; internal set; } public static int AutoSlowmodeTrigger { get; internal set; } public static ulong GuildID { get; set; } public static ulong MutedRoleID { get; internal set; } public static string ConfigPath = Environment.CurrentDirectory + "\\Data\\Config.json"; internal static void ReadConfig() { var jsonObj = JsonConvert.DeserializeObject<Dictionary<object, object>>(File.ReadAllText(ConfigPath)); Token = jsonObj["Token"].ToString(); Prefix = char.Parse(jsonObj["Prefix"].ToString()); ModeratorRoleID = Convert.ToUInt64(jsonObj["ModeratorRoleID"]); AutoSlowmodeToggle = bool.Parse(jsonObj["AutoSlowmodeToggle"].ToString()); AutoSlowmodeTrigger = int.Parse(jsonObj["AutoSlowmodeTrigger"].ToString()); GuildID = ulong.Parse(jsonObj["GuildID"].ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace pjank.BossaAPI { public class BosPapers : IEnumerable<BosPaper> { /// <summary> /// Rachunek, na którym znajdują się te papiery. /// </summary> public readonly BosAccount Account; /// <summary> /// Liczba różnych papierów wartościowych znajdujących się na tym rachunku. /// </summary> public int Count { get { return list.Count; } } /// <summary> /// Dostęp do obiektu konkretnego papieru wartościowego, po jego indeksie (licząc od zera). /// </summary> public BosPaper this[int index] { get { return list[index]; } } /// <summary> /// Dostęp do obiektu konkretnego papieru wartościowego na rachunku, po jego symbolu. /// Jeśli brak papieru o takim symbolu, zwraca tymczasowy obiekt z ilością równą zeru /// (nie musimy więc sprawdzać "!= null" przed próbą odczytu np. właściwości Quantity). /// </summary> public BosPaper this[string symbol] { get { return GetPaper(symbol); } } #region Generic list stuff private List<BosPaper> list = new List<BosPaper>(); public IEnumerator<BosPaper> GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Internal library stuff // konstruktor, wywoływany z samej klasy BosAccount internal BosPapers(BosAccount account) { Account = account; } // aktualizacja danych na liście po odebraniu ich z sieci internal void Update(DTO.Paper[] dtoPapers) { list = dtoPapers.Select(p => new BosPaper(Account, p)).ToList(); } #endregion #region Private stuff private BosPaper GetPaper(string symbol) { var paper = list.SingleOrDefault(p => p.Instrument.Symbol == symbol); if (paper == null) { var instrument = Bossa.Instruments[symbol]; paper = new BosPaper(instrument); } return paper; } #endregion } }
/******************************************************************************\ * Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. * * Leap Motion proprietary and confidential. Not for distribution. * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * \******************************************************************************/ using System; namespace LeapInternal { public class ObjectPool<T> where T : PooledObject, new() { private T[] pool; //the pooled objects private UInt64 age = 0; private const double _growRate = 1.5; public bool Growable { get; set; } /** * If Growable is true, then Capacity is only the **current** * size of the underlying memory store. */ public int Capacity { get { return pool.Length; } } public ObjectPool(int initialCapacity, bool growable = false) { this.pool = new T[initialCapacity]; this.Growable = growable; } public T CheckOut() { UInt64 eldest = UInt64.MaxValue; uint indexToUse = 0; bool freeObjectFound = false; for (uint p = 0; p < Capacity; p++) { if (this.pool[p] == null || this.pool[p].age == 0) { indexToUse = p; freeObjectFound = true; break; } if (this.pool[p].age < eldest) { eldest = this.pool[p].age; indexToUse = p; } } if (!freeObjectFound) { if (Growable) { indexToUse = (uint)pool.Length; expand(); } } //else recycle existing object if (this.pool[indexToUse] == null) this.pool[indexToUse] = new T(); this.pool[indexToUse].poolIndex = indexToUse; this.pool[indexToUse].age = ++age; return this.pool[indexToUse]; } public T FindByPoolIndex(UInt64 index) { for (int e = 0; e < this.pool.Length; e++) { T item = this.pool[e]; if (item != null && item.poolIndex == index && item.age > 0) return item; } return null; } private void addItem(uint index) { this.pool[index] = new T(); this.pool[index].poolIndex = index; this.pool[index].age = 0; } private void expand() { int newSize = (int)Math.Floor(Capacity * _growRate); T[] newPool = new T[newSize]; uint m = 0; for (; m < this.pool.Length; m++) { newPool[m] = this.pool[m]; } this.pool = newPool; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Wee.Common.Contracts { public interface IMenuCategory { string Title { get; } int Order { get; } } }
using CEMAPI.DAL; using CEMAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CEMAPI.BAL { public class NotificationHistoryBAL { TETechuvaDBContext context = new TETechuvaDBContext(); RecordExceptions exception = new RecordExceptions(); public NotificationHistoryBAL() { context.Configuration.ProxyCreationEnabled = false; } public bool saveNotification(string subject, int? UserID, string CallName, int? lastmodifiedby) { bool res = true; try { TENotification NF = new TENotification(); NF.description = subject; NF.CreatedOn = DateTime.Now; NF.LastModifiedOn = DateTime.Now; NF.Objectid = UserID; NF.Name = CallName; if (lastmodifiedby != null) { NF.LastModifiedBy = lastmodifiedby.ToString(); } NF.Status = subject; context.TENotifications.Add(NF); context.SaveChanges(); } catch (Exception ex) { exception.RecordUnHandledException(ex); res = false; } return res; } // these methods are used to store the emails (sent to customer only like Our Yahoo or Gmail InBox) against to the LeadID public int CustomerEmailTransactions(int? leadId, string From, string To, string Bcc, string Cc, string body, string subject, int? lastmodifiedBy) { int LeadtransId = 0; try { LeadTransaction ldTrans = new LeadTransaction(); ldTrans.Bcc = Bcc; ldTrans.Cc = Cc; ldTrans.Body = body; ldTrans.IsDeleted = false; ldTrans.LastModifiedBy_Id = lastmodifiedBy; ldTrans.LastModifiedOn = DateTime.Now; ldTrans.LeadId = leadId; ldTrans.SubjectName = subject; ldTrans.SentTo = To; ldTrans.Sender = From; context.LeadTransactions.Add(ldTrans); context.SaveChanges(); LeadtransId = ldTrans.UniqueId; } catch (Exception ex) { exception.RecordUnHandledException(ex); } return LeadtransId; } public int CustomerEmailTransactionWithAttachments(int leadTransactionId, string filetype, string attachment, string urlPath, int? lastmodifiedBy) { int LeadtransAttachId = 0; try { LeadTransactionWithAttachment ldTransAttach = new LeadTransactionWithAttachment(); ldTransAttach.Attachment = attachment; ldTransAttach.FileType = filetype; ldTransAttach.IsDeleted = false; ldTransAttach.LastModifiedOn = DateTime.Now; ldTransAttach.LeadTransactionID = leadTransactionId; ldTransAttach.LastModifiedBy_Id = lastmodifiedBy; ldTransAttach.UrlPath = urlPath; context.LeadTransactionWithAttachments.Add(ldTransAttach); context.SaveChanges(); LeadtransAttachId = ldTransAttach.UniqueId; } catch (Exception ex) { exception.RecordUnHandledException(ex); } return LeadtransAttachId; } public bool saveEmailNotificaton_History(string triggerEvent, string type, string appOrigin, string attachment, string template, string From, string To, string Bcc, string Cc, string subject, string originModule, int? lastmodifiedBy) { bool res = true; try { TENotification_History noteHistory = new TENotification_History(); noteHistory.ApplicationOrigin = appOrigin; noteHistory.OriginModule = originModule; noteHistory.Bcc = Bcc; noteHistory.Cc = Cc; noteHistory.FromEmail = From; noteHistory.LastModifiedBy = lastmodifiedBy; noteHistory.LastModifiedOn = DateTime.Now; noteHistory.Subject = subject; noteHistory.Template = template; noteHistory.SentOn = DateTime.Now; noteHistory.ToEmail = To; noteHistory.TriggerName = triggerEvent; noteHistory.Type = type; context.TENotification_History.Add(noteHistory); context.SaveChanges(); } catch (Exception ex) { exception.RecordUnHandledException(ex); res = false; } return res; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp3 { /// <summary> /// Interaction logic for ExpenseItHome.xaml /// </summary> public partial class Home : Page { public Home() { InitializeComponent(); } private void All_Items_Click(object sender, RoutedEventArgs e) { AllItems allItems = new AllItems(); this.NavigationService.Navigate(allItems); } private void Add_Item_Click(object sender, RoutedEventArgs e) { AddItem addItem = new AddItem(); this.NavigationService.Navigate(addItem); } private void Deadlines_Click(object sender, RoutedEventArgs e) { Deadlines deadlines = new Deadlines(); this.NavigationService.Navigate(deadlines); } } }
// Name: Colin Campbell // Class: Graded Unit // Project description: A stock system to be used within the clothing department of Sainsburys (Tu Clothing) // Version: 1.00 // Date: 07/02/2018 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Tu_Stock_System { public partial class LocationView : Form { // connection string used to connect to local database // used in all SQL queries SqlConnection myConnection = new SqlConnection("Server=.;Database=Tu;Trusted_Connection=True;"); // global employee object to be used in the constructor of any other form opened Employee currentUser = new Employee(); // global list object used to populate locations list box List<string> locations = new List<string>(); /// <summary> /// Default constructor. /// </summary> public LocationView() { InitializeComponent(); } /// <summary> /// Second constructor which takes one employee object. /// </summary> /// <param name="employeeIn">Employee that's currently logged in.</param> public LocationView(Employee employeeIn) { InitializeComponent(); currentUser = employeeIn; } // Events /// <summary> /// When the form loads, populate the locations list box with values from database. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LocationView_Load(object sender, EventArgs e) { listBoxLocations.Items.Clear(); listBoxStyleNumbers.Items.Clear(); SQLGetLocations(ref locations); foreach (var item in locations) { listBoxLocations.Items.Add(item); } } /// <summary> /// This will populate the second list box with all style numbers associated with the chosen location. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnViewLocation_Click(object sender, EventArgs e) { // only carry out the functionality if an item has actually been selected in the locations list box if (listBoxLocations.SelectedIndex >= 0) { listBoxStyleNumbers.Items.Clear(); List<string> styleNumbers = new List<string>(); SQLGetStyleNumbersByLocation(ref styleNumbers); foreach (var item in styleNumbers) { listBoxStyleNumbers.Items.Add(item); } } else { MessageBox.Show(this, "Please select a location.", "No location selected", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// This will delete the chosen location, update the locations table in the database, reload the locations list box with the new information and select the appropriate index. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRemoveLocation_Click(object sender, EventArgs e) { Location locationBeingEdited = new Location(); // only carry out the necessary work if a location has been chosen if (listBoxLocations.SelectedIndex >= 0) { // only allow user to remove location if they're a manager if (currentUser.GetIsManager() == true) { locationBeingEdited.SetName(listBoxLocations.SelectedItem.ToString()); SQLRemoveFromShopFloor(locationBeingEdited); SQLRemoveLocation(locationBeingEdited); SQLGetLocations(ref locations); listBoxLocations.Items.Clear(); foreach (var item in locations) { listBoxLocations.Items.Add(item); } SelectAppropriateIndex(listBoxLocations); listBoxStyleNumbers.Items.Clear(); MessageBox.Show(this, "Location removed succesfully.", "Location removed", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(this, $"Please get a manager or team leader to remove this location.", "Unable to remove location", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } else { MessageBox.Show(this, "Please select a location.", "No location selected", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// This will remove the chosen barcode from the selected location. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRemoveStock_Click(object sender, EventArgs e) { Location locationBeingEdited = new Location(); // only carry out necessary work if a location has been selected if (listBoxLocations.SelectedIndex >= 0) { locationBeingEdited.SetName(listBoxLocations.SelectedItem.ToString()); // only carry out necessary work if a style number has been selected if (listBoxStyleNumbers.SelectedIndex >= 0) { SQLRemoveStockFromLocation(locationBeingEdited, listBoxStyleNumbers.SelectedItem.ToString()); btnViewLocation_Click(sender, e); SelectAppropriateIndex(listBoxStyleNumbers); } else { MessageBox.Show(this, "Please select a style number.", "No style number selected", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show(this, "Please select a location.", "No location selected", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Kill the application if the user closes the form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LocationView_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } // Custom methods /// <summary> /// Deletes selected item from listbox and will choose the appropriate index. /// </summary> /// <param name="listBoxIn">Listbox to have values deleted from.</param> private void SelectAppropriateIndex(ListBox listBoxIn) { int newIndex = listBoxIn.SelectedIndex; if (newIndex >= listBoxIn.Items.Count) { listBoxIn.SelectedIndex = newIndex - 1; } else { listBoxIn.SelectedIndex = newIndex; } } /// <summary> /// This function contains the SQL command necessary to retrieve all style numbers associated with a location. /// </summary> /// <param name="myReaderIn">Reader used to read rows in chosen table.</param> /// <param name="listIn">The list that will be populated with style numbers.</param> private void SQLGetStyleNumbersByLocation(ref List<string> listIn) { myConnection.Open(); SqlCommand cmdGetStyleNumbers = new SqlCommand("dbo.spGetStyleNumbersByLocationName", myConnection); cmdGetStyleNumbers.CommandType = CommandType.StoredProcedure; cmdGetStyleNumbers.Parameters.AddWithValue("@LocationNameIn", SqlDbType.VarChar).Value = listBoxLocations.SelectedItem.ToString(); SqlDataReader myReader = null; myReader = cmdGetStyleNumbers.ExecuteReader(); while (myReader.Read()) { listIn.Add(myReader["style_number"].ToString()); } myReader.Close(); myConnection.Close(); } /// <summary> /// This function contains the SQL command necessary to retrieve all locations held in the database. /// </summary> /// <param name="listIn">The list that will be populated with location names.</param> private void SQLGetLocations(ref List<string> listIn) { listIn.Clear(); //myConnection.Open(); //SqlCommand cmdGetLocations = new SqlCommand("dbo.spGetAllLocations", myConnection); //cmdGetLocations.CommandType = CommandType.StoredProcedure; //SqlDataReader myReader = null; //myReader = cmdGetLocations.ExecuteReader(); //while (myReader.Read()) //{ // listIn.Add(myReader["name"].ToString()); //} //myReader.Close(); //myConnection.Close(); } /// <summary> /// This function contains the SQL command necessary to alter any clothing rows so that they appear to be off the shop floor. /// </summary> /// <param name="locationIn">The location that is having stock removed.</param> private void SQLRemoveFromShopFloor(Location locationIn) { myConnection.Open(); SqlCommand cmdRemoveFromShopFloor = new SqlCommand("dbo.spRemoveFromShopFloor", myConnection); cmdRemoveFromShopFloor.CommandType = CommandType.StoredProcedure; cmdRemoveFromShopFloor.Parameters.AddWithValue("@LocationNameIn", SqlDbType.VarChar).Value = locationIn.GetName(); cmdRemoveFromShopFloor.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// This function contains the SQL command necessary to set the lcn_id of appropriate row to null. /// </summary> /// <param name="locationIn">The location that will have the stock removed.</param> /// <param name="styleNumIn">The style number to have its location set to null.</param> private void SQLRemoveStockFromLocation(Location locationIn, string styleNumIn) { myConnection.Open(); SqlCommand cmdRemoveStockFromLocation = new SqlCommand("dbo.spRemoveStockFromLocation", myConnection); cmdRemoveStockFromLocation.CommandType = CommandType.StoredProcedure; cmdRemoveStockFromLocation.Parameters.AddWithValue("@LocationNameIn", SqlDbType.VarChar).Value = locationIn.GetName(); cmdRemoveStockFromLocation.Parameters.AddWithValue("@StyleNumberIn", SqlDbType.VarChar).Value = styleNumIn; cmdRemoveStockFromLocation.ExecuteNonQuery(); myConnection.Close(); } /// <summary> /// This function contains the SQL command necessary to remove a location from the database. /// </summary> /// <param name="locationIn">The location that will be removed from the database.</param> private void SQLRemoveLocation(Location locationIn) { myConnection.Open(); SqlCommand cmdRemoveLocation = new SqlCommand("dbo.spRemoveLocation", myConnection); cmdRemoveLocation.CommandType = CommandType.StoredProcedure; cmdRemoveLocation.Parameters.AddWithValue("@LocationNameIn", SqlDbType.VarChar).Value = locationIn.GetName(); cmdRemoveLocation.ExecuteNonQuery(); myConnection.Close(); } #region Menustrip code private void viewStockToolStripMenuItem_Click(object sender, EventArgs e) { StockView stockView = new StockView(currentUser); this.Hide(); stockView.Show(); } private void addStockToolStripMenuItem_Click(object sender, EventArgs e) { // allow access to form if user is a manager if (currentUser.GetEmployeeType() == "mgr") { StockAdd stockAdd = new StockAdd(currentUser); this.Hide(); stockAdd.Show(); } // otherwise deny access else { MessageBox.Show(this, $"Access denied - please get a manager or team leader to access this page.", "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void findToolStripMenuItem_Click(object sender, EventArgs e) { StockFind stockFind = new StockFind(currentUser); this.Hide(); stockFind.Show(); } private void editToolStripMenuItem_Click(object sender, EventArgs e) { // allow access to form if user is a manager if (currentUser.GetEmployeeType() == "mgr") { StockEdit stockEdit = new StockEdit(currentUser); this.Hide(); stockEdit.Show(); } // otherwise deny access else { MessageBox.Show(this, $"Access denied - please get a manager or team leader to access this page.", "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void viewToolStripMenuItem_Click(object sender, EventArgs e) { LocationView locationView = new LocationView(currentUser); this.Hide(); locationView.Show(); } private void addToolStripMenuItem_Click(object sender, EventArgs e) { // allow access to form if user is a manager if (currentUser.GetEmployeeType() == "mgr") { LocationAdd locationAdd = new LocationAdd(currentUser); this.Hide(); locationAdd.Show(); } // otherwise deny access else { MessageBox.Show(this, $"Access denied - please get a manager or team leader to access this page.", "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void addStockToolStripMenuItem1_Click(object sender, EventArgs e) { LocationAddStock locationAddStock = new LocationAddStock(currentUser); this.Hide(); locationAddStock.Show(); } private void addUserToolStripMenuItem_Click(object sender, EventArgs e) { // allow access to form if user is a manager if (currentUser.GetEmployeeType() == "mgr") { AddUser addUser = new AddUser(currentUser); this.Hide(); addUser.Show(); } // otherwise deny access else { MessageBox.Show(this, $"Access denied - please get a manager or team leader to access this page.", "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void auditToolStripMenuItem_Click(object sender, EventArgs e) { // allow access to form if user is a manager if (currentUser.GetEmployeeType() == "mgr") { Audit audit = new Audit(currentUser); this.Hide(); audit.Show(); } // otherwise deny access else { MessageBox.Show(this, $"Access denied - please get a manager or team leader to access this page.", "Access denied", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void logOutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show(this, "Logout successful.", "Logout", MessageBoxButtons.OK, MessageBoxIcon.Information); SplashScreen splashScreen = new SplashScreen(); this.Hide(); splashScreen.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AngularSPAWebAPI.Models.DatabaseModels.Inventory { public abstract class BaseSubProduct : IProduct { [Key] public int ProductID { get; set; } public double ProductPrice { get; set; } public string Name { get; set; } public DateTime Creation { get;} public string Description { get; set; } public ProductCategory ProductCategory { get; set; } public BaseSubProduct() { Creation = DateTime.Now; } public abstract double CalculatePrice(); } }
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using UnityEditor; using UnityEngine.SceneManagement; public class PlayerInScene : MonoBehaviour { private string sceneToTest = "Game"; [UnityTest] public IEnumerator PlayerPresentTest() { yield return SceneManager.LoadSceneAsync(sceneToTest, LoadSceneMode.Additive); SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneToTest)); var player = GameObject.Find("Player"); Assert.IsNotNull(player); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CQCM { public class CmProducer { /// <summary> /// 输出扩容结果 /// </summary> /// <param name="cmSite"></param> /// <param name="dbDt"></param> /// <param name="cmDt"></param> /// <returns></returns> public DataTable Produce(List<string> cmSite, DataTable dbDt, DataTable cmDt) { DataTable outDt = dbDt.Clone(); foreach (var site in cmSite) { List<string> cellNum = new List<string> { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K","L"}; foreach (var num in cellNum) { //构造CELL string cell = string.Format("{0}{1}", site, num); //输出第一载波数据 var query = GetDbCarrier(dbDt,cell,""); //没有待扩容数据,不输出,不扩容 if (query == null) { break; } outDt.Rows.Add(query[0].ItemArray); //二载波扩容 GetTwoCarrierData(ref outDt, dbDt, cmDt, cell, query[0]); //三载波扩容 GetThreeCarrierData(ref outDt, dbDt, cmDt, cell, query[0]); } } return outDt; } /// <summary> /// db数据中的 /// </summary> /// <param name="dbDt"></param> /// <param name="cell"></param> /// <returns></returns> public List<DataRow> GetDbCarrier(DataTable dbDt, string cell, string carrier) { var query = from row in dbDt.AsEnumerable() where row[new ParseDatabase().GetCellIndex(dbDt.Columns)].Equals(cell + carrier) select row; if (query == null || query.Count() == 0) { return null; } return query.ToList(); } /// <summary> /// 二载波扩容 /// </summary> /// <param name="outDt"></param> /// <param name="dbDt"></param> /// <param name="cmDt"></param> /// <param name="cell"></param> /// <param name="firstCarrier"></param> public void GetTwoCarrierData(ref DataTable outDt, DataTable dbDt, DataTable cmDt, string cell, DataRow firstCarrier) { //db输入数据检查二载波数据 var dbTwoCarrier = GetDbCarrier(dbDt, cell, "1"); if (dbTwoCarrier == null) { //扩容数据是否存在二载波扩容 //二载波数据 var cmTwoCarrier = from row in cmDt.AsEnumerable() where row[new ParseCMSite().GetCellIndex(cmDt.Columns)].ToString().Contains(cell) && row[new ParseCMSite().GetCounterIndex(cmDt.Columns)].ToString().Contains(StaticField.twoCarrier) select row; //检测原始数据有没有二载波数据 if (cmTwoCarrier == null || cmTwoCarrier.Count() == 0) { } else { DataRow newRow = CmCarrier(outDt, cell, firstCarrier, 2); outDt.Rows.Add(newRow); } } else { outDt.Rows.Add(dbTwoCarrier[0].ItemArray); } } /// <summary> /// 三载波扩容 /// </summary> /// <param name="outDt"></param> /// <param name="dbDt"></param> /// <param name="cmDt"></param> /// <param name="cell"></param> /// <param name="firstCarrier"></param> /// <param name="carrier"></param> public void GetThreeCarrierData(ref DataTable outDt, DataTable dbDt, DataTable cmDt, string cell, DataRow firstCarrier) { //db输入数据检查三载波数据 var dbThreeCarrier = GetDbCarrier(dbDt,cell,"2"); if (dbThreeCarrier == null) { //扩容数据是否存在三载波扩容 var cmThreeCarrier = from row in cmDt.AsEnumerable() where row[new ParseCMSite().GetCellIndex(cmDt.Columns)].ToString().Contains(cell) && row[new ParseCMSite().GetCounterIndex(cmDt.Columns)].ToString().Contains(StaticField.threeCarrier) select row; //检测原始数据有没有三载波数据 if (cmThreeCarrier == null || cmThreeCarrier.Count() == 0) { } else { //三载波扩容 DataRow newRow = CmCarrier(outDt, cell, firstCarrier,3); outDt.Rows.Add(newRow); } } else { outDt.Rows.Add(dbThreeCarrier[0].ItemArray); } } /// <summary> /// 扩容后的数据 /// </summary> /// <param name="outDt"></param> /// <param name="cell"></param> /// <param name="firstCarrier"></param> /// <returns></returns> public DataRow CmCarrier(DataTable outDt, string cell, DataRow firstCarrier, int carrier) { //三载波扩容 DataRow newRow = outDt.NewRow(); var colNames = outDt.Columns; for (int i = 0; i < outDt.Columns.Count; i++) { string colName = colNames[i].ToString(); if (colName.Equals(StaticField.cell)) { newRow[i] = string.Format("{0}{1}", cell,carrier-1); } else if (colName.Equals(StaticField.cellId)) { newRow[i] = int.Parse(firstCarrier[i].ToString()) + (16*carrier); } else if (colName.Equals(StaticField.earfcndl) || colName.Equals(StaticField.earfcnul)) { string earfcndl = firstCarrier[i].ToString(); newRow[i] = carrier.Equals(3)? GetEarfcndl(earfcndl):GetEarfcnul(earfcndl); } else { newRow[i] = firstCarrier[i].ToString(); } } return newRow; } /// <summary> /// 根据第一载波earfcndl计算第三载波 /// </summary> /// <param name="earfcndl">第一载波的值</param> /// <returns>第三载波的值</returns> public string GetEarfcndl(string earfcndl) { if (earfcndl.Equals("37900")) { return "40936"; } else if (earfcndl.Equals("38950")) { return "39292"; } else if (earfcndl.Equals("38400")) { return string.Empty; } else { return "请检查第一载波是否有问题"; } } /// <summary> /// 根据第一载波earfcnul计算第二载波 /// </summary> /// <param name="earfcnul"></param> /// <returns></returns> public string GetEarfcnul(string earfcnul) { if (earfcnul.Equals("37900")) { return "38098"; } else if (earfcnul.Equals("38950")) { return "39148"; } else if (earfcnul.Equals("38400")) { return "38544"; } else { return "请检查第一载波是否有问题"; } } } }
using PrismTest1.Business; using PrismTest1.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrismTest1.People.ViewModels { public interface IPersonViewModel: IViewModel { Person Person { get; set; } } }
using UnityEngine; using System.Collections; public class UIAutoLayout : MonoBehaviour { const int kIconSize = 100; const int kOffset = 2; public GameObject gameFieldView; public GameObject sidePanel; public GameObject bottomPanel; // Use this for initialization void Start () { this.CalculateBounds (); } // Update is called once per frame void Update () { this.CalculateBounds (); } void CalculateBounds () { RectTransform gfSize = gameFieldView.GetComponent<RectTransform> (); RectTransform spSize = sidePanel.GetComponent<RectTransform> (); float gfHeight = Screen.height; float spHeight = Screen.height; float gfWidth = gfHeight; // game field is likely to be square float spMinWidth = 2 * kIconSize + 3 * kOffset; float spMaxWidth = Screen.width * 0.4375f; float spWidth = Screen.width - gfWidth; if (spWidth > spMaxWidth) { spWidth = spMaxWidth; gfWidth = Screen.width - spWidth; } else if (spWidth < spMinWidth) { spWidth = spMinWidth; gfWidth = Screen.width - spWidth; } gfSize.position = new Vector2(gfSize.position.x - (gfSize.rect.width - gfWidth)/2, gfSize.position.y + (gfSize.rect.height - gfHeight)/2); spSize.position = new Vector2(spSize.position.x + (spSize.rect.width - spWidth)/2, spSize.position.y + (spSize.rect.height - spHeight)/2); gfSize.sizeDelta = new Vector2 (gfWidth, gfHeight); spSize.sizeDelta = new Vector2 (spWidth, spHeight); // change box collider size BoxCollider2D gfBox = gameFieldView.GetComponent<BoxCollider2D> (); gfBox.size = new Vector2 (gfWidth, gfHeight); } }
namespace ThaiTable.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; using System.Linq; public partial class Order { public int OrderID { get; set; } public DateTime OrderDate { get; set; } public bool IsPaid { get; set; } public Guid RowID { get; set; } public string TxnId { get; set; } public double FeeShipping { get; set; } public bool Shipping { get; set; } public DateTime DeliveryDT { get; set; } public virtual Customer Customer { get; set; } [StringLength(1)] public string MoveToClient { get; set; } public virtual ICollection<OrderItem> OrderItems { get; set; } public Order() { OrderDate = DateTime.Now; OrderItems = new HashSet<OrderItem>(); } public Order(Guid id) : this() { this.RowID = id; } public void AddItem(string productID, int amount, string modifierId) { OrderItem item = (from c in OrderItems where c.productID == productID select c).SingleOrDefault(); ModifierOfOrder modItem = null; if (item == null) OrderItems.Add(new OrderItem(productID, amount, modifierId)); else { item.Amount += amount; if (modifierId != "") { modItem = (from c in item.ModifierOfOrders where c.ModifierID == modifierId select c).FirstOrDefault(); if (modItem == null) { item.ModifierOfOrders.Add(new ModifierOfOrder(item.productID, modifierId, amount)); } } } } internal void RemoveItem(string productID) { OrderItem item = (from c in OrderItems where c.productID == productID select c).SingleOrDefault(); if (item == null) throw new InvalidOperationException("Unknown item in shopping cart."); else OrderItems.Remove(item); } public void UpdateItem(string productId, int quantity) { OrderItem item = (from c in OrderItems where c.productID == productId select c).SingleOrDefault(); if (item != null) item.Amount = quantity; } } }
using System;using Alabo.Domains.Repositories.EFCore;using Alabo.Domains.Repositories.Model; using System.Linq; using Alabo.Domains.Entities; using Microsoft.AspNetCore.Mvc; using Alabo.Framework.Core.WebApis.Filter; using MongoDB.Bson; using Alabo.Framework.Core.WebApis.Controller; using Alabo.RestfulApi;using ZKCloud.Open.ApiBase.Configuration; using Alabo.Domains.Services; using Alabo.Web.Mvc.Attributes; using Alabo.Web.Mvc.Controllers; using Alabo.Data.People.ServiceCenters.Domain.Entities; using Alabo.Data.People.ServiceCenters.Domain.Services; namespace Alabo.Data.People.ServiceCenters.Controllers { [ApiExceptionFilter] [Route("Api/ServiceCenter/[action]")] public class ApiServiceCenterController : ApiBaseController<ServiceCenter,ObjectId> { public ApiServiceCenterController() : base() { BaseService = Resolve<IServiceCenterService>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Integer.Domain.Acesso.Exceptions; using Integer.Infrastructure.Email.TemplateModels; using Integer.Infrastructure.Tasks; namespace Integer.Domain.Acesso { public class TrocaSenhaService { private Usuarios usuarios; private UsuarioTokens usuarioTokens; public TrocaSenhaService(Usuarios usuarios, UsuarioTokens usuarioTokens) { this.usuarios = usuarios; this.usuarioTokens = usuarioTokens; } public void EnviarSenha(string email) { var usuario = ObterUsuario(email); string token = CriarToken(usuario); EnviarEmail(usuario, token); } private Usuario ObterUsuario(string email) { var usuario = usuarios.Com(u => u.Email == email); if (usuario == null) throw new UsuarioInexistenteException(); return usuario; } private string CriarToken(Usuario usuario) { var token = new UsuarioToken(usuario); usuarioTokens.Salvar(token); return token.Codigo.ToString(); } private void EnviarEmail(Usuario usuario, string token) { TaskExecutor.ExcuteLater(new SendEmailTask("Trocar senha", "TrocarSenha", usuario.Email, new TrocarSenhaModel { UserId = usuario.Id, Token = token })); } public bool ValidarToken(string usuarioId, Guid token) { UsuarioToken usuarioToken = usuarioTokens.Com(u => u.UsuarioId == usuarioId && u.Codigo == token); return usuarioToken.EstaValido; } public void DesativarToken(string usuarioId, Guid token) { UsuarioToken usuarioToken = usuarioTokens.Com(u => u.UsuarioId == usuarioId && u.Codigo == token); usuarioToken.Desativar(); } public void TrocarSenha(Guid token, string usuarioId, string senha) { UsuarioToken usuarioToken = usuarioTokens.Com(u => u.UsuarioId == usuarioId && u.Codigo == token); if (!usuarioToken.EstaValido) throw new UsuarioTokenExpiradoException(); var usuario = usuarios.Com(u => u.Id == usuarioId); if (usuario == null) throw new UsuarioInexistenteException(); usuario.TrocarSenha(senha); usuarioToken.Desativar(); } } }
using System; using Framework.Core.Common; using Tests.Data.Oberon; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Oberon.GivingRecipient { public class GivingRecipientCreate : GivingRecipientBasePage { #region Page Objects public const string Url = "/GivingRecipient/Create"; #endregion public GivingRecipientCreate(Driver driver) : base(driver) { } #region Methods /// <summary> /// returns true if validation exists /// </summary> public bool NameValidatorExists() { return _driver.Exists( RecipientName.FindElement(By.XPath("./following-sibling::span[@class='field-validation-error']"))); } /// <summary> /// enters form data from giving history recipient object /// </summary> public void EnterFormData(GivingHistoryRecipient recipient) { _driver.SendKeys(RecipientName, recipient.Name); _driver.SendKeys(RecipientDescription, recipient.Description); _driver.SendKeys(RecipientOffice, recipient.Office); _driver.SendKeys(RecipientDistrict, recipient.District); _driver.SelectOptionByText(RecipientState, recipient.State); _driver.SelectOptionByText(RecipientParty, recipient.PoliticalPartyName); _driver.SendKeys(RecipientCycle, DateTime.Now.Year.ToString()); } #endregion } }
namespace Tutorial.Introduction { using System; using System.IO; internal static partial class Functional { internal static FileInfo DownloadHtml(Uri uri) { return default; } internal static FileInfo ConvertToWord(FileInfo htmlDocument, FileInfo template) { return default; } internal static void UploadToOneDrive(FileInfo file) { } internal static Action<Uri, FileInfo> CreateDocumentBuilder( Func<Uri, FileInfo> download, Func<FileInfo, FileInfo, FileInfo> convert, Action<FileInfo> upload) { return (uri, wordTemplate) => { FileInfo htmlDocument = download(uri); FileInfo wordDocument = convert(htmlDocument, wordTemplate); upload(wordDocument); }; } } internal static partial class Functional { internal static void BuildDocument(Uri uri, FileInfo template) { Action<Uri, FileInfo> buildDocument = CreateDocumentBuilder( DownloadHtml, ConvertToWord, UploadToOneDrive); buildDocument(uri, template); } } }
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using RabbitMQ.Client; namespace RabbitMQ.Async { public class RabbitAsyncPublisher : IDisposable { private readonly BlockingCollection<EnqueuedMessage> _queue; private readonly IConfirmStrategy _confirmStrategy; private readonly Thread _thread; private readonly ConnectionHolder _connectionHolder; public RabbitAsyncPublisher(IConnectionFactory connectionFactory, bool publisherConfirms = true) { _queue = new BlockingCollection<EnqueuedMessage>(); _confirmStrategy = publisherConfirms ? (IConfirmStrategy) new AckNackConfirmStrategy() : new NoConfirmStrategy(); _connectionHolder = new ConnectionHolder(new[] {connectionFactory}, _confirmStrategy); _thread = new Thread(ThreadLoop) {Name = typeof (RabbitAsyncPublisher).Name}; _thread.Start(); } public void Dispose() { _queue.CompleteAdding(); _thread.Join(); _connectionHolder.Dispose(); _queue.Dispose(); } public Task PublishAsync(string exchange, byte[] body, string routingKey = "") { var tcs = new TaskCompletionSource<object>(); _queue.Add(new EnqueuedMessage { Exchange = exchange, Body = body, RoutingKey = routingKey, Tcs = tcs }); return tcs.Task; } private void ThreadLoop() { foreach (var msg in _queue.GetConsumingEnumerable()) { if (_queue.IsAddingCompleted) { msg.Tcs.TrySetCanceled(); continue; } _connectionHolder.Try(ch => { var basicProperties = ch.CreateBasicProperties(); basicProperties.SetPersistent(true); _confirmStrategy.Publishing(ch); ch.BasicPublish(msg.Exchange, msg.RoutingKey, basicProperties, msg.Body); _confirmStrategy.Published(msg.Tcs); }, ex => { msg.Tcs.TrySetException(ex); }); } } private class EnqueuedMessage { public byte[] Body { get; set; } public TaskCompletionSource<object> Tcs { get; set; } public string Exchange { get; set; } public string RoutingKey { get; set; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Loadgrid(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { Loadgrid(); } SqlConnection con = null; protected void Dbcon() { try { String strcon = "Data Source=DESKTOP-3R4I38T;Initial Catalog=Student;Integrated Security=True"; con = new SqlConnection(strcon); con.Open(); } catch (Exception) { throw; } } private void Loadgrid() { Dbcon(); String r = "select * from studentinfo"; DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(r, con); da.Fill(dt); if (dt.Rows.Count > 0) { GridView1.DataSource = dt; GridView1.DataBind(); } else { GridView1.DataSource = dt; GridView1.DataBind(); } con.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Restaurant.Models { public class NMViewModel { public int MessageID { get; set; } public string Subject { get; set; } public string Body { get; set; } public NewMessage newmes { get; set; } public NewMessage nm { get; set; } } }
using Conjure.Security; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using System.Threading.Tasks; namespace Example.Server.Controllers { [ApiController] [Route("api/security")] public class AppSecurityController : Controller { private static readonly AppUser AnonymousUser = new AppUser { IsAuthenticated = false, Name = "ServerAnon", }; [HttpGet("user")] public AppUser GetUser() { return User.Identity.IsAuthenticated ? new AppUser { IsAuthenticated = true, Name = User.Identity.Name, } : AnonymousUser; } [HttpGet("user/signin")] public async Task SignIn(string redirectUri) { if (string.IsNullOrEmpty(redirectUri) || !Url.IsLocalUrl(redirectUri)) { redirectUri = "/"; } await HttpContext.ChallengeAsync( new AuthenticationProperties { RedirectUri = redirectUri }); } [HttpGet("user/signout")] public async Task<IActionResult> SignOut() { await HttpContext.SignOutAsync( CookieAuthenticationDefaults.AuthenticationScheme); return Redirect("~/"); } [HttpGet("user/fake-signin")] public async Task<IActionResult> FakeSignIn(string redirectUri) { if (string.IsNullOrEmpty(redirectUri) || !Url.IsLocalUrl(redirectUri)) { redirectUri = "/"; } // Fake Login var identity = new ClaimsIdentity("fake"); identity.AddClaim(new Claim(ClaimTypes.Name, "FakeUser1")); await HttpContext.SignInAsync("fake", new ClaimsPrincipal(identity)); return Redirect(redirectUri); } [HttpGet("user/fake-signout")] public async Task<IActionResult> FakeSignOut() { await HttpContext.SignOutAsync("fake"); return Redirect("~/"); } } }
using System.Collections.Generic; using System.Globalization; using System.Threading; using Atc.Tests.XUnitTestData; using FluentAssertions; using Xunit; namespace Atc.Tests { public class EnumTranslationTests { [Theory] [MemberData(nameof(TestMemberDataForEnumTranslation.BooleanOperatorTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.CollectionActionTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.DateTimeDiffCompareTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.DropDownFirstItemTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.FileSystemWatcherChangeTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.ForwardReverseTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.IdentityRoleTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.InsertRemoveTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.LeftRightTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.LogCategoryTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.OnOffTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.SortDirectionTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.TriggerActionTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.UpDownTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] [MemberData(nameof(TestMemberDataForEnumTranslation.YesNoTypeData), MemberType = typeof(TestMemberDataForEnumTranslation))] public void ToDictionary<T>(T dummyForT, int arrangeUiLcid, List<KeyValuePair<int, string>> expectedKeyValues) where T : System.Enum { // ReSharper disable once UnusedVariable object dummyAssignment = dummyForT; // Arrange Thread.CurrentThread.CurrentUICulture = new CultureInfo(arrangeUiLcid); var type = dummyAssignment.GetType(); var includeDefault = type == typeof(DateTimeDiffCompareType) || type == typeof(LogCategoryType); // Act var actual = Enum<T>.ToDictionary(DropDownFirstItemType.None, true, includeDefault); // Assert actual.Should() .NotBeNull() .And.HaveCount(expectedKeyValues.Count) .And.Contain(expectedKeyValues); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CubeBehaviorScript : MonoBehaviour { public GameObject SomeObject; Rigidbody SomeRigidbody; Vector3 PositionOffset; private bool correct = true; private bool My_Play; AudioSource My_AudioSource; // Start is called before the first frame update void Start() { PositionOffset = SomeObject.transform.position; My_AudioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { if (correct) { SomeObject.transform.position = new Vector3(0, Mathf.Sin(Time.time) * 10, 0) + PositionOffset; if (Input.GetKeyDown(KeyCode.Space)) { My_Play = true; My_AudioSource.Play(); } } else { My_Play = false; My_AudioSource.Stop(); } } }
/* Copyright 2019 Sannel Software, L.L.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using System.Text.Json; using Sannel.House.SensorLogging.Models; using System; using System.Collections.Generic; using System.Text; namespace Sannel.House.SensorLogging.Data { public class SensorLoggingContext : DbContext { /// <summary> /// Gets the sensor entries. /// </summary> /// <value> /// The sensor entries. /// </value> public DbSet<SensorEntry> SensorEntries => Set<SensorEntry>(); /// <summary> /// Gets the devices. /// </summary> /// <value> /// The devices. /// </value> public DbSet<Device> Devices => Set<Device>(); /// <summary> /// Gets the sensor readings. /// </summary> /// <value> /// The sensor readings. /// </value> public DbSet<SensorReading> SensorReadings => Set<SensorReading>(); /// <summary> /// Initializes a new instance of the <see cref="SensorLoggingContext"/> class. /// </summary> /// <param name="options">The options for this context.</param> public SensorLoggingContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var se = modelBuilder.Entity<SensorEntry>(); //se.Property(i => i.Values) //.HasConversion( // j => (j == null)?null:JsonSerializer.Serialize(j, null), // k => (k == null)?null:JsonSerializer.Deserialize<Dictionary<string, double>>(k, null)); se.Property(i => i.SensorType) .HasConversion( j => (int)j, k => (Base.Sensor.SensorTypes)k ); se.HasMany(i => i.Values).WithOne("SensorEntry"); se.HasIndex(i => i.LocalDeviceId); se.HasIndex(i => i.SensorType); var sr = modelBuilder.Entity<SensorReading>(); sr.Property(i => i.Name).IsRequired(); sr.Property(i => i.Value).IsRequired(); sr.HasIndex(i => i.Name); var d = modelBuilder.Entity<Device>(); d.HasIndex(i => i.DeviceId); d.HasIndex(i => i.Uuid); d.HasIndex(i => i.MacAddress); d.HasIndex(nameof(Device.Manufacture), nameof(Device.ManufactureId)); } } }
 using System; using System.Collections.Generic; using System.Text; namespace AnyTest.IDataRepository { public interface IRepository<T>:IGetter<T>, IPoster<T>, IEditor<T>, IDeleter<T> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace TowerDefence.Buttons { class SellTowerButton : Button { public static int SellCost = 0; public SellTowerButton(IServiceProvider serviceProvider, Vector2 position) : base(serviceProvider, position) { base.text = "Sell Tower"; } protected override string getText() { return "Sell Tower : $" + SellCost.ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Core.BIZ; using Core.DAL; namespace WinForm.Views { public partial class frmDanhMucHoaDonDaiLy : Form { public frmDanhMucHoaDonDaiLy() { InitializeComponent(); } private List<DaiLy> _DMDaiLy; private HoaDonDaiLy _CurrentHD; private void LoadDaiLy() { _DMDaiLy = DaiLyManager.getAll(); cmbDaiLy.DataSource = _DMDaiLy; cmbDaiLy.DisplayMember = nameof(DaiLyManager.Properties.TenDaiLy); cmbDaiLy.ValueMember = nameof(DaiLyManager.Properties.MaSoDaiLy); } private void frmDanhMucHoaDonDaiLy_Load(object sender, EventArgs e) { createGridViewColumns(); LoadDaiLy(); btDuyet.Enabled = false; btXoa.Enabled = false; } private void btChuaDuyet_Click(object sender, EventArgs e) { gdvHoaDon.DataSource = HoaDonDaiLyManager.getUnaproved(); } private void btLoadAll_Click(object sender, EventArgs e) { gdvHoaDon.DataSource = HoaDonDaiLyManager.getAll(); } private void gdvHoaDon_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void gdvHoaDon_SelectionChanged(object sender, EventArgs e) { int index = ((DataGridView)sender).CurrentRow.Index; _CurrentHD = (((DataGridView)sender).DataSource as List<HoaDonDaiLy>)[index]; select(_CurrentHD); } public void select(HoaDonDaiLy hd) { if (hd != null) { txbMaHD.Text = hd.MaSoHoaDon + ""; cmbDaiLy.SelectedValue = hd.MaSoDaiLy; string day = hd.NgayLap.ToString(); DateTime thedate = DateTime.Parse(day); String dateString = thedate.ToString("yyyy/MM/dd"); day = dateString; char[] cut = day.ToCharArray(); string nam = ""; for (int i = 0; i < 4; i++) { nam += cut[i]; } string thang = ""; for (int i = 5; i < 7; i++) { thang += cut[i]; } string ngay = ""; for (int i = 8; i < 10; i++) { ngay += cut[i]; } dtpNgay.Value = new DateTime(int.Parse(nam), int.Parse(thang), int.Parse(ngay)); int trangthai = (int)hd.TrangThai; if (trangthai == 1) { btDuyet.Text = "Đã duyệt"; btDuyet.Enabled = false; btXoa.Enabled = false; } if (trangthai == 0) { btDuyet.Text = "Duyệt hóa đơn"; btDuyet.Enabled = true; btXoa.Enabled = true; } } } private void btnThoat_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Bạn có muốn thoát", "Thông báo", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { this.Close(); } else if (dialogResult == DialogResult.No) { return; } } private void btXoa_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Bạn có muốn xóa", "Thông báo", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { if (HoaDonDaiLyManager.delete(_CurrentHD.MaSoHoaDon)) MessageBox.Show("Đã xóa thành công hóa đơn"); else MessageBox.Show("Không xóa được"); } else if (dialogResult == DialogResult.No) { return; } } private void btDuyet_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Bạn có muốn duyệt hóa đơn", "Thông báo", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { if (_CurrentHD != null && _CurrentHD.TrangThai == 0) { if (_CurrentHD.accept()) { MessageBox.Show("Duyệt hóa đơn thành công"); gdvHoaDon.DataSource = HoaDonDaiLyManager.getAll(); } else MessageBox.Show("Duyệt không thành công, vui lòng kiểm tra lại Công nợ"); } } else if (dialogResult == DialogResult.No) { return; } } private void btXemCT_Click(object sender, EventArgs e) { frmChiTietHoaDonDaiLy fr = new frmChiTietHoaDonDaiLy(this, _CurrentHD); fr.Show(); } private void panelContainer_Paint(object sender, PaintEventArgs e) { } private void createGridViewColumns() { gdvHoaDon.AutoGenerateColumns = false; // Bỏ auto generate Columns gdvHoaDon.ColumnCount = 6; // Xác định số columns có setColumn(gdvHoaDon.Columns[0] , nameof(HoaDonDaiLyManager.Properties.MaSoHoaDon) , HoaDonDaiLyManager.Properties.MaSoHoaDon); setColumn(gdvHoaDon.Columns[1] , nameof(HoaDonDaiLyManager.Properties.MaSoDaiLy) , HoaDonDaiLyManager.Properties.MaSoDaiLy); setColumn(gdvHoaDon.Columns[2] , nameof(HoaDonDaiLyManager.Properties.DaiLy) , HoaDonDaiLyManager.Properties.DaiLy); setColumn(gdvHoaDon.Columns[3] , nameof(HoaDonDaiLyManager.Properties.NgayLap) , HoaDonDaiLyManager.Properties.NgayLap); setColumn(gdvHoaDon.Columns[4] , nameof(HoaDonDaiLyManager.Properties.TongTien) , HoaDonDaiLyManager.Properties.TongTien); setColumn(gdvHoaDon.Columns[5] , nameof(HoaDonDaiLyManager.Properties.TrangThai) , HoaDonDaiLyManager.Properties.TrangThai); gdvHoaDon.Columns[0].Width = 125; gdvHoaDon.Columns[1].Width = 125; gdvHoaDon.Columns[2].Width = 125; gdvHoaDon.Columns[3].Width = 125; gdvHoaDon.Columns[4].Width = 125; gdvHoaDon.Columns[5].Width = 100; } private void setColumn(DataGridViewColumn column, string propertyName, string name) { column.Name = propertyName; column.DataPropertyName = propertyName; column.HeaderText = name; } } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; [RequireComponent(typeof(Animator))] public class HitboxManager : MonoBehaviour { private const string PATH = "Hitboxes/Player"; //Carpeta contenedora (Separar con subcarpetas como "Player" o "Enemy") private HitboxLibrary[] m_HitBoxLibraries; private HitboxLibrary currenHitboxLibrary; private HitBox currentHitbox; private Animator m_Animator; protected PolygonCollider2D localCollider; #region Public methods public HitBox getCurrentHitbox() { return this.currentHitbox; } public void initialize() { m_Animator = GetComponent<Animator>(); LoadHitBoxLibraries(PATH); FindLocalCollider(); } public FrameData SearchFrameData(string id) { //int size = TemporalGameManager.newData.FramesData.Count; //Debug.Log("Tamano del arreglo de frames: " + size); string name = id; /* foreach (FrameData frameData in TemporalGameManager.newData.FramesData) { if (frameData.Id.Equals(name)) { return frameData; } }*/ return null; } #endregion void Start () { initialize(); } /// <summary> /// Cargar todas las librerias de hitbox asociados a este personaje en un lugar determinado /// </summary> /// <param name="path"></param> private void LoadHitBoxLibraries(string path) { m_HitBoxLibraries = Resources.LoadAll<HitboxLibrary>(path); //Debug.Log(m_HitBoxLibraries.Length); } private HitboxLibrary getHitboxLibrary(PrimaryWeaponType primaryWeaponType) { foreach (HitboxLibrary hitboxLibrary in m_HitBoxLibraries) { if (hitboxLibrary.primaryWeaponType.Equals(primaryWeaponType)) { return hitboxLibrary; } } return null; } #region Private methods private HitBox getHitbox(PrimaryWeaponType pwt, string animationName) { if (currenHitboxLibrary != null) { if (currenHitboxLibrary.primaryWeaponType != pwt) { setCurrentHitboxLibrary(pwt);//Filtro para buscar } } else { setCurrentHitboxLibrary(pwt);//Filtro para buscar } if (currenHitboxLibrary == null) { Debug.Log("No se encontro o no existe la libreria de hitbox del arma " + pwt.ToString()); return null; } else { for (int i = 0; i < currenHitboxLibrary.Hitbox.Length; i++) { if (currenHitboxLibrary.Hitbox[i].animationName.Equals(animationName)) { return currenHitboxLibrary.Hitbox[i]; } } } return null; } private void setCurrentHitboxLibrary(PrimaryWeaponType primaryWeaponType) { foreach (HitboxLibrary hitboxLibrary in m_HitBoxLibraries) { if (hitboxLibrary.primaryWeaponType.Equals(primaryWeaponType)) { this.currenHitboxLibrary = hitboxLibrary; } } if (currenHitboxLibrary == null) { Debug.Log("La libreria no se encontro, se colocara la libreria por defecto"); currenHitboxLibrary = m_HitBoxLibraries[0]; } } private void FindLocalCollider() { if (gameObject.GetComponent<PolygonCollider2D>() == null) { localCollider = gameObject.AddComponent<PolygonCollider2D>(); } else { localCollider = gameObject.GetComponent<PolygonCollider2D>(); } localCollider.isTrigger = true; localCollider.pathCount = 0; } #endregion public void Update() { //AnimatorClipInfo[] m_CurrentClipInfo = MyAnimator.GetCurrentAnimatorClipInfo(0); UpdateHitbox(); } public void UpdateHitbox() { //Debug.Log(hitBox.frameDataId); //Debug.Log("Total Frames = " + totalFrames); //Debug.Log("startUp = " + startUp); AnimatorClipInfo[] m_AnimatorClipInfo; m_AnimatorClipInfo = m_Animator.GetCurrentAnimatorClipInfo(0); AnimationClip anim = m_AnimatorClipInfo[0].clip; float animationLenght = anim.length; string animationName = anim.name; HitBox hitBox = getHitbox(PrimaryWeaponType.Staff, animationName); this.currentHitbox = hitBox; if (hitBox != null) { FrameData frameData = SearchFrameData(hitBox.frameData); int startUp = frameData.startUp; int recovery = frameData.recovery; int totalFrames = hitBox.totalFrames; float activationTime = timeToActivate(startUp, totalFrames); float desActivationTime = timeToActivate(recovery, totalFrames); float totalNormalizedTime = m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime; if (anim.name == hitBox.animationName) { if (totalNormalizedTime >= activationTime && totalNormalizedTime <= desActivationTime) //normalizedTime va de 0 a 1; { //Debug.Log("Activar"); setColliderHitbox(hitBox); } else { //Debug.Log("Desactivar"); setColliderHitbox(new HitBox()); } } } else { Debug.Log("No se encontro el hitbox que buscabas"); } } private float timeToActivate(int startUp , int totalFrames) { float timeToActivate = ((startUp * 100.0f) / totalFrames) / 100.0f; return timeToActivate; } public void setColliderHitbox(HitBox hitBox) { if (hitBox.hitBox != null) { localCollider.SetPath(0, hitBox.hitBox.GetPath(0)); //localCollider.SetPath(0, colliders[(int)val].GetPath(0)); return; } localCollider.pathCount = 0; } }
using Common; using Common.Business; using Common.Data; using Common.Exceptions; using Common.Extensions; using Contracts.ContentOps; using Entity; using LFP.Common.DataAccess; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.ServiceModel; using System.Text; using System.Windows.Forms; namespace Services.ContentOps { [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession)] public class ContentOpsService : IContentOpsService { #region Private Fields private string mConnectionString = String.Empty; private DataAccess mDataAccess = null; private int mInstance = 0; private string mUserName = String.Empty; private const string mXXXSort = "10, 9, 8, 6, 5, 14, 4, 1, 2, 7, 15, 3, 11,"; //Ratings from lowest to highest. #endregion #region Public Methods public bool AddAMHistory(TrackBHistory data) { TrackBHistory history = new TrackBHistory(); try { return history.AddAMHistory(mConnectionString, data); } finally { history = null; } } public bool AddDSMBW500History(TrackDSMBW500History data) { TrackDSMBW500History history = new TrackDSMBW500History(); try { return history.AddHistory(mConnectionString, data); } finally { history = null; } } public bool AddHDHistory(TrackQHistory data) { TrackQHistory history = new TrackQHistory(); try { return history.AddRecord(mConnectionString, data); } finally { history = null; } } public bool AddItemToAMFixesScreen(int id) { ConformingAMFixes fixes = new ConformingAMFixes(); try { return fixes.AddItemToAMFixesScreen(mConnectionString, id); } finally { fixes = null; } } public bool AddLocationHistory(int id, string track, string digital, string analog, string userName, bool wmv) { bool result = false; TrackBHistory trackB = null; string sql = ""; try { if (track.Equals("B")) { trackB = new TrackBHistory(); trackB.ID = id; trackB.History_Date = DateTime.Now; if (!String.IsNullOrEmpty(analog)) trackB.Location = analog; if (!String.IsNullOrEmpty(digital)) trackB.Location_Digital = digital; trackB.Notes = "Movement - Location Change"; trackB.Username = userName; Tuple<string, string> tuple = GetAMStatuses(id); if (tuple != null) { trackB.Status = tuple.Item1; trackB.Previous_Status = tuple.Item2; } result = AddAMHistory(trackB); } else { string locationString = ""; if (!track.Equals("Y") && !wmv) //Do not update location if track is Y and has been submitted to WMV. { if (!String.IsNullOrEmpty(analog)) locationString = analog; if (!String.IsNullOrEmpty(digital)) locationString = digital; } sql = "insert track_" + track + "_history (id, history_date, location, username, notes) "; sql += "values (" + id.ToString() + ", '" + DateTime.Now.ToString() + "', '" + locationString + "', " + "'" + userName + "', 'Movement - Location Change')"; if (track.Equals("Y") && wmv) { sql = "insert track_" + track + "_history (id, history_date, date_submitted, username, notes) "; sql += "values (" + id.ToString() + ", '" + DateTime.Now.ToString() + "', " + "'" + DateTime.Now.ToString() + "', '" + userName + "', 'Movement - Location Change')"; } using (Database database = new Database(mConnectionString)) { result = database.ExecuteNonQuery(sql); } } } catch (Exception e) { throw new EntityException(sql, e); } finally { trackB = null; } return result; } public bool AddProjectIdData(MRGProjectProjectIDs data) { MRGProjectProjectIDs ids = new MRGProjectProjectIDs(); try { return ids.AddRecord(mConnectionString, data); } finally { ids = null; } } public bool AddQueueRecord(QueueLTORetrieve data) { QueueLTORetrieve queue = new QueueLTORetrieve(); try { return queue.AddRecord(mConnectionString, data); } finally { queue = null; } } public bool AddUpdateAMRecord(TrackB data, bool isNew) { TrackB trackB = new TrackB(); try { return trackB.AddUpdateRecord(mConnectionString, data, isNew); } finally { trackB = null; } } public bool AddUpdateHDRecord(TrackQ data, bool isNew) { TrackQ q = new TrackQ(); try { return q.AddUpdateRecord(mConnectionString, data, isNew); } finally { q = null; } } public bool AddUpdateInternationalQC(IInternationalQC data, string assetType) { bool result = false; TrackBInternationalQC trackB = null; TrackPixilatedInternationalQC pixilated = null; TrackSInternationalQC trackS = null; try { switch (assetType) { case "B": trackB = new TrackBInternationalQC(); result = trackB.AddUpdateRecord(mConnectionString, (TrackBInternationalQC)data); break; case "Pixilated": pixilated = new TrackPixilatedInternationalQC(); break; case "S": trackS = new TrackSInternationalQC(); break; } } finally { trackB = null; pixilated = null; trackS = null; } return result; } public bool AddUpdateJRecord(TrackJ data, bool isNew) { TrackJ j = new TrackJ(); try { return j.AddUpdateRecord(mConnectionString, data, isNew); } finally { j = null; } } public bool AddUpdateLocation(int id, string track, string digital, string analog, string userName, bool wmv) { bool result = false; TrackB trackB = null; TrackY trackY = null; string sql = "select * from track_" + track + " where id = " + id.ToString(); ; bool isNew = false; try { if (track.Equals("B")) { trackB = new TrackB(); TrackB b = trackB.GetAirMaster(mConnectionString, id); if (b == null) { isNew = true; b = new TrackB(); b.ID = id; b.Create_Date = DateTime.Now; } if (!String.IsNullOrEmpty(analog)) b.Location = analog; if (!String.IsNullOrEmpty(digital)) b.Location_Digital = digital; b.LastModified_Date = DateTime.Now; b.LastModified_Username = userName; result = AddUpdateAMRecord(b, isNew); } else { using (Database database = new Database(mConnectionString)) { using (DataTable table = database.ExecuteSelect(sql)) { if (table.Rows.Count == 0) isNew = true; } } if (track.Equals("Y")) { trackY = new TrackY(); TrackY y = new TrackY(); y.ID = id; if (!String.IsNullOrEmpty(analog)) y.Location = analog; if (!String.IsNullOrEmpty(digital)) y.Location = digital; y.LastModified = DateTime.Now; y.LastUsername = userName; if (wmv) y.Date_Submitted = DateTime.Now; result = trackY.AddUpdateRecord(mConnectionString, y, isNew); } else { string locationString = ""; if (!String.IsNullOrEmpty(analog)) locationString = analog; if (!String.IsNullOrEmpty(digital)) locationString = digital; using (Database database = new Database(mConnectionString)) { if (isNew) { sql = "insert track_" + track + " (id, location, lastmodified, lastusername) "; sql += "values (" + id.ToString() + ", "; sql += "'" + locationString + "', '" + DateTime.Now.ToString() + "', '" + userName + "')"; result = database.ExecuteNonQuery(sql); } else { sql = "update track_" + track + " set location = '" + locationString + "', " + "lastmodified = '" + DateTime.Now.ToString() + "', lastusername = '" + userName + "' " + "where id =" + id.ToString(); result = database.ExecuteNonQuery(sql); } } } } } catch (Exception e) { throw new EntityException(sql, e); } finally { trackY = null; trackB = null; } return result; } public bool AddUpdateYRecord(TrackY data, bool isNew) { TrackY y = new TrackY(); try { return y.AddUpdateRecord(mConnectionString, data, isNew); } finally { y = null; } } public Tuple<string, int> CheckAssetExists(string id, string subId) { Tuple<string, int> result = null; string[] list = { "A", "AA", "AMCC", "B", "C", "D", "DD", "DMG", "E", "F", "FCP", "G", "J", "K", "L", "M", "O", "PP", "T", "Y" }; string sql = "select location, passed from track_" + subId + " where id = " + id; if (list.Contains(subId)) sql = "select location from track_" + subId + " where id = " + id; using (Database database = new Database(mConnectionString)) { try { using (DataTable table = database.ExecuteSelect(sql)) { if (table.HasRows()) { DataRow row = table.Rows[0]; string location = row["location"].ToString(); int status = -1; if (table.Columns.Count > 1) status = Convert.ToInt32(row["passed"]); result = new Tuple<string, int>(location, status); } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public QueueLTORetrieve CheckLTOQueueRecordExists(int id, string path, string fileName) { QueueLTORetrieve queue = new QueueLTORetrieve(); try { return queue.CheckRecordExists(mConnectionString, id, path, fileName); } finally { queue = null; } } public bool CheckMOVExists(int id) { LTO lto = new LTO(); try { return lto.CheckMOVExists(mConnectionString, id); } finally { lto = null; } } public MovieConform CheckMovieConformExists(int id) { //TODO return null; } public bool CheckProductionTemplateExists(string userName, string templateName, bool shared) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.CheckTemplateExists(mConnectionString, userName, templateName, shared); } finally { prod = null; } } public bool CheckProjectTemplateExists(string userName, string templateName, bool shared) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.CheckTemplateExists(mConnectionString, userName, templateName, shared); } finally { mrg = null; } } public bool CheckRejectionExists(int id) { SapphireRejections rejections = new SapphireRejections(); try { return rejections.CheckExists(mConnectionString, id); } finally { rejections = null; } } public bool CheckTitleOnAssetFailureExists(int id) { TrackSQC qc = new TrackSQC(); try { return qc.CheckTitleOnAssetFailureExists(mConnectionString, id); } finally { qc = null; } } public TrackSQC CheckTrackSQCRecordExists(int id, int itemNumber) { TrackSQC sqc = null; try { return sqc.CheckRecordExists(mConnectionString, id, itemNumber); } finally { sqc = null; } } public TrackY CheckTrackYRecordExists(int id) { TrackY y = new TrackY(); try { return y.CheckRecordExists(mConnectionString, id); } finally { y = null; } } public void CreateContentOpsMethods(string connectionString, string userName, int instance) { mConnectionString = connectionString; mUserName = userName; mDataAccess = new DataAccess(connectionString, userName); mInstance = instance; } public bool DeleteProductionTemplate(string userName, string templateName, bool shared) { bool result = false; UsersContentOpsProd prod = new UsersContentOpsProd(); try { if (shared) result = prod.DeleteSharedTemplate(mConnectionString, userName, templateName); else result = prod.DeleteMyTemplate(mConnectionString, userName, templateName); } finally { prod = null; } return result; } public bool DeleteProject(int id) { bool result = true; MRGProjectProjectHeader header = new MRGProjectProjectHeader(); MRGProjectProjectColumns columns = new MRGProjectProjectColumns(); try { result &= columns.DeleteColumns(mConnectionString, id); result &= DeleteProjectIds(id); result &= header.DeleteProjectHeader(mConnectionString, id); } finally { columns = null; header = null; } return result; } public bool DeleteProjectIds(int projectId) { MRGProjectProjectIDs ids = new MRGProjectProjectIDs(); try { return ids.DeleteIds(mConnectionString, projectId); } finally { ids = null; } } public bool DeleteProjectTemplate(string userName, string templateName, bool shared) { bool result = false; UsersMRGProjects mrg = new UsersMRGProjects(); try { if (shared) result = mrg.DeleteSharedTemplate(mConnectionString, userName, templateName); else result = mrg.DeleteMyTemplate(mConnectionString, userName, templateName); } finally { mrg = null; } return result; } public bool DeleteSapphireRejection(int id) { SapphireRejections sapphire = new SapphireRejections(); try { return sapphire.DeleteRecord(mConnectionString, id); } finally { sapphire = null; } } public TrackB GetAirMaster(int id) { TrackB b = new TrackB(); try { return b.GetAirMaster(mConnectionString, id); } finally { b = null; } } public string GetAlternateMovieTitle(int id) { Movie movie = new Movie(); try { return movie.GetBroadcastTitle(mConnectionString, id); } finally { movie = null; } } public int GetAlternateSDHDId(int id) { return mDataAccess.GetAltSDHDId(id); } public Tuple<string, string, string> GetAMLocationStatus(int id) { TrackB b = new TrackB(); try { return b.GetLocationStatus(mConnectionString, id); } finally { b = null; } } public Tuple<string, string> GetAMLocationStatuses(int id) { return GetAMStatuses(id); } public List<string> GetAnalogLocations() { SystemLocation location = new SystemLocation(); try { return location.GetLocations(mConnectionString); } finally { location = null; } } public int GetAssetId(int id, string track) { return mDataAccess.GetAssetId(id, track); } public string GetAssignedEmployeeString() { PromotionsListEmployees ple = new PromotionsListEmployees(); try { string result = ple.GetAssignedEmployees(mConnectionString); result += "COD|"; result += "Conforming 1|"; result += "Conforming 2|"; result += "Conforming 3|"; result += "Conforming 4|"; result += "Edit Bay 1|"; result += "Edit Bay 2|"; result += "Edit Bay 3|"; result += "Edit Bay 4|"; result += "Storage Cabinet - LA|"; result += "Storage Cabinet - Winchester"; return result; } finally { ple = null; } } public DataTable GetCCMovie(int id) { Movie movie = new Movie(); try { return movie.GetCCMovie(mConnectionString, id); } finally { movie = null; } } public List<string> GetChannels() { SystemStations stations = new SystemStations(); try { return stations.GetChannels(mConnectionString, 1); } finally { stations = null; } } public string[] GetChannelsById(int id) { MovieChannel channel = new MovieChannel(); try { return channel.GetChannels(mConnectionString, id); } finally { channel = null; } } public string GetClipAlternateId(int id, int rating, int hd) { string result = String.Empty; string derivedAsset = ""; int highestRatingPosition = -2; string title = ""; string highestRatingTitle = ""; Movie movie = new Movie(); MovieDerivative derivative = null; string ratingString = rating.ToString(); try { title = movie.GetBroadcastTitle1(mConnectionString, id); if (String.IsNullOrEmpty(title)) return ""; int masterId = mDataAccess.GetMasterId(id); if (masterId < 1) return ""; derivative = new MovieDerivative(); using (DataTable table = derivative.GetClip(mConnectionString, masterId, hd)) { foreach (DataRow dr in table.Rows) { string xxx = dr["xxx"].ToString(); if (mXXXSort.IndexOf(" " + xxx + ",") > highestRatingPosition) //Rating is higher than we currently have. { highestRatingPosition = mXXXSort.IndexOf(" " + xxx + ","); highestRatingTitle = dr["title"].ToString(); derivedAsset = "0,"; if (dr["has_file"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["has_file"]) == 1) derivedAsset = "1,"; else { if (dr["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } } else { if (dr["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } derivedAsset += dr["id"].ToString(); } else { if (mXXXSort.IndexOf(" " + xxx + ",") == highestRatingPosition) //Rating is the same. { if (dr["title"].ToString().Equals(title)) { //Change the current asset if the title is the same. highestRatingPosition = mXXXSort.IndexOf(" " + xxx + ","); highestRatingTitle = dr["title"].ToString(); derivedAsset = "0,"; if (dr["has_file"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["has_file"]) == 1) derivedAsset = "1,"; else { if (dr["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } } else { if (dr["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } derivedAsset += dr["id"].ToString(); } } } } } result = derivedAsset; } finally { derivative = null; movie = null; } return result; } public string GetClipStatus(int id) { return mDataAccess.GetStatusClip(id); } public DataTable GetClosedCaptionReportData(string ids) { Movie movie = new Movie(); try { return movie.GetCloseCaptionReportData(mConnectionString, ids); } finally { movie = null; } } public DataTable GetClosedCaptionSchedules() { SystemStations stations = new SystemStations(); try { return stations.GetClosedCaptioningSchedules(mConnectionString); } finally { stations = null; } } public DataTable GetClosedCaptionSchedules(string assetType, string channels, string channelsPlus1Month, string assetIds, string period, bool showAll) { DataTable result = null; Movie movie = null; Schedule schedule = null; try { if (assetType.Equals("All")) { movie = new Movie(); result = movie.GetCloseCaptionMovies(mConnectionString, assetIds); } else { schedule = new Schedule(); result = schedule.GetCloseCaptionMovies(mConnectionString, assetType, channels, channelsPlus1Month, period, showAll); } } finally { movie = null; schedule = null; } return result; } public DataTable GetComps(int id) { ETCBlock etc = new ETCBlock(); try { return etc.GetComps(mConnectionString, id); } finally { etc = null; } } public Tuple<string, string, string> GetConformingRunTimes(int id) { MovieConform conform = new MovieConform(); try { return conform.GetRuntimes(mConnectionString, id); } finally { conform = null; } } public int GetCurrentHistoryCount(int id, int itemNumber, string type) { int result = 0; TrackBQC trackB = null; switch (type) { case "B": trackB = new TrackBQC(); result = trackB.GetCurrentRecordCount(mConnectionString, id, itemNumber); break; } return result; } public DataTable GetDerivative(int id) { MovieDerivative derivative = new MovieDerivative(); try { return derivative.GetDerivative(mConnectionString, id); } finally { derivative = null; } } public List<string> GetDigitalLocations() { SystemLocationDigital sld = new SystemLocationDigital(); try { return sld.GetLocations(mConnectionString); } finally { sld = null; } } public DataTable GetDSMBW500Record(int id) { TrackDSMBW500 dsmbw500 = new TrackDSMBW500(); try { return dsmbw500.GetItem(mConnectionString, id); } finally { dsmbw500 = null; } } public string GetDSMBW500SourceLocation(int id) { TrackDSMBW500 dsmbw = new TrackDSMBW500(); try { return dsmbw.GetSourceLocation(mConnectionString, id); } finally { dsmbw = null; } } public string GetEditSourceLocation(int id) { TrackC c = new TrackC(); try { return c.GetLocation(mConnectionString, id); } finally { c = null; } } public int GetFailureCount(int id, int itemNumber, string track, string type) { int result = 0; TrackBQC trackB = null; try { switch (track) { case "B": trackB = new TrackBQC(); result = trackB.GetFailureCount(mConnectionString, id, itemNumber, type); break; } } finally { trackB = null; } return result; } public string GetFCPXmlColor(string type, int id) { string result = ""; Movie movie = null; MovieDerivative derivative = null; ETCBlock etc = null; TrackDSMBCC dsm = null; try { switch (type) { case "Clip": case "Wireless Clip": case "Movie": movie = new Movie(); int masterId = mDataAccess.GetMasterId(id); if (masterId > 0) result = movie.GetColor(mConnectionString, masterId, type); break; case "Clip Comp": case "Short Clip Comp": etc = new ETCBlock(); result = etc.GetColor(mConnectionString, id); break; case "Episode Comp": case "Scene Comp": derivative = new MovieDerivative(); result = derivative.GetColor(mConnectionString, id); break; case "Episode": case "Scene": dsm = new TrackDSMBCC(); result = dsm.GetPassedQC(mConnectionString, id); break; } } finally { dsm = null; etc = null; derivative = null; movie = null; } return result; } public TrackFCPXml GetFCPXmlRecord(int id) { TrackFCPXml xml = new TrackFCPXml(); try { return xml.GetFCPXmlRecord(mConnectionString, id); } finally { xml = null; } } public List<string> GetFormats() { SystemDSMBFormat dsmb = new SystemDSMBFormat(); try { return dsmb.GetDSMBFormats(mConnectionString); } finally { dsmb = null; } } public DataTable GetHardDriveLocations(List<int> ids) { TrackQ trackQ = new TrackQ(); try { return trackQ.GetHardDriveLocations(mConnectionString, ids); } finally { trackQ = null; } } public List<Tuple<int, string>> GetHardDriveMovies(int option) { Movie movie = new Movie(); try { return movie.GetHardDriveMovies(mConnectionString, option); } finally { movie = null; } } public List<string> GetHardDriveNotes(List<int> ids) { MovieNotes notes = new MovieNotes(); try { List<string> result = new List<string>(); foreach (int id in ids) { result.AddRange(notes.GetMovieNotes(mConnectionString, id)); } return result; } finally { notes = null; } } public string GetHardDriveString() { SystemLocationHardDriveNOOF noof = new SystemLocationHardDriveNOOF(); try { string result = noof.GetLocationString(mConnectionString); result += "Storage Cabinet - LA|"; result += "Storage Cabinet - Winchester"; return result; } finally { noof = null; } } public TrackQ GetHDRecord(int id) { TrackQ q = new TrackQ(); try { return q.GetHDRecord(mConnectionString, id); } finally { q = null; } } public string GetHighestRateSource(int id, string type, string movieTypes) { string result = ""; if (!movieTypes.StartsWith("(")) movieTypes = "(" + movieTypes; if (!movieTypes.EndsWith(")")) movieTypes += ")"; MovieDerivative derivative = new MovieDerivative(); string derivedAsset = ""; try { int masterId = id; if (type.Equals("Master")) masterId = mDataAccess.GetMasterId(id); if (masterId > 0) { using (DataTable table = derivative.GetRateSource(mConnectionString, type, masterId, movieTypes)) { if (table.HasRows()) { bool highestRateHD = false; int highestRatePosition = -1; foreach (DataRow row in table.Rows) { int xxxPosition = mXXXSort.IndexOf(" " + row["xxx"].ToString() + ","); if (xxxPosition > highestRatePosition) { highestRatePosition = xxxPosition; if (row["HD"].GetType() != typeof(DBNull)) highestRateHD = (Convert.ToInt32(row["HD"]) == 1); derivedAsset = "0,"; if (row["has_file"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(row["has_file"]) == 1) derivedAsset = "1,"; else { if (row["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } } else { if (row["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } derivedAsset += row["ID"].ToString(); } else if (xxxPosition == highestRatePosition) { if (row["HD"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(row["HD"]) == 1 && !highestRateHD) { highestRateHD = true; derivedAsset = "0,"; if (row["has_file"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(row["has_file"]) == 1) derivedAsset = "1,"; else { if (row["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } } else { if (row["has_SRT"].GetType() != typeof(DBNull)) derivedAsset = "2,"; } derivedAsset += row["ID"].ToString(); } } } } } } } result = derivedAsset; } finally { derivative = null; } return result; } public IInternationalQC GetInternationalQC(int id, string type) { IInternationalQC result = null; TrackBInternationalQC trackB = null; TrackPixilatedInternationalQC pixilated = null; TrackSInternationalQC trackS = null; try { switch (type) { case "B": trackB = new TrackBInternationalQC(); result = trackB.GetQC(mConnectionString, id); break; case "Pixilated": pixilated = new TrackPixilatedInternationalQC(); break; case "S": trackS = new TrackSInternationalQC(); break; } } finally { trackB = null; pixilated = null; trackS = null; } return result; } public TrackJ GetJRecord(int id) { TrackJ j = new TrackJ(); try { return j.GetRecordById(mConnectionString, id); } finally { j = null; } } public LTO GetLTOInfo(int id, string track) { LTO lto = new LTO(); try { return lto.GetLTOInfo(mConnectionString, id, track); } finally { lto = null; } } public int GetMarkedAsFailedCount(int id) { TrackSHistory history = new TrackSHistory(); try { return history.GetMarkedAsFailedCount(mConnectionString, id); } finally { history = null; } } public int GetMasterId(int id) { return mDataAccess.GetMasterId(id); } public int GetMasterIdByScreenerId(int id) { Movie movie = new Movie(); try { return movie.GetMasterIdByScreenerId(mConnectionString, id); } finally { movie = null; } } public List<Tuple<int, string, int?>> GetMOVData(string location, int id) { TrackDSMBW500MOV mov = new TrackDSMBW500MOV(); try { return mov.GetMOVData(mConnectionString, location, id); } finally { mov = null; } } public Tuple<int, string> GetMovie(int id) { Movie movie = new Movie(); try { return movie.GetMovieIdTitle(mConnectionString, id); } finally { movie = null; } } public Tuple<string, int> GetMovieContractTitleRating(int id) { Movie movie = new Movie(); try { return movie.GetMovieContractTitleRating(mConnectionString, id); } finally { movie = null; } } public string GetMovieType(int id) { return mDataAccess.GetItemType(id); } public int GetMRGProjectId(string name) { MRGProjectProjectHeader header = new MRGProjectProjectHeader(); try { return header.GetProjectId(mConnectionString, name); } finally { header = null; } } public List<string> GetMRGProjectNames(int id) { MRGProjectProjectHeader header = new MRGProjectProjectHeader(); try { return header.GetProjectNames(mConnectionString, id); } finally { header = null; } } public List<string> GetMRGTemplateNames() { MRGProjectTemplate template = new MRGProjectTemplate(); try { return template.GetTemplateNames(mConnectionString); } finally { template = null; } } public string[] GetMSOAltTitles() { SystemMSOAltTitles smat = new SystemMSOAltTitles(); try { List<string> result = smat.GetDisplayNames(mConnectionString); if (result.Count > 0) return result.ToArray(); return null; } finally { smat = null; } } public UsersContentOpsProd GetMyProductionTemplate(string template, string userName) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetProjectTemplate(mConnectionString, userName, template); } finally { prod = null; } } public DataTable GetMyProductionTemplateDataTable(string template, string userName) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetMyTemplateDataTable(mConnectionString, userName, template); } finally { prod = null; } } public List<string> GetMyProductionTemplates(string userName) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetMyTemplates(mConnectionString, userName); } finally { prod = null; } } public UsersMRGProjects GetMyProjectTemplate(string template, string userName) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetProjectTemplate(mConnectionString, userName, template); } finally { mrg = null; } } public DataTable GetMyProjectTemplateDataTable(string template, string userName) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetMyTemplateDataTable(mConnectionString, userName, template); } finally { mrg = null; } } public List<string> GetMyProjectTemplates(string userName) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetMyTemplates(mConnectionString, userName); } finally { mrg = null; } } public string GetNADByType(int id, string type) { return mDataAccess.GetNAD(id, type); } public Tuple<int, int, string> GetNADInfo(int id) { Movie movie = new Movie(); try { return movie.GetNADInfo(mConnectionString, id); } finally { movie = null; } } public int GetNewProjectId(string userName) { MRGProjectProjectHeader header = new MRGProjectProjectHeader(); try { if (header.AddProject(mConnectionString, userName)) return header.GetProjectId(mConnectionString, userName); return -1; } finally { header = null; } } public string GetNextAirDate(int id) { Schedule schedule = new Schedule(); try { return schedule.GetNextAirDate(mConnectionString, id); } finally { schedule = null; } } public int GetNOCUnderReviewCount(int id) { TrackSHistory history = new TrackSHistory(); try { return history.GetNOCUnderReviewCount(mConnectionString, id); } finally { history = null; } } public string GetNotes(int id) { MovieNotes notes = new MovieNotes(); try { List<string> list = notes.GetMovieNotes(mConnectionString, id); if (list.Count > 0) return list[0]; return ""; } finally { notes = null; } } public int GetOtherVersionId(int masterId, bool isHD, string type, int rating) { MovieDerivative derivative = new MovieDerivative(); try { return derivative.GetOtherVersionId(mConnectionString, masterId, isHD, type, rating); } finally { derivative = null; } } public string GetPathById(string id) { return mDataAccess.GetPathById(id); } public DataTable GetPreferences(string userName) { TrafficProductionPreferences tpp = new TrafficProductionPreferences(); try { return tpp.GetPreferences(mConnectionString, userName); } finally { tpp = null; } } public string GetProductionTemplateCreator(string template, int? shared = null) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetTemplateCreator(mConnectionString, template, shared); } finally { prod = null; } } public UsersContentOpsProd GetProductionTemplateInfo(string userName, string templateName) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetTemplateInfo(mConnectionString, userName, templateName); } finally { prod = null; } } public string GetProjectTemplateCreator(string template, int? shared = null) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetTemplateCreator(mConnectionString, template, shared); } finally { mrg = null; } } public UsersMRGProjects GetProjectTemplateInfo(string userName, string templateName) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetTemplateInfo(mConnectionString, userName, templateName); } finally { mrg = null; } } public DataTable GetProjectTemplateList(string userName, string templateName, ref int currentId) { DataTable result = null; UsersMRGProjects mrg = new UsersMRGProjects(); MRGProjectTemplate mpt = null; MRGProjectProjectColumns mppc = null; try { result = mrg.GetTemplateList(mConnectionString, userName); if (result == null || result.Rows.Count == 0) { result = new DataTable("MRG"); //Create default columns. result.Columns.Add(new DataColumn("ID", typeof(int))); result.Columns.Add(new DataColumn("Contract Title", typeof(string))); result.Columns.Add(new DataColumn("Broadcast Title 1", typeof(string))); mpt = new MRGProjectTemplate(); MRGProjectTemplate template = mpt.GetTemplate(mConnectionString, templateName); if (template != null) { if (template.Template_ID.HasValue) currentId = template.Template_ID.Value; } mppc = new MRGProjectProjectColumns(); List<string> columns = mppc.GetColumnNames(mConnectionString, currentId); foreach (string col in columns) { result.Columns.Add(new DataColumn(col)); } //Add remaining default columns. result.Columns.Add(new DataColumn("Air Date", typeof(DateTime))); result.Columns.Add(new DataColumn("Show In Conforming", typeof(bool))); result.Columns.Add(new DataColumn("Show In Media Services", typeof(bool))); result.Columns.Add(new DataColumn("Show In Production Status", typeof(bool))); } } finally { mppc = null; mpt = null; mrg = null; } return result; } public List<ITrackQCHistory> GetQCHistory(int id, string type) { List<ITrackQCHistory> result = new List<ITrackQCHistory>(); TrackBQCHistory trackB = null; try { switch (type) { case "B": trackB = new TrackBQCHistory(); foreach (TrackBQCHistory item in trackB.GetHistoryList(mConnectionString, id)) { result.Add(item as ITrackQCHistory); } break; } } finally { trackB = null; } return result; } public ITrackQCHistory GetQCHistoryById(int historyId, string type) { ITrackQCHistory result = null; TrackBQCHistory trackB = null; try { switch (type) { case "B": trackB = new TrackBQCHistory(); result = trackB.GetRecordById(mConnectionString, historyId) as ITrackQCHistory; break; } } finally { trackB = null; } return result; } public string GetRatingText(int xxx) { return mDataAccess.GetXXX(xxx); } public List<Tuple<string, string>> GetRelatedFiles(int id, string track) { LTO lto = new LTO(); try { return lto.GetRelatedFiles(mConnectionString, id, track); } finally { lto = null; } } public List<string> GetSapphireAirDates(int id) { Schedule schedule = new Schedule(); try { return schedule.GetSapphireAirDates(mConnectionString, id); } finally { schedule = null; } } public List<int> GetSapphireRejectedIds(bool save, bool email, ref string messageBody, int addId = -1) { List<int> result = new List<int>(); SapphireRejections sr = new SapphireRejections(); bool hasFutureAirDate = false; string airDates = ""; List<int> ids = new List<int>(); try { if (addId > -1) ids.Add(addId); else ids = sr.GetRejectedIds(mConnectionString); if (save) { foreach (int id in ids) { hasFutureAirDate = false; List<string> dates = GetSapphireAirDates(id); foreach (string date in dates) { airDates += date; DateTime airDate = Convert.ToDateTime(date.Substring(0, date.IndexOf(" ")).Trim()); if (airDate > DateTime.Now) hasFutureAirDate = true; } if (airDates.Trim().Length > 0) { if (MessageBox.Show("This asset has the following air date(s):\n" + airDates + "\n\n" + "Would you like to add this asset anyway?", "Add ID", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) continue; if (hasFutureAirDate) { if (email) { messageBody += "The following asset has been added to the Sapphire Rejection list:\n\n"; messageBody += id.ToString().PadLeft(8, '0') + " "; messageBody += GetAlternateMovieTitle(id); } } //If the ID is already in the list, skip it. if (CheckRejectionExists(id)) { MessageBox.Show("The ID " + id.ToString() + " is already in the list. It will not be imported.", "Import", MessageBoxButtons.OK, MessageBoxIcon.Information); continue; } result.Add(id); } } } } finally { sr = null; } return result; } public DataTable GetSapphireRejectionRecord(int id) { DataTable result = new DataTable(); result.Columns.Add(new DataColumn("ID", typeof(int))); result.Columns.Add(new DataColumn("Alt ID", typeof(int))); result.Columns.Add(new DataColumn("Contract Title", typeof(string))); result.Columns.Add(new DataColumn("Notes", typeof(string))); DataRow row = result.NewRow(); Tuple<int, string> movie = GetMovie(id); string notes = GetNotes(id); row["ID"] = id; row["Alt ID"] = movie.Item1; row["Contract Title"] = movie.Item2; row["Notes"] = notes; result.Rows.Add(row); return result; } public string GetSCCPath() { SystemMediaLocations mediaLocations = new SystemMediaLocations(); try { return mediaLocations.GetMediaPathByFriendlyName(mConnectionString, "SCC"); } finally { mediaLocations = null; } } public DataTable GetScheduledCCAsset(int id) { Movie movie = new Movie(); try { return movie.GetScheduledCCAsset(mConnectionString, id); } finally { movie = null; } } public ScreenerMovie GetScreener(int id) { ScreenerMovie screener = new ScreenerMovie(); try { return screener.GetScreenerMovie(mConnectionString, id); } finally { screener = null; } } public UsersContentOpsProd GetSharedProductionTemplate(string template) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetSharedTemplate(mConnectionString, template); } finally { prod = null; } } public DataTable GetSharedProductionTemplateDataTable(string template) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetSharedTemplateDataTable(mConnectionString, template); } finally { prod = null; } } public string GetSharedProductionTemplateLastUser(string template) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetSharedTemplateLastUser(mConnectionString, template); } finally { prod = null; } } public List<SharedTemplate> GetSharedProductionTemplates() { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.GetSharedTemplates(mConnectionString); } finally { prod = null; } } public UsersMRGProjects GetSharedProjectTemplate(string template) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetSharedTemplate(mConnectionString, template); } finally { mrg = null; } } public DataTable GetSharedProjectTemplateDataTable(string template) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetSharedTemplateDataTable(mConnectionString, template); } finally { mrg = null; } } public string GetSharedProjectTemplateLastUser(string template) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetSharedTemplateLastUser(mConnectionString, template); } finally { mrg = null; } } public List<SharedTemplate> GetSharedProjectTemplates() { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.GetSharedTemplates(mConnectionString); } finally { mrg = null; } } public List<string> GetShipAddressees() { List<string> result = new List<string>(); ShipAddress ship = new ShipAddress(); try { List<ShipAddress> list = ship.GetAddressees(mConnectionString); foreach (ShipAddress address in list) { result.Add(address.Ship_Address_ID.Replace("@noof.com", "").Replace("@lfp.com", "")); } } finally { ship = null; } return result; } public string GetStatusType(int id, string type) { return mDataAccess.GetStatus(id, type); } public int GetTemplateId(string name) { MRGProjectTemplate template = new MRGProjectTemplate(); try { return template.GetTemplateId(mConnectionString, name); } finally { template = null; } } public string GetTitle(int id) { Movie movie = new Movie(); try { return movie.GetTitle(mConnectionString, id, String.Empty); } finally { movie = null; } } /// <summary> /// Gets titles that are searchable. /// </summary> /// <returns>The titles, as a list.</returns> public SystemSearchTitles[] GetTitles() { SystemSearchTitles titles = new SystemSearchTitles(); try { return titles.GetTitles(mConnectionString).ToArray(); } finally { titles = null; } } public int GetTVMACount(int id) { ETCBlock etc = new ETCBlock(); try { return etc.GetTVMACount(mConnectionString, id); } finally { etc = null; } } public List<string> GetUpdatedScheduleDates(string selectedChannels, string selectedChannelsPlus1Month) { List<string> result = new List<string>(); Schedule schedule = new Schedule(); try { List<DateTime?> list = schedule.GetUpdatedScheduleDates(mConnectionString, selectedChannels, selectedChannelsPlus1Month); foreach (DateTime? value in list) { if (value.HasValue) result.Add(value.Value.ToString("MMMM dd, yyyy")); //e.g., April 30, 2015 } } finally { schedule = null; } return result; } public string GetWMVFile(int id) { TrackDSMBW500 dsmbw = new TrackDSMBW500(); try { return dsmbw.GetWMVFile(mConnectionString, id); } finally { dsmbw = null; } } public bool HasAirMaster(int id) { TrackB b = new TrackB(); try { return b.CheckExists(mConnectionString, id); } finally { b = null; } } public bool IsAlreadySaved(int id, int itemId, string track) { bool result = false; TrackBQC bqc = null; TrackSQC sqc = null; try { switch (track) { case "B": bqc = new TrackBQC(); result = bqc.IsAlreadySaved(mConnectionString, id, itemId); break; case "S": sqc = new TrackSQC(); result = sqc.IsAlreadySaved(mConnectionString, id, itemId); break; } } finally { sqc = null; bqc = null; } return result; } public bool IsHD(int id) { return mDataAccess.IsHD(id); } public bool IsRetired(int id) { Movie movie = new Movie(); try { return movie.IsRetired(mConnectionString, id); } finally { movie = null; } } public bool MarkAllComplete(int hdId, int sdId, string period) { ScheduleCCComplete cc = new ScheduleCCComplete(); List<int> list = new List<int>(); list.Add(hdId); list.Add(sdId); try { return cc.MarkAssetsComplete(mConnectionString, list, period); } finally { list.Clear(); cc = null; } } public bool SavePreferences(TrafficProductionPreferences data) { TrafficProductionPreferences tpp = new TrafficProductionPreferences(); try { return tpp.SavePreferences(mConnectionString, data); } finally { tpp = null; } } public bool UpdateDSMBW500Record(TrackDSMBW500 data) { TrackDSMBW500 dsmbw = new TrackDSMBW500(); try { return dsmbw.UpdateRecord(mConnectionString, data); } finally { dsmbw = null; } } public bool UpdateFCPXmlRecord(TrackFCPXml data) { TrackFCPXml xml = new TrackFCPXml(); try { return xml.UpdateFCPXmlRecord(mConnectionString, data); } finally { xml = null; } } public bool UpdateProductionTemplate(UsersContentOpsProd data) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.Update(mConnectionString, data); } finally { prod = null; } } public bool UpdateProjectHeader(MRGProjectProjectHeader data) { MRGProjectProjectHeader header = new MRGProjectProjectHeader(); try { return header.UpdateHeader(mConnectionString, data); } finally { header = null; } } public bool UpdateProjectTemplate(UsersMRGProjects data) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.Update(mConnectionString, data); } finally { mrg = null; } } public bool UpdateSCCSubmitRecord(TrackW9500 data) { TrackW9500 w9500 = new TrackW9500(); try { return w9500.UpdateSubmitInfo(mConnectionString, data); } finally { w9500 = null; } } public bool UpdateScreenerLocation(int id, string location) { ScreenerMovie movie = new ScreenerMovie(); try { return movie.UpdateScreenerLocation(mConnectionString, id, location); } finally { movie = null; } } public bool UpdateSharedProductionTemplateLastUser(string template, string userName) { UsersContentOpsProd prod = new UsersContentOpsProd(); try { return prod.UpdateSharedTemplateLastUser(mConnectionString, template, userName); } finally { prod = null; } } public bool UpdateSharedProjectTemplateLastUser(string template, string userName) { UsersMRGProjects mrg = new UsersMRGProjects(); try { return mrg.UpdateSharedTemplateLastUser(mConnectionString, template, userName); } finally { mrg = null; } } public bool UpdateTrackLocation(ITrackLocation data, string subId, string digitalLocation) { bool result = false; string sql = "update track_" + subId + " set location = '" + data.Location + "', " + "lastmodified = '" + data.LastModified.Value.ToString() + "', lastusername = '" + data.LastUsername + "'"; if (subId.ToUpper().Equals("Y") && digitalLocation.Equals("Submitted for WMV Screener")) sql += ", date_submitted = '" + DateTime.Now.ToString() + "'"; sql += " where id = " + data.ID.Value.ToString(); using (Database database = new Database(mConnectionString)) { try { result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public bool UpdateTrackLocationHistory(ITrackLocationHistory data, string subId, string digitalLocation) { bool result = false; string sql = "update track_" + subId + "_history set location = '" + data.Location + "', " + "history_date = '" + data.History_Date.Value.ToString() + "', username = '" + data.Username + "'"; if (subId.ToUpper().Equals("Y") && digitalLocation.Equals("Submitted for WMV Screener")) sql += ", date_submitted = '" + DateTime.Now.ToString() + "'"; sql += " where id = " + data.ID.Value.ToString(); using (Database database = new Database(mConnectionString)) { try { result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } #endregion #region Private Methods private Tuple<string, string> GetAMStatuses(int id) { TrackBHistory b = new TrackBHistory(); try { return b.GetStatuses(mConnectionString, id); } finally { b = null; } } #endregion } }
using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.HuDong.Domain.Enums { public enum HuDongEnums { /// <summary> /// 大转盘 /// </summary> [Display(Name = "大转盘")] BigWheel = 1, /// <summary> /// 超级扭蛋机 /// </summary> [Display(Name = "超级扭蛋机")] EggMachine = 2, /// <summary> /// 刮刮乐 /// </summary> [Display(Name = "刮刮乐")] GuaGuaLe = 3, /// <summary> /// 多功能签到 /// </summary> [Display(Name = "多功能签到")] MultiSign = 4, /// <summary> /// 红包雨 /// </summary> [Display(Name = "红包雨")] RedPack = 5, /// <summary> /// 摇一摇 /// </summary> [Display(Name = "摇一摇")] ShakeShake = 6 } }
using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using CODE.Framework.Wpf.Mvvm; namespace CODE.Framework.Wpf.TestBench { /// <summary> /// Interaction logic for RibbonTest.xaml /// </summary> public partial class RibbonTest : Window { public RibbonTest() { Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/CODE.Framework.Wpf.Theme.Workplace;component/Workplace-Icon-Standard.xaml", UriKind.Relative) }); InitializeComponent(); ribbon.Model = new RibbonData(); } } public class RibbonData : IHaveActions { public RibbonData() { Actions = new ViewActionsCollection { new ViewAction("Save", groupTitle: "File") {Significance = ViewActionSignificance.AboveNormal, Visibility = Visibility.Collapsed, BrushResourceKey = "CODE.Framework-Icon-Save"}, new ViewAction("Change Save Visibility", groupTitle: "File", execute: (a, o) => Actions["Save"].Visibility = Actions["Save"].Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible) {Significance = ViewActionSignificance.AboveNormal, BrushResourceKey = "CODE.Framework-Icon-Settings"}, new ViewAction("The quick brown fox jumps over the lazy dog", groupTitle: "File", canExecute: (o, e) => false) {Significance = ViewActionSignificance.AboveNormal, BrushResourceKey = "CODE.Framework-Icon-Shop"}, new ViewAction("Enable/Disable", category: "Page 2", execute: (s, e) => Actions["Two B"].InvalidateCanExecute()) {Significance = ViewActionSignificance.AboveNormal, BrushResourceKey = "CODE.Framework-Icon-Read"}, new ViewAction("Two B", category: "Page 2", canExecute: (a, e) => { if (a.Caption == "Two B") { a.Caption = "Two BX"; return false; } a.Caption = "Two B"; return true; }) {Significance = ViewActionSignificance.AboveNormal, BrushResourceKey = "CODE.Framework-Icon-Remote"}, new ViewAction("Three B", category: "Page 2") {Significance = ViewActionSignificance.AboveNormal, BrushResourceKey = "CODE.Framework-Icon-RotateCamera"}, new ViewAction("Example Button", category: "Custom Views") {ActionView = new Button{Content = "Test", Margin = new Thickness(5)}}, new ViewAction("Font Controls", execute: (a, o) => { /* Launch an action UI */ }, category: "Custom Views", beginGroup: true, groupTitle: "Format") {ActionView = new FontControls()}, new ViewAction("Example List", category: "Custom Views", beginGroup: true, groupTitle: "List") {ActionView = new ExampleListInRibbon(), ActionViewModel = new RibbonListViewModel()} }; } public ViewActionsCollection Actions { get; private set; } public event NotifyCollectionChangedEventHandler ActionsChanged; } public class RibbonListViewModel { public RibbonListViewModel() { Items = new ObservableCollection<RibbonListItem>(); for (var counter = 0; counter < 100; counter++) Items.Add(new RibbonListItem {Text = "Item #" + counter, Icon = Application.Current.FindResource("CODE.Framework-Icon-Video") as Brush}); } public ObservableCollection<RibbonListItem> Items { get; set; } } public class RibbonListItem { public string Text { get; set; } public Brush Icon { 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.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using Microsoft.VisualBasic; namespace WindowsFormsApplication1 { public partial class siparişİşlemleri : Form { public siparişİşlemleri() { InitializeComponent(); } public static string fisid = ""; SqlConnection baglanti = new SqlConnection("Server=DESKTOP-JMR7LFH;Database=pizza;User Id=sa;Password=123456;"); SqlCommand komut; DataSet dset = new DataSet(); string tutar; string mad; string msoyad; private void siparişİşlemleri_Load(object sender, EventArgs e) { listele(); try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from siparis_durum", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { comboBox4.Items.Add(oku["id"].ToString()); } } catch (Exception hata) { MessageBox.Show(hata.Message); } baglanti.Close(); try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from musteriler", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { comboBox2.Items.Add(oku["id"].ToString()); } } catch (Exception hata) { MessageBox.Show(hata.Message); } baglanti.Close(); try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from siparis_liste ORDER BY id DESC", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { comboBox6.Items.Add(oku["id"].ToString()); } } catch (Exception hata) { MessageBox.Show(hata.Message); } baglanti.Close(); /* try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from kullanici", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { comboBox3.Items.Add(oku["id"].ToString()); } } catch (Exception hata) { MessageBox.Show(hata.Message); } baglanti.Close();*/ } void listele() { baglanti.Close(); comboBox6.Text = ""; textBox5.Text = ""; textBox4.Text = ""; textBox3.Text = ""; textBox5.Text = ""; textBox6.Text = ""; textBox7.Text = ""; textBox8.Text = ""; comboBox1.Text = ""; comboBox2.Text = ""; //comboBox3.Text = ""; dset.Clear(); baglanti.Open(); SqlDataAdapter adtr = new SqlDataAdapter("select * From siparisler", baglanti); adtr.Fill(dset, "siparisler"); dataGridView1.DataSource = dset.Tables["siparisler"]; adtr.Dispose(); baglanti.Close(); } private void button1_Click(object sender, EventArgs e) { try { baglanti.Open(); komut = new SqlCommand("insert into siparisler(siparis_liste,iskonta,musteri_id,siparis_tarihi,para_alinma_tarihi,teslim_tarihi,tutar,kullanici_id,durum_id,alindi) values('" + comboBox6.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox1.Text + "','" + comboBox4.Text + "','" + textBox6.Text + "')", baglanti); komut.ExecuteNonQuery(); MessageBox.Show("Ekleme İşleme Başarıyla Tamamlandı"); baglanti.Close(); } catch (Exception hata) { MessageBox.Show(hata.ToString()); } try { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into log(kullanici_adi,tarih,islem,aciklama) values('" + Form1.giris + "','" + DateTime.Now.ToString() + "','" + "ekleme" + "','" + "Sipariş Ekleme İşlemi Yapılmıştır" + "')", baglanti); komut2.ExecuteNonQuery(); baglanti.Close(); } catch { ; } listele(); } private void button4_Click(object sender, EventArgs e) { baglanti.Open(); try { komut = new SqlCommand("delete from siparisler where id='" + dataGridView1.CurrentRow.Cells["id"].Value.ToString() + "'", baglanti); komut.ExecuteNonQuery(); MessageBox.Show("Silme İşleme Başarıyla Tamamlandı"); baglanti.Close(); listele(); } catch (Exception hata) { MessageBox.Show(hata.Message); ; } try { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into log(kullanici_adi,tarih,islem,aciklama) values('" + Form1.giris + "','" + DateTime.Now.ToString() + "','" + "silme" + "','" + "Sipariş silme İşlemi Yapılmıştır" + "')", baglanti); komut2.ExecuteNonQuery(); baglanti.Close(); } catch { ; } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string durumgirisi = Interaction.InputBox("Sipariş Durumu Girişi", "Lütfen Durum Giriniz."); try { baglanti.Open(); komut = new SqlCommand("insert into siparis_durum(durum) values('" + durumgirisi + "')", baglanti); komut.ExecuteNonQuery(); MessageBox.Show("Ekleme İşleme Başarıyla Tamamlandı"); baglanti.Close(); listele(); } catch (Exception hata) { MessageBox.Show(hata.ToString()); } try { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into log(kullanici_adi,tarih,islem,aciklama) values('" + Form1.giris + "','" + DateTime.Now.ToString() + "','" + "ekleme" + "','" + "Sipariş Durumu Ekleme İşlemi Yapılmıştır" + "')", baglanti); komut2.ExecuteNonQuery(); baglanti.Close(); } catch { ; } listele(); comboBox4.Items.Clear(); try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from siparis_durum", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { comboBox4.Items.Add(oku["id"].ToString()); } } catch (Exception hata) { MessageBox.Show(hata.Message); } } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { textBox3.Text = DateTime.Now.ToString(); } private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { textBox4.Text = DateTime.Now.ToString(); } private void button3_Click(object sender, EventArgs e) { this.Hide(); } private void comboBox6_SelectedIndexChanged(object sender, EventArgs e) { try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from siparis_liste WHERE id='" + comboBox6.Text + "'", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { textBox2.Text = oku["siparis_tarihi"].ToString(); tutar = oku["tutar"].ToString(); textBox8.Text = oku["k_adi"].ToString(); textBox5.Text = oku["tutar"].ToString(); mad = oku["musteri_adi"].ToString(); msoyad = oku["musteri_soyadi"].ToString(); } baglanti.Close(); textBox7.Text = mad + " " + msoyad; baglanti.Open(); SqlCommand com2 = new SqlCommand("Select * from musteriler WHERE adi='" + mad + "'and soyadi='" + msoyad + "'", baglanti); SqlDataReader oku2 = com2.ExecuteReader(); while (oku2.Read()) { comboBox2.Text = oku2["id"].ToString(); } baglanti.Close(); baglanti.Open(); SqlCommand com3 = new SqlCommand("Select * from kullanici WHERE k_adi='" + textBox8.Text + "'", baglanti); SqlDataReader oku3 = com3.ExecuteReader(); while (oku3.Read()) { textBox1.Text = oku3["id"].ToString(); } baglanti.Close(); } catch (Exception hata) { MessageBox.Show(hata.Message); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox5.Text = (double.Parse(tutar) - ((double.Parse(comboBox1.Text) / 100) * double.Parse(tutar))).ToString(); } private void comboBox4_SelectedIndexChanged(object sender, EventArgs e) { try { baglanti.Open(); SqlCommand com = new SqlCommand("Select * from siparis_durum WHERE id='" + comboBox4.Text + "'", baglanti); SqlDataReader oku = com.ExecuteReader(); while (oku.Read()) { textBox6.Text = oku["durum"].ToString(); } baglanti.Close(); } catch (Exception hata) { MessageBox.Show(hata.Message); } } private void button2_Click(object sender, EventArgs e) { fisid = comboBox2.Text; fis fisler = new fis(); fisler.Show(); } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { } private void button6_Click(object sender, EventArgs e) { adminPaneli admin = new adminPaneli(); admin.Show(); this.Hide(); } } class Interaction { internal static string InputBox(string v1, string v2) { throw new NotImplementedException(); } } }
using System.Windows.Input; namespace SqlServerRunnerNet.Commands { public static class ScriptsCommands { public static readonly ICommand AddCommand = new RoutedUICommand( "Add", "Add", typeof(ScriptsCommands)); public static readonly ICommand RemoveCommand = new RoutedUICommand( "Remove", "Remove", typeof(ScriptsCommands)); public static readonly ICommand ClearCommand = new RoutedUICommand( "Clear", "Clear", typeof (ScriptsCommands)); public static readonly ICommand RunSelectedCommand = new RoutedUICommand( "Run Selected", "Run Selected", typeof (ScriptsCommands)); public static readonly ICommand ClearOutputCommand = new RoutedUICommand( "Clear Output", "Clear Output", typeof (ScriptsCommands)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LobbyTeamUI : SingletonObject<LobbyTeamUI> { void Awake() { CreateInstance(this); } // Use this for initialization void Start () { m_buttonMakeTeam.onClick.AddListener(delegate () { LoginControler.Instance().MakeTeam(); }); m_buttonTeamStart.onClick.AddListener(delegate () { LoginControler.Instance().TeamStart(); }); m_buttonOnlinePlayers.onClick.AddListener(delegate () { LoginControler.Instance().OnlinePlayers(); }); m_buttonLeave.onClick.AddListener(delegate () { LoginControler.Instance().LeaveTeam(); }); m_textName.gameObject.SetActive(true); m_textName.text = PlayerData.Instance().proName; m_imgHead.gameObject.SetActive(true); m_imgHead.texture = PlayerData.Instance().proHeadTex; m_textID.text = "ID:" + PlayerData.Instance().proPlayerId.ToString(); } // Update is called once per frame void Update () { } [SerializeField] UnityEngine.UI.Button m_buttonMakeTeam = null; [SerializeField] UnityEngine.UI.Button m_buttonTeamStart = null; [SerializeField] UnityEngine.UI.Button m_buttonOnlinePlayers = null; [SerializeField] UnityEngine.UI.Button m_buttonLeave = null; [SerializeField] UnityEngine.UI.RawImage m_imgHead = null; [SerializeField] UnityEngine.UI.Image m_imgFrame = null; [SerializeField] UnityEngine.UI.Text m_textName = null; [SerializeField] UnityEngine.UI.Text m_textID = null; }
namespace MusicStore.Models.DataModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; [CustomValidation(typeof(Album), "ValiderAlbum")] public class Album { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int AlbumId { get; set; } [Required,MaxLength(100)] public string Titre { get; set; } [Required] public int AnneeParution { get; set; } [Required,DataType(DataType.MultilineText)] public string Description { get; set; } [Required] public int GenreId { get; set; } [Required, MaxLength(50)] public string Artiste { get; set; } public double Prix { get; set; } [NotMapped] public string Cover { get => $"/Content/Images/Albums/{AlbumId}.jpg"; } public static ValidationResult ValiderAlbum(Album album) { if (album.AnneeParution <= 1930 && album.AnneeParution >= 2100) return new ValidationResult("La annee de parution doit etre comprise entre 1930 et 2100"); if (album.Prix < 10 && album.Prix > 100) return new ValidationResult("Le prix doit etre compris entre 10 et 100 dollars"); return ValidationResult.Success; } } }
using System; using System.IO; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; namespace Exemplo.Api.Config { public static class ConfigSwagger { public static void ConfigureServices(IConfiguration configuration, IServiceCollection services) { services.AddOpenApiDocument(doc => { doc.Title = "API - Exemplo Thaiz"; doc.Description = "API tem como objetivo demonstrar nível de conhecimento técnico."; doc.GenerateExamples = true; doc.UseControllerSummaryAsTagDescription = true; doc.GenerateXmlObjects = true; }); } public static void Configure(IApplicationBuilder app) { app.UseOpenApi(); app.UseSwaggerUI(s => { s.RoutePrefix = "swagger"; s.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Example"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BradescoPGP.Web.Models.Graficos { public class TedGraficos { public GraficoQuantidadeTed GraficoQuantidadeTed { get; set; } public GraficoValorTed GraficoValorTed { get; set; } public GraficoQuantidadeStatus GraficoQuantidadeStatus { get; set; } public GraficoValorStatus GraficoValorStatus { get; set; } public GraficoAplicacaoProduto GraficoAplicacaoProduto { get; set; } public GraficoMotivoNaoAplicacao GraficoMotivoNaoAplicacao { get; set; } } }
namespace E11 { public class Aplicacion { private int tiempoDeUso; public int TiempoDeUso { get => tiempoDeUso; } private int cantidadDeToquesEnLaPantalla; public int CantidadDeToquesEnLaPantalla { get => cantidadDeToquesEnLaPantalla; } private int tiempoDeUsoDelTeclado; public int TiempoDeUsoDelTeclado { get => tiempoDeUsoDelTeclado; } private bool permisos; public bool Permisos { get => permisos; } public Aplicacion(int tiempoDeUso, int cantidadDeToquesEnLaPantalla, int tiempoDeUsoDelTeclado, bool permisos) { this.tiempoDeUso = tiempoDeUso; this.cantidadDeToquesEnLaPantalla = cantidadDeToquesEnLaPantalla; this.tiempoDeUsoDelTeclado = tiempoDeUsoDelTeclado; this.permisos = permisos; } public bool esUnJuego(){ return cantidadDeToquesEnLaPantalla/tiempoDeUso == 25; } public bool esUnaRedSocial(){ return tiempoDeUsoDelTeclado / tiempoDeUso > 20 && permisos; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Strategy.Cars { public interface ICar { int GetMaxSpeed(); } public enum CarModel { Porsche, Ferrari, Lamborgini} }
using System; using System.ComponentModel; using System.Threading.Tasks; using System.Windows.Input; using BSMU_Schedule.Commands; using BSMU_Schedule.Entities; using BSMU_Schedule.Exceptions; using BSMU_Schedule.Interfaces; using BSMU_Schedule.Services; using Xamarin.Forms; namespace BSMU_Schedule.ViewModels { public class MenuViewModel: INotifyPropertyChanged { public ICommand DownloadSchedulePreviewCommand { get; set; } public ICommand DownloadGroupCommand { get; set; } public INavigation Navigation { get; set; } public Page MenuPage { get; set; } public ScheduleViewModel ScheduleViewModel { get; set; } public event PropertyChangedEventHandler PropertyChanged; private readonly IScheduleRetrievingService scheduleRetrievingService; public MenuViewModel(INavigation navigation, ScheduleViewModel viewModel, Page menuPage) { MenuPage = menuPage; ScheduleViewModel = viewModel; Navigation = navigation; DownloadSchedulePreviewCommand = new DownloadSchedulePreviewCommand(this); DownloadGroupCommand = new DownloadGroupCommand(this); scheduleRetrievingService = new ScheduleRetrievingService(); ChangeStateOfDownloading(false); } private bool _isThinking; public bool IsThinking { get => _isThinking; set { _isThinking = value; OnPropertyChanged(nameof(IsThinking)); } } private string _groupNumber; public string GroupNumber { get => _groupNumber; set { if (_groupNumber == value) { return; } _groupNumber = value; OnPropertyChanged(nameof(GroupNumber)); } } private bool _isGroupFieldVisible; public bool IsGroupFieldVisible { get => _isGroupFieldVisible; set { if (_isGroupFieldVisible == value) { return; } _isGroupFieldVisible = value; OnPropertyChanged(nameof(IsGroupFieldVisible)); } } private bool _isDownloadPreviewButtonVisible; public bool IsDownloadPreviewButtonVisible { get => _isDownloadPreviewButtonVisible; set { if (_isDownloadPreviewButtonVisible == value) { return; } _isDownloadPreviewButtonVisible = value; OnPropertyChanged(nameof(IsDownloadPreviewButtonVisible)); } } private bool _isValidationErrorHappened; public bool IsValidationErrorHappened { get => _isValidationErrorHappened; set { if (_isValidationErrorHappened == value) { return; } _isValidationErrorHappened = value; OnPropertyChanged(nameof(IsValidationErrorHappened)); } } public void DownloadSchedulePreviewOpen() { ChangeStateOfDownloading(true); } private void ChangeStateOfDownloading(bool isGroupUploading) { IsDownloadPreviewButtonVisible = !isGroupUploading; IsGroupFieldVisible = isGroupUploading; } public async Task DownloadGroup() { if (!int.TryParse(GroupNumber, out int result)) { IsValidationErrorHappened = true; return; } IsValidationErrorHappened = false; Schedule schedule; try { IsThinking = true; schedule = await scheduleRetrievingService.GetScheduleForGroup(result); } catch (NetworkProblemException) { IsThinking = false; await MenuPage.DisplayAlert("Error", "There are problems with network", "Ok", "Cancel"); return; } catch (InvalidOperationException) { IsThinking = false; await MenuPage.DisplayAlert("Error", "Cannot find this group number", "Ok", "Cancel"); return; } await ScheduleViewModel.UpdateSchedule(schedule); IsThinking = false; await Navigation.PopModalAsync(false); } protected virtual void OnPropertyChanged(string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using UnityEngine; using System.Collections; public class LifeBar : MonoBehaviour { [SerializeField] private Sprite m_sprite = null; public SpriteRenderer m_rend; [SerializeField] Musician m_me = null; float m_barLen = -1.0f; float m_barFull = 0.425f;//Magic number for scale int m_health; int m_fullHealth; // Use this for initialization void Start() { m_rend.color = Color.green; m_sprite = Instantiate(m_sprite); m_rend.sprite = m_sprite; m_health = m_me.Health; m_barLen = m_barFull; m_fullHealth = m_health; m_barFull = m_rend.transform.localScale.x; } // Update is called once per frame void Update() { m_barLen = m_barFull; m_health = m_me.Health; m_barLen *= ((float)m_health / m_fullHealth); if (float.IsInfinity(m_barLen)) m_barLen = 0.00000000000000001f; else m_rend.GetComponent<Transform>().localScale = new Vector3(m_barLen, 1, 0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Final_Project { class CommodityPrices { private static double goatMilkPrice; private static double cowMilkPrice; private static double sheepWoolPrice; private static double waterPrice; private static double taxPerKG; private static double jerseyCowTax; public static double GoatMilkPrice { get; set; } public static double CowMilkPrice { get; set; } public static double SheepWoolPrice { get; set; } public static double WaterPrice { get; set; } public static double TaxPerKG { get; set; } public static double JerseyCowTax { get; set; } } }
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public TreeNode BuildTree(int[] inorder, int[] postorder) { return Helper(inorder, postorder, 0, inorder.Length - 1, 0, postorder.Length - 1); } private TreeNode Helper(int[] inorder, int[] postorder, int iStart, int iEnd, int pStart, int pEnd) { if (iEnd - iStart < 0 || pEnd - pStart < 0) return null; TreeNode root = new TreeNode(postorder[pEnd]); int idx; for (idx = iStart; idx <= iEnd; idx ++) { if (inorder[idx] == postorder[pEnd]) break; } root.left = Helper(inorder, postorder, iStart, idx - 1, pStart, pStart + idx - iStart - 1); root.right = Helper(inorder, postorder, idx + 1, iEnd, pEnd - iEnd + idx, pEnd - 1); return root; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassLibraryIofly { /// <summary> /// GeoRecordset类 /// </summary> public class GeoRecordset {//todo: 判断record里面的值的类型是否和字段匹配 public Fields fields; public Records records; public string valueType; public GeoRecordset() { ; } public GeoRecordset(Fields fs, Records rs) { fields = fs; records = rs; valueType = records.Item(0).Value(0).ToString(); } public bool Open(string filename) { return true; } public bool Save(string filename) { return true; } /// <summary> /// 检查是否所有记录值类型与对应字段相符 /// </summary> /// <returns></returns> public bool CheckValueType() { for(int i=0;i<records.Count();i++) { for (int j = 0; j < fields.Count(); j++) { if (records.Item(i).Value(j).GetType().Name != fields.Item(j).valueType) return false; } } return true; } /// <summary> /// 根据field名称返回值集合 /// </summary> /// <returns></returns> public List<object> GetValuesByField(string name) { int index = -1; List<object> values = new List<object>(); //object[] values = new object[0]; for(int i=0;i<fields.Count();i++) { if(name==fields.Item(i).name) { index = i; break; } } if (index == -1) return values; else { for(int j=0;j<records.Count();j++) { values.Add(records.Item(j).Value(index)); } values = values.Distinct().ToList(); } return values; } /// <summary> /// 根据索引号删除Field,同步删除相关联的record.value /// </summary> /// <param name="index"></param> public void DeleteField(int index) { fields.Delete(index); for (int i = 0; i < records.Count(); i++) { records.Item(i).Delete(index); } } public GeoRecordset SelectByText(string text) { return new GeoRecordset(); } /// <summary> /// 点选要素 /// </summary> /// <param name="point"></param> /// <param name="tolerance"></param> /// <returns></returns> public GeoRecordset SelectByPoint(PointD point, double tolerance) { Records newRecords = new Records(); Fields newFeilds = fields; for (int i = 0; i < records.Count(); i++) { string valuetype = (string)(records.Item(i).Value(0)); if (valuetype == typeof(PointD).Name) { PointD tempPt = (PointD)records.Item(i).Value(1); if (tempPt.isNearPoint(point, tolerance)) { newRecords.Append(records.Item(i)); } } else if (valuetype == typeof(Polygon).Name) { Polygon temppolygon = (Polygon)records.Item(i).Value(1); if(temppolygon.isContainPoint(point)) { newRecords.Append(records.Item(i)); } } else if (valuetype == typeof(MultiPolygon).Name) { MultiPolygon tempmpolygon = (MultiPolygon)records.Item(i).Value(1); if (tempmpolygon.isContainPoint(point)) { newRecords.Append(records.Item(i)); } } else if (valuetype == typeof(Polyline).Name) { Polyline temppolyline = (Polyline)records.Item(i).Value(1); if(temppolyline.isNearPoint(point,tolerance)) { newRecords.Append(records.Item(i)); } } else if(valuetype == typeof(MultiPolyline).Name) { MultiPolyline tempmpolyline = (MultiPolyline)records.Item(i).Value(1); if (tempmpolyline.isNearPoint(point, tolerance)) { newRecords.Append(records.Item(i)); } } } return new GeoRecordset(); } /// <summary> /// 完全位于矩形内的图形被选中 /// </summary> /// <param name="box"></param> /// <returns></returns> public GeoRecordset SelectByBox(RectangleD box) { Records newRecords = new Records(); Fields newFeilds = fields; for (int i = 0; i < records.Count(); i++) { string valuetype = (string)(records.Item(i).Value(0)); if (valuetype == typeof(PointD).Name) { PointD tempPt = (PointD)records.Item(i).Value(1); if (tempPt.isInBox(box)) { newRecords.Append(records.Item(i)); } } else if (valuetype == typeof(Polygon).Name || valuetype == typeof(MultiPolygon).Name || valuetype == typeof(Polyline).Name || valuetype == typeof(MultiPolyline).Name) { object temp = records.Item(i).Value(0); object[] para = new object[1]; para[0] = box; object tempIsIn = temp.GetType().GetMethod("isInBox").Invoke(temp, para); bool isIn = Convert.ToBoolean(tempIsIn); if (isIn) { newRecords.Append(records.Item(i)); } } } return new GeoRecordset(newFeilds, newRecords); } /// <summary> /// 根据行索引号数组进行选择 /// </summary> /// <param name="indices"></param> /// <returns></returns> public GeoRecordset SelectByIndices(int[] indices) { Records newRecords = new Records(); for(int i=0; i<indices.Count();i++) { newRecords.Append(records.Item(indices[i])); } Fields newFeilds = fields; return new GeoRecordset(newFeilds, newRecords); } } /// <summary> /// Field类 /// </summary> public class Field { public string name; public string valueType; public Field(string n, string vt) { name = n; valueType = vt; } } /// <summary> /// Fields类 /// </summary> public class Fields { public Field[] fields; private List<Field> _fields = new List<Field>(); public Fields() { } public Fields(Field[] fds) { _fields.AddRange(fds); fields = fds; } /// <summary> /// 根据字段名称返回字段索引,找不到返回-1 /// </summary> /// <param name="name">字段名</param> /// <returns></returns> public int GetIndexOfField(string name) { int index = -1; for (int i = 0; i < _fields.Count(); i++) { if (name == _fields[i].name) { index = i; break; } } return index; } /// <summary> /// 根据索引号返回Field /// </summary> /// <param name="index"></param> /// <returns></returns> public Field Item(int index) { return _fields[index]; } /// <summary> /// 返回名字为name的第一个Field /// </summary> /// <param name="name"></param> /// <returns></returns> public Field Item(string name) { int count = _fields.Count; for (int i = 0; i < count; i++) { if (_fields[i].name == name) { return _fields[i]; } } return null; } /// <summary> /// 返回fields的数量 /// </summary> /// <returns></returns> public int Count() { return _fields.Count; } /// <summary> /// 添加field /// </summary> /// <param name="field"></param> public void Append(Field field) { _fields.Add(field); } /// /// <summary> /// 根据索引号移除field /// </summary> /// <param name="index"></param> public void Delete(int index) { _fields.Remove(_fields[index]); //_fields[index].name = ""; //_fields[index].valueType = string; } } /// <summary> /// Record类 /// </summary> public class Record { object[] values; List<object> _values = new List<object>(); public Record(object[] v) { _values.AddRange(v); values = v; } /// <summary> /// 根据索引返回value /// </summary> /// <param name="index"></param> /// <returns></returns> public object Value(int index) { return _values[index]; } /// <summary> /// 返回value的数目 /// </summary> /// <returns></returns> public int Count() { return _values.Count; } /// <summary> /// 添加value /// </summary> /// <param name="value"></param> public void Append(object value) { _values.Add(value); } /// <summary> /// 根据索引号删除value /// </summary> /// <param name="index"></param> public void Delete(int index) { _values.Remove(_values[index]); //_values[index] = ""; } } /// <summary> /// Records类 /// </summary> public class Records { Record[] records; List<Record> _records = new List<Record>(); public Records() { ; } public Records(Record[] rds) { _records.AddRange(rds); records = rds; } /// <summary> /// 根据索引号返回Record /// </summary> /// <param name="index"></param> /// <returns></returns> public Record Item(int index) { return _records[index]; } /// <summary> /// 返回Record数目 /// </summary> /// <returns></returns> public int Count() { return _records.Count; } /// <summary> /// 添加Record /// </summary> /// <param name="record"></param> public void Append(Record record) { _records.Add(record); } /// <summary> /// 根据索引号删除Record /// </summary> /// <param name="index"></param> public void Delete(int index) { _records.Remove(_records[index]); } } }
/** * Author: János de Vries * Date: Sep. 2014 * Student Number: 208418 **/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.ComponentModel; using System.Windows.Forms; namespace ThreadCollor { /// <summary> /// This class has control over all the worker threads /// </summary> class ThreadManager { //Create an array of ColorCalculators (workers) private ColorCalculator[] workers; //A variable that keeps track of the number of workers running private int tasksRunning = 0; //A lock for the getTask() method static readonly object taskLock = new object(); //A flag to provide information if threads are running private bool threadsRunning = false; //A public reference to threads running public bool ThreadsRunning { get { return threadsRunning; } } //An event handler to tell the MainForm all the threads have finished working public event AllThreadsDone allThreadsDone; public delegate void AllThreadsDone(); public void startThreads(FileManager fileManager, ListView listView_overview, int numberOfThreads, int numberOfCores) { //Give the workers array a length workers = new ColorCalculator[numberOfThreads]; //Set threads running to true threadsRunning = true; //For every worker in workers for (int i = 0; i < workers.Length; i++) { //Fill the workers array with ColorCalculators workers[i] = new ColorCalculator(listView_overview, fileManager, i%numberOfCores, taskLock); //Add a listener that's called when the thread is done working workers[i].Done += new ColorCalculator.DoneHandler(threadFinished); //Start the worker workers[i].RunWorkerAsync(); //Iterate the number of running workers tasksRunning++; } } /// <summary> /// When all the workers are finished working let the listeners (MainForm) know /// </summary> public void threadFinished(object sender, EventArgs e) { tasksRunning--; //If there are no tasks working they're all done if(tasksRunning <= 0) { //Set threadsRunning to false threadsRunning = false; //Signal the event allThreadsDone(); } } } }
using System; using UnityEngine; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; using LitJson; using UnityEditor; using Object = UnityEngine.Object; namespace BattleEditor { /// <summary> /// <para>Class Introduce</para> /// <para>Author: zhengnan</para> /// <para>Create: 2019/6/12 22:48:38</para> /// </summary> public static class BattleEditorUtility { public static List<string> GetExcelFileList(string excelFolder, string[] fileList) { List<string> excelFileList = new List<string>(); for (int i = 0; i < fileList.Length; i++) excelFileList.Add(Path.Combine(excelFolder, fileList[i])); if(excelFileList.Count == 0) Debug.LogErrorFormat("There is not any excel file in folder"); return excelFileList; } public static Dictionary<string, ExcelColHeader> GetExcelHeaderList(string excelPath) { var jsonPath = Application.dataPath + excelPath.Replace(".xlsx", ".json"); Dictionary<string, ExcelColHeader> excelColHeaders = new Dictionary<string, ExcelColHeader>(); var json = LoadText(jsonPath); if (!string.IsNullOrEmpty(json)) { JsonData jsonData = JsonMapper.ToObject(json); foreach (var key in jsonData.Keys) { ExcelColHeader header = new ExcelColHeader(key, jsonData[key]); excelColHeaders.Add(key, header); } } else { //Debug.LogError($"{excelPath} has not header json file"); } return excelColHeaders; } public static void DisplayProgress(int progress, int total, string file) { string title = $"Progress..[{progress}/{total}]"; EditorUtility.DisplayCancelableProgressBar(title, file, (float) progress / (float) total); } public static BattleEditorSetting LoadSetting(string settingPath) { if (!File.Exists(settingPath)) CreateAsset<BattleEditorSetting>(settingPath); return AssetDatabase.LoadAssetAtPath<BattleEditorSetting>(settingPath); } /// <summary> /// 绝对路径->相对路径 /// </summary> public static string Absolute2Relativity(string path) { string temp = path.Substring(path.IndexOf("Assets")); temp = temp.Replace('\\', '/'); return temp; } /// <summary> /// 创建asset配置文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path"></param> public static void CreateAsset<T>(string path) where T : ScriptableObject { T asset = ScriptableObject.CreateInstance<T>(); if (string.IsNullOrEmpty(path)) { Debug.LogError("Not select files, select files first! "); return; } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path); AssetDatabase.CreateAsset(asset, assetPathAndName); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; } public static string LoadText(string path) { if (File.Exists(path)) return File.ReadAllText(path); else return null; } public static void SaveUTF8TextFile(string fn, string txt) { byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(txt); byte[] bom = new byte[] { 0xef, 0xbb, 0xbf }; byte[] saveData = new byte[data.Length + bom.Length]; Array.Copy(bom, 0, saveData, 0, bom.Length); Array.Copy(data, 0, saveData, bom.Length, data.Length); SaveFileData(fn, saveData); } public static byte[] GetFileData(string fn) { if (!File.Exists(fn)) return null; FileStream fs = new FileStream(fn, FileMode.Open); try { if (fs.Length > 0) { byte[] data = new byte[(int)fs.Length]; fs.Read(data, 0, (int)fs.Length); return data; } else { return null; } } finally { fs.Close(); } } public static void SaveFileData(string fn, byte[] data) { string dir = Path.GetDirectoryName(fn); System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(dir); if (!dirinfo.Exists) dirinfo.Create(); FileStream fs = new FileStream(fn, FileMode.Create); try { fs.Write(data, 0, data.Length); } finally { fs.Close(); } } public static Dictionary<string, string> GetDictionaryFromFile(string fn) { byte[] data = GetFileData(fn); if (data != null) { ByteReader br = new ByteReader(data); return br.ReadDictionary(); } return null; } public static void SaveDictionary(string fn, Dictionary<string, string> dic) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string k in dic.Keys) { string v = dic[k]; sb.Append(string.Format("{0}={1}\r\n", k, v)); } byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); SaveFileData(fn, data); } /// <summary> /// 获取文件的MD5值 /// </summary> /// <param name="_PathValue"></param> /// <returns></returns> public static string GetFileMD5(string _PathValue) { string fileMd5 = ""; string tempPath = Application.dataPath.Replace("Assets", ""); //外部文件的MD5值 try { FileStream fs = new FileStream(tempPath + _PathValue, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); for (int i = 0; i < retVal.Length; i++) { fileMd5 += retVal[i].ToString("x2"); } } catch (System.Exception ex) { Debug.Log(ex); } return fileMd5; } public static string DataRowToJson(DataColumnCollection columns, DataRow valueRow) { StringBuilder sb = new StringBuilder(); sb.Append("{"); for (int i = 0; i < columns.Count; i++) { if (IsNumberic(valueRow[i])) sb.Append($"\"{columns[i].ColumnName}\": {valueRow[i]}"); else sb.Append($"\"{columns[i].ColumnName}\": \"{valueRow[i]}\""); if(i < columns.Count - 1) sb.Append(", "); } sb.Append("}"); return sb.ToString(); } //判断字符串是否是数字 static bool IsNumberic(object message) { System.Text.RegularExpressions.Regex rex= new System.Text.RegularExpressions.Regex(@"^\d+$"); return rex.IsMatch(message.ToString()); } public static string[] JsonToArray(JsonData json, string fieldName) { if(json.Keys.Contains(fieldName)) { string[] list = new string[json[fieldName].Count]; for (int i = 0; i < list.Length; i++) { list[i] = json[fieldName][i].ToString(); } return list; } return null; } } }
using HotelReservationSystem.Models; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace HotelReservationSystem.DAL { public class HotelContext : DbContext { public HotelContext() : base("HotelContext") { Database.SetInitializer<HotelContext>(new MyDbInitializer()); Database.SetInitializer<HotelContext>(new MyDbInitializer1()); } public DbSet <User> Users { get; set; } public DbSet<Room> Rooms { get; set; } public DbSet<RoomFacility> RoomFacilities { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }
// <copyright file="DownloadProgressArgs.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ namespace FiroozehGameService.Models.EventArgs { /// <summary> /// Represents DownloadProgressArgs /// </summary> public class DownloadProgressArgs : System.EventArgs { /// <summary> /// Gets the File Name. /// </summary> /// <value>the File Name</value> public string FileTag { internal set; get; } /// <summary> /// Gets Downloaded File BytesReceived /// </summary> /// <value>Downloaded File BytesReceived</value> public long BytesReceived { internal set; get; } /// <summary> /// Gets Download File TotalBytesToReceive /// </summary> /// <value>Download File TotalBytesToReceive</value> public long TotalBytesToReceive { internal set; get; } /// <summary> /// Gets Downloaded File ProgressPercentage /// </summary> /// <value>Downloaded File ProgressPercentage</value> public int ProgressPercentage { internal set; get; } } }
using System.Diagnostics; using System.IO; using System.Web.Http; using API.Host.Console.Providers; using Microsoft.Owin; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using Owin; using Service.AppStart; namespace API.Host.Console { public class Startup { private static readonly string HostName = "*"; private static readonly string Port = "1234"; public void Configuration(IAppBuilder app) { // STEP - Static content hosting const string clientPathForDevLocal = ""; const string webAppPath = "dist/dev"; //compiled javascript in local developer environment DirectoryInfo staticContentDir = new DirectoryInfo(@"C:\codeNG2\angular2-seed\dist\dev"); if (staticContentDir.Exists) { var filesystem = staticContentDir.FullName; var fsOptions = new FileServerOptions { EnableDirectoryBrowsing = true, EnableDefaultFiles = true, FileSystem = new PhysicalFileSystem(filesystem), RequestPath = new PathString(""), StaticFileOptions = { ContentTypeProvider = new CustomContentTypeProvider() } }; app.UseFileServer(fsOptions); } staticContentDir = new DirectoryInfo(@"C:\codeNG2\angular2-seed"); if (staticContentDir.Exists) { var filesystem = staticContentDir.FullName; var fsOptions = new FileServerOptions { EnableDirectoryBrowsing = true, EnableDefaultFiles = true, FileSystem = new PhysicalFileSystem(filesystem), RequestPath = new PathString(""), StaticFileOptions = { ContentTypeProvider = new CustomContentTypeProvider() } }; app.UseFileServer(fsOptions); } // STEP - Log configuration info LogConfigSettingsAtStartup(webAppPath, staticContentDir); //// STEP - Self-host the WebApi var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } private void LogConfigSettingsAtStartup(string webAppPath, DirectoryInfo staticContentDir) { Debug.WriteLine($"Started server ###########################"); #if DEBUG Debug.WriteLine($"Local Dev Gateway API URL: http://localhost:{Port}/{WebApiConfig.GwApiRoot}"); Debug.WriteLine($"Local Dev Detail API URL : http://localhost:{Port}/{WebApiConfig.ApiRoot}"); Debug.WriteLine($"Local Dev Browser App URL: http://localhost:{Port}{webAppPath}"); Debug.WriteLine(""); Debug.WriteLine($"WebApp start url: {GetSiteUrl()}"); Debug.WriteLine($"Static Content Directory for LocalDev: {staticContentDir?.FullName}"); #endif Debug.WriteLine(""); ValidateStaticContentDirectory(staticContentDir); } private void ValidateStaticContentDirectory(DirectoryInfo webDirectory) { if (webDirectory == null || !webDirectory.Exists) { var currentDIr = Directory.GetCurrentDirectory(); throw new FileNotFoundException("Path not found: " + (webDirectory?.FullName ?? "") + " current dir:" + currentDIr); } } public static string GetSiteUrl() { return string.Format("http://{0}:{1}", HostName, Port); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClotheOurKids.Model.Repository { public interface IRegisterFormRepository { IList<OfficeType> GetAllOfficeTypes(); IList<Position> GetAllPositions(); IList<Office> GetAllOffices(); IList<Office> GetOfficesByOfficeType(int officeTypeId); IList<Office> GetOfficesByZipCode(string zipcode); IList<Position> GetPositionsByOffice(int officeId); IList<Position> GetPositionsByOfficeType(int officeTypeId); IList<ContactMethod> GetAllContactMethods(); } }
using Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual; using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual; using Pe.Stracon.SGC.Infraestructura.Repository.Base; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Infraestructura.Repository.Query.Contractual { /// <summary> /// Implementación del repositorio de Consulta /// </summary> public class ConsultaLogicRepository : QueryRepository<ConsultaLogic>, IConsultaLogicRepository { /// <summary> /// Retorna la lista de consulta. /// </summary> /// <param name="codigoRemitente">Codigo de Remitente</param> /// <param name="codigoDestinatario">Código de destinatario</param> /// <param name="CodigoTipoConsulta">Código de tipo de consulta</param> /// <param name="codigoUnidadOperativa">Código de unidad operativa</param> /// <param name="codigoArea">Código de área</param> /// <param name="codigoConsulta">Código de consulta</param> /// <param name="codigoUsuarioSesion">Código de usuario de sesion</param> /// <returns>Lista de consultas</returns> public List<ConsultaLogic> ListaConsulta(Guid? codigoRemitente, Guid? codigoDestinatario, string CodigoTipoConsulta, Guid? codigoUnidadOperativa, string codigoArea, Guid? codigoConsulta, Guid? codigoUsuarioSesion, string estadoConsulta, int numeroPagina, int registroPagina) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("CODIGO_REMITENTE",SqlDbType.UniqueIdentifier) { Value = (object)codigoRemitente ?? DBNull.Value}, new SqlParameter("CODIGO_DESTINATARIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoDestinatario ?? DBNull.Value}, new SqlParameter("CODIGO_TIPO_CONSULTA",SqlDbType.NVarChar) { Value = (object)CodigoTipoConsulta ?? DBNull.Value}, new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value}, new SqlParameter("CODIGO_AREA",SqlDbType.NVarChar) { Value = (object)codigoArea ?? DBNull.Value}, new SqlParameter("CODIGO_CONSULTA",SqlDbType.UniqueIdentifier) { Value = (object)codigoConsulta ?? DBNull.Value}, new SqlParameter("ESTADO_CONSULTA",SqlDbType.VarChar) { Value = (object)estadoConsulta ?? DBNull.Value}, new SqlParameter("CODIGO_USUARIO_SESSION",SqlDbType.UniqueIdentifier) { Value = (object)codigoUsuarioSesion ?? DBNull.Value}, new SqlParameter("PageNo",SqlDbType.Int) { Value = (object)numeroPagina ?? DBNull.Value}, new SqlParameter("PageSize",SqlDbType.Int) { Value = (object)registroPagina ?? DBNull.Value} }; var result = this.dataBaseProvider.ExecuteStoreProcedure<ConsultaLogic>("CTR.USP_CONSULTA_SEL", parametros).ToList(); return result; } /// <summary> /// Envia correo de consulta /// </summary> /// <param name="asunto">Asunto</param> /// <param name="textoNotificar">Texto a notificar</param> /// <param name="cuentaNotificar">Cuenta a notificar</param> /// <param name="cuentasCopias">Cuentas a copiar en el correo</param> /// <param name="profileCorreo">Perfil del correo</param> public int NotificarConsulta(string asunto, string textoNotificar, string cuentaNotificar, string cuentasCopias, string profileCorreo) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("ASUNTO",SqlDbType.NVarChar) { Value = (object)asunto ?? DBNull.Value}, new SqlParameter("TEXTO_NOTIFICAR",SqlDbType.NVarChar) { Value = (object)textoNotificar ?? DBNull.Value}, new SqlParameter("CUENTA_NOTIFICAR",SqlDbType.NVarChar) { Value = (object)cuentaNotificar ?? DBNull.Value}, new SqlParameter("CUENTAS_COPIAS",SqlDbType.NVarChar) { Value = (object)cuentasCopias ?? DBNull.Value}, new SqlParameter("PROFILE_CORREO",SqlDbType.NVarChar) { Value = (object)profileCorreo ?? DBNull.Value}, }; var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_ENVIAR_CORREO_CONSULTA", parametros).FirstOrDefault(); return result; } /// <summary> /// Retorna la lista de consulta. /// </summary> /// <param name="codigoRemitente">Codigo de Remitente</param> /// <param name="codigoDestinatario">Código de destinatario</param> /// <param name="CodigoTipoConsulta">Código de tipo de consulta</param> /// <param name="codigoUnidadOperativa">Código de unidad operativa</param> /// <param name="codigoArea">Código de área</param> /// <param name="codigoConsulta">Código de consulta</param> /// <param name="codigoUsuarioSesion">Código de usuario de sesion</param> /// <returns>Lista de consultas</returns> public List<ConsultaLogic> ListaConsultaSimple(Guid? codigoRemitente, Guid? codigoDestinatario, string CodigoTipoConsulta, Guid? codigoUnidadOperativa, string codigoArea, Guid? codigoConsulta, string estadoConsulta) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("CODIGO_REMITENTE",SqlDbType.UniqueIdentifier) { Value = (object)codigoRemitente ?? DBNull.Value}, new SqlParameter("CODIGO_DESTINATARIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoDestinatario ?? DBNull.Value}, new SqlParameter("CODIGO_TIPO_CONSULTA",SqlDbType.NVarChar) { Value = (object)CodigoTipoConsulta ?? DBNull.Value}, new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value}, new SqlParameter("CODIGO_AREA",SqlDbType.NVarChar) { Value = (object)codigoArea ?? DBNull.Value}, new SqlParameter("CODIGO_CONSULTA",SqlDbType.UniqueIdentifier) { Value = (object)codigoConsulta ?? DBNull.Value}, new SqlParameter("ESTADO_CONSULTA",SqlDbType.VarChar) { Value = (object)estadoConsulta ?? DBNull.Value}, }; var result = this.dataBaseProvider.ExecuteStoreProcedure<ConsultaLogic>("CTR.USP_LISTAR_CONSULTA_SEL", parametros).ToList(); return result; } } }
namespace MazeApp { public interface IMazeSolver { void Run(string[,] maze); } }