text
stringlengths
13
6.01M
using System; using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Helpers; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.EmbeddedContentItemsGraphSyncer; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Helpers; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Results.AllowSync; using Newtonsoft.Json.Linq; using OrchardCore.Flows.Models; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts.Flow { #pragma warning disable S1481 // need the variable for the new using syntax, see https://github.com/dotnet/csharplang/issues/2235 public class FlowPartGraphSyncer : EmbeddingContentPartGraphSyncer { private readonly IContentFieldsGraphSyncer _contentFieldsGraphSyncer; public override string PartName => nameof(FlowPart); protected override string ContainerName => "Widgets"; private static readonly Func<string, string> _flowFieldsPropertyNameTransform = n => $"flow_{n}"; public FlowPartGraphSyncer( IFlowPartEmbeddedContentItemsGraphSyncer flowPartEmbeddedContentItemsGraphSyncer, IContentFieldsGraphSyncer contentFieldsGraphSyncer) : base(flowPartEmbeddedContentItemsGraphSyncer) { _contentFieldsGraphSyncer = contentFieldsGraphSyncer; } public override Task AllowSync(JObject content, IGraphMergeContext context, IAllowSync allowSync) { return Task.WhenAll( base.AllowSync(content, context, allowSync), _contentFieldsGraphSyncer.AllowSync(content, context, allowSync)); } public override async Task AddSyncComponents(JObject content, IGraphMergeContext context) { //todo: make concurrent? await base.AddSyncComponents(content, context); // FlowPart allows part definition level fields, but values are on each FlowPart instance // prefix flow field property names, so there's no possibility of a clash with the eponymous fields property names using var _ = context.SyncNameProvider.PushPropertyNameTransform(_flowFieldsPropertyNameTransform); await _contentFieldsGraphSyncer.AddSyncComponents(content, context); } public override async Task<(bool validated, string failureReason)> ValidateSyncComponent(JObject content, IValidateAndRepairContext context) { (bool validated, string failureReason) = await base.ValidateSyncComponent(content, context); if (!validated) return (validated, failureReason); using var _ = context.SyncNameProvider.PushPropertyNameTransform(_flowFieldsPropertyNameTransform); return await _contentFieldsGraphSyncer.ValidateSyncComponent( content, context); } } #pragma warning restore S1481 }
namespace ForumSystem.Web.Tests.Routes.APIs { using ForumSystem.Web.Controllers.APIs; using ForumSystem.Web.ViewModels.Votes; using MyTested.AspNetCore.Mvc; using Xunit; public class VotesApiControllerTests { [Fact] public void PostPostVoteShouldBeRoutedCorrectly() => MyRouting .Configuration() .ShouldMap(request => request .WithMethod(HttpMethod.Post) .WithLocation("/api/votes") .WithJsonBody(new { id = 1, isUpVote = true, })) .To<VotesApiController>(c => c.PostPostVote(new VoteOnPostInpuModel { Id = 1, IsUpVote = true, })); [Fact] public void PostCommentVoteShouldBeRoutedCorrectly() => MyRouting .Configuration() .ShouldMap(request => request .WithMethod(HttpMethod.Post) .WithLocation("/api/votes/comment") .WithJsonBody(new { id = 1, isUpVote = true, })) .To<VotesApiController>(c => c.PostCommentVote(new VoteOnCommentInputModel { Id = 1, IsUpVote = true, })); } }
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using UnityEngine; using UnityEngine.UI; public class LogListGenerator : MonoBehaviour { public Transform logsGrid; List<GameObject> createdLogs = new List<GameObject> (); static GameObject listElementPrefab; ObservableCollection<string> _log; void Start () { listElementPrefab = Resources.Load ("Prefabs/LogElement") as GameObject; } public void Init (ObservableCollection<string> log) { _log = log; log.CollectionChanged += LogChanged; } public void Clear() { foreach (var logEl in createdLogs) { Destroy (logEl.gameObject); } createdLogs.Clear (); } void LogChanged (object sender, NotifyCollectionChangedEventArgs e) { if (e.Action != NotifyCollectionChangedAction.Add) { print ("Added to collection"); } /* if (_log.Count == createdLogs.Count) return; */ //Add more elements to the list of GameObjects for (int i = createdLogs.Count; i < _log.Count; i++) { if (listElementPrefab == null) listElementPrefab = Resources.Load ("Prefabs/LogElement") as GameObject; var obj = Instantiate (listElementPrefab, new Vector3 (0, 0, 0), Quaternion.identity); var textObj = obj.GetComponentInChildren<Text> (); textObj.text += _log [i]; createdLogs.Add (obj); obj.transform.SetParent (logsGrid); } //Rewrite text on created blocks int index = _log.Count - 1; foreach (string log in _log) { createdLogs [index].GetComponentInChildren<Text> ().text = log; index--; } } /* public void GenerateList(ObservableCollection<string> logs) { //public NotifyCollectionChangedEventHandler GenerateList () { if (logs.Count == createdLogs.Count) return; //Add more elements to the list of GameObjects for (int i = createdLogs.Count; i < logs.Count; i++) { if (listElementPrefab == null) listElementPrefab = Resources.Load ("Prefabs/LogElement") as GameObject; var obj = GameObject.Instantiate (listElementPrefab, new Vector3 (0, 0, 0), Quaternion.identity); var textObj = obj.GetComponentInChildren<Text> (); textObj.text += logs[i]; createdLogs.Add (obj); obj.transform.SetParent(logsGrid); } //Rewrite text on created blocks int index = logs.Count-1; foreach (string log in logs) { createdLogs [index].GetComponentInChildren<Text> ().text = log; index--; } } */ }
using AutoMapper; namespace Xunmei.Docs.Web { public class DocsWebAutoMapperProfile : Profile { public DocsWebAutoMapperProfile() { //Define your AutoMapper configuration here for the Web project. } } }
using System; using System.Web.Services; using System.Web.UI.WebControls; using BusinessLogic; using DataAccess; using log4net; namespace FirstWebStore.Pages { public partial class HomePage : System.Web.UI.Page { [WebMethod] public static string AddToCart(string id, string amount) //принимающий, обрабатывающий и отправляющий обратно данные метод { var logger = LogManager.GetLogger(typeof(HomePage)); var msg = "AJAX call AddToCart"; logger.Debug(msg); return "ID=" + id + Environment.NewLine + " Amount=" + amount; } [WebMethod] public static string GetCurrentTime(string name) //принимающий, обрабатывающий и отправляющий обратно данные метод { return "Hello to\"" + name + "\"" + Environment.NewLine + "Cur time is:" + DateTime.Now.ToString(); } protected void Page_Load(object sender, EventArgs e) { } protected void OnRowCommand(object sender, GridViewCommandEventArgs e) { Page.Validate(); if (!Page.IsValid || e.CommandName != "AddToCart") { return; } var index = Convert.ToInt32(e.CommandArgument); var row = GrViewOfProductsList.Rows[index]; int amount; if (!int.TryParse(((TextBox)row.Cells[5].FindControl("amountInput")).Text, out amount)) { return; } int selectedProductId; if (!int.TryParse(row.Cells[0].Text, out selectedProductId)) { return; } var userId = (Guid)Session["UserId"]; var businessLogicCart = StrMapContainer.GetInstance.GetContainer.GetInstance<BusinessLogicCart>(); businessLogicCart.InsertProductIntoCart(userId, selectedProductId, amount); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise9 { class Front { List<Employee> EmployeeList = new List<Employee>(); Logger LoggBok = new Logger(); public void fronten() { while (true) { Console.Clear(); Console.WriteLine(" -- Menu --\n---------------------------------------"); Console.WriteLine("1. Add employee \n2. Remove employee \n3. Print LoggBok \n4. Search\n5. exit\n---------------------------------------"); ConsoleKeyInfo key; key = Console.ReadKey(true); switch (key.KeyChar) { case '1': addEmployee(); break; case '2': RemoveEmployee(); break; case '3': LoggBok.ReadLog(); break; case '4': AdvansedSearch(); break; case '5': Environment.Exit(-1); return; default: break; } Console.ReadKey(); } } public void addEmployee() { Console.Clear(); Console.WriteLine("---Add Employee---\n"); Console.Write("FirstName: "); string FirstName = ERROR.NameCheck(); Console.Write("LastName: "); string LastName = ERROR.NameCheck(); Console.Write("Social security number:(10 numbers) :Example \"7803184069\" "); string Ssn = ERROR.CheckSsn(); Console.Write("Hourly wage: "); string Wage = ERROR.NumberCheckString(); Employee newEmployee = new Employee(FirstName, LastName, Ssn, Wage); EmployeeList.Add(newEmployee); Console.WriteLine("Employee added!"); LoggBok.Logg($"New employee added!\n\nName: {FirstName} {LastName}\nSsn: {Ssn}\nWage: {Wage}\n----------------------------"); } public void RemoveEmployee() { Console.Clear(); Console.WriteLine("Employee Social security number :10 numbers Example \"7803184069\" "); string control = ERROR.CheckSsn(); for(int i = 0;i< EmployeeList.Count;i++) { if (control == EmployeeList[i].Ssn) { LoggBok.Logg($"Employee removed!\n\nName: {EmployeeList[i].FullName}\nSsn: {EmployeeList[i].Ssn}\nWage: {EmployeeList[i].Wage}\n----------------------------"); EmployeeList.Remove(EmployeeList[i]); Console.WriteLine("Employee removed!"); return; } } } public void ReadEmployeeList() { Console.Clear(); Console.WriteLine("Employees\n\n----------------------------"); foreach (var item in EmployeeList) { Console.WriteLine($"Name: {item.FullName}\nSsn: {item.Ssn}\nWage: {item.Wage}\n----------------------------"); } } public void PutSomeEmployeeInList() { Employee Olle = new Employee("Olle", "Svensson", "0201175049", "112"); Employee Sven = new Employee("Sven", "Paulander", "8506134342", "155"); EmployeeList.Add(Olle); EmployeeList.Add(Sven); } public void AdvansedSearch() { Console.Clear(); Console.WriteLine("AdvansedSearch Search\n\n----------------------------------\n1.See all Employees\n2.Search with age\n3.Back\n----------------------------------"); ConsoleKeyInfo key; key = Console.ReadKey(true); switch (key.KeyChar) { case '1': ReadEmployeeList(); break; case '2': SearchWithAge(); break; case '3': return; default: AdvansedSearch(); break; } } public void SearchWithAge() { Console.Clear(); Console.WriteLine("--Search with age--\n\nSearch with as manny numbers you want\nMore numbers = more precise example: 1984"); int check; if (!int.TryParse(Console.ReadLine(), out check)) { Console.WriteLine("Write numbers!"); } int counter = 0; string stringcheck = Convert.ToString(check); foreach (var item in EmployeeList) { if (item.Ssn.StartsWith(stringcheck)) { Console.WriteLine($"Name: {item.FullName}\nSsn: {item.Ssn}\nWage: {item.Wage}\n----------------------------"); } if((!item.Ssn.StartsWith(stringcheck))) { counter++; } if (counter == EmployeeList.Count) { Console.WriteLine("No Match!"); } } } } }
using System; using System.Threading; namespace DesignPatternsWideWorldImporters.Singleton { public class StaticConstructorSingleton { static StaticConstructorSingleton() { Console.WriteLine("Calling StaticConstructorSingleton constructor..."); Thread.Sleep(1000); } public static StaticConstructorSingleton GetSingleton() { Console.WriteLine("Getting StaticConstructorSingleton instance..."); return new StaticConstructorSingleton(); } public int IntProperty { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelData : MonoBehaviour { public static LevelData instance; public byte id; public string levelName; public float levelTimer = 60; public string objectiveDescription = "Do something!"; public Objective[] mainObjectives; public Objective[] secondaryObjectives; private void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } SceneManager.LoadScene("LevelNecessities", LoadSceneMode.Additive); } public void Initialize(string _name, float _timer) { levelName = _name; levelTimer = _timer; } }
using System; using System.IO; using Aspose.Pdf.Generator; using Profiling2.Domain.Scr; namespace Profiling2.Infrastructure.Export.Screening { /// <summary> /// Ported from Profiling1. /// /// TODO rare problem with word wrap not working properly in table cells when columns set (PROF2-344). /// </summary> public abstract class BasePdfExportRequest { public byte[] PdfBytes { get; set; } /// <summary> /// Sets the PDF document information such as authors, etc. /// </summary> /// <returns>Pdf document object</returns> protected Pdf SetDocumentInformation() { Pdf pdf = new Pdf(); pdf.Author = "MONUSCO"; pdf.Creator = "MONUSCO"; pdf.Keywords = "MONUSCO Conditionality Policy"; pdf.Subject = "MONUSCO Conditionality Policy"; pdf.Title = "Request for Screening"; pdf.DestinationType = DestinationType.FitPage; pdf.PageSetup.Margin.Top = 72; pdf.PageSetup.Margin.Right = 72; pdf.PageSetup.Margin.Bottom = 72; pdf.PageSetup.Margin.Left = 72; return pdf; } /// <summary> /// Sets the header and footer for a section /// </summary> /// <param name="section">Pdf section for which to set header and footer</param> /// <returns>Pdf section object</returns> protected Section SetHeaderFooter(Request request, Section section) { Text text; //adding header HeaderFooter header = new HeaderFooter(); header.Margin.Top = 36; header.TextInfo.Alignment = AlignmentType.Center; header.TextInfo.Color = new Color("Red"); header.TextInfo.FontSize = 10; section.OddHeader = header; section.EvenHeader = header; header.Paragraphs.Add(new Text(header, "MONUSCO CONFIDENTIAL")); header.Paragraphs.Add(new Text(header, "SHARING WITH THIRD PARTIES SHOULD BE AUTHORISED BY MONUSCO")); //adding footer HeaderFooter footer = new HeaderFooter(); footer.Margin.Top = 0; footer.Margin.Bottom = 0; section.OddFooter = footer; section.EvenFooter = footer; text = new Text(footer, "Request for Screening #" + request.ReferenceNumber + " exported on " + DateTime.Now.ToString("dd MMMM yyyy h:mm:ss tt")); text.TextInfo.Alignment = AlignmentType.Center; text.TextInfo.FontSize = 10; footer.Paragraphs.Add(text); text = new Text(footer, "$p of $P"); text.TextInfo.Alignment = AlignmentType.Right; text.TextInfo.FontSize = 8; footer.Paragraphs.Add(text); return section; } /// <summary> /// Retrieves a byte array from the Pdf object /// </summary> /// <param name="pdf">Pdf object from which to retrieve byte array</param> /// <returns>Byte array of pdf object</returns> protected byte[] GetByteArray(Pdf pdf) { byte[] bytes; using (MemoryStream stream = new MemoryStream()) { pdf.Save(stream); bytes = stream.ToArray(); stream.Dispose(); } return bytes; } /// <summary> /// Sets the title /// </summary> /// <param name="section">Pdf section for which to set the title</param> /// <returns>Pdf section object</returns> protected Section SetTitle(Request request, ScreeningEntity screeningEntity, Section section) { string s = "Request for Screening #" + request.ReferenceNumber; if (screeningEntity != null) s += ", Response From " + screeningEntity.ToString(); Text text = new Text(section, s); text.TextInfo.FontSize = 18; text.TextInfo.IsUnderline = true; text.TextInfo.Alignment = AlignmentType.Left; text.Margin.Top = 24; text.Margin.Bottom = 24; section.Paragraphs.Add(text); return section; } /// <summary> /// Sets a row in the request details /// </summary> /// <param name="row">The row that has already been added to the request details table</param> /// <param name="label">The label of this request details row</param> /// <param name="value">The value for this request details row</param> /// <returns>Pdf row object</returns> protected Row SetRequestDetailsRow(Row row, string label, string value) { Cell labelCell, valueCell; TextInfo labelTextInfo = new TextInfo(); TextInfo valueTextInfo = new TextInfo(); row.VerticalAlignment = VerticalAlignmentType.Top; //text customization for labels in request details labelTextInfo.FontSize = 12; labelTextInfo.IsTrueTypeFontBold = false; labelTextInfo.Alignment = AlignmentType.Right; //text customization for values in request details valueTextInfo.FontSize = 12; valueTextInfo.IsTrueTypeFontBold = true; valueTextInfo.Alignment = AlignmentType.Left; //adding cell holding label labelCell = row.Cells.Add(label, labelTextInfo); labelCell.IsNoBorder = true; labelCell.Padding.Top = 9; labelCell.Padding.Right = 9; labelCell.Padding.Bottom = 9; labelCell.Padding.Left = 9; //adding cell holding value valueCell = row.Cells.Add(value, valueTextInfo); valueCell.IsNoBorder = true; valueCell.IsWordWrapped = true; valueCell.Padding.Top = 9; valueCell.Padding.Right = 9; valueCell.Padding.Bottom = 9; valueCell.Padding.Left = 9; return row; } } }
using Assets.src.data; using UnityEngine; using ViewModelFramework; namespace Assets.src.views { public class BuildingPrototypeView : BaseView { public MeshRenderer rendererScript; public Material placeFreeMaterial; public Material placeBusyMaterial; public Collider colliderScript; protected bool isActive = false; protected GameObject graphic; public override void ManualInit() { var buildingPrototypeModel = model as BuildingPrototypeModel; //buildingPrototypeModel.CurrentData.AsObservable().Subscribe(UpdateGraphics); } public void UpdateGraphics(BuildingData data) { if (data == null) return; if (graphic != null) Destroy(graphic); graphic = Object.Instantiate(data.prefab); graphic.transform.SetParent(transform, false); rendererScript = graphic.GetComponentInChildren<MeshRenderer>(); } public override void UpdateView() { base.UpdateView(); var buildingPrototypeModel = model as BuildingPrototypeModel; if (graphic != null) { graphic.SetActive(buildingPrototypeModel.IsActive); rendererScript.material = buildingPrototypeModel.PlaceIsNotFree ? placeBusyMaterial : placeFreeMaterial; } transform.localPosition = buildingPrototypeModel.Position; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Otiport.API.Data.Entities.ProfileItem; namespace Otiport.API.Repositories { public interface IProfileItemRepository { Task<IEnumerable<ProfileItemEntity>> GetProfileItemsAsync(); Task<bool> AddProfileItemAsync(ProfileItemEntity entity); Task<bool> DeleteProfileItemAsync(ProfileItemEntity entity); Task<ProfileItemEntity> GetProfileItemById(int id); Task<bool> UpdateProfileItemsAsync(ProfileItemEntity entity); } }
using System.Collections.Generic; using System; using Microsoft.AspNetCore.Mvc; using RestaurantList.Models; namespace RestaurantList.Controllers { public class HomeController : Controller { [HttpGet("/")] public ActionResult Index() { return View(); } [HttpGet("/restaurants")] public ActionResult Restaurants() { return View(); } [HttpPost("/restaurants")] public ActionResult AddRestaurant() { return View(); } [HttpGet("/restaurants/new")] public ActionResult RestaurantForm() { return View(); } [HttpGet("/cuisines")] public ActionResult Cuisines() { return View(); } [HttpPost("/cuisines")] public ActionResult AddCuisine() { Cuisine newCuisine = new Cuisine(Request.Form["new-name"]); newCuisine.Save(); return View(); } [HttpGet("/cuisines/new")] public ActionResult CuisineForm() { return View(); } } }
using System; using Grasshopper.Kernel; using Pterodactyl; using Xunit; namespace UnitTestsGH { public class TestFlowchartGhHelper { public static FlowchartGH TestObject { get { FlowchartGH testObject = new FlowchartGH(); return testObject; } } } public class TestFlowchartGh { [Theory] [InlineData("Flowchart", "Flowchart", "Add flowchart", "Pterodactyl", "Tools")] public void TestName(string name, string nickname, string description, string category, string subCategory) { Assert.Equal(name, TestFlowchartGhHelper.TestObject.Name); Assert.Equal(nickname, TestFlowchartGhHelper.TestObject.NickName); Assert.Equal(description, TestFlowchartGhHelper.TestObject.Description); Assert.Equal(category, TestFlowchartGhHelper.TestObject.Category); Assert.Equal(subCategory, TestFlowchartGhHelper.TestObject.SubCategory); } [Theory] [InlineData(0, "Direction", "Direction", "Set direction, True = from left to right, False = from top to bottom", GH_ParamAccess.item)] [InlineData(1, "Last Nodes", "Last Nodes", "Add last node / nodes of a flowchart as list", GH_ParamAccess.list)] public void TestRegisterInputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestFlowchartGhHelper.TestObject.Params.Input[id].Name); Assert.Equal(nickname, TestFlowchartGhHelper.TestObject.Params.Input[id].NickName); Assert.Equal(description, TestFlowchartGhHelper.TestObject.Params.Input[id].Description); Assert.Equal(access, TestFlowchartGhHelper.TestObject.Params.Input[id].Access); } [Theory] [InlineData(0, "Report Part", "Report Part", "Created part of the report", GH_ParamAccess.item)] public void TestRegisterOutputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestFlowchartGhHelper.TestObject.Params.Output[id].Name); Assert.Equal(nickname, TestFlowchartGhHelper.TestObject.Params.Output[id].NickName); Assert.Equal(description, TestFlowchartGhHelper.TestObject.Params.Output[id].Description); Assert.Equal(access, TestFlowchartGhHelper.TestObject.Params.Output[id].Access); } [Fact] public void TestGuid() { Guid expected = new Guid("b40a0ebe-dfe8-4586-82a6-cc95395fc9ef"); Guid actual = TestFlowchartGhHelper.TestObject.ComponentGuid; Assert.Equal(expected, actual); } [Fact] public void TestExposure() { GH_Exposure expected = GH_Exposure.secondary; GH_Exposure actual = TestFlowchartGhHelper.TestObject.Exposure; Assert.Equal(expected, actual); } } }
using GDS.Dal; using GDS.Entity; using System; using System.Collections.Generic; using GDS.Entity.Result; using GDS.Comon; using GDS.Entity.Constant; using System.Linq; namespace GDS.BLL { public class BackUserInfoBLL { IBackUerInfoDao<BackUserInfo> dal; public BackUserInfoBLL() { dal = new ImplBackUserInfo() { }; } /// <summary> /// 获取分页数据 /// </summary> /// <param name="preq"></param> /// <returns></returns> public List<BackUserInfo> GetDataByPage(PageRequest preq) { return dal.GetDataByPage<BackUserInfo>(preq); } public BackUserInfo GetBackUserInfoByLoginName(string name) { var user = dal.GetUserinfoByLoginName(name); if (user != null) { var role = GetRoleIdsByUId(user.Id).OrderBy(x => x.Id).FirstOrDefault(); if (role != null) { user.UserType = role.Id; user.UserTypeDesc = role.Name; } else { user.UserType = 0; user.UserTypeDesc = string.Empty; } //var userType = GetRoleIdsByUId(user.Id).OrderBy(x=>x.Id).FirstOrDefault()?.Id ?? 0; //取权限最大的 //user.UserType = userType; } return user; } public BackUserInfo GetBackUserInfoByloginToken(string loginToken) { var user = dal.GetUserinfoByloginToken(loginToken); if (user != null) { var userType = GetRoleIdsByUId(user.Id).OrderBy(x => x.Id).FirstOrDefault()?.Id ?? 0; user.UserType = userType; } return user; } public BackUserInfo GetDataById(int Id) { return dal.GetDataById<BackUserInfo>(Id); } /// <summary> /// 添加用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public ResultEntity<int> AddBackUserInfo(BackUserInfo user) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Insert<BackUserInfo>(user); if (repResult != null) { IntRet = int.Parse(repResult.ToString()); } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 修改用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public ResultEntity<int> UpdateBackUserInfo(BackUserInfo user) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<BackUserInfo>(user); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 删除用户 /// </summary> /// <param name="id"></param> /// <returns></returns> public ResultEntity<int> DeleteBackUserInfo(int Id) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.DeleteDataById<BackUserInfo>(Id); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipDelSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipDelFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 假删除数据 /// </summary> /// <param name="Ids"></param> /// <returns></returns> public ResultEntity<int> FalseDeleteDataByIds(int[] Ids) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.FalseDeleteDataByIds<BackUserInfo>(Ids); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipDelSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipDelFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 修改密码 /// </summary> /// <returns></returns> public ResultEntity<int> UpdatePassword(int UId, string psd) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<BackUserInfo>(new { Password = psd }, it => it.Id == UId); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } public ResultEntity<int> UpdateState(int UId, int State) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<BackUserInfo>(new { State = State }, it => it.Id == UId); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 修改用户登录信息 /// </summary> /// <param name="user"></param> /// <returns></returns> public ResultEntity<int> UpdateLoginToken(int UId, string LoginToken) { //ResultEntity<int> result; //try //{ // int IntRet = 0; // var repResult = dal.Update<BackUserInfo>(new { loginToken = LoginToken, loginTokenTime = DateTime.Now }, it => it.Id == UId); // if (repResult) // { // IntRet = 1; // } // if (IntRet > 0) // { // result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); // } // else // { // result = new ResultEntity<int>(ConstantDefine.TipSaveFail); // } //} //catch (Exception ex) //{ // Loger.LogErr(ex); // result = new ResultEntity<int>(ex.Message); //} //return result; ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<Users>(new { loginToken = LoginToken, loginTokenTime = DateTime.Now }, it => it.Id == UId); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } //根据用户获取角色 public List<BackRole> GetRoleIdsByUId(int Id) { List<BackUserRoleBind> RoleLi = new List<BackUserRoleBind>(); RoleLi = new BackUserRoleBindBLL().GetRoleIdsByUId(Id); List<BackRole> li = new List<BackRole>(); RoleLi.ForEach(x => { var entity = new BackRoleBLL().GetDataById(x.RoleId); if (entity != null) { li.Add(entity); } }); return li; } public bool IsRole(int Id, string role) { var roles = GetRoleIdsByUId(Id); return roles.Exists(x => x.Name == role); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using UberApp.Models; namespace UberApp.Controllers { public class OrdersController : ApiController { private MyAppDataEntities db = new MyAppDataEntities(); // GET: api/Orders public IQueryable<Order> GetOrders() { return db.Orders; } // GET: api/Orders/5 [ResponseType(typeof(Order))] public IHttpActionResult GetOrder(int id) { Order order = db.Orders.Find(id); if (order == null) { return NotFound(); } return Ok(order); } // PUT: api/Orders/5 [ResponseType(typeof(void))] public IHttpActionResult PutOrder(int id, Order order) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != order.OrdId) { return BadRequest(); } db.Entry(order).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); Console.WriteLine(message); } } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Orders [ResponseType(typeof(Order))] public IHttpActionResult PostOrder(Order order) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Orders.Add(order); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = order.OrdId }, order); } // DELETE: api/Orders/5 [ResponseType(typeof(Order))] public IHttpActionResult DeleteOrder(int id) { Order order = db.Orders.Find(id); if (order == null) { return NotFound(); } db.Orders.Remove(order); db.SaveChanges(); return Ok(order); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool OrderExists(int id) { return db.Orders.Count(e => e.OrdId == id) > 0; } [Route("api/GetDriverOrders")] public IEnumerable<OrderDetails> getInfo() { DriversGetsOrders1_Result oj = new DriversGetsOrders1_Result(); var result = db.Database.SqlQuery<OrderDetails>("SELECT OrdId ,CustId , totalPrice ,CustomerAddress , OrderStatus , DeliveryStatus FROM dbo.[Order] WHERE OrderStatus = 'Ready to be picked Up'"); return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnZombies : MonoBehaviour { //[SerializeField] public GameObject NewZombie; private int dayNum = 0; private int token = 0; // The token is to count the days! // Use this for initialization void Start () { //NewZombie = GameObject.FindWithTag("Zombie"); token = 0; } // Update is called once per frame void Update () { token = PlayerPrefs.GetInt("spawnZombieBool"); if (token == 1) { if (NewZombie == null) { Debug.Log("The zombie did not work! :( " + gameObject.name); } else { dayNum = PlayerPrefs.GetInt("dayCounter"); for (int i = 1; i <= dayNum; i++) { Instantiate(NewZombie); print("A new zombie spawned from " + gameObject.name); } token = 0; PlayerPrefs.SetInt("spawnZombieBool", token); } } } }
namespace Jypeli { /// <summary> /// Suunta/ele joka tunnistetaan. /// </summary> public enum AccelerometerDirection { /// <summary> /// kallistetaan mihin tahansa suuntaan. /// </summary> Any, /// <summary> /// Kallistetaan vasemalle. /// </summary> Left, /// <summary> /// Kallistetaan oikealle. /// </summary> Right, /// <summary> /// Kallistetaan ylös. /// </summary> Up, /// <summary> /// Kallistetaan alas. /// </summary> Down, /// <summary> /// Puhelimen ravistusele. /// </summary> Shake, /// <summary> /// Puhelimen "nopea liike"-ele, esim. näpäytys tai tärähdys. /// </summary> Tap } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AntiBacGrenade : MonoBehaviour { public float fuse = 3; public GameObject grenadeParticles; // Start is called before the first frame update void Start() { Destroy(gameObject, 3.02f); Vector2 antiBacGrenadeForce = new Vector2(0, -200); gameObject.GetComponent<Rigidbody2D>().AddRelativeForce(antiBacGrenadeForce, ForceMode2D.Impulse); } // Update is called once per frame void Update() { fuse = fuse - Time.deltaTime; if (fuse <= 0) for (int i = 0; i < 25; i++) Instantiate(grenadeParticles, transform.position, Quaternion.identity); } }
using System; using System.Collections.Generic; using System.Text; namespace InvoiceSOLIDApp { public interface ILogger { void Info(string info); void Debug(string info); void Error(string message, Exception ex); } public class Logger : ILogger { public Logger() { } public void Info(string info) { //throw new NotImplementedException(); } public void Debug(string info) { //throw new NotImplementedException(); } public void Error(string message, Exception ex) { //throw new NotImplementedException(); } } }
using Alabo.Cloud.People.UserDigitals.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.People.UserDigitals.Domain.Repositories { public class UserDigitalIndexRepository : RepositoryMongo<UserDigitalIndex, ObjectId>, IUserDigitalIndexRepository { public UserDigitalIndexRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Aranda.Users.BackEnd.Dtos; using Aranda.Users.BackEnd.Models; using Aranda.Users.BackEnd.Repositories.Definition; using Aranda.Users.BackEnd.Services.Definition; using AutoMapper; namespace Aranda.Users.BackEnd.Services.Implementation { public class UserService : IUserService { private readonly IUserRepository _userRepository; private readonly IRoleRepository _roleRepository; public UserService(IUserRepository userRepository, IRoleRepository roleRepository) { _userRepository = userRepository; _roleRepository = roleRepository; } public UserDataDto GetUser(string userName, string password) { var user = _userRepository.GetUser(userName, password); var userDto = Mapper.Map<UserDataDto>(user); var rol = _roleRepository.GetPermissionsByRol(user.RoleId); userDto.Role.RolePermission = rol.RolePermission.Select(x => new PermissionDto { Id = x.Permission.Id, Action = x.Permission.Action }); return userDto; } public IEnumerable<UserDto> GetAll(Func<User, bool> filter) { return _userRepository.GetAll(filter).Select(Mapper.Map<UserDto>); } public UserDto AddUser(UserDto user) { var userDto = _userRepository.AddUser(Mapper.Map<User>(user)); userDto.Role = _roleRepository.GetRolById(userDto.RoleId); return Mapper.Map<UserDto>(userDto); } public async Task<UserDto> UpdateUser(UserDto userDto) { var user = await _userRepository.UpdateUser(Mapper.Map<User>(userDto)); return Mapper.Map<UserDto>(user); } public bool DeleteUser(int userId) { return _userRepository.DeleteUser(userId); } } }
namespace OrganizerLive.Utility { using System; public static class Composer { public static char[][] GetBox(int width, int height) { char[][] matrix = new char[height][]; return matrix; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using KhanaKhajana.Models; using KhanaKhajana.Services; using System.Net.Mail; using System.Text; using System.Threading; namespace KhanaKhajana { public partial class Cart : System.Web.UI.Page { #region globalVariables ProductServices productServices = new ProductServices(); CommonFunctions commonFunction = new CommonFunctions(); User user = new User(); UserServices userServices = new UserServices(); CartItems cart = new CartItems(); OrderServices orderServices = new OrderServices(); #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.Master.PageHeader = "Cart"; DisplayCart(); if (Session["Source"] != null) { if (Convert.ToString(Session["Source"]) == "Cart") { DisplayUserDestails(); } } } } private void DisplayCart() { var list = cart.GetCart(); if (list.Count == 0) { btnCheckout.Enabled = false; rptrCart.DataSource = ""; rptrCart.DataBind(); pnlCheckout.Visible = false; } else { rptrCart.DataSource = list; rptrCart.DataBind(); CalculateFinalTotal(); } } private void CalculateFinalTotal() { double subtotal = 0; for (int j = 0; j < rptrCart.Items.Count; j++) { Label lblTotal = rptrCart.Items[j].FindControl("rptrlblTotalPrice") as Label; subtotal += Convert.ToDouble(lblTotal.Text.ToString().Split(new[] { " " }, StringSplitOptions.None)[1]); } lblSubtotal.Text = "$ " + subtotal.ToString(); } protected void rptrlbDelete_Command(object sender, CommandEventArgs e) { cart.RemoveItemFromCart(Convert.ToInt32(e.CommandName)); DisplayCart(); this.Master.NoOfProducts = cart.Count.ToString(); } protected void rptrtbQuantity_TextChanged(object sender, EventArgs e) { TextBox tb1 = ((TextBox)(sender)); RepeaterItem rp1 = ((RepeaterItem)(tb1.NamingContainer)); TextBox qnt = (TextBox)rp1.FindControl("rptrtbQuantity"); Label price = (Label)rp1.FindControl("rptrlblPrice"); Label total_lbl = (Label)rp1.FindControl("rptrlblTotalPrice"); if (Convert.ToInt32(qnt.Text) <= 0) { total_lbl.Text = ""; qnt.Text = "1"; total_lbl.Text = price.Text.ToString(); } else { double tot_price = Convert.ToInt32(qnt.Text) * Convert.ToDouble(price.Text.ToString().Split(new[] { " " }, StringSplitOptions.None)[1]); total_lbl.Text = "$ " + tot_price.ToString(); CalculateFinalTotal(); } } protected void btnCheckout_Click(object sender, EventArgs e) { if (Convert.ToString(Session["UserId"]) == "") { Session["Source"] = "Cart"; ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "alert('Login first.');window.location ='Login.aspx'", true); } else { DisplayUserDestails(); } } private void DisplayUserDestails() { pnlCheckout.Visible = true; pnlCheckout.Focus(); user = userServices.GetUserById(Convert.ToInt32(Session["UserId"])); tbAddressLine1.Text = user.AddressLine1; tbCity.Text = user.City; tbProvince.Text = user.Province; tbZipCode.Text = user.ZipCode; tbMobileNo.Text = user.MobileNo; } protected void btnConfirmOrder_Click(object sender, EventArgs e) { if (tbMobileNo.Text.Length != 10) { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showAlert('Error!','Invalid Mobile No.')", true); } else { Order order = new Order(); OrderViewModel model = new OrderViewModel(); List<OrderItem> oiList = new List<OrderItem>(); order.UserId = Convert.ToInt32(Session["UserId"]); order.OrderDate = DateTime.Now; order.AddressLine1 = tbAddressLine1.Text; order.City = tbCity.Text; order.Province = tbProvince.Text; order.ZipCode = tbZipCode.Text; order.MobileNo = tbMobileNo.Text; order.Instruction = tbInstruction.Text; order.Status = 1; for (int i = 0; i < rptrCart.Items.Count; i++) { OrderItem orderItem = new OrderItem(); Label lblProductid = rptrCart.Items[i].FindControl("rptrlblProductId") as Label; TextBox tbQty = rptrCart.Items[i].FindControl("rptrtbQuantity") as TextBox; ProductViewModel product = new ProductViewModel(); product = productServices.GetProductsByIdForCart(Convert.ToInt32(lblProductid.Text)); orderItem.ProductId = Convert.ToInt32(lblProductid.Text); orderItem.Qty = Convert.ToInt32(tbQty.Text); orderItem.Price = product.Price; orderItem.DiscountPercent = product.DiscountedPercent; orderItem.FinalPrice = product.DiscountedPrice; oiList.Add(orderItem); } model.order = order; model.OrderItems = oiList; SaveOrder(model); } } private void SaveOrder(OrderViewModel model) { string response = ""; response = orderServices.AddOrder(model); if (response == "Success") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showAlert('Success','Order is booked.')", true); EmptyCart(); // GenerateMsgForEmail(model); Thread email = new Thread(delegate() { SendEmail(model); }); email.IsBackground = true; email.Start(); } else { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showAlert('Error!','" + response + "')", true); } } public string GenerateMsgForEmail(OrderViewModel model) { string msg = ""; double? subTot = 0; msg += "<table width='100%' cellspacing='2' cellpadding='4' border='0' align='center' bgcolor='#ff6600'><thead><tr><th>Product Name</th><th>Qty.</th><th>Price</th><th>Total</th></tr></thead><tbody>"; foreach (var pr in model.OrderItems) { ProductViewModel Pmodel = new ProductViewModel(); Pmodel = productServices.GetProductsByIdForCart(pr.ProductId); double? price = pr.DiscountPercent == 0 ? pr.Price : pr.FinalPrice; //double? tot = pr.DiscountPercent == 0 ? (pr.Price * pr.Qty) : (pr.FinalPrice * pr.Qty); double? tot = price * pr.Qty; subTot += tot; msg += "<tr bgcolor='#ffffff' align='center'>"; msg += "<td>" + Pmodel.ProductName + "</td>"; msg += "<td>" + pr.Qty + "</td>"; msg += "<td>$ " + price.ToString() + "</td>"; msg += "<td>$ " + tot + "</td></tr>"; } msg += "<tr><td colspan='4' align='right' style='weight:900;'>Sub Total = $ " + subTot.ToString() + "</td></tr></tbody></table>"; return msg; } private void EmptyCart() { cart.EmptyCart(); DisplayCart(); this.Master.NoOfProducts = "0"; lblSubtotal.Text = ""; } private void SendEmail(OrderViewModel model) { try { User user = new User(); user = userServices.GetUserById(model.order.UserId); MailMessage mm = new MailMessage(); mm.From = new MailAddress("khajana246@gmail.com", "Khana Khajana"); mm.To.Add(user.EmailId); mm.Subject = "Order Details"; mm.Body += "<br />Hello: " + user.Fname + " " + user.Fname + "<br /><center><font style='font-size:12px;weight:550;'>Thank you for your booking from Khana Khajana. Your order has been received.</font>"; mm.Body += "<br/ ><b>Order Details :-</b><br/>"; mm.Body += GenerateMsgForEmail(model); mm.Body += "<br /><font style='font-size:12px;'>You Will Receive Your Order At Your Delivery Address With in 40 minutes.</font></center>"; mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; smtp.UseDefaultCredentials = true; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("khajana246@gmail.com", "khanakhajana@123"); smtp.Send(mm); } catch (Exception ex) { string Mail_msg = "Mail can't be sent because of server problem: "; // Mail_msg += ex.Message; ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showAlert('Error!','" + Mail_msg + "')", true); //Response.Write(Mail_msg); // Label11.Text = Mail_msg; } } } }
using System; using System.IO; using System.Linq; using System.Collections.Generic; using CoreGraphics; using UIKit; using CoreFoundation; using AVFoundation; using Photos; using Foundation; namespace AVMetadataRecordPlay { public class Rects { public IEnumerable<CGRect> Added { get; set; } public IEnumerable<CGRect> Removed { get; set; } } public partial class AssetGridViewController : UICollectionViewController, IPHPhotoLibraryChangeObserver { const string cellReuseIdentifier = "AssetGridViewCell"; public AssetGridViewController() : base("AssetGridViewController", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized){ SetUpPhotoLibrary(); UpdateTitle(); }else{ PHPhotoLibrary.RequestAuthorization((status)=>{ if (status == PHAuthorizationStatus.Authorized){ DispatchQueue.MainQueue.DispatchAsync(()=>{ this.SetUpPhotoLibrary(); this.UpdateTitle(); this.CollectionView.ReloadData(); }); }else{ DispatchQueue.MainQueue.DispatchAsync(() => { var message = "AVMetadataRecordPlay doesn't have permission to the photo library, please change privacy settings"; var alertController = UIAlertController.Create("AVMetadataRecordPlay", message, UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, null)); alertController.AddAction(UIAlertAction.Create("Settings", UIAlertActionStyle.Default, (action)=>{ UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString)); })); this.PresentViewController(alertController, true, null); }); } }); } } public override void ViewWillAppear(Boolean animated) { base.ViewWillAppear(animated); var screenScale = UIScreen.MainScreen.Scale; var spacing = new nfloat(2.0 / screenScale); var cellWidth = (Math.Min(View.Frame.Width, View.Frame.Height) - spacing * 3) / 4.0; var flowLayout = (UICollectionViewFlowLayout)this.Layout; flowLayout.ItemSize = new CGSize(cellWidth, cellWidth); flowLayout.SectionInset = new UIEdgeInsets(spacing, new nfloat(0.0), spacing, new nfloat(0.0)); flowLayout.MinimumInteritemSpacing = spacing; flowLayout.MinimumLineSpacing = spacing; // Save the thumbnail size in pixels. AssetGridThumbnailSize = new CGSize(cellWidth * screenScale, cellWidth * screenScale); } public override void ViewDidAppear(Boolean animated) { base.ViewDidAppear(animated); UpdateCachedAssets(); } bool IsScrolledToBottom = false; public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); if (!IsScrolledToBottom){ var numberOfAssets = AssetsFetchResult.Count; if (numberOfAssets > 0){ var lastIndexPath = NSIndexPath.FromItemSection(numberOfAssets - 1, 0); CollectionView.ScrollToItem(lastIndexPath, UICollectionViewScrollPosition.Bottom, false); IsScrolledToBottom = true; } } } public override void ViewDidDisappear(Boolean animated) { base.ViewDidDisappear(animated); if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized) { PHPhotoLibrary.SharedPhotoLibrary.UnregisterChangeObserver(this); } } // MARK: Photo Library PHCachingImageManager ImageManager; private void SetUpPhotoLibrary(){ ImageManager = new PHCachingImageManager(); ResetCachedAssets(); var videoSmartAlbumsFetchResult = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.SmartAlbumVideos, null); var videoSmartAlbum = (PHAssetCollection)videoSmartAlbumsFetchResult[0]; AssetsFetchResult = PHAsset.FetchAssets(videoSmartAlbum, null); PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this); } public void PhotoLibraryDidChange(PHChange changeInstance){ /* Change notifications may be made on a background queue. Re-dispatch to the main queue before acting on the change as we'll be updating the UI. */ DispatchQueue.MainQueue.DispatchAsync(() => { var collectionChanges = changeInstance.GetFetchResultChangeDetails(this.AssetsFetchResult); // Get the new fetch result. this.AssetsFetchResult = collectionChanges.FetchResultAfterChanges; this.UpdateTitle(); if (!collectionChanges.HasIncrementalChanges || collectionChanges.HasMoves){ CollectionView.ReloadData(); }else{ var collectionView = CollectionView; collectionView.PerformBatchUpdates(()=>{ var removed = collectionChanges.RemovedIndexes; if (removed != null && removed.Count > 0) CollectionView.DeleteItems(ToNSIndexPaths(removed)); var inserted = collectionChanges.InsertedIndexes; if (inserted != null && inserted.Count > 0) CollectionView.InsertItems(ToNSIndexPaths(inserted)); var changed = collectionChanges.ChangedIndexes; if (changed != null && changed.Count > 0) CollectionView.ReloadItems(ToNSIndexPaths(changed)); }, null); } this.ResetCachedAssets(); }); } static NSIndexPath[] ToNSIndexPaths(NSIndexSet indexSet) { var cnt = indexSet.Count; var result = new NSIndexPath[(int)cnt]; int i = 0; indexSet.EnumerateIndexes((nuint idx, ref bool stop) => { stop = false; result[i++] = NSIndexPath.FromItemSection((nint)idx, 0); }); return result; } private void UpdateTitle() { Title = $"Videos ({AssetsFetchResult.Count})"; } // MARK: Asset Management CGSize AssetGridThumbnailSize = CGSize.Empty; PHFetchResult AssetsFetchResult; CGRect previousPreheatRect = CGRect.Empty; int AssetRequestID = 0; //PHInvalidImageRequestID FIND THE KEY UIAlertController LoadingAssetAlertController = null; public AVAsset SelectedAsset = null; private void ResetCachedAssets(){ ImageManager.StopCaching(); previousPreheatRect = CGRect.Empty; } void UpdateCachedAssets() { bool isViewVisible = IsViewLoaded && View.Window != null; if (!isViewVisible) return; if (PHPhotoLibrary.AuthorizationStatus != PHAuthorizationStatus.Authorized){ return; } // The preheat window is twice the height of the visible rect. CGRect preheatRect = CollectionView.Bounds; preheatRect = preheatRect.Inset(0, -preheatRect.Height / 2); // Update only if the visible area is significantly different from the last preheated area. nfloat delta = NMath.Abs(preheatRect.GetMidY() - previousPreheatRect.GetMidY()); if (delta <= CollectionView.Bounds.Height / 3) return; // Compute the assets to start caching and to stop caching. var rects = ComputeDifferenceBetweenRect(previousPreheatRect, preheatRect); var addedAssets = rects.Added .SelectMany(rect => CollectionView.GetIndexPaths(rect)) .Select(indexPath => AssetsFetchResult.ObjectAt(indexPath.Item)) .Cast<PHAsset>() .ToArray(); var removedAssets = rects.Removed .SelectMany(rect => CollectionView.GetIndexPaths(rect)) .Select(indexPath => AssetsFetchResult.ObjectAt(indexPath.Item)) .Cast<PHAsset>() .ToArray(); // Update the assets the PHCachingImageManager is caching. ImageManager.StartCaching(addedAssets, AssetGridThumbnailSize, PHImageContentMode.AspectFill, null); ImageManager.StopCaching(removedAssets, AssetGridThumbnailSize, PHImageContentMode.AspectFill, null); // Store the preheat rect to compare against in the future. previousPreheatRect = preheatRect; } static Rects ComputeDifferenceBetweenRect(CGRect oldRect, CGRect newRect) { if (!oldRect.IntersectsWith(newRect)) { return new Rects { Added = new CGRect[] { newRect }, Removed = new CGRect[] { oldRect } }; } var oldMaxY = oldRect.GetMaxY(); var oldMinY = oldRect.GetMinY(); var newMaxY = newRect.GetMaxY(); var newMinY = newRect.GetMinY(); var added = new List<CGRect>(); var removed = new List<CGRect>(); if (newMaxY > oldMaxY) added.Add(new CGRect(newRect.X, oldMaxY, newRect.Width, newMaxY - oldMaxY)); if (oldMinY > newMinY) added.Add(new CGRect(newRect.X, newMinY, newRect.Width, oldMinY - newMinY)); if (newMaxY < oldMaxY) removed.Add(new CGRect(newRect.X, newMaxY, newRect.Width, oldMaxY - newMaxY)); if (oldMinY < newMinY) removed.Add(new CGRect(newRect.X, oldMinY, newRect.Width, newMinY - oldMinY)); return new Rects { Added = added, Removed = removed }; } // MARK: Collection View public override nint GetItemsCount(UICollectionView collectionView, nint section) { return AssetsFetchResult.Count; } public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var asset = (PHAsset)AssetsFetchResult[indexPath.Item]; // Dequeue an GridViewCell. var cell = (AssetGridViewCell)collectionView.DequeueReusableCell(cellReuseIdentifier, indexPath); // Request an image for the asset from the PHCachingImageManager. cell.RepresentedAssetIdentifier = asset.LocalIdentifier; ImageManager.RequestImageForAsset(asset, AssetGridThumbnailSize, PHImageContentMode.AspectFill, null, (image, info) => { // Set the cell's thumbnail image if it's still showing the same asset. if (cell.RepresentedAssetIdentifier == asset.LocalIdentifier) cell.ThumbnailImage = image; }); return cell; } public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath) { var asset = (PHAsset)AssetsFetchResult[indexPath.Item]; var requestOptions = new PHVideoRequestOptions(); requestOptions.NetworkAccessAllowed = true; requestOptions.ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => { stop = false; if (error != null){ Console.WriteLine("Error loading video"); //DO SOMETHING BETTER HERE return; } var requestID = (NSNumber)info[PHImageKeys.ResultRequestID]; DispatchQueue.MainQueue.DispatchAsync(() => { if (this.AssetRequestID == (int)requestID){ if (this.LoadingAssetAlertController != null){ LoadingAssetAlertController.Message = $"Progress: {progress * 100}%"; }else{ this.LoadingAssetAlertController = UIAlertController.Create("Loading Video", "Progress: 0%", UIAlertControllerStyle.Alert); LoadingAssetAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => { this.ImageManager.CancelImageRequest((int)requestID); this.AssetRequestID = 0; //INVALID REQUEST ID this.LoadingAssetAlertController = null; })); this.PresentViewController(LoadingAssetAlertController, true, null); } } }); }; this.AssetRequestID = ImageManager.RequestAvAsset(asset, requestOptions, (vasset, audioMix, info) => { DispatchQueue.MainQueue.DispatchAsync(() => { if (vasset != null){ this.SelectedAsset = vasset; this.PerformSegue("backToPlayer", this); } }); }); } public override void Scrolled(UIScrollView scrollView){ UpdateCachedAssets(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TY.SPIMS.Utilities; namespace TY.SPIMS.Client.Helper.CodeGenerator { public class PurchaseCounterCodeGenerator : IGenerator { //Format: PCOU[YY]-0001 public string GenerateCode() { try { string number = "1"; var db = ConnectionManager.Instance.Connection; var p = db.CounterPurchases .OrderByDescending(a => a.Id) .FirstOrDefault(); if (p != null) //If there are previous items { string[] vCode = p.CounterNumber.Split('-'); if (vCode.Length == 2) { string thisYear = DateTime.Now.Year.ToString().Substring(2, 2); string voucherYear = vCode[0].Substring(4, 2); int oldNumber = vCode[1].ToInt(); if (string.Compare(voucherYear, thisYear) == 0) number = (oldNumber + 1).ToString(); } } StringBuilder codeBuilder = new StringBuilder(); codeBuilder.AppendFormat("PCOU{0}-{1}", DateTime.Now.Year.ToString().Substring(2, 2), number.PadLeft(4, '0')); return codeBuilder.ToString(); } catch (Exception ex) { throw ex; } } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `StringPair`. Inherits from `AtomDrawer&lt;StringPairEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(StringPairEvent))] public class StringPairEventDrawer : AtomDrawer<StringPairEvent> { } } #endif
using System.ComponentModel; namespace Properties.Core.Objects { public enum DealType { Unknown = 0, [Description("Pay When Rented")] PayWhenRented = 1, [Description("Pay Upfront")] PayUpfront = 2, [Description("Free Listing")] Free = 3, } }
namespace DChild.Gameplay.Player { internal interface ILever { void MoveLever(); void SnapLever(); } }
namespace HiLoSocket.Compressor { /// <summary> /// ICompressor. /// </summary> public interface ICompressor { /// <summary> /// Compresses the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> /// <returns>Bytes</returns> byte[ ] Compress( byte[ ] bytes ); /// <summary> /// Decompresses the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> /// <returns>Bytes</returns> byte[ ] Decompress( byte[ ] bytes ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace goPlayApi.Models { public class Venue { public int VenueId { get; set; } public String VenueName { get; set; } public String Address { get; set; } public String Number { get; set; } public String Image { get; set; } public double Ratings { get; set; } = 0.0; public int RatingCount { get; set; } = 0; public double Amount { get; set; } = 0.0; public String Description { get; set; } public String TimeSlot { get; set; } public List<VenuesImage> VenueImages { get; set; } } }
using System.Data; using System.Linq; namespace Marten { public interface IDiagnostics { /// <summary> /// Generates the NpgsqlCommand object that would be used to execute a Linq query. Use this /// to preview SQL or trouble shoot problems /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <returns></returns> IDbCommand CommandFor<T>(IQueryable<T> queryable); /// <summary> /// Returns the dynamic C# code that will be generated for the document type. Useful to understand /// the internal behavior of Marten for a single document type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> string DocumentStorageCodeFor<T>(); } }
using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Crawler; using CrawlerTest.Commands; using CrawlerTest.Model; namespace CrawlerTest.ViewModel { internal class CrawlerViewModel : ViewModelBase { private readonly AsyncCommand command; private CrawlResult crawlResult; private readonly CrawlerModel crawlerModel; public CrawlerViewModel() { crawlerModel = new CrawlerModel(); command = new AsyncCommand( async () => { if (command.CanExecute) { DisableCommand(); CrawlResult = await crawlerModel.GetCrawlerResult(); EnableCommand(); } }); } public CrawlResult CrawlResult { get { return crawlResult; } set { if (crawlResult != value) { crawlResult = value; OnPropertyChanged(nameof(CrawlResult)); } } } public AsyncCommand Comand => command; private void DisableCommand() { command.CanExecute = false; } private void EnableCommand() { command.CanExecute = true; } } }
using System; using System.Linq.Expressions; using Expr = System.Linq.Expressions.Expression; namespace Utils.Specification { public class NotSpec<T> : Spec<T> { private readonly Spec<T> _spec; public NotSpec(Spec<T> spec) { _spec = spec ?? throw new ArgumentNullException(nameof(spec)); } public override Expression<Func<T, bool>> Expression { get { var expr = _spec.Expression; return Expr.Lambda<Func<T, bool>>(Expr.Not(expr.Body), expr.Parameters); } } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj is NotSpec<T> other) return Equals(other); return false; } protected bool Equals(NotSpec<T> other) { return Equals(_spec, other._spec); } public override int GetHashCode() { return _spec.GetHashCode() ^ GetType().GetHashCode(); } } }
using Sort.Model; using System.Collections.Generic; namespace Sort.View { public interface ISortView : IView { DataList GetDataList(); void Display(IEnumerable<Data> data); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Colours { class Bullet { Texture2D texProj, texHit; Vector2 pos, posadj; Vector2 origin = new Vector2(0, 0); public Vector2 Pos{ get { return pos; } } private readonly int[] DAMAGE = new int[3] { 4, 4, 8 }; private readonly int[] SPEED = new int[3] { 4, 4, 8 }; public int Damage{ get { return DAMAGE[level]; } } byte colour; public byte Colour{ get { return colour; } } sbyte level; bool active; public bool Active{ get { return active; } } bool hit; public bool Hit{ get { return hit; } } const int HITTIMEMAX = 15; int hitTime; const int BLOCKWIDTH = 4; const int BLOCKHEIGHT = 8; const int IBLOCKWIDTH = 16; const int IBLOCKHEIGHT = 16; Vector2 posadji = new Vector2(IBLOCKWIDTH / 2, IBLOCKHEIGHT / 2); /// <summary> /// Constructs a bullet with default values /// </summary> public Bullet() { } /// <summary> /// Constructs a Bullet with new values. Exceptions retain defaults. /// </summary> public Bullet(sbyte weplevel, byte wepcolour, Vector2 mousePos, Vector2 playerPos, Texture2D bullettex, Texture2D hittex, byte dual) { level = weplevel; colour = wepcolour; texProj = bullettex; texHit = hittex; active = true; int mouseX = (int)mousePos.X; int mouseY = (int)mousePos.Y; int playerX = (int)playerPos.X; int playerY = (int)playerPos.Y; if (weplevel != -1) { switch (weplevel) { case 0: posadj = new Vector2(BLOCKWIDTH / 2, BLOCKHEIGHT / 2); pos.X = playerX; pos.Y = playerY - 64; break; case 1: posadj = new Vector2(BLOCKWIDTH / 2, BLOCKHEIGHT / 2); if (dual == 0) { //left bullet pos.X = playerX - 42; pos.Y = playerY - 64; } if (dual == 1) { //right bullet pos.X = playerX + 42; pos.Y = playerY - 64; } break; case 2: posadj = new Vector2(BLOCKWIDTH, BLOCKHEIGHT); if (dual == 0) { //left bullet pos.X = playerX - 42; pos.Y = playerY - 64; } if (dual == 1) { //right bullet pos.X = playerX + 42; pos.Y = playerY - 64; } break; } } } public void Move() { if (active && !hit) { pos.Y -= SPEED[level]; } if (pos.Y < 0) { active = false; } } public void Draw(SpriteBatch sprbat) { if (active == true && level != -1) { if (level != 2) { if (!hit) { sprbat.Draw(texProj, new Rectangle((int)(pos.X - posadj.X), (int)(pos.Y - posadj.Y), BLOCKWIDTH, BLOCKHEIGHT), new Rectangle(colour * BLOCKWIDTH, 0, BLOCKWIDTH, BLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else { hitTime--; if (hitTime > (HITTIMEMAX / 3 * 2)) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X), (int)(pos.Y - posadji.Y), IBLOCKWIDTH, IBLOCKHEIGHT), new Rectangle(colour * IBLOCKWIDTH, 0, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime > (HITTIMEMAX / 3)) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X), (int)(pos.Y - posadji.Y), IBLOCKWIDTH, IBLOCKHEIGHT), new Rectangle(colour * IBLOCKWIDTH, IBLOCKHEIGHT, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime > 0) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X), (int)(pos.Y - posadji.Y), IBLOCKWIDTH, IBLOCKHEIGHT), new Rectangle(colour * IBLOCKWIDTH, IBLOCKHEIGHT * 2, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime <= 0) { active = false; } } } else if (level == 2) { if (!hit) { sprbat.Draw(texProj, new Rectangle((int)(pos.X - posadj.X), (int)(pos.Y - posadj.Y), BLOCKWIDTH * 2, BLOCKHEIGHT * 2), new Rectangle(colour * BLOCKWIDTH * 2, 0, BLOCKWIDTH * 2, BLOCKHEIGHT * 2), Color.White, 0, origin, 0, 0.01f); } else { hitTime--; if (hitTime > (HITTIMEMAX / 3 * 2)) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X * 2), (int)(pos.Y - posadji.Y * 2), IBLOCKWIDTH * 2, IBLOCKHEIGHT * 2), new Rectangle(colour * IBLOCKWIDTH, 0, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime > (HITTIMEMAX / 3)) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X * 2), (int)(pos.Y - posadji.Y * 2), IBLOCKWIDTH * 2, IBLOCKHEIGHT * 2), new Rectangle(colour * IBLOCKWIDTH, IBLOCKHEIGHT, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime > 0) { sprbat.Draw(texHit, new Rectangle((int)(pos.X - posadji.X * 2), (int)(pos.Y - posadji.Y * 2), IBLOCKWIDTH * 2, IBLOCKHEIGHT * 2), new Rectangle(colour * IBLOCKWIDTH, IBLOCKHEIGHT * 2, IBLOCKWIDTH, IBLOCKHEIGHT), Color.White, 0, origin, 0, 0.01f); } else if (hitTime <= 0) { active = false; } } } } } public Rectangle GetRect() { if (level == 2) { return new Rectangle((int)(pos.X - posadj.X), (int)(pos.Y - posadj.Y), BLOCKWIDTH * 2, BLOCKHEIGHT * 2); } else { return new Rectangle((int)(pos.X - posadj.X), (int)(pos.Y - posadj.Y), BLOCKWIDTH, BLOCKHEIGHT); } } public void HitObject() { if (!hit) { hit = true; hitTime = HITTIMEMAX; } } } }
// <copyright file="ZipkinTraceExporterRemoteEndpointTests.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // 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> using System.Collections.Generic; using OpenTelemetry.Exporter.Zipkin.Implementation; using Xunit; namespace OpenTelemetry.Exporter.Zipkin.Tests.Implementation { public class ZipkinTraceExporterRemoteEndpointTests { private static readonly ZipkinEndpoint DefaultZipkinEndpoint = new ZipkinEndpoint("TestService"); [Fact] public void ZipkinSpanConverterTest_GenerateSpan_RemoteEndpointOmittedByDefault() { // Arrange var activity = ZipkinExporterTests.CreateTestActivity(); // Act & Assert var zipkinSpan = ZipkinActivityConversionExtensions.ToZipkinSpan(activity, DefaultZipkinEndpoint); Assert.Null(zipkinSpan.RemoteEndpoint); } [Fact] public void ZipkinSpanConverterTest_GenerateSpan_RemoteEndpointResolution() { // Arrange var activity = ZipkinExporterTests.CreateTestActivity( additionalAttributes: new Dictionary<string, object> { ["net.peer.name"] = "RemoteServiceName", }); // Act & Assert var zipkinSpan = ZipkinActivityConversionExtensions.ToZipkinSpan(activity, DefaultZipkinEndpoint); Assert.NotNull(zipkinSpan.RemoteEndpoint); Assert.Equal("RemoteServiceName", zipkinSpan.RemoteEndpoint.ServiceName); } [Fact] public void ZipkinSpanConverterTest_GenerateSpan_RemoteEndpointResolutionPriority() { // Arrange var activity = ZipkinExporterTests.CreateTestActivity( additionalAttributes: new Dictionary<string, object> { ["http.host"] = "DiscardedRemoteServiceName", ["net.peer.name"] = "RemoteServiceName", ["peer.hostname"] = "DiscardedRemoteServiceName", }); // Act & Assert var zipkinSpan = ZipkinActivityConversionExtensions.ToZipkinSpan(activity, DefaultZipkinEndpoint); Assert.NotNull(zipkinSpan.RemoteEndpoint); Assert.Equal("RemoteServiceName", zipkinSpan.RemoteEndpoint.ServiceName); } } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using Alabo.Users.Entities; namespace Alabo.Users.Services { /// <summary> /// Class UserService. /// </summary> public class AlaboUserService : ServiceBase<User, long>, IAlaboUserService { public AlaboUserService(IUnitOfWork unitOfWork, IRepository<User, long> repository) : base(unitOfWork, repository) { ; } } }
using System.Collections.Generic; using System.Text; using System; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using CocosSharp; namespace ChipmunkSharp { public class CCChipmunkDebugDraw : cpDebugDraw { #if WINDOWS_PHONE || OUYA public const int CircleSegments = 16; #else public const int CircleSegments = 32; #endif internal Color TextColor = Color.White; CCPrimitiveBatch primitiveBatch; SpriteFont spriteFont; List<StringData> stringData; StringBuilder stringBuilder; cpVect[] springPoints = new cpVect[]{ new cpVect(0.00f, 0.0f), new cpVect(0.20f, 0.0f), new cpVect(0.25f, 3.0f), new cpVect(0.30f, -6.0f), new cpVect(0.35f, 6.0f), new cpVect(0.40f, -6.0f), new cpVect(0.45f, 6.0f), new cpVect(0.50f, -6.0f), new cpVect(0.55f, 6.0f), new cpVect(0.60f, -6.0f), new cpVect(0.65f, 6.0f), new cpVect(0.70f, -3.0f), new cpVect(0.75f, 6.0f), new cpVect(0.80f, 0.0f), new cpVect(1.00f, 0.0f) }; #region Structs struct StringData { public object[] Args; public Color Color; public string S; public int X, Y; public StringData(int x, int y, string s, object[] args, Color color) { X = x; Y = y; S = s; Args = args; Color = color; } } #endregion Structs #region Constructors public CCChipmunkDebugDraw(string spriteFontName) { primitiveBatch = new CCPrimitiveBatch(CCDrawManager.SharedDrawManager); spriteFont = CCContentManager.SharedContentManager.Load<SpriteFont>(spriteFontName); stringData = new List<StringData>(); stringBuilder = new StringBuilder(); } #endregion Constructors public override void DrawBB(cpBB bb, cpColor color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } DrawPolygon(new cpVect[] { new cpVect(bb.r, bb.b), new cpVect(bb.r, bb.t), new cpVect(bb.l, bb.t), new cpVect(bb.l, bb.b) }, 4, color); return; } public override void DrawPolygon(cpVect[] vertices, int vertexCount, cpColor color) { CCColor4B fillColor = color.ToCCColor4B(); if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } for (int i = 0; i < vertexCount - 1; i++) { primitiveBatch.AddVertex(vertices[i].ToCCVector2(), fillColor, PrimitiveType.LineList); primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2(), fillColor, PrimitiveType.LineList); } primitiveBatch.AddVertex(vertices[vertexCount - 1].ToCCVector2(), fillColor, PrimitiveType.LineList); primitiveBatch.AddVertex(vertices[0].ToCCVector2(), fillColor, PrimitiveType.LineList); } public override void DrawSolidPolygon(cpVect[] vertices, int vertexCount, cpColor color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } if (vertexCount == 2) { DrawPolygon(vertices, vertexCount, color); return; } CCColor4B colorFill = color.ToCCColor4B() * 0.5f; for (int i = 1; i < vertexCount - 1; i++) { CCVector2 vertice0 = vertices[0].ToCCVector2(); primitiveBatch.AddVertex(ref vertice0, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(vertices[i].ToCCVector2(), colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2(), colorFill, PrimitiveType.TriangleList); } DrawPolygon(vertices, vertexCount, color); } public override void DrawCircle(cpVect center, float radius, cpColor color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const float increment = cp.M_PI * 2.0f / CircleSegments; float theta = 0.0f; var col = color; var colorOutline = col.ToCCColor4B(); CCVector2 centr = center.ToCCVector2(); CCVector2 thetaV = CCVector2.Zero; for (int i = 0, count = CircleSegments; i < count; i++) { thetaV.X = cp.cpfcos(theta); thetaV.Y = cp.cpfsin(theta); CCVector2 v1 = centr + Convert.ToSingle(radius) * thetaV; thetaV.X = cp.cpfcos(theta + increment); thetaV.Y = cp.cpfsin(theta + increment); CCVector2 v2 = centr + Convert.ToSingle(radius) * thetaV; primitiveBatch.AddVertex(ref v1, colorOutline, PrimitiveType.LineList); primitiveBatch.AddVertex(ref v2, colorOutline, PrimitiveType.LineList); theta += increment; } } public override void DrawSolidCircle(cpVect center, float radius, cpVect axis, cpColor color) { float segments = (10 * cp.cpfsqrt(radius)); //<- Let's try to guess at # segments for a reasonable smoothness var colorOutline = color.ToCCColor4B(); var colorFill = colorOutline * 0.5f; var centr = center.ToCCVector2(); if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } float increment = cp.M_PI * 2.0f / segments; float theta = 0.0f; CCVector2 thetaV = new CCVector2((float)Math.Cos(theta), (float)Math.Sin(theta)); CCVector2 v0 = center.ToCCVector2() + (float)radius * thetaV; theta += increment; var v1 = CCVector2.Zero; var v2 = CCVector2.Zero; for (int i = 0, count = (int)segments; i < count; i++) { thetaV.X = (float)Math.Cos(theta); thetaV.Y = (float)Math.Sin(theta); v1 = centr + Convert.ToSingle(radius) * thetaV; thetaV.X = (float)Math.Cos(theta + increment); thetaV.Y = (float)Math.Sin(theta + increment); v2 = centr + Convert.ToSingle(radius) * thetaV; primitiveBatch.AddVertex(ref v0, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(ref v1, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(ref v2, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(ref v1, colorOutline, PrimitiveType.LineList); primitiveBatch.AddVertex(ref v2, colorOutline, PrimitiveType.LineList); theta += increment; } DrawSegment(center, center + axis * radius, color); } public void DrawSegment(CCPoint from, CCPoint to, float radius, cpColor color) { var colorFill = color.ToCCColor4B(); if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } var a = from; var b = to; var n = CCPoint.Normalize(CCPoint.PerpendicularCCW(a - b)); var nw = n * (float)radius; var v0 = b - nw; var v1 = b + nw; var v2 = a - nw; var v3 = a + nw; // Triangles from beginning to end primitiveBatch.AddVertex(v1, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(v2, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(v0, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(v1, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(v2, colorFill, PrimitiveType.TriangleList); primitiveBatch.AddVertex(v3, colorFill, PrimitiveType.TriangleList); } public override void DrawSegment(cpVect p1, cpVect p2, cpColor color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } DrawSegment( new CCPoint((float)p1.x, (float)p1.y), new CCPoint((float)p2.x, (float)p2.y), 1, color); } public override void DrawSegment(cpVect p1, cpVect p2, float lineWidth, cpColor color) { if (!primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } DrawSegment(new CCPoint((float)p1.x, (float)p1.y), new CCPoint((float)p2.x, (float)p2.y), lineWidth, color); } public override void DrawString(int x, int y, string format, params object[] objects) { stringData.Add(new StringData(x, y, format, objects, Color.White)); } public override void DrawPoint(cpVect p, float size, cpColor color) { float hs = (float)size / 2.0f; cpVect[] verts = new cpVect[]{ p + new cpVect(-hs, -hs), p + new cpVect(hs, -hs), p + new cpVect(hs, hs), p + new cpVect(-hs, hs) }; DrawSolidPolygon(verts, 4, color); } public bool Begin() { primitiveBatch.Begin(); return true; } public void End() { primitiveBatch.End(); var _batch = CCDrawManager.SharedDrawManager.SpriteBatch; _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); for (int i = 0; i < stringData.Count; i++) { stringBuilder.Length = 0; stringBuilder.AppendFormat(stringData[i].S, stringData[i].Args); _batch.DrawString(spriteFont, stringBuilder, new Vector2(stringData[i].X, stringData[i].Y), stringData[i].Color); } _batch.End(); stringData.Clear(); } public override void DrawSpring(cpVect a, cpVect b, cpColor cpColor) { cpVect prevPoint = new cpVect(a.x, a.y); var delta = cpVect.cpvsub(b, a); var len = cpVect.cpvlength(delta); var rot = cpVect.cpvmult(delta, 1f / len); cpVect tmpPoint; for (var i = 1; i < springPoints.Length; i++) { tmpPoint = cpVect.cpvadd(a, cpVect.cpvrotate(new cpVect(springPoints[i].x * len, springPoints[i].y * cp.scale), rot)); DrawSegment(prevPoint, tmpPoint, cpColor); prevPoint = tmpPoint; } } } }
using Newtonsoft.Json; using System; namespace ReceptiAPI.DTO { public class KorakPripremeDTO { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "idRecepta")] public string IdRecepta { get; set; } [JsonProperty(PropertyName = "redniBroj")] public uint RedniBroj { get; set; } [JsonProperty(PropertyName = "opis")] public string Opis { get; set; } [JsonProperty(PropertyName = "savet")] public string Savet { get; set; } [JsonProperty(PropertyName = "datumKreiranja")] public DateTime DatumKreiranja { get; set; } [JsonProperty(PropertyName = "datumAzuriranja")] public DateTime DatumAzuriranja { get; set; } } }
using System; namespace ProvaP1___Semestre2 { class Conta { public float saldo; public string nome; public string nconta; public Conta() { saldo = 0; nome = "Vinícius Orrutia"; nconta = "27067559-6"; } public void Depositar(float va) { saldo += va; } public void Sacar(float vs) { saldo -= vs; } public void ObterNomeCliente() { Console.WriteLine(nome); } public void ObterSaldo() { Console.WriteLine("O seu saldo atual é de : R${0}", saldo); } public void ObterNumeroConta() { Console.WriteLine(nconta); } } class Program { static void Main(string[] args) { Conta c1 = new Conta(); float va; float vs; int op; Console.WriteLine(" -*Conta Bancária*-"); c1.ObterNomeCliente(); c1.ObterNumeroConta(); do { Console.WriteLine(); Console.WriteLine("1 - Depositar"); Console.WriteLine("2 - Sacar"); Console.WriteLine("3 - Dados da conta"); Console.WriteLine("4 - Calcular saldo"); Console.WriteLine("5 - Sair"); Console.WriteLine(); op = int.Parse(Console.ReadLine()); switch (op) { case 1: Console.WriteLine(); Console.WriteLine("Insira o valor do depósito: "); va = float.Parse(Console.ReadLine()); c1.Depositar(va); Console.WriteLine(); c1.ObterSaldo(); break; case 2: Console.WriteLine(); Console.WriteLine("Insira o valor a ser sacado: "); vs = float.Parse(Console.ReadLine()); c1.Sacar(vs); Console.WriteLine(); c1.ObterSaldo(); break; case 3: Console.Write("O nome do titular da conta é: "); c1.ObterNomeCliente(); Console.Write("O número da conta é: "); c1.ObterNumeroConta(); break; case 4: Console.WriteLine(); c1.ObterSaldo(); break; case 5: break; } } while (op != 5); } } }
using System.Threading.Tasks; using Xamarin.Forms; namespace XamJam.Nav.Navigation { public class NavigationDestination<TViewModel> : PageDestination<NavigationScheme> { public NavigationDestination(NavigationScheme navScheme, TViewModel viewModel, View view) : base(navScheme, viewModel, view) { } public NavigationDestination(NavigationScheme navScheme, TViewModel viewModel, Page page) : base(navScheme, viewModel, page) { } public async Task PushAsync() { if (NavScheme.NavigationPage == null) NavScheme.SetupNavigationPage(Page); await NavScheme.NavigationPage.PushAsync(Page, false); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShapeDestroy : MonoBehaviour { [SerializeField] PlayerMovement PM; void Update() { transform.position = new Vector3(PM.transform.position.x, transform.position.y, PM.transform.position.z); transform.rotation = Quaternion.Lerp(transform.rotation, PM.transform.rotation, 0.1f); } private void OnTriggerEnter(Collider other) { if(other.gameObject.CompareTag("AllyShape") || other.gameObject.CompareTag("EnemyShape")) { Destroy(other.gameObject); } } }
using Microwave.Exceptions; namespace Microwave.Entities { public static class Verifiers { public static void VerifyName(string text) { if (string.IsNullOrWhiteSpace(text)) { throw new CustomExceptions("É necessário informar um alimento."); } } public static void VerifyTimer(string text) { if (string.IsNullOrWhiteSpace(text)) { throw new CustomExceptions("É necessário informar o tempo de aquecimento."); } int textToInt = int.Parse(text); if (textToInt < DefaultConfiguration.MIN_TIMER || textToInt > DefaultConfiguration.MAX_TIMER) { throw new CustomExceptions("É necessário informar um valor dentro do limite (1~120)."); } } public static int VerifyPower(string text) { if (text.Trim() == "") { return DefaultConfiguration.DEFAULT_POWER; } int textToInt = int.Parse(text); if (textToInt < DefaultConfiguration.MIN_POWER || textToInt > DefaultConfiguration.MAX_POWER) { throw new CustomExceptions("É necessário informar um valor dentro do limite (1~10)."); } return textToInt; } public static char VerifyChar(string text) { if (string.IsNullOrWhiteSpace(text)) { throw new CustomExceptions("É necessário informar o caractere de aquecimento."); } char textToChar = char.Parse(text); return textToChar; } public static bool VerifyProgram(string text) { foreach (DefaultPrograms obj in DefaultPrograms.programsList) { if (text.ToUpper().Trim() == obj.ProgramName.ToUpper().Trim()) { return true; } } return false; } } }
using GatewayEDI.Logging.Factories; namespace GatewayEDI.Logging.Resolver { /// <summary> A resolver that always returns a <see cref="NullLogFactory" />, which in turn creates a <see cref="NullLog" /> instance. </summary> public sealed class NullLogFactoryResolver : IFactoryResolver { /// <summary> The log factory instance. </summary> private static readonly ILogFactory factory = NullLogFactory.Instance; /// <summary> Determines a factory which cab create an <see cref="ILog" /> instance based on a request for a named log. </summary> /// <param name="logName"> The log name. </param> /// <returns> A factory which in turn is responsible for creating a given <see cref="ILog" /> implementation. </returns> public ILogFactory GetFactory(string logName) { return factory; } #region singleton /// <summary> Singleton instance. </summary> private static readonly NullLogFactoryResolver instance = new NullLogFactoryResolver(); /// <summary> Explicit static constructor to tell C# compiler not to mark type as beforefieldint </summary> static NullLogFactoryResolver() { } /// <summary> Provides access to the singleton instance of the class. </summary> public static NullLogFactoryResolver Instance { get { return instance; } } /// <summary> Private constructor. A reference to the Singleton instance of this class is available through the static <see cref="Instance" /> property. </summary> private NullLogFactoryResolver() { } #endregion } }
using FeriaVirtual.App.Desktop.Extensions.DependencyInjection; using FeriaVirtual.App.Desktop.Forms.MainForms; using FeriaVirtual.App.Desktop.SeedWork.FormControls; using FeriaVirtual.App.Desktop.Services.SignIn; using MetroFramework; using MetroFramework.Forms; using Microsoft.Extensions.DependencyInjection; using System; using System.Windows.Forms; namespace FeriaVirtual.App.Desktop.Forms.SignIn { public partial class LoginForm : MetroForm { private readonly ThemeManager _themeManager; public LoginForm() { InitializeComponent(); _themeManager = ThemeManager.SuscribeForm(this); _themeManager.DarkMode(); } private void LoginForm_Load(object sender, EventArgs e) { UsernameTextBox.Text = string.Empty; PasswordTextBox.Text = string.Empty; UsernameTextBox.Focus(); } private async void AceptFormButton_Click (object sender, EventArgs e) { try { var serviceProvider = DependencyContainer.GetProvider; ISigninService s = serviceProvider.GetService<ISigninService>(); await s.SigninAsync(this.UsernameTextBox.Text, this.PasswordTextBox.Text); OpenForm(); } catch (Exception ex) { MetroMessageBox.Show(this, ex.Message, "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void CancelFormButton_Click (object sender, EventArgs e) => Environment.Exit(0); private void OpenForm() { Hide(); using (var form = new AdminForm()) { form.ShowDialog(); } } } }
using System; namespace Exercicio11 { class ImpressaoQuadrado { static String Quadrado(int N, int I, int J, char C1) { { if (I < 0) { return "\n"; } else { if (J <= N - 1) return C1 + Quadrado(N, I, J + 1, C1); else return "\n" + Quadrado(N, I - 1, 0, C1); } } } static void Main(string[] args) { char C1 = '*'; int N = 6; Console.WriteLine(Quadrado(N, N - 1, 0, C1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Model.APIModels.Result { public class E_WorkingHours: E_Response { public List<E_WorkingHoursInfo> content { get; set; } } }
using EasyDev.Configuration; using System.Data.Common; namespace EasyDev.PL { /// <summary> /// 数据源管理器 /// <example> /// 创建默认的数据源:<br/> /// <code> /// IDataSourceObject dsObj = DataSourceManager.CreateDefaultDataSource(); /// </code> /// 创建命名数据源:<br/> /// <code> /// IDataSourceObject dsObj = DataSourceManager.CreateDataSource(dataSourceName); /// </code> /// <remarks> /// 数据源名称是在EasyDev.Persistence.Config文件中设置的名称,默认数据源是在这个配置文件中DataSources结点Default属性的值所对应的数据源配置 /// </remarks> /// </example> /// </summary> public class DataSourceManager { private static PersistenceConfigManager configMgr = null; #region IDBProviderManager 成员 /// <summary> /// 根据配置信息产生数据库提供程序 /// </summary> /// <returns></returns> public static DataSourceObject CreateDefaultDataSource() { configMgr = PersistenceConfigManager.GetInstance(); DataSourceObject provider = new DataSourceObject(DbProviderFactories.GetFactory(configMgr.GetDefaultDataSource().ProviderType)); provider.ProviderName =configMgr.DefaultDataSource; return provider; } /// <summary> /// 根据配置信息中的数据源名称产生会话对象的方法 /// </summary> /// <param name="name">数据源配置的名称</param> /// <returns></returns> public static DataSourceObject CreateDataSource(string name) { string type = ""; configMgr = PersistenceConfigManager.GetInstance(); foreach (IDataSource providerItem in configMgr.DataSources.Values) { if (providerItem.Name == name) { type = providerItem.ProviderType; } } DataSourceObject provider = new DataSourceObject(DbProviderFactories.GetFactory(type)); provider.ProviderName = name; return provider; } #endregion } }
using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramFootballBot.Core.Data; using TelegramFootballBot.Core.Exceptions; using TelegramFootballBot.Core.Services; namespace TelegramFootballBot.Core.Models.Commands { public class UnregisterCommand : Command { public override string Name => "/unreg"; private readonly IMessageService _messageService; private readonly IPlayerRepository _playerRepository; public UnregisterCommand(IMessageService messageService, IPlayerRepository playerRepository) { _messageService = messageService; _playerRepository = playerRepository; } public override async Task ExecuteAsync(Message message) { var playerName = await DeletePlayer(message.From.Id); var messageForUser = string.IsNullOrEmpty(playerName) ? "Вы не были зарегистрированы" : "Рассылка отменена"; await Task.WhenAll(new[] { _messageService.SendMessageAsync(message.Chat.Id, messageForUser), _messageService.SendMessageToBotOwnerAsync($"{playerName} отписался от рассылки") }); } private async Task<string> DeletePlayer(long playerId) { try { var player = await _playerRepository.GetAsync(playerId); await _playerRepository.RemoveAsync(player.Id); return player.Name; } catch (UserNotFoundException) { return null; } } } }
namespace DealOrNoDeal.Data.SettingVariables { /// <summary> /// Holds the settings for the cases to open /// /// Author: Alex DeCesare /// Version: 04-September-2021 /// </summary> public enum CasesToOpenSettings { /// <summary> /// The five round cases to open settings /// </summary> FiveRoundGame, /// <summary> /// The seven round cases to open settings /// </summary> SevenRoundGame, /// <summary> /// The ten round cases to open settings /// </summary> TenRoundGame } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaveSpawner : MonoBehaviour { public float minTime = 5f; public float maxTime = 15f; public float duration = 10; public float minSpeed = 3f; public float maxSpeed = 10f; public float minXPos = -5f; public float maxXPos = 5f; public float angleBound = 45f; public GameObject wavePrefab; private float timer; // Use this for initialization void Start () { timer = Random.Range(minTime, maxTime); } // Update is called once per frame void Update () { if(LevelState.singleton.gameActive) { timer -= Time.smoothDeltaTime; if (timer <= 0f) { timer = Random.Range(minTime, maxTime); GameObject wave = Instantiate(wavePrefab); float angle = Random.Range(-angleBound, angleBound); float xPos = Random.Range(minXPos, maxXPos); float yPos = Camera.main.orthographicSize * (Random.value > 0.5f ? 1f : -1f); float speed = Random.Range(minSpeed, maxSpeed); angle -= 90 * Mathf.Sign(yPos); wave.transform.position = new Vector3(xPos, yPos); ForceArea forceArea = wave.GetComponent<ForceArea>(); forceArea.desiredSpeed = speed * 0.8f; forceArea.angle = angle; forceArea.acceleration = 10f * (speed/maxSpeed); StartCoroutine(MoveWave(wave, duration, angle, speed)); //LevelState.singleton.waves.Add(forceArea); } } } IEnumerator MoveWave (GameObject g, float duration, float angle, float speed) { for(float f = duration; f >= 0; f -= Time.smoothDeltaTime) { if(g == null) break; Vector2 velocity = (Vector2) (Quaternion.Euler(0,0,angle) * Vector2.right * speed * Time.smoothDeltaTime); g.transform.position += (Vector3) velocity; yield return new WaitForFixedUpdate(); } Destroy(g); } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.Entity { public class PictureType { public string pictureTypeId { get; set; } public string pictureType { get; set; } public string parentPictureTypeId { get; set; } public bool isActive { get; set; } public int sort { get; set; } public DateTime? createDate { get; set; } public DateTime? updateDate { get; set; } public string createBy { get; set; } public string updateBy { get; set; } public string taskTypeId { get; set; } } public class PictureTypeConfig : EntityTypeConfiguration<PictureType> { public PictureTypeConfig() { ToTable("PictureType"); Property(t => t.pictureTypeId).HasColumnName("picture_type_id"); Property(t => t.pictureType).HasColumnName("picture_type"); Property(t => t.parentPictureTypeId).HasColumnName("parent_picture_type_id"); Property(t => t.isActive).HasColumnName("isActive"); Property(t => t.sort).HasColumnName("sort"); Property(t => t.createDate).HasColumnName("create_date"); Property(t => t.updateDate).HasColumnName("update_date"); Property(t => t.createBy).HasColumnName("create_by"); Property(t => t.updateBy).HasColumnName("update_by"); Property(t => t.taskTypeId).HasColumnName("task_type_id"); HasKey(t => t.pictureTypeId); } } }
using System; using System.Collections.Generic; using Xunit; using ZKCloud.Domains.EntityHistory; using ZKCloud.Extensions; using ZKCloud.Test.Samples; using ZKCloud.Test.XUnitHelpers; namespace ZKCloud.Test.Domains { /// <summary> /// 列表比较器测试 /// </summary> public class ListComparatorTest { /// <summary> /// 测试初始化 /// </summary> public ListComparatorTest() { _comparator = new ListComparator<AggregateRootSample, Guid>(); } /// <summary> /// 列表比较器 /// </summary> private readonly ListComparator<AggregateRootSample, Guid> _comparator; /// <summary> /// 测试列表比较 /// </summary> [Fact] public void TestCompare() { var id = Guid.NewGuid(); var id2 = Guid.NewGuid(); var id3 = Guid.NewGuid(); var id4 = Guid.NewGuid(); var newList = new List<AggregateRootSample> { new AggregateRootSample(id), new AggregateRootSample(id2), new AggregateRootSample(id3) }; var oldList = new List<AggregateRootSample> { new AggregateRootSample(id2), new AggregateRootSample(id3), new AggregateRootSample(id4) }; var result = newList.Compare(oldList); Assert.Single(result.CreateList); Assert.Equal(id, result.CreateList[0].Id); Assert.Single(result.DeleteList); Assert.Equal(id4, result.DeleteList[0].Id); Assert.Equal(2, result.UpdateList.Count); Assert.Equal(id2, result.UpdateList[0].Id); Assert.Equal(id3, result.UpdateList[1].Id); } /// <summary> /// 测试列表比较 - 获取创建列表 /// </summary> [Fact] public void TestCompare_CreateList() { var id = Guid.NewGuid(); var newList = new List<AggregateRootSample> { new AggregateRootSample(id) {Name = "a"} }; var result = _comparator.Compare(newList, new List<AggregateRootSample>()); Assert.Single(result.CreateList); Assert.Equal("a", result.CreateList[0].Name); } /// <summary> /// 测试列表比较 - 获取删除列表 /// </summary> [Fact] public void TestCompare_DeleteList() { var id = Guid.NewGuid(); var oldList = new List<AggregateRootSample> { new AggregateRootSample(id) {Name = "a"} }; var result = _comparator.Compare(new List<AggregateRootSample>(), oldList); Assert.Empty(result.CreateList); Assert.Single(result.DeleteList); Assert.Equal("a", result.DeleteList[0].Name); } /// <summary> /// 测试列表比较 - 获取更新列表 /// </summary> [Fact] public void TestCompare_UpdateList() { var id = Guid.NewGuid(); var newList = new List<AggregateRootSample> { new AggregateRootSample(id) {Name = "a"} }; var oldList = new List<AggregateRootSample> { new AggregateRootSample(id) {Name = "b"} }; var result = _comparator.Compare(newList, oldList); Assert.Empty(result.CreateList); Assert.Empty(result.DeleteList); Assert.Single(result.UpdateList); Assert.Equal("a", result.UpdateList[0].Name); } /// <summary> /// 测试列表比较 - 验证集合为空 /// </summary> [Fact] public void TestCompare_Validate() { var list = new List<AggregateRootSample>(); AssertHelper.Throws<ArgumentNullException>(() => { _comparator.Compare(null, list); }); AssertHelper.Throws<ArgumentNullException>(() => { _comparator.Compare(list, null); }); AssertHelper.Throws<ArgumentNullException>(() => { // list.Compare(null); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio2 { class Program { static void Main(string[] args) { /*Ingrese 3 notas por teclado Informe su total y su promedio llamando a una funcion que se llame CalcularPromedio*/ /*Generar una funcion que se llame FuncionCubo*/ string flag = ""; do { Console.WriteLine("Ingrese nota numero 1 (puede contener decimales): "); double n1 = double.Parse(Console.ReadLine()); Console.WriteLine("Ingrese nota numero 2 (puede contener decimales): "); double n2 = double.Parse(Console.ReadLine()); Console.WriteLine("Ingrese nota numero 3 (puede contener decimales): "); double n3 = double.Parse(Console.ReadLine()); Console.WriteLine("El promedio de las 3 notas es de {0}.", CalcularPromedio(n1,n2,n3)); Console.WriteLine("\n¿Desea seguir? Escriba NO para salir: "); flag = Console.ReadLine(); Console.WriteLine(""); } while (flag.ToLower() != "no"); Console.ReadKey(); } public static double CalcularPromedio(double n1, double n2, double n3) { return ((n1 + n2 + n3) / 3); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Core4.Controllers.Resources; using Core4.Core; using Core4.Core.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace Core4.Controllers { [Route("/api/vehciles/{vehcileId}/photos")] public class PhotosController : Controller { private readonly IHostingEnvironment host; private readonly IVehcileRepository repository; private readonly IUnitOfWork unitOfWork; private readonly IMapper mapper; private readonly PhotoSettings photoSettings; private readonly IPhotoRepository photoRepository; private readonly IPhotoService photoService; public PhotosController(IPhotoService photoService, IHostingEnvironment host, IVehcileRepository repository, IMapper mapper , IOptionsSnapshot<PhotoSettings> options, IPhotoRepository photoRepository) { this.photoSettings = options.Value; this.host = host; this.repository = repository; this.mapper = mapper; this.photoRepository = photoRepository; this.photoService = photoService; } public IActionResult Index() { return View(); } [HttpGet("/api/vehciles/{vehcileId}/photos")] public async Task<IEnumerable<PhotoResource>> GetPhotos(int vehcileId) { var photo = await photoRepository.GetPhotos(vehcileId); return mapper.Map<IEnumerable<Photo>, IEnumerable<PhotoResource>>(photo); } [HttpPost] public async Task<IActionResult> Upload(int vehcileId, IFormFile file ) { var vehcile = await repository.GetVehcile(vehcileId,IncludeRelated:false); if (vehcile == null) return NotFound(); if (file == null) return BadRequest("File not found"); if (file.Length == 0) return BadRequest("Empty File"); if (file.Length > photoSettings.MaxBytes) return BadRequest("Max File size"); if (!photoSettings.isSupport(file.FileName)) return BadRequest("Extension issue"); var uploadFolderPath = Path.Combine(host.WebRootPath, "uploads"); var photo= await photoService.UploadPhoto(vehcile, file, uploadFolderPath); return Ok(mapper.Map<Photo, PhotoResource>(photo)); } } }
using DAL.Controllers; using DAL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SHOeP.Account { public partial class MittKonto : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { /* Visa User info */ var userController = new UserController(); /* Har ska vänta på Session--------------*/ var user = (User)Session["user"]; lblFN.Text += user.FirstName; lblEfterN.Text += user.LastName; lblPost.Text += user.Email; lblPhone.Text += user.Phone; lblAdress.Text += user.Address; lblCode.Text += user.Zip; lblCity.Text += user.City; lblPassword.Text += user.Password; } protected void btnShicka_Click(object sender, EventArgs e) { User newUser = new DAL.Models.User(); newUser.FirstName = txtFirstname.Text; newUser.LastName = txtLastname.Text; newUser.Email = txtMail.Text; newUser.Address = txtAddress.Text; newUser.City = txtCity.Text; newUser.Zip = txtZip.Text; newUser.Password = txtPassword.Text; UserController usercon = new UserController(); usercon.UpdateUser(newUser); if (!string.IsNullOrEmpty(newUser?.Email) && !string.IsNullOrEmpty(newUser.Password)) { Session["User"] = newUser; Response.RedirectPermanent("~/Default.aspx"); } else { Response.Redirect("~/Account/MittKonto.aspx"); } } } }
namespace WinAppDriver.UI { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Windows.Automation; using System.Xml; using System.Xml.XPath; internal class UIAutomation : IUIAutomation { private static ILogger logger = Logger.GetLogger("WinAppDriver"); private static IDictionary<ControlType, string> controlTypes = new Dictionary<ControlType, string>(); private static IDictionary<string, ControlType> tagNames = new Dictionary<string, ControlType>(); private IElementFactory elementFactory; static UIAutomation() { var types = new List<ControlType> { ControlType.Button, ControlType.Calendar, ControlType.CheckBox, ControlType.ComboBox, ControlType.Custom, ControlType.DataGrid, ControlType.DataItem, ControlType.Document, ControlType.Edit, ControlType.Group, ControlType.Header, ControlType.HeaderItem, ControlType.Hyperlink, ControlType.Image, ControlType.List, ControlType.ListItem, ControlType.Menu, ControlType.MenuBar, ControlType.MenuItem, ControlType.Pane, ControlType.ProgressBar, ControlType.RadioButton, ControlType.ScrollBar, ControlType.Separator, ControlType.Slider, ControlType.Spinner, ControlType.SplitButton, ControlType.StatusBar, ControlType.Tab, ControlType.TabItem, ControlType.Table, ControlType.Text, ControlType.Thumb, ControlType.TitleBar, ControlType.ToolBar, ControlType.ToolTip, ControlType.Tree, ControlType.TreeItem, ControlType.Window }; foreach (var type in types) { var tag = type.ProgrammaticName.Substring(12); // ControlType. controlTypes.Add(new KeyValuePair<ControlType, string>(type, tag)); tagNames.Add(new KeyValuePair<string, ControlType>(tag, type)); } } public IElement FocusedElement { get { // AutomationElement.FocusedElement may temporarily return null. var stopwatch = new Stopwatch(); stopwatch.Start(); AutomationElement element = null; do { element = AutomationElement.FocusedElement; } while (element == null && stopwatch.ElapsedMilliseconds <= 3000); if (element == null) { throw new WinAppDriverException("There is no focused element available."); } return this.elementFactory.GetElement(element); } } public void SetElementFactory(IElementFactory elementFactory) { this.elementFactory = elementFactory; } public AutomationElement GetFocusedWindowOrRoot() { var walker = TreeWalker.ContentViewWalker; var node = this.FocusedElement.AutomationElement; var parent = node; while (parent != AutomationElement.RootElement) { node = parent; parent = walker.GetParent(node); } return node; } public ISet<AutomationElement> GetTopLevelWindows() { var windows = new HashSet<AutomationElement>(); var walker = TreeWalker.ControlViewWalker; var child = walker.GetFirstChild(AutomationElement.RootElement); while (child != null) { windows.Add(child); child = walker.GetNextSibling(child); } return windows; } public IntPtr ToNativeWindowHandle(AutomationElement element) { var handle = (int)element.GetCurrentPropertyValue( AutomationElement.NativeWindowHandleProperty, true); return new IntPtr(handle); } public AutomationElement FromNativeWindowHandle(IntPtr handle) { return AutomationElement.FromHandle(handle); } public string DumpXml(AutomationElement start) { return this.DumpXmlImpl(start, null); } public string DumpXml(AutomationElement start, out IList<AutomationElement> elements) { elements = new List<AutomationElement>(); return this.DumpXmlImpl(start, elements); } public ControlType FromTagName(string tag) { return tagNames[tag]; } public string ToTagName(ControlType type) { return controlTypes[type]; } public AutomationElement FindFirstByXPath(AutomationElement start, string xpath) { IList<AutomationElement> nodes; string xml = this.DumpXml(start, out nodes); var doc = new XPathDocument(new StringReader(xml)); XPathNavigator node = doc.CreateNavigator().SelectSingleNode(xpath); if (node == null) { return null; } else { var index = int.Parse(node.GetAttribute("_index_", string.Empty)); return nodes[index]; } } public IList<AutomationElement> FindAllByXPath(AutomationElement start, string xpath) { IList<AutomationElement> elements; string xml = this.DumpXml(start, out elements); var doc = new XPathDocument(new StringReader(xml)); XPathNodeIterator nodes = doc.CreateNavigator().Select(xpath); var results = new List<AutomationElement>(); foreach (XPathNavigator node in nodes) { var index = int.Parse(node.GetAttribute("_index_", string.Empty)); results.Add(elements[index]); } return results; } public IElement GetScrollableContainer(IElement element) { logger.Debug("Trying to find the scrollable container; id = [{0}], name = [{1}].", element.ID, element.Name); var walker = TreeWalker.ContentViewWalker; AutomationElement node = element.AutomationElement; while (node != AutomationElement.RootElement) { node = walker.GetParent(node); object pattern = null; if (node.TryGetCurrentPattern(ScrollPattern.Pattern, out pattern)) { var container = this.elementFactory.GetElement(node); logger.Debug("The container is found; id = [{0}], name = [{1}].", container.ID, element.Name); return container; } } logger.Debug("The container is NOT found."); return null; } private string DumpXmlImpl(AutomationElement start, IList<AutomationElement> elements) { var stringWriter = new StringWriter(); XmlWriter writer = new XmlTextWriter(stringWriter); writer.WriteStartDocument(); writer.WriteStartElement("WinAppDriver"); this.WalkTree(start, TreeWalker.ControlViewWalker, writer, elements); writer.WriteEndDocument(); return stringWriter.ToString(); } private void WalkTree(AutomationElement parent, TreeWalker walker, XmlWriter writer, IList<AutomationElement> elements) { var element = this.elementFactory.GetElement(parent); writer.WriteStartElement(element.TypeName); if (elements != null) { writer.WriteAttributeString("_index_", elements.Count.ToString()); elements.Add(parent); } writer.WriteAttributeString("id", element.ID); writer.WriteAttributeString("framework", element.UIFramework); writer.WriteAttributeString("name", element.Name); writer.WriteAttributeString("value", element.Value); writer.WriteAttributeString("class", element.ClassName); writer.WriteAttributeString("help", element.Help); writer.WriteAttributeString("visible", element.Visible ? "true" : "false"); writer.WriteAttributeString("enabled", element.Enabled ? "true" : "false"); writer.WriteAttributeString("focusable", element.Focusable ? "true" : "false"); writer.WriteAttributeString("focused", element.Focused ? "true" : "false"); writer.WriteAttributeString("selected", element.Selected ? "true" : "false"); writer.WriteAttributeString("protected", element.Protected ? "true" : "false"); writer.WriteAttributeString("scrollable", element.Scrollable ? "true" : "false"); writer.WriteAttributeString("handle", element.Handle.ToString()); writer.WriteAttributeString("x", element.X.ToString()); writer.WriteAttributeString("y", element.Y.ToString()); writer.WriteAttributeString("width", element.Width.ToString()); writer.WriteAttributeString("height", element.Height.ToString()); writer.WriteAttributeString( "bounds", string.Format("[{0},{1}][{2},{3}]", element.X, element.Y, element.Width, element.Height)); var node = walker.GetFirstChild(parent); var children = new List<AutomationElement>(); while (node != null) { this.WalkTree(node, walker, writer, elements); children.Add(node); node = walker.GetNextSibling(node); // GetNextSibling may recursively return the first child again. if (node != null && children.Contains(node)) { logger.Warn("Next sibling node causes a loop. STOP!"); node = null; break; } } writer.WriteEndElement(); } private bool IsElementSelected(AutomationElement element) { object pattern; if (element.TryGetCurrentPattern(TogglePattern.Pattern, out pattern)) { var state = ((TogglePattern)pattern).Current.ToggleState; return state != ToggleState.Off; } else { return false; } } } }
using System; using System.Collections.Generic; namespace PizzaBox.Data.Entities { public partial class Order { public Order() { Pizza = new HashSet<Pizza>(); } public int OrderId { get; set; } public int LocId { get; set; } public int UserId { get; set; } public virtual Location Loc { get; set; } public virtual User User { get; set; } public virtual ICollection<Pizza> Pizza { get; set; } } }
using System; using Xunit; namespace NStandard.Test { public class DateTimeExTests { [Fact] public void TotalYearDiffTest() { static void InnerTest(DateTime start, DateTime end, double diff) { Assert.Equal(diff, DateTimeEx.TotalYears(start, end)); Assert.Equal(end, start.AddTotalYears(diff)); } InnerTest(new DateTime(2020, 2, 1), new DateTime(2020, 3, 1), 29d / 366); InnerTest(new DateTime(2020, 2, 1), new DateTime(2020, 3, 15), 43d / 366); InnerTest(new DateTime(2020, 2, 2, 15, 0, 0), new DateTime(2020, 3, 2, 12, 0, 0), (29d * 24 - 3d) / (366 * 24)); InnerTest(new DateTime(2020, 2, 2, 15, 0, 0), new DateTime(2020, 3, 2, 18, 0, 0), (29d * 24 + 3d) / (366 * 24)); InnerTest(new DateTime(2020, 3, 1), new DateTime(2020, 2, 1), -29d / 366); InnerTest(new DateTime(2020, 3, 15), new DateTime(2020, 2, 1), -43d / 366); InnerTest(new DateTime(2020, 3, 2, 12, 0, 0), new DateTime(2020, 2, 2, 15, 0, 0), -(29d * 24 - 3d) / (366 * 24)); InnerTest(new DateTime(2020, 3, 2, 18, 0, 0), new DateTime(2020, 2, 2, 15, 0, 0), -(29d * 24 + 3d) / (366 * 24)); // Special Test InnerTest(new DateTime(2000, 7, 15), new DateTime(2000, 8, 16), 32d / 365); InnerTest(new DateTime(2000, 8, 16), new DateTime(2000, 7, 15), -32d / 366); } [Fact] public void TotalMonthDiffTest() { static void InnerTest(DateTime start, DateTime end, double diff) { Assert.Equal(diff, DateTimeEx.TotalMonths(start, end)); Assert.Equal(end, start.AddTotalMonths(diff).ToFixed()); } InnerTest(new DateTime(2020, 2, 1), new DateTime(2020, 3, 1), 1d); InnerTest(new DateTime(2020, 2, 1), new DateTime(2020, 3, 15), 1d + 14d / 31); InnerTest(new DateTime(2020, 2, 2, 15, 0, 0), new DateTime(2020, 3, 2, 12, 0, 0), 1d - 3d / (29 * 24)); InnerTest(new DateTime(2020, 2, 2, 15, 0, 0), new DateTime(2020, 3, 2, 18, 0, 0), 1d + 3d / (31 * 24)); InnerTest(new DateTime(2020, 3, 1), new DateTime(2020, 2, 1), -1d); InnerTest(new DateTime(2020, 3, 15), new DateTime(2020, 2, 1), -(1d + 14d / 31)); InnerTest(new DateTime(2020, 3, 2, 12, 0, 0), new DateTime(2020, 2, 2, 15, 0, 0), -(1d - 3d / (29 * 24))); InnerTest(new DateTime(2020, 3, 2, 18, 0, 0), new DateTime(2020, 2, 2, 15, 0, 0), -(1d + 3d / (31 * 24))); // Special Test InnerTest(new DateTime(2000, 7, 15), new DateTime(2000, 8, 16), 1d + 1d / 31); InnerTest(new DateTime(2000, 8, 16), new DateTime(2000, 7, 15), -(1d + 1d / 30)); } [Fact] public void TestUnixTimestamp() { var dt = new DateTime(1970, 1, 1, 16, 0, 0, DateTimeKind.Utc); Assert.Equal(57600, dt.ToUnixTimeSeconds()); Assert.Equal(57600000, dt.ToUnixTimeMilliseconds()); Assert.Equal(dt, DateTimeEx.FromUnixTimeSeconds(57600)); Assert.Equal(dt, DateTimeEx.FromUnixTimeMilliseconds(57600_000)); Assert.Equal(new DateTime(2018, 10, 31, 15, 55, 17), DateTimeEx.FromUnixTimeSeconds(1540972517).ToLocalTime()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class ProblemGoogle2 : GoogleBase { public override string ProblemName { get { return "Google: Revenge of the Pancakes"; } } public override string GetAnswer() { Solve(); DownloadOutputFile(); return "done"; } private void Solve() { foreach (string stack in _tests) { FindMinimumFlipCount(stack); } } private void FindMinimumFlipCount(string stack) { int flipCount = 0; for (int index = 1; index < stack.Length; index++) { if (stack.Substring(index, 1) != stack.Substring(index - 1, 1)) { flipCount++; } } if (stack.Substring(stack.Length - 1, 1) == "-") { flipCount++; } _results.Add(flipCount.ToString()); } } }
using System; using System.Data.SqlClient; namespace _03.GetMinionNames { class GetMinionNames { static void Main() { int vilianID = Convert.ToInt32(Console.ReadLine().Trim()); string connStr = @"Server=.\SQLEXPRESS;database=MinionsDB;Trusted_Connection=true;"; string vilianName = GetVilianName(vilianID, connStr); if (vilianName == "null") { Console.WriteLine($"No villain with ID {vilianID} exists in the database."); return; } Console.WriteLine($"Villain: {vilianName}"); using (SqlConnection connection = new SqlConnection(connStr)) { SqlCommand sqlCommand = new SqlCommand(); string sql = "SELECT m.[Name], m.Age FROM Minions AS m JOIN VillainsMinions AS vm ON vm.MinionID = m.id AND vm.VillainID = @VillainID;"; sqlCommand.CommandText = sql; sqlCommand.Connection = connection; sqlCommand.Parameters.AddWithValue("@VillainID", vilianID); connection.Open(); using (SqlDataReader reader = sqlCommand.ExecuteReader()) { int counter = 1; bool isRecord = false; while (reader.Read()) { Console.Write($"{counter}. "); for (int i = 0; i < reader.FieldCount; i++) { Console.Write($"{reader[i]} "); isRecord = true; } Console.WriteLine(); counter++; } if (!isRecord) { Console.WriteLine("<no minions>"); } } } } private static string GetVilianName(int vilianId, string connStr) { var result = "null"; using (var connection = new SqlConnection(connStr)) { SqlCommand sqlCommand = new SqlCommand(); string sql = "SELECT v.[name] FROM Villains AS v WHERE v.id = @VilianID; "; sqlCommand.CommandText = sql; sqlCommand.Connection = connection; sqlCommand.Parameters.AddWithValue("@VilianID", vilianId); try { connection.Open(); result = sqlCommand.ExecuteScalar().ToString(); } catch (Exception ex) { //Console.WriteLine(ex.Message); } } return result.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace PayRoll { public partial class LeaveReport: System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["luname"] != null && Session["lpass"] != null) { Data(); } else { Response.Redirect("Login.aspx"); } } } void Data() { con.Open(); SqlDataAdapter da = new SqlDataAdapter("select a.Name,b.* from Employee as a inner join ApplyLeave as b on a.EmpId=b.EmpId", con); DataSet ds = new DataSet(); da.Fill(ds); gdvleave.DataSource = ds; gdvleave.DataBind(); } protected void btnapproval_Click(object sender, EventArgs e) { Button btn = (Button)sender; GridViewRow row = (GridViewRow)btn.NamingContainer; Label id = (Label)row.FindControl("lbllid"); int ids = Convert.ToInt32(id.Text); string s = "Success"; con.Open(); SqlCommand cmd = new SqlCommand("update ApplyLeave set ApprovalStatus='" + s + "' where LeaveId='" + ids + "'", con); int i = cmd.ExecuteNonQuery(); if (i > 0) { Response.Redirect("Dashboard.aspx"); } else { Response.Redirect("LeaveReport.aspx"); } con.Close(); } } }
using System.Collections.ObjectModel; using GeoAPI.Geometries; using NUnit.Framework; using SharpMap.Converters.WellKnownText; using SharpMap.Data; using SharpMap.Data.Providers; using SharpMap.Layers; namespace SharpMap.Tests.Data.Providers { [TestFixture] public class GeometryProviderTest { [Test] public void SetAttributes() { Collection<IGeometry> geometries = new Collection<IGeometry>(); geometries.Add(GeometryFromWKT.Parse("LINESTRING (20 20, 20 30, 30 30, 30 20, 40 20)")); geometries.Add(GeometryFromWKT.Parse("LINESTRING (21 21, 21 31, 31 31, 31 21, 41 21)")); geometries.Add(GeometryFromWKT.Parse("LINESTRING (22 22, 22 32, 32 32, 32 22, 42 22)")); DataTableFeatureProvider dataTableFeatureFeatureProvider = new DataTableFeatureProvider(geometries); VectorLayer vectorLayer = new VectorLayer(); vectorLayer.DataSource = dataTableFeatureFeatureProvider; // add column FeatureDataRow r = (FeatureDataRow)vectorLayer.DataSource.GetFeature(0); r.Table.Columns.Add("Value", typeof(float)); // set value attribute for (int i = 0; i < dataTableFeatureFeatureProvider.GetFeatureCount(); i++) { r = (FeatureDataRow)dataTableFeatureFeatureProvider.GetFeature(i); r[0] = i; } FeatureDataRow row = (FeatureDataRow)dataTableFeatureFeatureProvider.GetFeature(2); Assert.AreEqual(2, row[0], "Attribute 0 in the second feature must be set to 2"); } [Test] public void InitializationTest() { DataTableFeatureProvider gp = new DataTableFeatureProvider("LINESTRING(20 20,40 40)"); Assert.AreEqual(1, gp.Geometries.Count); } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Instancer of type `Vector2`. Inherits from `AtomEventInstancer&lt;Vector2, Vector2Event&gt;`. /// </summary> [EditorIcon("atom-icon-sign-blue")] [AddComponentMenu("Unity Atoms/Event Instancers/Vector2 Event Instancer")] public class Vector2EventInstancer : AtomEventInstancer<Vector2, Vector2Event> { } }
// This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.UIManager UIManager; private global::Gtk.Action ArchivoAction; private global::Gtk.Action GuardarAction; private global::Gtk.Action GuardarComoAction; private global::Gtk.Action AbrirAction; private global::Gtk.Action SalirAction; private global::Gtk.Action EditarAction; private global::Gtk.Action CopiarAction; private global::Gtk.Action CortarAction; private global::Gtk.Action PegarAction; private global::Gtk.Action BorrarAction; private global::Gtk.Action FuenteAction; private global::Gtk.Action newAction; private global::Gtk.Action openAction; private global::Gtk.Action saveAction; private global::Gtk.Action saveAsAction; private global::Gtk.Action closeAction2; private global::Gtk.Action closeAction; private global::Gtk.Action deleteAction; private global::Gtk.Action removeAction; private global::Gtk.Action dialogErrorAction; private global::Gtk.Action quitAction; private global::Gtk.Action closeAction1; private global::Gtk.Action stopAction; private global::Gtk.Action findAction; private global::Gtk.Action findAndReplaceAction; private global::Gtk.Action indentAction; private global::Gtk.Action mediaPlayAction; private global::Gtk.Action RunAction; private global::Gtk.Action CompilarAction; private global::Gtk.Action CompilarYCorrerAction; private global::Gtk.Action mediaPlayAction1; private global::Gtk.VBox vbox1; private global::Gtk.VBox vbox2; private global::Gtk.MenuBar menubar1; private global::Gtk.HBox hbox18; private global::Gtk.Toolbar toolbar1; private global::Gtk.VPaned vpaned1; private global::Gtk.HPaned hpaned3; private global::Gtk.HBox hbox19; private global::Gtk.Notebook NoteBook; private global::Gtk.Notebook notebook3; private global::Gtk.ScrolledWindow GtkScrolledWindow1; private global::Gtk.TextView TreeLexico; private global::Gtk.Label label9; private global::Gtk.ScrolledWindow GtkScrolledWindow2; private global::Gtk.TextView TreeSinta; private global::Gtk.Label label12; private global::Gtk.ScrolledWindow GtkScrolledWindow3; private global::Gtk.TextView TreeSema; private global::Gtk.Label label13; private global::Gtk.ScrolledWindow GtkScrolledWindow6; private global::Gtk.TextView Hashtable; private global::Gtk.Label label1; private global::Gtk.VBox vbox3; private global::Gtk.ScrolledWindow GtkScrolledWindow4; private global::Gtk.TextView Intermedio; private global::Gtk.Label label14; private global::Gtk.Notebook notebook6; private global::Gtk.ScrolledWindow GtkScrolledWindow; private global::Gtk.TreeView TreeErrores; private global::Gtk.Label label15; private global::Gtk.ScrolledWindow GtkScrolledWindow5; private global::Gtk.TextView TreeResultados; private global::Gtk.Label label16; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.UIManager = new global::Gtk.UIManager (); global::Gtk.ActionGroup w1 = new global::Gtk.ActionGroup ("Default"); this.ArchivoAction = new global::Gtk.Action ("ArchivoAction", global::Mono.Unix.Catalog.GetString ("Archivo"), null, null); this.ArchivoAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Archivo"); w1.Add (this.ArchivoAction, null); this.GuardarAction = new global::Gtk.Action ("GuardarAction", global::Mono.Unix.Catalog.GetString ("Guardar"), null, null); this.GuardarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Guardar"); w1.Add (this.GuardarAction, null); this.GuardarComoAction = new global::Gtk.Action ("GuardarComoAction", global::Mono.Unix.Catalog.GetString ("Guardar Como"), null, null); this.GuardarComoAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Guardar Como"); w1.Add (this.GuardarComoAction, null); this.AbrirAction = new global::Gtk.Action ("AbrirAction", global::Mono.Unix.Catalog.GetString ("Abrir"), null, null); this.AbrirAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Abrir"); w1.Add (this.AbrirAction, null); this.SalirAction = new global::Gtk.Action ("SalirAction", global::Mono.Unix.Catalog.GetString ("Salir"), null, null); this.SalirAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Salir"); w1.Add (this.SalirAction, null); this.EditarAction = new global::Gtk.Action ("EditarAction", global::Mono.Unix.Catalog.GetString ("Editar"), null, null); this.EditarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Editar"); w1.Add (this.EditarAction, null); this.CopiarAction = new global::Gtk.Action ("CopiarAction", global::Mono.Unix.Catalog.GetString ("Copiar"), null, null); this.CopiarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Copiar"); w1.Add (this.CopiarAction, null); this.CortarAction = new global::Gtk.Action ("CortarAction", global::Mono.Unix.Catalog.GetString ("Cortar"), null, null); this.CortarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Cortar"); w1.Add (this.CortarAction, null); this.PegarAction = new global::Gtk.Action ("PegarAction", global::Mono.Unix.Catalog.GetString ("Pegar"), null, null); this.PegarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Pegar"); w1.Add (this.PegarAction, null); this.BorrarAction = new global::Gtk.Action ("BorrarAction", global::Mono.Unix.Catalog.GetString ("Borrar"), null, null); this.BorrarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Borrar"); w1.Add (this.BorrarAction, null); this.FuenteAction = new global::Gtk.Action ("FuenteAction", global::Mono.Unix.Catalog.GetString ("Fuente"), null, null); this.FuenteAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Fuente"); w1.Add (this.FuenteAction, null); this.newAction = new global::Gtk.Action ("newAction", null, null, "gtk-new"); w1.Add (this.newAction, null); this.openAction = new global::Gtk.Action ("openAction", null, null, "gtk-open"); w1.Add (this.openAction, null); this.saveAction = new global::Gtk.Action ("saveAction", null, null, "gtk-save"); w1.Add (this.saveAction, null); this.saveAsAction = new global::Gtk.Action ("saveAsAction", null, null, "gtk-save-as"); w1.Add (this.saveAsAction, null); this.closeAction2 = new global::Gtk.Action ("closeAction2", null, null, "gtk-close"); w1.Add (this.closeAction2, null); this.closeAction = new global::Gtk.Action ("closeAction", null, null, "gtk-close"); w1.Add (this.closeAction, null); this.deleteAction = new global::Gtk.Action ("deleteAction", null, null, "gtk-delete"); w1.Add (this.deleteAction, null); this.removeAction = new global::Gtk.Action ("removeAction", null, null, "gtk-remove"); w1.Add (this.removeAction, null); this.dialogErrorAction = new global::Gtk.Action ("dialogErrorAction", null, null, "gtk-dialog-error"); w1.Add (this.dialogErrorAction, null); this.quitAction = new global::Gtk.Action ("quitAction", null, null, "gtk-quit"); w1.Add (this.quitAction, null); this.closeAction1 = new global::Gtk.Action ("closeAction1", null, null, "gtk-close"); w1.Add (this.closeAction1, null); this.stopAction = new global::Gtk.Action ("stopAction", null, null, "gtk-stop"); w1.Add (this.stopAction, null); this.findAction = new global::Gtk.Action ("findAction", null, null, "gtk-find"); w1.Add (this.findAction, null); this.findAndReplaceAction = new global::Gtk.Action ("findAndReplaceAction", null, null, "gtk-find-and-replace"); w1.Add (this.findAndReplaceAction, null); this.indentAction = new global::Gtk.Action ("indentAction", null, null, "gtk-indent"); w1.Add (this.indentAction, null); this.mediaPlayAction = new global::Gtk.Action ("mediaPlayAction", null, null, "gtk-media-play"); w1.Add (this.mediaPlayAction, null); this.RunAction = new global::Gtk.Action ("RunAction", global::Mono.Unix.Catalog.GetString ("Run"), null, null); this.RunAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Run"); w1.Add (this.RunAction, null); this.CompilarAction = new global::Gtk.Action ("CompilarAction", global::Mono.Unix.Catalog.GetString ("Compilar"), null, null); this.CompilarAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Compilar"); w1.Add (this.CompilarAction, null); this.CompilarYCorrerAction = new global::Gtk.Action ("CompilarYCorrerAction", global::Mono.Unix.Catalog.GetString ("Compilar y correr"), null, null); this.CompilarYCorrerAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("Compilar y correr"); w1.Add (this.CompilarYCorrerAction, null); this.mediaPlayAction1 = new global::Gtk.Action ("mediaPlayAction1", null, null, "gtk-media-play"); w1.Add (this.mediaPlayAction1, null); this.UIManager.InsertActionGroup (w1, 0); this.AddAccelGroup (this.UIManager.AccelGroup); this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("Compilador M&M ++**--"); this.Icon = global::Stetic.IconLoader.LoadIcon (this, "stock_smiley-22", global::Gtk.IconSize.Menu); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); this.Gravity = ((global::Gdk.Gravity)(5)); // Container child MainWindow.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; // Container child vbox2.Gtk.Box+BoxChild this.UIManager.AddUiFromString ("<ui><menubar name='menubar1'><menu name='ArchivoAction' action='ArchivoAction'><menuitem name='GuardarAction' action='GuardarAction'/><menuitem name='GuardarComoAction' action='GuardarComoAction'/><menuitem name='AbrirAction' action='AbrirAction'/><menuitem name='SalirAction' action='SalirAction'/></menu><menu name='EditarAction' action='EditarAction'><menuitem name='CopiarAction' action='CopiarAction'/><menuitem name='CortarAction' action='CortarAction'/><menuitem name='PegarAction' action='PegarAction'/><menuitem name='BorrarAction' action='BorrarAction'/><menuitem name='FuenteAction' action='FuenteAction'/></menu><menu name='RunAction' action='RunAction'><menuitem name='CompilarAction' action='CompilarAction'/><menuitem name='mediaPlayAction1' action='mediaPlayAction1'/></menu></menubar></ui>"); this.menubar1 = ((global::Gtk.MenuBar)(this.UIManager.GetWidget ("/menubar1"))); this.menubar1.Name = "menubar1"; this.vbox2.Add (this.menubar1); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.menubar1])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.hbox18 = new global::Gtk.HBox (); this.hbox18.Name = "hbox18"; this.hbox18.Spacing = 6; // Container child hbox18.Gtk.Box+BoxChild this.UIManager.AddUiFromString ("<ui><toolbar name='toolbar1'><toolitem name='newAction' action='newAction'/><toolitem name='openAction' action='openAction'/><toolitem name='saveAction' action='saveAction'/><toolitem name='closeAction2' action='closeAction2'/><toolitem name='mediaPlayAction' action='mediaPlayAction'/></toolbar></ui>"); this.toolbar1 = ((global::Gtk.Toolbar)(this.UIManager.GetWidget ("/toolbar1"))); this.toolbar1.Name = "toolbar1"; this.toolbar1.ShowArrow = false; this.hbox18.Add (this.toolbar1); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox18 [this.toolbar1])); w3.Position = 0; this.vbox2.Add (this.hbox18); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.hbox18])); w4.Position = 1; w4.Expand = false; w4.Fill = false; this.vbox1.Add (this.vbox2); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.vbox2])); w5.Position = 0; w5.Expand = false; w5.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.vpaned1 = new global::Gtk.VPaned (); this.vpaned1.CanFocus = true; this.vpaned1.Name = "vpaned1"; this.vpaned1.Position = 410; // Container child vpaned1.Gtk.Paned+PanedChild this.hpaned3 = new global::Gtk.HPaned (); this.hpaned3.CanFocus = true; this.hpaned3.Name = "hpaned3"; this.hpaned3.Position = 1056; // Container child hpaned3.Gtk.Paned+PanedChild this.hbox19 = new global::Gtk.HBox (); this.hbox19.Name = "hbox19"; this.hbox19.Spacing = 6; // Container child hbox19.Gtk.Box+BoxChild this.NoteBook = new global::Gtk.Notebook (); this.NoteBook.CanFocus = true; this.NoteBook.Name = "NoteBook"; this.NoteBook.CurrentPage = 0; this.hbox19.Add (this.NoteBook); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.hbox19 [this.NoteBook])); w6.Position = 0; this.hpaned3.Add (this.hbox19); global::Gtk.Paned.PanedChild w7 = ((global::Gtk.Paned.PanedChild)(this.hpaned3 [this.hbox19])); w7.Resize = false; // Container child hpaned3.Gtk.Paned+PanedChild this.notebook3 = new global::Gtk.Notebook (); this.notebook3.CanFocus = true; this.notebook3.Name = "notebook3"; this.notebook3.CurrentPage = 4; // Container child notebook3.Gtk.Notebook+NotebookChild this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow1.Name = "GtkScrolledWindow1"; this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow1.Gtk.Container+ContainerChild this.TreeLexico = new global::Gtk.TextView (); this.TreeLexico.CanFocus = true; this.TreeLexico.Name = "TreeLexico"; this.TreeLexico.Editable = false; this.TreeLexico.CursorVisible = false; this.GtkScrolledWindow1.Add (this.TreeLexico); this.notebook3.Add (this.GtkScrolledWindow1); // Notebook tab this.label9 = new global::Gtk.Label (); this.label9.Name = "label9"; this.label9.LabelProp = global::Mono.Unix.Catalog.GetString ("Lexico"); this.notebook3.SetTabLabel (this.GtkScrolledWindow1, this.label9); this.label9.ShowAll (); // Container child notebook3.Gtk.Notebook+NotebookChild this.GtkScrolledWindow2 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow2.Name = "GtkScrolledWindow2"; this.GtkScrolledWindow2.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow2.Gtk.Container+ContainerChild this.TreeSinta = new global::Gtk.TextView (); this.TreeSinta.CanFocus = true; this.TreeSinta.Name = "TreeSinta"; this.TreeSinta.Editable = false; this.TreeSinta.CursorVisible = false; this.GtkScrolledWindow2.Add (this.TreeSinta); this.notebook3.Add (this.GtkScrolledWindow2); global::Gtk.Notebook.NotebookChild w11 = ((global::Gtk.Notebook.NotebookChild)(this.notebook3 [this.GtkScrolledWindow2])); w11.Position = 1; // Notebook tab this.label12 = new global::Gtk.Label (); this.label12.Name = "label12"; this.label12.LabelProp = global::Mono.Unix.Catalog.GetString ("Sintactico"); this.notebook3.SetTabLabel (this.GtkScrolledWindow2, this.label12); this.label12.ShowAll (); // Container child notebook3.Gtk.Notebook+NotebookChild this.GtkScrolledWindow3 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow3.Name = "GtkScrolledWindow3"; this.GtkScrolledWindow3.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow3.Gtk.Container+ContainerChild this.TreeSema = new global::Gtk.TextView (); this.TreeSema.CanFocus = true; this.TreeSema.Name = "TreeSema"; this.TreeSema.Editable = false; this.TreeSema.CursorVisible = false; this.GtkScrolledWindow3.Add (this.TreeSema); this.notebook3.Add (this.GtkScrolledWindow3); global::Gtk.Notebook.NotebookChild w13 = ((global::Gtk.Notebook.NotebookChild)(this.notebook3 [this.GtkScrolledWindow3])); w13.Position = 2; // Notebook tab this.label13 = new global::Gtk.Label (); this.label13.Name = "label13"; this.label13.LabelProp = global::Mono.Unix.Catalog.GetString ("Semantico"); this.notebook3.SetTabLabel (this.GtkScrolledWindow3, this.label13); this.label13.ShowAll (); // Container child notebook3.Gtk.Notebook+NotebookChild this.GtkScrolledWindow6 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow6.Name = "GtkScrolledWindow6"; this.GtkScrolledWindow6.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow6.Gtk.Container+ContainerChild this.Hashtable = new global::Gtk.TextView (); this.Hashtable.CanFocus = true; this.Hashtable.Name = "Hashtable"; this.GtkScrolledWindow6.Add (this.Hashtable); this.notebook3.Add (this.GtkScrolledWindow6); global::Gtk.Notebook.NotebookChild w15 = ((global::Gtk.Notebook.NotebookChild)(this.notebook3 [this.GtkScrolledWindow6])); w15.Position = 3; // Notebook tab this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Hashtable"); this.notebook3.SetTabLabel (this.GtkScrolledWindow6, this.label1); this.label1.ShowAll (); // Container child notebook3.Gtk.Notebook+NotebookChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.GtkScrolledWindow4 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow4.Name = "GtkScrolledWindow4"; this.GtkScrolledWindow4.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow4.Gtk.Container+ContainerChild this.Intermedio = new global::Gtk.TextView (); this.Intermedio.CanFocus = true; this.Intermedio.Name = "Intermedio"; this.Intermedio.Editable = false; this.GtkScrolledWindow4.Add (this.Intermedio); this.vbox3.Add (this.GtkScrolledWindow4); global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.GtkScrolledWindow4])); w17.Position = 1; this.notebook3.Add (this.vbox3); global::Gtk.Notebook.NotebookChild w18 = ((global::Gtk.Notebook.NotebookChild)(this.notebook3 [this.vbox3])); w18.Position = 4; // Notebook tab this.label14 = new global::Gtk.Label (); this.label14.Name = "label14"; this.label14.LabelProp = global::Mono.Unix.Catalog.GetString ("Cod Intermedio"); this.notebook3.SetTabLabel (this.vbox3, this.label14); this.label14.ShowAll (); this.hpaned3.Add (this.notebook3); this.vpaned1.Add (this.hpaned3); global::Gtk.Paned.PanedChild w20 = ((global::Gtk.Paned.PanedChild)(this.vpaned1 [this.hpaned3])); w20.Resize = false; // Container child vpaned1.Gtk.Paned+PanedChild this.notebook6 = new global::Gtk.Notebook (); this.notebook6.CanFocus = true; this.notebook6.Name = "notebook6"; this.notebook6.CurrentPage = 0; // Container child notebook6.Gtk.Notebook+NotebookChild this.GtkScrolledWindow = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow.Name = "GtkScrolledWindow"; this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow.Gtk.Container+ContainerChild this.TreeErrores = new global::Gtk.TreeView (); this.TreeErrores.CanFocus = true; this.TreeErrores.Name = "TreeErrores"; this.GtkScrolledWindow.Add (this.TreeErrores); this.notebook6.Add (this.GtkScrolledWindow); // Notebook tab this.label15 = new global::Gtk.Label (); this.label15.Name = "label15"; this.label15.LabelProp = global::Mono.Unix.Catalog.GetString ("Errores"); this.notebook6.SetTabLabel (this.GtkScrolledWindow, this.label15); this.label15.ShowAll (); // Container child notebook6.Gtk.Notebook+NotebookChild this.GtkScrolledWindow5 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow5.Name = "GtkScrolledWindow5"; this.GtkScrolledWindow5.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow5.Gtk.Container+ContainerChild this.TreeResultados = new global::Gtk.TextView (); this.TreeResultados.CanFocus = true; this.TreeResultados.Name = "TreeResultados"; this.TreeResultados.Editable = false; this.TreeResultados.CursorVisible = false; this.GtkScrolledWindow5.Add (this.TreeResultados); this.notebook6.Add (this.GtkScrolledWindow5); global::Gtk.Notebook.NotebookChild w24 = ((global::Gtk.Notebook.NotebookChild)(this.notebook6 [this.GtkScrolledWindow5])); w24.Position = 1; // Notebook tab this.label16 = new global::Gtk.Label (); this.label16.Name = "label16"; this.label16.LabelProp = global::Mono.Unix.Catalog.GetString ("Resultados"); this.notebook6.SetTabLabel (this.GtkScrolledWindow5, this.label16); this.label16.ShowAll (); this.vpaned1.Add (this.notebook6); this.vbox1.Add (this.vpaned1); global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.vpaned1])); w26.Position = 1; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 1544; this.DefaultHeight = 771; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.GuardarAction.Activated += new global::System.EventHandler (this.OnGuardarActionActivated); this.GuardarComoAction.Activated += new global::System.EventHandler (this.OnGuardarComoActionActivated); this.AbrirAction.Activated += new global::System.EventHandler (this.OnAbrirActionActivated); this.SalirAction.Activated += new global::System.EventHandler (this.OnSalirActionActivated); this.CopiarAction.Activated += new global::System.EventHandler (this.OnCopiarActionActivated); this.CortarAction.Activated += new global::System.EventHandler (this.OnCortarActionActivated); this.PegarAction.Activated += new global::System.EventHandler (this.OnPegarActionActivated); this.BorrarAction.Activated += new global::System.EventHandler (this.OnBorrarActionActivated); this.FuenteAction.Activated += new global::System.EventHandler (this.OnFuenteActionActivated); this.newAction.Activated += new global::System.EventHandler (this.OnNewActionActivated); this.openAction.Activated += new global::System.EventHandler (this.OnOpenActionActivated); this.saveAction.Activated += new global::System.EventHandler (this.OnSaveActionActivated); this.saveAsAction.Activated += new global::System.EventHandler (this.OnSaveAsActionActivated); this.closeAction2.Activated += new global::System.EventHandler (this.OnNoActionActivated); this.stopAction.Activated += new global::System.EventHandler (this.OnDialogErrorAction1Activated); this.findAndReplaceAction.Activated += new global::System.EventHandler (this.OnFindAndReplaceActionActivated); this.indentAction.Activated += new global::System.EventHandler (this.OnIndentActionActivated); this.mediaPlayAction.Activated += new global::System.EventHandler (this.OnExecuteActionActivated); } }
using System.Collections.Generic; namespace SortAlgorithm { /// <summary> /// 【插入排序--希尔排序】 /// 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序; /// 随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。 /// 不稳定 时间复杂度 O(n^(1.3—2)) 空间复杂度 O(1) /// </summary> public class ShellSort : SortBase { public override void Sort(List<int> nums) { int count = nums.Count; for (int dk = count / 2; dk >= 1; dk /= 2) { // 增量为dk时,需要对dk个分组进行直接插入排序。 for(int groupIndex = 0; groupIndex < dk; groupIndex++) ShellInsertSort(nums, dk, groupIndex); } } // 使用直接插入排序做分组的排序 private void ShellInsertSort(List<int> nums, int dk, int groupIndex) { int count = nums.Count; for(int i = groupIndex + dk; i < count; i += dk) { if(nums[i] < nums[i - dk]) { int temp = nums[i]; int j = i - dk; while(j >= 0 && nums[j] > temp) { nums[j + dk] = nums[j]; j -= dk; } nums[j + dk] = temp; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UniRx; using XinputGamePad; public class LogSampleUniRx : MonoBehaviour { public XinputGamePadListener GamePad; // Use this for initialization void Start () { GamePad.OnButtonPushed.Subscribe(key => { if(key == XinputKey.LEFT){ Debug.Log(key); } if(key == XinputKey.RIGHT){ Debug.Log(key); } if(key == XinputKey.UP){ Debug.Log(key); } if(key == XinputKey.DOWN){ Debug.Log(key); } if(key == XinputKey.A){ Debug.Log(key); } if(key == XinputKey.B){ Debug.Log(key); } if(key == XinputKey.X){ Debug.Log(key); } if(key == XinputKey.Y){ Debug.Log(key); } }); } void Update(){ Debug.LogFormat("RightStick : ({0} , {1})\n",GamePad.GetRightStick().x,GamePad.GetRightStick().y); Debug.LogFormat("LeftStick : ({0} , {1})\n",GamePad.GetLeftStick().x,GamePad.GetLeftStick().y); Debug.Log("TrigerRight : " + GamePad.GetTriger().Right + " TrigerLeft : " + GamePad.GetTriger().Left); } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using CIPMSBC; using System.Data.SqlClient; using Microsoft.Reporting.WebForms; public partial class ExcelExport2 : System.Web.UI.Page { private SrchCamperDetails _objCamperDet = new SrchCamperDetails(); private General _objGen = new General(); protected void Page_Load(object sender, EventArgs e) { // PopulateGrid(); RenderReport("23", "2009", "null"); } private void RenderReport(string FederationID, string CampYear, string PaymentID) { try { string strRpt = "/CIPMS_Reports/ViewDump"; string strReportServerURL = ConfigurationManager.AppSettings["ReportServerURL"]; string strParamValue = ""; //***************************** //Set general report properties //***************************** ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local; ReportViewer1.ServerReport.ReportServerUrl = new Uri(strReportServerURL); // Report Server URL ReportViewer1.ServerReport.ReportPath = strRpt; // Report Name //ReportViewer1.ShowParameterPrompts = false; //ReportViewer1.ShowDocumentMapButton = true; //ReportViewer1.ShowPrintButton = true; //************************* // Create report parameters //************************* //Report mode parameter ReportParameter reportFederationID = new ReportParameter(); reportFederationID.Name = "FederationID"; strParamValue = Session["FedId"].ToString(); reportFederationID.Values.Add(null); //Federation Name parameter ReportParameter reportFederation = new ReportParameter(); reportFederation.Name = "FederationName"; strParamValue = "xxxx"; reportFederation.Values.Add(strParamValue); // Set the report parameters for the report ReportViewer1.ServerReport.SetParameters( new ReportParameter[] { reportFederationID, reportFederation}); //convert to excel string mimeType; string encoding; string[] streams; string extension; Microsoft.Reporting.WebForms.Warning[] warnings; byte[] returnValue; returnValue = ReportViewer1.ServerReport.Render("Excel", null, out mimeType, out encoding, out extension, out streams, out warnings); Response.Buffer = true; Response.Clear(); Response.ContentType = mimeType; Response.AddHeader("content-disposition", "attachment ; filename=filename." + extension); Response.BinaryWrite(returnValue); Response.Flush(); Response.End(); } catch (Exception ex) { throw ex; } } //private void PopulateGrid() //{ // string Federation = "Federations: All"; // System.IO.StringWriter tw = new System.IO.StringWriter(); // System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); // CIPDataAccess dal = new CIPDataAccess(); // DataSet dsExport; // string FederationID = string.Empty; // try // { // FederationID = Session["FedId"].ToString(); // } // catch { }; // if (FederationID.Trim() == string.Empty) // { // dsExport = dal.getDataset("usp_GetViewDupm", null); // } // else // { // Federation = "Federation: " + Session["FedName"].ToString(); // SqlParameter[] param = new SqlParameter[1]; // param[0] = new SqlParameter("@FederationID", FederationID); // dsExport = dal.getDataset("[usp_GetViewDupm]", param); // } // string FileName = "CIPMS-Camper-Extract-" + String.Format("{0:M/d/yyyy}", DateTime.Now) + ".xls"; // Response.ContentType = "application/vnd.ms-excel"; // Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1255"); // Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName); // if (dsExport.Tables[0].Rows.Count == 0) // { // this.Controls.Remove(gvExport); // Response.Write("No matching records found."); // Response.End(); // } // else // { // gvExport.DataSource = dsExport; // gvExport.DataBind(); // hw.WriteLine("<table><tr><td><b><font size='3'>" + // "Campers Data Export" + // "</font></b></td></tr>"); // hw.WriteLine("<tr><td><font size='2'>" + Federation + // "</font></td></tr>"); // hw.WriteLine("<tr><td><font size='2'>" + // "Export Date: " + String.Format("{0:M/d/yyyy hh:mm tt}", DateTime.Now) + // "</font></td></tr></table>"); // form1.Controls.Clear(); // form1.Controls.Add(gvExport); // form1.RenderControl(hw); // //gvExport.RenderControl(hw); // this.EnableViewState = false; // Response.Write(tw.ToString()); // Response.End(); // } //} protected void gvWrkQ_SelectedIndexChanged(object sender, EventArgs e) { } protected void gvExport_DataBound(object sender, EventArgs e) { } protected void gvExport_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label mylabel = e.Row.FindControl("lblFJCID") as Label; mylabel.Text = "=TEXT(" + mylabel.Text + ",\"#\")"; } } }
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 WindowsFormsApp1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Add_Sotrudnik_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(Program.ConnectionString)) { string query = $"INSERT INTO [Sotrudnik] (Id_sot, Lastname, Firstname, Patronymic, Dolzhnost, Telephone, Id_kompl, Id_polz) VALUES ({new Random().Next(10010,10000000)},N'{LastName.Text}', N'{FirstName.Text}', N'{Patronymic.Text}', N'{Dolzhnost.Text}', {Telephone.Text}, 3, 4)"; try { con.Open(); SqlCommand sqlCommand = new SqlCommand(query, con); if (sqlCommand.ExecuteNonQuery() > 0) { MessageBox.Show( "Вставка произошла успешно", "Добавление", MessageBoxButtons.OK, MessageBoxIcon.Information ); } else { MessageBox.Show( "Что-то пошло не так...", "Добавление", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } catch { MessageBox.Show( "Что-то пошло не так..." + query, "Добавление", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } this.Close(); } private void Form2_Load(object sender, EventArgs e) { } } }
namespace ProgFrog.Interface.Data.Serialization { public interface IModelSerializer<T> { string Serialize(T model); T Deserialize(string str); } }
using AsyncInn.Models; using AsyncInn.Models.DTOs; using System.Collections.Generic; using System.Threading.Tasks; namespace AsyncInn.Data.Interfaces { public interface IAmenitiesRepository { //C: Create Task<Amenities> CreateAmenities(Amenities amenities); //R: Read Task<AmenityDTO> GetAmenitiesById(int Id); //U: Update Task<bool> UpdateAmenities(int Id, Amenities amenities); Task<AmenityDTO> SaveNewAmenity(Amenities amenities); //D: Delete Task<Amenities> DeleteAmenities(int Id); Task<IEnumerable<AmenityDTO>> GetAllRoomAmenities(); } }
using System; namespace claseExcepciones { class Program { static void Main(string[] args) { Console.Write("Ingrese un número por consola: "); int numero; try { numero = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Número ingresado correctamente!"); } catch (FormatException ex) { Console.WriteLine("No has ingresado un número"); numero = 0; }catch(OverflowException ex) { Console.WriteLine("El número que has ingresado es demasiado grande!"); numero = Int32.MaxValue; } catch (Exception ex) { Console.WriteLine("No se pudo generar la acción, por favor contacte al área correspondiente(CO-01)"); Console.WriteLine(ex.Message); numero = 0; } finally { Console.WriteLine("La ejecución de bloque try-catch ha terminado!"); } Console.WriteLine("El valor del número es: "+numero); } } }
using Crystal.Plot2D.Common; using System; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace Crystal.Plot2D.Charts { /// <summary> /// Adds to Plotter two crossed lines, bound to mouse cursor position, /// and two labels near axes with mouse position in its text. /// </summary> public partial class CursorCoordinateGraph : ContentGraph { /// <summary> /// Initializes a new instance of the <see cref="CursorCoordinateGraph"/> class. /// </summary> public CursorCoordinateGraph() { InitializeComponent(); } Vector blockShift = new(3, 3); #region Plotter protected override void OnPlotterAttached() { UIElement parent = (UIElement)Parent; parent.MouseMove += parent_MouseMove; parent.MouseEnter += Parent_MouseEnter; parent.MouseLeave += Parent_MouseLeave; UpdateVisibility(); UpdateUIRepresentation(); } protected override void OnPlotterDetaching() { UIElement parent = (UIElement)Parent; parent.MouseMove -= parent_MouseMove; parent.MouseEnter -= Parent_MouseEnter; parent.MouseLeave -= Parent_MouseLeave; } #endregion /// <summary> /// Gets or sets a value indicating whether to hide automatically cursor lines when mouse leaves plotter. /// </summary> /// <value><c>true</c> if auto hide; otherwise, <c>false</c>.</value> public bool AutoHide { get; set; } = true; private void Parent_MouseEnter(object sender, MouseEventArgs e) { if (AutoHide) { UpdateVisibility(); } } private void UpdateVisibility() { horizLine.Visibility = vertGrid.Visibility = GetHorizontalVisibility(); vertLine.Visibility = horizGrid.Visibility = GetVerticalVisibility(); } private Visibility GetHorizontalVisibility() { return showHorizontalLine ? Visibility.Visible : Visibility.Hidden; } private Visibility GetVerticalVisibility() { return showVerticalLine ? Visibility.Visible : Visibility.Hidden; } private void Parent_MouseLeave(object sender, MouseEventArgs e) { if (AutoHide) { horizLine.Visibility = Visibility.Hidden; vertLine.Visibility = Visibility.Hidden; horizGrid.Visibility = Visibility.Hidden; vertGrid.Visibility = Visibility.Hidden; } } private bool followMouse = true; /// <summary> /// Gets or sets a value indicating whether lines are following mouse cursor position. /// </summary> /// <value><c>true</c> if lines are following mouse cursor position; otherwise, <c>false</c>.</value> public bool FollowMouse { get { return followMouse; } set { followMouse = value; if (!followMouse) { AutoHide = false; } UpdateUIRepresentation(); } } private void parent_MouseMove(object sender, MouseEventArgs e) { if (followMouse) { UpdateUIRepresentation(); } } protected override void OnViewportPropertyChanged(ExtendedPropertyChangedEventArgs e) { UpdateUIRepresentation(); } private string customXFormat = null; /// <summary> /// Gets or sets the custom format string of x label. /// </summary> /// <value>The custom X format.</value> public string CustomXFormat { get { return customXFormat; } set { if (customXFormat != value) { customXFormat = value; UpdateUIRepresentation(); } } } private string customYFormat = null; /// <summary> /// Gets or sets the custom format string of y label. /// </summary> /// <value>The custom Y format.</value> public string CustomYFormat { get { return customYFormat; } set { if (customYFormat != value) { customYFormat = value; UpdateUIRepresentation(); } } } private Func<double, string> xTextMapping = null; /// <summary> /// Gets or sets the text mapping of x label - function that builds text from x-coordinate of mouse in data. /// </summary> /// <value>The X text mapping.</value> public Func<double, string> XTextMapping { get { return xTextMapping; } set { if (xTextMapping != value) { xTextMapping = value; UpdateUIRepresentation(); } } } private Func<double, string> yTextMapping = null; /// <summary> /// Gets or sets the text mapping of y label - function that builds text from y-coordinate of mouse in data. /// </summary> /// <value>The Y text mapping.</value> public Func<double, string> YTextMapping { get { return yTextMapping; } set { if (yTextMapping != value) { yTextMapping = value; UpdateUIRepresentation(); } } } private bool showHorizontalLine = true; /// <summary> /// Gets or sets a value indicating whether to show horizontal line. /// </summary> /// <value><c>true</c> if horizontal line is shown; otherwise, <c>false</c>.</value> public bool ShowHorizontalLine { get { return showHorizontalLine; } set { if (showHorizontalLine != value) { showHorizontalLine = value; UpdateVisibility(); } } } private bool showVerticalLine = true; /// <summary> /// Gets or sets a value indicating whether to show vertical line. /// </summary> /// <value><c>true</c> if vertical line is shown; otherwise, <c>false</c>.</value> public bool ShowVerticalLine { get { return showVerticalLine; } set { if (showVerticalLine != value) { showVerticalLine = value; UpdateVisibility(); } } } private void UpdateUIRepresentation() { Point position = followMouse ? Mouse.GetPosition(this) : Position; UpdateUIRepresentation(position); } private void UpdateUIRepresentation(Point mousePos) { if (Plotter2D == null) { return; } var transform = Plotter2D.Viewport.Transform; DataRect visible = Plotter2D.Viewport.Visible; Rect output = Plotter2D.Viewport.Output; if (!output.Contains(mousePos)) { if (AutoHide) { horizGrid.Visibility = horizLine.Visibility = vertGrid.Visibility = vertLine.Visibility = Visibility.Hidden; } return; } if (!followMouse) { mousePos = mousePos.DataToScreen(transform); } horizLine.X1 = output.Left; horizLine.X2 = output.Right; horizLine.Y1 = mousePos.Y; horizLine.Y2 = mousePos.Y; vertLine.X1 = mousePos.X; vertLine.X2 = mousePos.X; vertLine.Y1 = output.Top; vertLine.Y2 = output.Bottom; if (UseDashOffset) { horizLine.StrokeDashOffset = (output.Right - mousePos.X) / 2; vertLine.StrokeDashOffset = (output.Bottom - mousePos.Y) / 2; } Point mousePosInData = mousePos.ScreenToData(transform); string text = null; if (showVerticalLine) { double xValue = mousePosInData.X; if (xTextMapping != null) { text = xTextMapping(xValue); } // doesnot have xTextMapping or it returned null if (text == null) { text = GetRoundedValue(visible.XMin, visible.XMax, xValue); } if (!string.IsNullOrEmpty(customXFormat)) { text = string.Format(customXFormat, text); } horizTextBlock.Text = text; } double width = horizGrid.ActualWidth; double x = mousePos.X + blockShift.X; if (x + width > output.Right) { x = mousePos.X - blockShift.X - width; } Canvas.SetLeft(horizGrid, x); if (showHorizontalLine) { double yValue = mousePosInData.Y; text = null; if (yTextMapping != null) { text = yTextMapping(yValue); } if (text == null) { text = GetRoundedValue(visible.YMin, visible.YMax, yValue); } if (!string.IsNullOrEmpty(customYFormat)) { text = string.Format(customYFormat, text); } vertTextBlock.Text = text; } // by default vertGrid is positioned on the top of line. double height = vertGrid.ActualHeight; double y = mousePos.Y - blockShift.Y - height; if (y < output.Top) { y = mousePos.Y + blockShift.Y; } Canvas.SetTop(vertGrid, y); if (followMouse) { Position = mousePos; } } /// <summary> /// Gets or sets the mouse position in screen coordinates. /// </summary> /// <value>The position.</value> public Point Position { get { return (Point)GetValue(PositionProperty); } set { SetValue(PositionProperty, value); } } /// <summary> /// Identifies Position dependency property. /// </summary> public static readonly DependencyProperty PositionProperty = DependencyProperty.Register( "Position", typeof(Point), typeof(CursorCoordinateGraph), new UIPropertyMetadata(new Point(), OnPositionChanged)); private static void OnPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CursorCoordinateGraph graph = (CursorCoordinateGraph)d; graph.UpdateUIRepresentation((Point)e.NewValue); } private string GetRoundedValue(double min, double max, double value) { double roundedValue = value; var log = RoundingHelper.GetDifferenceLog(min, max); string format = "G3"; double diff = Math.Abs(max - min); if (1E3 < diff && diff < 1E6) { format = "F0"; } if (log < 0) { format = "G" + (-log + 2).ToString(); } return roundedValue.ToString(format); } #region UseDashOffset property public bool UseDashOffset { get { return (bool)GetValue(UseDashOffsetProperty); } set { SetValue(UseDashOffsetProperty, value); } } public static readonly DependencyProperty UseDashOffsetProperty = DependencyProperty.Register( "UseDashOffset", typeof(bool), typeof(CursorCoordinateGraph), new FrameworkPropertyMetadata(true, UpdateUIRepresentation)); private static void UpdateUIRepresentation(DependencyObject d, DependencyPropertyChangedEventArgs e) { CursorCoordinateGraph graph = (CursorCoordinateGraph)d; if ((bool)e.NewValue) { graph.UpdateUIRepresentation(); } else { graph.vertLine.ClearValue(Shape.StrokeDashOffsetProperty); graph.horizLine.ClearValue(Shape.StrokeDashOffsetProperty); } } #endregion #region LineStroke property public Brush LineStroke { get { return (Brush)GetValue(LineStrokeProperty); } set { SetValue(LineStrokeProperty, value); } } public static readonly DependencyProperty LineStrokeProperty = DependencyProperty.Register( "LineStroke", typeof(Brush), typeof(CursorCoordinateGraph), new PropertyMetadata(new SolidColorBrush(Color.FromArgb(170, 86, 86, 86)))); #endregion #region LineStrokeThickness property public double LineStrokeThickness { get { return (double)GetValue(LineStrokeThicknessProperty); } set { SetValue(LineStrokeThicknessProperty, value); } } public static readonly DependencyProperty LineStrokeThicknessProperty = DependencyProperty.Register( "LineStrokeThickness", typeof(double), typeof(CursorCoordinateGraph), new PropertyMetadata(2.0)); #endregion #region LineStrokeDashArray property [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public DoubleCollection LineStrokeDashArray { get { return (DoubleCollection)GetValue(LineStrokeDashArrayProperty); } set { SetValue(LineStrokeDashArrayProperty, value); } } public static readonly DependencyProperty LineStrokeDashArrayProperty = DependencyProperty.Register( "LineStrokeDashArray", typeof(DoubleCollection), typeof(CursorCoordinateGraph), new FrameworkPropertyMetadata(DoubleCollectionHelper.Create(3, 3))); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraControll : MonoBehaviour { // Main CameraのTransform Transform tf; public GameObject targetObj; Vector3 targetPos; // Start is called before the first frame update void Start() { targetPos = targetObj.transform.position; // Main CameraのTransformを取得する tf = this.gameObject.GetComponent<Transform>(); } // Update is called once per frame void Update() { transform.position += targetObj.transform.position - targetPos; targetPos = targetObj.transform.position; if (Input.GetKey(KeyCode.LeftArrow)) { // カメラを左へ回転 transform.Rotate(new Vector3(0.0f, -2.0f, 0.0f)); } else if (Input.GetKey(KeyCode.RightArrow)) { // カメラを右へ回転 transform.Rotate(new Vector3(0f, 2.0f, 0f)); } if (Input.GetKeyDown(KeyCode.UpArrow)) { // カメラの回転をリセットする tf.rotation = new Quaternion(0f, 0f, 0f, 0f); } } }
using System; using System.Linq.Expressions; using DynamicClassBuilder.Models; namespace DynamicClassBuilder.Services { public interface IBuilder<T> { IBuilder<T> Implement<TMember>(Expression<Func<T, TMember>> member, Expression<Func<TMember>> implementationBody); IBuilder<T> Implement<TMember>(Func<ISimplePropertyInfo, Expression<Func<TMember>>> func); T Build(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThrowBehav : MonoBehaviour { public static float count; public GameObject player; public GameObject theCam; public GameObject boss; float totalSnowballsDestroyed; Transform enemy1, enemy2, enemy3, enemy4; bool detectEndOfThrowing = false, enemyCycleEnd = false, shakeItUp = false; static bool handlingRespawn = false; Transform[] enemies = new Transform[8]; static Collider currCollider; static GameObject theObj; bool moveItBack; // Start is called before the first frame update void Start() { totalSnowballsDestroyed = 0; count = 0; } // Update is called once per frame void Update() { if (LevelPassScript.entered && !moveItBack) { EnablePrevCollider(); LevelPassScript.entered = false; } if (CharacterForBlue.hitCount >= 100) { if (!handlingRespawn) { RespawnCharacter(); handlingRespawn = true; } } else { if (totalSnowballsDestroyed == 6 && count == 1) { //Debug.Log("1g"); player.transform.Translate(Vector3.right * Time.deltaTime * 8); } if (totalSnowballsDestroyed == 8 && count == 2) { //Debug.Log("2g"); player.transform.Translate(Vector3.right * Time.deltaTime * 8); } if (totalSnowballsDestroyed == 10 && count == 3) { //Debug.Log("3g"); player.transform.Translate(Vector3.right * Time.deltaTime * 8); } if (totalSnowballsDestroyed == 12 && count == 4) { //Debug.Log("4g"); player.transform.Translate(Vector3.right * Time.deltaTime * 8); } if (detectEndOfThrowing) { //Debug.Log("detectEndOfThrowingTrue"); enemyCycleEnd = enemies[0].GetComponent<EnemyThrow>().finishedThrowing; for (int i = 1; i < transform.childCount; i++) { enemyCycleEnd = enemyCycleEnd && enemies[i].GetComponent<EnemyThrow>().finishedThrowing; } if (enemyCycleEnd) { theCam.GetComponent<CameraShake>().shakeDuration = 1.3f; theCam.GetComponent<CameraShake>().pie = true; boss.GetComponent<BlueBoss>().idle = false; boss.GetComponent<BlueBoss>().NextLevel(); enemyCycleEnd = false; detectEndOfThrowing = false; shakeItUp = true; } } if (theCam.GetComponent<CameraShake>().pie && shakeItUp) { Debug.Log("camShakeTrue"); shakeItUp = false; Invoke("ShakeAndCont", 1.5f); } } } void OnTriggerEnter(Collider other) { if (!moveItBack) { if (handlingRespawn) { CharacterForBlue.hitCount = 0; Debug.Log("dirty bit"); handlingRespawn = false; } count++; theObj = transform.gameObject; if (count != 5) { Debug.Log("TriggerIf"); totalSnowballsDestroyed = 0; Debug.Log("ppppp " + count + " " + totalSnowballsDestroyed); currCollider = gameObject.GetComponent<Collider>(); currCollider.enabled = false; MakeThrow(); } else { Debug.Log("TriggerElse"); boss.GetComponent<BlueBoss>().idle = false; boss.GetComponent<BlueBoss>().player = player; boss.transform.Rotate(12, 0, 0); boss.GetComponent<BlueBoss>().globalattack1 = true; } } } void MakeThrow() { Debug.Log("MakeThrow"); Debug.Log("zzzz " + transform.childCount); for (int i = 0; i < transform.childCount; i++) { enemies[i] = transform.GetChild(i); if (count == 4) enemies[i].gameObject.GetComponent<EnemyThrow>().wasBouncy = true; enemies[i].gameObject.GetComponent<EnemyThrow>().theTarget = player; enemies[i].gameObject.GetComponent<EnemyThrow>().StartThrowing(); } detectEndOfThrowing = true; } void ShakeAndCont() { Debug.Log("ShakeAndCont"); boss.GetComponent<BlueBoss>().LevelBegin(); if (count == 1) totalSnowballsDestroyed = 6; if (count == 2) totalSnowballsDestroyed = 8; if (count == 3) totalSnowballsDestroyed = 10; if (count == 4) totalSnowballsDestroyed = 12; Debug.Log("wwww " + totalSnowballsDestroyed + " " + count); } void EnablePrevCollider() { //Debug.Log("LevelPass"); //Debug.Log(currCollider.gameObject.name); currCollider.enabled = true; } void RespawnCharacter() { Debug.Log("HitCount Reached"); count = 0; totalSnowballsDestroyed = 0; moveItBack = true; detectEndOfThrowing = false; count = 1; player.transform.position = new Vector3(12.25f, 1f, 5.12f); for (int i = 0; i < theObj.transform.childCount; i++) { Debug.Log(theObj.name); enemies[i] = theObj.transform.GetChild(i); if (enemies[i].gameObject.GetComponent<EnemyThrow>().snowballClone != null) enemies[i].gameObject.GetComponent<EnemyThrow>().snowballClone.SetActive(false); enemies[i].gameObject.SetActive(false); if(theObj.name == "LevelFourEnemies") { enemies[i].gameObject.GetComponent<EnemyThrow>().wasBouncy = false; enemies[i].gameObject.GetComponent<EnemyThrow>().bouncy = false; enemies[i].gameObject.transform.position = enemies[i].gameObject.GetComponent<EnemyThrow>().orgPos; } enemies[i].gameObject.SetActive(true); } GetComponent<Collider>().enabled = true; moveItBack = false; //CharacterForBlue.hitCount = 0; //handlingRespawn = false; } }
using System; using System.Security.Cryptography; using System.Threading; using DM7_PPLUS_Integration.Messages.PPLUS; using NetMQ; using NetMQ.Sockets; namespace DM7_PPLUS_Integration.Implementierung.PPLUS { public class Adapter : IDisposable { public static int Authentication_Port(int portRangeStart) => portRangeStart; public static int Capabilities_Port(int portRangeStart) => portRangeStart + 1; public static int Query_Port(int portRangeStart) => portRangeStart + 2; public static int Command_Port(int portRangeStart) => portRangeStart + 3; public static int Notification_Port(int portRangeStart) => portRangeStart + 4; public const string Mitarbeiter_Topic = "Mitarbeiter"; public const string Dienste_Topic = "Dienste"; private readonly PPLUS_Handler _pplusHandler; private readonly string _encryptionKey; private readonly NetMQPoller _poller; private readonly Thread _thread; public Adapter(string address, int port_range_start, PPLUS_Handler pplusHandler, string encryptionKey) { _pplusHandler = pplusHandler; _encryptionKey = encryptionKey; _poller = new NetMQPoller(); _thread = new Thread(() => { using (var authentication_socket = new RouterSocket()) using (var capability_socket = new RouterSocket()) using (var query_socket = new RouterSocket()) using (var command_socket = new RouterSocket()) using (var notification_socket = new PublisherSocket()) { authentication_socket.Bind($"tcp://{address}:{Authentication_Port(port_range_start)}"); authentication_socket.ReceiveReady += (_, args) => Authenticate(args.Socket); capability_socket.Bind($"tcp://{address}:{Capabilities_Port(port_range_start)}"); capability_socket.ReceiveReady += (_, args) => Handle_Capabilities(args.Socket); query_socket.Bind($"tcp://{address}:{Query_Port(port_range_start)}"); query_socket.ReceiveReady += (_, args) => Handle_Query(args.Socket); command_socket.Bind($"tcp://{address}:{Command_Port(port_range_start)}"); command_socket.ReceiveReady += (_, args) => Handle_Command(args.Socket); notification_socket.Bind($"tcp://{address}:{Notification_Port(port_range_start)}"); pplusHandler.Mitarbeiteränderungen_liegen_bereit += () => notification_socket.SendMoreFrame(Mitarbeiter_Topic).SendFrameEmpty(); pplusHandler.Dienständerungen_liegen_bereit += () => notification_socket.SendMoreFrame(Dienste_Topic).SendFrameEmpty(); using (_poller) { _poller.Add(authentication_socket); _poller.Add(capability_socket); _poller.Add(query_socket); _poller.Add(command_socket); _poller.Add(notification_socket); _poller.Run(); } } }); _thread.Start(); } private void Authenticate(NetMQSocket socket) { var caller = socket.ReceiveFrameBytes(); socket.SkipFrame(); using (var encryption = Encryption.From_encoded_Key(_encryptionKey)) { AuthenticationResult message; try { var request = AuthenticationRequest.Decoded(encryption.Decrypt(socket.ReceiveFrameBytes())); var token = _pplusHandler.Authenticate(request.User, request.Password).Result; message = token.HasValue ? (AuthenticationResult) new AuthenticationSucceeded(token.Value.Value) : new AuthenticationFailed("Zugriff nicht zugelassen."); } catch (CryptographicException) { message = new AuthenticationFailed("Unbekannte Verschlüsselung! Bitte gleichen Sie den benutzten Schlüssel mit P-PLUS ab."); } socket.SendMoreFrame(caller); socket.SendMoreFrameEmpty(); socket.SendFrame(Encoding.AuthenticationResult_Encoded(message)); } } private void Handle_Capabilities(NetMQSocket socket) { var caller = socket.ReceiveFrameBytes(); socket.SkipFrame(); socket.SkipFrame(); var capabilities = _pplusHandler.Capabilities().Result; socket.SendMoreFrame(caller); socket.SendMoreFrameEmpty(); socket.SendFrame(capabilities.Encoded()); } private void Handle_Query(NetMQSocket socket) { using (var encryption = Encryption.From_encoded_Key(_encryptionKey)) { var caller = socket.ReceiveFrameBytes(); socket.SkipFrame(); var message = QueryMessage.Decoded(socket.ReceiveFrameBytes()); ResponseMessage response; try { var query = Encoding.Query_Decoded(encryption.Decrypt(message.Query)); var result = _pplusHandler.HandleQuery(Message_mapper.Token_aus(message), query).Result; response = new QuerySucceeded(encryption.Encrypt(Encoding.QueryResult_Encoded(result))); } catch (CryptographicException) { response = new QueryFailed("Unbekannte Verschlüsselung! Bitte gleichen Sie den benutzten Schlüssel mit P-PLUS ab."); } socket.SendMoreFrame(caller); socket.SendMoreFrameEmpty(); socket.SendFrame(Encoding.ResponseMessage_Encoded(response)); } } private void Handle_Command(NetMQSocket socket) { using (var encryption = Encryption.From_encoded_Key(_encryptionKey)) { var caller = socket.ReceiveFrameBytes(); socket.SkipFrame(); var message = CommandMessage.Decoded(socket.ReceiveFrameBytes()); CommandResponseMessage response; try { var command = Encoding.Command_Decoded(encryption.Decrypt(message.Command)); var result = _pplusHandler.HandleCommand(Message_mapper.Token_aus(message), command).Result; response = new CommandSucceeded(encryption.Encrypt(Encoding.CommandResult_Encoded(result))); } catch (CryptographicException) { response = new CommandFailed("Unbekannte Verschlüsselung! Bitte gleichen Sie den benutzten Schlüssel mit P-PLUS ab."); } socket.SendMoreFrame(caller); socket.SendMoreFrameEmpty(); socket.SendFrame(Encoding.CommandResponseMessage_Encoded(response)); } } public void Dispose() { _poller.Dispose(); var gracefullyStopped = _thread.Join(TimeSpan.FromSeconds(10)); if (!gracefullyStopped) _thread.Abort(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace XORProjetCrypto { public partial class Form1 : Form { string directoryPath = string.Empty; string dictionnairePath = string.Empty; string startKey1 = string.Empty; string endKey1 = string.Empty; string key1 = string.Empty; string startKey2 = string.Empty; string endKey2 = string.Empty; string key2 = string.Empty; string startKey3 = string.Empty; string endKey3 = string.Empty; string key3 = string.Empty; string startKey4 = string.Empty; string endKey4 = string.Empty; string key4 = string.Empty; string startKey5 = string.Empty; string endKey5 = string.Empty; string key5 = string.Empty; List<string> pathDocuments = new List<string>(); List<Tuple<string, string>> document = new List<Tuple<string, string>>(); //Tuple<string, int> List<string> results = new List<string>(); //Thread decrypt; public Form1() { InitializeComponent(); } private void test() { /* ============= UTILISATION DIC ============= *\ Dictionary test = new Dictionary(dictionnairePath); Console.WriteLine(test.CheckString("couecou et de cette zz aerf azer zqbduq qzd")); \* ============= =============== ============= */ /* ============= UTILISATION KEY ============= *\ KeyGenerator key = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey.Text, textBoxEndKey.Text); key.GenerateKey(); \* ============= =============== ============= */ /* ============= UTILISATION XOR ============= *\ string cipherBin = XOR.Encode("test du code XOR pour voir", "azesgrhdtjy"); Console.WriteLine(cipherBin); string cipherChar = XOR.BinaryToString(cipherBin); Console.WriteLine(cipherChar); string textBin = XOR.Decode(cipherChar, "azesgrhdtjy"); Console.WriteLine(textBin); string textChar = XOR.BinaryToString(textBin); Console.WriteLine(textChar); \* ============= =============== ============= */ } private void buttonDirectory_Click(object sender, EventArgs e) { folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer; DialogResult result = folderBrowserDialog.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath)) { string[] files = Directory.GetFiles(folderBrowserDialog.SelectedPath); textBoxDirectory.Text = folderBrowserDialog.SelectedPath; directoryPath = folderBrowserDialog.SelectedPath; } } private void buttonDictionnaire_Click(object sender, EventArgs e) { openFileDialog.InitialDirectory = "c:\\"; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { dictionnairePath = openFileDialog.FileName; this.textBoxDictionnaire.Text = dictionnairePath; } } private void buttonStart_Click(object sender, EventArgs e) { test(); if (Directory.Exists(directoryPath)) { if (File.Exists(dictionnairePath)) { LoadFiles(); if (textBoxStartkey1.Text.Length == textBoxEndKey1.Text.Length) { Console.WriteLine("Task 1 - Start"); endKey1 = textBoxEndKey1.Text; key1 = textBoxStartkey1.Text; var t1 = Task.Factory.StartNew(() => Start1()); } if (textBoxStartkey2.Text.Length == textBoxEndKey2.Text.Length) { Console.WriteLine("Task 2 - Start"); endKey2 = textBoxEndKey2.Text; key2 = textBoxStartkey2.Text; var t2 = Task.Factory.StartNew(() => Start2()); } if (textBoxStartkey3.Text.Length == textBoxEndKey3.Text.Length) { Console.WriteLine("Task 3 - Start"); endKey3 = textBoxEndKey3.Text; key3 = textBoxStartkey3.Text; var t3 = Task.Factory.StartNew(() => Start3()); } if (textBoxStartkey4.Text.Length == textBoxEndKey4.Text.Length) { Console.WriteLine("Task 4 - Start"); endKey4 = textBoxEndKey4.Text; key4 = textBoxStartkey4.Text; var t4 = Task.Factory.StartNew(() => Start4()); } if (textBoxStartkey5.Text.Length == textBoxEndKey5.Text.Length) { Console.WriteLine("Task 5 - Start"); endKey5 = textBoxEndKey5.Text; key5 = textBoxStartkey5.Text; var t5 = Task.Factory.StartNew(() => Start5()); } /* if (textBoxStartkey1.Text.Length == 6 & textBoxEndKey1.Text.Length == 6) { Console.WriteLine("OK"); endKey1 = textBoxEndKey1.Text; key1 = textBoxStartkey1.Text; //KeyGenerator key = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey.Text, textBoxEndKey.Text); //key.GenerateKeys(); decrypt = new Thread(Start1); decrypt.Start(); //Start(); }*/ } } } private void Start1() { double scoreKey = 0; string textBin; string textChar = ""; KeyGenerator keyGen = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey1.Text, textBoxEndKey1.Text); Dictionary dictionary = new Dictionary(dictionnairePath); long i = 0; while (!key1.SequenceEqual(endKey1)) { key1 = keyGen.GenerateKey(); i++; List<string> write = new List<string>(); foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar = XOR.BinaryToString(textBin); scoreKey += dictionary.CheckString(textChar); */ string t = XOR.EncryptOrDecrypt(doc.Item2, key1); textChar += t; scoreKey += dictionary.CheckString(t); //} if (scoreKey > 100) using (StreamWriter sw = File.AppendText("c:\\test.txt")) {sw.WriteLine("Task 1 - File:[" + doc.Item1 + "] - Key:[" + key1 + "] - Score:[" + scoreKey + "]");} //Console.WriteLine("File:[" + doc.Item1 + "] - Key:[" + key1 + "] - Score:[" + scoreKey + "]" + textChar); scoreKey = 0; } //Console.WriteLine(key); textChar = ""; } Console.WriteLine("Task 1 - End"); } private void Start2() { double scoreKey = 0; string textBin; string textChar = ""; KeyGenerator keyGen = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey2.Text, textBoxEndKey2.Text); Dictionary dictionary = new Dictionary(dictionnairePath); long i = 0; while (!key2.SequenceEqual(endKey2)) { key2 = keyGen.GenerateKey(); i++; List<string> write = new List<string>(); foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar = XOR.BinaryToString(textBin); scoreKey += dictionary.CheckString(textChar); */ string t = XOR.EncryptOrDecrypt(doc.Item2, key2); textChar += t; scoreKey += dictionary.CheckString(t); //} if (scoreKey > 100) using (StreamWriter sw = File.AppendText("c:\\test.txt")) { sw.WriteLine("Task 2 - File:[" + doc.Item1 + "] - Key:[" + key2 + "] - Score:[" + scoreKey + "]"); } //Console.WriteLine("File:[" + doc.Item1 + "] - Key:[" + key + "] - Score:[" + scoreKey + "]" + textChar); scoreKey = 0; } //Console.WriteLine(key); textChar = ""; } Console.WriteLine("Task 2 - End"); } private void Start3() { double scoreKey = 0; string textBin; string textChar = ""; KeyGenerator keyGen = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey3.Text, textBoxEndKey3.Text); Dictionary dictionary = new Dictionary(dictionnairePath); long i = 0; while (!key3.SequenceEqual(endKey3)) { key3= keyGen.GenerateKey(); i++; List<string> write = new List<string>(); foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar = XOR.BinaryToString(textBin); scoreKey += dictionary.CheckString(textChar); */ string t = XOR.EncryptOrDecrypt(doc.Item2, key3); textChar += t; scoreKey += dictionary.CheckString(t); //} if (scoreKey > 100) using (StreamWriter sw = File.AppendText("c:\\test.txt")) { sw.WriteLine("Task 3 - File:[" + doc.Item1 + "] - Key:[" + key3 + "] - Score:[" + scoreKey + "]"); } //Console.WriteLine("File:[" + doc.Item1 + "] - Key:[" + key + "] - Score:[" + scoreKey + "]" + textChar); scoreKey = 0; } //Console.WriteLine(key); textChar = ""; } Console.WriteLine("Task 3 - End"); } private void Start4() { double scoreKey = 0; string textBin; string textChar = ""; KeyGenerator keyGen = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey4.Text, textBoxEndKey4.Text); Dictionary dictionary = new Dictionary(dictionnairePath); long i = 0; while (!key4.SequenceEqual(endKey4)) { key4 = keyGen.GenerateKey(); i++; List<string> write = new List<string>(); foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar = XOR.BinaryToString(textBin); scoreKey += dictionary.CheckString(textChar); */ string t = XOR.EncryptOrDecrypt(doc.Item2, key4); textChar += t; scoreKey += dictionary.CheckString(t); //} if (scoreKey > 100) using (StreamWriter sw = File.AppendText("c:\\test.txt")) { sw.WriteLine("Task 4 - File:[" + doc.Item1 + "] - Key:[" + key4 + "] - Score:[" + scoreKey + "]"); } //Console.WriteLine("File:[" + doc.Item1 + "] - Key:[" + key + "] - Score:[" + scoreKey + "]" + textChar); scoreKey = 0; } //Console.WriteLine(key); textChar = ""; } Console.WriteLine("Task 4 - End"); } private void Start5() { double scoreKey = 0; string textBin; string textChar = ""; KeyGenerator keyGen = new KeyGenerator("abcdefghijklmnopqrstuvwxyz", 6, textBoxStartkey5.Text, textBoxEndKey5.Text); Dictionary dictionary = new Dictionary(dictionnairePath); long i = 0; while (!key5.SequenceEqual(endKey5)) { key5 = keyGen.GenerateKey(); i++; List<string> write = new List<string>(); foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar = XOR.BinaryToString(textBin); scoreKey += dictionary.CheckString(textChar); */ string t = XOR.EncryptOrDecrypt(doc.Item2, key5); textChar += t; scoreKey += dictionary.CheckString(t); //} if (scoreKey > 100) using (StreamWriter sw = File.AppendText("c:\\test.txt")) { sw.WriteLine("Task 5 - File:[" + doc.Item1 + "] - Key:[" + key5 + "] - Score:[" + scoreKey + "]"); } //Console.WriteLine("File:[" + doc.Item1 + "] - Key:[" + key + "] - Score:[" + scoreKey + "]" + textChar); scoreKey = 0; } //Console.WriteLine(key); textChar = ""; } Console.WriteLine("Task 5 - End"); } private void buttonPause_Click(object sender, EventArgs e) { } public void LoadFiles() { string[] files = Directory.GetFiles(directoryPath); foreach(string path in files) { string logFile = File.ReadAllText(path); document.Add(new Tuple<string, string>(path, logFile)); } } private void buttonTryKey_Click(object sender, EventArgs e) { LoadFiles(); string textBin; string textChar =""; key1 = tryKey.Text; textBoxResult.Text += key1 + Environment.NewLine; foreach (Tuple<string, string> doc in document) { //foreach (string line in doc.Item2) //{ /* textBin = XOR.Decode(line, key); textChar += XOR.BinaryToString(textBin); */ textChar += XOR.EncryptOrDecrypt(doc.Item2, key1); textBoxResult.Text += textChar; //} textBoxResult.Text += Environment.NewLine; textBoxResult.Text += Environment.NewLine; } } } }
using System.Collections.Generic; namespace HairSalon.Models { public class Stylist { public Stylist() { this.Clients = new HashSet<Client>(); //HashSet is an unordered collection of unique elements - no duplicates allowed (one to many)/handles no records case } public int StylistId { get; set; } //1st coloumn in "stylists" table: primary key in table (used as foreign key in Client.cs) public string Name { get; set; } //2nd column in "stylists" table public virtual ICollection<Client> Clients { get; set; } //"Clients" represent DBSet of "one" in "many". // DBSet is declared as ICollection<Client> (interface) data type, so that EF can use all the ICollection // methods it requires on the "one" objects in order to act as ORM. "Virtual" needed for lazy loading. } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entities.MES { /// <summary> /// 送修在制品修复转出工序 /// </summary> public class QCOperationsForNG { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 工序叶标识 /// </summary> public int T216Leaf { get; set; } /// <summary> /// 工序代码 /// </summary> public string T216Code { get; set; } /// <summary> /// 工序名称 /// </summary> public string T216Name { get; set; } public override string ToString() { return string.Format( "[{0}] {1}", T216Code, T216Name); } public QCOperationsForNG Clone() { return MemberwiseClone() as QCOperationsForNG; } } }
using System; using System.Collections.Generic; using System.IO; 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 FileExplorer { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { foreach (string drive in Directory.GetLogicalDrives()) { TreeViewItem item = new TreeViewItem() { Header = drive, Tag = drive }; item.Items.Add(null); item.Expanded += Folder_Expanded; folderTrVw.Items.Add(item); } } private void Folder_Expanded(object sender, RoutedEventArgs e) { TreeViewItem item = (TreeViewItem)sender; if (item.Items.Count != 1 || item.Items[0] != null) { return; } item.Items.Clear(); string fullPath = (string)item.Tag; createTreeViewSubItem(item, fullPath, ElementType.Folder); createTreeViewSubItem(item, fullPath, ElementType.File); } enum ElementType { Folder, File }; private void createTreeViewSubItem(TreeViewItem item, string fullPath, ElementType type) { getElements(fullPath, type).ForEach(path => { TreeViewItem subItem = new TreeViewItem() { Header = getFileFolderName(path), Tag = path }; switch (type) { case ElementType.Folder: subItem.Items.Add(null); subItem.Expanded += Folder_Expanded; item.Items.Add(subItem); break; case ElementType.File: item.Items.Add(subItem); break; default: break; } }); } private static List<string> getElements(string fullPath, ElementType type) { var elements = new List<string>(); string[] stringArray = null; switch (type) { case ElementType.Folder: try { stringArray = Directory.GetDirectories(fullPath); } catch { } break; case ElementType.File: try { stringArray = Directory.GetFiles(fullPath); } catch { } break; } if (stringArray != null && stringArray.Length > 0) { elements.AddRange(stringArray); } return elements; } public static string getFileFolderName(string path) { if (string.IsNullOrEmpty(path)) { return string.Empty; } string normalizedPath = path.Replace('/', '\\'); int lastIndex = normalizedPath.LastIndexOf('\\'); if (lastIndex <= 0) { return path; } return path.Substring(lastIndex + 1); } } }
namespace Itida2axitrade.model { public class RestProcess : TransferProcess { public override string SqlQueryString { get { return "select cast(cast (nn as int) as varchar) as GOODCODE,sklad as WH_CODE,cast(cena as varchar) as COST_PRICE,cast (dbo.fn_calcclev_cena( nn, '', '001', '001' ) as varchar) AS SALE_PRICE,cast (kolp as varchar) as REST from reg_c001 where kolp!=0"; } } public override string FbQueryString { get { return "execute procedure SP_MODIFY_IMPORTREST(:WH_CODE, :GOODCODE, :REST, :COST_PRICE, :SALE_PRICE)"; } } public override string ProcessName { get { return "Rest process"; } } } }
using Exiled.API.Features; using Exiled.API.Enums; using System; namespace AdminAlarm { public class AdminAlarmPlugin : Plugin<Config> { #region Info public override string Name { get; } = "Admin Alarm Plugin"; public override string Prefix { get; } = "AdminAlarm"; public override string Author { get; } = "CubeRuben"; public override PluginPriority Priority { get; } = PluginPriority.Default; public override Version Version { get; } = new Version(1, 0, 0); public override Version RequiredExiledVersion { get; } = new Version(2, 1, 0); #endregion EventHandlers EventHandlers; public AdminAlarmPlugin() { } public override void OnEnabled() { EventHandlers = new EventHandlers(this); Exiled.Events.Handlers.Server.SendingRemoteAdminCommand += EventHandlers.OnSendingRemoteAdminCommand; } public override void OnDisabled() { Exiled.Events.Handlers.Server.SendingRemoteAdminCommand -= EventHandlers.OnSendingRemoteAdminCommand; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiCoin.Models; using FiiiCoin.ServiceAgent; using FiiiCoin.Wallet.Win.Biz.Services; using FiiiCoin.Wallet.Win.Common; using FiiiCoin.Wallet.Win.Converters; using FiiiCoin.Wallet.Win.Models; using GalaSoft.MvvmLight.Command; using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace FiiiCoin.Wallet.Win.ViewModels.ShellPages { public class SendSettingViewModel : PopupShellBase { protected override string GetPageName() { return Pages.SendSettingPage; } protected override void OnLoaded() { Setting = new ProfessionalSetting(); base.OnLoaded(); RegeistMessenger<SendMsgData<ProfessionalSetting>>(OnGetData); ChooseUtxoCommand = new RelayCommand(ChooseUtxo); ChooseAddrCommand = new RelayCommand(ChooseAddr); RemoveUtxoCommand = new RelayCommand<PageUnspent>(RemoveUtxo); } private ProfessionalSetting _setting; public ProfessionalSetting Setting { get { return _setting; } set { _setting = value; RaisePropertyChanged("Setting"); } } SendMsgData<ProfessionalSetting> _data = null; public void OnGetData(SendMsgData<ProfessionalSetting> data) { Setting.UTXO = data.Token.UTXO; Setting.LockTime = data.Token.LockTime; Setting.ChangeAddress = data.Token.ChangeAddress; Setting.IsEnable = data.Token.IsEnable; _data = data; } public override void OnOkClick() { if (_data != null) { _data.Token.LockTime = Setting.LockTime; _data.Token.ChangeAddress = Setting.ChangeAddress; _data.Token.UTXO = Setting.UTXO; _data.Token.IsEnable = Setting.IsEnable; _data.CallBack(); } base.OnOkClick(); } public ICommand ChooseUtxoCommand { get; private set; } public ICommand ChooseAddrCommand { get; private set; } public ICommand RemoveUtxoCommand { get; private set; } void ChooseUtxo() { SendMsgData<PageUnspent> sendMsgData = new SendMsgData<PageUnspent>(); sendMsgData.SetCallBack(() => { if (sendMsgData.CallBackParams != null && sendMsgData.CallBackParams is PageUnspent) { Setting.UTXO.Add((PageUnspent)sendMsgData.CallBackParams); } UpdatePage(Pages.SendSettingPage); }); UpdatePage(Pages.Choose_Utxo_Page); SendMessenger(Pages.Choose_Utxo_Page, sendMsgData); } void ChooseAddr() { SendMsgData<AccountInfo> sendMsgData = new SendMsgData<AccountInfo>(); sendMsgData.SetCallBack(() => { if (sendMsgData.CallBackParams != null && sendMsgData.CallBackParams is AccountInfo) { Setting.ChangeAddress = (AccountInfo)sendMsgData.CallBackParams; } UpdatePage(Pages.SendSettingPage); }); UpdatePage(Pages.Choose_Change_Addr_Page); SendMessenger(Pages.Choose_Change_Addr_Page, sendMsgData); } void RemoveUtxo(PageUnspent utxo) { Setting.UTXO.Remove((PageUnspent)utxo); } } public class ProfessionalSetting : NotifyBase { public ProfessionalSetting() { _isEnable = false; LockTime = DateTime.UtcNow; } private ObservableCollection< PageUnspent> _uTXO; private DateTime _lockTime; private AccountInfo _changeAddress; private bool _isEnable; public ObservableCollection<PageUnspent> UTXO { get { if (_uTXO == null) _uTXO = new ObservableCollection<PageUnspent>(); return _uTXO; } set { _uTXO = value; RaisePropertyChanged("UTXO"); } } public DateTime LockTime { get { return _lockTime; } set { _lockTime = value; RaisePropertyChanged("LockTime"); } } public AccountInfo ChangeAddress { get { return _changeAddress; } set { _changeAddress = value; RaisePropertyChanged("ChangeAddress"); } } public bool IsEnable { get { return _isEnable; } set { if (UTXO == null || !UTXO.Any() || ChangeAddress == null) { _isEnable = false; } else { _isEnable = value; } RaisePropertyChanged("IsEnable"); } } public ProfessionalSetting Clone() { ProfessionalSetting setting = new ProfessionalSetting(); setting.LockTime = this.LockTime; if (UTXO == null) setting.UTXO = null; else { setting.UTXO.Clear(); UTXO.ToList().ForEach(utxo => setting.UTXO.Add(new PageUnspent() { Amount = utxo.Amount, Account = utxo.Account, Vout = utxo.Vout, Txid = utxo.Txid, Address = utxo.Address })); } if (ChangeAddress == null) setting.ChangeAddress = null; else setting.ChangeAddress = new AccountInfo() { Address = ChangeAddress.Address, Balance = ChangeAddress.Balance, Tag = ChangeAddress.Tag, }; setting.IsEnable = this.IsEnable; return setting; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HomeWorkOOP3_2 { class Cаг { public Cаг() { } } }
using System; using System.Collections.Generic; namespace Seterlund.CodeGuard { public abstract class ValidatorBase<T> { public abstract T Value { get; } public abstract string Name { get; } public abstract void ArgumentMessage(string message); public abstract void ArgumentNullMessage(); public abstract void ArgumentOutRangeMessage(); protected List<string> Result; public List<string> GetResult() { return Result; } /// <summary> /// Is argument instance of type /// </summary> /// <typeparam name="TType">The type to check</typeparam> /// <returns></returns> public ValidatorBase<T> Is<TType>() { var isType = this.Value is TType; if (!isType) { this.ArgumentMessage(string.Format("Value is not <{0}>", typeof(TType).Name)); } return this; } /// <summary> /// Is argument not the default value /// </summary> /// <returns></returns> public ValidatorBase<T> IsNotDefault() { if (default(T).Equals(this.Value)) { this.ArgumentMessage("Value cannot be the default value."); } return this; } /// <summary> /// Is the fucntion true for the argument. /// </summary> /// <returns></returns> public ValidatorBase<T> IsTrue(Func<T, bool> booleanFunction, string exceptionMessage) { if (booleanFunction(this.Value)) { this.ArgumentMessage(exceptionMessage); } return this; } } }
using HarmonyLib; using RainyReignGames.RevealMask; namespace RealisticBleeding { public static class DisableMaskMipMappingPatch { [HarmonyPatch(typeof(RevealMaterialController), "Start")] public static class StartPatch { private static void Prefix(ref bool ___generateMipMaps) { ___generateMipMaps = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using DelftTools.Hydro; using DelftTools.Hydro.CrossSections; using DelftTools.Hydro.Helpers; using DelftTools.Hydro.Structures; using DelftTools.TestUtils; using DelftTools.Utils; using GeoAPI.Extensions.Coverages; using GeoAPI.Geometries; using GisSharpBlog.NetTopologySuite.Geometries; using NetTopologySuite.Extensions.Actions; using NetTopologySuite.Extensions.Coverages; using NetTopologySuite.Extensions.Networks; using NUnit.Framework; namespace DelftTools.Tests.Hydo.Helpers { [TestFixture] public class HydroNetworkHelperTest { [Test] public void DetectAndUpdateBranchBoundaries() { var network = new HydroNetwork(); var branch1 = new Channel(); var node1 = new HydroNode(); var node2 = new HydroNode(); branch1.Source = node1; branch1.Target = node2; network.Branches.Add(branch1); network.Nodes.Add(node1); network.Nodes.Add(node2); Assert.IsTrue(node1.IsBoundaryNode); Assert.IsTrue(node2.IsBoundaryNode); } [Test] public void GenerateCalculationPointsOnCrossSectionsSkipsIfAlsoStructurePresent() { var network = CreateTestNetwork(); var cs1 = network.CrossSections.First(); var branch = cs1.Branch as IChannel; var weir = new Weir(); NetworkHelper.AddBranchFeatureToBranch(weir, branch, cs1.Offset); IDiscretization computationalGrid = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(computationalGrid, network, false, false, 1.0 ,false, 1.0, true, false, 0.0); Assert.AreEqual( new INetworkLocation[] { new NetworkLocation(branch, 0), new NetworkLocation(branch, 115), new NetworkLocation(branch, branch.Length) }, computationalGrid.Locations.Values); } /// <summary> /// Creates a simple test network of 1 branch amd 2 nodes. The branch has '3' parts, in the center of /// the first aand last is a cross section. /// n /// / /// / /// cs /// / /// -------/ /// / /// cs /// / /// n /// </summary> /// <returns></returns> private static IHydroNetwork CreateTestNetwork() { var network = new Hydro.HydroNetwork(); var branch1 = new Channel { Geometry = new LineString(new[] { new Coordinate(0, 0), new Coordinate(30, 40), new Coordinate(70, 40), new Coordinate(100, 100) }) }; var node1 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(0, 0)) }; var node2 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(100, 100)) }; network.Branches.Add(branch1); network.Nodes.Add(node1); network.Nodes.Add(node2); var crossSection1 = new CrossSectionDefinitionXYZ { Geometry = new LineString(new[] { new Coordinate(15, 20), new Coordinate(16, 20) }) }; double offset1 = Math.Sqrt(15 * 15 + 20 * 20); var crossSectionBranchFeature1 = new CrossSection(crossSection1) {Offset = offset1}; var crossSection2 = new CrossSectionDefinitionXYZ { Geometry = new LineString(new[] { new Coordinate(85, 70), new Coordinate(86, 70) }) }; double offset2 = Math.Sqrt(30 * 30 + 40 * 40) + 40 + Math.Sqrt(15 * 15 + 20 * 20); var crossSectionBranchFeature2 = new CrossSection(crossSection2) { Offset = offset2 }; branch1.Source = node1; branch1.Target = node2; NetworkHelper.AddBranchFeatureToBranch(crossSectionBranchFeature1, branch1, crossSectionBranchFeature1.Offset); NetworkHelper.AddBranchFeatureToBranch(crossSectionBranchFeature2, branch1, crossSectionBranchFeature2.Offset); return network; } /// <summary> /// Creates the testnetwork, inserts a node and test if it added correctly. /// </summary> [Test] [Category(TestCategory.Integration)] public void SplitBranchIn2() { IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); branch1.Name = "branch1"; branch1.LongName = "maas"; double length = branch1.Geometry.Length; int nodesCount = network.Nodes.Count; IHydroNode hydroNode = HydroNetworkHelper.SplitChannelAtNode(branch1, length / 2); Assert.AreEqual(nodesCount + 1, network.Nodes.Count); Assert.AreNotEqual(-1, network.Nodes.IndexOf(hydroNode)); Assert.AreEqual("branch1_A",branch1.Name); Assert.AreEqual("maas_A", branch1.LongName); var branch2 = network.Channels.ElementAt(1); Assert.AreEqual("branch1_B", branch2.Name); Assert.AreEqual("maas_B", branch2.LongName); Assert.AreEqual(0, hydroNode.Geometry.Coordinate.Z); } [Test] public void SplitBranchAndRemoveNode() { // related to TOOLS-3665 : Insert nodes and remove changes nodetype to incorrect type var network = CreateTestNetwork(); var leftBranch = network.Channels.First(); var startNode = leftBranch.Source; Assert.IsTrue(startNode.IsBoundaryNode); var endNode = leftBranch.Target; Assert.IsTrue(endNode.IsBoundaryNode); var insertdeNode = HydroNetworkHelper.SplitChannelAtNode(leftBranch, leftBranch.Geometry.Length / 2); Assert.IsTrue(startNode.IsBoundaryNode); Assert.IsFalse(insertdeNode.IsBoundaryNode); Assert.IsTrue(endNode.IsBoundaryNode); NetworkHelper.MergeNodeBranches(insertdeNode, network); Assert.IsTrue(startNode.IsBoundaryNode); // would fail for TOOLS-3665 Assert.IsTrue(endNode.IsBoundaryNode); } [Test] [Category(TestCategory.Integration)] public void SplitBranchDoesNotCreateANaNInBranchGeometry() { //relates to issue 2477 IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); double length = branch1.Geometry.Length; int nodesCount = network.Nodes.Count; IHydroNode hydroNode = HydroNetworkHelper.SplitChannelAtNode(branch1, length / 2); Assert.AreEqual(nodesCount + 1, network.Nodes.Count); Assert.AreNotEqual(-1, network.Nodes.IndexOf(hydroNode)); //the network should not contain branches with coordinates as NaN (messes up wkbwriter ) Assert.IsFalse(network.Branches.Any(b => b.Geometry.Coordinates.Any(c => double.IsNaN(c.Z)))); } /// <summary> /// Creates the testnetwork, adds a route and split the branch. /// TOOLS-1199 collection changed events caused recreating routing network triggered /// by changing of geometry of branch (removeunused nodes) and temporarily invalid network. /// </summary> [Test] [Category(TestCategory.Integration)] public void SplitBranchWithRouteIn2() { IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); double length = branch1.Geometry.Length; NetworkCoverage route = new Route { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; route.Locations.Values.Add(new NetworkLocation(branch1, length / 12)); route.Locations.Values.Add(new NetworkLocation(branch1, length / 8)); int nodesCount = network.Nodes.Count; IHydroNode hydroNode = HydroNetworkHelper.SplitChannelAtNode(branch1, length / 2); Assert.AreEqual(nodesCount + 1, network.Nodes.Count); Assert.AreNotEqual(-1, network.Nodes.IndexOf(hydroNode)); Assert.AreEqual(2, route.Locations.Values.Count); Assert.AreEqual(1, route.Segments.Values.Count); } /// <summary> /// Split the test network in the center. /// </summary> [Test] public void SplitCustomLengthBranchWithCrossSections() { IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); branch1.IsLengthCustom = true; double length = branch1.Geometry.Length; HydroNetworkHelper.SplitChannelAtNode(branch1, new Coordinate(50, 40)); double offset1 = Math.Sqrt(15 * 15 + 20 * 20); double offset2 = Math.Sqrt(30 * 30 + 40 * 40) + 40 + Math.Sqrt(15 * 15 + 20 * 20); double length1 = Math.Sqrt(30 * 30 + 40 * 40) + 20; double length2 = 20 + Math.Sqrt(30 * 30 + 60 * 60); Assert.AreEqual(length, length1 + length2); Assert.AreEqual(2, network.Branches.Count); var branch2 = network.Channels.Skip(1).First(); Assert.AreEqual(3, network.Nodes.Count); Assert.AreEqual(1, network.Nodes[0].OutgoingBranches.Count); Assert.AreEqual(1, network.Nodes[1].IncomingBranches.Count); Assert.AreEqual(1, network.Nodes[2].IncomingBranches.Count); Assert.AreEqual(1, network.Nodes[2].OutgoingBranches.Count); Assert.AreEqual(2, network.CrossSections.Count()); Assert.AreEqual(1, branch1.CrossSections.Count()); Assert.AreEqual(1, branch2.CrossSections.Count()); Assert.AreEqual(offset1, branch1.CrossSections.First().Offset); Assert.AreEqual(length1, branch1.Geometry.Length); Assert.AreEqual(offset2 - length1, branch2.CrossSections.First().Offset); Assert.AreEqual(length2, branch2.Geometry.Length); Assert.AreEqual(branch1, branch1.CrossSections.First().Branch); Assert.AreEqual(branch2, branch2.CrossSections.First().Branch); } /// <summary> /// Split the test network in the center. /// </summary> [Test] public void SplitBranchWithCrossSections() { IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); double length = branch1.Geometry.Length; HydroNetworkHelper.SplitChannelAtNode(branch1, new Coordinate(50, 40)); double offset1 = Math.Sqrt(15 * 15 + 20 * 20); double offset2 = Math.Sqrt(30 * 30 + 40 * 40) + 40 + Math.Sqrt(15 * 15 + 20 * 20); double length1 = Math.Sqrt(30 * 30 + 40 * 40) + 20; double length2 = 20 + Math.Sqrt(30 * 30 + 60 * 60); Assert.AreEqual(length, length1 + length2); Assert.AreEqual(2, network.Branches.Count); var branch2 = network.Channels.Skip(1).First(); Assert.AreEqual(3, network.Nodes.Count); Assert.AreEqual(1, network.Nodes[0].OutgoingBranches.Count); Assert.AreEqual(1, network.Nodes[1].IncomingBranches.Count); Assert.AreEqual(1, network.Nodes[2].IncomingBranches.Count); Assert.AreEqual(1, network.Nodes[2].OutgoingBranches.Count); Assert.AreEqual(2, network.CrossSections.Count()); Assert.AreEqual(1, branch1.CrossSections.Count()); Assert.AreEqual(1, branch2.CrossSections.Count()); Assert.AreEqual(offset1, branch1.CrossSections.First().Offset); Assert.AreEqual(length1, branch1.Geometry.Length); Assert.AreEqual(offset2 - length1, branch2.CrossSections.First().Offset); Assert.AreEqual(length2, branch2.Geometry.Length); Assert.AreEqual(branch1, branch1.CrossSections.First().Branch); Assert.AreEqual(branch2, branch2.CrossSections.First().Branch); } /// <summary> /// split at begin or end of branch should not work /// split on chainage = branch.length or 0 returns null /// </summary> [Test] public void SplitBranchOnExistingNodeShouldNotWork() { IHydroNetwork network = CreateTestNetwork(); var numberOfChannels = network.Channels.Count(); var branch1 = network.Channels.First(); double length = branch1.Geometry.Length; var result = HydroNetworkHelper.SplitChannelAtNode(branch1, length); Assert.IsNull(result); Assert.AreEqual(numberOfChannels, network.Channels.Count()); } [Test] public void CreateNetworkCoverageSegments() { IHydroNetwork network = CreateTestNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; var branch1 = network.Channels.First(); var length = branch1.Geometry.Length; HydroNetworkHelper.GenerateDiscretization(networkCoverage, branch1, new[] { 0.0, length / 3, 2 * length / 3, length }); Assert.AreEqual(4, networkCoverage.Locations.Values.Count); Assert.AreEqual(3, networkCoverage.Segments.Values.Count); Assert.AreEqual(0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(2 * length / 3, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(length, networkCoverage.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(0, networkCoverage.Segments.Values[0].Offset, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[0].EndOffset, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[0].Length, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[1].Offset, 1.0e-6); Assert.AreEqual(2 * length / 3, networkCoverage.Segments.Values[1].EndOffset, 1.0e-6); Assert.AreEqual(2 * length / 3, networkCoverage.Segments.Values[2].Offset, 1.0e-6); Assert.AreEqual(length, networkCoverage.Segments.Values[2].EndOffset, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[0].Length, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[1].Length, 1.0e-6); Assert.AreEqual(length / 3, networkCoverage.Segments.Values[2].Length, 1.0e-6); } [Test] public void CreateSegementsAndIgnoreFor1Channel() { var network = new HydroNetwork(); var channel1 = new Channel { Geometry = new LineString(new[] { new Coordinate(0, 0), new Coordinate(100, 0) }) }; var channel2 = new Channel { Geometry = new LineString(new[] { new Coordinate(100, 0), new Coordinate(200, 0) }) }; var node1 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(0, 0)) }; var node2 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(100, 0)) }; var node3 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(200, 0)) }; network.Branches.Add(channel1); network.Branches.Add(channel2); network.Nodes.Add(node1); network.Nodes.Add(node2); network.Nodes.Add(node3); channel1.Source = node1; channel1.Target = node2; channel2.Source = node2; channel2.Target = node3; var discretization = new Discretization { Network = network }; HydroNetworkHelper.GenerateDiscretization(discretization, network, true, false, 100.0, false, 0.0, false, true, 20.0, null); // 6 + 6 Assert.AreEqual(12, discretization.Locations.Values.Count); HydroNetworkHelper.GenerateDiscretization(discretization, network, true, false, 100.0, false, 0.0, false, true, 10.0, new List<IChannel> { channel2 }); // 11 + 6 Assert.AreEqual(17, discretization.Locations.Values.Count); HydroNetworkHelper.GenerateDiscretization(discretization, network, true, false, 100.0, false, 0.0, false, true, 10.0, new List<IChannel> { channel1 }); // 11 + 11 Assert.AreEqual(22, discretization.Locations.Values.Count); } /// <summary> /// Creates the testnetwork, adds 3 branch segments and splits the branch in 2. /// </summary> [Test] public void SplitBranchWithBranchSegments() { IHydroNetwork network = CreateTestNetwork(); var branch1 = network.Channels.First(); double length = branch1.Geometry.Length; // see also test GenerateDiscretization INetworkCoverage networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocationsFullyCovered }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, branch1, new[] { 0.0, length / 3, 2 * length / 3, length }); HydroNetworkHelper.SplitChannelAtNode(branch1, length / 2); var branch2 = network.Channels.Skip(1).First(); //4 segments are craeted...2 on branch 1 and 2 on branch 2 Assert.AreEqual(4, networkCoverage.Segments.Values.Count); Assert.AreEqual(2, networkCoverage.Segments.Values.Where(s => s.Branch == branch1).Count()); Assert.AreEqual(2, networkCoverage.Segments.Values.Where(s => s.Branch == branch2).Count()); } /// <summary> /// Creates the testnetwork, splits the branch in 2 and merges them again. /// </summary> [Test] public void MergeBranchWithCrossSections() { var network = CreateTestNetwork(); var branch1 = network.Channels.First(); var offset1 = Math.Sqrt(15 * 15 + 20 * 20); var offset2 = Math.Sqrt(30 * 30 + 40 * 40) + 40 + Math.Sqrt(15 * 15 + 20 * 20); var length1 = Math.Sqrt(30 * 30 + 40 * 40) + 20; var length2 = 20 + Math.Sqrt(30 * 30 + 60 * 60); var node = HydroNetworkHelper.SplitChannelAtNode(branch1, new Coordinate(50, 40)); // remove the newly added node NetworkHelper.MergeNodeBranches(node, network); Assert.AreEqual(1, network.Branches.Count); Assert.AreEqual(2, network.Nodes.Count); Assert.AreEqual(2, network.CrossSections.Count()); Assert.AreEqual(2, branch1.CrossSections.Count()); Assert.AreEqual(offset1, branch1.CrossSections.First().Offset); Assert.AreEqual(offset2, branch1.CrossSections.Skip(1).First().Offset); Assert.AreEqual(length1 + length2, branch1.Geometry.Length); Assert.AreEqual(branch1, branch1.CrossSections.First().Branch); Assert.AreEqual(branch1, branch1.CrossSections.Skip(1).First().Branch); } [Test] public void ReverseBranchWithCrossSections() { var network = CreateTestNetwork(); var branch1 = (IChannel)network.Branches[0]; var nodeFrom = branch1.Source; var nodeTo = branch1.Target; double offsetCrossSection1 = branch1.CrossSections.First().Offset; double offsetCrossSection2 = branch1.CrossSections.Skip(1).First().Offset; double length = branch1.Geometry.Length; HydroNetworkHelper.ReverseBranch(branch1); Assert.AreEqual(nodeFrom, branch1.Target); Assert.AreEqual(nodeTo, branch1.Source); Assert.AreEqual(length - offsetCrossSection2, branch1.CrossSections.First().Offset); Assert.AreEqual(length - offsetCrossSection1, branch1.CrossSections.Skip(1).First().Offset); } /// <summary> /// Creates a simple test network of 1 branch amd 2 nodes. The branch has '3' parts, in the center of /// the first aand last is a cross section. /// n /// / /// / /// cs /// / /// -------/ /// / /// cs /// / /// n /// </summary> /// <returns></returns> private static IHydroNetwork CreateSegmentTestNetwork() { var network = new Hydro.HydroNetwork(); var branch1 = new Channel { Geometry = new LineString(new[] { new Coordinate(0, 0), new Coordinate(0, 100), }) }; var node1 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(0, 0)) }; var node2 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(100, 0)) }; network.Branches.Add(branch1); network.Nodes.Add(node1); network.Nodes.Add(node2); branch1.Source = node1; branch1.Target = node2; return network; } private static void AddTestStructureAt(IHydroNetwork network, IChannel branch, double offset) { IWeir weir = new Weir { Offset = offset }; CompositeBranchStructure compositeBranchStructure = new CompositeBranchStructure { Network = network, Geometry = new Point(offset, 0), Offset = offset }; compositeBranchStructure.Structures.Add(weir); branch.BranchFeatures.Add(compositeBranchStructure); } private static void AddTestCrossSectionAt(IHydroNetwork network, IChannel branch, double offset) { var crossSectionXyz = new CrossSectionDefinitionXYZ { Geometry = new LineString(new[] { new Coordinate(offset - 1, 0), new Coordinate(offset + 1, 0) }) }; HydroNetworkHelper.AddCrossSectionDefinitionToBranch(branch, crossSectionXyz, offset); } [Test] public void CreateSegments1Structure() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 10); var networkCoverage = new Discretization { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(4, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(9.5, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(10.5, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[3].Offset, 1.0e-6); } [Test] public void CreateSegmentsMultipleStructures() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 20); AddTestStructureAt(network, branch1, 40); AddTestStructureAt(network, branch1, 60); var networkCoverage = new Discretization { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(8, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(19.5, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(20.5, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(39.5, networkCoverage.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(40.5, networkCoverage.Locations.Values[4].Offset, 1.0e-6); Assert.AreEqual(59.5, networkCoverage.Locations.Values[5].Offset, 1.0e-6); Assert.AreEqual(60.5, networkCoverage.Locations.Values[6].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[7].Offset, 1.0e-6); } [Test] public void CreateSegments1StructureAtMinimumBeginBranch() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 0.4); var networkCoverage = new Discretization { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // structure at less than minimumdistance; expect 1 point left out // [---------------------- // 0.4 // x x ----------------------------- x // 0 0.9 100 Assert.AreEqual(3, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(0.9, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); } [Test] public void CreateSegments1StructureAtNearMinimumBeginBranch() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 0.8); var networkCoverage = new Discretization { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // structure at near minimumdistance; expect point centered at 0.8 - 0.5 = 0.3 not created // [---------------------- // 0.8 // x x x ----------------------------- x // 0 (0.3) 1.3 100 // ^ Assert.AreEqual(3, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(1.3, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); } [Test] public void CreateSegments2StructureAtNearMinimumBeginBranch() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 0.8); AddTestStructureAt(network, branch1, 1.2); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.001, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // structure at near minimumdistance; expect 1 point centered at first segment // [---------------------- // 0.8 1.2 // x x x x ------------------ x // 0 0.3 1.0 1.7 100 // ^ Assert.AreEqual(5, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(0.3, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(1.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(1.7, networkCoverage.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[4].Offset, 1.0e-6); // repeat with minimumDistance set to 0.5 HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // expect gridpoints at 0.3 eliminated Assert.AreEqual(4, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(1.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(1.7, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[3].Offset, 1.0e-6); } [Test] public void CreateSegments1StructureAtMinimumEndBranch() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 99.6); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // structure at less than minimumdistance; expect 1 point left out // [-----------------------------------------------------] // 99.6 // x-------------------------------------------x-----(x)--- x // 0 99.1 (99.8) 100 Assert.AreEqual(3, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(99.1, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); } [Test] public void CreateSegments2StructureAtNearMinimumEndBranch() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestStructureAt(network, branch1, 99.2); AddTestStructureAt(network, branch1, 98.8); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance true, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // structure at near minimumdistance; expect 1 point centered at first segment // structure at less than minimumdistance; expect 1 point left out // [-----------------------------------------------------------] // 98.8 99.2 // x----------------------------------------x-------x------x---x // 0 98.3 99 (99.6) 100 Assert.AreEqual(4, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(98.3, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(99.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); //Assert.AreEqual(99.6, networkCoverage.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[3].Offset, 1.0e-6); } [Test] public void CreateSegmentsCrossSection() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestCrossSectionAt(network, branch1, 50.0); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 0.5, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(3, networkCoverage.Locations.Values.Count); Assert.AreEqual(50.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); } [Test] public void CreateSegmentsFixedLocations() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); var discretization = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 0.5, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection true, // gridAtFixedLength 10); // fixedLength Assert.AreEqual(11, discretization.Locations.Values.Count); Assert.AreEqual(0.0, discretization.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(50.0, discretization.Locations.Values[5].Offset, 1.0e-6); Assert.AreEqual(100.0, discretization.Locations.Values[10].Offset, 1.0e-6); INetworkLocation networkLocation = discretization.Locations.Values[7]; Assert.AreEqual(70.0, networkLocation.Offset, 1.0e-6); discretization.ToggleFixedPoint(networkLocation); //DiscretizationHelper.SetUserDefinedGridPoint(networkLocation, true); HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 0.5, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection true, // gridAtFixedLength 40); // fixedLength // expect values at // - 0 and 100 start and end // - 70 for fixed location // - none between 70 and 100 // - (0 - 70) > 40, divide in equal parts -> 35 Assert.AreEqual(4, discretization.Locations.Values.Count); Assert.AreEqual(0.0, discretization.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(35.0, discretization.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(70.0, discretization.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(100.0, discretization.Locations.Values[3].Offset, 1.0e-6); } [Test] public void CreateSegmentsForChannelWithCustomLength() { var network = CreateTestNetwork(); IChannel firstBranch = (IChannel)network.Branches[0]; var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage firstBranch, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(2, networkCoverage.Locations.Values.Count); Assert.AreEqual(1, networkCoverage.Segments.Values.Count); firstBranch.Length = firstBranch.Length * 2; firstBranch.IsLengthCustom = true; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage firstBranch, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(2, networkCoverage.Locations.Values.Count); Assert.AreEqual(1, networkCoverage.Segments.Values.Count); } [Test] public void CreateSegmentsCrossSectionAndMinimumDistance() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestCrossSectionAt(network, branch1, 1.0); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(2, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); } [Test] public void CreateSegmentsCrossSectionAndMinimumDistanceNearEnd() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); AddTestCrossSectionAt(network, branch1, 99.0); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(2, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); } [Test] public void CreateSegmentsMultipleCrossSection() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); // add multiple cross sections and generate calculation points at the cross section locations // Grid cells too smal should not be generated. AddTestCrossSectionAt(network, branch1, 10.0); AddTestCrossSectionAt(network, branch1, 20.0); AddTestCrossSectionAt(network, branch1, 30.0); AddTestCrossSectionAt(network, branch1, 40.0); AddTestCrossSectionAt(network, branch1, 50.0); AddTestCrossSectionAt(network, branch1, 60.0); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(8, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(10.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(20.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(30.0, networkCoverage.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(40.0, networkCoverage.Locations.Values[4].Offset, 1.0e-6); Assert.AreEqual(50.0, networkCoverage.Locations.Values[5].Offset, 1.0e-6); Assert.AreEqual(60.0, networkCoverage.Locations.Values[6].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[7].Offset, 1.0e-6); } [Test] public void CreateSegmentsMultipleCrossSectionAndMinimumDistance() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); // add multiple cross sections and generate calculation points at the cross section locations // Grid cells too smal should not be generated. AddTestCrossSectionAt(network, branch1, 1.0); AddTestCrossSectionAt(network, branch1, 2.0); AddTestCrossSectionAt(network, branch1, 3.0); AddTestCrossSectionAt(network, branch1, 4.0); AddTestCrossSectionAt(network, branch1, 5.0); AddTestCrossSectionAt(network, branch1, 6.0); var networkCoverage = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(networkCoverage, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength Assert.AreEqual(3, networkCoverage.Locations.Values.Count); Assert.AreEqual(0.0, networkCoverage.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(5.0, networkCoverage.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(100.0, networkCoverage.Locations.Values[2].Offset, 1.0e-6); } [Test] public void CreateSegmentsMultipleCrossSectionsAndFixedPoint() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); var discretization = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection true, // gridAtFixedLength 2); // fixedLength Assert.AreEqual(51, discretization.Locations.Values.Count); INetworkLocation networkLocation = discretization.Locations.Values.Where(nl => nl.Offset == 8).First(); //DiscretizationHelper.SetUserDefinedGridPoint(networkLocation, true); discretization.ToggleFixedPoint(networkLocation); networkLocation = discretization.Locations.Values.Where(nl => nl.Offset == 32).First(); discretization.ToggleFixedPoint(networkLocation); AddTestCrossSectionAt(network, branch1, 10.0); AddTestCrossSectionAt(network, branch1, 20.0); AddTestCrossSectionAt(network, branch1, 30.0); HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // expect gridpoints at: // begin and end 0 and 100 // fixed locations 8 and 32. // 20 for the cross section, 10 and 30 should not be generated due to existing // fixed points and minimium distance 0f 5. Assert.AreEqual(5, discretization.Locations.Values.Count); Assert.AreEqual(0.0, discretization.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(8.0, discretization.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(20.0, discretization.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(32.0, discretization.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(100.0, discretization.Locations.Values[4].Offset, 1.0e-6); } [Test] public void CreateSegmentsMultipleStructuresAndFixedPoint() { IHydroNetwork network = CreateSegmentTestNetwork(); var branch1 = network.Channels.First(); var discretization = new Discretization() { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 5.0, // minimumDistance false, // gridAtStructure 0.5, // structureDistance false, // gridAtCrossSection true, // gridAtFixedLength 2); // fixedLength Assert.AreEqual(51, discretization.Locations.Values.Count); INetworkLocation networkLocation = discretization.Locations.Values.Where(nl => nl.Offset == 8).First(); //DiscretizationHelper.SetUserDefinedGridPoint(networkLocation, true); discretization.ToggleFixedPoint(networkLocation); networkLocation = discretization.Locations.Values.Where(nl => nl.Offset == 32).First(); discretization.ToggleFixedPoint(networkLocation); //DiscretizationHelper.SetUserDefinedGridPoint(networkLocation, true); AddTestStructureAt(network, branch1, 10.0); AddTestStructureAt(network, branch1, 20.0); AddTestStructureAt(network, branch1, 30.0); HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage branch1, // branch 6.0, // minimumDistance true, // gridAtStructure 4.0, // structureDistance false, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // expect gridpoints with no minimumDistance // 0 8 (6 14) (16 24) (26 34) 32 100 // 0 6 8 14 16 24 26 32 34 100 // 10 20 30 // structure locations // 0 8 14 24 32 100 // result // fixed locations 8 and 32. // first structure (6) and 14 // second structure 16 and 24; 16 will be merged into 14 -> 15 // third structure 26 and (34); 26 will be merged into 24 -> 25 // fixed points and minimium distance 0f 5. Assert.AreEqual(6, discretization.Locations.Values.Count); Assert.AreEqual(0.0, discretization.Locations.Values[0].Offset, 1.0e-6); Assert.AreEqual(8.0, discretization.Locations.Values[1].Offset, 1.0e-6); Assert.AreEqual(15.0, discretization.Locations.Values[2].Offset, 1.0e-6); Assert.AreEqual(25.0, discretization.Locations.Values[3].Offset, 1.0e-6); Assert.AreEqual(32.0, discretization.Locations.Values[4].Offset, 1.0e-6); Assert.AreEqual(100.0, discretization.Locations.Values[5].Offset, 1.0e-6); } /// <summary> /// Test for Jira Issue 2213. Grid points at channel Ovk98 are to close connected. /// grid points generated at: /// (OVK98, 0) /// (OVK98, 0.9999) /// (OVK98, 227.6) /// (OVK98, 229.6) /// (OVK98, 241.4) /// (OVK98, 241.5) /// (OVK98, 243.4) /// (OVK98, 243.4) /// (OVK98, 595) /// (OVK98, 597) /// (OVK98, 730.2) /// (OVK98, 732.2) /// (OVK98, 1253) /// (OVK98, 1255) /// (OVK98, 1260.51113164371) /// (OVK98, 1261.51114183887) /// settings at structure and crosssection /// 1m before and after structure /// minimum 0.5 m. /// thus point at 241.4, 241.5 and 243.4, 243.4 should either be merged or eliminated. /// </summary> [Test] public void JiraTools2213Ovk98() { var network = new HydroNetwork(); var channel = new Channel { Geometry = new LineString(new[] { new Coordinate(0, 0), new Coordinate(1262.0, 0), }) }; var node1 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(0, 0)) }; var node2 = new HydroNode { Network = network, Geometry = new Point(new Coordinate(1262.0, 0)) }; network.Branches.Add(channel); network.Nodes.Add(node1); network.Nodes.Add(node2); channel.Source = node1; channel.Target = node2; AddCrossSection(channel, 1.0); AddCrossSection(channel, 241.47); AddCrossSection(channel, 243.44); AddCrossSection(channel, 1260.51); AddTestStructureAt(network, channel, 228.61); AddTestStructureAt(network, channel, 242.42); AddTestStructureAt(network, channel, 596.01); AddTestStructureAt(network, channel, 731.25); AddTestStructureAt(network, channel, 1253.95); var discretization = new Discretization { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; HydroNetworkHelper.GenerateDiscretization(discretization, // networkCoverage channel, // branch 0.5, // minimumDistance true, // gridAtStructure 1.0, // structureDistance true, // gridAtCrossSection false, // gridAtFixedLength -1); // fixedLength // expected at: // 0: 0 = start channel // 1: 1 = cross section // 2: 227.61 = 1 m before struct // 3: 229.61 = 1 m after struct // 4: 241.42 = 1 m before struct // 5: 243.42 = 1 m after struct // 6: 595.01 = 1 m before struct // 7: 597.01 = 1 m after struct // 8: 730.25 = 1 m before struct // 9: 732.25 = 1 m after struct // 10: 1252.95 = 1 m before struct // 11: 1254.95 = 1 m after struct // 12: 1260.51 = cross section // 13: 1262 = length channel // = skipped cross sections at 241.47 and 243.44 var gridPoints = discretization.Locations.Values; Assert.AreEqual(14, gridPoints.Count); Assert.AreEqual(0.0, gridPoints[0].Offset, 1.0e-5); Assert.AreEqual(1.0, gridPoints[1].Offset, 1.0e-5); Assert.AreEqual(227.61, gridPoints[2].Offset, 1.0e-5); Assert.AreEqual(229.61, gridPoints[3].Offset, 1.0e-5); Assert.AreEqual(241.42, gridPoints[4].Offset, 1.0e-5); Assert.AreEqual(243.42, gridPoints[5].Offset, 1.0e-5); Assert.AreEqual(595.01, gridPoints[6].Offset, 1.0e-5); Assert.AreEqual(597.01, gridPoints[7].Offset, 1.0e-5); Assert.AreEqual(730.25, gridPoints[8].Offset, 1.0e-5); Assert.AreEqual(732.25, gridPoints[9].Offset, 1.0e-5); Assert.AreEqual(1252.95, gridPoints[10].Offset, 1.0e-5); Assert.AreEqual(1254.95, gridPoints[11].Offset, 1.0e-5); Assert.AreEqual(1260.51, gridPoints[12].Offset, 1.0e-5); Assert.AreEqual(1262, gridPoints[13].Offset, 1.0e-5); } private static void AddCrossSection(Channel branch, double chainage) { var crossSection = new CrossSectionDefinitionXYZ { Geometry = new LineString(new[] { new Coordinate(chainage, 0), new Coordinate(chainage + 1, 0) }), }; HydroNetworkHelper.AddCrossSectionDefinitionToBranch(branch, crossSection, chainage); } [Test] public void SendCustomActionForSplitBranch() { var network = HydroNetworkHelper.GetSnakeHydroNetwork(new Point(0, 0), new Point(0, 100)); int callCount = 0; IChannel channelToSplit = network.Channels.First(); ((INotifyPropertyChange)network).PropertyChanged += (s, e) => { //finished editing if ((e.PropertyName == "IsEditing") && (!network.IsEditing)) { callCount++; var editAction = (BranchSplitAction) network.CurrentEditAction; Assert.AreEqual(channelToSplit, editAction.SplittedBranch); Assert.AreEqual(50, editAction.SplittedBranch.Length); Assert.AreEqual( network.Channels.ElementAt(1), editAction.NewBranch); } }; HydroNetworkHelper.SplitChannelAtNode(channelToSplit, 50); Assert.AreEqual(1, callCount); } } }
using System.Collections.Generic; using System.Security.Claims; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using WebStore.Controllers; using WebStore.DomainNew.Dto; using WebStore.DomainNew.ViewModels; using WebStore.Interfaces; using Xunit; namespace WebStore.Tests { public class CartControllerTests { private readonly CartController _cartController; private readonly Mock<ICartService> _mockCartService; private readonly Mock<IOrderService> _mockOrderService; public CartControllerTests() { _mockCartService = new Mock<ICartService>(); _mockOrderService = new Mock<IOrderService>(); _cartController = new CartController( _mockCartService.Object, _mockOrderService.Object); } [Fact] public void CheckoutModelStateInvalidModelStateReturnsViewModel() { _cartController.ModelState .AddModelError("error", "Invalid Model"); var result = _cartController.Checkout(new OrderViewModel { Name = "test" }); var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsAssignableFrom<OrderDetailsViewModel>( viewResult.Model); Assert.Equal("test", model.OrderViewModel.Name); } [Fact] public void CheckoutCallsServiceAndReturnRedirect() { var user = new ClaimsPrincipal(new ClaimsIdentity( new[] { new Claim(ClaimTypes.NameIdentifier, "1") })); _mockCartService .Setup(c => c.TransformCart()) .Returns(new CartViewModel { Items = new Dictionary<ProductViewModel, int> { {new ProductViewModel(), 1} } }); _mockOrderService .Setup(o => o.CreateOrder(It.IsAny<CreateOrderDto>(), It.IsAny<string>())) .Returns(new OrderDto { Id = 1 }); _cartController.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = user } }; var result = _cartController.Checkout(new OrderViewModel { Name = "test", Address = "", Phone = "" }); var redirectResult = Assert.IsType<RedirectToActionResult>(result); Assert.Null(redirectResult.ControllerName); Assert.Equal("OrderConfirmed", redirectResult.ActionName); Assert.Equal(1, redirectResult.RouteValues["id"]); } } }
//namespace Uintra.Infrastructure.Providers //{ // public interface IXPathProvider // { // string UserTagFolderXPath { get; } // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using com.Sconit.Entity.Exception; using com.Sconit.Utility; using Telerik.Web.Mvc; using com.Sconit.Web.Models; using com.Sconit.Entity.INV; using com.Sconit.Entity.VIEW; using com.Sconit.Entity.SCM; using com.Sconit.Service; using com.Sconit.Entity.MD; using com.Sconit.Entity.ORD; using com.Sconit.PrintModel.INV; using AutoMapper; using com.Sconit.Utility.Report; using System.Data.SqlClient; using System.Data; using com.Sconit.Entity.SYS; using NHibernate; using com.Sconit.Web.Models.SearchModels.WMS; using com.Sconit.Entity.WMS; namespace com.Sconit.Web.Controllers.WMS { public class DeliveryBarCodeController : WebAppBaseController { private static string selectCountStatement = "select count(*) from DeliveryBarCode as h"; private static string selectStatement = "select h from DeliveryBarCode as h"; public IDeliveryBarCodeMgr deliveryBarCodeMgr { get; set; } #region public method #region search [SconitAuthorize(Permissions = "Url_DeliveryBarCode_View")] public ActionResult Index() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_DeliveryBarCode_View")] public ActionResult List(GridCommand command, DeliveryBarCodeSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel); ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_DeliveryBarCode_View")] public ActionResult _AjaxList(GridCommand command, DeliveryBarCodeSearchModel searchModel) { SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); return PartialView(GetAjaxPageData<DeliveryBarCode>(searchStatementModel, command)); } #endregion #region new [SconitAuthorize(Permissions = "Url_DeliveryBarCode_New")] public ActionResult New() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_DeliveryBarCode_New")] public ActionResult _ShipPlanList(GridCommand command, string flow) { ViewBag.flow = flow; return PartialView(); } [GridAction] [SconitAuthorize(Permissions = "Url_DeliveryBarCode_New")] public ActionResult _AjaxShipPlanList(string flow) { IList<ShipPlan> shipPlanList = new List<ShipPlan>(); if (!string.IsNullOrEmpty(flow)) { string shipPlanSql = "select s from ShipPlan as s where s.Flow = ? and s.IsActive = ?"; shipPlanList = genericMgr.FindAll<ShipPlan>(shipPlanSql, new object[] { flow, true }); } return View(new GridModel(shipPlanList)); } [SconitAuthorize(Permissions = "Url_DeliveryBarCode_New")] public ActionResult CreateDeliveryBarCode(string idStr, string qtyStr) { try { IList<ShipPlan> shipPlanList = new List<ShipPlan>(); if (!string.IsNullOrEmpty(idStr)) { string[] idArray = idStr.Split(','); string[] qtyArray = qtyStr.Split(','); for (int i = 0; i < idArray.Count(); i++) { ShipPlan sp = genericMgr.FindById<ShipPlan>(Convert.ToInt32(idArray[i])); sp.ToDeliveryBarCodeQty = Convert.ToDecimal(qtyArray[i]); shipPlanList.Add(sp); } } IList<DeliveryBarCode> deliveryBarCodeList = deliveryBarCodeMgr.CreateDeliveryBarCode(shipPlanList); IList<object> data = new List<object>(); data.Add(deliveryBarCodeList); data.Add(CurrentUser.FullName); var barCodeTemplate = this.systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.DefaultDeliveryBarCodeTemplate); string printUrl = reportGen.WriteToFile(barCodeTemplate, data); object obj = new { SuccessMessage = Resources.WMS.DeliveryBarCode.DeliveryBarcodePrintedSuccessfully, PrintUrl = printUrl }; return Json(obj); } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.GetMessages()[0].GetMessageString()); return Json(null); } } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_DeliveryBarCode_New")] public JsonResult PrintDeliveryBarCodeList(string checkedbarCodes) { string[] checkedBarCodeArray = checkedbarCodes.Split(','); string dbcSql = string.Empty; IList<object> selectPartyPara = new List<object>(); foreach (var para in checkedBarCodeArray) { if (dbcSql == string.Empty) { dbcSql = "from DeliveryBarCode where BarCode in (?"; } else { dbcSql += ",?"; } selectPartyPara.Add(para); } dbcSql += ")"; IList<DeliveryBarCode> deliveryBarCodeList = genericMgr.FindAll<DeliveryBarCode>(dbcSql, selectPartyPara.ToArray()); var barCodeTemplate = this.systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.DefaultDeliveryBarCodeTemplate); IList<object> data = new List<object>(); data.Add(deliveryBarCodeList); data.Add(CurrentUser.FullName); string reportFileUrl = reportGen.WriteToFile(barCodeTemplate, data); object obj = new { SuccessMessage = Resources.WMS.DeliveryBarCode.DeliveryBarcodePrintedSuccessfully, PrintUrl = reportFileUrl }; return Json(obj); } #endregion #endregion #region private method private SearchStatementModel PrepareSearchStatement(GridCommand command, DeliveryBarCodeSearchModel searchModel) { string whereStatement = string.Empty; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("BarCode", searchModel.BarCode, HqlStatementHelper.LikeMatchMode.Anywhere, "h", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("CreateUserName", searchModel.CreateUserName, HqlStatementHelper.LikeMatchMode.Start, "h", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "h", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Flow", searchModel.Flow, "h", ref whereStatement, param); if (searchModel.StartDate != null & searchModel.EndDate == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartDate, "h", ref whereStatement, param); } if (searchModel.EndDate != null) { HqlStatementHelper.AddLtStatement("CreateDate", searchModel.EndDate.Value.AddDays(1), "h", ref whereStatement, param); } string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); if (command.SortDescriptors.Count == 0) { sortingStatement = " order by CreateDate desc"; } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } #endregion #region private #endregion } }
using UnityEngine; using System.Collections; public class ZoneListController : MonoBehaviour { public static string s_zoneListURL = ""; // Use this for initialization void Start () { Debug.Log("zone list controller start"); StartCoroutine(LoadZoneList()); } private IEnumerator LoadZoneList() { /*WWW w = new WWW(s_zoneListURL); yield return w; if(!string.IsNullOrEmpty(w.error)) { Debug.LogError("www load zone list failed:" + w.error); } w.Dispose(); w = null; */ yield return new WaitForSeconds(0.5f); //NetController.Instance.ServerIP = "121.199.48.63"; //NetController.Instance.ServerPort = 8888; //NetController.Instance.ServerIP = "119.15.139.149"; //NetController.Instance.ServerPort = 4444; ShowLoginBtn(); } private void ShowLoginBtn() { GameObject loginBtnPrefab = ABManager.get(AppConst.AB_LOGIN).LoadAsset ("login_btn") as GameObject; if (null == loginBtnPrefab) { Debug.LogError("ShowLoginBtn failed,loginBtnPrefab load failed"); return; } GameObject loginBtnGo = GameObject.Instantiate (loginBtnPrefab); loginBtnGo.transform.SetParent(CSBridge.s_uiRoot, false); //loginBtnGo.transform.localPosition = new Vector3(0f, -425f, 0f); //loginBtnGo.transform.localScale = new Vector3(1f, 1f, 1f); Destroy(this.gameObject); //BGMController btm = BGMController.Instance; } public void OnDestroy() { Debug.Log("zone list controller destroy"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entities.Common { public interface IBaseEntity { } public abstract class BaseEntity<T>:IBaseEntity { public T Id { get; set; } } public abstract class BaseEntity:BaseEntity<int> { } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AutoFixture; using FluentAssertions; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Moq; using Newtonsoft.Json; using NUnit.Framework; using SFA.DAS.Authorization.Services; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Api.Types.Requests; using SFA.DAS.CommitmentsV2.Api.Types.Responses; using SFA.DAS.CommitmentsV2.Api.Types.Validation; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.CommitmentsV2.Shared.Models; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.Encoding; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.DraftApprenticeship; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Queries.GetTrainingCourses; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderCommitments.Web.Models; using SFA.DAS.ProviderUrlHelper; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.DraftApprenticeshipControllerTests { public class DraftApprenticeshipControllerTestFixture { private readonly GetDraftApprenticeshipResponse _draftApprenticeshipDetails; private readonly DraftApprenticeshipRequest _draftApprenticeshipRequest; private readonly GetCohortResponse _cohortResponse; private readonly DraftApprenticeshipController _controller; private readonly GetTrainingCoursesQueryResponse _courseResponse; private readonly Mock<IMediator> _mediator; private readonly Mock<IModelMapper> _modelMapper; private readonly Mock<ICommitmentsApiClient> _commitmentsApiClient; private readonly Mock<IAuthorizationService> _providerFeatureToggle; private readonly Mock<ILinkGenerator> _linkGenerator; private readonly AddDraftApprenticeshipViewModel _addModel; private readonly SelectCourseViewModel _selectCourseViewModel; private readonly EditDraftApprenticeshipViewModel _editModel; private readonly AddDraftApprenticeshipApimRequest _createAddDraftApprenticeshipRequest; private readonly UpdateDraftApprenticeshipApimRequest _updateDraftApprenticeshipRequest; private readonly ReservationsAddDraftApprenticeshipRequest _reservationsAddDraftApprenticeshipRequest; private readonly GetReservationIdForAddAnotherApprenticeRequest _getReservationIdForAddAnotherApprenticeRequest; private IActionResult _actionResult; private readonly CommitmentsApiModelException _apiModelException; private readonly long _cohortId; private readonly long _draftApprenticeshipId; private readonly int _providerId; private readonly string _cohortReference; private readonly string _draftApprenticeshipHashedId; private ViewDraftApprenticeshipViewModel _viewModel; private readonly SelectOptionsRequest _selectOptionsRequest; private readonly ViewSelectOptionsViewModel _viewSelectOptionsViewModel; private readonly ViewSelectOptionsViewModel _selectOptionsViewModel; private readonly Mock<ITempDataDictionary> _tempData; private readonly Mock<IOuterApiService> _outerApiService; private ValidateUlnOverlapResult _validateUlnOverlapResult; private Infrastructure.OuterApi.Responses.ValidateUlnOverlapOnStartDateQueryResult _validateUlnOverlapOnStartDateResult; public DraftApprenticeshipControllerTestFixture() { var autoFixture = new Fixture(); _cohortId = autoFixture.Create<long>(); _draftApprenticeshipId = autoFixture.Create<long>(); _providerId = autoFixture.Create<int>(); _cohortReference = autoFixture.Create<string>(); _draftApprenticeshipHashedId = autoFixture.Create<string>(); _draftApprenticeshipRequest = autoFixture.Build<DraftApprenticeshipRequest>() .With(x => x.CohortId, _cohortId) .With(x => x.DraftApprenticeshipId, _draftApprenticeshipId) .Create(); _selectOptionsRequest = autoFixture.Build<SelectOptionsRequest>() .With(c => c.CohortId, _cohortId) .With(x => x.DraftApprenticeshipId, _draftApprenticeshipId) .Create(); _selectOptionsViewModel = autoFixture.Build<ViewSelectOptionsViewModel>() .With(c => c.CohortId, _cohortId) .With(x => x.DraftApprenticeshipId, _draftApprenticeshipId) .Create(); _draftApprenticeshipDetails = autoFixture.Build<GetDraftApprenticeshipResponse>() .With(x => x.Id, _draftApprenticeshipId) .Create(); _getReservationIdForAddAnotherApprenticeRequest = autoFixture .Build<GetReservationIdForAddAnotherApprenticeRequest>().Without(x => x.TransferSenderHashedId) .Create(); _createAddDraftApprenticeshipRequest = new AddDraftApprenticeshipApimRequest(); _updateDraftApprenticeshipRequest = new UpdateDraftApprenticeshipApimRequest(); _reservationsAddDraftApprenticeshipRequest = autoFixture.Build<ReservationsAddDraftApprenticeshipRequest>() .With(x => x.ProviderId, _providerId) .With(x => x.CohortId, _cohortId) .With(x => x.CohortReference, _cohortReference) .With(x => x.StartMonthYear, "012019") .Create(); _courseResponse = new GetTrainingCoursesQueryResponse { TrainingCourses = new TrainingProgramme[0] }; _selectCourseViewModel = new SelectCourseViewModel() { CourseCode = "123", ProviderId = _providerId, CohortId = _cohortId, CohortReference = _cohortReference, DeliveryModel = DeliveryModel.Regular, }; _addModel = new AddDraftApprenticeshipViewModel { CourseCode = "123", ProviderId = _providerId, CohortId = _cohortId, CohortReference = _cohortReference, DeliveryModel = DeliveryModel.Regular, }; _editModel = new EditDraftApprenticeshipViewModel { ProviderId = _providerId, CohortId = _cohortId, CohortReference = _cohortReference, DraftApprenticeshipId = _draftApprenticeshipId, DraftApprenticeshipHashedId = _draftApprenticeshipHashedId, DeliveryModel = DeliveryModel.Regular, }; _viewModel = new ViewDraftApprenticeshipViewModel { ProviderId = _providerId, CohortReference = _cohortReference }; _validateUlnOverlapResult = new ValidateUlnOverlapResult { HasOverlappingEndDate = false, HasOverlappingStartDate = false, ULN = "XXXX" }; _viewSelectOptionsViewModel = autoFixture.Build<ViewSelectOptionsViewModel>().Create(); _cohortResponse = autoFixture.Build<GetCohortResponse>() .With(x => x.LevyStatus, ApprenticeshipEmployerType.Levy) .With(x => x.ChangeOfPartyRequestId, default(long?)) .Create(); _apiModelException = new CommitmentsApiModelException(new List<ErrorDetail>() {new ErrorDetail("Name", "Cannot be more than...")}); _mediator = new Mock<IMediator>(); _mediator.Setup(x => x.Send(It.IsAny<GetTrainingCoursesQueryRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(_courseResponse); _modelMapper = new Mock<IModelMapper>(); _modelMapper.Setup(x => x.Map<AddDraftApprenticeshipApimRequest>(It.IsAny<AddDraftApprenticeshipViewModel>())) .ReturnsAsync(_createAddDraftApprenticeshipRequest); _modelMapper.Setup(x => x.Map<UpdateDraftApprenticeshipApimRequest>(It.IsAny<EditDraftApprenticeshipViewModel>())) .ReturnsAsync(_updateDraftApprenticeshipRequest); _modelMapper.Setup(x => x.Map<AddDraftApprenticeshipViewModel>(It.IsAny<ReservationsAddDraftApprenticeshipRequest>())) .ReturnsAsync(_addModel); _modelMapper.Setup(x => x.Map<UpdateDraftApprenticeshipApimRequest>(It.IsAny<GetDraftApprenticeshipResponse>())) .ReturnsAsync(_updateDraftApprenticeshipRequest); _modelMapper.Setup(x => x.Map<UpdateDraftApprenticeshipApimRequest>(It.IsAny<ViewSelectOptionsViewModel>())) .ReturnsAsync(_updateDraftApprenticeshipRequest); _commitmentsApiClient = new Mock<ICommitmentsApiClient>(); _commitmentsApiClient.Setup(x => x.GetCohort(It.IsAny<long>(), It.IsAny<CancellationToken>())) .ReturnsAsync(_cohortResponse); _commitmentsApiClient.Setup(x => x.ValidateUlnOverlap(It.IsAny<ValidateUlnOverlapRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(() => _validateUlnOverlapResult); _providerFeatureToggle = new Mock<IAuthorizationService>(); _providerFeatureToggle.Setup(x => x.IsAuthorized(It.IsAny<string>())).Returns(false); _tempData = new Mock<ITempDataDictionary>(); var encodingService = new Mock<IEncodingService>(); encodingService.Setup(x => x.Encode(_draftApprenticeshipId, EncodingType.ApprenticeshipId)) .Returns(_draftApprenticeshipHashedId); _outerApiService = new Mock<IOuterApiService>(); _outerApiService.Setup(x => x.ValidateUlnOverlapOnStartDate(It.IsAny<long>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(() => _validateUlnOverlapOnStartDateResult); _outerApiService.Setup( x => x.AddDraftApprenticeship(_addModel.CohortId.Value, _createAddDraftApprenticeshipRequest)) .ReturnsAsync(new Infrastructure.OuterApi.Responses.AddDraftApprenticeshipResponse { DraftApprenticeshipId = _draftApprenticeshipId }); _controller = new DraftApprenticeshipController( _mediator.Object, _commitmentsApiClient.Object, _modelMapper.Object, encodingService.Object, _providerFeatureToggle.Object, _outerApiService.Object); _controller.TempData = _tempData.Object; _linkGenerator = new Mock<ILinkGenerator>(); _linkGenerator.Setup(x => x.ReservationsLink(It.IsAny<string>())) .Returns((string url) => "http://reservations/" + url); } public DraftApprenticeshipControllerTestFixture SetupStartDateOverlap(bool overlapStartDate, bool overlapEndDate) { _validateUlnOverlapOnStartDateResult = new Infrastructure.OuterApi.Responses.ValidateUlnOverlapOnStartDateQueryResult { HasOverlapWithApprenticeshipId = 1, HasStartDateOverlap = overlapStartDate }; return this; } public DraftApprenticeshipControllerTestFixture SetupAddDraftApprenticeshipViewModelForStartDateOverlap() { _addModel.IsOnFlexiPaymentPilot = false; _addModel.StartMonth = 1; _addModel.StartYear = 2022; _addModel.EndMonth = 1; _addModel.EndYear = 2023; _addModel.Uln = "XXXX"; return this; } public DraftApprenticeshipControllerTestFixture SetupEditDraftApprenticeshipViewModelForStartDateOverlap() { _editModel.IsOnFlexiPaymentPilot = false; _editModel.StartMonth = 1; _editModel.StartYear = 2022; _editModel.EndMonth = 1; _editModel.EndYear = 2023; _editModel.Uln = "XXXX"; return this; } public async Task<DraftApprenticeshipControllerTestFixture> AddDraftApprenticeshipWithReservation() { _actionResult = await _controller.AddDraftApprenticeship(_reservationsAddDraftApprenticeshipRequest); return this; } public DraftApprenticeshipControllerTestFixture AddNewDraftApprenticeshipWithReservation() { _actionResult = _controller.AddNewDraftApprenticeship(_reservationsAddDraftApprenticeshipRequest); return this; } public DraftApprenticeshipControllerTestFixture GetReservationId(string transferSenderId = null) { if (transferSenderId != null) { _getReservationIdForAddAnotherApprenticeRequest.TransferSenderHashedId = transferSenderId; } _actionResult = _controller.GetReservationId(_getReservationIdForAddAnotherApprenticeRequest, _linkGenerator.Object); return this; } public async Task<DraftApprenticeshipControllerTestFixture> EditDraftApprenticeship() { _modelMapper.Setup(x => x.Map<IDraftApprenticeshipViewModel>(_draftApprenticeshipRequest)) .ReturnsAsync(_editModel); _actionResult = await _controller.ViewEditDraftApprenticeship(_draftApprenticeshipRequest); return this; } public async Task<DraftApprenticeshipControllerTestFixture> ViewDraftApprenticeship() { _modelMapper.Setup(x => x.Map<IDraftApprenticeshipViewModel>(_draftApprenticeshipRequest)) .ReturnsAsync(_viewModel); _actionResult = await _controller.ViewEditDraftApprenticeship(_draftApprenticeshipRequest); return this; } public DraftApprenticeshipControllerTestFixture ReturnNoMappedOptions() { _viewSelectOptionsViewModel.Options = new List<string>(); return this; } public async Task<DraftApprenticeshipControllerTestFixture> ViewStandardOptions() { _modelMapper.Setup(x => x.Map<ViewSelectOptionsViewModel>(_selectOptionsRequest)) .ReturnsAsync(_viewSelectOptionsViewModel); _actionResult = await _controller.SelectOptions(_selectOptionsRequest); return this; } public DraftApprenticeshipControllerTestFixture SetUpNoStandardSelected() { _selectCourseViewModel.CourseCode = ""; return this; } public DraftApprenticeshipControllerTestFixture SetUpFlexibleStandardSelected() { _addModel.CourseCode = "456FlexiJob"; return this; } internal async Task<DraftApprenticeshipControllerTestFixture> PostToSelectStandard() { _actionResult = await _controller.SetCourse(_selectCourseViewModel); return this; } public async Task<DraftApprenticeshipControllerTestFixture> PostToAddDraftApprenticeship(string changeCourse = null, string changeDeliveryModel = null, string changePilotStatus = null) { _actionResult = await _controller.AddDraftApprenticeship(changeCourse, changeDeliveryModel, changePilotStatus, _addModel); return this; } public async Task<DraftApprenticeshipControllerTestFixture> PostToEditDraftApprenticeship(string changeCourse = null, string changeDeliveryModel = null, string changePilotStatus = null) { _actionResult = await _controller.EditDraftApprenticeship(changeCourse, changeDeliveryModel, changePilotStatus, _editModel); return this; } public async Task<DraftApprenticeshipControllerTestFixture> PostToSelectOption() { _actionResult = await _controller.PostSelectOptions(_selectOptionsViewModel); return this; } public DraftApprenticeshipControllerTestFixture SetupHasChosenToChooseOptionLater() { _selectOptionsViewModel.SelectedOption = "-1"; return this; } public DraftApprenticeshipControllerTestFixture SetupUpdateRequestCourseOptionChooseLater() { _updateDraftApprenticeshipRequest.CourseOption = string.Empty; return this; } public DraftApprenticeshipControllerTestFixture SetupUpdateRequestCourseOption() { _updateDraftApprenticeshipRequest.CourseOption = _selectOptionsViewModel.SelectedOption; return this; } public DraftApprenticeshipControllerTestFixture SetupProviderIdOnEditRequest(long providerId) { _draftApprenticeshipRequest.ProviderId = providerId; return this; } public DraftApprenticeshipControllerTestFixture SetApprenticeshipStarting(string startDateAsString, bool actual = false) { if (startDateAsString != null) { var startDate = DateTime.Parse(startDateAsString); if (actual) { _addModel.StartDate = new MonthYearModel(""); _addModel.ActualStartDate = new DateModel(startDate); _editModel.StartDate = _addModel.StartDate; _editModel.ActualStartDate = _addModel.ActualStartDate; _viewModel.StartDate = null; _viewModel.ActualStartDate = startDate; _addModel.IsOnFlexiPaymentPilot = _editModel.IsOnFlexiPaymentPilot = _viewModel.IsOnFlexiPaymentPilot = true; } else { _addModel.StartDate = new MonthYearModel($"{startDate.Month}{startDate.Year}"); _addModel.ActualStartDate = new DateModel(); _editModel.StartDate = _addModel.StartDate; _editModel.ActualStartDate = _addModel.ActualStartDate; _viewModel.StartDate = startDate; _viewModel.ActualStartDate = null; } } SetupCommitmentsApiToReturnADraftApprentice(); return this; } public DraftApprenticeshipControllerTestFixture SetupCohortFundedByTransfer(bool transferFunded) { if (transferFunded) { _cohortResponse.TransferSenderId = 9879; } else { _cohortResponse.TransferSenderId = null; } return this; } public DraftApprenticeshipControllerTestFixture SetCohortWithChangeOfParty(bool isChangeOfParty) { if (isChangeOfParty) { _cohortResponse.ChangeOfPartyRequestId = 12345; } else { _cohortResponse.ChangeOfPartyRequestId = null; } return this; } public DraftApprenticeshipControllerTestFixture SetupLevyStatus(ApprenticeshipEmployerType status) { _cohortResponse.LevyStatus = status; return this; } public DraftApprenticeshipControllerTestFixture SetupTempDraftApprenticeship() { object addModelAsString = JsonConvert.SerializeObject(_addModel); _tempData.Setup(x => x.TryGetValue(nameof(AddDraftApprenticeshipViewModel), out addModelAsString)); return this; } public DraftApprenticeshipControllerTestFixture SetupTempEditDraftApprenticeship() { object addModelAsString = JsonConvert.SerializeObject(_editModel); _tempData.Setup(x => x.TryGetValue(nameof(EditDraftApprenticeshipViewModel), out addModelAsString)); return this; } public void VerifyViewModelFromTempDataHasDeliveryModelAndCourseValuesSet() { var model = _actionResult.VerifyReturnsViewModel().WithModel<AddDraftApprenticeshipViewModel>(); ViewModelHasRequestDeliveryModelAndCourseCode(model); } public DraftApprenticeshipControllerTestFixture SetupCommitmentsApiToReturnADraftApprentice() { _commitmentsApiClient .Setup(x => x.GetDraftApprenticeship(_cohortId, _draftApprenticeshipId, It.IsAny<CancellationToken>())).ReturnsAsync(_draftApprenticeshipDetails); return this; } public DraftApprenticeshipControllerTestFixture VerifyCommitmentsApiGetDraftApprenticeshipNotCalled() { _commitmentsApiClient .Verify(x => x.GetDraftApprenticeship(It.IsAny<long>(), It.IsAny<long>(), It.IsAny<CancellationToken>()), Times.Never); return this; } public DraftApprenticeshipControllerTestFixture SetUpStandardToReturnOptions() { _draftApprenticeshipDetails.HasStandardOptions = true; return this; } public DraftApprenticeshipControllerTestFixture SetUpStandardToReturnNoOptions() { _draftApprenticeshipDetails.HasStandardOptions = false; return this; } public DraftApprenticeshipControllerTestFixture SetupAddingToThrowCommitmentsApiException() { _outerApiService .Setup(x => x.AddDraftApprenticeship(It.IsAny<long>(), It.IsAny<AddDraftApprenticeshipApimRequest>())) .ThrowsAsync(_apiModelException); return this; } public DraftApprenticeshipControllerTestFixture SetupUpdatingToThrowCommitmentsApiException() { _outerApiService .Setup(x => x.UpdateDraftApprenticeship(It.IsAny<long>(), It.IsAny<long>(), It.IsAny<UpdateDraftApprenticeshipApimRequest>())) .ThrowsAsync(_apiModelException); return this; } public DraftApprenticeshipControllerTestFixture SetupModelStateToBeInvalid() { _controller.ModelState.AddModelError("Error", "ErrorMessage"); return this; } public DraftApprenticeshipControllerTestFixture SetupCohortTransferFundedStatus(bool isFundedByTransfer) { _commitmentsApiClient .Setup(pcs => pcs.GetCohort(_cohortId, It.IsAny<CancellationToken>())) .ReturnsAsync(new GetCohortResponse { CohortId = _cohortId, TransferSenderId = 1 }); return this; } public DraftApprenticeshipControllerTestFixture VerifyEditDraftApprenticeshipViewModelIsSentToViewResult() { Assert.IsInstanceOf<ViewResult>(_actionResult); Assert.IsInstanceOf<EditDraftApprenticeshipViewModel>(((ViewResult)_actionResult).Model); return this; } public DraftApprenticeshipControllerTestFixture VerifyViewDraftApprenticeshipViewModelIsSentToViewResult() { Assert.IsInstanceOf<ViewResult>(_actionResult); Assert.IsInstanceOf<ViewDraftApprenticeshipViewModel>(((ViewResult)_actionResult).Model); return this; } public DraftApprenticeshipControllerTestFixture VerifyEditDraftApprenticeshipViewModelHasProviderIdSet() { Assert.IsInstanceOf<EditDraftApprenticeshipViewModel>(((ViewResult)_actionResult).Model); var model = ((ViewResult)_actionResult).Model as EditDraftApprenticeshipViewModel; Assert.AreEqual(_draftApprenticeshipRequest.ProviderId, model.ProviderId); return this; } public DraftApprenticeshipControllerTestFixture VerifyAddViewWasReturnedAndHasErrors() { Assert.IsInstanceOf<ViewResult>(_actionResult); Assert.IsInstanceOf<AddDraftApprenticeshipViewModel>(((ViewResult)_actionResult).Model); var view = ((ViewResult)_actionResult); Assert.AreEqual(1, view.ViewData.ModelState.ErrorCount); return this; } public DraftApprenticeshipControllerTestFixture VerifyEditViewWasReturnedAndHasErrors() { Assert.IsInstanceOf<ViewResult>(_actionResult); Assert.IsInstanceOf<EditDraftApprenticeshipViewModel>(((ViewResult)_actionResult).Model); var view = ((ViewResult)_actionResult); Assert.AreEqual(1, view.ViewData.ModelState.ErrorCount); return this; } public DraftApprenticeshipControllerTestFixture VerifyCohortDetailsWasCalledWithCorrectId() { _commitmentsApiClient.Verify(x => x.GetCohort(_cohortId, It.IsAny<CancellationToken>()), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyGetCoursesWasCalled() { _mediator.Verify(x => x.Send(It.IsAny<GetTrainingCoursesQueryRequest>(), It.IsAny<CancellationToken>()), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyMappingToApiTypeIsCalled() { _modelMapper.Verify(x => x.Map<AddDraftApprenticeshipApimRequest>(_addModel), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyMappingFromReservationAddRequestIsCalled() { _modelMapper.Verify(x => x.Map<AddDraftApprenticeshipViewModel>(_reservationsAddDraftApprenticeshipRequest), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyUpdateMappingToApiTypeIsCalled() { _modelMapper.Verify(x => x.Map<UpdateDraftApprenticeshipApimRequest>(_editModel), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyApiAddMethodIsCalled() { _outerApiService.Verify( x => x.AddDraftApprenticeship(_addModel.CohortId.Value, _createAddDraftApprenticeshipRequest), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyApiUpdateMethodIsCalled() { _outerApiService.Verify( x => x.UpdateDraftApprenticeship(_cohortId, _draftApprenticeshipId, _updateDraftApprenticeshipRequest), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyApiUpdateWithStandardOptionSet(string standardOption = null) { _outerApiService.Verify( x => x.UpdateDraftApprenticeship(_cohortId, _draftApprenticeshipId, It.Is<UpdateDraftApprenticeshipApimRequest>(c => c.CourseOption.Equals(standardOption ?? _updateDraftApprenticeshipRequest.CourseOption))), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedBackToCohortDetailsPage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("Details"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedBackToSelectStandardPage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("SelectCourse"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToSelectCoursePage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("AddDraftApprenticeshipCourse"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToReservationsPage() { var redirect = _actionResult.VerifyReturnsRedirect(); redirect.Url.Should().Contain($"/{_getReservationIdForAddAnotherApprenticeRequest.ProviderId}/reservations/{_getReservationIdForAddAnotherApprenticeRequest.AccountLegalEntityHashedId}/select?"); redirect.Url.Should().Contain($"cohortReference={_getReservationIdForAddAnotherApprenticeRequest.CohortReference}"); redirect.Url.Should().Contain($"encodedPledgeApplicationId={_getReservationIdForAddAnotherApprenticeRequest.EncodedPledgeApplicationId}"); redirect.Url.Should().Contain($"encodedPledgeApplicationId={_getReservationIdForAddAnotherApprenticeRequest.EncodedPledgeApplicationId}"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToReservationsPageContainsTransferSenderId() { var redirect = _actionResult.VerifyReturnsRedirect(); redirect.Url.Should().Contain($"transferSenderId={_getReservationIdForAddAnotherApprenticeRequest.TransferSenderHashedId}"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToSelectForEditCoursePage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("EditDraftApprenticeshipCourse"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToSelectDeliveryModelPage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("SelectDeliveryModel"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToSelectDeliveryForEditModelPage() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("SelectDeliveryModelForEdit"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectedToAddDraftApprenticeshipDetails() { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName("AddDraftApprenticeship"); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectToSelectOptionsPage() { _actionResult.VerifyRedirectsToSelectOptionsPage(_draftApprenticeshipHashedId); return this; } public DraftApprenticeshipControllerTestFixture VerifyRedirectToRecognisePriorLearningPage() { _actionResult.VerifyRedirectsToRecognisePriorLearningPage(_draftApprenticeshipHashedId); return this; } public DraftApprenticeshipControllerTestFixture VerifySelectOptionsViewReturned() { var viewResult = _actionResult as ViewResult; Assert.IsNotNull(viewResult); Assert.AreEqual("SelectStandardOption", viewResult.ViewName); var model = viewResult.Model as ViewSelectOptionsViewModel; Assert.IsNotNull(model); return this; } public DraftApprenticeshipControllerTestFixture VerifyWeGetABadRequestResponse() { Assert.IsInstanceOf<BadRequestObjectResult>(_actionResult); return this; } public DraftApprenticeshipControllerTestFixture VerifyWhetherFrameworkCourseWereRequested(bool expectFrameworkCoursesToBeRequested) { _mediator .Verify(m => m.Send( It.Is<GetTrainingCoursesQueryRequest>(request => request.IncludeFrameworks == expectFrameworkCoursesToBeRequested), It.IsAny<CancellationToken>()), Times.Once); return this; } public DraftApprenticeshipControllerTestFixture ViewModelHasRequestDeliveryModelAndCourseCode(AddDraftApprenticeshipViewModel model) { if (model.DeliveryModel != _reservationsAddDraftApprenticeshipRequest.DeliveryModel || model.CourseCode != _reservationsAddDraftApprenticeshipRequest.CourseCode) { Assert.Fail("DeliveryModel and CourseCode must match Request Value"); } return this; } public DraftApprenticeshipControllerTestFixture VerifyUserRedirectedTo(string page) { _actionResult.VerifyReturnsRedirectToActionResult().WithActionName(page); return this; } } }
using AbstractFactory.Classes.PizzaIngredientFactories.Ingredients; namespace AbstractFactory.Classes.PizzaIngredientFactories { public class NyPizzaIngredientFactory : IPizzaIngredientFactory { public IDough CreateDough() => new ThinCrustDough(); public ISause CreateSause() => new MarinaraSause(); } }
using System; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Threading; using RimDev.AspNetCore.FeatureFlags.Tests.Testing.Configuration; namespace RimDev.AspNetCore.FeatureFlags.Tests.Testing.Database { /// <summary>Base class for any System.Data.SqlClient database fixture. This fixture only /// takes care of database creation/disposal and not initialization (migrations, etc.). /// If a connection string is not provided, it will make use of <see cref="TestConfigurationHelpers"/> /// methods to figure it out.</summary> public abstract class TestSqlClientDatabaseFixture : IDisposable { private readonly bool deleteBefore; private readonly bool deleteAfter; /// <summary>The PRNG is (somewhat) expensive to created and the default seed is the current /// instant. So it's best to create one and only one instance of the Random class.</summary> private static readonly Random Random = new Random(); /// <summary> /// <para>In order for the fixture to create other databases, it must be able to connect /// to an existing database within the SQL server. By custom, this is usually the 'master' /// database. The connection string is then mutated to replace 'master' with the /// dbName parameter.</para> /// </summary> /// <param name="masterConnectionString">SQL server connection string to 'master' database.</param> /// <param name="dbName">Optional database name to be created and used for tests. If a database /// name is not provided, it will be randomly generated and it is strongly recommended that /// the deleteBefore and deleteAfter arguments be set to true.</param> /// <param name="deleteBefore">Whether the database should be dropped prior to tests.</param> /// <param name="deleteAfter">Whether the database should be dropped after tests.</param> /// <param name="dbNameSuffix">Optional suffix to be tacked onto the randomly generated database /// name. This can be used in multi-database situations to keep track of which is which.</param> /// <exception cref="ArgumentNullException"></exception> protected TestSqlClientDatabaseFixture( string masterConnectionString = null, string dbName = null, bool deleteBefore = true, bool deleteAfter = true, string dbNameSuffix = null ) { Console.WriteLine($"Creating {nameof(TestSqlClientDatabaseFixture)} instance..."); if (string.IsNullOrEmpty(masterConnectionString)) { var testConfiguration = TestConfigurationHelpers.GetRimDevTestsConfiguration(); masterConnectionString = testConfiguration?.Sql?.MasterConnectionString; } if (string.IsNullOrEmpty(dbName)) { var now = DateTimeOffset.UtcNow; dbName = $"test-{now:yyyyMMdd}-{now:HHmm}-{UpperCaseAlphanumeric(6)}"; } if (!string.IsNullOrEmpty(dbNameSuffix)) { dbName = $"{dbName}-{dbNameSuffix}"; } MasterConnectionString = masterConnectionString; DbName = dbName; ConnectionString = SwitchMasterToDbNameInConnectionString(masterConnectionString, dbName); this.deleteBefore = deleteBefore; this.deleteAfter = deleteAfter; Console.WriteLine(MasterConnectionStringDebug); Console.WriteLine(ConnectionStringDebug); RecreateDatabase(); // Databases do not always wake up right away after the CREATE DATABASE call WaitUntilDatabaseIsHealthy(); Console.WriteLine($"{nameof(TestSqlClientDatabaseFixture)} instance created."); } /// <summary>Test fixtures need to point at the "master" database initially, because the database /// to be used in the tests may not exist yet.</summary> private string MasterConnectionString { get; } /// <summary>Returns a parsed connection string, listing key details about it. /// This debug string will not output the database password, which makes it safe-ish /// for output in console logs / build logs.</summary> public string MasterConnectionStringDebug { get { try { var b = new SqlConnectionStringBuilder(MasterConnectionString); return $"MASTER-DB: DataSource={b.DataSource}, InitialCatalog={b.InitialCatalog}, UserID={b.UserID}"; } catch { return "MASTER-DB: Bad connection string, unable to parse!"; } } } /// <summary>The temporary database name that was created by the fixture.</summary> public string DbName { get; } /// <summary>The connection string to get to the database which will be used for tests.</summary> public string ConnectionString { get; } /// <summary>Returns a parsed connection string, listing key details about it. /// This debug string will not output the database password, which makes it safe-ish /// for output in console logs / build logs.</summary> public string ConnectionStringDebug { get { try { var b = new SqlConnectionStringBuilder(ConnectionString); return $"TEST-DB: DataSource={b.DataSource}, InitialCatalog={b.InitialCatalog}, UserID={b.UserID}"; } catch { return "TEST-DB: Bad connection string, unable to parse!"; } } } /// <summary>Returns a SqlConnection object to the test database for the fixture. /// Since the SqlConnection implements IDisposable, it should be paired with "using". /// </summary> public SqlConnection CreateSqlConnection() { return new SqlConnection(ConnectionString); } /// <summary>Convert from the "master" database SQL connection string over to the specific database name /// that is being used for a particular database fixture. This relies on the connectionString being /// something that can be parsed by System.Data.SqlClient.</summary> private string SwitchMasterToDbNameInConnectionString(string connectionString, string dbName) { if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullException(nameof(connectionString)); if (string.IsNullOrWhiteSpace(dbName)) throw new ArgumentNullException(nameof(dbName)); var builder = new SqlConnectionStringBuilder(connectionString) { InitialCatalog = dbName }; return builder.ConnectionString; } private static string UpperCaseAlphanumeric(int size) { string input = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; var chars = Enumerable.Range(0, size) .Select(x => input[Random.Next(0, input.Length)]); return new string(chars.ToArray()); } /// <summary>Tracks whether the fixture thinks that it has already initialized /// (created) the database, or decided that the database already exists.</summary> private bool databaseInitialized; private readonly object @lock = new object(); private void RecreateDatabase() { // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_C# if (databaseInitialized) return; lock (@lock) { if (databaseInitialized) return; if (deleteBefore) { try { if (DatabaseExists()) DropDatabase(); } catch (Exception e) { Console.WriteLine($"ERROR: Failed to drop database {DbName} before the run!"); Console.WriteLine(e.Message); throw; } } try { if (!DatabaseExists()) CreateDatabase(); } catch (Exception e) { Console.WriteLine($"ERROR: Failed to create database {DbName}!"); Console.WriteLine(e.Message); throw; } databaseInitialized = true; } } public void Dispose() { // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_C# if (!databaseInitialized) return; lock (@lock) { if (!databaseInitialized) return; if (deleteAfter) { if (DatabaseExists()) DropDatabase(); } databaseInitialized = false; } } private bool DatabaseExists() { //TODO: Consider querying the standard SQL metadata tables instead, but this works okay using var connection = CreateSqlConnection(); var command = new SqlCommand("select 1;", connection); try { connection.Open(); var result = (int)command.ExecuteScalar(); return (result == 1); } catch (SqlException) { return false; } } /// <summary>Is the database accepting connections and will it run queries? </summary> private bool DatabaseIsHealthy() { using var connection = CreateSqlConnection(); var command = new SqlCommand("select 1;", connection); try { connection.Open(); var result = (int)command.ExecuteScalar(); return (result == 1); } catch (SqlException) { return false; } } private void CreateDatabase() { Console.WriteLine($"Creating database '{DbName}'..."); using (var connection = new SqlConnection(MasterConnectionString)) { connection.Open(); using var command = connection.CreateCommand(); command.CommandText = FormattableString.Invariant( $"CREATE DATABASE [{DbName}];"); command.ExecuteNonQuery(); Console.WriteLine($"Created database '{DbName}'."); } } private void WaitUntilDatabaseIsHealthy() { Console.WriteLine($"Begin waiting for '{DbName}' to accept queries."); var timer = new Stopwatch(); timer.Start(); var attempt = 1; while (!DatabaseIsHealthy()) { attempt++; var sleepMilliseconds = Math.Min((int) (Math.Pow(1.1, attempt) * 150), 1000); Thread.Sleep(sleepMilliseconds); if (attempt > 60) throw new Exception( $"Database '{DbName}' refused to execute queries!" ); } timer.Stop(); Console.WriteLine($"The '{DbName}' is healthy after {timer.ElapsedMilliseconds}ms and {attempt} attempts."); } private void DropDatabase() { Console.WriteLine($"Dropping database '{DbName}'..."); using var connection = new SqlConnection(MasterConnectionString); connection.Open(); using var command = connection.CreateCommand(); command.CommandText = FormattableString.Invariant( $"ALTER DATABASE [{DbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{DbName}];"); command.ExecuteNonQuery(); Console.WriteLine($"Dropped database '{DbName}'."); } } }
using System; using Vintagestory.API.Common; using Vintagestory.API.Common.Entities; using Vintagestory.API.MathTools; using Vintagestory.API.Server; using Vintagestory.GameContent; namespace OreCrystals { class EntityCrystalGrenade: Entity { private const double grenadeVerticalSpeed = 5; private const double grenadeHorizontalSpeed = 0.125; private const float grenadeParticleVelocityModifier = 6; private const int grenadeDamage = 10; private const int grenadeRange = 3; protected CollisionTester collTester = new CollisionTester(); protected EntityPos grenadeTransforms = new EntityPos(); protected SimpleParticleProperties grenadeAngerParticles; protected SimpleParticleProperties grenadeBreakParticles; private bool isTriggered = false; private long triggeredTime; private int fuseTime = 5000; private Random particleRand; private string grenadeVariant; public override void Initialize(EntityProperties properties, ICoreAPI api, long InChunkIndex3d) { base.Initialize(properties, api, InChunkIndex3d); grenadeTransforms = ServerPos; Pos.SetFrom(ServerPos); particleRand = new Random((int)this.EntityId); grenadeVariant = this.LastCodePart(); this.LightHsv = CrystalColour.GetLight(grenadeVariant); } public override void OnGameTick(float dt) { base.OnGameTick(dt); if(isTriggered == false) { if(!collTester.IsColliding(World.BlockAccessor, this.CollisionBox, this.ServerPos.XYZ)) { this.ServerPos.SetFrom(CalculatePosition(dt)); } else { isTriggered = true; triggeredTime = World.ElapsedMilliseconds; this.ServerPos.SetPos(this.ServerPos.XYZ - (this.ServerPos.Motion.Normalize() * 0.25)); } } else { if (this.Api.Side == EnumAppSide.Client) { InitAngerParticles(); this.Api.World.SpawnParticles(grenadeAngerParticles); } if(World.ElapsedMilliseconds >= triggeredTime + fuseTime) { if (this.Api.Side == EnumAppSide.Client) { InitBreakParticles(); this.Api.World.SpawnParticles(grenadeBreakParticles); } else { Api.World.PlaySoundAt(new AssetLocation("orecrystals", "sounds/block/glass"), ServerPos.X, ServerPos.Y, ServerPos.Z, null, true, 32, 1.0f); DamageEntities(); } this.Die(); } } } private void InitAngerParticles() { Vec3f velocityRand = new Vec3f((float)(particleRand.Next(0, 1) + particleRand.NextDouble()), (float)(particleRand.Next(0, 1) + particleRand.NextDouble()), (float)(particleRand.Next(0, 1) + particleRand.NextDouble())); grenadeAngerParticles = new SimpleParticleProperties() { MinPos = new Vec3d(this.Pos.X, this.Pos.Y + .25, this.Pos.Z), MinVelocity = new Vec3f(-velocityRand.X, -velocityRand.Y, -velocityRand.Z), AddVelocity = velocityRand * 2, GravityEffect = 0.0f, MinSize = 0.1f, MaxSize = 0.4f, SizeEvolve = new EvolvingNatFloat(EnumTransformFunction.LINEAR, -0.1f), MinQuantity = 5, AddQuantity = 15, LifeLength = 0.6f, addLifeLength = 1.4f, ShouldDieInLiquid = true, WithTerrainCollision = true, Color = CrystalColour.GetColour(grenadeVariant), OpacityEvolve = new EvolvingNatFloat(EnumTransformFunction.LINEARREDUCE, 255), VertexFlags = 150, ParticleModel = EnumParticleModel.Quad }; } private void InitBreakParticles() { Vec3f velocityRand = new Vec3f((float)particleRand.NextDouble(), (float)particleRand.NextDouble(), (float)particleRand.NextDouble()) * grenadeParticleVelocityModifier; grenadeBreakParticles = new SimpleParticleProperties() { MinPos = new Vec3d(this.Pos.X, this.Pos.Y + .25, this.Pos.Z), MinVelocity = new Vec3f(velocityRand.X, velocityRand.Y, velocityRand.Z), AddVelocity = new Vec3f(-velocityRand.X, -velocityRand.Y, -velocityRand.Z) * 2, GravityEffect = 0.2f, MinSize = 0.1f, MaxSize = 0.4f, SizeEvolve = new EvolvingNatFloat(EnumTransformFunction.LINEAR, -0.1f), MinQuantity = 40, AddQuantity = 80, LifeLength = 0.6f, addLifeLength = 2.0f, ShouldDieInLiquid = true, WithTerrainCollision = true, Color = CrystalColour.GetColour(grenadeVariant), OpacityEvolve = new EvolvingNatFloat(EnumTransformFunction.LINEARREDUCE, 255), VertexFlags = 150, ParticleModel = EnumParticleModel.Cube }; } private EntityPos CalculatePosition(float dt) { this.grenadeTransforms.SetAngles(0, (World.ElapsedMilliseconds / 200.0f) % GameMath.TWOPI, (World.ElapsedMilliseconds / 150.0f) % GameMath.TWOPI); this.grenadeTransforms.SetPos(this.grenadeTransforms.XYZ + this.grenadeTransforms.Motion.Normalize()); if (this.grenadeTransforms.Motion.Y < 0) this.grenadeTransforms.Motion = this.grenadeTransforms.Motion.AddCopy(-this.grenadeTransforms.Motion.X * grenadeHorizontalSpeed * dt, this.grenadeTransforms.Motion.Y * grenadeVerticalSpeed * dt, -this.grenadeTransforms.Motion.Z * grenadeHorizontalSpeed * dt); else if (this.grenadeTransforms.Motion.Y <= grenadeVerticalSpeed / 2) this.grenadeTransforms.Motion = this.grenadeTransforms.Motion.AddCopy(-this.grenadeTransforms.Motion.X * grenadeHorizontalSpeed * dt, -1 * grenadeVerticalSpeed * dt, -this.grenadeTransforms.Motion.Z * grenadeHorizontalSpeed * dt); else this.grenadeTransforms.Motion = this.grenadeTransforms.Motion.AddCopy(-this.grenadeTransforms.Motion.X * grenadeHorizontalSpeed * dt, -this.grenadeTransforms.Motion.Y * grenadeVerticalSpeed * dt, -this.grenadeTransforms.Motion.Z * grenadeHorizontalSpeed * dt); return this.grenadeTransforms; } private void DamageEntities() { World.GetEntitiesInsideCuboid(new BlockPos((int)Math.Ceiling(ServerPos.X - grenadeRange), (int)Math.Ceiling(ServerPos.Y - grenadeRange), (int)Math.Ceiling(ServerPos.Z - grenadeRange)), new BlockPos((int)Math.Ceiling(ServerPos.X + grenadeRange), (int)Math.Ceiling(ServerPos.Y + grenadeRange), (int)Math.Ceiling(ServerPos.Z + grenadeRange)), (entity) => { entity.ReceiveDamage(new DamageSource() { SourceEntity = this }, grenadeDamage); return true; }); } } }
using Infra.Context; using Welic.Dominio.Models.Uploads.Maps; using Welic.Dominio.Models.Uploads.Services; using Welic.Dominio.Patterns.Repository.Pattern.Repositories; using Welic.Dominio.Patterns.Service.Pattern; namespace Services.Uploads { public class UploadsService : Service<UploadsMap>, IUploadsService { private AuthContext _context; public UploadsService(IRepositoryAsync<UploadsMap> repository, AuthContext context) : base(repository) { _context = context; } } }
using System; using Utilities; namespace EddiEvents { [PublicAPI] public class FSDEngagedEvent : Event { public const string NAME = "FSD engaged"; public const string DESCRIPTION = "Triggered when your FSD has engaged"; public const string SAMPLE = @"{""timestamp"":""2016-08-09T08:46:29Z"",""event"":""StartJump"",""JumpType"":""Hyperspace"",""StarClass"":""L"",""StarSystem"":""LFT 926""}"; [PublicAPI("The target frame (Supercruise/Hyperspace)")] public string target { get; private set; } [PublicAPI("The class of the destination primary star (only if type is Hyperspace)")] public string stellarclass { get; private set; } [PublicAPI("The destination system (only if type is Hyperspace)")] public string system { get; private set; } [PublicAPI( "True if traveling via taxi" )] public bool taxijump { get; private set; } // Not intended to be user facing public ulong? systemAddress { get; private set; } // Only set when the fsd target is hyperspace public FSDEngagedEvent(DateTime timestamp, string jumptype, string systemName, ulong? systemAddress, string stellarclass, bool isTaxi) : base(timestamp, NAME) { this.target = jumptype; this.system = systemName; this.systemAddress = systemAddress; this.stellarclass = stellarclass; this.taxijump = isTaxi; } } }
using Newtonsoft.Json; namespace Settlement.Classes.Other { class DataConfig { [JsonProperty("server_epayment")] public static string ServerEPayment { get; set; } [JsonProperty("server_epass")] public static string ServerEPass { get; set; } [JsonProperty("database_name")] public static string DatabaseName { get; set; } [JsonProperty("database_username")] public static string DatabaseUsername { get; set; } [JsonProperty("database_password")] public static string DatabasePassword { get; set; } [JsonProperty("settlement_destination_path_in_linux")] public static string SettlementDestinationLinux { get; set; } [JsonProperty("settlement_destination_path_in_windows")] public static string SettlementDestinationWindows { get; set; } [JsonProperty("TID_Settlement")] public static string TIDSettlement { get; set; } [JsonProperty("MID_Settlement")] public static string MIDSettlement { get; set; } [JsonProperty("bank_name")] public static string BankName { get; set; } [JsonProperty("api_url_server_epass")] public static string ApiUrl { get; set; } } }