text
stringlengths
13
6.01M
using System; using System.Threading.Tasks; namespace Szogun1987.EventsAndTasks.Callbacks.NeverCalledback { public class BrokenTaskAdapter : ITaskAdapter { private readonly Func<CallbacksApi> _callbacksApiFactory; public BrokenTaskAdapter(Func<CallbacksApi> callbacksApiFactory) { _callbacksApiFactory = callbacksApiFactory; } public Task<int> GetNextInt() { var api = _callbacksApiFactory(); var completionSource = new TaskCompletionSource<int>(); api.GetNextInt((arg, exception) => { if (exception != null) { completionSource.SetException(exception); } else { completionSource.SetResult(arg); } }); return completionSource.Task; } public Task<int> GetNextIntWithArg(string arg) { var api = _callbacksApiFactory(); var completionSource = new TaskCompletionSource<int>(); api.GetNextIntWithArg(arg, (arg1, exception) => { if (exception != null) { completionSource.SetException(exception); } else { completionSource.SetResult(arg1); } }); return completionSource.Task; } } }
/** Copyright (c) 2020, Institut Curie, Institut Pasteur and CNRS Thomas BLanc, Mohamed El Beheiry, Jean Baptiste Masson, Bassam Hajj and Clement Caporal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Institut Curie, Insitut Pasteur and CNRS. 4. Neither the name of the Institut Curie, Insitut Pasteur and CNRS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using VRTK; using Data; namespace VR_Interaction { public class VRHistogramPlacementTool : VRObjectPlacementTool { public bool task1_On = false;//place first cylinder side public bool task2_On = false;//place second cylinder side public bool taskSectionSelection_On = false;//select number of bins public GameObject histogramCanvasPrefab; public GameObject baseCircle; public GameObject secondCircle; public Vector3 secondCicleOriginalPosition; int sign; public GameObject histogramContainer; public List<GameObject> sectionList = new List<GameObject>(); GameObject lineobject; public VRHistogramPlacementTool(VRTK_ControllerEvents controller) : base(controller) { } protected override void ReloadContainers(int id = 0) { if (!CloudSelector.instance.noSelection) { Debug.Log("At least one cloud is loaded"); if (CloudUpdater.instance.LoadStatus(id).globalMetaData.histogramList.Count != 0) { Debug.Log("Cloud Contains previous histogram data"); containersList = new Dictionary<int, VRContainer>(); foreach (var obj in CloudUpdater.instance.LoadStatus(id).globalMetaData.histogramList) { obj.Value.SetActive(true); VRContainerHistogram containerscript = obj.Value.GetComponent<VRContainerHistogram>(); containersList.Add(containerscript.id, containerscript); } selectedContainerID = 0; UIdisplayID = 0; textmesh.text = "0"; pointNumber = containersList[selectedContainerID].GetObjectCount(); objectplacementCanvas.SetActive(false); containerselectionCanvas.SetActive(true); } else { Debug.Log("Cloud Contains no previous histogram data"); CreateNewContainerList(); } } else { Debug.Log("No Cloud is loaded"); CreateNewContainerList(); } } public override void CreateContainer(int id) { if (!containersList.ContainsKey(id)) { GameObject VRContainer = new GameObject("Histogram Container"); VRContainer.transform.position = this.transform.position; VRContainer.AddComponent<MeshRenderer>(); VRContainer.AddComponent<MeshFilter>(); VRContainer.AddComponent<VRContainerHistogram>(); VRContainer.GetComponent<VRContainerHistogram>().id = id; VRContainer.AddComponent<HistogramPointSelector>(); containersList.Add(id, VRContainer.GetComponent<VRContainerHistogram>()); } } public override void AddPoint() { if (!task1_On && !task2_On) { if (containersList[selectedContainerID].GetObjectCount() == 0) { containersList[selectedContainerID].transform.position = sphere.transform.position; containersList[selectedContainerID].gameObject.AddComponent<CloudChildHistogram>(); containersList[selectedContainerID].gameObject.GetComponent<CloudChildHistogram>().id = containersList[selectedContainerID].id; containersList[selectedContainerID].gameObject.AddComponent<BoxCollider>(); containersList[selectedContainerID].gameObject.GetComponent<BoxCollider>().size = Vector3.one * 0.01f; VRObjectsManager.instance.ContainerCreated(containersList[selectedContainerID].id, containersList[selectedContainerID].gameObject, "Histogram"); /** containersList[selectedContainerID].gameObject.GetComponent<CapsuleCollider>().center = containersList[selectedContainerID].transform.position; containersList[selectedContainerID].gameObject.GetComponent<CapsuleCollider>().height = Vector3.Distance(baseCircle.transform.position, secondCircle.transform.position); containersList[selectedContainerID].gameObject.GetComponent<CapsuleCollider>().radius = baseCircle.transform.localScale.x; **/ } GameObject go = CreatePoint(0); baseCircle = go; baseCircle.transform.SetParent(containersList[selectedContainerID].transform,true); GameObject go2 = CreatePoint(0); secondCircle = go2; secondCircle.transform.position = baseCircle.transform.position; secondCircle.transform.localScale = baseCircle.transform.localScale; secondCircle.transform.rotation = baseCircle.transform.rotation; secondCicleOriginalPosition = go2.transform.position; controllerRefs.SetUpperTextDisplayActive(true); GameObject obj = new GameObject(); //obj.transform.SetParent(baseCircle.transform, false); MeshRenderer mr = obj.AddComponent<MeshRenderer>(); MeshFilter mf = obj.AddComponent<MeshFilter>(); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); vertices.Add(baseCircle.transform.position); vertices.Add(secondCircle.transform.position); indices.Add(0); indices.Add(1); mf.mesh.vertices = vertices.ToArray(); mf.mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); mr.material = new Material(Shader.Find("Standard")); lineobject = obj; task1_On = true; return; } if(task1_On && !task2_On) { //secondCircle.transform.SetParent(sphere.transform, false); task1_On = false; secondCircle.transform.SetParent(containersList[selectedContainerID].transform, true); task2_On = true; return; } if(task2_On && !task1_On) { task2_On = false; controllerRefs.SetUpperTextDisplayActive(false); Destroy(lineobject); GameObject go3 = new GameObject("center"); go3.AddComponent<MeshRenderer>(); go3.AddComponent<MeshFilter>(); Mesh mesh = new Mesh(); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); vertices.Add(baseCircle.transform.position + (baseCircle.transform.up * baseCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (secondCircle.transform.up * secondCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (-secondCircle.transform.up * secondCircle.transform.localScale.y)); vertices.Add(baseCircle.transform.position + ( - baseCircle.transform.up * baseCircle.transform.localScale.y)); vertices.Add(baseCircle.transform.position + (baseCircle.transform.right * baseCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (-secondCircle.transform.right * secondCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (secondCircle.transform.right * secondCircle.transform.localScale.y)); vertices.Add(baseCircle.transform.position + (-baseCircle.transform.right * baseCircle.transform.localScale.y)); /** vertices.Add(baseCircle.transform.position + (new Vector3(Mathf.Sqrt(2)/2, Mathf.Sqrt(2) / 2, 0) * baseCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (new Vector3(Mathf.Sqrt(2) / 2, Mathf.Sqrt(2) / 2, 0) * secondCircle.transform.localScale.y)); vertices.Add(secondCircle.transform.position + (new Vector3( - Mathf.Sqrt(2) / 2, Mathf.Sqrt(2) / 2, 0) * secondCircle.transform.localScale.y)); vertices.Add(baseCircle.transform.position + (new Vector3( - Mathf.Sqrt(2) / 2, Mathf.Sqrt(2) / 2, 0) * baseCircle.transform.localScale.y)); **/ for (int i = 0; i < vertices.Count; i++) { indices.Add(i); } mesh.vertices = vertices.ToArray(); mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); go3.GetComponent<MeshRenderer>().material = VRMaterials.instance._default; go3.GetComponent<MeshFilter>().mesh = mesh; GameObject container = new GameObject("Histogram"); baseCircle.transform.SetParent(container.transform, true); secondCircle.transform.SetParent(container.transform, true); go3.transform.SetParent(container.transform, true); container.AddComponent<VRObjectHistogramCylinder>(); if (containersList[selectedContainerID].CheckID(0)) { GameObject obj = containersList[selectedContainerID].GetVRObject(0).gameObject; containersList[selectedContainerID].DeleteVRObject(0); Destroy(obj); } //container.GetComponent<VRObjectHistogramCylinder>().id = containersList[selectedContainerID].GetObjectCount(); container.transform.SetParent(containersList[selectedContainerID].transform, true); containersList[selectedContainerID].gameObject.GetComponent<HistogramPointSelector>().canvasPrefab = histogramCanvasPrefab; containersList[selectedContainerID].AddVRObject(container.GetComponent<VRObjectHistogramCylinder>(), 0); taskSectionSelection_On = true; histogramContainer = container; SelectSections(); return; } } protected override void OnSelectionValueChanged() { if(sectionList.Count != 0) { for (int j = 0; j < sectionList.Count; j++) { Destroy(sectionList[j]); } sectionList.Clear(); } float distance = Vector3.Distance(baseCircle.transform.position, secondCircle.transform.position); float sizeinterval = distance / selectiondisplayID; for (int i = 1; i < selectiondisplayID; i++) { GameObject newcircle = CreatePoint(0); newcircle.transform.position = baseCircle.transform.position; newcircle.transform.localScale = baseCircle.transform.localScale; newcircle.transform.rotation = baseCircle.transform.rotation; Vector3 direction = secondCircle.transform.position - baseCircle.transform.position; newcircle.transform.position += (direction.normalized * (i*sizeinterval)); newcircle.transform.SetParent(histogramContainer.transform); sectionList.Add(newcircle); } HistogramPointSelector selector = containersList[selectedContainerID].GetComponent<HistogramPointSelector>(); List<GameObject> circleList = new List<GameObject>(); List<Vector3> circlePositionsList = new List<Vector3>(); circlePositionsList.Add(baseCircle.transform.position); circleList.Add(baseCircle); foreach (var go in sectionList) { circlePositionsList.Add(go.transform.position); circleList.Add(go); } circlePositionsList.Add(secondCircle.transform.position); circleList.Add(secondCircle); selector.radius = baseCircle.transform.localScale.x; selector.sectionsNumber = selectiondisplayID; selector.FindPointsProto(circleList, circlePositionsList); } protected override void OnSelectionEnd() { sectionList.Clear(); histogramContainer.GetComponent<VRObjectHistogramCylinder>().ReloadMeshList(); base.OnSelectionEnd(); } public void SelectSections() { objectplacementCanvas.SetActive(false); containerselectionCanvas.SetActive(false); sectionselectionCanvas.SetActive(true); selectiondisplayID = 1; sectionselectiontextmesh.text = selectiondisplayID.ToString(); } public override void RemovePoint() { base.RemovePoint(); } public override GameObject CreatePoint(int id) { GameObject go = CreateCircleMesh(); return go; } public GameObject CreateCircleMesh() { GameObject newpoint = new GameObject("Circle"); //Creates a circle MeshRenderer mr = newpoint.AddComponent<MeshRenderer>(); MeshFilter mf = newpoint.AddComponent<MeshFilter>(); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); int counter = 0; int n = 50; float radius = 1f; float x, y, z; for (int i = 0; i < n; i++) // phi { x = radius * Mathf.Cos((2 * Mathf.PI * i) / n); y = radius * Mathf.Sin((2 * Mathf.PI * i) / n); z = 0; vertices.Add(new Vector3(x, y, z)); indices.Add(counter++); x = radius * Mathf.Cos((2 * Mathf.PI * (i + 1)) / n); y = radius * Mathf.Sin((2 * Mathf.PI * (i + 1)) / n); z = 0; vertices.Add(new Vector3(x, y, z)); indices.Add(counter++); } mf.mesh.vertices = vertices.ToArray(); mf.mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); mr.material = new Material(Shader.Find("Standard")); //newpoint.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f); newpoint.AddComponent<VRObjectAngleCylinder>(); newpoint.transform.rotation = sphere.transform.rotation; newpoint.transform.localScale = Vector3.one * 0.05f; newpoint.transform.position = sphere.transform.position; //newpoint.transform.SetParent(sphere.transform, true); return newpoint; } public override void RemoveContainer(int id) { base.RemoveContainer(id); } public void Update() { if (task1_On) { secondCircle.transform.position = sphere.transform.position; secondCircle.transform.rotation = sphere.transform.rotation; baseCircle.transform.LookAt(secondCircle.transform, secondCircle.transform.up); secondCircle.transform.LookAt(baseCircle.transform, baseCircle.transform.up); float l = Vector3.Distance(baseCircle.transform.position, secondCircle.transform.position); controllerRefs.UpdateUpperTextDisplay("L = "+ System.Math.Round(l,3).ToString()); MeshRenderer mr = lineobject.GetComponent<MeshRenderer>(); MeshFilter mf = lineobject.GetComponent<MeshFilter>(); List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); vertices.Add(baseCircle.transform.position); vertices.Add(secondCircle.transform.position); indices.Add(0); indices.Add(1); mf.mesh.vertices = vertices.ToArray(); mf.mesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0); } if (task2_On) { float distance = Vector2.Distance(new Vector2(secondCircle.transform.position.x, secondCircle.transform.position.y), new Vector2(sphere.transform.position.x, sphere.transform.position.y)); baseCircle.transform.localScale = 2 * distance * Vector3.one; secondCircle.transform.localScale = 2 * distance * Vector3.one; controllerRefs.UpdateUpperTextDisplay("H = " + (System.Math.Round(2*distance,3).ToString())); /** float distancefull = Vector3.Distance(baseCircle.transform.position, sphere.transform.position); float dot = Vector3.Dot(secondCircle.transform.forward, sphere.transform.position - secondCicleOriginalPosition); if (dot > 0.0001f) { sign = 1; } else { sign = -1; } secondCircle.transform.position = secondCicleOriginalPosition + (sign * (baseCircle.transform.forward * distancefull)); **/ } } protected override void OnContainerSelected(int id) { if (containersList[id].GetComponent<HistogramPointSelector>()) { containersList[id].GetComponent<HistogramPointSelector>().enabled = true; } } protected override void OnContainerUnselected(int id) { if (containersList[id].GetComponent<HistogramPointSelector>()) { containersList[id].GetComponent<HistogramPointSelector>().enabled = false; } } } }
using System; using System.Collections.Generic; using System.Text; namespace LM.Senac.BouncingBall.Physics { public class Size2d { public Size2d(double width, double height) { this.dWidth = width; this.dHeight = height; } public static Size2d Zero = new Size2d(0, 0); private double dWidth; public double Width { get { return dWidth; } set { dWidth = value; } } private double dHeight; public double Height { get { return dHeight; } set { dHeight = value; } } #region Operators public static Size2d operator +(Size2d thisP, Size2d pt) { return new Size2d(thisP.dWidth + pt.dWidth, thisP.dHeight + pt.dHeight); } public static Size2d operator -(Size2d thisP, Size2d pt) { return new Size2d(thisP.dWidth - pt.dWidth, thisP.dHeight - pt.dHeight); } public static Size2d operator *(Size2d thisP, Size2d pt) { return new Size2d(thisP.dWidth * pt.dWidth, thisP.dHeight * pt.dHeight); } public static Size2d operator /(Size2d thisP, Size2d pt) { return new Size2d(thisP.dWidth / pt.dWidth, thisP.dHeight / pt.dHeight); } public static Size2d operator *(Size2d thisP, double scalar) { return new Size2d(thisP.dWidth * scalar, thisP.dHeight * scalar); } public static Size2d operator /(Size2d thisP, double scalar) { return new Size2d(thisP.dWidth / scalar, thisP.dHeight / scalar); } public static Size2d operator *(double scalar, Size2d thisP) { return new Size2d(thisP.dWidth * scalar, thisP.dHeight * scalar); } public static bool operator ==(Size2d thisP, Size2d pt) { return thisP.dWidth == pt.dWidth && thisP.dHeight == pt.dHeight; } public static bool operator !=(Size2d thisP, Size2d pt) { return thisP.dWidth != pt.dWidth || thisP.dHeight != pt.dHeight; } public static implicit operator System.Drawing.SizeF(Size2d thisP) { return new System.Drawing.SizeF(Convert.ToSingle(thisP.dWidth), Convert.ToSingle(thisP.dHeight)); } #endregion } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class CommanderContinuedEvent : Event { public const string NAME = "Commander continued"; public const string DESCRIPTION = "Triggered when you continue an existing game"; public const string SAMPLE = "{\"timestamp\":\"2016-06-10T14:32:03Z\",\"event\":\"LoadGame\",\"Commander\":\"HRC1\",\"FID\":\"F44396\",\"Horizons\":true,\"Ship\":\"CobraMkIII\",\"ShipID\":1,\"GameMode\":\"Group\",\"Group\":\"Mobius\",\"Credits\":600120,\"Loan\":0,\"ShipName\":\"jewel of parhoon\",\"ShipIdent\":\"hr-17f\",\"FuelLevel\":3.964024,\"FuelCapacity\":8}"; [PublicAPI("The commander's name")] public string commander { get; private set; } [PublicAPI("The game version includes the 'Horizons' DLC")] public bool horizons { get; private set; } [PublicAPI("The game version includes the 'Odyssey' DLC")] public bool odyssey { get; private set; } [PublicAPI("The commander's ship")] public string ship => shipEDModel == "TestBuggy" ? Constants.VEHICLE_SRV : shipEDModel.ToLowerInvariant().Contains("fighter") ? Constants.VEHICLE_FIGHTER : shipEDModel.ToLowerInvariant().Contains("suit") ? Constants.VEHICLE_LEGS : shipEDModel.ToLowerInvariant().Contains("taxi") ? Constants.VEHICLE_TAXI : ShipDefinitions.FromEDModel(shipEDModel, false)?.model; [PublicAPI("The ID of the commander's ship")] public long? shipid { get; private set; } // this serves double duty in the journal - for ships it is the localId (an integer value). For suits, it is the suit ID (a long). [PublicAPI("The game mode (Open, Group or Solo)")] public string mode { get; private set; } [PublicAPI("The name of the group (only if mode == Group)")] public string group { get; private set; } [PublicAPI("The number of credits the commander has")] public long credits { get; private set; } [PublicAPI("The current loan the commander has")] public long loan { get; private set; } [PublicAPI("The current fuel level of the commander's vehicle")] public decimal? fuel { get; private set; } [PublicAPI("The total fuel capacity of the commander's vehicle")] public decimal? fuelcapacity { get; private set; } [PublicAPI("True if the commander is starting landed")] public bool? startlanded { get; private set; } [PublicAPI("True if the commander is starting dead / at the rebuy screen")] public bool? startdead { get; private set; } // Not intended to be user facing public string shipname { get; private set; } public string shipident { get; private set; } public string frontierID { get; private set; } public string shipEDModel { get; private set; } public string gameversion { get; private set; } public string gamebuild { get; private set; } public CommanderContinuedEvent(DateTime timestamp, string commander, string frontierID, bool horizons, bool odyssey, long? shipId, string shipEdModel, string shipName, string shipIdent, bool? startedLanded, bool? startDead, GameMode mode, string group, long credits, long loan, decimal? fuel, decimal? fuelcapacity, string version, string build) : base(timestamp, NAME) { this.commander = commander; this.frontierID = frontierID; this.horizons = horizons; this.odyssey = odyssey; this.shipid = shipId; this.shipEDModel = shipEdModel; this.shipname = shipName; this.shipident = shipIdent; this.startlanded = startedLanded; this.startdead = startDead; this.mode = (mode?.localizedName); this.group = group; this.credits = credits; this.loan = loan; this.fuel = fuel; this.fuelcapacity = fuelcapacity; this.gameversion = version; this.gamebuild = build; } } }
using EngineLibrary.Scripts; using GameLibrary.Components; namespace GameLibrary.Scripts.Utils { /// <summary> /// Класс обновления компонента видимости объекта /// </summary> public class VisibleScript : Script { private VisibleComponent _visibleComponent; /// <summary> /// Инициализация класса /// </summary> public override void Init() { _visibleComponent = GameObject.GetComponent<VisibleComponent>(); } /// <summary> /// Обновление поведения /// </summary> /// <param name="delta">Время между кадрами</param> public override void Update(float delta) { _visibleComponent.Update(delta); } } }
using System; using Welic.Dominio.Utilitarios.Entidades; using Welic.Dominio.Validacao; namespace Welic.Dominio.Utilitarios.Escopos { public static class EscoposListaMesAnoUtil { public static bool ValidarNovaLista(this ListarMesAnoUtil listarMesAnoUtil) { return Validador.SeSatisfazPor( Validador.AssegurarMaiorQue(listarMesAnoUtil.QuantidadeMeses, 0, "A Quantidade de meses deve ser maior que zero"), Validador.AssegurarMenorOuIgualQue(listarMesAnoUtil.QuantidadeMeses, 1000, "A quantidade de meses deve ser menor que 1000"), Validador.AssegurarMaiorQue(listarMesAnoUtil.DataInicial, new DateTime(1900, 1, 1), "A data inicial deve ser maior que 01/01/1900"), Validador.AssegurarMenorOuIgualQue(listarMesAnoUtil.DataInicial, new DateTime(3000, 1, 1), "A data inicial deve ser maior que 01/01/3000") ); } } }
using System.Web.Mvc; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Domain.Contracts.Tasks.Screenings; namespace Profiling2.Web.Mvc.Areas.Screening.Controllers { public class RequestEntityController : ScreeningBaseController { protected readonly IRequestTasks requestTasks; protected readonly IUserTasks userTasks; public RequestEntityController(IRequestTasks requestTasks, IUserTasks userTasks) { this.requestTasks = requestTasks; this.userTasks = userTasks; } public ActionResult Details(int id) { return View(this.requestTasks.GetRequestEntity(id)); } } }
/* * @Author: Atilla Tanrikulu * @Date: 2018-04-16 10:10:45 * @Last Modified by: Atilla Tanrikulu * @Last Modified time: 2018-06-11 10:46:21 */ using IdentityModel; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Test; using System.Collections.Generic; using System.Security.Claims; namespace SSO.Web { public class Config { // scopes define the resources in your system public static IEnumerable<IdentityResource> GetIdentityResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email(), new IdentityResource { Name = "role", DisplayName="Your role names", Description="Your role names and role codes", UserClaims = { "role", "admin", "user"}, ShowInDiscoveryDocument=true } }; } // authorized applications, protedted resources public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource(){ Name = "core.api", DisplayName ="Core.API", UserClaims = {"name", "role", "email"} }, new ApiResource("alarm.api", "Alarm.API") }; } // clients want to access resources (aka scopes) public static IEnumerable<Client> GetClients() => // client credentials client new List<Client> { new Client { ClientId = "client", ClientName = "ConsoleClient", AllowedGrantTypes = GrantTypes.Implicit, ClientSecrets ={new Secret("*****".Sha256())}, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, "role", "core.api", "alarm.api" } }, // resource owner password grant client new Client { ClientId = "jsclient", ClientName = "JavaScriptClient", AllowedGrantTypes = GrantTypes.Implicit, ClientSecrets ={new Secret("*****".Sha256())}, RedirectUris = { "http://localhost:5003/callback.html","http://localhost:5003" }, PostLogoutRedirectUris = { "http://localhost:5003/index.html" }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, "role", "core.api", "alarm.api" }, AllowedCorsOrigins = new List<string>{ "http://127.0.0.1:5003", "http://127.0.0.1:5004", "http://127.0.0.1:5005", "http://127.0.0.1:5006", "http://127.0.0.1:5007", "http://localhost:5003", "http://localhost:5004", "http://localhost:5005", "http://localhost:5006", "http://localhost:5007" }, RequireConsent = true, AllowAccessTokensViaBrowser=true }, // Angular client core service new Client { ClientId = "cweb", ClientName = "cweb", AccessTokenLifetime = 60*60,// 60 minutes AllowedGrantTypes = GrantTypes.Implicit, AlwaysSendClientClaims=true, AlwaysIncludeUserClaimsInIdToken = true, ClientSecrets ={new Secret("*****".Sha256())}, RequireConsent = false, AllowAccessTokensViaBrowser = true, AllowOfflineAccess = true, AccessTokenType = AccessTokenType.Jwt, AllowedScopes = { "openid", "profile", "email", "role", "core.api" }, RedirectUris = { "http://localhost:4200" }, PostLogoutRedirectUris = { "http://localhost:4200" }, AllowedCorsOrigins = new List<string>{ "http://127.0.0.1:4200", // web "http://127.0.0.1:5001", // api "http://localhost:4200", "http://localhost:5001", } }, // OpenID Connect hybrid flow and client credentials client (MVC) new Client { ClientId = "mvc", ClientName = "MVC Client", AllowedGrantTypes = GrantTypes.HybridAndClientCredentials, RequireConsent = true, ClientSecrets ={new Secret("*****".Sha256())}, RedirectUris = { "http://localhost:5002/signin-oidc" }, PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, "role", "core.api", "alarm.api" }, AllowOfflineAccess = true } }; public static List<TestUser> GetUsers() { return new List<TestUser> { new TestUser { SubjectId = "1", Username = "systemuser", Password = "123", Claims = { new Claim(JwtClaimTypes.Name,"Systemuser"), new Claim(JwtClaimTypes.Role,"system"), new Claim(JwtClaimTypes.Email, "systemuser@mycompany.com") } }, new TestUser { SubjectId = "2", Username = "adminuser", Password = "123", Claims = { new Claim(JwtClaimTypes.Name,"Adminuser"), new Claim(JwtClaimTypes.Role,"admin"), new Claim(JwtClaimTypes.Email, "adminuser@mycompany.com") } }, new TestUser { SubjectId = "4", Username = "testuser", Password = "123", Claims = { new Claim(JwtClaimTypes.Name,"Testuser"), new Claim(JwtClaimTypes.Role,"test"), new Claim(JwtClaimTypes.Email, "testuser@mycompany.com") } } }; } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.MonoHooks.Editor { /// <summary> /// Variable property drawer of type `CollisionGameObject`. Inherits from `AtomDrawer&lt;CollisionGameObjectVariable&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(CollisionGameObjectVariable))] public class CollisionGameObjectVariableDrawer : VariableDrawer<CollisionGameObjectVariable> { } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Kingdee.CAPP.BLL; using Kingdee.CAPP.Model; using Kingdee.CAPP.UI.Resource; namespace Kingdee.CAPP.UI.SystemSetting { public partial class AddNodeFrm : BaseSkinForm { public AddNodeFrm() { InitializeComponent(); } public AddNodeFrm(CardManager cardManager) { InitializeComponent(); _businessModule = cardManager; if (_businessModule.BType == BusinessType.Card) { Text = GlobalResource.AddNewModule; } else if(_businessModule.BType == BusinessType.Folder) { Text = GlobalResource.AddNewFolder; } } private CardManager _businessModule; public CardManager BusinessModule { get { return _businessModule; } set { _businessModule = value; } } private void btnAdd_Click(object sender, EventArgs e) { try { int currentNode = CardManagerBLL.AddBusiness( txtBusinessName.Text.Trim(), (int)BusinessModule.BType, BusinessModule.ParentNode, BusinessModule.BusinessId); /// 当前节点的Level CurrentNode = currentNode; this.DialogResult = DialogResult.OK; } catch (Exception ex) { MessageBox.Show(ex.Message); this.DialogResult = DialogResult.Cancel; } } private void btnClose_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } public string NewNodeName { get { return txtBusinessName.Text; } set { txtBusinessName.Text = value; } } public int CurrentNode { get; set; } private void txtBusinessName_KeyDown(object sender, KeyEventArgs e) { if ((int)e.KeyCode == 13) { e.SuppressKeyPress = true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeColor : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { // Le code suivant sert a intercepter un ButtonDown event sur l’indexTrigger de // l’oculus Touch et change la couleur de l’objet if (OVRInput.GetDown(OVRInput.Button.SecondaryHandTrigger)) { Color actualColor = this.gameObject.GetComponent<Renderer>().material.color; Color newColor = (actualColor == Color.gray ? Color.red : Color.grey); this.gameObject.GetComponent<Renderer>().material.color = newColor; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiveLecture_10._01._13 { class MultiDimentionalArrays { static void SomeMethod(int[,] nums) { nums[0, 0] = 100; } static void Main() { var numbers = new int[2, 2]; Console.WriteLine(numbers[0, 0]); SomeMethod(numbers); Console.WriteLine(numbers[0, 0]); } } }
using System.Drawing; namespace libthumbnailer { public class FontFactory { public static Font CreateFont(FontFamily fontFamily, int fontSize) { return new Font(fontFamily, fontSize); } } public class BrushFactory { public static SolidBrush CreateBrush(Color color) { return new SolidBrush(color); } } }
using System; namespace Profiling2.Domain.DTO { public class SourceFolderDTO { public string Folder { get; set; } public string ParentFolder { get; set; } public string OwnerCode { get; set; } public int NumFiles { get; set; } public DateTime? LatestFileDate { get; set; } public SourceFolderDTO() { } public SourceFolderDTO(string folder) { if (!string.IsNullOrEmpty(folder)) { this.Folder = folder; int i = folder.LastIndexOf(System.IO.Path.DirectorySeparatorChar); if (i > -1) this.ParentFolder = folder.Substring(0, i); } } } }
using System; using System.Collections.Generic; namespace gView.GraphicsEngine.Abstraction { public interface IBrushCollection : IDisposable { IEnumerable<IBrush> Brushes { get; } } }
using NUnit.Framework; using SimpleLibrary; using SimpleLibrary.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tests { [TestFixture] public class TeacherTests { private IStringHelper _stringHelper; [SetUp] public void Init() { _stringHelper = new StringHelper(); } [Test] public void CheckSubstring() { var result = _stringHelper.GetMySubsting("123456789", 1, 3); Assert.AreEqual("234", result); } [Test] public void CheckNotCallNullException() { var result = _stringHelper.GetMySubsting(null, 0, null); Assert.AreEqual(null, result); } [Test] public void CheckWhenLengthBigThenRealLength() { var result = _stringHelper.GetMySubsting("123456789", 1, 100); Assert.AreEqual("23456789", result); } } }
using System.Collections.Generic; using System.Linq; using Data; using Data.Infrastructure; using Model.Models; using Model.ViewModels; using Core.Common; using System; using Model; using System.Threading.Tasks; using Data.Models; using Model.ViewModel; namespace Service { public interface IRolesDivisionService : IDisposable { RolesDivision Create(RolesDivision pt); void Delete(int id); void Delete(RolesDivision pt); RolesDivision Find(int ptId); void Update(RolesDivision pt); RolesDivision Add(RolesDivision pt); IEnumerable<RolesDivision> GetRolesDivisionList(); RolesDivision Find(int DivisionId, string RoleId); IEnumerable<RolesDivisionViewModel> GetRolesDivisionList(string RoleId); } public class RolesDivisionService : IRolesDivisionService { ApplicationDbContext db = new ApplicationDbContext(); private readonly IUnitOfWorkForService _unitOfWork; private readonly Repository<RolesDivision> _RolesDivisionRepository; RepositoryQuery<RolesDivision> RolesDivisionRepository; public RolesDivisionService(IUnitOfWorkForService unitOfWork) { _unitOfWork = unitOfWork; _RolesDivisionRepository = new Repository<RolesDivision>(db); RolesDivisionRepository = new RepositoryQuery<RolesDivision>(_RolesDivisionRepository); } public RolesDivision Find(int pt) { return _unitOfWork.Repository<RolesDivision>().Find(pt); } public RolesDivision Create(RolesDivision pt) { pt.ObjectState = ObjectState.Added; _unitOfWork.Repository<RolesDivision>().Insert(pt); return pt; } public void Delete(int id) { _unitOfWork.Repository<RolesDivision>().Delete(id); } public void Delete(RolesDivision pt) { _unitOfWork.Repository<RolesDivision>().Delete(pt); } public void Update(RolesDivision pt) { pt.ObjectState = ObjectState.Modified; _unitOfWork.Repository<RolesDivision>().Update(pt); } public IEnumerable<RolesDivision> GetRolesDivisionList() { var pt = _unitOfWork.Repository<RolesDivision>().Query().Get(); return pt; } public RolesDivision Add(RolesDivision pt) { _unitOfWork.Repository<RolesDivision>().Insert(pt); return pt; } public RolesDivision Find(int DivisionId, string RoleId) { return _unitOfWork.Repository<RolesDivision>().Query().Get().Where(m=>m.RoleId==RoleId && m.DivisionId==DivisionId).FirstOrDefault(); } public IEnumerable<RolesDivisionViewModel> GetRolesDivisionList(string RoleId) { return (from p in db.RolesDivision where p.RoleId == RoleId select new RolesDivisionViewModel { DivisionId = p.DivisionId, RoleId = p.RoleId, RoleName = p.Role.Name, RolesDivisionId = p.RolesDivisionId }); } public void Dispose() { } } }
using System; using System.Collections.Generic; using DelftTools.Functions.Filters; using DelftTools.Utils; namespace DelftTools.Functions.Generic { public interface IVariable<T> : IVariable { /// <summary> /// List of values of the variable. /// </summary> new IMultiDimensionalArray<T> Values { get; set; } /// <summary> /// Default value of the variable. Used when number of values in dependent variable changes and default values need to be added. /// </summary> new T DefaultValue { get; set; } /// <summary> /// List of values which will be interpreted as no-data values. /// </summary> new IList<T> NoDataValues { get; set; } /// <summary> /// Gets values with filters /// </summary> /// <param name="filters"></param> /// <returns></returns> new IMultiDimensionalArray<T> GetValues(params IVariableFilter[] filters); new IVariable<T> Clone(); /// <summary> /// /// </summary> /// <param name="values"></param> void AddValues<T>(IEnumerable<T> values); //new T MinValue { get; } //new T MaxValue { get; } NextValueGenerator<T> NextValueGenerator{ get; set; } /// <summary> /// Minimum value of the variable /// </summary> new T MinValue{ get;} /// <summary> /// Maximum value of the variable /// </summary> new T MaxValue { get; } /// <summary> /// Returns all values of the variable. Includes values that have been filtered out. /// </summary> IMultiDimensionalArray<T> AllValues { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WizSE.RPC { public class Server { public class Connection { } } }
using ReactMusicStore.Core.Domain.Entities; using ReactMusicStore.Core.Domain.Interfaces.Service.Common; namespace ReactMusicStore.Core.Domain.Interfaces.Service { public interface IAlbumService : IService<Album> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Groundwork.Domain { public class FakeReadOnlyRepository<TEntity, TopLevelDomain> : IReadOnlyRepository<TEntity, TopLevelDomain> where TEntity : IEntity<TopLevelDomain> { private readonly Dictionary<TopLevelDomain, TEntity> _entities; public FakeReadOnlyRepository(IEnumerable<TEntity> entities) { _entities = new Dictionary<TopLevelDomain, TEntity>(); foreach (var entity in entities) { _entities.Add(entity.Id, entity); } } public int Count => _entities.Count; public bool Contains(TopLevelDomain id) => _entities.ContainsKey(id); public TEntity Get(TopLevelDomain id) { _entities.TryGetValue(id, out TEntity entity); return entity; } public IQueryable<TEntity> Get(Expression<Func<TEntity, bool>> predicate) => _entities.Values.AsQueryable().Where(predicate); public IEnumerable<TEntity> Get() => _entities.Values.ToList(); } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ProjectCompany.Models { public class EmployeeSkill { [Column("employee_id")] public int EmployeeId { get; set; } public Employee Employee {get; set;} [Column("skill_id")] public int SkillId { get; set; } public Skill Skill { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace DAL.Models { public class Model : IModel { public int ModelId { get; set; } public string Brand { get; set; } public string ModelName { get; set; } public string Material { get; set; } public string Category { get; set; } public string ShoeType { get; set; } public string Picture { get; set; } public string Description { get; set; } public decimal Price { get; set; } public void FromSqlReader(SqlDataReader reader) { if (!reader.HasRows) return; ModelId = int.Parse(reader["ModelId"].ToString()); Brand = reader["Brand"].ToString(); ModelName = reader["ModelName"].ToString(); Material = reader["Material"].ToString(); Category = reader["Category"].ToString(); ShoeType = reader["ShoeType"].ToString(); Picture = reader["Picture"].ToString(); Description = reader["Description"].ToString(); Price = decimal.Parse(reader["Price"].ToString()); } } }
using UnityEngine; using System.Collections; using System; using LuaInterface; public sealed class LuaBehaviour : MonoBehaviour { private static string s_luaFileName = null; private LuaTable m_self = null; private LuaFunction m_luaUpdate = null; private LuaFunction m_luaFixedUpdate = null; private LuaFunction m_luaLateUpdate = null; public static string LuaFileName { get { return s_luaFileName; } set { s_luaFileName = value; } } public void Awake() { LuaTable metatable = (LuaTable)MsgHandler.Instance.Require(s_luaFileName); if(metatable == null) { Debug.LogError("[LuaBehaviour] require lua file failed: " + s_luaFileName); return; } LuaFunction newFunc = (LuaFunction)metatable["New"]; if(newFunc == null) { Debug.LogError("[LuaBehaviour] load 'New' lua function failed: " + s_luaFileName); return; } //执行New函数生成脚本对象 object[] res = newFunc.Call(metatable, this); if(res == null || res.Length == 0) { Debug.LogError("[LuaBehaviour] 'New' function should return a table instance: " + s_luaFileName); return; } m_self = (LuaTable)res[0]; //给脚本对象设置上常用的属性 m_self["transform"] = transform; m_self["gameObject"] = gameObject; m_self["behaviour"] = this; m_luaUpdate = (LuaFunction)m_self["Update"]; m_luaFixedUpdate = (LuaFunction)m_self["FixedUpdate"]; m_luaLateUpdate = (LuaFunction)m_self["LateUpdate"]; if(m_luaUpdate == null) { Debug.LogWarning("[LuaBehaviour] luaUpdate function not found"); } if(m_luaFixedUpdate == null) { Debug.LogWarning("[LuaBehaviour] luaFixedUpdate function not found"); } if(m_luaLateUpdate == null) { Debug.LogWarning("[LuaBehaviour] luaLateUpdate function not found"); } CallMethod("Awake"); } // Use this for initialization public void Start () { CallMethod("Start"); } // Update is called once per frame public void Update () { if (m_luaUpdate != null) { m_luaUpdate.Call(m_self); } } public void LateUpdate() { if (m_luaLateUpdate != null) { m_luaLateUpdate.Call(m_self); } } public void FixedUpdate() { if (m_luaFixedUpdate != null) { m_luaFixedUpdate.Call(m_self); } } public void OnDestroy() { Debug.Log("[LuaBehaviour] OnDestroy called"); CallMethod("OnDestroy"); if(m_luaUpdate != null) { m_luaUpdate.Dispose(); m_luaUpdate = null; } if(m_luaFixedUpdate != null) { m_luaFixedUpdate.Dispose(); m_luaFixedUpdate = null; } if(m_luaLateUpdate != null) { m_luaLateUpdate.Dispose(); m_luaLateUpdate = null; } if(m_self != null) { m_self.Dispose(); m_self = null; } } protected object[] CallMethod(string func_, params object[] args_) { if (m_self == null) return null; LuaFunction luaFunc = (LuaFunction)m_self[func_]; if(luaFunc == null) { Debug.LogWarning("[LuaBehaviour] call method failed,lua function not found"); return null; } int oldTop = luaFunc.BeginPCall(); luaFunc.Push(m_self); luaFunc.PushArgs(args_); luaFunc.PCall(); object[] objs = MsgHandler.Instance.GetLuaState().CheckObjects(oldTop); luaFunc.EndPCall(); return objs; } public LuaTable LuaTable() { return m_self; } } /* public class LuaBehaviour : MonoBehaviour { [NoToLuaAttribute] public bool createInCS = false; [NoToLuaAttribute] public string luaFile = null; [NoToLuaAttribute] public string tableName = null; [NoToLuaAttribute] public bool unique = true; protected LuaFunction LuaNew = null; protected LuaFunction LuaAwake = null; protected LuaFunction LuaStart = null; protected LuaFunction LuaOnDestroy = null; protected LuaFunction LuaOnTriggerEnter = null; protected LuaFunction LuaOnTriggerExit = null; protected LuaTable self = null; private LuaState luaState = null; public virtual void SetLuaTable(LuaTable table) { if (self == null) { self = table; self.name = tableName != null ? tableName : gameObject.name; } if (self != null) { LuaAwake = self.GetLuaFunction("Awake") as LuaFunction; LuaStart = self.GetLuaFunction("Start") as LuaFunction; LuaOnDestroy = self.GetLuaFunction("OnDestroy") as LuaFunction; LuaOnTriggerEnter = self.GetLuaFunction("OnTriggerEnter") as LuaFunction; LuaOnTriggerExit = self.GetLuaFunction("OnTriggerExit") as LuaFunction; } } protected void Awake() { luaState = LuaClient.GetMainState(); if (createInCS && luaState != null) { luaState.Require(luaFile); self = luaState.GetTable(tableName); if (!unique) { LuaNew = self.GetLuaFunction("New"); LuaNew.BeginPCall(); LuaNew.PCall(); SafeRelease(ref self); self = LuaNew.CheckLuaTable(); self.name = tableName; LuaNew.EndPCall(); } self["gameObject"] = gameObject; self["this"] = this; SetLuaTable(self); if (LuaAwake != null) { LuaAwake.BeginPCall(); LuaAwake.Push(self); LuaAwake.PCall(); LuaAwake.EndPCall(); } } } protected void SafeRelease(ref LuaFunction func) { if (func != null) { func.Dispose(); func = null; } } protected void SafeRelease(ref LuaTable table) { if (table != null) { table.Dispose(); table = null; } } protected void Release() { SafeRelease(ref LuaNew); SafeRelease(ref LuaAwake); SafeRelease(ref LuaStart); SafeRelease(ref LuaOnDestroy); SafeRelease(ref LuaOnTriggerEnter); SafeRelease(ref LuaOnTriggerExit); //SafeRelease(ref update); //SafeRelease(ref lateUpdate); //SafeRelease(ref fixedUpdate); SafeRelease(ref self); } protected void Start() { if (LuaStart != null) { LuaStart.BeginPCall(); LuaStart.Push(self); LuaStart.PCall(); LuaStart.EndPCall(); } //beStart = true; //AddUpdate(); } protected void OnDestroy() { if (LuaOnDestroy != null && luaState != null) { LuaOnDestroy.BeginPCall(); LuaOnDestroy.Push(self); LuaOnDestroy.PCall(); LuaOnDestroy.EndPCall(); Release(); } } protected void OnApplicationQuit() { LuaOnDestroy = null; } void OnTriggerEnter(Collider other) { if (LuaOnTriggerEnter != null) { LuaOnTriggerEnter.BeginPCall(); LuaOnTriggerEnter.Push(self); LuaOnTriggerEnter.Push(other); LuaOnTriggerEnter.PCall(); LuaOnTriggerEnter.EndPCall(); } } void OnTriggerExit(Collider other) { if (LuaOnTriggerExit != null) { LuaOnTriggerExit.BeginPCall(); LuaOnTriggerExit.Push(self); LuaOnTriggerExit.Push(other); LuaOnTriggerExit.PCall(); LuaOnTriggerExit.EndPCall(); } } } */
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class DirectController : MonoBehaviour, IPointerUpHandler, IPointerDownHandler { public void OnPointerDown(PointerEventData data_) { if (gameObject.name == "UpBtn") { PlayController.s_rocketController.UpPressed = true; } else if (gameObject.name == "DownBtn") { PlayController.s_rocketController.DownPressed = true; } else if (gameObject.name == "LeftBtn") { PlayController.s_rocketController.LeftPressed = true; } else if (gameObject.name == "RightBtn") { PlayController.s_rocketController.RightPressed = true; } Debug.Log("OnPointerDown gameobject name:" + gameObject.name); } public void OnPointerUp(PointerEventData data_) { if (gameObject.name == "UpBtn") { PlayController.s_rocketController.UpPressed = false; } else if (gameObject.name == "DownBtn") { PlayController.s_rocketController.DownPressed = false; } else if (gameObject.name == "LeftBtn") { PlayController.s_rocketController.LeftPressed = false; } else if (gameObject.name == "RightBtn") { PlayController.s_rocketController.RightPressed = false; } Debug.Log("OnPointerUp gameobject name:" + gameObject.name); } }
#if !NET45 namespace Vlc.DotNet.Wpf { using System; using System.Runtime.InteropServices; public static class Win32Interop { /// <summary> /// Creates or opens a named or unnamed file mapping object for a specified file. /// </summary> /// <param name="hFile">A handle to the file from which to create a file mapping object.</param> /// <param name="lpAttributes">A pointer to a SECURITY_ATTRIBUTES structure that determines whether a returned handle can be inherited by child processes. The lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure specifies a security descriptor for a new file mapping object.</param> /// <param name="flProtect">Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection.</param> /// <param name="dwMaximumSizeLow">The high-order DWORD of the maximum size of the file mapping object.</param> /// <param name="dwMaximumSizeHigh">The low-order DWORD of the maximum size of the file mapping object.</param> /// <param name="lpName">The name of the file mapping object.</param> /// <returns>The value is a handle to the newly created file mapping object.</returns> [DllImport("kernel32", SetLastError = true)] public static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpAttributes, PageAccess flProtect, int dwMaximumSizeLow, int dwMaximumSizeHigh, string lpName); /// <summary> /// Maps a view of a file mapping into the address space of a calling process. /// </summary> /// <param name="hFileMappingObject">A handle to a file mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.</param> /// <param name="dwDesiredAccess">The type of access to a file mapping object, which determines the protection of the pages. This parameter can be one of the following values.</param> /// <param name="dwFileOffsetHigh">A high-order DWORD of the file offset where the view begins.</param> /// <param name="dwFileOffsetLow">A low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within the file mapping.</param> /// <param name="dwNumberOfBytesToMap">The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by CreateFileMapping. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping.</param> /// <returns>The value is the starting address of the mapped view.</returns> [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, FileMapAccess dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap); /// <summary> /// Unmaps a mapped view of a file from the calling process's address space. /// </summary> /// <param name="lpBaseAddress">A pointer to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value returned by a previous call to the MapViewOfFile or MapViewOfFileEx function.</param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [DllImport("kernel32", SetLastError = true)] public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); /// <summary> /// Closes an open object handle. /// </summary> /// <param name="handle">A valid handle to an open object.</param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); public enum PageAccess { NoAccess = 0x01, ReadOnly = 0x02, ReadWrite = 0x04, WriteCopy = 0x08, Execute = 0x10, ExecuteRead = 0x20, ExecuteReadWrite = 0x40, ExecuteWriteCopy = 0x80, Guard = 0x100, NoCache = 0x200, WriteCombine = 0x400 } public enum FileMapAccess : uint { Write = 0x00000002, Read = 0x00000004, AllAccess = 0x000f001f, Copy = 0x00000001, Execute = 0x00000020 } } } #endif
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Text; using System.IO; using System.Drawing; namespace jaytwo.Common.Http { public partial class HttpClient { public Image DownloadImage(string url) { var request = CreateRequest(url); return DownloadImage(request); } public Image DownloadImage(Uri uri) { var request = CreateRequest(uri); return DownloadImage(request); } public Image DownloadImage(HttpWebRequest request) { using (var response = Submit(request, HttpMethod.GET)) { return DownloadImage(response); } } public Image DownloadImage(HttpWebResponse response) { var resultBytes = DownloadBytes(response); using (var imageStream = new MemoryStream(resultBytes)) { return Image.FromStream(imageStream); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AngleSharp.Parser.Html; using AngleSharp.Dom.Html; using System.Net; using System.Net.Http; namespace GitDrawer.GitCore { class Parser { //url of repository commits information string gitRepsUrl = "https://github.com/{CurrentUser}?tab=repositories"; string gitRepComsUrl = "https://github.com/{CurrentRep}/commits/"; DateTime SearchingDate; public event Action<string> OnError; public event Action<string> OnNewData; public event Action<int> OnCommits; public Parser(string username, DateTime searchingDate) { gitRepsUrl = gitRepsUrl.Replace("{CurrentUser}", username); SearchingDate = searchingDate; Parse(); } private async void Parse() { int CommitsInDay = 0; try { var domParser = new HtmlParser(); HtmlLoader RepsLoader = new HtmlLoader(gitRepsUrl); var RepsSource = await RepsLoader.GetSource(); var gitPageDoc = await domParser.ParseAsync(RepsSource); var divs = gitPageDoc.QuerySelectorAll("div").Where(item => item.ClassName != null && item.ClassName.Contains("d-inline-block mb-1")); foreach (var div in divs) { string repName = div.QuerySelectorAll("a").FirstOrDefault().GetAttribute("href"); HtmlLoader CommitsLoader = new HtmlLoader(gitRepComsUrl.Replace("{CurrentRep}", repName)); var CommitsSource = await CommitsLoader.GetSource(); var gitCommitsDoc = await domParser.ParseAsync(CommitsSource); var times = gitCommitsDoc.QuerySelectorAll("relative-time"); foreach (var time in times) { string s = time.GetAttribute("datetime").Split('T')[0]; DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); bool isSame = (dt.DayOfYear == SearchingDate.DayOfYear); if (isSame) CommitsInDay++; OnNewData?.Invoke(repName + ": " + dt.ToLongDateString() + " : " + SearchingDate.ToLongDateString() + " ? " + isSame.ToString()); } } } catch { OnError?.Invoke("Error"); } OnCommits?.Invoke(CommitsInDay); } class HtmlLoader { readonly HttpClient client; readonly string url; public HtmlLoader(string url) { client = new HttpClient(); this.url = url; } public async Task<string> GetSource() { var response = await client.GetAsync(url); string source = null; if (response != null && response.StatusCode == HttpStatusCode.OK) { source = await response.Content.ReadAsStringAsync(); } return source; } } } }
using UnityEngine.UI; using UnityEngine; using TMPro; public class ItemUI : MonoBehaviour { public CollectableScript CS; GameObject ItemDetail; GameObject CanvasOri; Transform Canvas; ItemDetail ID; [SerializeField] GameObject ItemDetaidPrefab; public Image ItemIcon; public TextMeshProUGUI Name; public void Start() { CanvasOri = GameObject.FindWithTag("Canvas"); Canvas = CanvasOri.transform; ItemIcon.sprite = CS.Icon; Name.text = CS.Name; } public void Clickitem() { ItemDetail = Instantiate(ItemDetaidPrefab, Canvas); ID = ItemDetail.GetComponent<ItemDetail>(); ID.ItemUI = this; ID.CS = CS; } public void DestroySelf() { Destroy(gameObject); } }
using System; using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.Extensions; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Exceptions; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Helpers; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Parts; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement; using DFC.ServiceTaxonomy.Taxonomies.Models; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts { public class TermPartGraphSyncer : ContentPartGraphSyncer, ITermPartGraphSyncer { public override string PartName => nameof(TermPart); private const string TaxonomyContentItemId = "TaxonomyContentItemId"; private readonly IServiceProvider _serviceProvider; public TermPartGraphSyncer(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override async Task AddSyncComponents(JObject content, IGraphMergeContext context) { string? taxonomyContentItemId = (string?)content[TaxonomyContentItemId]; if (taxonomyContentItemId == null) throw new GraphSyncException($"{PartName} is missing {TaxonomyContentItemId}."); //todo: check for null ContentItem? contentItem = await context.ContentItemVersion.GetContentItem(context.ContentManager, taxonomyContentItemId); ISyncNameProvider termSyncNameProvider = _serviceProvider.GetSyncNameProvider(contentItem!.ContentType); //todo: override/extension that takes a contentitem context.ReplaceRelationshipsCommand.AddRelationshipsTo( //todo: go through syncNameProvider $"has{contentItem.ContentType}", null, await termSyncNameProvider.NodeLabels(), termSyncNameProvider.IdPropertyName(), termSyncNameProvider.GetNodeIdPropertyValue(contentItem.Content.GraphSyncPart, context.ContentItemVersion)); } //todo: would need to add AddSyncComponentsDetaching if we start using this public override Task<(bool validated, string failureReason)> ValidateSyncComponent( JObject content, IValidateAndRepairContext context) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace Foundry.Security { public interface IAuthorizationService { AuthorizationInformation GetAuthorizationInformation(Guid userId); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //by julia duda public class FallDecector : MonoBehaviour { //dodaje cheakpoint, który ma zapisaną pozycje starową Playera Vector3 cheakpoint; void Start() { cheakpoint = new Vector3(-10, 2, 3); } // Update is called once per frame //tworze warunek: jeżeli pozycja y playera będzie niższa niż -5 ma ona nas przemieścić do cheakpointu; void Update() { if (transform.position.y < -5) { transform.position = cheakpoint; } } }
using ProjetDLL; using System; using System.IO; namespace ProjetConsole { class Program { static void Main(string[] args) { // Ceci est un commentaire sur une ligne /* * ceci est un commentaire sur plusieurs lignes */ Console.WriteLine("Test de c#"); Tools.MaMethod(); #region Variables Console.WriteLine("***************************Variables*****************************"); //Variable; zone mémoire qui contient une valeur typé; //Type simples (types valeur): entier, réels, boolean, char //Type complexes (type références): tableau, string, dates, Classes (Objects) //entiers: byte(1 o), short (2 o), int (4 o), long (8 o) //réels: float(4 o), double (8 o), decimal (16 o) //declaration d'une varibale: type, nom_variable = valeur; int myInt = 10; int myInt2 = myInt; myInt = 20; Console.WriteLine("Contenu de myInt: " + myInt);// le + est une concatenation double myDouble = 10.5; char myChar = 'b'; bool myBool = true; string myString = "M"; // mot clef var: inférence de type - c'est le compilateur qui détermine le type de la varibale selon sa valeur; var maVariable = 10; //type nullablrd: .net propose une synthaxe qui permet de définir des types mples null int? x = null; //Avant utilisation de x , on doit vérifier qu'elle contient une valeur if (x.HasValue) { Console.WriteLine("x n'est pas null"); } else { Console.WriteLine("x est null"); } string str = null; int age = 0; Console.WriteLine("quel est votre age?"); age = Convert.ToInt32(Console.ReadLine()); // si le user oublie de fournir l'age on aura une erreur Console.WriteLine("Votre age est de :" + age); //Constante : varaible contenant une valeu non modifiable const double MA_CONSTANTE = 10.5; #endregion #region Operateurs Console.WriteLine("***************************Operateur*****************************"); //opérateur mathématiques: +, -, *, /, %(Modulo: reste de la division entière Console.WriteLine("Reste de la division de 10 par 3" + (10 % 3)); //opératuers combinés: +=, -=, *=, /= myInt += 5; // myInt = myInt +5 //opératuers d'incrémentation et de décrementation int val = 0; Console.WriteLine(val++); Console.WriteLine(6 + "5" + 2); // sortie 652; Console.WriteLine(6 + 2 + "5"); // sortie 85 Console.WriteLine("6" + 5 + 2); //sortie 652 //operateur de comparaison : ==, <, >, <=, >=, != //operateur logique: &&(et logique), || (ou logique), ! (non logique), ^ (ou exclusif) int v1 = 10, v2 = 15; Console.WriteLine((v1 > v2 && (v1 < v2))); //Table logique //A B A&&B A||B A^B //v v v v f //v f f v v //f v f v v //f f f f f #endregion #region Conversion de type Console.WriteLine("***************************Conversion de type*****************************"); //conversion implicite: concerne le passsage d'un type inferieur a un type supérieur byte myByte = 10; int myInt3 = myByte; //Conversion explicite: passage d'un type sup à un type inf - risque de perte de données //Pour les conversions explicites on peut utiliser: //CAST: (int), (byte), (double) ... //La classe Convert int myInt4 = 20; byte myByte2 = (byte)myInt4; byte myByte3 = Convert.ToByte(myInt4); string chaine = "25"; int myInt5 = Convert.ToInt32(chaine); int myInt6 = int.Parse(chaine); #endregion #region Conditions Console.WriteLine("***************************Conditions*****************************"); //Exprimer un test conditionnel: if(condition = vrai ) {instruction} else {instructions;} int nb = 5; if (nb > 0) { Console.WriteLine("nb positif"); } else if (nb == 0) { Console.WriteLine("nb est null"); } else { Console.WriteLine("nb est negatif"); } //Switch: est une variant de la condition if int note = 10; switch (note) { case 0: Console.WriteLine("recalé"); break; case 10: case 11: case 12: Console.WriteLine("Les 10 , 11 et 12"); break; default: Console.WriteLine("Autres notes"); break; } #endregion #region Boucles Console.WriteLine("***************************Boucles*****************************"); //Boucles conditionnelles: While , do while //Boucles Itératives: For, for each - répéter un traitement un certain nombre de fois //for for (int i = 0; i < 10; i++) { //Passer à l'itération suivante : si i == 3 if (i ==3) { continue; } Console.WriteLine("Passage numéro:" + i); //Quitter la boucle for si i = 6 if (i == 6) { break; // permet de sortir de la boucle for } } //for each - permet de faire un parcours complet d'une collection int[] tab = {1, 2, 3, 4}; foreach (int item in tab) { Console.WriteLine(item); } //while int valeur = 1; while (valeur < 5) // Tant que valeur est inférieur a 5 { Console.WriteLine("Passage numéro : " + valeur); valeur++; } // do while : s'execute au moins une fois do { Console.WriteLine("Passage numéro :" + valeur); valeur++; } while (valeur < 10); // si l'age est compris entre 18 et 60 afficher Valide - sinon age non - saisir un nouveau age do { Console.WriteLine("Quel est votre age :"); int ageUser = Convert.ToInt32(Console.ReadLine()); if (ageUser >= 18 && ageUser <=60) { break; } } while (true); #endregion #region Tableaux Console.WriteLine("***************************Tableaux*****************************"); //Tableau: un ensemble d'éléments typés // 1 dimension //déclaration d'un tableau int[] tableau = new int[3]; // tableau de 3 cases tableau[0] = 10; tableau[1] = 20; tableau[2] = 30; Console.WriteLine("taille du tableau : " + tableau.Length); //3 //Parcours du tableau avec la boucle foreach foreach (int item in tableau) { Console.WriteLine(item); } for (int i = 0; i < tableau.Length ; i++) { Console.WriteLine(tableau[i]); } //Deuxieme facon de déclarer un tableau int[] tableau2 = {10 , 20 , 30 }; //tableau à deux dimensions int[,] matrice = new int[2, 3]; matrice[0, 0] = 10; matrice[0, 1] = 20; matrice[0, 2] = 30; matrice[1, 0] = 40; matrice[1, 1] = 50; matrice[1, 2] = 60; Console.WriteLine(matrice[0,2]); int[,] matrice2 = { {10,15,58 }, {12,25,32 } }; //autre facon de déclarer un tableau à deux dimensions Console.WriteLine("nombre de ligne de la matrice2 :" + matrice2.GetLength(0)); //2 Console.WriteLine("nombre de colonnes" + matrice2.GetLength(1)); //3 Console.WriteLine("nombre total d'éléments de matrice2:" + matrice2.Length); //6 Console.WriteLine("nombre de dimensions de matrice2:" + matrice2.Rank); //2 #endregion #region Methodes Console.WriteLine("***************************Methodes*****************************"); //méthodes: un ensemble d'instruction réutilisable //dans la programmation objet on a 2 types de méthodes: //Procédures: méthode qui ne renvoie aucune valeur (void) //fonctions: méthode qui renvoie une valeur ou un résultats - on doit préciser le type du résultat renvoyé //déclaration d'une méthode: Visibilité (mot clé static), type de retour, nom méthode(paramètres){instructions;} /*MesMethodes mm = new MesMethodes(); mm.Somme(10, 20);*/ int resultat = MesMethodes.Somme(10, 20); Console.WriteLine(resultat); MesMethodes.Afficher(); int[] monTableau = { 10, 1, 20, 15 }; MesMethodes.Afficher(monTableau); Console.WriteLine("somme tab : " + MesMethodes.SommeTab(monTableau)); Console.WriteLine("average tab : " + MesMethodes.AverageTab(monTableau)); Console.WriteLine("littlest element tab : " + MesMethodes.LittlestElemTab(monTableau)); //appelle de la méthode SumOpt MesMethodes.SumOpt(10,20); //Valeur par défaut de z qui est pris en compte MesMethodes.SumOpt(10, 20, 50); int val1 = 10, val2 = 20; //Concaténation + Console.WriteLine("concaténation" + MesMethodes.Somme(val1, val2)); //interpolation Console.WriteLine($"Avant permutation : val1 = {val1} - val2 = {val2}"); MesMethodes.Permutation( ref val1, ref val2); Console.WriteLine($"Après permutation : val1 = {val1} - val2 = {val2}"); // appelle de méthode avec des parametres de sortie double sum = 0, moyenne = 0; double produit = MesMethodes.Calculer(10, 20, out sum, out moyenne ); Console.WriteLine($"Produit = {produit}"); Console.WriteLine($"Somme = {sum}"); Console.WriteLine($"Moyenne = {moyenne}"); //appelle de la méthode avec un nombre variable d'arguments MesMethodes.Produit(10, 20); MesMethodes.Produit(10, 20, 30); MesMethodes.Produit(10, 20, 30, 40); #endregion // Maintenir la console active Console.ReadLine(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using CEMAPI.Models; using CEMAPI.DAL; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using CEMAPI.Controllers; using log4net; namespace CEMAPI.BAL { public class TransitionToCEMBAL { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); TETechuvaDBContext context = new TETechuvaDBContext(); CEMEmailControllerBal email = new CEMEmailControllerBal(); public TransitionToCEMBAL() { context.Configuration.ProxyCreationEnabled = false; } public HttpResponseMessage GetCEMManagersByProjectId(JObject json) { string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); try { int projectId = json["ProjectID"].ToObject<int>(); if (projectId == 0) { errorMsg = String.Format("Invalid Project Id: {0} Received", projectId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } List<CEMManagersInfoDTO> cemManagerslist = genDAL.GetCEMManagersByProjectId(projectId); if (cemManagerslist != null && cemManagerslist.Count > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Success"; return new HttpResponseMessage() { Content = new JsonContent(new { result = cemManagerslist, info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "No Records Found"; return new HttpResponseMessage() { Content = new JsonContent(new { result = cemManagerslist, info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to retrieve Customer Summary List"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage IntiateTransitionToCEM(JObject json) { string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null, updatedOffer = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); try { int offerId = json["OfferId"].ToObject<int>(); int cEMManagerId = json["CEMManagerId"].ToObject<int>(); int lastModifiedBy_Id = json["LastModifiedBy_Id"].ToObject<int>(); #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (cEMManagerId == 0) { errorMsg = String.Format("Invalid CEMManager Id: {0} Received", cEMManagerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (lastModifiedBy_Id == 0) { errorMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedBy_Id.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && offerObj.OrderStatus == "TS Signed" && offerObj.IsEMD == true)) { string isEMD = "No"; if (offerObj.IsEMD == true) isEMD = "Yes"; errorMsg = String.Format("Transition to CEM cannot be intiated for received Offer Id: {0}. Offer Status: {1}, EMD Completed: {2}", offerId.ToString(), offerObj.OrderStatus, isEMD); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && (offerObj.TransitionStatus != "Transition Not Intiated" && offerObj.TransitionStatus != "Rejected")) { errorMsg = String.Format("Transition to CEM cannot be intiated for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && offerObj.TransitionStatus == "Transition Intiated") { errorMsg = String.Format("Transition to CEM already intiated for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } //if (offerObj.OfferID > 0 && !genDAL.IsPostLaunchOffer(offerObj.OfferID)) //{ // errorMsg = String.Format("Transition to CEM can be intiated only for PostLaunch Offers"); // finfo.errorcode = 1; // finfo.errormessage = errorMsg; // return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; //} UserProfile cemMgrUserObj = genDAL.GetUserByUserId(cEMManagerId); if (cemMgrUserObj == null || cemMgrUserObj.UserId == 0) { errorMsg = String.Format("CEMManager User not found with received User Id: {0}", cEMManagerId.ToString()); throw new InvalidDataException(errorMsg); } UserProfile lastModifiedByUserObj = genDAL.GetUserByUserId(lastModifiedBy_Id); if (lastModifiedByUserObj == null || lastModifiedByUserObj.UserId == 0) { errorMsg = String.Format("LastModifiedBy User not found with received User Id: {0}", lastModifiedBy_Id.ToString()); throw new InvalidDataException(errorMsg); } #endregion List<TECollection> colln = context.TECollections.Where(a => a.SAPCustomerID == offerObj.SAPCustomerID && (a.Status == "Received" || a.Status == "Deposited")).ToList(); if (colln.Count > 0) { List<TECollection> collrecieved = context.TECollections.Where(a => a.SAPCustomerID == offerObj.SAPCustomerID && (a.Status == "Cleared")).ToList(); if (collrecieved.Count > 0) { decimal minEMDAmnt = 0; var emdRuleValue = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("MinimumEMDAmountRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); if(emdRuleValue != null) minEMDAmnt = Convert.ToDecimal(emdRuleValue); decimal? receivedAmount = collrecieved.Sum(a => a.Amount); if (receivedAmount < minEMDAmnt) { finfo.errorcode = 1; finfo.errormessage = "Receipts under Clearance, Minimum amount not received, Transition cannot proceed"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } } //Save Transition Measures for this Offer SuccessInfo tempSI = cemDAL.SaveMeasuresForIntiateTransitionToCEM(offerId, lastModifiedBy_Id); if (tempSI != null && tempSI.errorcode > 0) { return new HttpResponseMessage() { Content = new JsonContent(new { info = tempSI }) }; } //Update Offer Details with Transition to CEM details if (offerObj != null && offerObj.OfferID > 0) { offerObj.CEMmanager = cEMManagerId; offerObj.LastModifiedBy_Id = lastModifiedBy_Id; offerObj.TransitionStatus = "Transition Intiated"; offerObj.LastModifiedOn = DateTime.Now; updatedOffer = genDAL.UpdateOffer(offerObj); } //save offer event data genDAL.SaveOfferEvent(offerId, "TRANSITONINITAITEDDATE", lastModifiedBy_Id); if (updatedOffer.TransitionStatus == "Transition Intiated") { sinfo.errorcode = 0; sinfo.errormessage = "TransitionToCEM Intiated Successfully"; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Failed to do TransitionToCEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to do TransitionToCEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage ReAssignCEMManager(JObject json) { string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); bool isReAssigned = false; try { int offerId = json["OfferId"].ToObject<int>(); int cEMManagerId = json["CEMManagerId"].ToObject<int>(); int lastModifiedBy_Id = json["LastModifiedBy_Id"].ToObject<int>(); #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (cEMManagerId == 0) { errorMsg = String.Format("Invalid CEMManager Id: {0} Received", cEMManagerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (lastModifiedBy_Id == 0) { errorMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedBy_Id.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && (offerObj.OrderStatus == "TS Signed" || offerObj.OrderStatus == "Confirmed") && offerObj.IsEMD == true && offerObj.CEMmanager>0)) { string isEMD = "No"; if (offerObj.IsEMD == true) isEMD = "Yes"; errorMsg = String.Format("Re-Assign cannot be done for received Offer Id: {0}. Offer Status: {1}, EMD Completed: {2}", offerId.ToString(), offerObj.OrderStatus, isEMD); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && offerObj.TransitionStatus != "Transition Intiated") { errorMsg = String.Format("Re-Assign cannot be done for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } UserProfile cemMgrUserObj = genDAL.GetUserByUserId(cEMManagerId); if (cemMgrUserObj == null || cemMgrUserObj.UserId == 0) { errorMsg = String.Format("CEMManager User not found with received User Id: {0}", cEMManagerId.ToString()); throw new InvalidDataException(errorMsg); } UserProfile lastModifiedByUserObj = genDAL.GetUserByUserId(lastModifiedBy_Id); if (lastModifiedByUserObj == null || lastModifiedByUserObj.UserId == 0) { errorMsg = String.Format("LastModifiedBy User not found with received User Id: {0}", lastModifiedBy_Id.ToString()); throw new InvalidDataException(errorMsg); } #endregion //ResSet the Transition Measures for this Offer to false cemDAL.ResetTransitionMeasuresByOfferId(offerId, lastModifiedBy_Id); //Update Offer Details with Re-Assigned CEM Manager Details if (offerObj != null && offerObj.OfferID > 0) { offerObj.CEMmanager = cEMManagerId; offerObj.LastModifiedBy_Id = lastModifiedBy_Id; offerObj.LastModifiedOn = DateTime.Now; genDAL.UpdateOffer(offerObj); } isReAssigned = true; if (isReAssigned) { sinfo.errorcode = 0; sinfo.errormessage = "Re-Assign completed Successfully"; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Failed to do Re-Assign"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to do Re-Assign"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage GetTransitionToCEMMeasuresByOfferId(JObject json) { string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); List<TransitionToCEMMeasureInfoDTO> measuresList = null; try { int offerId = json["OfferId"].ToObject<int>(); #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && offerObj.OrderStatus == "TS Signed" && offerObj.IsEMD == true)) { string isEMD = "No"; if (offerObj.IsEMD == true) isEMD = "Yes"; errorMsg = String.Format("Accept Transition to CEM cannot be done for received Offer Id: {0}. Offer Status: {1}, EMD Completed: {2}", offerId.ToString(), offerObj.OrderStatus, isEMD); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && offerObj.TransitionStatus != "Transition Intiated") { errorMsg = String.Format("Accept Transition to CEM cannot be done for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion measuresList = cemDAL.GetTransitionToCEMMeasuresByOfferId(offerId); if (measuresList != null && measuresList.Count > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Success"; return new HttpResponseMessage() { Content = new JsonContent(new { result = measuresList, info = sinfo }) }; } else { sinfo.errorcode = 0; sinfo.errormessage = "Transition to CEM Measures Not Found"; return new HttpResponseMessage() { Content = new JsonContent(new { result = measuresList, info = sinfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to retrieve Transition to CEM Measures List"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage AcceptTransitionToCEMByOfferId(JObject json, int lastModifiedById) { string errorMsg = string.Empty, saleOrderId = string.Empty, notes = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null, updatedOffer = null; List<TRANSITIONTOCEMMEASURE> measuresList = null, modifiedMeasuresList = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); int checkedMeasuresCount = 0; List<int?> orgMeasureIds = new List<int?>(); List<int?> measureIds = null; try { int offerId = json["OfferID"].ToObject<int>(); if (json["MeasureId"] != null) { if (json["MeasureId"].HasValues) { JToken json1 = json["MeasureId"]; if (json1 is JArray) { orgMeasureIds = json["MeasureId"].ToObject<List<int?>>(); } } } if (json["Notes"] != null) { notes= json["Notes"].ToObject<string>(); } if (orgMeasureIds != null && orgMeasureIds.Count > 0) { measureIds = new List<int?>(); foreach (int measure in orgMeasureIds) { if (measure > 0) measureIds.Add(measure); } } #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } //if (measureIds == null || measureIds.Count == 0) //{ // errorMsg = String.Format("Transition to CEM Measures not Received"); // finfo.errorcode = 1; // finfo.errormessage = errorMsg; // return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; //} if (lastModifiedById == 0) { errorMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedById.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && offerObj.OrderStatus == "TS Signed" && offerObj.IsEMD == true)) { string isEMD = "No"; if (offerObj.IsEMD == true) isEMD = "Yes"; errorMsg = String.Format("Accept Transition to CEM cannot be done for received Offer Id: {0}. Offer Status: {1}, EMD Completed: {2}", offerId.ToString(), offerObj.OrderStatus, isEMD); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && offerObj.TransitionStatus != "Transition Intiated") { errorMsg = String.Format("Accept Transition to CEM cannot be done for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } //if (offerObj.OfferID > 0 && !genDAL.IsPostLaunchOffer(offerObj.OfferID)) //{ // errorMsg = String.Format("Accept Transition to CEM can be allowed only for PostLaunch Offers"); // finfo.errorcode = 1; // finfo.errormessage = errorMsg; // return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; //} #endregion measuresList = cemDAL.GetTransitionToCEMMeasuresListByOfferId(offerId); int orgMeasuresCount = measuresList.Count; if (orgMeasuresCount > 0) { modifiedMeasuresList = new List<TRANSITIONTOCEMMEASURE>(); foreach (TRANSITIONTOCEMMEASURE cemMeasure in measuresList) { if (measureIds.Contains(cemMeasure.MEASUREID)) cemMeasure.ISCHECKED = true; else cemMeasure.ISCHECKED = false; cemMeasure.MODIFIEDBY = lastModifiedById; cemMeasure.MODIFIEDON = DateTime.Now; TRANSITIONTOCEMMEASURE modifiedMeasure = cemDAL.UpdateTransitionToCEMMeasure(cemMeasure); modifiedMeasuresList.Add(modifiedMeasure); } foreach (TRANSITIONTOCEMMEASURE cemMeasure in modifiedMeasuresList) { if (cemMeasure.ISCHECKED == true) checkedMeasuresCount = checkedMeasuresCount + 1; } if (checkedMeasuresCount+1 == orgMeasuresCount) { if (genDAL.IsPostLaunchOffer(offerObj.OfferID) == true) { saleOrderId = cemDAL.GenerateSaleOrder(offerObj.UnitID, offerObj.ProjectID, offerObj.OfferID); if (!string.IsNullOrEmpty(saleOrderId)) { //Update Offer Details with Transition to CEM details if (offerObj != null && offerObj.OfferID > 0) { offerObj.LastModifiedBy_Id = lastModifiedById; offerObj.TransitionStatus = "Accepted"; offerObj.OrderStatus = "Confirmed"; offerObj.LastModifiedOn = DateTime.Now; offerObj.SAPOrderID = saleOrderId; var Ids = (from unit in context.TEUnits join tower in context.TETowerMasters on unit.TowerID equals tower.TowerID where unit.UnitID == offerObj.UnitID select new { unit.TowerID, offerObj.ProjectID }).FirstOrDefault(); var completionpercentage = (from tower in context.TETowerMasters where tower.TowerID == Ids.TowerID select tower.CurrentCompletionPercentage).FirstOrDefault(); var ReImbursementRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("ReImbursementRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var CancellationFeeRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("CancellationFeeRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var DelayCompensationRate = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("DelayCompensationRate") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var DelayCompensatoinRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("DelayCompensationRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var TransferOrderFeeRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("TransferOrderFee") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); offerObj.ConstructionComplPercentage = (completionpercentage != null || completionpercentage != "") ? Convert.ToDecimal(completionpercentage) : 0; offerObj.ReImbursementAmount = (ReImbursementRule != null || ReImbursementRule != "") ? Convert.ToInt32(ReImbursementRule) : 0; offerObj.DelayCompensationRate = (DelayCompensationRate != null || DelayCompensationRate != "") ? Convert.ToDecimal(DelayCompensationRate) : 0; offerObj.CancellationFee = (CancellationFeeRule != null || CancellationFeeRule != "") ? Convert.ToDecimal(CancellationFeeRule) : 0; offerObj.DelayCompensatoinRule = (DelayCompensatoinRule != null || DelayCompensatoinRule != "") ? Convert.ToDecimal(DelayCompensatoinRule) : 0; offerObj.TransferOrderFee = (TransferOrderFeeRule != null || TransferOrderFeeRule != "") ? Convert.ToDecimal(TransferOrderFeeRule) : 0; updatedOffer = genDAL.UpdateOffer(offerObj); } //updaate lead stage TELead tlead = context.TELeads.Where(l => l.LeadID == offerObj.LeadID && l.IsDeleted == false).FirstOrDefault(); tlead.LeadStageNum = 0; tlead.LeadStage = context.TELeadStageMasters.Where(a => a.LeadStageNum == 0 && a.IsDeleted == false).Select(a => a.LeadStage).FirstOrDefault(); ; tlead.LastModifiedOn = DateTime.Now; context.Entry(tlead).CurrentValues.SetValues(tlead); context.SaveChanges(); //save offer event data genDAL.SaveOfferEvent(offerId, "TRANSITIONACCEPTEDDATE", lastModifiedById); //save offer event data genDAL.SaveOfferEvent(offerId, "SALEORDERGENERATEDDATE", lastModifiedById); //update unit details try { int? unitid = offerObj.UnitID; TEUnit tempUnits = context.TEUnits.Where(a => a.UnitID == unitid).FirstOrDefault(); tempUnits.Status = "Sold"; tempUnits.LastModifiedDate = DateTime.Now; context.Entry(tempUnits).CurrentValues.SetValues(tempUnits); context.SaveChanges(); } catch (Exception ex) { } //EMD milestone invoice confirmation - mahipal 14-may-2018 int MilesotneId = 0; var emdMilestone = context.TEOfferMileStones.Where(a => a.OfferID == offerId && a.IsDeleted == false && a.Code == "EMD" ).FirstOrDefault(); if (emdMilestone != null) { MilesotneId = emdMilestone.MileStoneID; } SuccessInfo sucinfo = new SuccessInfo(); sucinfo = new InvoiceDAL().GenerateInvoiceForMainMilestone(MilesotneId, lastModifiedById); //Save offer notes TENote note; if (!string.IsNullOrEmpty(notes)) note = cemDAL.SaveAcceptTransitionToCEMRemarksInNotes(notes, offerId, lastModifiedById); //For the leads generated from BP Mobile App, when ever Tansition to CEM is done need to update the status //as "Transitioned" in BPLeadStaging int? leadId = offerObj.LeadID; TEBPLeadsStaging bpLead = context.TEBPLeadsStagings.Where(a => a.TELeadId == leadId && a.IsDeleted == false).FirstOrDefault(); if (bpLead != null && bpLead.BPLeadsStagingID > 0) { if (bpLead.status == "TS Signed") { bpLead.status = "Transitioned"; context.Entry(bpLead).CurrentValues.SetValues(bpLead); context.SaveChanges(); } } } else { errorMsg = String.Format("Transition not completed Successfully. SAP Sale Order Id not gernerated"); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } else { //Update Offer Details with Transition to CEM details if (offerObj != null && offerObj.OfferID > 0) { offerObj.LastModifiedBy_Id = lastModifiedById; offerObj.TransitionStatus = "Accepted"; offerObj.OrderStatus = "Confirmed"; offerObj.LastModifiedOn = DateTime.Now; //offerObj.SAPOrderID = saleOrderId; var Ids = (from unit in context.TEUnits join tower in context.TETowerMasters on unit.TowerID equals tower.TowerID where unit.UnitID == offerObj.UnitID select new { unit.TowerID, offerObj.ProjectID }).FirstOrDefault(); var completionpercentage = (from tower in context.TETowerMasters where tower.TowerID == Ids.TowerID select tower.CurrentCompletionPercentage).FirstOrDefault(); var ReImbursementRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("ReImbursementRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var CancellationFeeRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("CancellationFeeRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var DelayCompensationRate = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("DelayCompensationRate") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var DelayCompensatoinRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("DelayCompensationRule") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); var TransferOrderFeeRule = (from projectrule in context.TEProjectRules where projectrule.ProjectID == offerObj.ProjectID && projectrule.Type.Contains("TransferOrderFee") && projectrule.IsDeleted == false select projectrule.Value).FirstOrDefault(); offerObj.ConstructionComplPercentage = (completionpercentage != null || completionpercentage != "") ? Convert.ToDecimal(completionpercentage) : 0; offerObj.ReImbursementAmount = (ReImbursementRule != null || ReImbursementRule != "") ? Convert.ToInt32(ReImbursementRule) : 0; offerObj.DelayCompensationRate = (DelayCompensationRate != null || DelayCompensationRate != "") ? Convert.ToDecimal(DelayCompensationRate) : 0; offerObj.CancellationFee = (CancellationFeeRule != null || CancellationFeeRule != "") ? Convert.ToDecimal(CancellationFeeRule) : 0; offerObj.DelayCompensatoinRule = (DelayCompensatoinRule != null || DelayCompensatoinRule != "") ? Convert.ToDecimal(DelayCompensatoinRule) : 0; offerObj.TransferOrderFee = (TransferOrderFeeRule != null || TransferOrderFeeRule != "") ? Convert.ToDecimal(TransferOrderFeeRule) : 0; updatedOffer = genDAL.UpdateOffer(offerObj); try { int? unitid = offerObj.UnitID; TEUnit tempUnits = context.TEUnits.Where(a => a.UnitID == unitid).FirstOrDefault(); tempUnits.Status = "Sold"; tempUnits.LastModifiedDate = DateTime.Now; context.Entry(tempUnits).CurrentValues.SetValues(tempUnits); context.SaveChanges(); } catch (Exception ex) { } } //save offer event data genDAL.SaveOfferEvent(offerId, "TRANSITIONACCEPTEDDATE", lastModifiedById); //Save offer notes TENote note; if (!string.IsNullOrEmpty(notes)) note = cemDAL.SaveAcceptTransitionToCEMRemarksInNotes(notes, offerId, lastModifiedById); } } } else { errorMsg = String.Format("Transition to CEM Measures Not Found for received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (checkedMeasuresCount+1 == orgMeasuresCount && updatedOffer.TransitionStatus == "Accepted") { email.OnCEMAccept(offerId,lastModifiedById); sinfo.errorcode = 0; sinfo.errormessage = "Accept TransitionToCEM Completed Successfully"; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else if (checkedMeasuresCount + 1 < orgMeasuresCount) { sinfo.errorcode = 0; sinfo.errormessage = "Updated Successfully"; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Failed to do Accept TransitionToCEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to do Accept Transition to CEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage RejecttTransAcceptTransitionToCEMByOfferId(JObject json, int lastModifiedById) { string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null, updatedOffer = null; List<TRANSITIONTOCEMMEASURE> measuresList = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); try { int offerId = json["OfferID"].ToObject<int>(); string rejectRemarks = json["Remarks"].ToObject<string>(); #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (string.IsNullOrEmpty(rejectRemarks)) { errorMsg = String.Format("Please Enter Remarks", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (lastModifiedById == 0) { errorMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedById.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && offerObj.OrderStatus == "TS Signed" && offerObj.IsEMD == true)) { string isEMD = "No"; if (offerObj.IsEMD == true) isEMD = "Yes"; errorMsg = String.Format("Reject Transition to CEM cannot be done for received Offer Id: {0}. Offer Status: {1}, EMD Completed: {2}", offerId.ToString(), offerObj.OrderStatus, isEMD); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && offerObj.TransitionStatus != "Transition Intiated") { errorMsg = String.Format("Reject Transition to CEM cannot be done for received Offer Id: {0}. Offer TransitionStatus: {1}", offerId.ToString(), offerObj.TransitionStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion measuresList = cemDAL.GetTransitionToCEMMeasuresListByOfferId(offerId); if (measuresList != null && measuresList.Count > 0) { foreach (TRANSITIONTOCEMMEASURE cemMeasure in measuresList) { cemMeasure.ISDELETED = true; cemMeasure.MODIFIEDBY = lastModifiedById; cemMeasure.MODIFIEDON = DateTime.Now; cemDAL.UpdateTransitionToCEMMeasure(cemMeasure); } } if (offerObj != null && offerObj.OfferID > 0) { offerObj.LastModifiedBy_Id = lastModifiedById; offerObj.TransitionStatus = "Rejected"; offerObj.LastModifiedOn = DateTime.Now; offerObj.OrderStatus = "TS Generated"; offerObj.CEMmanager = 0; updatedOffer = genDAL.UpdateOffer(offerObj); } TENote note = cemDAL.SaveRejectTransitionToCEMRemarksInNotes(rejectRemarks, offerId, lastModifiedById); if (offerObj.TransitionStatus == "Rejected" && note.NotesID > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Reject TransitionToCEM Completed Successfully"; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Failed to do Reject TransitionToCEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to do Reject Transition to CEM"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage CreateOrUpdateSaleOrderByOfferId(JObject json, int lastModifiedById) { if (log.IsDebugEnabled) log.Info("Entered into CreateOrUpdateSaleOrderByOfferId"); string errorMsg = string.Empty, saleOrderId = string.Empty; //SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); TEOffer offerObj = null; TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); try { int offerId = json["OfferID"].ToObject<int>(); #region Mandatory Validations if (offerId == 0) { errorMsg = String.Format("Invalid Offer Id: {0} Received", offerId.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (lastModifiedById == 0) { errorMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedById.ToString()); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } #endregion #region Buisiness Validation offerObj = genDAL.GetOfferByOfferId(offerId); if (offerObj == null || offerObj.OfferID == 0) { errorMsg = String.Format("Offer not found with received Offer Id: {0}", offerId.ToString()); if (log.IsDebugEnabled) log.Info(errorMsg); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (!(offerObj.OfferID > 0 && offerObj.TransitionStatus == "Accepted" && offerObj.OrderStatus == "Confirmed")) { if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") errorMsg = String.Format("Sale Order cannot be created for received Offer Id: {0}. Offer TransitionStatus: {1} & OrderStatus: {2}", offerObj.OfferID, offerObj.TransitionStatus, offerObj.OrderStatus); else errorMsg = String.Format("Sale Order cannot be updated for received Offer Id: {0}. Offer TransitionStatus: {1} & OrderStatus: {2}", offerObj.OfferID, offerObj.TransitionStatus, offerObj.OrderStatus); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } if (offerObj.OfferID > 0 && !genDAL.IsPostLaunchOffer(offerObj.OfferID)) { if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") { errorMsg = String.Format("Saler Order creation can be allowed only for PostLaunch Offers"); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } #endregion saleOrderId = cemDAL.GenerateSaleOrder(offerObj.UnitID, offerObj.ProjectID, offerObj.OfferID); //Updating Saleorder Id for the offer if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") { offerObj.SAPOrderID = saleOrderId; genDAL.UpdateOffer(offerObj); } // save offer event data if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") genDAL.SaveOfferEvent(offerId, "SALEORDERGENERATEDDATE", lastModifiedById); if (!string.IsNullOrEmpty(saleOrderId) && saleOrderId != "0") { if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") errorMsg = String.Format("Sale Order is created successfully"); else errorMsg = String.Format("Sale Order is updated successfully"); finfo.errorcode = 0; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } else { if (offerObj.SAPOrderID == null || offerObj.SAPOrderID == "" || offerObj.SAPOrderID == "0") errorMsg = String.Format("Sale Order creation is failed in SAP"); else errorMsg = String.Format("Sale Order updation is failed in SAP"); finfo.errorcode = 1; finfo.errormessage = errorMsg; if (log.IsDebugEnabled) log.Info(errorMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to Created or Update Sale Order"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } public HttpResponseMessage CreateSaleOrderForAllMissingOffers() { if (log.IsDebugEnabled) log.Info("Entered into CreateSaleOrderForAllMissingOffers"); string logMsg = string.Empty, saleOrderId = string.Empty; FailInfo finfo = new FailInfo(); TransitionToCEMDAL cemDAL = new TransitionToCEMDAL(); GenericDAL genDAL = new GenericDAL(); int totalOffersCnt = 0, validOffersCnt = 0, invalidOffersCnt = 0, postLaunchOffersCnt = 0, otherThanPostLaunchOffersCnt = 0, sapOrderIdGenCnt = 0, sapOrderIdGenFailedCnt = 0; try { int lastModifiedById = GetSystemAdminID(); if (!(lastModifiedById > 0)) { logMsg = String.Format("Invalid LastModifiedBy Id: {0} Received", lastModifiedById.ToString()); finfo.errorcode = 1; finfo.errormessage = logMsg; if (log.IsDebugEnabled) log.Info(logMsg); return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } else { logMsg = String.Format("Received LastModifiedBy Id: {0}", lastModifiedById.ToString()); if (log.IsDebugEnabled) log.Info(logMsg); } var offersList = context.TEOffers.Where(a => a.IsDeleted == false && a.isOrderInUse == true && a.TransitionStatus == "Accepted" && a.OrderStatus == "Confirmed" && (a.SAPOrderID == null || a.SAPOrderID == "" || a.SAPOrderID == "0")).ToList(); if (offersList != null && offersList.Count > 0) { totalOffersCnt = offersList.Count; logMsg = String.Format("No.of Offers Retrieved: {0}", totalOffersCnt.ToString()); if (log.IsDebugEnabled) log.Info(logMsg); foreach (var ofr in offersList) { if (ofr.OfferID > 0) { validOffersCnt = validOffersCnt + 1; if (genDAL.IsPostLaunchOffer(ofr.OfferID)) { postLaunchOffersCnt = postLaunchOffersCnt + 1; saleOrderId = cemDAL.GenerateSaleOrder(ofr.UnitID, ofr.ProjectID, ofr.OfferID); if (!string.IsNullOrEmpty(saleOrderId) && saleOrderId != "0") { sapOrderIdGenCnt = sapOrderIdGenCnt + 1; //Updating Saleorder Id for the offer TEOffer offerObj = genDAL.GetOfferByOfferId(ofr.OfferID); offerObj.SAPOrderID = saleOrderId; genDAL.UpdateOffer(offerObj); // save offer event data genDAL.SaveOfferEvent(ofr.OfferID, "SALEORDERGENERATEDDATE", lastModifiedById); logMsg = String.Format("Sale Order: {0} is created successfully for OfferId: {1}", ofr.OfferID.ToString(), saleOrderId); if (log.IsDebugEnabled) log.Info(logMsg); } else { sapOrderIdGenFailedCnt = sapOrderIdGenFailedCnt + 1; logMsg = String.Format("Sale Order creation is failed in SAP for OfferId: {0}",ofr.OfferID.ToString()); if (log.IsDebugEnabled) log.Info(logMsg); } } else { otherThanPostLaunchOffersCnt = otherThanPostLaunchOffersCnt + 1; logMsg = String.Format(@"OfferId: {0} is not a PostLaunch Offer. Saler Order creation can be allowed only for PostLaunch Offers", ofr.OfferID,ToString()); if (log.IsDebugEnabled) log.Info(logMsg); } } else { invalidOffersCnt = invalidOffersCnt + 1; logMsg = String.Format("Invalid OfferId"); if (log.IsDebugEnabled) log.Info(logMsg); } } logMsg = String.Format(@"Totla Offers: {0}, Valid Offers: {1}, Invalid Offers: {2}, PostLaunch Offers: {3}, Otherthan PostLaunch Offers: {4}, SapOrderIdGenerated: {5}, SapOrderIdGenFailed: {6}", totalOffersCnt.ToString(), validOffersCnt.ToString(), invalidOffersCnt.ToString(), postLaunchOffersCnt.ToString(), otherThanPostLaunchOffersCnt.ToString(), sapOrderIdGenCnt.ToString(), sapOrderIdGenFailedCnt.ToString()); if (log.IsDebugEnabled) log.Info(logMsg); finfo.errorcode = 0; finfo.errormessage = logMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } else { logMsg = String.Format("No Offers found to generate SAPOrderId"); if (log.IsDebugEnabled) log.Info(logMsg); finfo.errorcode = 0; finfo.errormessage = logMsg; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to Created or Update Sale Order"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } private int GetSystemAdminID() { int systAdminId = 0; systAdminId = (from user in context.UserProfiles where user.UserName.ToLower() == "systemadmin" && user.IsDeleted == false select user.UserId).FirstOrDefault(); return systAdminId; } } }
public class ModularStateMachine { #region Variables public IState CurrentState { get { return currentState; } } public IState PreviousState { get { return previousState; } } private IState currentState; private IState previousState; #endregion #region Methods public void ChangeState(IState newState) { if(currentState != null) { previousState = currentState; currentState.Exit(); } currentState = newState; currentState.Enter(); } public void ExecuteStateUpdate() { if(currentState != null) { currentState.Execute(); } } #endregion public void ReturnToPreviousState() { if(currentState != null) { currentState.Exit(); currentState = previousState; currentState.Enter(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Task2 { class Program { static void Main(string[] args) { Queue q = new Queue(); q.Enqueue("Nigel"); q.Enqueue("Makuini"); q.Enqueue("Jerome"); q.Enqueue("Makaio"); q.Enqueue("Zane"); // Check to see if name is in queue Console.Write("Enter a name to search: "); string input = Console.ReadLine(); if (q.Contains(input)) { Console.WriteLine("Name is in the queue"); } else { Console.WriteLine("Name is not found"); } } } }
using UnityEngine; namespace Source.Code.Environment { public class SelfDestroyer : MonoBehaviour { public void Initialize(float lifeTimeDuration) { Destroy(gameObject, lifeTimeDuration); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace starategy { class Program { static void Main(string[] args) { CustomerManager customermanager = new CustomerManager(); customermanager.CrediCalculatorBase = new After2010CreditCalculator(); customermanager.SaveCredit(); customermanager.CrediCalculatorBase = new Before2010CreditCalculator (); customermanager.SaveCredit(); Console.ReadLine(); } } abstract class CrediCalculatorBase { public abstract void Calculate(); } class Before2010CreditCalculator : CrediCalculatorBase { public override void Calculate() { Console.WriteLine("Credit calculated using before2010"); } } class After2010CreditCalculator : CrediCalculatorBase { public override void Calculate() { Console.WriteLine("Credit calculated using after2010"); } } class CustomerManager { public CrediCalculatorBase CrediCalculatorBase { get; set; } public void SaveCredit() { Console.WriteLine("Customer manager business"); CrediCalculatorBase.Calculate(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Windows.Forms; using DelftTools.Utils.Aop; using DelftTools.Utils.Aop.NotifyPropertyChange; using DelftTools.Utils.Collections; using DelftTools.Utils.Collections.Generic; using DelftTools.Utils.Threading; using GeoAPI.Extensions.Feature; using GeoAPI.Geometries; using log4net; using SharpMap.Layers; using SharpMap.Rendering.Thematics; using SharpMap.Styles; using SharpMap.Topology; using SharpMap.UI.Snapping; using SharpMap.UI.Tools; using SharpMap.UI.Tools.Zooming; using SharpMap.Converters.Geometries; namespace SharpMap.UI.Forms { /// <summary> /// MapControl Class - MapControl control for Windows forms /// </summary> [DesignTimeVisible(true)]///, NotifyPropertyChange] [Serializable] public class MapControl : Control, IMapControl { #region Delegates /// <summary> /// MouseEventtype fired from the MapImage control /// </summary> /// <param name="worldPos"></param> /// <param name="imagePos"></param> public delegate void MouseEventHandler(ICoordinate worldPos, MouseEventArgs imagePos); #endregion private static readonly ILog Log = LogManager.GetLogger(typeof(MapControl)); private static readonly Color[] MDefaultColors = new[] { Color.DarkRed, Color.DarkGreen, Color.DarkBlue, Color.Orange, Color.Cyan, Color.Black, Color.Purple, Color.Yellow, Color.LightBlue, Color.Fuchsia }; private static int mDefaultColorIndex; // other commonly-used specific tools private readonly CurvePointTool curvePointTool; private readonly DeleteTool deleteTool; private readonly FixedZoomInTool fixedZoomInTool; private readonly FixedZoomOutTool fixedZoomOutTool; private readonly LegendTool legendTool; private readonly MoveTool linearMoveTool; private readonly SolidBrush mRectangleBrush = new SolidBrush(Color.FromArgb(210, 244, 244, 244)); private readonly Pen mRectanglePen = new Pen(Color.FromArgb(244, 244, 244), 1); private readonly MeasureTool measureTool; private readonly MoveTool moveTool; private readonly PanZoomTool panZoomTool; private readonly CoverageProfileTool profileTool; private readonly QueryTool queryTool; private readonly ZoomUsingRectangleTool rectangleZoomTool; private readonly SelectTool selectTool; private readonly List<ISnapRule> snapRules = new List<ISnapRule>(); private readonly SnapTool snapTool; private readonly EventedList<IMapTool> tools; private readonly PanZoomUsingMouseWheelTool wheelPanZoomTool; private readonly ZoomHistoryTool zoomHistoryTool; //NS, 2013-12-02 private readonly DrawPolygonTool drawPolygonTool; // TODO: fieds below should be moved to some more specific tools? private int mQueryLayerIndex; private Map map; private DelayedEventHandler<NotifyCollectionChangingEventArgs> mapCollectionChangedEventHandler; private DelayedEventHandler<PropertyChangedEventArgs> mapPropertyChangedEventHandler; private IList<IFeature> selectedFeatures = new List<IFeature>(); /// <summary> /// NS, 2013-12-02, Fired when a new polygon has been defined /// </summary> public event GeometryDefinedHandler GeometryDefined; /// <summary> /// Initializes a new map /// </summary> public MapControl() { SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); LostFocus += MapBox_LostFocus; base.AllowDrop = true; tools = new EventedList<IMapTool>(); tools.CollectionChanged += tools_CollectionChanged; // Visible = true, kalo ingin nampilin Arah Utara var northArrowTool = new NorthArrowTool(this) { Anchor = AnchorStyles.Right | AnchorStyles.Top, Visible = false }; Tools.Add(northArrowTool); var scaleBarTool = new ScaleBarTool(this) { Size = new Size(230, 50), Anchor = AnchorStyles.Right | AnchorStyles.Bottom, Visible = true }; Tools.Add(scaleBarTool); // Visible = true, utuk menampilkan legend Map //legendTool = new LegendTool(this) {Anchor = AnchorStyles.Left | AnchorStyles.Top, Visible = false}; //Tools.Add(legendTool); queryTool = new QueryTool(this); Tools.Add(queryTool); // add commonly used tools zoomHistoryTool = new ZoomHistoryTool(this); Tools.Add(zoomHistoryTool); panZoomTool = new PanZoomTool(this); Tools.Add(panZoomTool); wheelPanZoomTool = new PanZoomUsingMouseWheelTool(this) { WheelZoomMagnitude = 0.8 };//-2}; Tools.Add(wheelPanZoomTool); rectangleZoomTool = new ZoomUsingRectangleTool(this); Tools.Add(rectangleZoomTool); fixedZoomInTool = new FixedZoomInTool(this); Tools.Add(fixedZoomInTool); fixedZoomOutTool = new FixedZoomOutTool(this); Tools.Add(fixedZoomOutTool); selectTool = new SelectTool { IsActive = true }; Tools.Add(selectTool); // Active = true, biar bisa move point... moveTool = new MoveTool { Name = "Move selected vertices", FallOffPolicy = FallOffPolicyRule.None, IsActive = true}; Tools.Add(moveTool); linearMoveTool = new MoveTool { Name = "Move selected vertices (linear)", FallOffPolicy = FallOffPolicyRule.Linear }; Tools.Add(linearMoveTool); deleteTool = new DeleteTool(); Tools.Add(deleteTool); measureTool = new MeasureTool(this); tools.Add(measureTool); profileTool = new CoverageProfileTool(this) {Name = "Make grid profile"}; tools.Add(profileTool); curvePointTool = new CurvePointTool(); Tools.Add(curvePointTool); drawPolygonTool = new DrawPolygonTool(); Tools.Add(drawPolygonTool); snapTool = new SnapTool(); Tools.Add(snapTool); var toolTipTool = new ToolTipTool(); Tools.Add(toolTipTool); MapTool fileHandlerTool = new FileDragHandlerTool(); Tools.Add(fileHandlerTool); Width = 100; Height = 100; mapPropertyChangedEventHandler = new DelayedEventHandler<PropertyChangedEventArgs>(map_PropertyChanged_Delayed) { SynchronizingObject = this, FireLastEventOnly = true, FullRefreshDelay = 300, Filter = (sender, e) => sender is ILayer || sender is VectorStyle || sender is ITheme, Enabled = false }; mapCollectionChangedEventHandler = new DelayedEventHandler<NotifyCollectionChangingEventArgs>(map_CollectionChanged_Delayed) { SynchronizingObject = this, FireLastEventOnly = true, FullRefreshDelay = 300, Filter = (sender, e) => sender is Map || sender is ILayer, Enabled = false }; Map = new Map(ClientSize) { Zoom = 100 }; } [Description("The color of selecting rectangle.")] [Category("Appearance")] public Color SelectionBackColor { get { return mRectangleBrush.Color; } set { //if (value != mRectangleBrush.Color) mRectangleBrush.Color = value; } } [Description("The color of selection rectangle frame.")] [Category("Appearance")] public Color SelectionForeColor { get { return mRectanglePen.Color; } set { //if (value != mRectanglePen.Color) mRectanglePen.Color = value; } } /// <summary> /// Gets or sets the index of the active query layer /// </summary> public int QueryLayerIndex { get { return mQueryLayerIndex; } set { mQueryLayerIndex = value; } } #region IMapControl Members [Description("The map image currently visualized.")] [Category("Appearance")] public Image Image { get { if (Map == null) { return null; } var bitmap = new Bitmap(Width, Height); DrawToBitmap(bitmap, ClientRectangle); return bitmap; } } public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; if (Map != null) { Map.BackColor = value; } } } /// <summary> /// Map reference /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Map Map { get { return map; } set { if (map != null) { //unsubscribe from changes in the map layercollection UnSubscribeMapEvents(); } map = value; if (map == null) { return; } map.Size = ClientSize; SubScribeMapEvents(); SetMapStyles(); Refresh(); } } private void SetMapStyles() { DoubleBuffered = true; SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); } private void UnSubscribeMapEvents() { map.CollectionChanged -= mapCollectionChangedEventHandler; ((INotifyPropertyChanged)map).PropertyChanged -= mapPropertyChangedEventHandler; map.MapRendered -= MapMapRendered; map.MapLayerRendered -= MMapMapLayerRendered; } private void SubScribeMapEvents() { map.CollectionChanged += mapCollectionChangedEventHandler; ((INotifyPropertyChanged)map).PropertyChanged += mapPropertyChangedEventHandler; map.MapRendered += MapMapRendered; map.MapLayerRendered += MMapMapLayerRendered; } private void MMapMapLayerRendered(Graphics g, ILayer layer) { foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMapLayerRendered(g, layer); } } public IList<IMapTool> Tools { get { return tools; } } public IMapTool GetToolByName(string toolName) { return Tools.FirstOrDefault(tool => tool.Name == toolName); // Do not throw ArgumentOutOfRangeException UI handlers (button checked) can ask for not existing tool } public IMapTool GetToolByType(Type type) { foreach (var tool in Tools.Where(tool => tool.GetType() == type)) { return tool; } throw new ArgumentOutOfRangeException(type.ToString()); } public T GetToolByType<T>() where T : class { //change it to support interfaces.. return Tools.Where(tool => tool is T).Cast<T>().FirstOrDefault(); } public void ActivateTool(IMapTool tool) { if (tool.IsActive) { // tool already active return; } if (tool.AlwaysActive) { throw new InvalidOperationException("Tool is AlwaysActive, use IMapTool.Execute() to make it work"); } // deactivate other tools foreach (var t in tools.Where(t => t.IsActive && !t.AlwaysActive)) { t.IsActive = false; } tool.IsActive = true; } public QueryTool QueryTool { get { return queryTool; } } public ZoomHistoryTool ZoomHistoryTool { get { return zoomHistoryTool; } } public PanZoomTool PanZoomTool { get { return panZoomTool; } } public PanZoomUsingMouseWheelTool WheelPanZoomTool { get { return wheelPanZoomTool; } } public ZoomUsingRectangleTool RectangleZoomTool { get { return rectangleZoomTool; } } public FixedZoomInTool FixedZoomInTool { get { return fixedZoomInTool; } } public FixedZoomOutTool FixedZoomOutTool { get { return fixedZoomOutTool; } } public MoveTool MoveTool { get { return moveTool; } } public MoveTool LinearMoveTool { get { return linearMoveTool; } } public DrawPolygonTool DrawPolygonTool { get { return drawPolygonTool; } } public SelectTool SelectTool { get { return selectTool; } } public CoverageProfileTool CoverageProfileTool { get { return profileTool; } } public LegendTool LegendTool { get { return legendTool; } } public SnapTool SnapTool { get { return snapTool; } } public IEnumerable<IFeature> SelectedFeatures { get { return selectedFeatures; } set { selectedFeatures = value.ToList(); FireSelectedFeaturesChanged(); if (Visible) { Refresh(); } } } private void FireSelectedFeaturesChanged() { if (SelectedFeaturesChanged != null) { SelectedFeaturesChanged(this, EventArgs.Empty); } } public event EventHandler SelectedFeaturesChanged; public IList<ISnapRule> SnapRules { get { return snapRules; } } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); mapPropertyChangedEventHandler.Enabled = true; mapCollectionChangedEventHandler.Enabled = true; } protected override void OnHandleDestroyed(EventArgs e) { mapPropertyChangedEventHandler.Enabled = false; mapCollectionChangedEventHandler.Enabled = false; base.OnHandleDestroyed(e); } /// <summary> /// Refreshes the map /// </summary> [InvokeRequired] public override void Refresh() { //NS Currsoroff //var c = Cursor; //Cursor = Cursors.WaitCursor; if (map == null) { return; } map.Render(); base.Refresh(); // log.DebugFormat("Refreshed"); if (MapRefreshed != null) { MapRefreshed(this, null); } //NS Currsoroff //Cursor = c; } public event EditorBeforeContextMenuEventHandler BeforeContextMenu; public IList<ISnapRule> GetSnapRules(ILayer layer, IFeature feature, IGeometry geometry, int trackingIndex) { return SnapRules.Where(snapRule => snapRule.SourceLayer == layer).ToList(); } public bool IsProcessing { get { var processingPropertyChangedEvents = mapPropertyChangedEventHandler != null && (mapPropertyChangedEventHandler.IsRunning || mapPropertyChangedEventHandler.HasEventsToProcess); var processingCollectionChangedEvents = mapCollectionChangedEventHandler != null && (mapCollectionChangedEventHandler.IsRunning || mapCollectionChangedEventHandler.HasEventsToProcess); return processingPropertyChangedEvents || processingCollectionChangedEvents; } } #endregion private void tools_CollectionChanged(object sender, NotifyCollectionChangingEventArgs e) { switch (e.Action) { case NotifyCollectionChangeAction.Add: ((IMapTool)e.Item).MapControl = this; break; case NotifyCollectionChangeAction.Remove: ((IMapTool)e.Item).MapControl = null; break; default: break; } } /* private void MapMapLayerRendered(Graphics g, ILayer layer) { foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMapLayerRendered(g, layer); } } */ private void MapMapRendered(Graphics g) { // TODO: review, migrated from GeometryEditor if (g == null) { return; } //UserLayer.Render(g, this.mapbox.Map); // always draw trackers when they exist -> full redraw when trackers are deleted SelectTool.Render(g, Map); zoomHistoryTool.MapRendered(Map); } private void map_PropertyChanged_Delayed(object sender, PropertyChangedEventArgs e) { if (IsDisposed || !IsHandleCreated) // must be called before InvokeRequired { return; } Log.DebugFormat("IsDisposed: {0}, IsHandleCreated: {1}, Disposing: {2}", IsDisposed, IsHandleCreated, Disposing); map_PropertyChanged(sender, e); } [InvokeRequired] private void map_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (IsDisposed) { return; } foreach (var tool in tools.ToArray()) { tool.OnMapPropertyChanged(sender, e); // might be a problem, events are skipped } if (Visible) { Refresh(); } else { map.Layers.ForEach(l => { if (!l.RenderRequired) l.RenderRequired = true; }); } } private void map_CollectionChanged_Delayed(object sender, NotifyCollectionChangingEventArgs e) { if (IsDisposed || !IsHandleCreated) // must be called before InvokeRequired { return; } map_CollectionChanged(sender, e); } [InvokeRequired] private void map_CollectionChanged(object sender, NotifyCollectionChangingEventArgs e) { if (IsDisposed) { return; } // hack: some tools add extra tools and can remove them in response to a layer // change. For example NetworkEditorMapTool adds NewLineTool for NetworkMapLayer foreach (var tool in tools.ToArray().Where(tool => tools.Contains(tool))) { tool.OnMapCollectionChanged(sender, e); } var layer = e.Item as ILayer; if (layer == null) { return; } switch (e.Action) { case NotifyCollectionChangeAction.Add: var allLayersWereEmpty = Map.Layers.Except(new[] { layer }).All(l => l.Envelope.IsNull); if (allLayersWereEmpty && !layer.Envelope.IsNull) { map.ZoomToExtents(); //HACK: OOPS, changing domain model from separate thread! } break; case NotifyCollectionChangeAction.Replace: throw new NotImplementedException(); } Refresh(); } public static void RandomizeLayerColors(VectorLayer layer) { layer.Style.EnableOutline = true; layer.Style.Fill = new SolidBrush(Color.FromArgb(80, MDefaultColors[mDefaultColorIndex % MDefaultColors.Length])); layer.Style.Outline = new Pen( Color.FromArgb(100, MDefaultColors[ (mDefaultColorIndex + ((int)(MDefaultColors.Length * 0.5))) % MDefaultColors.Length]), 1f); mDefaultColorIndex++; } // TODO: add smart resize here, probably can cache some area around map protected override void OnResize(EventArgs e) { if (map != null && ClientSize.Width > 0 && ClientSize.Height > 0) { //log.DebugFormat("Resizing map '{0}' from {1} to {2}: ", map.Name, map.Size, ClientSize); map.Size = ClientSize; map.Layers.ForEach(l => l.RenderRequired = true); } base.OnResize(e); } private void MapBox_LostFocus(object sender, EventArgs e) { } // TODO handle arrow keys. MapTool should handle key protected override bool ProcessDialogKey(Keys keyData) { switch (keyData) { case Keys.Down: break; case Keys.Up: break; case Keys.Left: break; case Keys.Right: break; default: break; } return base.ProcessDialogKey(keyData); } /// <summary> /// Handles the key pressed by the user /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); var shouldRefresh = false; var canceled = false; foreach (var tool in tools) { if (e.KeyCode == Keys.Escape) { // if the user presses the escape key first cancel an operation in progress if (tool.IsBusy) { tool.Cancel(); shouldRefresh = true; canceled = true; } continue; } tool.OnKeyDown(e); } if ((!canceled) && (e.KeyCode == Keys.Escape) && (!SelectTool.IsActive)) { // if the user presses the escape key and there was no operation in progress switch to select. ActivateTool(SelectTool); shouldRefresh = true; } if ((e.KeyCode == Keys.Delete) && (!e.Handled)) { deleteTool.DeleteSelection(); shouldRefresh = true; } if (shouldRefresh) { Refresh(); } } protected override void OnKeyUp(KeyEventArgs e) { foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnKeyUp(e); } base.OnKeyUp(e); } protected override void OnMouseHover(EventArgs e) { foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMouseHover(null, e); } base.OnMouseHover(e); } protected override void OnMouseDoubleClick(MouseEventArgs e) { if (map == null) { return; } foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMouseDoubleClick(this, e); } // todo (TOOLS-1151) move implemention in mapView_MouseDoubleClick to SelectTool::OnMouseDoubleClick? if (SelectTool.IsActive) { base.OnMouseDoubleClick(e); } //NS, 2013-12-02, generate polygon coordinate if (drawPolygonTool.IsActive) { if (GeometryDefined != null) { var cl = new GisSharpBlog.NetTopologySuite.Geometries.CoordinateList(drawPolygonTool.pointArray, false); cl.CloseRing(); GeometryDefined(GeometryFactory.CreatePolygon(GeometryFactory.CreateLinearRing(GisSharpBlog.NetTopologySuite.Geometries.CoordinateArrays.AtLeastNCoordinatesOrNothing(4, cl.ToCoordinateArray())), null)); drawPolygonTool.pointArray = null; } ActivateTool(panZoomTool); } } protected override void OnMouseWheel(MouseEventArgs e) { if (map == null) { return; } var mousePosition = map.ImageToWorld(new Point(e.X, e.Y)); foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMouseWheel(mousePosition, e); } base.OnMouseWheel(e); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (map == null) { return; } var worldPosition = map.ImageToWorld(new Point(e.X, e.Y)); foreach (var tool in Tools.Where(tool => tool.IsActive)) { tool.OnMouseMove(worldPosition, e); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (!Focused) { Focus(); } if (map == null) { return; } var worldPosition = map.ImageToWorld(new Point(e.X, e.Y)); foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnMouseDown(worldPosition, e); } } protected override void OnMouseUp(MouseEventArgs e) { if (map == null) { return; } var worldPosition = map.ImageToWorld(new Point(e.X, e.Y)); var contextMenu = new ContextMenuStrip(); var activeTools = tools.Where(tool => tool.IsActive).ToList(); foreach (var tool in activeTools) { tool.OnMouseUp(worldPosition, e); if (e.Button == MouseButtons.Right) { tool.OnBeforeContextMenu(contextMenu, worldPosition); } } if (!disposed) { contextMenu.Show(PointToScreen(e.Location)); } //make sure the base event is fired first...HydroNetworkEditorMapTool enables the base.OnMouseUp(e); } protected override void OnDragEnter(DragEventArgs drgevent) { foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnDragEnter(drgevent); } base.OnDragEnter(drgevent); } /// <summary> /// Drop object on map. This can result in new tools in the tools collection /// </summary> /// <param name="e"></param> protected override void OnDragDrop(DragEventArgs e) { IList<IMapTool> mapTools = tools.Where(tool => tool.IsActive).ToList(); foreach (var tool in mapTools) { tool.OnDragDrop(e); } base.OnDragDrop(e); } protected override void OnPaint(PaintEventArgs e) { //HACK: check if this works and then move this code/logic elsewhere if (!DelayedEventHandlerController.FireEvents) { return;//stop painting.. } if (Map == null || Map.Image == null) { return; } // TODO: fix this if (Map.Image.PixelFormat == PixelFormat.Undefined) { Log.Error("Map image is broken - bug!"); return; } e.Graphics.DrawImageUnscaled(Map.Image, 0, 0); foreach (var tool in tools.Where(tool => tool.IsActive)) { tool.OnPaint(e); } SelectTool.OnPaint(e); base.OnPaint(e); } /// <summary> /// Fired when the map has been refreshed /// </summary> public event EventHandler MapRefreshed; private bool disposed; protected override void Dispose(bool disposing) { if (!disposed) { mapPropertyChangedEventHandler.Enabled = false; mapCollectionChangedEventHandler.Enabled = false; if (disposing) { mRectangleBrush.Dispose(); mRectanglePen.Dispose(); if (map != null) { map.Dispose(); } mapCollectionChangedEventHandler.Dispose(); mapPropertyChangedEventHandler.Dispose(); } } try { base.Dispose(disposing); } catch(Exception e) { Log.Error("Exception during dispose", e); } disposed = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Task3 { class Program { static Random rnd; static void Main(string[] args) { rnd = new Random(); Thread sinThread = new Thread(drawSin); sinThread.Start(); } private static void drawSin() { int x = 0; int y = 0; int turn = 0; int nxt = 0; while (true) { int prec = 14; if (y == nxt) { nxt = (int)(Math.Sin(turn) * prec); turn++; } if (y < nxt) { y += Math.Min(rnd.Next(1, 4), nxt - y); } else { y -= Math.Min(rnd.Next(1, 4), y - nxt); } Console.ForegroundColor = ConsoleColor.Yellow; if (x >= Console.BufferWidth) { Console.Clear(); x = 0; } Console.SetCursorPosition(x, y + 20); Console.Write("."); //Console.WriteLine(x + " " + y); x++; Thread.Sleep(123); // Thread.Sleep(rnd.Next(100, 250)); } } } }
using System; using BattleEngine.Actors.Buildings; using BattleEngine.Modifiers; using Records.Units; using BattleEngine.Components.Units; namespace BattleEngine.Actors.Units { public class BattleUnit : BattleUnitOwner { private UnitMoveComponent _move; private UnitRecord _info; private UnitLevelRecord _infoLevel; private int _level; private double _hp; private double _unitHP; private bool _attachedToBuilding; public BattleUnit() { _move = AddComponent<UnitMoveComponent>(); } public UnitRecord info { get { return _info; } } public UnitLevelRecord infoLevel { get { return _infoLevel; } } public void initialize(BattleBuilding from, BattleBuilding to, int unitCount) { _attachedToBuilding = false; setOwnerId(from.ownerId); _level = from.level; _info = engine.configuration.unitRecords.GetBy(from.info.Levels[from.level].UnitId, from.info.Race); _infoLevel = _info.Levels[_level]; _move.moveTo(to.transform); transform.setFrom(from.transform); _unitHP = engine.players.getPlayer(from.ownerId).modifier.calculate(ModifierType.UNITS_HP, _infoLevel.Hp, _info.Id); _hp = _unitHP * unitCount; units.setCount(getUnits()); } public double hp { get { return _hp; } } public bool isDied { get { return _hp <= 0; } } public void decreaseHp(double value) { _hp -= value; } public void die() { _hp = 0; } public void attachTo(BattleBuilding building) { building.units.add(units.count); _attachedToBuilding = true; _hp = 0; units.change(getUnits()); } public void receiveDamage(double damage) { var unitDefense = oneUnitDefense; var unitHP = oneUnitHp; while (damage > 0 && units.count > 0) { var currentHP = unitHP; damage -= unitDefense; currentHP -= damage; damage -= unitHP; if (currentHP <= 0) { decreaseHp(unitHP); } else { decreaseHp(currentHP); } } units.change(getUnits()); } public int level { get { return _level; } } public int getUnits() { return (int)Math.Ceiling(_hp / _unitHP); } public int unitId { get { return _info.Id; } } public double powerDamage { get { return units.count * damageOneUnit; } } public double damageOneUnit { get { var damage = engine.players.getPlayer(ownerId).modifier.calculate(ModifierType.UNITS_DAMAGE, infoLevel.Damage, info.Id); return damage; } } public double oneUnitDefense { get { var defense = GetComponent<UnitDefenseComponent>(); if (defense != null) { return defense.calculateDefense(_infoLevel.Defense); } return _infoLevel.Defense; } } public double oneUnitMagicDefense { get { var defense = GetComponent<UnitDefenseComponent>(); if (defense != null) { return defense.calculateMagicDefense(_infoLevel.MagicDefense); } return _infoLevel.MagicDefense; } } public double oneUnitHp { get { return _unitHP; } } public bool attachedToBuilding { get { return _attachedToBuilding; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VerifyParameter.Interface; namespace VerifyParameter.Data.AttributeData { [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class ObjectAttribute : Attribute, IVerifyAttribute { public ObjectAttribute() { } public int MaxLength { get; set; } public string MaxLengthError { get; set; } public int MinLength { get; set; } public string MinLengthError { get; set; } public void Range(int minLength, int maxLength) { MaxLength = minLength; MinLength = maxLength; } public bool IsNotNull { get; set; } public string IsNotNullError { get; set; } } }
namespace ForumSystem.Web.ViewModels.Administration.Categories { using ForumSystem.Data.Models; using ForumSystem.Services.Mapping; public class CategoryCrudModel : IMapFrom<Category> { public int Id { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } public bool IsApprovedByAdmin { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArrayIndexers_virtual_ { class ProtectedIndexer { //создание массива string[] pArray = new string[3] { "one", "two", "three" }; //реализация индексатора с проверкой выхода индекса за диапазон массива public string this[int index] { get { if (index >= 0 & index < pArray.Length) { return pArray[index]; } else { return "get:index out of range"; } } set { if (index >= 0 & index < pArray.Length) { pArray[index] = value; } else { Console.WriteLine("set:index out of range"); } } } } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core { public sealed partial class VlcMediaPlayer { private EventCallback myOnMediaPlayerPlayingInternalEventCallback; public event EventHandler<VlcMediaPlayerPlayingEventArgs> Playing; private void OnMediaPlayerPlayingInternal(IntPtr ptr) { OnMediaPlayerPlaying(); } public void OnMediaPlayerPlaying() { var del = Playing; if (del != null) del(this, new VlcMediaPlayerPlayingEventArgs()); } } }
namespace ChirperLive.Models { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ChImg { public byte[] Image { get; set; } public int ChirpId { get; set; } public virtual Chirp Chirp { get; set; } } }
using Manor.MsExcel.Contracts; using OfficeOpenXml; namespace Techical.MsExcel.EpPlus { internal class Column : IColumn { private readonly ExcelColumn _column; public Column(ExcelColumn column) { _column = column; } public double Width { get { return _column.Width; } set { _column.Width = value; } } } }
// Ref: https://www.shadertoy.com/view/4dfGDH #version 430 layout (binding = 0, r16ui) readonly uniform uimage2DArray dataIn; // Input depth map layout (binding = 1, r16ui) writeonly uniform uimage2DArray dataOut; // Output depth map uniform float depthScale; uniform float sigma; uniform float bSigma; const int mSize = 15; layout (local_size_x = 32, local_size_y = 32) in; float normPdf(float x, float sigma) { return 0.39894 * exp(-0.5 * x * x / (sigma * sigma)) / sigma; } void main(void) { ivec2 u = ivec2(gl_GlobalInvocationID.xy); float c = float(imageLoad(dataIn, ivec3(u, 0)).r) * depthScale; const int kSize = (mSize - 1) / 2; float kernel[mSize]; float finalColor = 0.0; // Create the 1-D kernel float Z = 0.0; for (int i = 0; i <= kSize; ++i) { kernel[kSize + i] = kernel[kSize - i] = normPdf(float(i), sigma); } float cc; float factor; float bZ = 1.0 / normPdf(0.0, bSigma); // Read out the texels for (int x = -kSize; x <= kSize; ++x) { for (int y = -kSize; y <= kSize; ++y) { cc = float(imageLoad(dataIn, ivec3(u + ivec2(x, y), 0)).r) * depthScale; factor = normPdf(cc - c, bSigma) * bZ * kernel[kSize + y] * kernel[kSize + x]; Z += factor; finalColor += factor * cc; } } imageStore(dataOut, ivec3(u, 0), uvec4((finalColor / Z) / depthScale, 0.0, 0.0, 1.0)); }
namespace OpenApiLib.Json.Models { public class PositionJson : AbstractJson { public long PositionId { get; set; } public long EntryTimestamp { get; set; } public long UtcLastUpdateTimestamp { get; set; } public string SymbolName { get; set; } public string TradeSide { get; set; } public double EntryPrice { get; set; } public long Volume { get; set; } public double StopLoss { get; set; } public double TakeProfit { get; set; } public long Profit { get; set; } public double ProfitInPips { get; set; } public long Commission { get; set; } public double MarginRate { get; set; } public long Swap { get; set; } public double CurrentPrice { get; set; } public string Comment { get; set; } public string Channel { get; set; } public string Label { get; set; } } }
namespace PluginDevelopment.Model { /// <summary> /// 文件上传 /// </summary> public class FileData { public FileData(string name, string url, string size) { Name = name; Url = url; Size = size; } /// <summary> /// 文件名 /// </summary> public string Name { get; set; } /// <summary> /// 路径 /// </summary> public string Url { get; set; } /// <summary> /// 文件大小 /// </summary> public string Size { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Electricity : Entity { public Electricity creator; bool creatorInRange; public bool firstGeneration; protected override void CheckObjects(Collider[] _colliders) { creatorInRange = false; base.CheckObjects(_colliders); if (!creatorInRange && !firstGeneration) main.StopElectrified(); } protected override void Interact(Interactable _object) { if ((_object.parameters.material == ObjectMaterial.Metal || _object.wet) && !_object.electrified /*&& (_object.electricityScript != creator && _object.electricityScript != null)*/) canSpreadObjects.Add(_object); if (!firstGeneration) if (_object.electrified && _object.electricityScript == creator && _object.electricityScript.enabled) //TO DEBUG: Objects with different sizes mean sometimes one will detect the other but not he other way around creatorInRange = true; } protected override void Spread() { if (!creatorInRange && !firstGeneration) { main.StopElectrified(); return; } for (int i = 0; i < canSpreadObjects.Count; i++) { canSpreadObjects[i].GetElectrified(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyHomeWorkLab7 { class Program { static void Main(string[] args) { Person p = new Person(); p.fam = "Попов"; p.status = "Студент"; p.salary = 3000; p.age = 22; p.health = 90; Console.WriteLine("Фамилия Статус Зарплата Возраст Здоровье"); Console.WriteLine(p.fam+" "+p.status + " " +p.salary + " " +p.age + " " +p.health); Console.WriteLine("Задание 2:"); Random a = new Random(); Random b = new Random(); for (int i = 0; i < 3; i++) { Rational r = new Rational(b.Next(10,20),a.Next(1,10)); Console.WriteLine(r.ToString()); } Rational r1 = new Rational(1, 7), r2 = new Rational(1, 5); Console.WriteLine($"{r1} + {r2} = " + (r1 + r2)); Console.WriteLine($"{r1} + {r2} = " + (r1 - r2)); } } }
using System; namespace TimeLogger.Web.Models { public partial class Profile /*: Realms.RealmObject*/ { public int EmpId { get; set; } public string Name { get; set; } public DateTimeOffset? DateOfBirth { get; set; } public string Designation { get; set; } public double? Experience { get; set; } public string Token { get; set; } public int? UserId { get; set; } public string Password { get; set; } } }
using UnityEngine; using UnityEditor; public class MeshCombiner : EditorWindow { GameObject meshObject, selectedMeshGroup; string newMeshName = "Mesh Name"; [MenuItem ("Window/Level Editor/Mesh Combiner")] static void Init () { // Get existing open window or if none, make a new one: MeshCombiner window = (MeshCombiner)EditorWindow.GetWindow (typeof (MeshCombiner)); window.minSize = new Vector2(300,500); window.maxSize = new Vector2(300,500); window.maximized = true; window.Show(); } void OnGUI(){ if(Selection.activeGameObject)CreateNewMesh(); else DisplayHelp(); } void CreateNewMesh(){ GUILayout.Label ("Create New Mesh from selection", EditorStyles.whiteBoldLabel); newMeshName = EditorGUILayout.TextField ("New Mesh Name", newMeshName); if (GUILayout.Button("Combine!"))CombineSelectedMeshes(); } void DisplayHelp(){ GUILayout.Label("Select one or more Gameobjects to begin combining meshes", EditorStyles.helpBox); } void CombineSelectedMeshes(){ meshObject = new GameObject(); meshObject.name = "New Mesh Object"; meshObject.AddComponent<MeshFilter>(); meshObject.AddComponent<MeshRenderer>(); selectedMeshGroup = new GameObject(); selectedMeshGroup.name = "Selected Mesh Group"; selectedMeshGroup.AddComponent<MeshFilter>(); selectedMeshGroup.AddComponent<MeshRenderer>(); foreach(Transform t in Selection.transforms){ t.parent = selectedMeshGroup.transform; } selectedMeshGroup.transform.position = Vector3.zero; selectedMeshGroup.transform.rotation = Quaternion.identity; MeshFilter[] meshFilters = selectedMeshGroup.GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length-1]; int index = 0; for (var i = 0; i < meshFilters.Length; i++){ if (meshFilters[i].sharedMesh == null) continue; combine[index].mesh = meshFilters[i].sharedMesh; combine[index++].transform = meshFilters[i].transform.localToWorldMatrix; meshFilters[i].transform.GetComponent<Renderer>().enabled = false; } selectedMeshGroup.GetComponent<MeshFilter>().sharedMesh = new Mesh(); selectedMeshGroup.GetComponent<MeshFilter>().sharedMesh.CombineMeshes (combine); selectedMeshGroup.GetComponent<Renderer>().material = meshFilters[1].GetComponent<Renderer>().sharedMaterial; while(selectedMeshGroup.transform.childCount != 0){ DestroyImmediate(selectedMeshGroup.transform.GetChild(0).gameObject); } selectedMeshGroup.name = newMeshName; Selection.activeGameObject = selectedMeshGroup; DestroyImmediate(meshObject); SaveMeshToAssets(); } void SaveMeshToAssets(){ //Create Mesh Folder AssetDatabase.CreateFolder("Assets/Meshes/Room Components", newMeshName); //Save Mesh Mesh newMesh = selectedMeshGroup.GetComponent<MeshFilter>().sharedMesh; AssetDatabase.CreateAsset( newMesh, "Assets/Meshes/Room Components/"+newMeshName+"/" +newMeshName+" .asset"); Debug.Log(AssetDatabase.GetAssetPath(newMesh)); //Save All Assets AssetDatabase.SaveAssets(); //Create Prefab //Object prefab = EditorUtility.CreateEmptyPrefab("Assets/Resources/_ROOMS/"+roomName+".prefab"); //EditorUtility.ReplacePrefab(Selection.activeGameObject.transform.parent.parent.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyClassLibrary; namespace Les3Exercise2 { class Program { //Ронжин Л. //2. а) С клавиатуры вводятся числа, пока не будет введён 0 (каждое число в новой строке). //Требуется подсчитать сумму всех нечётных положительных чисел. //Сами числа и сумму вывести на экран, используя tryParse. //б) Добавить обработку исключительных ситуаций на то, что могут быть введены некорректные данные. // При возникновении ошибки вывести сообщение.Напишите соответствующую функцию; static void Main(string[] args) { // Пункт б как я понимаю был выполнен еще на 1м уроке, где я заранее использовал tryParse MyMetods.Print("Введите целое число."); int n = MyMetods.ReadInt(); int sum = 0; string str = n.ToString(); do { if (n > 0 && (n % 2 != 0)) sum += n; MyMetods.Print("Введите следующее число."); n = MyMetods.ReadInt(); str = str + ", " + n.ToString(); } while (n != 0); Console.WriteLine($"Сумма всех нечетных положительных чисел из ряда: {str} составляет {sum}."); MyMetods.Pause(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NotSoSmartSaverAPI.DTO.GoalDTO { public class AddMoneyDTO { public string userId { get; set; } public string goalId { get; set; } public string goalName { get; set; } public float moneyToAdd { get; set; } public float goalAllocatedMoney { get; set; } public float goalRequiredMoney { get; set; } } }
using MikeGrayCodes.BuildingBlocks.Domain.Entities; namespace MikeGrayCodes.BuildingBlocks.Domain { public interface IRepository<T> where T : IAggregateRoot { } }
using UnityEngine; using System.Collections; public class SizeCamera : MonoBehaviour { public float minWorldAspectRatio = 800f/600f; public float targetWorldHalfHeight = 5f; public float screenPixelsTopCameraSlop = 0f; public delegate void CameraConfiguredHandler(); public event CameraConfiguredHandler CameraConfigured; public float finalActualWorldHalfHeight { get; private set; } float phaseStartTime; Camera myCamera; ZoomCamera myZoomCamera; bool registeredForEvents; float finalAspectRatio; void Awake() { finalAspectRatio = 0; myCamera = GetComponent<Camera>(); myZoomCamera = GetComponent<ZoomCamera>(); } void UpdateCameraSize() { if (myZoomCamera) { myZoomCamera.UpdateCameraSize(); } else { myCamera.orthographicSize = finalActualWorldHalfHeight; } } public float GetAspectRatio() { return finalAspectRatio; } public void Configure(float screenPixelsBottomToIgnore) { float focusHeightInPixels = (float)Screen.height - (screenPixelsTopCameraSlop + screenPixelsBottomToIgnore); float actualHeightInPixels = (float)Screen.height; finalAspectRatio = (float)Screen.width / focusHeightInPixels; float focusWorldHalfHeight = targetWorldHalfHeight; float focusWorldHalfWidth = finalAspectRatio * focusWorldHalfHeight; if (finalAspectRatio < minWorldAspectRatio) { // The available rect to render into on screen is narrower than we'd like. // Adjust worldHalfHeight so that resultant width is wide enough. focusWorldHalfWidth = minWorldAspectRatio * targetWorldHalfHeight; focusWorldHalfHeight = focusWorldHalfWidth / finalAspectRatio; } float pixelsToWorldScale = 2 * focusWorldHalfHeight / focusHeightInPixels; float actualWorldHalfHeight = (actualHeightInPixels * pixelsToWorldScale)/2; finalActualWorldHalfHeight = actualWorldHalfHeight; UpdateCameraSize (); float pixelsOffset = (screenPixelsTopCameraSlop - screenPixelsBottomToIgnore) / 2; float yAdjust = pixelsOffset * pixelsToWorldScale; Vector3 newPos = new Vector3 (0, yAdjust, 0); newPos = myCamera.transform.TransformVector(newPos); myCamera.transform.localPosition = myCamera.transform.localPosition + newPos; Rect rect = myCamera.rect; // Camera always goes all the way across.... float heightViewport = actualHeightInPixels / (float)Screen.height; rect.width = 1f; rect.height = heightViewport; rect.x = 0; rect.y = 0; myCamera.rect = rect; if (CameraConfigured != null) { CameraConfigured (); } } }
using UnityEngine; using System.Collections; public class addForce : MonoBehaviour { private float currentKS; private randomInst Spd; // Use this for initialization void Start () { Spd = GameObject.Find ("keys").GetComponent<randomInst> (); } // Update is called once per frame void Update () { this.GetComponent<Rigidbody>().AddForce(transform.right * Spd.keySpeed); } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public PlayerOptions po; /// <summary> /// Player score displays. /// </summary> public Text player1ScoreText, player2ScoreText; /// <summary> /// game clock. /// </summary> public Text clock; /// <summary> /// Reference to the canvas object that displays the winner /// </summary> public GameObject gameOverScreen; /// <summary> /// the textobject declaring either player the winner! /// </summary> public Text winner; /// <summary> /// reference to the HUD object. /// </summary> public GameObject HUD; /// <summary> /// player scores /// </summary> public int player1Score, player2Score; /// <summary> /// the current game duration /// </summary> public float gameTime; /// <summary> /// is the game over. /// </summary> public bool gameOver; /// <summary> /// Update player score. /// </summary> /// <param name="playerName">String containing the name of player that scored</param> public void Score(string playerName){ Debug.Log("player: " + playerName + " Scored"); if(playerName.Equals("Player1")){ player1Score += 1; } else if(playerName.Equals("Player2")){ player2Score += 1; } else { Debug.Log("OOPS INVALID PLAYER IN GAMEMANAGER:SCORE"); } } // Use this for initialization void Start () { po = GameObject.Find("GameOptions").GetComponent<PlayerOptions>(); gameOver = false; player1Score = 0; player2Score = 0; gameTime = po.gameDuration; } public void replay(){ Time.timeScale = 1; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void mainMenu(){ Time.timeScale = 1; SceneManager.LoadScene("Main Menu"); } void endGame(){ HUD.SetActive(false); gameOverScreen.SetActive(true); if(player1Score == player2Score){ winner.text = "Tie!"; } else { winner.text = (player1Score > player2Score)? "Player 1 wins!": "Player 2 wins!"; } } // Update is called once per frame void Update () { gameTime -= Time.deltaTime; if(gameTime <= 0){ gameOver = true; endGame(); } player1ScoreText.text = "Player 1 : " + player1Score; player2ScoreText.text = "Player 2 : " + player2Score; float sec = gameTime % 60; float min = (gameTime - sec) / 60; string minutes = (min < 10)? "0"+min : min.ToString(); string seconds = (sec - (sec % 1)).ToString(); clock.text = minutes + ":" + seconds; //update some shit. } }
using System; namespace Assets.Scripts.Models.Seedlings.Watermelon { public class WatermelonWithered : Food.Food { public WatermelonWithered() { LocalizationName = "watermelon_withered"; IconName = "watermelon_withered_icon"; HungerEffect = 2f; ThirstEffect = 15f; HealthEffect = -10f; } public override void Use(GameManager gameManager, Action<int> changeAmount = null) { base.Use(gameManager, changeAmount); gameManager.PlayerModel.ChangeHunger(HungerEffect); gameManager.PlayerModel.ChangeThirst(ThirstEffect); gameManager.PlayerModel.ChangeHealth(HealthEffect); SoundManager.PlaySFX(WorldConsts.AudioConsts.PlayerEat); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Requests { public class CloudServerVolumesRetrieve { public string serverId { get; set; } public string zoneId { get; set; } public string status { get; set; } public string volumeSpecId { get; set; } public string limit { get; set; } public string offset { get; set; } } }
using System; using System.Diagnostics; using System.IO; //Zadanie 4. Przetestuj i porównaj (Stopwatch) //napisane przez nas metody testowania: Wybieranie, //szybkie oraz pozycyjne dla losowych tablic zawierających //liczby co najwyżej 6-cio cyfrowe. class Program { static void BabelSort(int[] L) { int N = L.Length; for (int i = 0; i < N; i++) { for (int j = N - 1; j > i; j--) { if (L[j] < L[j - 1]) { int t = L[j - 1]; L[j - 1] = L[j]; L[j] = t; } } } } static int Podzial(int[] T, int l, int p) { int i, j, klucz, tmp, index; index = (l + p) / 2; // mogą być inne klucz = T[index]; // zamien element centralny z prawym tmp = T[index]; T[index] = T[p]; T[p] = tmp; i = l; for (j = l; j < p; j++) { if (T[j] <= klucz) // zamień { tmp = T[i]; T[i] = T[j]; T[j] = tmp; i++; } } // wstaw element centralny na swoje miejsce tmp = T[i]; T[i] = T[p]; T[p] = tmp; return i; } static void QuickSort(int[] T, int l, int p) { if (l >= p) return; int i = Podzial(T, l, p); QuickSort(T, l, i - 1); QuickSort(T, i + 1, p); } static void Pozycyjne(int[] A, int podstawa) { int n = A.Length; int[] B = new int[n]; int m = A[0]; //szukamy najwiekszej liczby m for (int i = 1; i < n; i++) if (A[i] > m) m = A[i]; int exp = 1; // podstawa^0 potem podstawa^1 itd az while (m / exp > 0) //znajdziemy wartosc wieksza od najwiekszej liczby { int[] liczniki = new int[podstawa]; //zliczanie wartosci na pozycjach czyli znajdujemy liczniki for (int i = 0; i < n; i++) liczniki[(A[i] / exp) % podstawa]++; //sumujemy liczniki for (int i = 1; i < podstawa; i++) liczniki[i] += liczniki[i - 1]; //umieszczmy elementy na swoich pozycjach obnizajac licznik for (int i = n - 1; i >= 0; i--) B[--liczniki[(A[i] / exp) % podstawa]] = A[i]; //kopiujemy ciag wyjsciowy do tablicy poczatkowej for (int i = 0; i < n; i++) A[i] = B[i]; //przechodzimy do następnej pozycji exp *= podstawa; } } static int[] Wczytaj(string path, int dlugosc) { int[] tab = new int[dlugosc]; StreamReader sr = new StreamReader(path); int i = 0; while (i < tab.Length) { tab[i] = Convert.ToInt32(sr.ReadLine()); i++; } sr.Close(); return tab; } static void Main(string[] args) { // plik ma 100 000 elementów // w domu możemy podmienic na duży int[] tab = Wczytaj("plik6cyfrmaly.txt", 100000); Stopwatch sw = new Stopwatch(); sw.Start(); QuickSort(tab, 0, tab.Length - 1); sw.Stop(); Console.WriteLine(sw.ElapsedTicks); sw.Reset(); sw.Start(); Pozycyjne(tab, 10); sw.Stop(); Console.WriteLine(sw.ElapsedTicks); sw.Reset(); sw.Start(); BabelSort(tab); sw.Stop(); Console.WriteLine(sw.ElapsedTicks); Console.ReadKey(); } }
// // LookupDataModelProviderBase.cs // // Author: // nofanto ibrahim <nofanto.ibrahim@gmail.com> // // Copyright (c) 2011 sejalan // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using Sejalan.Framework.Provider; using System.Collections.Generic; using Sejalan.Framework.Cache; using System.Threading; namespace Sejalan.Framework.LookupDataModel { public abstract class LookupDataModelProviderBase: ProviderBase { private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(); public LookupDataModelProviderBase () { } public virtual LookupItemCollection GetLookups(string collectionName) { cacheLock.EnterUpgradeableReadLock(); try { Dictionary<string, LookupItemCollection> cachedItems = new Dictionary<string, LookupItemCollection>(); if (CacheProvider.Contains(this.Name)) { cachedItems = CacheProvider.Read(this.Name) as Dictionary<string,LookupItemCollection>; } if (cachedItems.ContainsKey(collectionName)) { return cachedItems[collectionName]; } else { cacheLock.EnterWriteLock(); try { LookupItemCollection result = InitializeLookups(collectionName); cachedItems.Add(collectionName, result); CacheProvider.Update(this.Name,cachedItems); return result; } finally { cacheLock.ExitWriteLock(); } } } finally { cacheLock.ExitUpgradeableReadLock(); } } protected abstract LookupItemCollection InitializeLookups (string collectionName); public abstract void SaveLookups(LookupItemCollection lookups); public CacheProviderBase CacheProvider { get{ return ProviderFactory.GetInstance<CacheFactory>(ProviderRepositoryFactory.Instance.Providers[Parameters["cacheProviderRepositoryName"]]).GetProviders<CacheProviderBase>()[Parameters["cacheProviderName"]]; } } } }
/* * Matt Kirchoff * red.cs * CIS 452 Assignment 10 * this returns the object to pool when run into the drain */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class red : MonoBehaviour { private ObjectPooler objectPooler; private Spawner spawner; private AudioSource audioSource; public AudioClip explode; public AudioClip drain; public float radius; public float power; // Start is called before the first frame update void Start() { audioSource = gameObject.GetComponent<AudioSource>(); objectPooler = FindObjectOfType<ObjectPooler>(); spawner = FindObjectOfType<Spawner>(); } // Update is called once per frame void Update() { } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Drain")) { audioSource.PlayOneShot(drain); int temp = spawner.score; spawner.score = temp - 1; objectPooler.ReturnObjectToPool("red", this.gameObject); } } public void Explode() { Rigidbody rb = gameObject.GetComponent<Rigidbody>(); Vector3 target = rb.gameObject.transform.position; Collider[] colliders = Physics.OverlapSphere(target, radius); foreach (Collider col in colliders) { Rigidbody rb2 = col.GetComponent<Rigidbody>(); if (rb2 != null) { rb2.AddExplosionForce(power, rb2.gameObject.transform.position, radius, 3.0f, ForceMode.Impulse); } } target = target + new Vector3(0, -2.5f, 0); rb.AddExplosionForce(power / 2, rb.gameObject.transform.position, radius, 3.0f, ForceMode.Impulse); audioSource.PlayOneShot(explode); } }
using Microsoft.EntityFrameworkCore.Migrations; namespace WebsiteManagerPanel.Migrations { public partial class AddDescForAllTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Description", table: "Sites", type: "nvarchar(max)", maxLength: 8000, nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "Description", table: "Fields", type: "nvarchar(max)", maxLength: 8000, nullable: false, defaultValue: ""); migrationBuilder.AlterColumn<string>( name: "Description", table: "Definitions", type: "nvarchar(max)", maxLength: 8000, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(150)", oldMaxLength: 150); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Description", table: "Sites"); migrationBuilder.DropColumn( name: "Description", table: "Fields"); migrationBuilder.AlterColumn<string>( name: "Description", table: "Definitions", type: "nvarchar(150)", maxLength: 150, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(max)", oldMaxLength: 8000); } } }
using UnityEngine; using UnityEditor; using Ardunity; [CustomEditor(typeof(GenericMotor))] public class GenericMotorEditor : ArdunityObjectEditor { bool foldout = false; SerializedProperty script; SerializedProperty id; SerializedProperty controlType; SerializedProperty pin1; SerializedProperty pin2; SerializedProperty pin3; SerializedProperty punchValue; void OnEnable() { script = serializedObject.FindProperty("m_Script"); id = serializedObject.FindProperty("id"); controlType = serializedObject.FindProperty("controlType"); pin1 = serializedObject.FindProperty("pin1"); pin2 = serializedObject.FindProperty("pin2"); pin3 = serializedObject.FindProperty("pin3"); punchValue = serializedObject.FindProperty("punchValue"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GenericMotor controller = (GenericMotor)target; GUI.enabled = false; EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]); GUI.enabled = true; foldout = EditorGUILayout.Foldout(foldout, "Sketch Options"); if(foldout) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(id, new GUIContent("id")); EditorGUILayout.PropertyField(controlType, new GUIContent("controlType")); if(controller.controlType == GenericMotor.ControlType.OnePWM_OneDir) { EditorGUILayout.PropertyField(pin1, new GUIContent("dir Pin")); EditorGUILayout.PropertyField(pin2, new GUIContent("pwm Pin(~_)")); } else if(controller.controlType == GenericMotor.ControlType.TwoPWM) { EditorGUILayout.PropertyField(pin1, new GUIContent("F pwm Pin(~_)")); EditorGUILayout.PropertyField(pin2, new GUIContent("B pwm Pin(~_)")); } else { EditorGUILayout.PropertyField(pin1, new GUIContent("pwm Pin(~_)")); EditorGUILayout.PropertyField(pin2, new GUIContent("F dir Pin")); EditorGUILayout.PropertyField(pin3, new GUIContent("B dir Pin")); } EditorGUI.indentLevel--; } EditorGUILayout.PropertyField(punchValue, new GUIContent("punchValue")); controller.Value = EditorGUILayout.Slider("Value", controller.Value, -1f, 1f); if(GUILayout.Button("Stop")) controller.Value = 0f; this.serializedObject.ApplyModifiedProperties(); } static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func) { string menuName = "ARDUINO/Add Controller/Motor/GenericMotor"; if(Selection.activeGameObject != null) menu.AddItem(new GUIContent(menuName), false, func, typeof(GenericMotor)); else menu.AddDisabledItem(new GUIContent(menuName)); } }
using Microsoft.EntityFrameworkCore; using NetNote.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NetNote.Repository { public class NoteTypeRepository : INoteTypeRepository { private NoteContext context; public NoteTypeRepository(NoteContext _context) { context = _context; } public Task<List<NoteType>> ListAsync() { return context.NoteTypes.ToListAsync(); } } }
using Microsoft.ServiceFabric.Data; using Microsoft.ServiceFabric.Services.Communication.Runtime; using System.Collections.Generic; using System.Fabric; using System.Threading; using System.Threading.Tasks; namespace Microsoft.ServiceFabric.Services.Runtime { public class StatefulService : StatefulServiceBase { //TODO: This hould not be static. It should have a way to resolve the state manager by the service private static IReliableStateManager _stateManager; public StatefulService(StatefulServiceContext context) { //TODO: Is that the right place to run this? Task.Factory.StartNew(async () => { await RunAsync(CancellationToken.None); }, TaskCreationOptions.LongRunning); } public IReliableStateManager StateManager { get { if (_stateManager == null) { _stateManager = new ReliableStateManager(); } return _stateManager; } } public StatefulServiceContext Context { get; } protected virtual IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() { return null; } protected virtual IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners() { return null; } protected override async Task RunAsync(CancellationToken cancellationToken) { await Task.Run(() => { }); } } }
namespace ForumSystem.Web.Controllers.APIs { using System.Threading.Tasks; using ForumSystem.Services.Data; using ForumSystem.Web.ViewModels.Posts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/categories")] public class CategoriesApiController : ControllerBase { private readonly ICategoriesService categories; public CategoriesApiController(ICategoriesService categories) { this.categories = categories; } [HttpGet] [Authorize] [Route("search")] public async Task<IActionResult> Search(string term) { if (!string.IsNullOrWhiteSpace(term)) { var data = await this.categories .FindCategoryByTermSearchAsync<CategoryDropDownViewModel>(term); return this.Ok(data); } else { var data = await this.categories .GetAllAsync<CategoryDropDownViewModel>(); return this.Ok(data); } } } }
namespace powerDg.M.KMS.MongoDB { public abstract class KMSMongoDbTestBase : KMSTestBase<KMSMongoDbTestModule> { } }
using Elrond.Dotnet.Sdk.Domain.Codec; using Elrond.Dotnet.Sdk.Domain.Values; using NUnit.Framework; namespace Elrond_sdk.dotnet.tests.Domain.Codec { public class BinaryCodecTests { [Test] public void DecodeNested_False() { // Arrange var buffer = new byte[] { 0x01 }; var codec = new BinaryCodec(); // Act var actual = codec.DecodeNested(buffer, TypeValue.BooleanValue); BytesValue.FromBuffer(new byte[] { 0x00 }); // Assert Assert.AreEqual(true, (actual.Value.ValueOf<BooleanValue>()).IsTrue()); } [Test] public void DecodeNested_True() { // Arrange var buffer = new byte[] { 0x01 }; var codec = new BinaryCodec(); // Act var actual = codec.DecodeNested(buffer, TypeValue.BooleanValue); BytesValue.FromBuffer(new byte[] { 0x00 }); // Assert Assert.AreEqual(true, (actual.Value.ValueOf<BooleanValue>()).IsTrue()); } } }
namespace GunSystem { public enum AttachmentType { Muzzle, Sight, Magazine, Grip, Stock } }
using System; using System.Linq; using System.Web.Mvc; using Tomelt.ContentManagement.Records; using Tomelt.DisplayManagement; using Tomelt.Environment.ShellBuilders.Models; using Tomelt.Forms.Services; using Tomelt.Localization; namespace Tomelt.Projections.Providers.Filters { public class ContentPartRecordsForm : IFormProvider { private readonly ShellBlueprint _shellBlueprint; protected dynamic Shape { get; set; } public Localizer T { get; set; } public ContentPartRecordsForm( ShellBlueprint shellBlueprint, IShapeFactory shapeFactory) { _shellBlueprint = shellBlueprint; Shape = shapeFactory; T = NullLocalizer.Instance; } public void Describe(DescribeContext context) { Func<IShapeFactory, object> form = shape => { var f = Shape.Form( Id: "AnyOfContentPartRecords", _Parts: Shape.SelectList( Id: "contentpartrecordss", Name: "ContentPartRecords", Title: T("Content part records"), Description: T("Select some content part records."), Size: 10, Multiple: true ) ); foreach (var recordBluePrint in _shellBlueprint.Records.OrderBy(x => x.Type.Name)) { if (typeof(ContentPartRecord).IsAssignableFrom(recordBluePrint.Type) || typeof(ContentPartVersionRecord).IsAssignableFrom(recordBluePrint.Type)) { f._Parts.Add(new SelectListItem { Value = recordBluePrint.Type.Name, Text = recordBluePrint.Type.Name }); } } return f; }; context.Form("ContentPartRecordsForm", form); } } }
using System; namespace GitTest { public class Class1 { } }
 namespace com.Sconit.Utility.Report { using System; using System.Collections.Generic; using System.Linq; using NPOI.HSSF.UserModel; using System.IO; public interface IReportBase { bool FillValues(String templateFileFolder, String templateFileName, IList<object> list); bool FillValues(String templateFileFolder, String templateFileName, IList<object> list, int sheetIndex); int CopyPage(int pageCount, int columnCount); void CopyPageValues(int pageIndex); HSSFWorkbook GetWorkbook(); } }
// Copyright (c) 2020, mParticle, Inc // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using MP.Json; using MP.Json.Validation; using Xunit; namespace JsonSchemaTestSuite.Draft201909 { public class OneOf { /// <summary> /// 1 - oneOf /// </summary> [Theory] [InlineData( "first oneOf valid", "1", true )] [InlineData( "second oneOf valid", "2.5", true )] [InlineData( "both oneOf valid", "3", false )] [InlineData( "neither oneOf valid", "1.5", false )] public void OneOfTest(string desc, string data, bool expected) { // oneOf Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ { 'type':'integer' }, { 'minimum':2 } ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 2 - oneOf with base schema /// </summary> [Theory] [InlineData( "mismatch base schema", "3", false )] [InlineData( "one oneOf valid", "'foobar'", true )] [InlineData( "both oneOf valid", "'foo'", false )] public void OneOfWithBaseSchema(string desc, string data, bool expected) { // oneOf with base schema Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ { 'minLength':2 }, { 'maxLength':4 } ], 'type':'string' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 3 - oneOf with boolean schemas, all true /// </summary> [Theory] [InlineData( "any value is invalid", "'foo'", false )] public void OneOfWithBooleanSchemasAllTrue(string desc, string data, bool expected) { // oneOf with boolean schemas, all true Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ true, true, true ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 4 - oneOf with boolean schemas, one true /// </summary> [Theory] [InlineData( "any value is valid", "'foo'", true )] public void OneOfWithBooleanSchemasOneTrue(string desc, string data, bool expected) { // oneOf with boolean schemas, one true Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ true, false, false ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 5 - oneOf with boolean schemas, more than one true /// </summary> [Theory] [InlineData( "any value is invalid", "'foo'", false )] public void OneOfWithBooleanSchemasMoreThanOneTrue(string desc, string data, bool expected) { // oneOf with boolean schemas, more than one true Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ true, true, false ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 6 - oneOf with boolean schemas, all false /// </summary> [Theory] [InlineData( "any value is invalid", "'foo'", false )] public void OneOfWithBooleanSchemasAllFalse(string desc, string data, bool expected) { // oneOf with boolean schemas, all false Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ false, false, false ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 7 - oneOf complex types /// </summary> [Theory] [InlineData( "first oneOf valid (complex)", "{ 'bar':2 }", true )] [InlineData( "second oneOf valid (complex)", "{ 'foo':'baz' }", true )] [InlineData( "both oneOf valid (complex)", "{ 'bar':2, 'foo':'baz' }", false )] [InlineData( "neither oneOf valid (complex)", "{ 'bar':'quux', 'foo':2 }", false )] public void OneOfComplexTypes(string desc, string data, bool expected) { // oneOf complex types Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ { 'properties':{ 'bar':{ 'type':'integer' } }, 'required':[ 'bar' ] }, { 'properties':{ 'foo':{ 'type':'string' } }, 'required':[ 'foo' ] } ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 8 - oneOf with empty schema /// </summary> [Theory] [InlineData( "one valid - valid", "'foo'", true )] [InlineData( "both valid - invalid", "123", false )] public void OneOfWithEmptySchema(string desc, string data, bool expected) { // oneOf with empty schema Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ { 'type':'number' }, { } ] }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 9 - oneOf with required /// </summary> [Theory] [InlineData( "both invalid - invalid", "{ 'bar':2 }", false )] [InlineData( "first valid - valid", "{ 'bar':2, 'foo':1 }", true )] [InlineData( "second valid - valid", "{ 'baz':3, 'foo':1 }", true )] [InlineData( "both valid - invalid", "{ 'bar':2, 'baz':3, 'foo':1 }", false )] public void OneOfWithRequired(string desc, string data, bool expected) { // oneOf with required Console.Error.WriteLine(desc); string schemaData = "{ 'oneOf':[ { 'required':[ 'foo', 'bar' ] }, { 'required':[ 'foo', 'baz' ] } ], 'type':'object' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alps.Domain.ProductMgr { public enum DeliveryVoucherState { Unconfirmed, Confirmed } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowerEnemy : EnemyController { public float LineOfSight; private Transform Player; public float speedtowardsplayer; Animator anim; void Start() { Player = GameObject.FindGameObjectWithTag("Player").transform; anim = GetComponent<Animator>(); } void Update() { float distanceFromPlayer = Vector2.Distance(Player.position, transform.position); if (distanceFromPlayer < LineOfSight) { if (transform.position.x > Player.transform.position.x) { transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z); isFacingRight = false; } if (transform.position.x < Player.transform.position.x) { isFacingRight = true; transform.localScale = new Vector3(-Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z); } transform.position = Vector2.MoveTowards(this.transform.position, Player.position, speedtowardsplayer * Time.deltaTime); anim.SetTrigger("Bite"); } } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, LineOfSight); } void OnTriggerEnter2D(Collider2D collider) { if (collider.tag == "Player") { FindObjectOfType<AudioManager>().Play("BTA"); FindObjectOfType<PlayerStatus>().TakeDamage(damage); Debug.Log("Text: Attack"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace CourseHunter_95_LINQ_ParsingCSV { public class FileHelper { public static void MinMaxSummAverage(string path) { var lines = File.ReadAllLines(path); IEnumerable<CheesPlayer> list = lines .Skip(1) // пропускаем первую строчку .Select(x => CheesPlayer.ParseFideCSV(x)) // Метод расширения (ПРОЕКЦИИ). Берет объект и трансформирует в другой тип. //.Select(CheesPlayer.ParseFideCSV) // Синтаксический сахар верхней строки. .Where(player => player.Birthday > 1989) // год рождения .OrderBy(player => player.Rank) // сортировка по .ThenBy(player => player.Country); // вторая сортировка по стране //.Take(10); // взять 10 //.ToList(); // метод расширения который IEnumerable превращает в лист. // int count = 1; //foreach (var item in list) //{ // Console.WriteLine($"{count} - {item}"); // count++; //} // ИЗ УЖЕ ВЫБРАННЫХ!!!!!!! Console.WriteLine($"The lowest rating in TOP: {list.Min(x => x.Rating)} "); Console.WriteLine($"The highest rating in TOP: {list.Max(x => x.Rating)}"); Console.WriteLine($"The average rating in TOP: {list.Average(x => x.Rating)}"); Console.WriteLine(new string ('-', 35)); Console.WriteLine(list.First()); //если последовательность пустая будет выбрашено исключение. А нет - первый элемент. Console.WriteLine(list.Last()); Console.WriteLine(new string('-', 35)); // эти расширения имеют свои делегаты, поэтому мы их можем использовать для других операций. Console.WriteLine(list.First(player => player.Country == "USA")); // если не нужна ошибка используй брата окрабата. Console.WriteLine(list.LastOrDefault(player => player.Country == "USA")); Console.WriteLine(new string('-', 35)); Console.WriteLine(list.First(player => player.Country == "FRA")); Console.WriteLine(list.Single(player => player.Country == "FRA")); Console.WriteLine(list.SingleOrDefault(player => player.Country == "BRA")); } } }
#region license // Copyright (c) 2007-2010 Mauricio Scheffer // // 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. #endregion using SolrNet.Impl; namespace SolrNet { /// <summary> /// Queries a field for a range /// </summary> /// <typeparam name="RT"></typeparam> public class SolrQueryByRange<RT> : AbstractSolrQuery, ISolrQueryByRange { private readonly string fieldName; private readonly RT from; private readonly RT to; private readonly bool inclusive; public SolrQueryByRange(string fieldName, RT from, RT to) : this(fieldName, from, to, true) {} public SolrQueryByRange(string fieldName, RT @from, RT to, bool inclusive) { this.fieldName = fieldName; this.from = from; this.to = to; this.inclusive = inclusive; } public string FieldName { get { return fieldName; } } public RT From { get { return from; } } object ISolrQueryByRange.From { get { return from; } } public RT To { get { return to; } } object ISolrQueryByRange.To { get { return to; } } public bool Inclusive { get { return inclusive; } } } }
using System; using System.ComponentModel.DataAnnotations; using Microsoft.Practices.ServiceLocation; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels; namespace Profiling2.Web.Mvc.Validators { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class UnitHierarchyPreventLoopAttribute : ValidationAttribute { public UnitHierarchyPreventLoopAttribute() { this.ErrorMessage = "A unit loop exists: please change one."; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { UnitHierarchyViewModel vm = (UnitHierarchyViewModel)value; // no hierarchy type should allow both units to be the same if (vm.ParentUnitId == vm.UnitId) return new ValidationResult(this.ErrorMessage); // don't allow duplicates or reverse relationships if already exists if (ServiceLocator.Current.GetInstance<IOrganizationTasks>().GetUnitHierarchy(vm.UnitId, vm.ParentUnitId) != null || ServiceLocator.Current.GetInstance<IOrganizationTasks>().GetUnitHierarchy(vm.ParentUnitId, vm.UnitId) != null) return new ValidationResult(this.ErrorMessage); } return ValidationResult.Success; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Text; using Android.Views; using Android.Widget; using Cashflow9000.Adapters; using Cashflow9000.Fragments; using Cashflow9000.Models; namespace Cashflow9000 { [Activity(Label = "MilestoneActivity")] public class MilestoneActivity : ItemActivity<Milestone> { public const string ExtraMilestoneId = "MilestoneActivity.ExtraMilestoneId"; protected override Fragment GetFragment(int id) { return new MilestoneFragment(id); } protected override string GetExtraId() { return ExtraMilestoneId; } } }
using EventBusRabbitMq.Common; using EventBusRabbitMq.Events; using EventBusRabbitMq.Producer; using MediatR; using Ordering.Application.Commands; using Ordering.Application.Mapper; using Ordering.Application.Responses; using Ordering.Core.Entities; using Ordering.Core.Repositories; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ordering.Application.Handles { public class CheckoutOrderHandler : IRequestHandler<CheckoutOrderCommand, OrderResponse> { private readonly IOrderRepository _order; private readonly EventBusRabbitMQProducer _eventBus; public CheckoutOrderHandler(IOrderRepository order, EventBusRabbitMQProducer eventBus) { _order = order; _eventBus = eventBus; } public async Task<OrderResponse> Handle(CheckoutOrderCommand request, CancellationToken cancellationToken) { var order = OrderMapper.Mapper.Map<Order>(request); if (order == null) throw new ApplicationException("not mapped"); var neworder = await _order.AddAsync(order); var model = OrderMapper.Mapper.Map<OrderResponse>(neworder); var eventMessage = OrderMapper.Mapper.Map<OrderCheckoutEvent>(model); try { _eventBus.PublishOrderCheckout(EventBusConstants.OrderCheckoutQueue, eventMessage); } catch (Exception) { throw; } return model; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Deveres { public partial class AddHomework : Form { string subjectName; string homework; SubjectsForm sbf =new SubjectsForm(); public List<Subject> listOfSubjects = new List<Subject>(); Homeworks hm; public AddHomework() { InitializeComponent(); } private void pbxBack_Click(object sender, EventArgs e) { Homeworks hms = new Homeworks(listOfSubjects); hms.Show(); this.Hide(); } public AddHomework(List<Subject> lista) { InitializeComponent(); listOfSubjects = lista; ForeachOfList(); } private void btnSave_Click(object sender, EventArgs e) { GetData(); if (tbxHomework.TextLength>0&&cbxSubject.Text!="") { using (StreamReader sr = new StreamReader(@"C: \Users\Windows\Documents\Visual Studio 2015\Projects\Deveres\Deveres\bin\Debug\Notepads\" + @"Subjects.txt")) { string linha; while ((linha = sr.ReadLine()) != null) { string[] dever = linha.Split('@'); string name= dever[0]; if ((subjectName+" ")==name) { if (dever[1] == homework) { MessageBox.Show("ja cadastrado"); } else { if (dever[1]!= null) { } MessageBox.Show("Dever adicionado com sucesso!"); hm = new Homeworks(listOfSubjects); using (StreamWriter outputFile = new StreamWriter(@"C:\Users\Windows\Documents\Visual Studio 2015\Projects\Deveres\Deveres\bin\Debug\Notepads" + @"\HomeWork.txt")) { foreach (Subject subjects in listOfSubjects) { if (subjects.SubjectName+" "==name) { subjects.Homework = homework; outputFile.WriteLine(subjects.SubjectName + " @ " +homework); } else { outputFile.WriteLine(subjects.SubjectName + " @ "+subjects.Homework); } } } hm.Show(); this.Hide(); } } } } } else { MessageBox.Show("Preencha as informações!"); } CleanData(); } private void GetData() { homework=tbxHomework.Text; subjectName=cbxSubject.Text; } private void CleanData() { tbxHomework.Text = ""; cbxSubject.Text = ""; } private void ForeachOfList() { foreach (Subject subject in listOfSubjects) { cbxSubject.Items.Add(subject.SubjectName); CleanData(); } } private void AddHomework_Load(object sender, EventArgs e) { } } }
namespace Ach.Fulfillment.Nacha.Message { using System; using System.Collections.Generic; using Ach.Fulfillment.Nacha.Attribute; using Ach.Fulfillment.Nacha.Record; using Ach.Fulfillment.Nacha.Serialization; [Serializable] public class File : SerializableBase { [Record(Position = 0, IsRequired = true, RecordType = "1", Postfix = "\n")] public FileHeaderRecord Header { get; set; } [Record(Position = 1, IsRequired = true, RecordType = "5")] public List<GeneralBatch> Batches { get; set; } [Record(Position = 2, IsRequired = true, RecordType = "9", Postfix = "\n")] public FileControlRecord Control { get; set; } } }
using MassTransit; using MassTransit.Saga; using Ntech.Saga.Contracts; using Ntech.Saga.Workflow; using System; using System.Threading; using System.Threading.Tasks; namespace Ntech.Saga.Service.Management { class Program { public static async Task Main(string[] args) { var sagaStateMachine = new BookingStateMachine(); var repository = new InMemorySagaRepository<BookingSagaState>(); // Register endpoint handle saga var bus = BusConfigurator.ConfigureBus((cfg, host) => { Console.WriteLine("Register endpoint handle saga..."); cfg.ReceiveEndpoint(host, RabbitMqConstants.SagaQueue, e => { e.StateMachineSaga(sagaStateMachine, repository); }); }); await bus.StartAsync(CancellationToken.None); Console.WriteLine("Saga active.. Press enter to exit"); Console.ReadLine(); await bus.StopAsync(CancellationToken.None); } } }
using static ExamWeb.Constants.HtmlConstants; using System.IO; using System.Text; using SimpleMVC.Interfaces; namespace ExamWeb.Views.Home { public class Login : IRenderable { public string Render() { string header = File.ReadAllText(ContentPath + Header); string navigation = File.ReadAllText(ContentPath + NavNotLogged); string login = File.ReadAllText(ContentPath + LoginHTML); string footer = File.ReadAllText(ContentPath + Footer); StringBuilder sb = new StringBuilder(); sb.Append(header); sb.Append(navigation); sb.Append(login); sb.Append(footer); return sb.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioPlayer : MonoBehaviour { public static AudioPlayer singleton = null; public bool iniciouPrimeiraFase = false; public bool iniciouSegundaFase = false; public bool iniciouTerceiraFase = false; public bool isPlaying = false; void Start() { } // Update is called once per frame void Update() { if ((iniciouPrimeiraFase || iniciouSegundaFase || iniciouTerceiraFase) && !isPlaying) { GetComponent<AudioSource>().Play(); isPlaying = true; } } void Awake() { DontDestroyOnLoad(this.gameObject); if (singleton == null) { singleton = this; } } }
using System; using System.Text.RegularExpressions; namespace Lab4.Ind._3 { class Program { static void Main(string[] args) { string text=Console.ReadLine(); Regex regex = new Regex(@"\(\d{3}\)\d{3}-?\d{2}-?\d{2}"); MatchCollection numbers = regex.Matches(text); if (numbers.Count > 0) { foreach (Match match in numbers) Console.Write(match.Value + "; "); } Console.ReadKey(); } } }
using ApiFipe.Domain.Model; using ApiFipe.Service.Service; using System; using System.ComponentModel.DataAnnotations; using System.Web.Http; using System.Net; using System.IO; using System.Web.Http.Cors; namespace ApiFipe.Controllers { public class HomeController : ApiController { FipeService srv = new FipeService(); [Route("BuscarTodos")] [HttpGet] public IHttpActionResult BuscarTodos() { return Ok(srv.List()); } [Route("AtualizarFipe")] [HttpGet] public IHttpActionResult AtualizarFipe(Fipe fipe) { srv.Update(fipe); return Ok(""); } [Route("Delete")] [HttpGet] public IHttpActionResult Delete(int id) { srv.Delete(id); return Ok(""); } [Route("BuscarPorId")] [HttpGet] public IHttpActionResult BuscarPorId(int id) { return Ok(srv.Get(id)); } [Route("Inserir")] [HttpGet] public IHttpActionResult Inserir(Fipe fipe) { srv.Add(fipe); return Ok(""); } [HttpPost] [EnableCors(origins: "*", headers: "*", methods: "*")] [Route("api/BuscarPorAno")] public IHttpActionResult BuscarPorAno(Fipe fipe) { return Ok(srv.BuscarPorAno(fipe.Ano)); } } }
using gView.Framework.Globalisation; using gView.Framework.system; using gView.Framework.UI; using System.Threading.Tasks; namespace gView.Plugins.MapTools { [RegisterPlugInAttribute("97F8675C-E01F-451e-AAE0-DC29CD547EB5")] public class ExitApplication : ITool, IExTool { IMapDocument _doc = null; IExplorerApplication _exapp = null; #region ITool Members public string Name { get { return LocalizedResources.GetResString("Tools.Exit", "Exit"); } } public bool Enabled { get { return true; } } public string ToolTip { get { return ""; } } public ToolType toolType { get { return ToolType.command; } } public object Image { get { return gView.Win.Plugin.Tools.Properties.Resources.exit_16_w; } } public void OnCreate(object hook) { if (hook is IMapDocument) { _doc = (IMapDocument)hook; } else if (hook is IExplorerApplication) { _exapp = (IExplorerApplication)hook; } } public Task<bool> OnEvent(object MapEvent) { if (_doc != null && _doc.Application != null) { _doc.Application.Exit(); } if (_exapp != null) { _exapp.Exit(); } return Task.FromResult(true); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace RelayUtil { using System; using System.Collections.Generic; using System.Net; using Microsoft.Azure.Relay; using Microsoft.Azure.Relay.Management; using Microsoft.Extensions.CommandLineUtils; using RelayUtil.HybridConnections; class HybridConnectionCommands : RelayCommands { internal const string DefaultPath = "RelayUtilHc"; internal static void ConfigureCommands(CommandLineApplication app) { app.RelayCommand("hc", (hcCommand) => { hcCommand.Description = "Operations for HybridConnections (CRUD, Test)"; ConfigureCreateCommand(hcCommand); ConfigureListCommand(hcCommand); ConfigureDeleteCommand(hcCommand); ConfigureCountCommand(hcCommand); ConfigureListenCommand(hcCommand); ConfigureSendCommand(hcCommand); ConfigureTestCommand(hcCommand); hcCommand.OnExecute(() => { hcCommand.ShowHelp(); return 0; }); }); } static void ConfigureCreateCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("create", (createCmd) => { createCmd.Description = "Create a HybridConnection"; var pathArgument = createCmd.Argument("path", "HybridConnection path"); var connectionStringArgument = createCmd.Argument("connectionString", "Relay ConnectionString"); var requireClientAuthOption = createCmd.Option( CommandStrings.RequiresClientAuthTemplate, CommandStrings.RequiresClientAuthDescription, CommandOptionType.SingleValue); createCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(pathArgument.Value)) { TraceMissingArgument(string.IsNullOrEmpty(connectionString) ? connectionStringArgument.Name : pathArgument.Name); createCmd.ShowHelp(); return 1; } var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); RelayTraceSource.TraceInfo($"Creating HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host}..."); var hcDescription = new HybridConnectionDescription(pathArgument.Value); hcDescription.RequiresClientAuthorization = GetBoolOption(requireClientAuthOption, true); var namespaceManager = new RelayNamespaceManager(connectionString); await namespaceManager.CreateHybridConnectionAsync(hcDescription); RelayTraceSource.TraceInfo($"Creating HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host} succeeded"); return 0; }); }); } static void ConfigureListCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("list", (listCmd) => { listCmd.Description = "List HybridConnection(s)"; var connectionStringArgument = listCmd.Argument("connectionString", "Relay ConnectionString"); listCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString)) { TraceMissingArgument(connectionStringArgument.Name); listCmd.ShowHelp(); return 1; } var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); RelayTraceSource.TraceInfo($"Listing HybridConnections for {connectionStringBuilder.Endpoint.Host}"); RelayTraceSource.TraceInfo($"{"Path",-38} {"ListenerCount",-15} {"RequiresClientAuth",-20}"); var namespaceManager = new RelayNamespaceManager(connectionString); IEnumerable<HybridConnectionDescription> hybridConnections = await namespaceManager.GetHybridConnectionsAsync(); foreach (var hybridConnection in hybridConnections) { RelayTraceSource.TraceInfo($"{hybridConnection.Path,-38} {hybridConnection.ListenerCount,-15} {hybridConnection.RequiresClientAuthorization}"); } return 0; }); }); } static void ConfigureDeleteCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("delete", (deleteCmd) => { deleteCmd.Description = "Delete a HybridConnection"; var pathArgument = deleteCmd.Argument("path", "HybridConnection path"); var connectionStringArgument = deleteCmd.Argument("connectionString", "Relay ConnectionString"); deleteCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(pathArgument.Value)) { TraceMissingArgument(string.IsNullOrEmpty(connectionString) ? connectionStringArgument.Name : pathArgument.Name); deleteCmd.ShowHelp(); return 1; } var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); RelayTraceSource.TraceInfo($"Deleting HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host}..."); var namespaceManager = new RelayNamespaceManager(connectionString); await namespaceManager.DeleteHybridConnectionAsync(pathArgument.Value); RelayTraceSource.TraceInfo($"Deleting HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host} succeeded"); return 0; }); }); } static void ConfigureCountCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("count", (countCommand) => { countCommand.Description = "Get HybridConnection Count"; var connectionStringArgument = countCommand.Argument("connectionString", "Relay ConnectionString"); countCommand.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString)) { TraceMissingArgument(connectionStringArgument.Name); countCommand.ShowHelp(); return 1; } var namespaceManager = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(connectionString); Uri namespaceUri = namespaceManager.Address; string namespaceHost = namespaceUri.Host; var tokenProvider = namespaceManager.Settings.TokenProvider; RelayTraceSource.TraceVerbose($"Getting HybridConnection count for '{namespaceUri}"); int count = await NamespaceUtility.GetEntityCountAsync(namespaceUri, tokenProvider, "HybridConnections"); RelayTraceSource.TraceInfo(string.Format($"{{0,-{namespaceHost.Length}}} {{1}}", "Namespace", "HybridConnectionCount")); RelayTraceSource.TraceInfo(string.Format($"{{0,-{namespaceHost.Length}}} {{1}}", namespaceHost, count)); return 0; }); }); } static void ConfigureListenCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("listen", (listenCmd) => { listenCmd.Description = "HybridConnection listen command"; var pathArgument = listenCmd.Argument("path", "HybridConnection path"); var connectionStringArgument = listenCmd.Argument("connectionString", "Relay ConnectionString"); var responseOption = listenCmd.Option("--response <response>", "Response to return", CommandOptionType.SingleValue); var responseLengthOption = listenCmd.Option("--response-length <responseLength>", "Length of response to return", CommandOptionType.SingleValue); var responseChunkLengthOption = listenCmd.Option("--response-chunk-length <responseLength>", "Length of response to return", CommandOptionType.SingleValue); var statusCodeOption = listenCmd.Option("--status-code <statusCode>", "The HTTP Status Code to return (200|201|401|404|etc.)", CommandOptionType.SingleValue); var statusDescriptionOption = listenCmd.Option("--status-description <statusDescription>", "The HTTP Status Description to return", CommandOptionType.SingleValue); listenCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString)) { TraceMissingArgument(connectionStringArgument.Name); listenCmd.ShowHelp(); return 1; } string response = GetMessageBody(responseOption, responseLengthOption, "<html><head><title>Azure Relay HybridConnection</title></head><body>Response Body from Listener</body></html>"); var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); connectionStringBuilder.EntityPath = pathArgument.Value ?? connectionStringBuilder.EntityPath ?? DefaultPath; var statusCode = (HttpStatusCode)GetIntOption(statusCodeOption, 200); int responseChunkLength = GetIntOption(responseChunkLengthOption, response.Length); return await HybridConnectionTests.VerifyListenAsync(RelayTraceSource.Instance, connectionStringBuilder, response, responseChunkLength, statusCode, statusDescriptionOption.Value()); }); }); } static void ConfigureSendCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("send", (sendCmd) => { sendCmd.Description = "HybridConnection send command"; var pathArgument = sendCmd.Argument("path", "HybridConnection path"); var connectionStringArgument = sendCmd.Argument("connectionString", "Relay ConnectionString"); var numberOption = sendCmd.Option(CommandStrings.NumberTemplate, CommandStrings.NumberDescription, CommandOptionType.SingleValue); var methodOption = sendCmd.Option("-m|--method <method>", "The HTTP Method (GET|POST|PUT|DELETE|WEBSOCKET)", CommandOptionType.SingleValue); var requestOption = sendCmd.Option(CommandStrings.RequestTemplate, CommandStrings.RequestDescription, CommandOptionType.SingleValue); var requestLengthOption = sendCmd.Option(CommandStrings.RequestLengthTemplate, CommandStrings.RequestLengthDescription, CommandOptionType.SingleValue); sendCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString)) { TraceMissingArgument(connectionStringArgument.Name); sendCmd.ShowHelp(); return 1; } var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); connectionStringBuilder.EntityPath = pathArgument.Value ?? connectionStringBuilder.EntityPath ?? DefaultPath; int number = GetIntOption(numberOption, 1); string method = GetStringOption(methodOption, "GET"); string requestContent = GetMessageBody(requestOption, requestLengthOption, null); await HybridConnectionTests.VerifySendAsync(connectionStringBuilder, number, method, requestContent, RelayTraceSource.Instance); return 0; }); }); } static void ConfigureTestCommand(CommandLineApplication hcCommand) { hcCommand.RelayCommand("test", (testCmd) => { testCmd.Description = "HybridConnection tests"; var connectionStringArgument = testCmd.Argument("connectionString", "Relay ConnectionString"); testCmd.OnExecute(async () => { string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument); if (string.IsNullOrEmpty(connectionString)) { TraceMissingArgument(connectionStringArgument.Name); testCmd.ShowHelp(); return 1; } return await HybridConnectionTests.RunTestsAsync(new RelayConnectionStringBuilder(connectionString), RelayTraceSource.Instance); }); }); } } }
using gView.Framework.Data; using gView.Framework.Editor.Core; using gView.Framework.FDB; using gView.Framework.system.UI; using gView.Framework.UI; using gView.Plugins.Editor.Dialogs; using System; using System.Collections.Generic; using System.Windows; namespace gView.Plugins.Editor.Editor { [gView.Framework.system.RegisterPlugIn("5434ca46-fc3a-466f-a9d5-88e8d5452bd6", Obsolete = true)] public class EditorRibbonTab : ICartoRibbonTab { private List<RibbonGroupBox> _groups; public EditorRibbonTab() { _groups = new List<RibbonGroupBox>( new RibbonGroupBox[]{ new RibbonGroupBox("Edit", new RibbonItem[] { //new RibbonItem(new Guid("784148EB-04EA-413d-B11A-1A0F9A7EA4A0")), new RibbonItem(new Guid("3C8A7ABC-B535-43d8-8F2D-B220B298CB17")), //new RibbonItem(new Guid("19396559-C13C-486c-B5F7-73DD5B12D5A8")), new RibbonItem(new Guid("9B7D5E0E-88A5-40e2-977B-8A2E21875221")) } ) { OnLauncherClick=OnEditLauncherClick }, new RibbonGroupBox(String.Empty, new RibbonItem[]{ new RibbonItem(new Guid("91392106-2C28-429c-8100-1E4E927D521C")), new RibbonItem(new Guid("3B64107F-00C8-4f4a-B781-163FE9DA2D4B"),"Middle"), new RibbonItem(new Guid("FD340DE3-0BC1-4b3e-99D2-E8DCD55A46F2"),"Middle"), new RibbonItem(new Guid("B576D3F9-F7C9-46d5-8A8C-16B3974F1BD7"),"Middle") } ), new RibbonGroupBox(String.Empty, new RibbonItem[]{ new RibbonItem(new Guid("96099E8C-163E-46ec-BA33-41696BFAE4D5")), new RibbonItem(new Guid("AC4620D4-3DE4-49ea-A902-0B267BA46BBF")), new RibbonItem(new Guid("11DEE52F-F241-406e-BB40-9F247532E43D")) } ) } ); } #region ICartoRibbonTab Member public string Header { get { return "Editor"; } } public List<RibbonGroupBox> Groups { get { return _groups; } } public int SortOrder { get { return 300; } } public bool IsVisible(IMapDocument mapDocument) { if (mapDocument == null || mapDocument.FocusMap == null) { return false; } foreach (IDataset dataset in mapDocument.FocusMap.Datasets) { if (dataset.Database is IFeatureUpdater) { return true; } } return false; } #endregion private void OnEditLauncherClick(object sender, RoutedEventArgs e) { if (e is RibbonGroupBox.LauncherClickEventArgs && ((RibbonGroupBox.LauncherClickEventArgs)e).Hook is IMapDocument) { IMapDocument mapDocument = (IMapDocument)((RibbonGroupBox.LauncherClickEventArgs)e).Hook; IMapApplication mapApplication = mapDocument.Application as IMapApplication; if (mapApplication != null) { Module module = mapApplication.IMapApplicationModule(Globals.ModuleGuid) as Module; if (!AppUIGlobals.IsAppReadOnly(mapDocument.Application)) { FormEditLauncher dlg = new FormEditLauncher(module); dlg.ShowDialog(); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Capa_de_Negocios_ONG_SYS; namespace ONG_SYS { /// <summary> /// Lógica de interacción para FRM_NuevoCliente.xaml /// </summary> public partial class FRM_NuevoCliente : Window { CN_Clientes objetoCN = new CN_Clientes(); Facturacion padre = null; public FRM_NuevoCliente() { InitializeComponent(); } public FRM_NuevoCliente(Facturacion padre) { InitializeComponent(); this.padre = padre; btn_Regresar_C.IsEnabled = false; } private void btn_Regresar_C_Click(object sender, RoutedEventArgs e) { this.Hide(); FRM_Principal_Cliente paginaanteriorP = new FRM_Principal_Cliente(); paginaanteriorP.ShowDialog(); this.Close(); } private void btn_Agregar_NC_Click(object sender, RoutedEventArgs e) { string identificacion = TXT_IDENTIFICACION_CLIENTE.Text; if (cmb_tipocliente.SelectedIndex == 0) { identificacion = identificacion + "001"; } if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(identificacion) == false || identificacion.Length < 13) { MessageBox.Show("Verifique identificación del cliente"); return; } else if (string.IsNullOrEmpty(TXT_Nombre_cliente.Text)) { MessageBox.Show("Verifique que el campo Nombre del cliente se encuentre lleno"); return; } else if (string.IsNullOrEmpty(TXT_IDENTIFICACION_CLIENTE.Text)) { MessageBox.Show("Verifique que el campo de identificación se encuentre lleno"); return; } else if (cmb_tipocliente.SelectedIndex == -1) { MessageBox.Show("Seleccione el tipo de cliente"); return; } else if (string.IsNullOrEmpty(TXT_APELLIDO_CLIENTE.Text)) { MessageBox.Show("Verifique que el campo apellido se encuentre lleno"); return; } else if (string.IsNullOrEmpty(TXT_DIRECCION.Text)) { MessageBox.Show("Verifique que el campo Dirección se encuentre lleno"); return; } else if (string.IsNullOrEmpty(TXT_TELEFONO.Text)) { MessageBox.Show("Verifique que el campo Teléfono se encuentre lleno"); return; } else if (string.IsNullOrEmpty(TXT_CORREO.Text)) { MessageBox.Show("Verifique que el campo de correo electrónico se encuentre lleno"); return; } else if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(identificacion) == true) { try { int id = objetoCN.InsertarCliente(cmb_tipocliente.SelectedIndex + 1, TXT_Nombre_cliente.Text, TXT_APELLIDO_CLIENTE.Text, TXT_IDENTIFICACION_CLIENTE.Text, TXT_TELEFONO.Text, TXT_DIRECCION.Text, TXT_CORREO.Text); MessageBox.Show("Guardado correctamente!"); if (padre != null) { padre.txtCedula.Text = TXT_IDENTIFICACION_CLIENTE.Text; padre.txtDireccion.Text = TXT_DIRECCION.Text; padre.txtNombre.Text = TXT_Nombre_cliente.Text + " " + TXT_APELLIDO_CLIENTE.Text; padre.txtCorreo.Text = TXT_CORREO.Text; padre.txtTelefono.Text = TXT_TELEFONO.Text; padre.idCliente = id.ToString(); padre.Show(); this.Close(); } limpiarForm(); } catch (Exception ex) { MessageBox.Show("Error Producido por: " + ex); } } } private void limpiarForm() { TXT_IDENTIFICACION_CLIENTE.Clear(); TXT_Nombre_cliente.Clear(); TXT_APELLIDO_CLIENTE.Clear(); cmb_tipocliente.Text = ""; TXT_DIRECCION.Clear(); TXT_TELEFONO.Clear(); TXT_CORREO.Clear(); } private void TXT_IDENTIFICACION_CLIENTE_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!char.IsDigit(e.Text, e.Text.Length - 1)) e.Handled = true; } private void TXT_TELEFONO_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!char.IsDigit(e.Text, e.Text.Length - 1)) e.Handled = true; } private void TXT_Nombre_cliente_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!System.Text.RegularExpressions.Regex.IsMatch(e.Text, "^[a-zA-Z]")) { e.Handled = true; } } private void TXT_APELLIDO_CLIENTE_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!System.Text.RegularExpressions.Regex.IsMatch(e.Text, "^[a-zA-Z]")) { e.Handled = true; } } private void cmb_tipocliente_SelectionChanged(object sender, SelectionChangedEventArgs e) { TXT_IDENTIFICACION_CLIENTE.Clear(); if (((ComboBox)sender).SelectedIndex == 0) { TXT_IDENTIFICACION_CLIENTE.MaxLength = 10; } else { TXT_IDENTIFICACION_CLIENTE.MaxLength = 13; } } } }
using Autofac; using EmberMemory.Components.Collector; using EmberMemoryReader.Abstract.Events; using System; using System.Diagnostics; namespace EmberMemoryReader.Components.Osu { public static class OsuDataCollectorBuilderExtenstion { public static CollectorBuilder UseOsuProcessEvent(this CollectorBuilder builder, OsuProcessMatchedEvent @event) { builder.Builder.RegisterInstance(@event).SingleInstance(); builder.Builder.Register((ctx) => { var process = Process.GetProcessById(ctx.Resolve<OsuProcessMatchedEvent>().ProcessId); if (process == null || process.HasExited) throw new EntryPointNotFoundException(); return process; }).As<Process>(); return builder; } } }
namespace Strategy { public interface IPaymentProcessor { void ProcessPayment(decimal amount); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; /* The ScoreRank class keeps track of the Player's score and rank. */ public class ScoreRank : MonoBehaviour { public static int value = 0;//$$$ value public Text scoreLabel; //UI Text showing score public Text rank; //UI Text showing rank /* The Awake function makes the ScoreRank to not be destroyed and it also sets the text. */ void Awake() { DontDestroyOnLoad(transform.gameObject); scoreLabel.text = "$$$: " + value; rank.text = "Rank: Newbie"; } /* The OnLevelWasLoaded function sets the scoreLabel and rank UI Text GameObjects active or inactive based on the level. */ void OnLevelWasLoaded(int level) { if (level>=2 && level<=8) { if (level>2) { increment (100); } scoreLabel.gameObject.SetActive(true); rank.gameObject.SetActive(true); } else { scoreLabel.gameObject.SetActive(false); rank.gameObject.SetActive(false); } } /* The Update function updates the current $$$ value and rank. */ void Update () { scoreLabel.text = "$$$: " + value; if (value < 100) { rank.text = "Rank: Newbie"; } else if (value < 500) { rank.text = "Rank: Novice Virus Hunter"; } else if (value < 1000) { rank.text = "Rank: Omega Class Virus Tracker"; } else if (value < 2000) { rank.text = "Rank: Delta Class Virus Tracker"; } else if (value < 3500) { rank.text = "Rank: Gamma Class Virus Tracker"; } else if (value < 5500) { rank.text = "Rank: Beta Class Virus Tracker"; } else if (value < 8000) { rank.text = "Rank: Alpha Class Virus Tracker"; } else if (value < 10000) { rank.text = "Rank: Gold Tier Virus Tracker"; } else { rank.text = "Rank: Platinum Tier Virus Tracker"; } } /* The increment function is called by other scripts and increases the $$$ value. */ public void increment (int x) { value += x; } }
using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Conditions; using Conditions.Guards; using Properties.Core.Interfaces; using Properties.Core.Objects; using Properties.Infrastructure.Data.Extensions; using Properties.Infrastructure.Data.Interfaces; namespace Properties.Infrastructure.Data { public class ContactDetailRepository : IContactDetailRepository { private readonly IPropertiesContext _propertiesContext; private readonly IMapToExisting<ContactDetail, ContactDetail> _contactDetailMapper; public ContactDetailRepository(IPropertiesContext propertiesContext, IMapToExisting<ContactDetail, ContactDetail> contactDetailMapper) { Check.If(propertiesContext).IsNotNull(); Check.If(contactDetailMapper).IsNotNull(); _propertiesContext = propertiesContext; _contactDetailMapper = contactDetailMapper; } public List<ContactDetail> GetContactDetailsReference(string landlordReference) { var landlord = _propertiesContext.Landlords.Active() .Include(x => x.AlternateContactDetails) .FirstOrDefault(x => x.LandlordReference == landlordReference); return landlord.IsNull() ? new List<ContactDetail>() : landlord.AlternateContactDetails; } public ContactDetail GetContactDetailForLandlordByReference(string landlordReference, string contactDetailReference) { var landlord = _propertiesContext.Landlords.Active() .Include(x => x.AlternateContactDetails) .FirstOrDefault(x => x.LandlordReference == landlordReference); return landlord.IsNull() ? null : landlord.AlternateContactDetails.FirstOrDefault(x => x.ContactDetailReference == contactDetailReference); } public bool CreatContactDetailForLandlord(string landlordReference, ContactDetail contactDetail) { var landlord = _propertiesContext.Landlords.Active() .Include(x => x.AlternateContactDetails) .FirstOrDefault(x => x.LandlordReference == landlordReference); if (landlord.IsNull()) return false; landlord.AlternateContactDetails.Add(contactDetail); return _propertiesContext.SaveChanges() > 0; } public bool UpdateContactDetailForLandlord(string landlordReference, string contactDetailReference, ContactDetail contactDetail) { var landlord = _propertiesContext.Landlords.Active() .Include(x => x.AlternateContactDetails) .FirstOrDefault(x => x.LandlordReference == landlordReference); var currentContactDetail = landlord?.AlternateContactDetails.FirstOrDefault(x => x.ContactDetailReference == contactDetailReference); if (currentContactDetail.IsNull()) return false; var isDirty = _contactDetailMapper.Map(contactDetail, currentContactDetail); return !isDirty || _propertiesContext.SaveChanges() > 0; } public bool DeleteContactDetailForLandlord(string landlordReference, string contactDetailReference) { var landlord = _propertiesContext.Landlords.Active() .Include(x => x.AlternateContactDetails) .FirstOrDefault(x => x.LandlordReference == landlordReference); if (landlord.IsNull()) return false; var currentContactDetail = landlord?.AlternateContactDetails.FirstOrDefault(x => x.ContactDetailReference == contactDetailReference); if (currentContactDetail.IsNull()) return false; currentContactDetail.SoftDelete(); return _propertiesContext.SaveChanges() > 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ByA; using Entidades; using Entidades; using DAL; using AutoMapper; using Entidades.Vistas; namespace BLL { public class mDIRECCIONES { Entities ctx; public mDIRECCIONES() { Mapper.CreateMap<vDIRECCIONES_EXTERNAS, DIRECCIONES_EXTERNAS>(); Mapper.CreateMap<DIRECCIONES_EXTERNAS, vDIRECCIONES_EXTERNAS>(); } public vDIRECCIONES_EXTERNAS Get(decimal ID) { using (ctx = new Entities()) { vDIRECCIONES_EXTERNAS r = new vDIRECCIONES_EXTERNAS(); DIRECCIONES_EXTERNAS o = ctx.DIRECCIONES_EXTERNAS.Where(t => t.ID == ID).FirstOrDefault(); Mapper.Map(o, r); return r; } } } }