text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using Events; public class Bar_Controller : MonoBehaviour { [SerializeField] private int barIdentifier; private bool canenterbar = false; private SceneController sceneController; private int[] collectablesIdentifiers; private GameObject[] activeCollectables; private bool dialogueactive; private void OnEnable() { EventController.AddListener<BeforeSceneUnloadEvent>(BeforeSceneUnloadEvent); EventController.AddListener<DialogueStatusEvent>(DialogueStatusEvent); } private void OnDisable() { EventController.RemoveListener<BeforeSceneUnloadEvent>(BeforeSceneUnloadEvent); EventController.RemoveListener<DialogueStatusEvent>(DialogueStatusEvent); } void Start() { sceneController = FindObjectOfType<SceneController>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.E) && canenterbar && !dialogueactive && PlayerOptions.InputEnabled) { //SceneManager.LoadScene("Battle", LoadSceneMode.Additive); //SceneManager.SetActiveScene(SceneManager.GetSceneByName("Battle")); //SaveMapState(); Player_Status.CurrentBar = barIdentifier; sceneController.FadeAndLoadScene("_Scene_Battle"); } } private void OnTriggerStay(Collider other) { if (other.tag == "Player") { canenterbar = true; } } private void OnTriggerExit(Collider other) { if (other.tag == "Player") { canenterbar = false; } } private void DialogueStatusEvent(DialogueStatusEvent status) { dialogueactive = status.dialogueactive; } private void SaveMapState() { //////Collectables //activeCollectables = GameObject.FindGameObjectsWithTag("Collectable"); //collectablesIdentifiers = new int[activeCollectables.Length]; //int i = 0; //foreach (GameObject activeCollectable in activeCollectables) //{ // collectablesIdentifiers[i] = activeCollectable.GetComponent<Collectable_Controller>().uniqueIdentifier; // i++; //} //Map_Status.CollectablesIdentifiers = collectablesIdentifiers; //////Player position //Map_Status.PlayerRotation = GameObject.FindGameObjectWithTag("Player").transform.rotation; //Map_Status.PlayerPosition = GameObject.FindGameObjectWithTag("Player").transform.position; //////Camera position //Map_Status.CameraRotation = GameObject.FindGameObjectWithTag("MainCamera").transform.rotation; //Map_Status.CameraPosition = GameObject.FindGameObjectWithTag("MainCamera").transform.position; //Map_Status.FirstTime = false; } private void BeforeSceneUnloadEvent(BeforeSceneUnloadEvent before) { //Player_Status.CurrentBar = barIdentifier; // Debug.Log("Bar Ident: " + barIdentifier); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using UI.Models; using UI.Entidades; namespace UI.Controllers { public class GestionBusInscripcionController : ApiController { [HttpPost] public Response<List<Evento>> EventosConBus() { Response<List<Evento>> obj = new Response<List<Evento>>(); GestionBusInscripcion eventos = new GestionBusInscripcion(); return obj = eventos.EventosConBus(); } [HttpPost] public Response<List<Participante>> ListarParticipantes([FromBody]decimal evento) { Response<List<Participante>> obj = new Response<List<Participante>>(); GestionBusInscripcion listaPar = new GestionBusInscripcion(); return obj = listaPar.ParticipantesPorEvento(evento); } [HttpPost] public Response<Participante> ParticipanteConTransporte([FromBody]Participante arg) { Response<Participante> obj = new Response<Participante>(); GestionBusInscripcion list = new GestionBusInscripcion(); return obj = list.ParticipanteConTransporte(arg); } [HttpPost] public Response<List<Bus>> BusesEvento([FromBody]decimal evento) { Response<List<Bus>> obj = new Response<List<Bus>>(); GestionBusInscripcion buses = new GestionBusInscripcion(); return obj = buses.BusesEvento(evento); } [HttpPost] public Response<List<Bus>> BusesDisponibles([FromBody] Participante arg) { Response<List<Bus>> obj = new Response<List<Bus>>(); GestionBusInscripcion listBus = new GestionBusInscripcion(); return obj = listBus.BusesDisponiblesAsignar(arg); } [HttpPost] public Response<List<BusInscripcion>> BusAsignado([FromBody] Participante arg) { Response<List<BusInscripcion>> obj = new Response<List<BusInscripcion>>(); GestionBusInscripcion bus = new GestionBusInscripcion(); return obj = bus.BusAsignado(arg); } [HttpPost] public Response<BusInscripcion> BusAsignadoDataUnico([FromBody] Participante arg) { Response<BusInscripcion> obj = new Response<BusInscripcion>(); GestionBusInscripcion busUnico = new GestionBusInscripcion(); return obj = busUnico.BusAsignadoDatoUnico(arg); } [HttpPost] public Response<BusInscripcion> AsignarBusParticipante([FromBody] BusInscripcion arg) { Response<BusInscripcion> obj = new Response<BusInscripcion>(); GestionBusInscripcion guardar = new GestionBusInscripcion(); return obj = guardar.AsignarBusParticipante(arg); } [HttpPost] public Response<List<Bus>> BusesDisponiblesModificar([FromBody] Participante arg) { Response<List<Bus>> obj = new Response<List<Bus>>(); GestionBusInscripcion listaBus = new GestionBusInscripcion(); return obj = listaBus.BusesDisponiblesModificar(arg); } [HttpPost] public Response<BusInscripcion> ModificarBusParticipante([FromBody] BusInscripcion arg) { Response<BusInscripcion> obj = new Response<BusInscripcion>(); GestionBusInscripcion actualizar = new GestionBusInscripcion(); return obj = actualizar.ModificarBus(arg); } } }
using System; using System.Collections.Generic; using System.Text; //klasa opisujaca wypozyczenia namespace Library { class Zdarzenie { private OpisStanu opisStanu; public Wykaz wykaz; private DateTime borrowTime; private DateTime returnTime; public OpisStanu OpisStanu { get => opisStanu; set => opisStanu = value; } public Wykaz Wykaz { get => wykaz; set => wykaz = value; } public DateTime BorrowTime { get => borrowTime; set => borrowTime = value; } public DateTime ReturnTime { get => returnTime; set => returnTime = value; } } }
using UnityEngine; using System.Collections; using System.IO; using System.Xml; public class Test3 : MonoBehaviour { // Use this for initialization void Start () { Load(); } void Load() { string filepath = Application.dataPath + "/StreamingAssets" + "/MyXML.xml"; if (File.Exists(filepath)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filepath); XmlNodeList nodeList = xmlDoc.SelectSingleNode("root").SelectSingleNode("scene").SelectNodes("fragment"); foreach (XmlElement gameobjects in nodeList) { string asset = "Prefab/" + gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText; Debug.Log(asset); Vector3 pos = Vector3.zero; Vector3 rot = Vector3.zero; Vector3 sca = Vector3.zero; string Tag = ""; int Layer = 0; foreach (XmlElement myTransform in gameobjects.SelectSingleNode("gameObject").SelectSingleNode("transform").ChildNodes) { #region 根据数据赋值参数 if (myTransform.Name == "position") { foreach (XmlAttribute position in myTransform.Attributes) { switch (position.Name) { case "x": pos.x = float.Parse(position.InnerText); break; case "y": pos.y = float.Parse(position.InnerText); break; case "z": pos.z = float.Parse(position.InnerText); break; } } } else if (myTransform.Name == "rotation") { foreach (XmlAttribute rotation in myTransform.Attributes) { switch (rotation.Name) { case "x": rot.x = float.Parse(rotation.InnerText); break; case "y": rot.y = float.Parse(rotation.InnerText); break; case "z": rot.z = float.Parse(rotation.InnerText); break; } } } else if (myTransform.Name == "scale") { foreach (XmlAttribute scale in myTransform.Attributes) { switch (scale.Name) { case "x": sca.x = float.Parse(scale.InnerText); break; case "y": sca.y = float.Parse(scale.InnerText); break; case "z": sca.z = float.Parse(scale.InnerText); break; } } } else if (myTransform.Name == "Tag") { Tag = myTransform.Attributes[0].InnerText; } else if (myTransform.Name == "Layer") { Layer = int.Parse(myTransform.Attributes[0].InnerText); } #endregion } Debug.Log(pos+" "+rot+" "+sca+" "+Tag+" "+Layer); //拿到 旋转 缩放 平移 以后克隆新游戏对象 //GameObject ob = (GameObject)Instantiate(Resources.Load(""), pos, Quaternion.Euler(rot)); //ob.transform.localScale = sca; //ob.tag = Tag; //ob.layer = Layer; } } } }
using Quark.Spells; using Quark.Targeting; using Quark.Utilities; using UnityEngine; namespace Quark.Contexts { /// <summary> /// This interface provides basic getters for CastContext compatible classes. /// </summary> public interface ICastContext : IContext { /// <summary> /// The Spell object being casted in this Cast Context. /// </summary> Spell Spell { get; } /// <summary> /// This property stores the current stage of this CastContext. /// </summary> CastStages Stage { get; } /// <summary> /// This property stores all of the Targets acquired by this CastContext. /// </summary> TargetCollection Targets { get; } /// <summary> /// Gets the cast done percentage, respective to the minimum casting time. /// </summary> int CastPercentage { get; } /// <summary> /// This property gets the time spent casting up to now. /// </summary> float CastTime { get; } /// <summary> /// This property stores the time this CastContext has transitioned to the Casting stage. /// </summary> float CastBeginTime { get; } /// <summary> /// This property stores the position this CastContext has transitioned to the Casting stage. /// </summary> Vector3 CastBeginPosition { get; } /// <summary> /// Interrupts this cast context. /// Can only cancel the casts in the Casting stage. /// </summary> void Interrupt(); /// <summary> /// Executes the clearing logic for this context. /// </summary> void Clear(); } /// <summary> /// CastContexts provide state for a Spell cast. /// </summary> public class CastContext : Context, ICastContext { /// <summary> /// Creates a new CastContext instance from a caster Character and a Spell to be casted. /// </summary> /// <param name="caster">The caster Character object.</param> /// <param name="spell">The Spell object to be casted.</param> public CastContext(Character caster, Spell spell) : base(caster.Context) { Spell = spell; Spell.SetContext(this); Identifier = Spell.Identifier + "@" + caster.Identifier; Initialize(); } public Spell Spell { get; private set; } public CastStages Stage { get; private set; } public TargetCollection Targets { get; private set; } public Vector3 CastBeginPosition { get; private set; } public float CastBeginTime { get; private set; } public float CastTime { get { return _lastCast - CastBeginTime; } } public int CastPercentage { get { if (Spell.MinCastDuration <= 0) return 100; return (int)(CastTime * 100 / Spell.MinCastDuration); } } /// <summary> /// This method executes the initialization logic of this CastContext and the Spell being casted. /// </summary> void Initialize() { Stage = CastStages.Initialization; if (!Source.CanCast(Spell)) { Messenger<ICastContext>.Broadcast("CasterBusy", this); return; } if (!Spell.CanInvoke()) { Messenger<ICastContext>.Broadcast("CannotCast", this); return; } Source.AddCast(this); Source.Context.AddChild(this); // Add this CastContext to the children of the Caster's Context. Spell.OnInvoke(); Targets = new TargetCollection(); Messenger<ICastContext>.Broadcast("Cast.Initialize", this); if (Spell.CastOrder == CastOrder.TargetFirst) BeginTargeting(); else PreCasting(); } /// <summary> /// Begin targeting logic /// </summary> void BeginTargeting() { Stage = CastStages.Targeting; TargetMacro macro = Spell.TargetMacro; macro.SetContext(this); macro.TargetingSuccess += delegate(TargetCollection targets) { Targets.AddRange(targets); Messenger<ICastContext>.Broadcast("Cast.TargetingSuccess", this); PostTargeting(); macro = null; }; macro.TargetingFailed += delegate(TargetingError error) { Stage = CastStages.TargetingFailed; Messenger<ICastContext, TargetingError>.Broadcast("Cast.TargetingFailed", this, error); macro = null; Clear(); }; Messenger<ICastContext>.Broadcast("Cast.BeginTargeting", this); macro.Run(); } void PostTargeting() { Spell.OnTargetingDone(); if (Spell.CastOrder == CastOrder.TargetFirst) PreCasting(); else BeginProjectiles(); } private ConditionCollection<ICastContext> _interruptConditions; private float _lastCast; void PreCasting() { Stage = CastStages.PreCasting; CastBeginTime = Time.timeSinceLevelLoad; CastBeginPosition = Source.transform.position; _lastCast = Time.timeSinceLevelLoad; if (Spell.IsInstant) { PostCasting(); return; } Messenger<ICastContext>.Broadcast("Cast.CastingBegin", this); Spell.OnCastingBegan(); _interruptConditions = Source.InterruptConditions.DeepCopy(); // Store the interrupt conditions on a member field... Messenger.AddListener("Update", Casting); } void Casting() { if (CheckInterrupt() || CastTime >= Spell.MaxCastDuration) { PostCasting(); return; } Messenger<ICastContext>.Broadcast("Cast.CastingTick", this); if (Time.timeSinceLevelLoad > _lastCast + Spell.CastingInterval) { Spell.OnCasting(); _lastCast = Time.timeSinceLevelLoad; } } bool CheckInterrupt() { _interruptConditions.SetContext(this); return _interruptConditions.Check() || Spell.CheckInterrupt(); } void PostCasting() { if (!Spell.IsInstant) Messenger.RemoveListener("Update", Casting); if (CastPercentage >= 100) { Messenger<ICastContext>.Broadcast("Cast.CastSuccess", this); // Cast is successful, run the cast success event. CastSuccess(); if (Spell.CastOrder == CastOrder.TargetFirst) BeginProjectiles(); else BeginTargeting(); } else { Messenger<ICastContext>.Broadcast("Cast.CastInterrupt", this); // Cast got interrupted somehow. Run the interruption event. Interrupt(); } Clear(); } void CastSuccess() { Stage = CastStages.CastSuccess; Spell.OnCastDone(); } public void Interrupt() { Stage = CastStages.CastFail; Spell.OnInterrupt(); } void BeginProjectiles() { if (Spell.IsProjectiled) Spell.CreateProjectiles(); else Spell.OnFinal(); Clear(); } public void Clear() { Source.ClearCast(this); _interruptConditions = null; } } /// <summary> /// This enumeration represents the state of a CastContext. /// </summary> public enum CastStages { /// <summary> /// The cast is invalid. /// </summary> Null, /// <summary> /// The cast is in initialization stage. /// </summary> Initialization, /// <summary> /// The cast is in targeting stage. /// </summary> Targeting, /// <summary> /// The cast has failed due to targeting. /// </summary> TargetingFailed, /// <summary> /// The cast is in the precasting stage. /// </summary> PreCasting, /// <summary> /// The cast is in the casting stage. /// </summary> Casting, /// <summary> /// The cast is in the interruption stage. /// </summary> CastFail, /// <summary> /// The cast has succeeded. /// </summary> CastSuccess } /// <summary> /// This enumeration represents the order of casting of a Spell. /// </summary> public enum CastOrder { /// <summary> /// In this ordering, casting will occur after targeting is done. /// </summary> TargetFirst, /// <summary> /// In this ordering, casting will occur right after initialization. /// </summary> CastFirst, } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GroupSelector : MonoBehaviour, InputListener { // to be set in editor public List<Doll> dolls; private Result<BattleUnit> awaitingResult; private int selectionIndex; private int dollFillIndex = 0; private bool awaitingConfirm; private bool canceledConfirm; public void Start() { //int pivot = (int)Mathf.Floor(((float)(dolls.Count - 1)) / 2.0f); //int offset = 0; //int direction = -1; //for (int i = pivot; i >= 0 && i < dolls.Count; i = pivot + offset * direction) { // dolls[i] = dollSlots // if (direction < 0) { // offset += 1; // } // direction *= -1; //} foreach (Doll doll in dolls) { doll.Populate(null); } } // call during initialization only public Doll AssignNextDoll(BattleUnit unit) { Doll doll = dolls[dollFillIndex]; doll.Populate(unit); dollFillIndex += 1; return doll; } public bool OnCommand(InputManager.Command command, InputManager.Event eventType) { if (eventType == InputManager.Event.Down) { if (awaitingConfirm) { if (command == InputManager.Command.Confirm) { Global.Instance().Audio.PlaySFX("confirm"); awaitingConfirm = false; } else if (command == InputManager.Command.Cancel) { canceledConfirm = true; Global.Instance().Audio.PlaySFX("cancel"); awaitingConfirm = false; } } else { switch (command) { case InputManager.Command.Cancel: awaitingResult.Cancel(); Global.Instance().Audio.PlaySFX("cancel"); break; case InputManager.Command.Confirm: awaitingResult.value = GetSelectedDoll().unit; Global.Instance().Audio.PlaySFX("confirm"); break; case InputManager.Command.Down: MoveSelection(1); break; case InputManager.Command.Up: MoveSelection(-1); break; } } } return true; } public IEnumerator SelectAnyOneRoutine(Result<BattleUnit> result, Intent intent) { StartSingle(result); while (!awaitingResult.finished) { yield return null; } yield return EndSingle(); } public IEnumerator SelectAnyExceptRoutine(Result<BattleUnit> result, Intent intent) { yield break; } public IEnumerator SelectAllRoutine(Result<List<BattleUnit>> result, Intent intent) { StartMulti(); while (awaitingConfirm) { yield return null; } EndMulti(result); } public IEnumerator SelectAllExceptRoutine(Result<List<BattleUnit>> result, Intent intent) { yield break; } public IEnumerator SelectSpecificallyRoutine(Result<BattleUnit> result, Intent intent) { StartSingle(null); GetSelectedDoll().GetComponent<Selectable>().selected = false; for (int i = selectionIndex; GetSelectedDoll().unit != intent.actor; i += 1) ; GetSelectedDoll().GetComponent<Selectable>().selected = true; awaitingConfirm = true; while (awaitingConfirm) { yield return null; } if (!canceledConfirm) { result.value = intent.actor; } else { result.Cancel(); } yield return EndSingle(); } private void StartSingle(Result<BattleUnit> result) { awaitingResult = result; selectionIndex = -1; MoveSelection(1); GetSelectedDoll().GetComponent<Selectable>().selected = true; Global.Instance().Input.PushListener(this); } private IEnumerator EndSingle() { awaitingResult = null; GetSelectedDoll().GetComponent<Selectable>().selected = false; Global.Instance().Input.RemoveListener(this); yield return StartCoroutine(GetSelectedDoll().unit.battle.controller.enemyHUD.disableRoutine()); } private void StartMulti() { canceledConfirm = false; awaitingConfirm = true; foreach (Doll doll in dolls) { doll.GetComponent<Selectable>().selected = true; } Global.Instance().Input.PushListener(this); } private void EndMulti(Result<List<BattleUnit>> result) { if (canceledConfirm) { result.Cancel(); } else { result.value = new List<BattleUnit>(); foreach (Doll doll in dolls) { doll.GetComponent<Selectable>().selected = false; result.value.Add(doll.unit); } } Global.Instance().Input.RemoveListener(this); } private Doll GetSelectedDoll() { if (selectionIndex == -1) return null; return dolls[selectionIndex]; } private void MoveSelection(int delta) { Doll oldSelected = GetSelectedDoll(); if (oldSelected != null) { oldSelected.GetComponent<Selectable>().selected = false; } int max = dolls.Count; do { selectionIndex += delta; if (selectionIndex < 0) { selectionIndex = max - 1; } else if (selectionIndex >= max) { selectionIndex = 0; } } while (GetSelectedDoll().unit.IsDead()); Doll newSelected = GetSelectedDoll(); newSelected.GetComponent<Selectable>().selected = true; if (newSelected.unit.align == Alignment.Enemy) { StartCoroutine(newSelected.unit.battle.controller.enemyHUD.enableRoutine(newSelected.unit)); } if (oldSelected != newSelected) { Global.Instance().Audio.PlaySFX("cursor"); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(IoTChallenge.Startup))] namespace IoTChallenge { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); app.MapSignalR(); } } }
namespace BuhtigIssueTracker.Utilities { using System; using System.Linq; using System.Security.Cryptography; using System.Text; public static class Extensions { public static string GetHashedPassword(this string password) { return string.Join( string.Empty, SHA1.Create() .ComputeHash( Encoding.Default.GetBytes(password)) .Select(x => x.ToString())); } public static string GetFormattedString(this string format, params object[] arguments) { return string.Format(format, arguments); } public static T GetStringValueAsEnumType<T>(this string value) { return (T)Enum.Parse(typeof(T), value, true); } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Threading; using log4net.Core; using NUnit.Framework; using RabbitMQ.Client; using Spring.Messaging.Amqp.Core; using Spring.Messaging.Amqp.Rabbit.Connection; using Spring.Messaging.Amqp.Rabbit.Core; using Spring.Messaging.Amqp.Rabbit.Test; namespace Spring.Messaging.Amqp.Rabbit.Admin { [TestFixture] public class RabbitBrokerAdminIntegrationTests { /// <summary> /// The connection factory. /// </summary> protected SingleConnectionFactory connectionFactory; /// <summary> /// The broker admin. /// </summary> private RabbitBrokerAdmin brokerAdmin; /// <summary> /// Sets up. /// </summary> /// <remarks></remarks> [SetUp] public void SetUp() { //if (environment.isActive()) //{ // Set up broker admin for non-root user this.brokerAdmin = BrokerTestUtils.GetRabbitBrokerAdmin(); //"rabbit@LOCALHOST", 5672); this.brokerAdmin.StartBrokerApplication(); //panic.setBrokerAdmin(brokerAdmin); // } } /// <summary> /// Tears down. /// </summary> /// <remarks></remarks> [TearDown] public void TearDown() { this.brokerAdmin.StopNode(); } /// <summary> /// Users the crud. /// </summary> /// <remarks></remarks> [Test] public void UserCrud() { List<String> users = this.brokerAdmin.ListUsers(); if (users.Contains("joe")) { this.brokerAdmin.DeleteUser("joe"); } Thread.Sleep(200); this.brokerAdmin.AddUser("joe", "trader"); Thread.Sleep(200); this.brokerAdmin.ChangeUserPassword("joe", "sales"); Thread.Sleep(200); users = this.brokerAdmin.ListUsers(); if (users.Contains("joe")) { Thread.Sleep(200); this.brokerAdmin.DeleteUser("joe"); } } /// <summary> /// Integrations the tests user crud with module adapter. /// </summary> /// <remarks></remarks> [Test] public void IntegrationTestsUserCrudWithModuleAdapter() { var adapter = new Dictionary<string, string>(); // Switch two functions with identical inputs! adapter.Add("rabbit_auth_backend_internal%add_user", "rabbit_auth_backend_internal%change_password"); adapter.Add("rabbit_auth_backend_internal%change_password", "rabbit_auth_backend_internal%add_user"); brokerAdmin.ModuleAdapter = adapter; var users = brokerAdmin.ListUsers(); if (users.Contains("joe")) { brokerAdmin.DeleteUser("joe"); } Thread.Sleep(200); brokerAdmin.ChangeUserPassword("joe", "sales"); Thread.Sleep(200); brokerAdmin.AddUser("joe", "trader"); Thread.Sleep(200); users = brokerAdmin.ListUsers(); if (users.Contains("joe")) { Thread.Sleep(200); brokerAdmin.DeleteUser("joe"); } } [Test] public void TestGetEmptyQueues() { var queues = this.brokerAdmin.GetQueues(); Assert.AreEqual(0, queues.Count); } [Test] public void TestGetQueues() { SingleConnectionFactory connectionFactory = new SingleConnectionFactory(); connectionFactory.Port = BrokerTestUtils.GetAdminPort(); Queue queue = new RabbitAdmin(connectionFactory).DeclareQueue(); Assert.AreEqual("/", connectionFactory.VirtualHost); List<QueueInfo> queues = brokerAdmin.GetQueues(); Assert.AreEqual(queue.Name, queues[0].Name); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class PlayerManager : MonoBehaviour { // Singleton // public static PlayerManager instance { get; protected set;} void Awake () { if (instance == null) { instance = this; } else if (instance != this) { Destroy (gameObject); } } // Singleton // public GameObject CharacterPrefab; public static Player myPlayer; public PlayerObject playerObject; public Dictionary<Player,GameObject> playerGameObjectMap; public static Vector2 entrancePoint = new Vector2(15,6); public static List<Player> playerList; // Use this for initialization public void Initialize () { EventsHandler.cb_keyPressed += MovePlayer; EventsHandler.cb_noKeyPressed += StopPlayer; EventsHandler.cb_playerMove += SavePlayerPosition; playerGameObjectMap = new Dictionary<Player, GameObject> (); } public void OnDestroy() { EventsHandler.cb_keyPressed -= MovePlayer; EventsHandler.cb_noKeyPressed -= StopPlayer; EventsHandler.cb_playerMove -= SavePlayerPosition; } // Update is called once per frame void Update () { /* if (Input.GetKeyDown (KeyCode.A)) { if (myPlayer.identificationName == "Daniel") { SwitchPlayer ("geM"); } else if (myPlayer.identificationName == "geM") { SwitchPlayer ("llehctiM"); } else { SwitchPlayer ("Daniel"); } } */ } // Create Players public void CreatePlayers() { // When first loading the game - create list and assign player if (playerList == null) { playerList = new List<Player> (); System.Object[] myPlayers = Resources.LoadAll ("Jsons/Players"); foreach (TextAsset txt in myPlayers) { Player player = JsonUtility.FromJson<Player> (txt.text); playerList.Add (player); } } } // -------- MOVE PLAYER --------- // public void MovePlayer(Direction myDirection) { if (GameManager.instance.inputState != InputState.Character) { return; } // if player is not in the room, return if (myPlayer.currentRoom != RoomManager.instance.myRoom.myName) { return; } // 4 tiles in one second float playerSpeed = 7f * Time.deltaTime; float offsetX = 0; float offsetY = 0; Vector3 newPos = new Vector3 (-1000, -1000, -1000); // check the new position according to the diretion switch (myDirection) { case Direction.left: newPos = new Vector3 ((myPlayer.myPos.x - playerSpeed), myPlayer.myPos.y, myPlayer.myPos.z); offsetX = -0.5f; //playerGameObjectMap [myPlayer].transform.localScale = new Vector3(1,1,1); break; case Direction.right: newPos = new Vector3 ((myPlayer.myPos.x + playerSpeed), myPlayer.myPos.y, myPlayer.myPos.z); offsetX = 0.5f; //playerGameObjectMap [myPlayer].transform.localScale = new Vector3(-1,1,1); break; case Direction.up: newPos = new Vector3 (myPlayer.myPos.x, (myPlayer.myPos.y + playerSpeed), myPlayer.myPos.z); offsetY = 0.5f; break; case Direction.down: newPos = new Vector3 (myPlayer.myPos.x, (myPlayer.myPos.y - playerSpeed), myPlayer.myPos.z); break; } // Debug.Log(RoomManager.instance.myRoom.myGrid == RoomManager.instance.myRoom.myMirrorRoom.shadowGrid); Tile tile = RoomManager.instance.myRoom.MyGrid.GetTileAt(new Vector3 (newPos.x + offsetX, newPos.y + offsetY, newPos.z)); if (tile == null) { StopPlayer (InputManager.instance.lastDirection); return; } if (tile != null) { // FURNITURE - if there a furniture at this tile if (tile.myFurniture != null) { if (tile.myFurniture.walkable == false && tile.myFurniture.hidden == false) { EventsHandler.Invoke_cb_playerHitPhysicalInteractable (tile.myFurniture); StopPlayer (InputManager.instance.lastDirection); //Debug.Log ("furniture " + tile.myFurniture.identificationName); return; } } // CHARACTER - if there a character at this tile if (tile.myCharacter != null) { if (tile.myCharacter.walkable == false && tile.myCharacter.hidden == false) { EventsHandler.Invoke_cb_playerHitPhysicalInteractable (tile.myCharacter); StopPlayer (InputManager.instance.lastDirection); return; } } // INACTIVE PLAYER - if there an inactive player at this tile if (tile.myInactivePlayer != null) { if (tile.myInactivePlayer.walkable == false) { EventsHandler.Invoke_cb_playerHitPhysicalInteractable (tile.myInactivePlayer); StopPlayer (InputManager.instance.lastDirection); return; } } // if there's no character at this tile if (ActionBoxManager.instance.currentPhysicalInteractable != null) { EventsHandler.Invoke_cb_playerLeavePhysicalInteractable (); } // TILE INTERACTION - If the next tile is interactable if (tile.myTileInteraction != null) { if (tile.myTileInteraction.walkable == false) { StopPlayer (InputManager.instance.lastDirection); } EventsHandler.Invoke_cb_playerHitTileInteraction (tile); if (tile.myTileInteraction.walkable == false) { return; } } if (GameActionManager.instance.currentTileInteraction != null) { EventsHandler.Invoke_cb_playerLeaveTileInteraction (); } // Walk to new pos myPlayer.ChangePosition (newPos); myPlayer.myDirection = myDirection; UpdatePlayerObjectPosition (myPlayer, myDirection); } } // When character has stopped public void StopPlayer(Direction lastDirection) { if (playerObject != null) { playerObject.StopCharacter (lastDirection); } } // Updating the character object position public void UpdatePlayerObjectPosition(Player myPlayer, Direction myDirection) { if (playerObject != null) { playerObject.MovePlayerObject (myPlayer, myDirection); } else { Debug.LogError ("player object is null"); } } // Updating the character sorting layer public void UpdatePlayerSortingLayer(Player myPlayer) { Tile currentTile = RoomManager.instance.myRoom.MyGrid.GetTileAt(myPlayer.myPos); playerGameObjectMap[myPlayer].GetComponent<SpriteRenderer> ().sortingOrder = (int) ((-myPlayer.myPos.y * 10f) + 6f); } // --- SWITCH PLAYER --- // public void SwitchPlayer(string newPlayer) { if (myPlayer.identificationName == newPlayer) { Debug.LogError ("switched to the same player"); return; } Player player = GetPlayerByName (newPlayer); // ---- switcharoo ---- // myPlayer.isActive = false; // Park Player ParkPlayerInTiles (myPlayer, myPlayer.myPos); // switch myPlayer = player; // new player is active myPlayer.isActive = true; GameManager.userData.currentActivePlayer = myPlayer.identificationName; // check if player is already in the room if (myPlayer.currentRoom == RoomManager.instance.myRoom.myName) { // remove new player from tiles RemovePlayerFromTiles (myPlayer); // if new player is in room if (playerGameObjectMap [myPlayer].GetComponent<PlayerObject> () == null) { playerGameObjectMap [myPlayer].AddComponent<PlayerObject> (); } playerObject = playerGameObjectMap [myPlayer].GetComponent<PlayerObject> (); } else { InteractionManager.instance.MoveToRoom (myPlayer.currentRoom, new Vector2 (myPlayer.myPos.x, myPlayer.myPos.y)); } EventsHandler.Invoke_cb_playerSwitched (player); return; } // Get player by name public Player GetPlayerByName(string name) { foreach (Player player in playerList) { if (player.identificationName == name) { return player; } } return null; } // Save player position to player data when player has moved public void SavePlayerPosition(Player player) { GameManager.userData.GetPlayerDataByPlayerName (player.identificationName).currentPos = player.myPos; GameManager.instance.SaveData (); } public void ParkPlayerInTiles(Player player, Vector3 currentPos) { Room myRoom = RoomManager.instance.myRoom; //Debug.Log ("currentPos" + currentPos); player.x = Mathf.FloorToInt(currentPos.x); player.y = Mathf.FloorToInt(currentPos.y); List<Tile> PlayerTiles = myRoom.GetMyTiles(myRoom.myGrid,player.mySize, player.x, player.y); PlayerTiles.ForEach (tile => tile.PlaceInactivePlayerInTile (player)); if (myRoom.roomState == RoomState.Mirror) { List<Tile> PlayerTiles_shadow = myRoom.GetMyTiles(myRoom.myMirrorRoom.shadowGrid,player.mySize, player.x, player.y); PlayerTiles_shadow.ForEach (tile => tile.PlaceInactivePlayerInTile (player)); } EventsHandler.Invoke_cb_tileLayoutChanged (); } public void RemovePlayerFromTiles(Player player) { Room myRoom = RoomManager.instance.myRoom; foreach (Tile tile in myRoom.myGrid.gridArray) { if(tile.myInactivePlayer == player) { tile.myInactivePlayer = null; } } if (myRoom.roomState == RoomState.Mirror) { foreach (Tile tile_shadow in myRoom.myMirrorRoom.shadowGrid.gridArray) { if(tile_shadow.myInactivePlayer == player) { tile_shadow.myInactivePlayer = null; } } } EventsHandler.Invoke_cb_tileLayoutChanged (); } public void PlayerEntersRoom(string playerName, Vector2 position) { Player player = GetPlayerByName (playerName); player.x = (int)position.x; player.y = (int)position.y; player.myPos = new Vector3 (position.x, position.y, player.myPos.z); // change current room of player player.currentRoom = RoomManager.instance.myRoom.myName; RoomManager.instance.nameSpeakerMap.Add (playerName, player); // FIXME: why is this here? GameManager.userData.GetPlayerDataByPlayerName (playerName).currentRoom = player.currentRoom; // create game object EventsHandler.Invoke_cb_playerChanged (player); // park in tiles if (player.isActive == false) { ParkPlayerInTiles (player, player.myPos); } } public void PlayerExitsRoom(string playerName, string nextRoom) { Player player = GetPlayerByName (playerName); // change current room of player player.currentRoom = nextRoom; GameManager.userData.GetPlayerDataByPlayerName (playerName).currentRoom = player.currentRoom; // destroy game object GameObject playerObj = playerGameObjectMap [player]; Destroy (playerObj); // remove from maps playerGameObjectMap.Remove (player); PI_Handler.instance.name_PI_map.Remove (player.identificationName); PI_Handler.instance.PI_gameObjectMap.Remove (player); // remove from tiles RemovePlayerFromTiles (player); } }
using Proyecto.ClassAux; using Proyecto.Database; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; using System.Web.Mvc; namespace Proyecto.Controllers { [Authorize] public class ReporteController : Controller { private DBEntities db; public ReporteController() { db = new DBEntities(); } [HttpGet] public ActionResult Reportes(int alert = 0) { ViewBag.alert = alert; return View(new ObjReporte(db)); } [HttpPost] public ActionResult EnviarCorreo(string correo) { ObjReporte obj = new ObjReporte(db); if (Send(correo, obj.GetBody())) { ViewBag.alert = 1; return RedirectToAction("Reportes", "Reporte", new { alert = 1}); } ViewBag.alert = 2; return View(obj); } private bool isOn() { try { using (var client = new WebClient()) using (client.OpenRead("http://clients3.google.com/generate_204")) { return true; } } catch (Exception) { return false; } } public bool Send(string email, string body) { if (isOn()) { MailMessage mail = new MailMessage(); SmtpClient client = new SmtpClient(); client.Port = 587; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new System.Net.NetworkCredential("stadisticBot", "bot123456"); client.EnableSsl = true; client.Host = "smtp.gmail.com"; mail.From = new MailAddress("to@example.com"); mail.To.Add(email); mail.Subject = ObjReporte.SUBJECT; mail.Body = body; mail.IsBodyHtml = true; client.Send(mail); return true; } else { return false; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task_5 { class Program { const string path = @"..\..\..\task5.txt"; public static Random rnd = new Random(); public static void CreateFile() { using (StreamWriter str = new StreamWriter(path)) { for (int i = 0; i < 100; i++) { string data = ""; int n = rnd.Next(3, 11); for (int j = 0; j < n; j++) { data += (char)rnd.Next('A', 'Z' + 1); } str.WriteLine(data); } } } static void Main(string[] args) { CreateFile(); using (var str = File.Open(path, FileMode.Open)) { List<byte> list = new List<byte>(); int u; while ((u = str.ReadByte()) != -1) list.Add((byte)u); var arr = list.Distinct().ToArray(); int[] countarr = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) countarr[i] = list.Count((x) => x == arr[i]); Array.Sort(countarr, arr); for(int i = arr.Length - 1; arr.Length - i < 11; i--) Console.WriteLine($"byte - {arr[i]}" + $" count - {countarr[i]}"); } } } }
using System; using System.Collections.Generic; using HelloWorldCore.com.learning.manager; using HelloWorldCore.com.learning.model; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace HelloWorldTests{ [TestClass] public class UnitTest1{ private PersonFactory factory = null; [TestInitialize] public void Init() { factory = new PersonFactory(); factory.UpsertPerson(new Person { Id = 1, FirstName = "James", LastName = "White" }); factory.UpsertPerson(new Person { Id = 2, FirstName = "Malcolm", LastName = "Turnbull" }); factory.UpsertPerson(new Person { Id = 3, FirstName = "Rebecca", LastName = "Black" }); factory.UpsertPerson(new Person { Id = 4, FirstName = "Jessica", LastName = "Brown" }); } [TestCleanup] public void CleanUp() { } [TestMethod] public void GetAllReturnSomethingTest(){ var everybody = factory.GetAll(); Assert.IsNotNull(everybody); Assert.IsTrue(everybody.Count > 0); //CollectionAssert } [TestMethod] public void GetByIdTest() { var person = factory.GetPersonById(1); Assert.IsNotNull(person); Assert.IsTrue(person.FirstName.Equals("James")); } [TestMethod] public void UpsertTest(){ var all = factory.GetAll(); Assert.IsTrue(all.Count == 4); var person = factory.GetPersonById(1); Assert.IsNotNull(person); Assert.IsTrue(person.FirstName.Equals("James")); var updatedPerson = new Person { Id = 1, FirstName = "Tracy", LastName = "Yap" }; factory.UpsertPerson(updatedPerson); var afterUpdatedPerson = factory.GetPersonById(1); Assert.IsNotNull(afterUpdatedPerson); Assert.IsTrue(afterUpdatedPerson.FirstName.Equals("Tracy"), "FirstName does not match " + person.FirstName); var afterUpdatedAll = factory.GetAll(); Assert.IsTrue(afterUpdatedAll.Count == 4); } [TestMethod] public void InsertNewPersonTest() { var abc = new List<Person> { new Person{ Id = 6, FirstName = "Adam", LastName = "Austin" }, new Person{ Id = 7, FirstName = "Joyce", LastName = "Koh" } }; abc.ForEach(x => factory.UpsertPerson(x)); var all = factory.GetAll(); Assert.IsTrue(all.Count == 6); CollectionAssert.AllItemsAreUnique(all); } } }
using AppointmentManagement.Business.Abstract; using AppointmentManagement.DataAccess.UnitOfWork; using AppointmentManagement.Entities.Concrete; using System; using System.Collections.Generic; using System.Text; namespace AppointmentManagement.Business.Concrete { public class EfPostedServiceService : IPostedServiceService { private readonly IUnitOfWork _unitOfWork; public EfPostedServiceService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public IEnumerable<PostedType> GetPostedTypes() { return _unitOfWork.PostedType.GetPostedTypes(); } } }
using iSukces.Code.Interfaces; namespace iSukces.Code.Irony { public sealed class DirectCode : ICsExpression { public DirectCode(string code) => Code = code; public string GetCode(ITypeNameResolver resolver) => Code; public string Code { get; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ShootableTarget : MonoBehaviour { public int Health = 3; public void Damage(int DMG_Amount) { Health -= DMG_Amount; if (Health <= 0) { Destroy(this.gameObject); gameObject.SetActive(false); } } }
namespace WinAppDriver.Handlers { using System.Collections.Generic; using WinAppDriver.UI; [Route("DELETE", "/session/:sessionId/window")] internal class CloseWindowHandler : IHandler { private IWindowUtils windowsUtils; public CloseWindowHandler(IWindowUtils windowsUtils) { this.windowsUtils = windowsUtils; } public object Handle(Dictionary<string, string> urlParams, string body, ref ISession session) { this.windowsUtils.GetCurrentWindow().Close(); return null; } } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Editor.Core; using gView.Framework.FDB; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.Symbology; using gView.Framework.system; using gView.Framework.UI; using gView.GraphicsEngine; using gView.Plugins.Editor.Dialogs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace gView.Plugins.Editor { [gView.Framework.system.RegisterPlugIn(Globals.ModuleGuidString, PluginUsage.Desktop)] public class Module : IMapApplicationModule, IModule, IPersistable { public enum EditTask { None = 0, CreateNewFeature = 1, ModifyFeature = 2 } public delegate void OnChangeSelectedFeatureEventHandler(Module sender, IFeature feature); public event OnChangeSelectedFeatureEventHandler OnChangeSelectedFeature = null; public delegate void OnChangeEditTaskEventHandler(Module sender, EditTask task); public event OnChangeEditTaskEventHandler OnChangeEditTask = null; public delegate void OnCreateStandardFeatureEventHandler(Module sender, IFeature feature); public event OnCreateStandardFeatureEventHandler OnCreateStandardFeature = null; private IMapDocument _doc = null; private string _lastMsg = String.Empty; private IFeatureClass _fc = null; private IFeature _feature = null; private IGraphicsContainer _sketchContainer, _moverContainer; private EditTask _task = EditTask.CreateNewFeature; private FormAttributeEditor _attributEditor; private List<IEditLayer> _editLayers = new List<IEditLayer>(); private IEditLayer _selectedEditLayer = null; public Module() { _sketchContainer = new gView.Framework.Carto.GraphicsContainer(); _moverContainer = new gView.Framework.Carto.GraphicsContainer(); _moverContainer.Elements.Add(new MoverGraphics(this)); _attributEditor = new FormAttributeEditor(this); } public EditTask ActiveEditTask { get { return _task; } internal set { if (value != _task) { _task = value; if (OnChangeEditTask != null) { OnChangeEditTask(this, _task); } this.Feature = null; } } } public IDockableWindow AttributeEditorWindow { get { return _attributEditor; } } #region IMapApplicationModule Member public void OnCreate(object hook) { if (hook is IMapDocument) { if (_doc != null) { if (_doc is IMapDocumentEvents) { ((IMapDocumentEvents)_doc).LayerAdded -= new LayerAddedEvent(_doc_LayerAdded); ((IMapDocumentEvents)_doc).LayerRemoved -= new LayerRemovedEvent(_doc_LayerRemoved); ((IMapDocumentEvents)_doc).MapAdded -= new MapAddedEvent(_doc_MapAdded); ((IMapDocumentEvents)_doc).MapDeleted -= new MapDeletedEvent(_doc_MapDeleted); } if (_doc.Application is IMapApplication) { ((IMapApplication)_doc.Application).AfterLoadMapDocument -= new AfterLoadMapDocumentEvent(Module_AfterLoadMapDocument); } } _doc = (IMapDocument)hook; ((IMapDocumentEvents)_doc).LayerAdded += new LayerAddedEvent(_doc_LayerAdded); ((IMapDocumentEvents)_doc).LayerRemoved += new LayerRemovedEvent(_doc_LayerRemoved); ((IMapDocumentEvents)_doc).MapAdded += new MapAddedEvent(_doc_MapAdded); ((IMapDocumentEvents)_doc).MapDeleted += new MapDeletedEvent(_doc_MapDeleted); if (_doc.Application is IMapApplication) { ((IMapApplication)_doc.Application).AfterLoadMapDocument += new AfterLoadMapDocumentEvent(Module_AfterLoadMapDocument); } } } #endregion #region Fire Events public bool PerformBeginEditFeature(IFeatureClass fc, IFeature feature) { EditorEventArgument args = new EditorEventArgument(fc, feature); if (OnBeginEditFeature != null) { OnBeginEditFeature(this, args); } if (args.Cancel) { _lastMsg = args.Message; return false; } return true; } public bool PerformCreateFeature(IFeatureClass fc, IFeature feature) { EditorEventArgument args = new EditorEventArgument(fc, feature); if (OnCreateFeature != null) { OnCreateFeature(this, args); } if (args.Cancel) { _lastMsg = args.Message; return false; } return true; } async public Task<bool> PerformInsertFeature(IFeatureClass fc, IFeature feature) { if (fc == null || feature == null || fc.Dataset == null || !(fc.Dataset.Database is IFeatureUpdater)) { return false; } if (_attributEditor != null && !_attributEditor.CommitValues()) { MessageBox.Show(_attributEditor.LastErrorMessage, "ERROR: Commit Values..."); return false; } EditorEventArgument args = new EditorEventArgument(fc, feature); if (OnInsertFeature != null) { OnInsertFeature(this, args); } if (args.Cancel) { _lastMsg = args.Message; return false; } IGeometry shape = feature.Shape; if (_doc != null && _doc.FocusMap != null && _doc.FocusMap.Display != null && _doc.FocusMap.Display.SpatialReference != null && !_doc.FocusMap.Display.SpatialReference.Equals(_fc.SpatialReference)) { feature.Shape = GeometricTransformerFactory.Transform2D( feature.Shape, _doc.FocusMap.Display.SpatialReference, _fc.SpatialReference); } bool ret = await ((IFeatureUpdater)fc.Dataset.Database).Insert(fc, feature); feature.Shape = shape; if (!ret) { _lastMsg = fc.Dataset.Database.LastErrorMessage; } return ret; } async public Task<bool> PerformUpdateFeature(IFeatureClass fc, IFeature feature) { if (fc == null || feature == null || fc.Dataset == null || !(fc.Dataset.Database is IFeatureUpdater)) { return false; } if (_attributEditor != null && !_attributEditor.CommitValues()) { MessageBox.Show(_attributEditor.LastErrorMessage, "ERROR: Commit Values..."); return false; } EditorEventArgument args = new EditorEventArgument(fc, feature); if (OnUpdateFeature != null) { OnUpdateFeature(this, args); } if (args.Cancel) { _lastMsg = args.Message; return false; } IGeometry shape = feature.Shape; if (_doc != null && _doc.FocusMap != null && _doc.FocusMap.Display != null && _doc.FocusMap.Display.SpatialReference != null && !_doc.FocusMap.Display.SpatialReference.Equals(_fc.SpatialReference)) { feature.Shape = GeometricTransformerFactory.Transform2D( feature.Shape, _doc.FocusMap.Display.SpatialReference, _fc.SpatialReference); } bool ret = await ((IFeatureUpdater)fc.Dataset.Database).Update(fc, feature); feature.Shape = shape; if (!ret) { _lastMsg = fc.Dataset.Database.LastErrorMessage; } return ret; } async public Task<bool> PerformDeleteFeature(IFeatureClass fc, IFeature feature) { if (fc == null || feature == null || fc.Dataset == null || !(fc.Dataset.Database is IFeatureUpdater)) { return false; } EditorEventArgument args = new EditorEventArgument(fc, feature); if (OnDeleteFeature != null) { OnDeleteFeature(this, args); } if (args.Cancel) { _lastMsg = args.Message; return false; } bool ret = await ((IFeatureUpdater)fc.Dataset.Database).Delete(fc, feature.OID); if (!ret) { _lastMsg = fc.Dataset.Database.LastErrorMessage; } return ret; } #endregion #region IModuleEvents Member public event OnBeginEditFeatureEventHandler OnBeginEditFeature = null; public event OnCreateFeatureEventHandler OnCreateFeature = null; public event OnInsertFeatureEventHandler OnInsertFeature = null; public event OnUpdateFeatureEventHandler OnUpdateFeature = null; public event OnDeleteFeatureEventHandler OnDeleteFeature = null; public event OnEditLayerCollectionChangedEventHandler OnEditLayerCollectionChanged = null; #endregion #region Properties internal IFeatureClass FeatureClass { get { return _fc; } } internal IFeature Feature { get { return _feature; } set { _feature = value; if (_feature == null || _feature.Shape == null) { Sketch = null; } else { Sketch = new EditSketch(_feature.Shape); } if (OnChangeSelectedFeature != null) { OnChangeSelectedFeature(this, _feature); } } } internal string LastMessage { get { return _lastMsg; } } //private void SetFeatureClassAndFeature(IFeatureClass fc, IFeature feature) //{ // if (_fc == fc && _feature == feature) return; // _fc = fc; // _feature = feature; // if (_feature == null || feature.Shape == null) // Sketch = null; // else // Sketch = new EditSketch(feature.Shape); // if (OnChangeSelectedFeature != null) // OnChangeSelectedFeature(this, fc, feature); //} internal void CreateStandardFeature() { if (_fc == null) { return; } Feature feature = new Feature(); GeometryType gType = _fc.GeometryType; if (gType == GeometryType.Unknown) { FormChooseGeometry dlg = new FormChooseGeometry(); if (dlg.ShowDialog() != DialogResult.OK) { this.Sketch = null; return; } gType = dlg.GeometryType; } switch (gType) { case GeometryType.Point: feature.Shape = new gView.Framework.Geometry.Point(); break; case GeometryType.Multipoint: feature.Shape = new MultiPoint(); break; case GeometryType.Polyline: feature.Shape = new Polyline(); break; case GeometryType.Polygon: feature.Shape = new Polygon(); break; default: return; } _feature = feature; if (OnCreateStandardFeature != null) { OnCreateStandardFeature(this, _feature); } Sketch = new EditSketch(_feature.Shape); } internal IMapDocument MapDocument { get { return _doc; } } internal List<IEditLayer> EditLayers { get { return ListOperations<IEditLayer>.Clone(_editLayers); } } internal IEditLayer SelectedEditLayer { get { return _selectedEditLayer; } set { if (!_editLayers.Contains(value)) { return; } _selectedEditLayer = value; if (_selectedEditLayer == null || _selectedEditLayer.FeatureLayer == null) { _fc = null; } else { _fc = _selectedEditLayer.FeatureLayer.FeatureClass; } this.Feature = null; } } internal void FireOnEditLayerCollectionChanged() { if (OnEditLayerCollectionChanged != null) { OnEditLayerCollectionChanged(this); } } #endregion #region Sketch Properties internal EditSketch Sketch { get { if (_sketchContainer.Elements.Count == 1) { return _sketchContainer.Elements[0] as EditSketch; } return null; } set { if (_doc == null || _doc.FocusMap == null || _doc.FocusMap.Display == null || _doc.FocusMap.Display.GraphicsContainer == null) { return; } foreach (IGraphicElement grElement in _doc.FocusMap.Display.GraphicsContainer.SelectedElements.Clone()) { if (grElement is EditSketch) { _doc.FocusMap.Display.GraphicsContainer.SelectedElements.Remove(grElement); } } foreach (IGraphicElement grElement in _doc.FocusMap.Display.GraphicsContainer.Elements.Clone()) { if (grElement is EditSketch) { _doc.FocusMap.Display.GraphicsContainer.Elements.Remove(grElement); } } EditSketch sketch = null; if (_sketchContainer.Elements.Count == 1) { sketch = _sketchContainer.Elements[0] as EditSketch; } // hat sich sketch nicht verändert... if (value != null && value.Equals(sketch)) { return; } if (value == null && sketch == null) { return; } _sketchContainer.Elements.Clear(); if (value != null) { _sketchContainer.Elements.Add(value); _doc.FocusMap.Display.GraphicsContainer.Elements.Add(value); _doc.FocusMap.Display.GraphicsContainer.SelectedElements.Add(value); } // neu zeichnen, wenn nicht gerade Afterloadmap läuft // und Sketch sich geändert hat; if (_doc.Application is IMapApplication && !_afterLoadMapDocument) { ((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics); } } } internal void RedrawhSketch() { if (_doc != null && _doc.FocusMap != null && _doc.FocusMap.Display != null) { _doc.FocusMap.Display.DrawOverlay(_sketchContainer, true); } } internal IPoint Mover { set { if (_doc != null && _doc.FocusMap != null && _doc.FocusMap.Display != null) { ((MoverGraphics)_moverContainer.Elements[0]).Mover = value; if (((MoverGraphics)_moverContainer.Elements[0]).IsValid) { _doc.FocusMap.Display.DrawOverlay(_moverContainer, true); } } } } #endregion #region HelperClasses private class MoverGraphics : IGraphicElement { private SimpleLineSymbol _symbol; private Module _module; private IPoint _mover = null; public MoverGraphics(Module module) { _module = module; _symbol = new SimpleLineSymbol(); _symbol.Color = ArgbColor.Gray; } public IPoint Mover { get { return _mover; } set { _mover = value; } } #region IGraphicElement Member public void Draw(IDisplay display) { if (_mover == null || _module == null || _module.Sketch == null) { return; } switch (_module.Sketch.GeometryType) { case GeometryType.Polyline: IPointCollection pColl1 = _module.Sketch.Part; if (pColl1 == null || pColl1.PointCount == 0) { return; } IPolyline pLine1 = new Polyline(); IPath path1 = new Path(); pLine1.AddPath(path1); path1.AddPoint(pColl1[pColl1.PointCount - 1]); path1.AddPoint(_mover); display.Draw(_symbol, pLine1); break; case GeometryType.Polygon: IPointCollection pColl2 = _module.Sketch.Part; if (pColl2 == null || pColl2.PointCount < 2) { return; } IPolyline pLine2 = new Polyline(); IPath path2 = new Path(); pLine2.AddPath(path2); path2.AddPoint(pColl2[pColl2.PointCount - 1]); path2.AddPoint(_mover); path2.AddPoint(pColl2[0]); display.Draw(_symbol, pLine2); break; } } #endregion public bool IsValid { get { if (_mover == null || _module == null || _module.Sketch == null) { return false; } switch (_module.Sketch.GeometryType) { case GeometryType.Point: return false; case GeometryType.Polyline: IPointCollection pColl1 = _module.Sketch.Part; if (pColl1 == null || pColl1.PointCount == 0) { return false; } break; case GeometryType.Polygon: IPointCollection pColl2 = _module.Sketch.Part; if (pColl2 == null || pColl2.PointCount < 2) { return false; } break; } return true; } } } private class MapEditLayerPersist : IPersistable { private Module _module; private IMap _map; public MapEditLayerPersist(Module module, IMap map) { _module = module; _map = map; } public Module Module { get { return _module; } } public IMap Map { get { return _map; } } #region IPersistable Member public void Load(IPersistStream stream) { if (stream == null || _module == null || _module.MapDocument == null) { return; } int index = (int)stream.Load("index", -1); if (index == -1 || index >= _module.MapDocument.Maps.Count()) { return; } string name = (string)stream.Load("name", string.Empty); var mapsList = _module.MapDocument.Maps.ToList(); if (mapsList[index] == null || mapsList[index].Name != name) { return; } _map = mapsList[index]; EditLayer eLayer; while ((eLayer = (EditLayer)stream.Load("EditLayer", null, new EditLayer())) != null) { if (eLayer.SetLayer(_map)) { _module.AddEditLayer(eLayer); } } } public void Save(IPersistStream stream) { if (stream == null || _module == null || _module.MapDocument == null || _map == null) { return; } int index = _module.MapDocument.Maps.ToList().IndexOf(_map); if (index == -1) { return; } stream.Save("index", index); stream.Save("name", _map.Name); foreach (IEditLayer editLayer in _module.EditLayers) { if (editLayer == null) { continue; } stream.Save("EditLayer", editLayer); } } #endregion } #endregion #region Helper static internal void SetValueOrAppendFieldValueIfNotExist(IFeature feature, string fieldName, object val) { if (feature == null || feature.Fields == null) { return; } foreach (IFieldValue fv in feature.Fields) { if (fv == null) { continue; } if (fv.Name == fieldName) { fv.Value = val; return; } } if (val != null && String.IsNullOrEmpty(val.ToString())) { // wenn nix im Attributeditor steht, soll objekt auch // nicht zwanghaft angelegt werden. // Sonst gibt oft Probleme beim neuen Anlegen von // Features (Datenbanktypen nicht verträglich...) return; } feature.Fields.Add(new FieldValue(fieldName, val)); } internal IFeatureLayer GetFeatureClassLayer(IFeatureClass fc) { if (_doc == null || _doc.FocusMap == null) { return null; } foreach (IDatasetElement element in _doc.FocusMap.MapElements) { if (element is IFeatureLayer && element.Class == fc) { return element as IFeatureLayer; } } return null; } private IEditLayer EditLayerByFeatureLayer(IFeatureLayer layer) { if (_editLayers == null) { return null; } foreach (IEditLayer editLayer in _editLayers) { if (editLayer != null && editLayer.FeatureLayer == layer) { return editLayer; } } return null; } #endregion #region IPersistable Member public void Load(IPersistStream stream) { _editLayers.Clear(); if (_doc == null || stream == null) { return; } MapEditLayerPersist mapEditLayers; while ((mapEditLayers = (MapEditLayerPersist)stream.Load("MapEditLayers", null, new MapEditLayerPersist(this, null))) != null) { } } public void Save(IPersistStream stream) { if (_doc == null || _doc.Maps == null) { return; } foreach (IMap map in _doc.Maps) { if (map == null) { continue; } stream.Save("MapEditLayers", new MapEditLayerPersist(this, map)); } } #endregion #region Document Events void _doc_MapDeleted(IMap map) { if (map == null) { return; } bool found = false; foreach (IEditLayer editLayer in ListOperations<IEditLayer>.Clone(_editLayers)) { if (editLayer.FeatureLayer == null) { _editLayers.Remove(editLayer); found = true; } if (map[editLayer.FeatureLayer] != null) { _editLayers.Remove(editLayer); found = true; } } if (found && OnEditLayerCollectionChanged != null) { OnEditLayerCollectionChanged(this); } } void _doc_MapAdded(IMap map) { } void _doc_LayerRemoved(IMap sender, ILayer layer) { if (sender == null || layer == null || _doc == null) { return; } bool found = false; foreach (IEditLayer editLayer in ListOperations<IEditLayer>.Clone(_editLayers)) { if (editLayer.FeatureLayer == null) { _editLayers.Remove(editLayer); found = true; } else if (editLayer.FeatureLayer == layer) { _editLayers.Remove(editLayer); found = true; } } if (found && OnEditLayerCollectionChanged != null) { OnEditLayerCollectionChanged(this); } } void _doc_LayerAdded(IMap sender, ILayer layer) { if (!(layer is IFeatureLayer)) { return; } IFeatureLayer fl = (IFeatureLayer)layer; if (fl.Class == null || fl.Class.Dataset == null || !(fl.Class.Dataset.Database is IEditableDatabase)) { return; } EditLayer editLayer = new EditLayer(fl, EditStatements.NONE); _editLayers.Add(editLayer); if (OnEditLayerCollectionChanged != null) { OnEditLayerCollectionChanged(this); } } private bool _afterLoadMapDocument = false; void Module_AfterLoadMapDocument(IMapDocument mapDocument) { if (_doc != mapDocument) { OnCreate(mapDocument); } if (_doc == null) { return; } _afterLoadMapDocument = true; foreach (IMap map in _doc.Maps) { foreach (IDatasetElement element in map.MapElements) { if (!(element is IFeatureLayer)) { continue; } if (EditLayerByFeatureLayer(element as IFeatureLayer) == null) { _editLayers.Add(new EditLayer(element as IFeatureLayer, EditStatements.NONE)); } } } if (OnEditLayerCollectionChanged != null) { OnEditLayerCollectionChanged(this); } _afterLoadMapDocument = false; } #endregion private void AddEditLayer(IEditLayer eLayer) { if (eLayer != null) { _editLayers.Add(eLayer); } } } class EditLayer : IEditLayer, IPersistable { private IFeatureLayer _layer; private EditStatements _statements; internal EditLayer() : this(null, EditStatements.NONE) { persistLayerID = -1; persistClassName = String.Empty; } public EditLayer(IFeatureLayer layer, EditStatements statements) { _layer = layer; _statements = statements; } private int persistLayerID; private string persistClassName; internal bool SetLayer(IMap map) { if (map == null || map.MapElements == null) { return false; } foreach (IDatasetElement element in map.MapElements) { if (!(element is IFeatureLayer) || element.Class == null) { continue; } if (element.ID == persistLayerID && element.Class.Name == persistClassName) { _layer = (IFeatureLayer)element; persistLayerID = -1; persistClassName = String.Empty; return true; } } return false; } #region IPersistable Member public void Load(IPersistStream stream) { persistLayerID = (int)stream.Load("id", -1); persistClassName = (string)stream.Load("class", String.Empty); _statements = (EditStatements)stream.Load("statement", (int)EditStatements.NONE); } public void Save(IPersistStream stream) { if (_layer == null || _layer.Class == null) { return; } stream.Save("id", _layer.ID); stream.Save("class", _layer.Class.Name); stream.Save("statement", (int)_statements); } #endregion #region IEditLayer Member public IFeatureLayer FeatureLayer { get { return _layer; } } public EditStatements Statements { get { return _statements; } internal set { _statements = value; } } public int LayerId { get { return _layer.ID; } } public string ClassName { get { return _layer?.Class?.Name; } } #endregion } }
using System; using IoTManager.Model; namespace IoTManager.Utility.Serializers { public class FieldSerializer { public FieldSerializer() { this.id = 0; this.fieldName = null; this.fieldId = null; this.createTime = null; this.updateTime = null; } public FieldSerializer(FieldModel fieldModel) { this.id = fieldModel.Id; this.fieldName = fieldModel.FieldName; this.fieldId = fieldModel.FieldId; this.createTime = fieldModel.CreateTime .ToString(Constant.getDateFormatString()); this.updateTime = fieldModel.UpdateTime .ToString(Constant.getDateFormatString()); } public int id { get; set; } public String fieldName { get; set; } public String fieldId { get; set; } public String createTime { get; set; } public String updateTime { get; set; } } }
using Alabo.Extensions; using MongoDB.Bson; using Newtonsoft.Json; using System; namespace Alabo.Domains.Repositories.Mongo.Extension { /// <summary> /// [ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段 /// [IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段 /// [JsonIgnore]//使用JsonConvert序列化时不序列化此字段 /// </summary> public sealed class ObjectIdConverter : JsonConverter { /// <summary> /// 序列化字段时 /// </summary> /// <param name="writer"></param> /// <param name="value"></param> /// <param name="serializer"></param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value); } /// <summary> /// 反序列化字段时 /// </summary> /// <param name="reader"></param> /// <param name="objectType"></param> /// <param name="existingValue"></param> /// <param name="serializer"></param> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (objectType != typeof(ObjectId)) { if (objectType == typeof(Guid)) { try { return Guid.Parse(reader.Value.ToString()); } catch { return Guid.Empty; } } if (objectType == typeof(short) || objectType == typeof(int) || objectType == typeof(long)) { return reader.Value.ConvertToLong(0); } } if (reader.ToString().IsNullOrEmpty()) { return null; } try { return ObjectId.Parse(reader.Value.ToString()); } catch { return ObjectId.Empty; } } public override bool CanConvert(Type objectType) { return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeverScript : MonoBehaviour { public enum LEVER_STATE { ON, OFF } bool triggerButtonAlreadyDown = false; public List<GameObject> triggerList; private bool playerOnTrigger = false; public LEVER_STATE state; public Sprite onSprite; public Sprite offSprite; public AudioClip[] flipSwitchSounds; public AudioClip switchError; private GameObject objectOnLever; public float cooldownTime = 2.0f; private Timer leverCooldown; private SoundCaller sc; void Awake() { sc = GetComponent<SoundCaller>(); leverCooldown = new Timer(cooldownTime); } void Start() { switch (state) //just checking what is set in inspector { case LEVER_STATE.ON: GetComponent<SpriteRenderer>().sprite = onSprite; break; case LEVER_STATE.OFF: GetComponent<SpriteRenderer>().sprite = offSprite; break; default: break; } } // Update is called once per frame void Update() { if (playerOnTrigger && Input.GetAxis("Interact") == 1 && !triggerButtonAlreadyDown) { triggerButtonAlreadyDown = true; if (leverCooldown.hasEnded()) { leverCooldown.restart(); switch (state) { case LEVER_STATE.ON: GetComponent<SpriteRenderer>().sprite = offSprite; state = LEVER_STATE.OFF; break; case LEVER_STATE.OFF: GetComponent<SpriteRenderer>().sprite = onSprite; state = LEVER_STATE.ON; break; default: break; } sc.attemptSound(flipSwitchSounds[Random.Range(0, flipSwitchSounds.Length)], 5); onTrigger(); } else { sc.attemptSound(switchError); } } if (Input.GetAxis("Interact") == 0) { triggerButtonAlreadyDown = false; } } void onTrigger() { foreach (GameObject obj in triggerList) { if (obj != null) { obj.GetComponent<Triggerable>().startTrigger(objectOnLever); } } } public void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Player")) { objectOnLever = collision.gameObject; playerOnTrigger = true; //TODO: not necessary... } } public void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.CompareTag("Player")) { playerOnTrigger = false; } } }
using System; using SpeedSlidingTrainer.Application.Infrastructure; namespace SpeedSlidingTrainer.Desktop.Infrastructure { public sealed class TimerAdapterFactory : ITimerFactory { public ITimer Create(TimeSpan interval, Action onTick) { return new TimerAdapter(interval, onTick); } } }
using Cosmos.HAL; using Cosmos.System.FileSystem.Listing; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace FrameOS.Systems.Logs { public enum LogType { Info, Warning, Error } public static class LogManager { public static string fileName = ""; public static void Log(string message, LogType type) { try { if (fileName == "") { fileName = Kernel.logFileTime + ".log"; } if (!File.Exists(@"0:\System\Logs\" + fileName)) { if (Directory.Exists(@"0:\System\Logs\")) { FileSystem.Filesystem.fs.CreateFile(@"0:\System\Logs\" + fileName); } else { throw new FatalException("Your FrameOS has corrupted. Please reinstall FrameOS to fix this."); } } string toWrite = ""; switch (type) { case LogType.Info: toWrite = "[INFO][" + RTC.Hour + "-" + RTC.Minute + "-" + RTC.Second + "]" + " " + message + "\n"; break; case LogType.Warning: toWrite = "[WARNING][" + RTC.Hour + "-" + RTC.Minute + "-" + RTC.Second + "]" + " " + message + "\n"; break; case LogType.Error: toWrite = "[ERROR][" + RTC.Hour + "-" + RTC.Minute + "-" + RTC.Second + "]" + " " + message + "\n"; break; } File.AppendAllText(@"0:\System\Logs\" + fileName, toWrite); } catch (Exception e) { Shell.Shell.Crash(e); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.PageObjects; using NUnit.Framework; namespace BusinessCreation { class GmailHomePage { IWebDriver driver; [FindsBy(How = How.Name)] private IWebElement Title; [FindsBy(How = How.Name)] private IWebElement Email; [FindsBy(How = How.Name)] private IWebElement Passwd; public GmailHomePage(IWebDriver driver) { this.driver = driver; } public void CheckTile() { try { Assert.AreEqual("Gmail: Email from Google",driver.Title); Console.WriteLine("The page title is correct: " +driver.Title); } catch (Exception) { Console.WriteLine("The page title is wrong: " +driver.Title); } } public void CheckElements() { try { Assert.IsTrue(Email.Enabled); Console.WriteLine("Email field enabled"); } catch (Exception) { Console.WriteLine("Email field disabled"); } try { Assert.IsTrue(Passwd.Enabled); Console.WriteLine("Passwd field enabled"); } catch (Exception) { Console.WriteLine("Passwd field disabled"); } } } class Login { } class program { //static void Main() //{ // IWebDriver driver = new FirefoxDriver(); // driver.Navigate().GoToUrl("http://www.gmail.com"); // GmailHomePage homepage = new GmailHomePage(driver); // PageFactory.InitElements(driver, homepage); // homepage.CheckTile(); // homepage.CheckElements(); // Console.ReadLine(); //} } //class LoginPage //{ // private IWebDriver driver; // [FindsBy(How = How.Name)] // private IWebElement userName; // How.NAME = userName // [FindsBy(How = How.Name)] // private IWebElement password; // How.NAME = password // [FindsBy(How = How.Name)] // private IWebElement login; // How.NAME = login // public LoginPage(IWebDriver driver) // { // this.driver = driver; // } // public void Do(string UserName, string Password) // { // userName.SendKeys(UserName); // password.SendKeys(Password); // login.Click(); // //PageFactory.InitElements(driver, (new FindFlightsPage(this.driver))); // //return new FindFlightsPage(driver); // } //} //class FindFlightsPage //{ // private IWebDriver driver; // public FindFlightsPage(IWebDriver driver) // { // this.driver = driver; // // 1. verify if page is valid // Console.WriteLine("Verify page load"); // //if (driver.Title != "Find a Flight: Mercury Tours:") // // throw new NoSuchWindowException("This is not the FindFlights page"); // } // // 2. method/code-block to find a flight // //public void Do() // //{ // // Console.WriteLine("In FindFlightsPage.Do [Checking for Flights]"); // //} // // returns LoginPage PageObject // public LoginPage Logout() // { // // 3. log-off and return to LoginPage // driver.FindElement(By.LinkText("SIGN-OFF")).Click(); // driver.FindElement(By.LinkText("Home")).Click(); // // 4. return the LoginPage object // return new LoginPage(driver); // } //} //class Program //{ // static void Main() // { // IWebDriver driver = new FirefoxDriver(); // driver.Navigate().GoToUrl("http://newtours.demoaut.com"); // LoginPage Login = new LoginPage(driver); // // initialize elements of the LoginPage class // PageFactory.InitElements(driver, Login); // // all elements in the 'WebElements' region are now alive! // // FindElement or FindElements no longer required to locate elements // Login.Do("User", "mercury"); // driver.Quit(); // Console.ReadLine(); // } //} }
/* Program Name: Movies Library System * * Author: Kazembe Rodrick * * Author Description: Freelancer software/web developer & Technical writter. Has over 7 years experience developing software * in Languages such as VB 6.0, C#.Net,Java, PHP and JavaScript & HTML. Services offered include custom * development, writting technical articles,tutorials and books. * Website: http://www.kazemberodrick.com * * Project URL: http://www.kazemberodrick.com/movies-library-system.html * * Email Address: kr@kazemberodrick. * * Purpose: Fairly complex Movies Library System For Educational purposes. Demonstrates how to develop complete database powered * Applications that Create and Update data in the database. The system also demonstrates how to create reports from * the database. * * Limitations: The system is currently a standalone. It does not support multiple users. This will be implemented in future * versions. * The system does not have a payments module. This can be developed upon request. Just sent an email to kr@kazemberodrick.com * The system does not have keep track of the number of movies to check for availability. This can be developed upon request. * * Movies Library System Road Map: This system is for educational purposes. I will be writting step-by-step tutorials on my * website http://www.kazemberodrick.com that explain; * -System Specifications for Movies Library System * -System Design Considerations * -System Database ERD * -System Class Diagram * -Explainations of the codes in each window * -Multiple-database support. The Base class BaseDBUtilities will be extended to create * classes that will support client-server database engines such as MySQL, MS SQL Server etc. * * Support Movies Library System: The System is completely free. Please support it by visiting http://www.kazemberodrick.com/c-sharp.html and recommending the site to * your friends. Share the tutorials on social media such as twitter and facebook. * * Github account: https://github.com/KazembeRodrick I regulary post and update sources on my Github account.Make sure to follow me * and never miss an update. * Facebook page: http://www.facebook.com/pages/Kazembe-Rodrick/487855197902730 Please like my page and get updates on latest articles * and source codes. You can get to ask questions too about the system and I will answer them. * * Twitter account: https://twitter.com/KazembeRodrick Spread the news. Tweet the articles and source code links on twitter. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Reflection; using System.Windows.Forms; namespace Movies_Library_System { partial class frmAbout : Form { public frmAbout() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; this.textBoxDescription.Text = AssemblyDescription; } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion private void frmAbout_Load(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoorKicker : MonoBehaviour { public float kickForce = 200f; // Start is called before the first frame update void Start() { } void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "PC") { float angle = 45; if ((collision.relativeVelocity.y > 1 || collision.relativeVelocity.x > 1) && Vector3.Angle(-collision.gameObject.transform.right, transform.position - collision.gameObject.transform.position) < angle) { float playerDir = collision.gameObject.transform.rotation.x; gameObject.layer = LayerMask.NameToLayer("Litter"); GetComponent<Rigidbody2D>().isKinematic = false; GetComponent<AudioSource>().Play(); Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>()); // Calculate Angle Between the collision point and the player Vector2 dir = collision.GetContact(0).point - new Vector2(Mathf.Round(transform.position.x / 90) * 90, Mathf.Round(transform.position.y / 90) * 90); // We then get the opposite (-Vector3) and normalize it dir = dir.normalized; // And finally we add force in the direction of dir and multiply it by force. // This will push back the player GetComponent<Rigidbody2D>().velocity = dir * kickForce; Vector2 size = gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size; transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y * 4, transform.localScale.z); } } } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Text; namespace Monogame.src.character { class Character { public Character() { } // move function // jump function } }
using Quokka.RISCV.Integration.DTO; using System; using System.Collections.Generic; using System.Text; namespace Quokka.RISCV.Integration.Client { public class RISCVIntegration { public static RISCVIntegrationContext DefaultContext(string rootPath) { var context = new RISCVIntegrationContext() .WithPort(15000) .WithExtensionClasses( new ExtensionClasses() .Text("") .Text("lds") .Text("s") .Text("c") .Text("cpp") .Text("h") .Binary("bin") .Binary("elf") .Text("map") ) .WithRootFolder(rootPath) .WithAllRegisteredFiles() .WithOperations(new BashInvocation("make firmware.bin")) .TakeModifiedFiles(); return context; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Plotter.Tweet.Processing.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Plotter.Tests.CommandTests { [TestClass] public class SwitchTests_CreatingNew : TestBase { [TestMethod] public void SwitchChart_NonePreExisting_MessageReturned() { Tweet.Tweet reply = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "switch" }); Assert.IsNull(reply.Image); Assert.AreEqual(SwitchCommand.JustSendSomeDangData, reply.Text); } [TestMethod] public void SwitchChart_CreateNew_WithName_NonePreExisting_MessageReturned() { Tweet.Tweet reply = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "switch bob" }); Assert.IsNull(reply.Image); Assert.AreEqual("bob", DBContext.Charts.First().Title); Assert.AreEqual(SwitchCommand.NewNamedChartCreated("bob"), reply.Text); } [TestMethod] public void SwitchChart_CreateNew_WithPreExisting_MessageReturned() { DBContext.Charts.Add(new Models.Chart() { Owner = "anna", Title = "chartA" }); Tweet.Tweet reply = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "switch bob" }); Assert.IsNull(reply.Image); Assert.AreEqual(SwitchCommand.NewNamedChartCreatedAndHowToViewPrevious("bob", "chartA"), reply.Text); } [TestMethod] public void SwitchChart_CreateNew_WithPreExisting_Unnamed_MessageReturned() { DBContext.Charts.Add(new Models.Chart() { Owner = "anna" }); DBContext.SaveChanges(); Tweet.Tweet reply = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "switch bob" }); Assert.IsNull(reply.Image); Assert.AreEqual(SwitchCommand.CurrentChartNeedsAName, reply.Text); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Cors; // Addiitonal namespaces using System.Net.Http; using System.Text.RegularExpressions; using System.Net; using Newtonsoft.Json.Linq; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace Nusstudios.Controllers { [Route("[controller]")] public class NussAPIController : Controller { private static JArray getalgo() { JArray actionList = new JArray(); actionList.Add(17772); JObject action = new JObject(); action["parameter"] = 1; action["action"] = "splice"; actionList.Add(action); action = new JObject(); action["parameter"] = 33; action["action"] = "swap"; actionList.Add(action); action = new JObject(); action["parameter"] = 2; action["action"] = "splice"; actionList.Add(action); action = new JObject(); action["parameter"] = null; action["action"] = "reverse"; actionList.Add(action); action = new JObject(); action["parameter"] = 2; action["action"] = "splice"; actionList.Add(action); action = new JObject(); action["parameter"] = 23; action["action"] = "swap"; actionList.Add(action); action = new JObject(); action["parameter"] = null; action["action"] = "reverse"; actionList.Add(action); action["parameter"] = 43; action["action"] = "swap"; actionList.Add(action); action = new JObject(); action["parameter"] = null; action["action"] = "reverse"; actionList.Add(action); return actionList; } private static JObject GetVimeoVideoInfo(int id) { HttpClient hc = new HttpClient(); string html = hc.GetStringAsync("https://vimeo.com/" + id).Result; List<string> VimeoVideoPageStreamConfigRegexes = new List<string>(); VimeoVideoPageStreamConfigRegexes.Add("\"\\s*?config_url\\s*?\"\\s*?:\\s*?\"\\s*?(.*?)\\s*?\""); VimeoVideoPageStreamConfigRegexes.Add("data-config-url\\s*?=\\s*?\"\\s*?(.*?)\""); foreach (string regstr in VimeoVideoPageStreamConfigRegexes) { Regex rgx = new Regex(regstr); Match mtch = rgx.Match(html); if (mtch.Success) { string originalConfigURL = Regex.Unescape(mtch.Groups[1].Value); return JObject.Parse(hc.GetStringAsync(originalConfigURL).Result); } } return JObject.Parse(hc.GetStringAsync("https://player.vimeo.com/video/" + id + "/config").Result); } private static JObject ReloadVimeoVideoInfo(JObject config) { var vimeoVideoInfo = new JObject(); // Adding vimeo video id and video count vimeoVideoInfo["id"] = config["video"]["id"]; vimeoVideoInfo["title"] = config["video"]["title"]; JArray fullStreamMap = (JArray)config["request"]["files"]["progressive"]; var streamArray = new JArray(); for (var i = 0; i < fullStreamMap.Count; i++) { var streamData = new JObject(); streamData["fps"] = fullStreamMap[i]["fps"]; streamData["height"] = fullStreamMap[i]["geight"]; streamData["mime"] = fullStreamMap[i]["mime"]; streamData["quality"] = fullStreamMap[i]["quality"]; streamData["url"] = fullStreamMap[i]["url"]; streamArray.Add(streamData); } vimeoVideoInfo["streams"] = streamArray; return vimeoVideoInfo; } [EnableCors("AnyOrigin")] [HttpGet("[action]/{id:int}")] public string vimeoquery(int id) { return ReloadVimeoVideoInfo(GetVimeoVideoInfo(id)).ToString(); } [EnableCors("AnyOrigin")] [HttpGet("[action]")] public JArray queryalgo() { return getalgo(); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace FiiiChain.Consensus.Api { public static class ApiHelper { public static ApiResponse GetApi(string url, List<KeyValuePair<string, string>> parameters) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, string> item in parameters) { if (!string.IsNullOrEmpty(sb.ToString())) { sb.Append("&"); } sb.Append(item.Key); sb.Append("="); sb.Append(item.Value); } string address = url + sb.ToString(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); request.Method = "GET"; request.ContentType = "application/json"; string result = null; using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse()) { using (Stream rspStream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } ApiResponse response = new ApiResponse(); response.Result = Newtonsoft.Json.Linq.JToken.Parse(result); return response; } public static string PostApi(string url, Dictionary<string, string> parameters) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; string strContent = Newtonsoft.Json.JsonConvert.SerializeObject(parameters); using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())) { dataStream.Write(strContent); dataStream.Close(); } string result = null; using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse()) { using (Stream rspStream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } return result; } } }
using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace SampleUWP { public sealed partial class P06 : Page { // A pointer to MainPage is needed if you want to call methods or variables in MainPage. private readonly MainPage mainPage = MainPage.mainPagePointer; public P06() { this.InitializeComponent(); pagePivot.ItemsSource = mainPage.bindingMenuList; // This provides the source for binding. Use mainPage pointer to access bindingMenuList in MenuMain.cs. pagePivot.SelectedIndex = 0; // Selects Pivot menu item. ShowSelectedPage(); // Shows the selected page. /* mainPage.HideDebugBar(); mainPage.dM4 = mainPage.bindingMenuList[0].MenuText; mainPage.dM5 = mainPage.bindingMenuList.Count.ToString(); mainPage.dM6 = mainPage.bindingMenuList[1].SymbolText; mainPage.ShowDebugBar(); */ } // Pivot Class: https://msdn.microsoft.com/library/windows/apps/dn608241 /// <summary> /// Navigate to selected page and show page name in page Title. Note: Pages are not being shown via PivotItem /// generated by ItemTemplate but moved outside of Pivot. More efficient than having all the pages loaded at once. /// </summary> private void ShowSelectedPage() { pageFrame.Navigate(mainPage.bindingMenuList[pagePivot.SelectedIndex].PageNavigate); pagePivot.Title = mainPage.bindingMenuList[pagePivot.SelectedIndex].MenuText; } /// <summary> /// Invoked when user press page Back button in Pivot header vs. app back button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BackButton_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. if (pagePivot.SelectedIndex > 0) { // If not at the first item, go back to the previous one. pagePivot.SelectedIndex -= 1; ShowSelectedPage(); } else { // The first PivotItem is selected, so loop around to the last item. pagePivot.SelectedIndex = pagePivot.Items.Count - 1; ShowSelectedPage(); } } /// <summary> /// Invoked when user press page Next button in Pivot header. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NextButton_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. if (pagePivot.SelectedIndex < pagePivot.Items.Count - 1) { // If not at the last item, go to the next one. pagePivot.SelectedIndex += 1; ShowSelectedPage(); } else { // The last PivotItem is selected, so loop around to the first item. pagePivot.SelectedIndex = 0; ShowSelectedPage(); } } /// <summary> /// Invoked when user selects an item from the Pivot menu. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PivotMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. ShowSelectedPage(); // Sweet and simple } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; /// <summary> /// プレイヤーの人数を選択するシーンの管理クラス /// </summary> public class PlayerNumberSelectManager : MonoBehaviour { //参加するかどうか bool[] isPlays = new bool[4]; delegate void StateType(); StateType state; [SerializeField] PlayerNumberSelectUIController[] uiControllers; [SerializeField] Image[] stageSelectUIs; float stageSelectUIalpha; #if UNITY_EDITOR [SerializeField, Range(0, 3)] int debugNumber; [SerializeField] bool debugIsPlay; [SerializeField] bool changeIsPlay; #endif void Start() { state = PushButtonPlayer; //フェード Fade.Instance.FadeOut(1.0f); StageSelectUIAlphaUpdate(0.0f); BgmManager.Instance.Play(BgmEnum.PLAYER_SELECT); } void Update() { if (!Fade.Instance.IsEnd) return; //タイトルに戻る if (!isPlays[0] && SwitchInput.GetButtonDown(0, SwitchButton.Cancel)) { StartCoroutine(TranslationPrevScene()); state = null; } if (state != null) state(); } /// <summary> /// ボタンを押して参加するプレイヤーを決める /// </summary> void PushButtonPlayer() { //プレイ人数 int playNumCount = 0; for (int i = 0; i < isPlays.Length; ++i) { bool isPlay = isPlays[i]; //参加かどうか if (SwitchInput.GetButtonDown(i, SwitchButton.Ok)) { isPlay = true; } else if (SwitchInput.GetButtonDown(i, SwitchButton.Cancel)) { isPlay = false; } #if UNITY_EDITOR if (debugNumber == i && changeIsPlay) { isPlay = debugIsPlay; changeIsPlay = false; } #endif //選択したものが変わったかどうか if (isPlay != isPlays[i]) { isPlays[i] = isPlay; uiControllers[i].SetOnOff(isPlay); } //プレイ人数の加算 if (isPlays[i]) ++playNumCount; } //二人以上参加しているとき if (playNumCount >= 2) { const float MinAlpha = 0.3f; stageSelectUIalpha += Time.deltaTime * 6; StageSelectUIAlphaUpdate((Mathf.Sin(stageSelectUIalpha) + 1) / 2 * (1 - MinAlpha) + MinAlpha); //ポーズを押すとプレイヤー人数の選択を終了 if (SwitchInput.GetButtonDown(0, SwitchButton.Pause)) { SoundManager.Instance.Push(); BlockCreater.GetInstance().isPlays = isPlays; StartCoroutine(TranslationNextScene()); state = null; } } else { StageSelectUIAlphaUpdate(0.0f); stageSelectUIalpha = 1.0f; } } void StageSelectUIAlphaUpdate(float alpha) { foreach (var stageSelectUI in stageSelectUIs) { Color color = stageSelectUI.color; color.a = alpha; stageSelectUI.color = color; } } /// <summary> /// 次のシーンに遷移する /// </summary> IEnumerator TranslationNextScene() { yield return StartCoroutine(SceneTranslationFade()); //シーン遷移 SceneManager.LoadScene("Select"); } /// <summary> /// 前のシーンに遷移する /// </summary> IEnumerator TranslationPrevScene() { yield return StartCoroutine(SceneTranslationFade()); //シーン遷移 SceneManager.LoadScene("Title"); } /// <summary> /// シーン遷移時のフェードイン /// </summary> IEnumerator SceneTranslationFade() { //フェード Fade.Instance.FadeIn(1.0f); //少し待つ while (!Fade.Instance.IsEnd) yield return null; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Business.OnlinePay.Company.ChinaPay.Loan { public class Response : ResponseBase { public override string ResponseName { get { return "C101LoanRs"; } } /// <summary> /// 投标订单号 /// </summary> public string OrderNo { get; set; } /// <summary> /// 标的号 /// </summary> public string SubjectNo { get; set; } /// <summary> /// 投资人用户号 /// </summary> public string PyrUserId { get; set; } /// <summary> /// 借款人用户号 /// </summary> public string PyeUserId { get; set; } /// <summary> /// 币种 /// </summary> public string CurCode { get; set; } /// <summary> /// 投资金额 /// </summary> public string PyrAmt { get; set; } /// <summary> /// 扩展域 /// </summary> public string Reserved { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelController : MonoBehaviour { public List<Level> levels; private void Awake() { DontDestroyOnLoad(gameObject); if (FindObjectsOfType<LevelController>().Length > 1) { Destroy(gameObject); } levels = new List<Level> { new Level(0, "FirstLevel", true, 2, false), new Level(1, "SecondLevel", false, 0, false), new Level(2, "Third level", false, 0, true), new Level(3, "Fourth level", false, 0, true), new Level(4, "Fifth level", false, 0, true), new Level(5, "Sixth level", false, 0, true), new Level(6, "Seventh level", false, 0, true), new Level(7, "Eigth level", false, 0, true), new Level(8, "Ninth level", false, 0, true), new Level(9, "Tenth level", false, 0, true), new Level(10, "Eleventh level", false, 0, true), new Level(11, "Twelwth level", false, 0, true), new Level(12, "Thirteenth level", false, 0, true), new Level(13, "Fourteenth level", false, 0, true), new Level(14, "Fifteenth level", false, 0, true), new Level(15, "Sixteenth level", false, 0, true) }; } public void StartLevel(string levelName) { SceneManager.LoadScene(levelName); } public void CompleteLevel(string levelName) { levels.Find(x => x.LevelName == levelName).Complete(); } public void CompleteLevel(string levelName, int stars) { levels.Find(x => x.LevelName == levelName).Complete(stars); } public void LockLevel(string levelName) { levels.Find(x => x.LevelName == levelName).Lock(); } public void UnlockLevel(string levelName) { levels.Find(x => x.LevelName == levelName).Unlock(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using GodMorgon.Models; using GodMorgon.GameSequencerSpace; namespace GodMorgon.CardEffect { public class MoveEffect : CardEffect { /** * Apply the move effect by creating the sequence in the gameSequencer */ public override void ApplyEffect(CardEffectData effectData, GameContext context) { //Trust if (effectData.trust) { if (BuffManager.Instance.IsTrustValidate(effectData.trustNb)) { PlayerManager.Instance.UpdateMultiplier(2); } } else PlayerManager.Instance.UpdateMultiplier(1); //add the move sequence GSA_PlayerMove playerMoveAction = new GSA_PlayerMove(); GameSequencer.Instance.AddAction(playerMoveAction); } } }
using System; using System.Collections.Generic; using System.Linq; using PokerHandShowdown; namespace PokerHandShowdownDemo { class Program { static IPokerGameSession pokerGameSession = new PokerGameSession(); static Dictionary<int, Card> cards = new Dictionary<int, Card>(52); static void Main(string[] args) { GenerateDeck(); Console.WriteLine("##########| Poker Hand Showdown |##########"); MainMenu(); } private static void GenerateDeck() { var index = 0; foreach (PokerSuit suit in ((PokerSuit[])Enum.GetValues(typeof(PokerSuit))).Where(s => !s.Equals(PokerSuit.None))) { foreach (PokerRank rank in (PokerRank[])Enum.GetValues(typeof(PokerRank))) { cards.Add(index++, new Card(suit, rank)); } } } private static void DisplayDeck() { foreach (var card in cards) { if(card.Key%6==0) Console.WriteLine($"[{card.Key} ({card.Value.Rank},{card.Value.Suit})],"); else Console.Write($"[{card.Key} ({card.Value.Rank},{card.Value.Suit})],"); } } private static void AddCardsMenu() { Console.Clear(); Console.WriteLine(); Console.WriteLine("###| Please Select one of the following options. |###"); Console.WriteLine("###| 1. Dispatch Single Card. |###"); Console.WriteLine("###| 2. Dispatch Cards. |###"); Console.WriteLine("###| 3. Go Back. |###"); Console.WriteLine("###| 4. Quit. |###"); var option = Console.ReadKey().KeyChar.ToString(); switch (option) { case "1": DisplayDeck(); Console.WriteLine(); Console.WriteLine("###| Please Pick from the Deck above index of card to add. |###"); var index = Console.ReadLine().ToString(); var card = cards[int.Parse(index)]; Console.WriteLine($"||({card.Rank},{card.Suit}) picked!||"); Console.WriteLine("###| Please Enter player participant name: |###"); var playerName = Console.ReadLine().ToString(); pokerGameSession.DispatchCardsToPlayer(playerName, card); Console.WriteLine($"||({card.Rank},{card.Suit}) added!||"); AddCardsMenu(); break; case "2": DisplayDeck(); Console.WriteLine("###| Please Pick from the Deck above up to 5 indexes of cards to add.\r\n press enter after each index, when you finish press * |###"); var playerCards = new List<Card>(); for (var i = 0; i < 5; i++) { var index1 = Console.ReadLine().ToString(); if (index1.Equals("*")) { break; } playerCards.Add(cards[int.Parse(index1)]); } Console.WriteLine("###| Please Enter Participant's name. |###"); var playerName1 = Console.ReadLine().ToString(); Console.WriteLine(); pokerGameSession.DispatchCardsToPlayer(playerName1, playerCards.ToArray()); Console.WriteLine($"||({playerCards.Count}) cards added! || "); AddCardsMenu(); break; case "3": MainMenu(); break; case "4": Environment.Exit(0); break; } } private static void AddPlayersMenu() { Console.Clear(); Console.WriteLine(); Console.WriteLine("###| Please Select one of the following options. |###"); Console.WriteLine("###| 1. Add Player. |###"); Console.WriteLine("###| 2. Add Player and Cards. |###"); Console.WriteLine("###| 3. Go Back. |###"); Console.WriteLine("###| 4. Quit. |###"); var option = Console.ReadKey().KeyChar.ToString(); switch (option) { case "1": Console.WriteLine("###| Please Enter Participant's name. |###"); var playerName = Console.ReadLine().ToString(); pokerGameSession.AddPlayer(playerName); Console.WriteLine($"||({playerName}) added!||"); AddPlayersMenu(); break; case "2": Console.WriteLine("###| Please Enter Participant's name. |###"); var playerName1 = Console.ReadLine().ToString(); Console.WriteLine(); DisplayDeck(); Console.WriteLine("###| Please Pick from the Deck above up to 5 indexes of cards to add.\r\n press enter after each index, when you finish press * |###"); var playerCards = new List<Card>(); for(var i = 0; i < 5; i++) { var index = Console.ReadLine().ToString(); if (index.Equals("*")) { break; } playerCards.Add(cards[int.Parse(index)]); } pokerGameSession.AddPlayer(playerName1,playerCards.ToArray()); Console.WriteLine($"||({playerName1}) added! || "); AddPlayersMenu(); break; case "3": MainMenu(); break; case "4": Environment.Exit(0); break; } } private static void MainMenu() { Console.Clear(); Console.WriteLine(); Console.WriteLine("###| Please Select one of the following options by pressing the number indicated and hit enter. |###"); Console.WriteLine("###| 0. Show Cards to Determine the winner. |###"); Console.WriteLine("###| 1. Add Players. |###"); Console.WriteLine("###| 2. Add Cards. |###"); Console.WriteLine("###| 3. Remove player. |###"); Console.WriteLine("###| 4. Empty hands. |###"); Console.WriteLine("###| 5. Get new Session. |###"); Console.WriteLine("###| 6. Quit. |###"); var option = Console.ReadKey().KeyChar.ToString(); switch (option) { case "0": ProcessGameSession(); MainMenu(); break; case "1": AddPlayersMenu(); break; case "2": AddCardsMenu(); break; case "3": Console.WriteLine("###| Please Enter name of participant(case sensitive). |###"); var playerName = Console.ReadLine().ToString(); try { pokerGameSession.RemoveParticipant(playerName); Console.WriteLine($"||Player {playerName} removed||"); } catch (Exception ex) when (ex is InvalidOperationException || ex is NullReferenceException) { Console.WriteLine($"!!!| Error {ex.Message}|!!!"); } MainMenu(); break; case "4": pokerGameSession.EmptyHands(); Console.WriteLine("||Hands Empty deck full||"); MainMenu(); break; case "5": pokerGameSession.ClearSession(); Console.WriteLine("||New session created||"); MainMenu(); break; case "6": Environment.Exit(0); break; default: Console.WriteLine(" Invalid Option"); MainMenu(); return; } } private static void ProcessGameSession() { pokerGameSession.PreparePlayersHands(); pokerGameSession.DetermineTheWinners(); foreach(var winner in pokerGameSession.Winners) { Console.WriteLine($"Winner : {winner}"); } Console.WriteLine(); } } }
using DigitalFormsSteamLeak.Business; using DigitalFormsSteamLeak.Entity.IModels; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Runtime.Serialization; using DigitalFormsSteamLeak.Entity.Models; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json.Linq; namespace DigitalFormsSteamLeak.SteamLeaksAPI.Controllers { public class LocationUnitController : ApiController { HttpResponseMessage response = new HttpResponseMessage(); public LocationUnitFactory locationUnitFactory = new LocationUnitFactory(); //Get: api/LocationUnit public HttpResponseMessage Get() { try { var result = locationUnitFactory.GetAll().ToList<ILocationUnit>(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JArray.FromObject(result).ToString()); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(ex.Message); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } return response; } // GET: api/LocationUnit/5 public HttpResponseMessage Get(Guid? id) { try { var result = locationUnitFactory.GetById(id); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(JArray.FromObject(result).ToString()); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(ex.Message); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } return response; } // POST: api/LocationUnit public HttpResponseMessage Post(LocationUnit locationUnit) { try { response.StatusCode = HttpStatusCode.Created; response.Content = new StringContent(locationUnitFactory.Create(locationUnit).ToString()); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(ex.Message); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } return response; } // PUT: api/LocationUnit/5 public HttpResponseMessage Put(LocationUnit locationUnit) { try { response.StatusCode = HttpStatusCode.Created; response.Content = new StringContent(locationUnitFactory.Update(locationUnit).ToString()); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent(ex.Message); response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromMinutes(20) }; } return response; } // DELETE: api/LocationUnit/5 public void Delete(int id) { } // GET: api/LocationUnit //public IEnumerable<ILocationUnit> Get() //{ // var result = locationUnitFactory.GetAll().ToList<ILocationUnit>(); // return result; //} //// GET: api/LocationUnit/5 //public IQueryable<ILocationUnit> Get(Guid? id) //{ // return locationUnitFactory.GetById(id); //} //// POST: api/LocationUnit //public void Post([FromBody]string value) //{ //} //// PUT: api/LocationUnit/5 //public void Put(int id, [FromBody]string value) //{ //} //// DELETE: api/LocationUnit/5 //public void Delete(int id) //{ //} } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xero.Api.Core.Model; using Xero.Api.Infrastructure.Interfaces; using Xero.Api.Serialization; using Xero.Api.Core.Model.Types; namespace CoreTests.Integration.Invoices { [TestFixture] public class Deserialization { private IJsonObjectMapper _jsonMapper; private IXmlObjectMapper _xmlMapper; [TestFixtureSetUp] public void SetUp() { _jsonMapper = new DefaultMapper(); _xmlMapper = new DefaultMapper(); } [Test] public void nullable_type_json() { var invoice = createInvoice(); var json = _jsonMapper.To(invoice); var deserialized = _jsonMapper.From<Invoice>(json); Assert.AreEqual(invoice.Id, deserialized.Id); Assert.AreEqual(invoice.Type, deserialized.Type); } [Test] public void nullable_type_xml() { var invoice = createInvoice(); var xml = _xmlMapper.To(invoice); var deserialized = _xmlMapper.From<Invoice>(xml); Assert.AreEqual(invoice.Id, deserialized.Id); Assert.AreEqual(invoice.Type, deserialized.Type); } private static Invoice createInvoice() { return new Invoice() { Id = Guid.NewGuid(), Type = InvoiceType.AccountsReceivable }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OcTur { static class Sessao { //Guarda as informações do usuário para manter as sessão ativa public static string Nome { get; set; } public static string Senha { get; set; } public static string Usuario { get; set; } public static int Idioma { get; set; } public static int Id { get; set; } public static bool [] Papel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Upkeep.Shell.Models { public class ViewInfoModel { public string ViewName { get; set;} } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Alabo.Domains.Entities; using Alabo.Domains.Enums; using Alabo.Validations; using Alabo.Web.Mvc.Attributes; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace Alabo.Framework.Basic.PostRoles.Domain.Entities { /// <summary> /// 岗位,也可立即成部门表 /// </summary> [BsonIgnoreExtraElements] [Table("Basic_PostRole")] [ClassProperty(Name = "岗位权限")] public class PostRole : AggregateMongodbRoot<PostRole> { /// <summary> /// 岗位名称 /// </summary> [Display(Name = "岗位名称")] [Required(ErrorMessage = ErrorMessage.NameNotCorrect)] [Field(ControlsType = ControlsType.TextBox, ListShow = true, IsShowAdvancedSerach = true, IsShowBaseSerach = true, Width = "150", IsMain = true, SortOrder = 1)] public string Name { get; set; } /// <summary> /// </summary> [Display(Name = "岗位说明")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [Field(ListShow = true, Width = "400", SortOrder = 100)] public string Summary { get; set; } /// <summary> /// 岗位权限IDs /// </summary> public List<ObjectId> RoleIds { get; set; } } }
using AddressBook.Application.Contacts.DTOs; using AddressBook.Core.Contacts; using AddressBook.Infrastructure.Application; using AddressBook.Infrastructure.UnitOfWork; using System.Linq; using System.Threading.Tasks; namespace AddressBook.Application.Contacts { public class ContactService : IContactService { private readonly IUnitOfWork _unitOfWork; private readonly IContactManager _contactManager; private readonly IContactRepository _contactRepository; public ContactService( IUnitOfWork unitOfWork, IContactManager contactManager, IContactRepository contactRepository) { _unitOfWork = unitOfWork; _contactManager = contactManager; _contactRepository = contactRepository; } public async Task<PaginationResultDto<ContactDto>> SearchAsync(PaginationDto pagination) { var paginationResult = await _contactRepository.SearchAsync(pagination.PageNumber, pagination.PageSize); return paginationResult.MapToPaginationResultDto(); } public async Task<ContactDto> GetAsync(int id) { var contact = await _contactRepository.GetByIdAsync(id); return contact.MapToContactDto(); } public async Task CreateAsync(ContactDto contactDto) { var contact = await _contactManager.CreateAsync(contactDto.Name, contactDto.DateOfBirth, contactDto.Address); foreach (var contactPhone in contactDto.Phones) { contact.AddPhone(contactPhone.PhoneNumber); } await _contactRepository.InsertAsync(contact); await _unitOfWork.CommitAsync(); } public async Task UpdateAsync(ContactDto contactDto) { var contact = await _contactRepository.GetByIdAsync(contactDto.Id); contact.SetName(contactDto.Name); contact.SetDateOfBirth(contactDto.DateOfBirth); contact.SetAddress(contactDto.Address); foreach (var contactPhoneDto in contactDto.Phones) { var contactPhone = contact.Phones.FirstOrDefault(p => p.Id == contactPhoneDto.Id); if (contactPhone == null) { contact.AddPhone(contactPhoneDto.PhoneNumber); } else { contactPhone.SetPhoneNumber(contactPhoneDto.PhoneNumber); } } foreach (var contactPhone in contact.Phones) { if (contactDto.Phones.All(p => p.Id != contactPhone.Id)) { contact.RemovePhone(contactPhone); } } await _contactRepository.UpdateAsync(contact); await _unitOfWork.CommitAsync(); } public async Task DeleteAsync(int id) { var contact = await _contactRepository.GetByIdAsync(id); await _contactRepository.DeleteAsync(contact); await _unitOfWork.CommitAsync(); } } }
 using NBatch.Main.Core.Repositories; namespace NBatch.Main.Core { public interface IStep { string Name { get; } bool Process(StepContext stepContext, IStepRepository stepRepository); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Agencia_Datos_Repositorio; using entidades = Agencia_Datos_Entidades; namespace Agencia_Dominio { public class D_Idiomas { private readonly Repositorio<entidades.Idiomas> idiomas; public D_Idiomas (Repositorio<entidades.Idiomas> idiomas) { this.idiomas = idiomas; } public void AgregarNuevo(entidades.Idiomas modelo) { idiomas.Agregar(modelo); idiomas.Guardar(); idiomas.Commit(); } public void Modificar(entidades.Idiomas modelo) { idiomas.Modificar(modelo); idiomas.Guardar(); idiomas.Commit(); } public void Eliminar(entidades.Idiomas modelo) { idiomas.Eliminar(modelo); idiomas.Guardar(); idiomas.Commit(); } public object TraerTodo() { return idiomas.TraerTodo(); } public object TraerUnoPorId(int id) { return idiomas.TraerUnoPorId(id); } public void Rollback() { idiomas.RollBack(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundManagerLoader : MonoBehaviour { private void Start() { AudioSource[] array = GetComponents<AudioSource>(); foreach(AudioSource src in array) { src.volume = SoundManager.soundFloat; } } }
using System; using System.Collections.Generic; using NHibernate.Criterion; using NHibernate.SqlCommand; using Profiling2.Domain.Contracts.Queries.Audit; using Profiling2.Domain.Prf; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries.Audit { public class AdminAuditQuery : NHibernateQuery, IAdminAuditQuery { public IList<AdminAudit> GetAdminAudits(string tableName, int auditTypeId, DateTime startDate, DateTime endDate) { AdminAuditType typeAlias = null; return Session.QueryOver<AdminAudit>() .JoinAlias(x => x.AdminAuditType, () => typeAlias, JoinType.InnerJoin) .Where(x => x.ChangedTableName == tableName) .And(() => typeAlias.Id == auditTypeId) .And(Restrictions.On<AdminAudit>(x => x.ChangedDateTime).IsBetween(startDate).And(endDate)) .OrderBy(x => x.ChangedDateTime).Asc .List<AdminAudit>(); } } }
interface ITransaction{ void InsertTransaction(BankAccount bankAccount, Transaction transaction); void ViewTransaction(BankAccount bankAccount); }
using System; namespace Task_02 { class Program { static void Main(string[] args) { if (!uint.TryParse(Console.ReadLine(), out uint N) || N % 2 == 0) { Console.WriteLine("Incorrect input"); return; } char[][] myArray = new char[N][]; for (uint i = 0, k = N; i < N; i++, k++) { { myArray[i] = new char[k]; } } for (int i = 0; i < myArray.Length; i++) { for (int j = 0; j < myArray[i].Length; j++) { myArray[i][j] = '*'; } } for (int i = 0; i < N - 1; i++) { for (int j = (int)(N - 2 - i); j >= 0; j--) { myArray[i][j] = ' '; } } for (int i = 0; i < myArray.Length; i++) { for (int j = 0; j < myArray[i].Length; j++) { Console.Write($"\t{myArray[i][j]}"); } Console.WriteLine(); } } } }
namespace E2 { public abstract class Monstruos { protected int respeto; public int Respeto { get => respeto; } public Monstruos (int respeto){ this.respeto = respeto; } public abstract void asustar(); public abstract void reir(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using CableMan.Model; using MvvmHelpers; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace CableMan.ViewModel { class PageKetCuoiGanDayViewModel : BaseViewModel { private INavigation _navigation; private ListView _listViewKetCuoiKhaDungCopper; private ListView _listViewKetCuoiKhaDungFiber; //private ListView _listViewKetCuoiKhaDungCapDong; //public PageKetCuoiGanDayViewModel(INavigation navigation) public PageKetCuoiGanDayViewModel(ListView listViewKetCuoiKhaDungCopper, ListView listViewKetCuoiKhaDungFiber) { ObservableCollection<DanhSachKetCuoi> fiber = new ObservableCollection<DanhSachKetCuoi>(); ObservableCollection<DanhSachKetCuoi> copper = new ObservableCollection<DanhSachKetCuoi>(); foreach (var item in Initial.dataGetTramVienThong[0].DanhSachKetCuoi) { string temp = ""; if (item.SPLITTER != "") temp = "(" + item.SPLITTER + ") "; if (item.FType == "0") copper.Add(new DanhSachKetCuoi() { CABI_NAME = item.CABI_NAME, //1A KC = temp + item.KC + " mét", //1B CABI_ADDR = item.CABI_ADDR, DungLuong = item.DungLuong, //2B DLCapDen = Initial.dataGetTramVienThong[0].TramVTNAME + " Cáp đến:" + item.DLCapDen + " đôi", //3A SoThueBao = item.SoThueBao + " tb", //3B FType = "copper50x50.jpg", HoTen = item.HoTen, SoDienThoai = item.SoDienThoai }); else { fiber.Add(new DanhSachKetCuoi() { CABI_NAME = item.CABI_NAME, //1A KC = temp + item.KC + " mét", //1B CABI_ADDR = item.CABI_ADDR, DungLuong = item.DungLuong, //2B DLCapDen = Initial.dataGetTramVienThong[0].TramVTNAME + " Cáp đến:" + item.DLCapDen + " đôi", //3A SoThueBao = item.SoThueBao + " tb", //3B FType = "fiber50x50.jpg", HoTen = item.HoTen, SoDienThoai = item.SoDienThoai }); } } _listViewKetCuoiKhaDungCopper = listViewKetCuoiKhaDungCopper; _listViewKetCuoiKhaDungCopper.ItemsSource = copper; _listViewKetCuoiKhaDungCopper.ItemTapped += ListViewKetCuoiKhaDungCopperOnItemTapped; _listViewKetCuoiKhaDungFiber = listViewKetCuoiKhaDungFiber; _listViewKetCuoiKhaDungFiber.ItemsSource = fiber; _listViewKetCuoiKhaDungFiber.ItemTapped += ListViewKetCuoiKhaDungFiberOnItemTapped; } private async void ListViewKetCuoiKhaDungFiberOnItemTapped(object sender, ItemTappedEventArgs itemTappedEventArgs) { DanhSachKetCuoi data = (DanhSachKetCuoi)itemTappedEventArgs.Item; var answer = await Application.Current.MainPage.DisplayAlert("Hỏi ý kiến kỹ thuật", "Anh" + data.HoTen + "\n SĐT: " + data.SoDienThoai + "\n Bạn có muốn gọi không?", "Yes", "No"); if (answer) { Device.OpenUri(new Uri("tel:" + data.SoDienThoai)); } } //ListViewKetCuoiKhaDungCopperOnItemTapped private async void ListViewKetCuoiKhaDungCopperOnItemTapped(object sender, ItemTappedEventArgs itemTappedEventArgs) { DanhSachKetCuoi data = (DanhSachKetCuoi)itemTappedEventArgs.Item; var answer = await Application.Current.MainPage.DisplayAlert("Hỏi ý kiến kỹ thuật", "Anh"+ data.HoTen +"\n SĐT: "+data.SoDienThoai + "\n Bạn có muốn gọi không?", "Yes", "No"); if (answer) { Device.OpenUri(new Uri("tel:"+ data.SoDienThoai)); } } } }
namespace BettingSystem.Domain.Betting.Factories.Bets { using Common; using Models.Bets; using Models.Matches; public interface IBetFactory : IFactory<Bet> { IBetFactory WithMatch(Match match); IBetFactory WithAmount(decimal amount); IBetFactory WithPrediction(Prediction prediction); } }
namespace CarDealer.Models.ViewModels.Sales { using Cars; public class SaleViewModel { public CarViewModel Car { get; set; } public string Customer { get; set; } public decimal Price { get; set; } public double DiscountPrice { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; namespace TownSuite.DapperExtras { internal class TsExtrasSqliteAdapter : TsExtrasCommonSqlGen { public override IEnumerable<T> GetWhere<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateGetWhereSql<T>(param, startQoute: "\"", endQoute: "\""); return connection.Query<T>(sql, param, transaction, commandTimeout: commandTimeout); } public override T GetWhereFirstOrDefault<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateGetWhereSql<T>(param, startQoute: "\"", endQoute: "\""); return connection.QueryFirstOrDefault<T>(sql, param, transaction, commandTimeout: commandTimeout); } public override async Task<IEnumerable<T>> GetWhereAsync<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateGetWhereSql<T>(param, startQoute: "\"", endQoute: "\""); return await connection.QueryAsync<T>(sql, param, transaction, commandTimeout: commandTimeout); } public override async Task<T> GetWhereFirstOrDefaultAsync<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateGetWhereSql<T>(param, startQoute: "\"", endQoute: "\""); return await connection.QueryFirstOrDefaultAsync<T>(sql, param, transaction, commandTimeout: commandTimeout); } public override void UpdateWhere<T>(IDbConnection connection, object setParam, object whereParam, IDbTransaction transaction = null, int? commandTimeout = null) { var result = GenerateUpdateWhereSql<T>(setParam, whereParam, startQoute: "\"", endQoute: "\""); connection.Execute(result.sql, result.parameters, transaction, commandTimeout: commandTimeout); } public override async Task UpdateWhereAsync<T>(IDbConnection connection, object setParam, object whereParam, IDbTransaction transaction = null, int? commandTimeout = null) { var result = GenerateUpdateWhereSql<T>(setParam, whereParam, startQoute: "\"", endQoute: "\""); await connection.ExecuteAsync(result.sql, result.parameters, transaction, commandTimeout: commandTimeout); } public override void DeleteWhere<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateDeleteWhereSql<T>(param, startQoute: "\"", endQoute: "\""); connection.Execute(sql, param, transaction, commandTimeout: commandTimeout); } public override async Task DeleteWhereAsync<T>(IDbConnection connection, object param, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = GenerateDeleteWhereSql<T>(param, startQoute: "\"", endQoute: "\""); await connection.ExecuteAsync(sql, param, transaction, commandTimeout: commandTimeout); } public override int UpSert<T>(IDbConnection connection, T setParam, object whereParam, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = UpSertSqlGeneration<T>(setParam, whereParam, startQoute: "\"", endQoute: "\""); var param = TsExtrasCommonSqlGen.Merge(whereParam, setParam); return connection.Execute(sql.ToString(), param, transaction, commandTimeout: commandTimeout); } public override async Task<int> UpSertAsync<T>(IDbConnection connection, T setParam, object whereParam, IDbTransaction transaction = null, int? commandTimeout = null) { var sql = UpSertSqlGeneration<T>(setParam, whereParam, startQoute: "\"", endQoute: "\""); var param = TsExtrasCommonSqlGen.Merge(setParam, whereParam); return await connection.ExecuteAsync(sql.ToString(), param, transaction, commandTimeout: commandTimeout); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace STLStruct { public class Model { //three points to be a facet public List<Facet> facets = new List<Facet>(); public string name; } }
using System; using UnityEngine.Events; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// None generic Unity Event of type `ColorPair`. Inherits from `UnityEvent&lt;ColorPair&gt;`. /// </summary> [Serializable] public sealed class ColorPairUnityEvent : UnityEvent<ColorPair> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mask : MonoBehaviour { private float midLineAngle; private float coneAngle; private bool isAcuteAngle; //Used to tell whether the wedge is greater than 180 degrees or not for the purpose of masking // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using SSGui; namespace SpreadsheetGUI { public partial class SpreadsheetWindow : Form, ISpreadsheetView { public event Func<bool> HandleClose; public event Action<string> CellValueBoxTextComplete; public event Action<int, int> CellSelectionChange; public event Action CreateNew; public event Action HandleOpen; public event Action HandleSave; public event Action HandleSaveAs; public event Action HandleHelp; public event Action HandleUndo; public SpreadsheetWindow() { InitializeComponent(); SpreadsheetData.SelectionChanged += SpreadsheetDataOnSelectionChanged; CellValueBox.KeyDown += CellValueBoxOnKeyDown; CellValueBox.Leave += CellValueBoxOnLostFocus; undoToolStripMenuItem.Click += DoUndo; } private void DoUndo(object sender, EventArgs eventArgs) { HandleUndo?.Invoke(); } private void CellValueBoxOnLostFocus(dynamic sender, EventArgs eventArgs) { CellValueBoxTextComplete?.Invoke(sender.Text); } private void CellValueBoxOnKeyDown(dynamic sender, KeyEventArgs keyEventArgs) { if (keyEventArgs.KeyCode == Keys.Enter) { CellValueBoxTextComplete?.Invoke(sender.Text); } } public string InfoBarText { set { DataBar.Text = value; } } public Color InfoBarColor { set { DataBar.ForeColor = value; } } public string SelectedCellText { set { SelectedCellName.Text = value; } } public string CellValueBoxText { set { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (CellValueBox.InvokeRequired) { Invoke(new Action<string>(s => { CellValueBoxText = s; }), value); } else { CellValueBox.Text = value; } } } public void SetSelection(int col, int row) { SpreadsheetData.SetSelection(col, row); } public void UpdateCell(int col, int row, string value) { SpreadsheetData.SetValue(col, row, value); } public void DoClose() { Close(); } public void SetTitle(string spreadsheetName) { Text = spreadsheetName; } public void CellBackgroundColor(int col, int row, Color color) { SpreadsheetData.SetCellBackground(col, row, color); } private void SpreadsheetDataOnSelectionChanged(SpreadsheetPanel sender) { int col, row; sender.GetSelection(out col, out row); CellSelectionChange?.Invoke(col, row); } private void SpreadsheetWindow_OnClose(object sender, CancelEventArgs e) { //Confirm closing if there is potential data loss. if (HandleClose != null) e.Cancel = HandleClose.Invoke(); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { CreateNew?.Invoke(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { HandleOpen?.Invoke(); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { HandleSaveAs?.Invoke(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { HandleSave?.Invoke(); } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { HandleHelp?.Invoke(); } private void SelectedSheet_Click(object sender, EventArgs e) { } } }
using System.Collections.Generic; namespace tyrone_sortingbasics { class StuSortLastFirstCourseID : IComparer<Student> { public int Compare(Student x, Student y) { if (x.LastName.ToUpper() == y.LastName.ToUpper()) return x.FirstName.ToUpper().CompareTo(y.FirstName.ToUpper()); else if (x.FirstName.ToUpper() == y.FirstName.ToUpper()) return x.CourseID.ToUpper().CompareTo(y.CourseID.ToUpper()); return x.LastName.ToUpper().CompareTo(y.LastName.ToUpper()); } } }
using System.Threading.Tasks; using Abp.Application.Services; using dgPower.PKMS.Sessions.Dto; namespace dgPower.PKMS.Sessions { public interface ISessionAppService : IApplicationService { Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations(); } }
using System.Collections; using GameManager; using UnityEngine; public class PlayerHealth : MonoBehaviour { public delegate void OnHealthChangedDelegate(); public OnHealthChangedDelegate onHealthChangedCallback; private int startingHealth; // The amount of health the player starts the game with. [SerializeField] private int currentHealth; // The current health the player has. private int maxHealth = 4; public AudioClip deathClip; public AudioClip damageClip; public AudioClip healingClip; private GameObject BGM; // (by Sabin Kim) the BGM GameObject private Animator anim; // Reference to the Animator component. private AudioSource playerAudio; // Reference to the AudioSource component. private PlayerMovement playerMovement; // Reference to the player's movement. private bool isDead; private int playerLives; private AudioSource BGMSource; // (by Sabin Kim) AudioSource of BGM GameObject private ParticleSystem particlesDeath; public float Health { get { return currentHealth; } } public float MaxHealth { get { return maxHealth; } } #region Sigleton private static PlayerHealth instance; public static PlayerHealth Instance { get { if (instance == null) instance = FindObjectOfType<PlayerHealth>(); return instance; } } #endregion private void Awake() { // Setting up the references. anim = GetComponentInChildren<Animator>(); playerAudio = GetComponent<AudioSource>(); playerMovement = GetComponent<PlayerMovement>(); // (by Sabin Kim) Find BGM GameObject (which wears "BackgroundMusic" Tag) and get its AudioSource component startingHealth = GameManager_Master.Instance.playerHealth; // Set the initial health of the player. currentHealth = startingHealth; } private void Start() { playerLives = GameManager_Master.Instance.playerLives; if (onHealthChangedCallback != null) onHealthChangedCallback.Invoke(); BGM = GameObject.FindGameObjectWithTag("BackgroundMusic"); if (BGM) { BGMSource = BGM.GetComponent<AudioSource>(); } else { Debug.LogWarning("No death music found"); } particlesDeath = GetComponentInChildren<ParticleSystem>(); } public void AddHealth() { if (currentHealth < maxHealth) { currentHealth += 1; if (healingClip != null) { playerAudio.clip = healingClip; playerAudio.Play(); } if (onHealthChangedCallback != null) onHealthChangedCallback.Invoke(); } } public void GiveLife() { playerLives++; GameManager_Master.Instance.playerLives = playerLives; GameManager_Master.Instance.CallLivesUI(); if (healingClip != null) { playerAudio.clip = healingClip; playerAudio.Play(); } } private void Update() { } public void TakeDamage() { if (!anim.GetCurrentAnimatorStateInfo(0).IsName("Damage")) { currentHealth--; ClampHealth(); if (currentHealth <= 0 && !isDead) { // ... it should die. Death(); } if (damageClip != null && !isDead) { playerAudio.clip = damageClip; playerAudio.Play(); anim.SetTrigger("Damage"); } } } public void Death() { isDead = true; anim.SetTrigger("Die"); currentHealth = 0; ClampHealth(); if (deathClip != null) { BGM = GameObject.FindGameObjectWithTag("BackgroundMusic"); if (BGM) { BGMSource = BGM.GetComponent<AudioSource>(); } BGMSource.Stop(); // (by Sabin Kim) when Whale dies, stop level BGM playerAudio.clip = deathClip; playerAudio.Play(); } StartCoroutine(DestroyPlayer()); playerMovement.enabled = false; playerLives--; if (playerLives >= 0) { GameManager_Master.Instance.CallPlayerDied(); } else { GameManager_Master.Instance.CallEventGameOver(); } } IEnumerator DestroyPlayer() { yield return new WaitForSeconds(2); if (particlesDeath) { Debug.Log("player"); particlesDeath.transform.parent = null; particlesDeath.Play(); Destroy(particlesDeath.gameObject, particlesDeath.main.duration); } Destroy(gameObject); } private void ClampHealth() { currentHealth = Mathf.Clamp(currentHealth, 0, startingHealth); if (onHealthChangedCallback != null) onHealthChangedCallback.Invoke(); } public bool PlayerAlive() { return !isDead; } }
using System; using Grasshopper.Kernel; using Grasshopper.Kernel.Parameters; using Grasshopper.Kernel.Types; using PterodactylEngine; using ShapeDiver.Public.Grasshopper.Parameters; using ShapeDiver.Public.Grasshopper.Parameters.SDMLDoc; namespace Pterodactyl { public class ExportMDComponent : GH_Component { /// <summary> /// Initializes a new instance of the ExportMDComponent class. /// </summary> public ExportMDComponent() : base("Export MD", "MD", "Exports an MD file along with a folder containing the referenced images. Assigning a local path for this component will only work when running locally (Local path will be ignored on the SHapeDiver platform).", "Pterodactyl", "Report") { } public override bool IsBakeCapable => false; public override GH_Exposure Exposure => GH_Exposure.secondary; /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddParameter(new ShapeDiverMLDocParam(), "Report", "Report", "Report to export", GH_ParamAccess.item); pManager.AddParameter(new Param_FilePath(), "File Path", "Path", "Path where your file(s) will be saved. Existing files will be overwritten.", GH_ParamAccess.item); this.Params.Input[1].Optional = true; } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddParameter(new ShapeDiverMLDocParam(), "Report", "Report", "Exported report", GH_ParamAccess.item); } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { if (DA.Iteration > 0) return; bool CloudMode = true; try { MarkdownDocument md = null; if (!DA.GetData(0, ref md)) return; if (!Utils.IsRunningOnWindowsServer) { GH_String fpath = new GH_String(); if (DA.GetData(1, ref fpath)) { if (fpath.Value != null && fpath.Value != string.Empty) { CloudMode = false; md.WriteDocumentToFile(fpath.Value, true); } } } DA.SetData(0, md); if (CloudMode) this.Message = "Cloud Mode"; else this.Message = string.Empty; } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Exception Caught: " + ex.Message); } } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon { get { //You can add image files to your project resources and access them like this: // return Resources.IconForThisComponent; return Properties.Resources.exportMD; } } /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("cef3d8f9-96c1-43ed-a64a-3de6d38b4891"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Integer.Api.Models; using Integer.Api.Infra.Raven; using Integer.Api.Infra.AutoMapper; namespace Integer.Api.Controllers { public class ParoquiaController : BaseController { [ActionName("Locais")] public IEnumerable<ItemModel> GetLocais() { var locais = RavenSession.ObterLocais(); return locais.MapTo<ItemModel>(); } } }
using System; using System.Collections.Generic; using System.Linq; using SMARTplanner.Data.Contracts; using SMARTplanner.Entities.Domain; using SMARTplanner.Logic.Contracts; namespace SMARTplanner.Logic.Exact { public class AccessService : IAccessService { private readonly ISmartPlannerContext _context; public AccessService(ISmartPlannerContext ctx) { _context = ctx; } public IEnumerable<Project> GetAccessibleProjects(string userId) { return _context.ProjectUserAccesses .Where(pu => pu.UserId.Equals(userId)) .Select(pu => pu.Project); } public IEnumerable<Issue> GetAccessibleIssues(string userId) { return _context.ProjectUserAccesses .Where(pu => pu.UserId.Equals(userId)) .SelectMany(pu => pu.Project.Issues); } public ProjectUserAccess GetAccessByProject(long projectId, string userId) { return _context.ProjectUserAccesses .SingleOrDefault(pu => pu.UserId.Equals(userId) && pu.ProjectId == projectId); } public ProjectUserAccess GetAccessByIssue(Issue issue, string userId) { return _context.ProjectUserAccesses .SingleOrDefault(pu => pu.ProjectId == issue.Project.Id && pu.UserId.Equals(userId)); } public ProjectUserAccess GetAccessByWorkItem(WorkItem item, string userId) { return _context.ProjectUserAccesses .SingleOrDefault(pu => pu.ProjectId == item.Issue.ProjectId && pu.UserId.Equals(userId)); } public ProjectUserAccess GetAccessByReport(Report report, string userId) { return _context.ProjectUserAccesses .SingleOrDefault(pu => pu.ProjectId == report.Issue.ProjectId && pu.UserId.Equals(userId)); } public void GrantAccess(ProjectUserAccess grantedAccess, string grantorId) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; namespace Soft_arch_encapsulation { public class Employee { private string _firstName; public String FirstName{get{ return _firstName;} set{if (value == null){ throw new ArgumentException("First Name is " + REQ_MESG); } _firstName = value;}} private string _lastName; public String LastName{get{ return _lastName;} set{if (value == null){ throw new ArgumentException("Last Name is " + REQ_MESG); } _lastName = value;}} private string _ssn; public String ssn{get{ return _ssn;} set{if (value == null || value.Length < ssnMin || value.Length > ssnMax ){ throw new ArgumentException("ssn is" + REQ_MESG + " and either " + ssnMin + " or " + ssnMax +" characters."); } _ssn = value;}} public const int ssnMin = 9; public const int ssnMax = 11; public const string REQ_MESG = " is manditory"; public const string NEWLINE = "\n"; public Boolean metWithHr {get; set;} public Boolean metDeptStaff{get; set;} public Boolean reviewedDeptPolicies{get; set;} public Boolean movedIn{get; set;} private string _cubeId; public string CubeId{get{return _cubeId;}set{if(value == null){ throw new ArgumentException("Cube Id is " + REQ_MESG); } _cubeId = value;}} private DateTime _orientationDate; private EmployeeReportService reportService = new EmployeeReportService(); public DateTime OrientationDate{ get{return _orientationDate;} set{_orientationDate = new DateTime();} } public void doFirstTimeOrientation(String cubeId) { meetWithHRForBenefitAndSalaryInfo(); meetDepartmentStaff(); reviewDeptPolicies(); moveIntoCubicle(cubeId); } private void meetWithHRForBenefitAndSalaryInfo(){ metWithHr = true; reportService.addData(_firstName + " " + _lastName + " met with HR on " + OrientationDate.ToString("D") + NEWLINE); } private void meetDepartmentStaff() { metDeptStaff = true; reportService.addData(_firstName + " " + _lastName + " met with dept staff on " + OrientationDate.ToString("D") + NEWLINE); } public void reviewDeptPolicies() { reviewedDeptPolicies = true; reportService.addData(_firstName + " " + _lastName + " reviewed dept policies on " + OrientationDate.ToString("D") + NEWLINE); } public void moveIntoCubicle(String cubeId) { CubeId = cubeId; movedIn = true; reportService.addData(_firstName + " " + _lastName + " moved into cubicle " + cubeId + " on " + OrientationDate.ToString("D") + NEWLINE); } public void printReport() { reportService.outputReport(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AbiokaScrum.Api.Entities { public class UserInfo { public string Email { get; set; } public string ProviderToken { get; set; } public AuthProvider Provider { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } public Guid Id { get; set; } public string Initials { get; set; } } }
using UnityEngine; using System.Collections; public class TurretProjectile : MonoBehaviour { //the projectile ejected from TurretEmitter private float speed = 15f; void Update () { this.transform.Translate(Vector2.up * speed * Time.deltaTime); } void OnTriggerEnter2D (Collider2D coll){ if (coll.gameObject.tag == "Enemy" || coll.gameObject.tag == "Bound"){ Destroy (gameObject); } } }
using System; using System.Collections.Generic; using System.Text; namespace Microsoft.ServiceFabric.Data.Collections { public interface IReliableCollection<T> : IReliableState { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace API.Model { [Table("Message")] public class Message { [Required] [Key] public int Id { get; set; } [Required] [MaxLength(8000)] public string Contenu { get; set; } [Required] [MaxLength(2000)] public string Intitule { get; set; } [Required] public DateTime DateTime { get; set; } [Required] public bool Status { get; set; } [ForeignKey("IdPersonne")] public Inscrit Personne { get; set; } [ForeignKey("IdTechnologie")] public Technologie Technologie { get; set; } [Required] [ForeignKey("IdDiscussion")] [NotMapped] public Discussion Discussion { get; set; } [NotMapped] public int NombreDIntervention { get; set; } public int IdTechnologie { get; set; } public int IdPersonne { get; set; } } }
using Payment.Domain.Enumerations; using Payment.Domain.ValueObjects; using System.Collections.Generic; namespace Payment.Domain.Models { public class PaymentRequest : ModelBase<long> { public PaymentRequest() { States = new HashSet<PaymentRequestState>(); } public CreditCard Card { get; set; } public decimal Amount { get; set; } public bool IsDeleted { get; set; } public PaymentState CurrentState { get; set; } public ICollection<PaymentRequestState> States { get; } } }
using System; namespace TemplateMethod { public abstract class Abstract { public abstract void PrimitivOperation1(); public abstract void PrimitivOperation2(); public void TemplateMethod() { PrimitivOperation1(); PrimitivOperation2(); Console.WriteLine(""); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace KartObjects.Entities.Documents { public class InvoiceGoodSpecRecord : DocGoodSpecRecord { private List<InvoiceAssortSpecRecord> invoiceAssortSpecRecords; private string nameAss; [DBIgnoreReadParam] [DBIgnoreAutoGenerateParam] public List<InvoiceAssortSpecRecord> DocAssortSpecRecords { get { if (invoiceAssortSpecRecords == null) { if (OnNeedInvoiceAssortSpecRecordsList != null) invoiceAssortSpecRecords = OnNeedInvoiceAssortSpecRecordsList(this); } return invoiceAssortSpecRecords; } set { invoiceAssortSpecRecords = value; } } [DisplayName("Количество")] public override double Quantity { get { if (invoiceAssortSpecRecords == null) return _quantity; return invoiceAssortSpecRecords.Sum(q => q.Quantity); } set { _quantity = value; } } /// <summary> /// Сумма с наценкой /// </summary> [DisplayName("Сумма с наценкой")] [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public decimal MarginSum { get { return MarginPrice*Convert.ToDecimal(Quantity); } set { if (Quantity != 0) MarginPrice = Convert.ToDecimal(Convert.ToDouble(value)/Quantity); } } /// <summary> /// Наименование ассортиментной позиции /// </summary> [DisplayName("Наименование ассортиментной позиции")] [DBIgnoreAutoGenerateParam] //[DBIgnoreReadParam] public string NameAssortment { get { return nameAss; } set { nameAss = value; } } [DisplayName("% наценки")] [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public double MarginPercent { get { return Price == 0 ? 0 : Convert.ToDouble((MarginPrice - Price)/Price); } set { MarginPrice = Math.Round(Price + Price*Convert.ToDecimal(value/100), 2); } } [DisplayName("Наименование страны производителя")] [DBIgnoreAutoGenerateParam] public string CountryName { get; set; } /// <summary> /// Признак того что позиция меняет прайс /// </summary> [DBIgnoreAutoGenerateParam] public bool ChangingPrice { get; set; } /// <summary> /// Срок годности /// </summary> [DisplayName("Срок годности")] public DateTime? ExpireDate { get; set; } public static event OnNeedLoadDelegate<InvoiceGoodSpecRecord, List<InvoiceAssortSpecRecord>> OnNeedInvoiceAssortSpecRecordsList; } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Threading.Tasks; using FamousQuoteQuiz.Api.Middlewares; using FamousQuoteQuiz.Api.Models; using FamousQuoteQuiz.Api.Models.Common; using FamousQuoteQuiz.Api.Models.Common.Contracts; using FamousQuoteQuiz.Api.Models.ValidationModels; using FamousQuoteQuiz.Api.Policies; using FamousQuoteQuiz.Data.Entity.Context; using FamousQuoteQuiz.Data.Entity.Repositories; using FamousQuoteQuiz.Data.EntityContracts; using FamousQuoteQuiz.Data.EntityModels; using FamousQuoteQuiz.Data.ServiceContracts; using FamousQuoteQuiz.Domain; using FluentValidation; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using FamousQuoteQuiz.Api.Helpers; namespace FamousQuoteQuiz.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //var mvcBuilder = services.AddMvc(options => //{ // // Force authorization by default. // var policy = new AuthorizationPolicyBuilder() // .RequireAuthenticatedUser() // .Build(); // options.Filters.Add(new AuthorizeFilter(policy)); //}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); //mvcBuilder.AddControllersAsServices(); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Version = "v1", Title = "Fqq Api V1" }); //x.SwaggerDoc("v2", new Microsoft.OpenApi.Models.OpenApiInfo //{ // Version = "v2", // Title = "Fqq Api V2" //}); }); services.AddApiVersioning(x => { x.DefaultApiVersion = new ApiVersion(1, 0); x.AssumeDefaultVersionWhenUnspecified = true; x.ReportApiVersions = true; }); services.AddMvcCore() //.AddAuthorization(options => //{ // options.AddPolicy("PermissionsPolicy", policy => policy.Requirements.Add(new PermissionRequirement())); //}) ; //services.AddAuthentication("Bearer") // .AddIdentityServerAuthentication(options => // { // options.Authority = "http://localhost:33235"; // options.ApiName = "Api Auth"; // }); services.AddScoped<IUserService, UserService>(); services.AddScoped<IQuoteService, QuoteService>(); services.RegisterValidators(); services.RegisterRepositories(); services.AddDbContext<BaseDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("FamousQuoteQuizContext"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(x => { x.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); x.SwaggerEndpoint("/swagger/v2/swagger.json", "v2"); }); app.UseMiddleware<ErrorHandlingMiddleware>(); app.UseRouting(); //app.UseAuthentication(); //app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }
using System; using System.Collections.Generic; namespace gView.Framework.Geometry { /// <summary> /// A orderd collection of points. /// </summary> public sealed class MultiPoint : PointCollection, IMultiPoint, ITopologicalOperation { public MultiPoint() : base() { } public MultiPoint(List<IPoint> points) : base(points) { } public MultiPoint(IPointCollection pColl) : base(pColl) { } #region IGeometry Member /// <summary> /// The type of the geometry (Multipoint) /// </summary> public gView.Framework.Geometry.GeometryType GeometryType { get { return GeometryType.Multipoint; } } public int VertexCount => base.PointCount; public void Clean(CleanGemetryMethods methods, double tolerance = 1e-8) { if(methods.HasFlag(CleanGemetryMethods.IdentNeighbors)) { base.RemoveIdentNeighbors(tolerance); } } public bool IsEmpty() => this.PointCount == 0; #endregion #region ICloneable Member public object Clone() { return new MultiPoint(_points); } #endregion #region ITopologicalOperation Member public IPolygon Buffer(double distance) { if (distance <= 0.0) { return null; } List<IPolygon> polygons = new List<IPolygon>(); for (int i = 0; i < this.PointCount; i++) { IPolygon buffer = gView.Framework.SpatialAlgorithms.Algorithm.PointBuffer(this[i], distance); if (buffer == null) { continue; } polygons.Add(buffer); } //return gView.Framework.SpatialAlgorithms.Algorithm.MergePolygons(polygons); return gView.Framework.SpatialAlgorithms.Algorithm.FastMergePolygon(polygons, null, null); } public void Clip(IEnvelope clipper) { throw new Exception("The method or operation is not implemented."); } public void Intersect(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Difference(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void SymDifference(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Union(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Clip(IEnvelope clipper, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Intersect(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Difference(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void SymDifference(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Union(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } #endregion } }
using System; namespace ЗаполнениеДвумерногоМассива { class Program { static void Main(string[] args) { int[,] myArray = new int[10, 6]; Random random = new Random(); for (int i = 0; i < myArray.GetLength(0); i++) { for (int j = 0; j < myArray.GetLength(1); j++) { myArray[i, j] = random.Next(); } } for (int i = 0; i < myArray.GetLength(0); i++) { for (int j = 0; j < myArray.GetLength(1); j++) { Console.Write(myArray[i, j] + "\t"); } Console.WriteLine(" "); } } } }
using System; public class House { public static void Main() { int n = int.Parse(Console.ReadLine()); Console.Write(new string('.', n / 2)); Console.Write(new string('*', 1)); Console.WriteLine(new string('.', n / 2)); int outsideCounter = n / 2 - 1; int insideCounter = 1; while (outsideCounter != 0) { Console.Write(new string('.', outsideCounter)); Console.Write(new string('*', 1)); Console.Write(new string('.', insideCounter)); Console.Write(new string('*', 1)); Console.WriteLine(new string('.', outsideCounter)); outsideCounter--; insideCounter += 2; } Console.WriteLine(new string('*', n)); int wallDistance = n / 4; for (int i = n / 2 + 1; i < n - 1; i++) { Console.Write(new string('.', wallDistance)); Console.Write(new string('*', 1)); Console.Write(new string('.', n - 2 * wallDistance - 2)); Console.Write(new string('*', 1)); Console.WriteLine(new string('.', wallDistance)); } Console.Write(new string('.', wallDistance)); Console.Write(new string('*', n - 2 * wallDistance)); Console.WriteLine(new string('.', wallDistance)); } }
using System.Collections; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.AI; using UnityEngine.Events; public class Door : MonoBehaviour { [SerializeField] private QuestionData _question = null; [SerializeField] private TextMeshPro _questionLabelFront = null; [SerializeField] private TextMeshPro _questionLabelBack = null; public QuestionData QuestionData => _question; public UnityAction<Door, Navigator> OnEnterDoor { get; set; } = null; public bool Questioned { get; set; } = false; private List<Navigator> _navigators = new List<Navigator>(); private void Start() { _questionLabelFront.text = _question.Question; _questionLabelBack.text = _question.Question; } private void OnTriggerEnter(Collider other) { if(other.TryGetComponent(out NavMeshAgent agent)) { Navigator navigator = FindObjectsOfType<Navigator>().First((n) => n.ContainsAgent(agent)); if (!Questioned) { Questioned = true; OnEnterDoor?.Invoke(this, navigator); } _navigators.Add(navigator); navigator.Active = false; } } private void OnDestroy() { foreach (var navigator in _navigators) navigator.Active = true; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace yemeksepeti { public partial class UserControl5 : UserControl { anasayfa anasayfa; string ad; int f; public UserControl5(string isim,int fiyat,anasayfa a) { InitializeComponent(); label1.Text = isim; label2.Text += fiyat; anasayfa = a; ad = isim; f = fiyat; } private void button1_Click(object sender, EventArgs e) { anasayfa.SiparisEkle(ad, f); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChampionsOfForest.Enemies { class EnemyCorpse : DamageCorpse { protected override void Start() { base.Start(); } } }
using Cs_Gerencial.Dominio.Entities; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Gerencial.Infra.Data.EntityConfig { public class BancosConfig: EntityTypeConfiguration<Bancos> { public BancosConfig() { HasKey(c => c.BancosId); Property(c => c.Codigo) .HasMaxLength(10); Property(c => c.Nome) .HasMaxLength(60); Property(c => c.Agencia) .HasMaxLength(20); Property(c => c.Conta) .HasMaxLength(20); } } }
using gView.Framework.Carto; using gView.Framework.Carto.UI; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.Globalisation; using gView.Framework.Symbology; using gView.Framework.Symbology.UI; using gView.Framework.Sys.UI; using gView.Framework.Sys.UI.Extensions; using gView.Framework.system; using gView.Framework.UI.Dialogs; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace gView.Framework.UI.Controls { /// <summary> /// Zusammenfassung für TOCControl. /// </summary> public class TOCControl : System.Windows.Forms.UserControl, IDockableWindow { private System.ComponentModel.IContainer components; private object _contextItem; private System.Windows.Forms.TextBox _renameBox; private ToolStripMenuItem _menuItemInsertGroup, _menuItemMoveToGroup, _menuItemSplitMultiLayer, _menuItemRemoveDatasetElement, _menuItemLockLayer; private ImageList imageList1; private ContextMenuStrip menuStripMap; private ToolStripMenuItem toolStripMenuItem1; private ToolStripMenuItem toolStripMapActivate; private ToolStripMenuItem toolStripMapNewMap; private ToolStripMenuItem toolStripMapDeleteMap; private ToolStripSeparator toolStripSeparator2; private ToolStripSeparator toolStripSeparator3; private ImageList iLMenuItem; private ContextMenuStrip menuStripFeatureLayer; private ToolStripMenuItem toolStripMenuUnlock; private ToolStripSeparator toolStripSeparator4; private ContextMenuStrip menuStripGroupLayer; private ToolStripSeparator toolStripSeparator5; private ToolStripMenuItem menuApply; private ToolStripMenuItem menuGroupApplyVisibility; private ToolStripMenuItem menuGroupApplyScales; private ScrollingListBox list; private bool _readonly = true, _fullversion = false; private ToolStripMenuItem debuggingToolStripMenuItem; private ToolStripMenuItem menuUnreferencedLayers; private ContextMenuStrip contextMenuStripDataset; private ToolStripMenuItem connectionPropertiesToolStripMenuItem; private ToolStripSeparator toolStripSeparator1; List<IDatasetElementContextMenuItem> _contextMenuItems; public event EventHandler SelectionChanged = null; public TOCControl() { // Dieser Aufruf ist für den Windows Form-Designer erforderlich. InitializeComponent(); _menuItemInsertGroup = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.InsertGroup", "Insert Group"), iLMenuItem.Images[1]); _menuItemInsertGroup.Click += new EventHandler(this.clickInsertGroup); _menuItemMoveToGroup = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.MoveToGroup", "Move to Group"), iLMenuItem.Images[2]); _menuItemSplitMultiLayer = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.SpitLayerGroup", "Split LayerGroup")); _menuItemSplitMultiLayer.Click += new System.EventHandler(this.clickSplitMultiLayer); _menuItemRemoveDatasetElement = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.Remove", "Remove"), iLMenuItem.Images[0]); _menuItemRemoveDatasetElement.Click += new EventHandler(RemoveDatasetElement_Click); _menuItemLockLayer = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.LockLayer", "Lock Layer"), iLMenuItem.Images[3]); _menuItemLockLayer.Click += new EventHandler(LockLayer_Click); _renameBox = new TextBox(); _renameBox.Parent = list; _renameBox.Visible = false; _renameBox.BorderStyle = BorderStyle.FixedSingle; _renameBox.LostFocus += new EventHandler(renameBoxLeave); _renameBox.KeyPress += new KeyPressEventHandler(renameBoxKeyPress); _contextMenuItems = new List<IDatasetElementContextMenuItem>(); PlugInManager compMan = new PlugInManager(); foreach (var contextTypes in compMan.GetPlugins(Plugins.Type.IDatasetElementContextMenuItem)) { IDatasetElementContextMenuItem contextMenuItem = compMan.CreateInstance<IDatasetElementContextMenuItem>(contextTypes); if (contextMenuItem == null) { continue; } _contextMenuItems.Add(contextMenuItem); } _contextMenuItems.Sort(new DatasetContextMenuItemComparer()); LocalizedResources.GlobalizeMenuItem(menuStripGroupLayer); LocalizedResources.GlobalizeMenuItem(menuStripMap); LocalizedResources.GlobalizeMenuItem(connectionPropertiesToolStripMenuItem); this.list.CalcFontScaleFactor(); } async void LockLayer_Click(object sender, EventArgs e) { if (!(_contextItem is LayerItem)) { return; } ((LayerItem)_contextItem).TOCElement.LayerLocked = true; _iMapDocument.TemporaryRestore(); await BuildList(list.Items[list.Items.IndexOf(_contextItem) - 1]); } private void RemoveDatasetElement_Click(object sender, EventArgs e) { if (list.SelectedItems.Contains(_contextItem)) { List<object> items = new List<object>(); foreach (object item in list.SelectedItems) { items.Add(item); } foreach (object item in items) { RemoveDatasetElement(item); } } else { RemoveDatasetElement(_contextItem); } if (_iMapDocument != null && _iMapDocument.Application is IMapApplication) { ((IMapApplication)_iMapDocument.Application).RefreshActiveMap(DrawPhase.All); } _iMapDocument.TemporaryRestore(); } private void RemoveDatasetElement(object item) { if (item is LayerItem) { foreach (ILayer layer in ((LayerItem)item).TOCElement.Layers) { _iMapDocument.FocusMap.RemoveLayer(layer); } } else if (item is GroupItem) { foreach (ILayer layer in ((GroupItem)item).TOCElement.Layers) { _iMapDocument.FocusMap.RemoveLayer(layer); } } _iMapDocument.TemporaryRestore(); } async private void clickInsertGroup(object sender, System.EventArgs e) { if (_mode != TOCViewMode.Groups || _iMapDocument == null) { return; } if (_iMapDocument.FocusMap == null) { return; } GroupLayer gLayer = new GroupLayer(); gLayer.Title = "New Group"; ITOCElement parent = null; if (_contextItem != null) { if (_contextItem is GroupItem) { parent = ((GroupItem)_contextItem).TOCElement; } if (_contextItem is LayerItem) { parent = ((LayerItem)_contextItem).TOCElement.ParentGroup; } } if (parent != null && parent.Layers.Count == 1 && parent.Layers[0] is IGroupLayer) { gLayer.GroupLayer = parent.Layers[0] as IGroupLayer; } /* _iMapDocument.FocusMap.TOC.AddGroup( "New Group",parent); */ _iMapDocument.FocusMap.AddLayer(gLayer); await this.BuildList(null); } async private void clickMoveToGroup(object sender, System.EventArgs e) { if (!(sender is GroupMenuItem)) { return; } ITOCElement Group = ((GroupMenuItem)sender).TOCElement; foreach (object item in list.SelectedItems) { if ((item is LayerItem)) { _iMapDocument.FocusMap.TOC.Add2Group(((LayerItem)item).TOCElement, Group); } if ((item is GroupItem)) { _iMapDocument.FocusMap.TOC.Add2Group(((GroupItem)item).TOCElement, Group); } } _iMapDocument.TemporaryRestore(); await this.BuildList(null); } async private void clickSplitMultiLayer(object sender, System.EventArgs e) { if (!(_contextItem is LayerItem)) { return; } _iMapDocument.FocusMap.TOC.SplitMultiLayer(((LayerItem)_contextItem).TOCElement); _iMapDocument.TemporaryRestore(); await this.BuildList(null); } private void clickLayerContextItem(object sender, System.EventArgs e) { if (_iMapDocument == null) { return; } if (!(sender is LayerContextMenuItem)) { return; } if (((LayerContextMenuItem)sender).Tool == null) { return; } ((LayerContextMenuItem)sender).Tool.OnCreate(_iMapDocument); IDatasetElement layer = ((LayerContextMenuItem)sender).Layer; if (layer == null) { return; } IMap map = _iMapDocument[layer]; if (map == null) { return; } IDataset dataset = map[layer]; //if(dataset==null) return; ((LayerContextMenuItem)sender).Tool.OnEvent( layer, dataset); } private void clickMenuContextItem(object sender, System.EventArgs e) { if (_iMapDocument == null) { return; } if (!(sender is MapContextMenuItem)) { return; } if (((MapContextMenuItem)sender).Item == null) { return; } ((MapContextMenuItem)sender).Item.OnCreate(_iMapDocument); ((MapContextMenuItem)sender).Item.OnEvent(((MapContextMenuItem)sender).Map, _iMapDocument); } async private void connectionPropertiesToolStripMenuItem_Click(object sender, EventArgs e) { if (_iMapDocument != null && _iMapDocument.FocusMap != null && _contextItem is DatasetItem) { FormConnectionProperties dlg = new FormConnectionProperties(_iMapDocument.FocusMap, ((DatasetItem)_contextItem).Dataset); if (dlg.ShowDialog() == DialogResult.OK) { _iMapDocument.TemporaryRestore(); await this.BuildList(null); } } } #region Eigenschaften private IMapDocument _iMapDocument; private System.Windows.Forms.ImageList iList; private TOCViewMode _mode = TOCViewMode.Groups; public IMapDocument GetMapDocument() { return _iMapDocument; } async public Task SetMapDocumentAsync(IMapDocument value) { if (_iMapDocument == value) { return; } _iMapDocument = value; if (value == null) { return; } if (_iMapDocument is IMapDocumentEvents) { ((IMapDocumentEvents)_iMapDocument).LayerAdded += new LayerAddedEvent(_iMapDocument_LayerAdded); ((IMapDocumentEvents)_iMapDocument).LayerRemoved += new LayerRemovedEvent(_iMapDocument_LayerRemoved); ((IMapDocumentEvents)_iMapDocument).MapAdded += new MapAddedEvent(_iMapDocument_MapAdded); ((IMapDocumentEvents)_iMapDocument).MapDeleted += new MapDeletedEvent(_iMapDocument_MapDeleted); } //LicenseTypes lt = _iMapDocument.Application.ComponentLicenseType("gview.desktop;gview.map"); //if (lt == LicenseTypes.Express || lt == LicenseTypes.Licensed) //{ // _readonly = false; // _fullversion = true; //} //else //{ // _readonly = true; // _fullversion = false; //} if (_iMapDocument.Application is IMapApplication) { ((IMapApplication)_iMapDocument.Application).AfterLoadMapDocument += new AfterLoadMapDocumentEvent(_iMapDocument_AfterLoadMapDocument); _readonly = ((IMapApplication)_iMapDocument.Application).ReadOnly; } if (_iMapDocument is IMapDocumentEvents) { ((IMapDocumentEvents)_iMapDocument).AfterSetFocusMap += new AfterSetFocusMapEvent(_iMapDocument_AfterSetFocusMap); } await BuildList(null); } public TOCViewMode TocViewMode { get { return _mode; } set { _mode = value; if (_mode == TOCViewMode.Groups && _readonly == false) { if (!menuStripFeatureLayer.Items.Contains(_menuItemInsertGroup)) { menuStripFeatureLayer.Items.Add(_menuItemInsertGroup); } if (!menuStripFeatureLayer.Items.Contains(_menuItemMoveToGroup)) { menuStripFeatureLayer.Items.Add(_menuItemMoveToGroup); } if (!menuStripFeatureLayer.Items.Contains(_menuItemRemoveDatasetElement)) { menuStripFeatureLayer.Items.Add(_menuItemRemoveDatasetElement); } if (!menuStripFeatureLayer.Items.Contains(_menuItemLockLayer)) { menuStripFeatureLayer.Items.Add(_menuItemLockLayer); } } else { if (menuStripFeatureLayer.Items.Contains(_menuItemInsertGroup)) { menuStripFeatureLayer.Items.Remove(_menuItemInsertGroup); } if (menuStripFeatureLayer.Items.Contains(_menuItemMoveToGroup)) { menuStripFeatureLayer.Items.Remove(_menuItemMoveToGroup); } if (menuStripFeatureLayer.Items.Contains(_menuItemRemoveDatasetElement)) { menuStripFeatureLayer.Items.Remove(_menuItemRemoveDatasetElement); } if (menuStripFeatureLayer.Items.Contains(_menuItemLockLayer)) { menuStripFeatureLayer.Items.Remove(_menuItemLockLayer); } } } } #endregion async private void _iMapDocument_LayerAdded(IMap sender, ILayer Layer) { await BuildList(null); } async void _iMapDocument_LayerRemoved(IMap sender, ILayer layer) { await BuildList(null); } async private void _iMapDocument_MapAdded(IMap map) { await BuildList(null); } async private void _iMapDocument_MapDeleted(IMap map) { await BuildList(null); } async private void _iMapDocument_AfterLoadMapDocument(IMapDocument mapDocument) { if (mapDocument != null && mapDocument.Application is IMapApplication && _fullversion == true) { _readonly = ((IMapApplication)mapDocument.Application).ReadOnly; this.TocViewMode = _mode; } await BuildList(null); } async void _iMapDocument_AfterSetFocusMap(IMap map) { await BuildList(null); if (SelectionChanged != null) { SelectionChanged(this, new EventArgs()); } } #region List private delegate void RefreshListCallback(); async public Task RefreshList() { //if (list.InvokeRequired) //{ // RefreshListCallback d = new RefreshListCallback(RefreshList); // list.Invoke(d); //} //else { await BuildList(null); } } public void RefreshTOCElement(IDatasetElement element) { List<LayerItem> items = new List<LayerItem>(); foreach (object item in list.Items) { LayerItem layerItem = item as LayerItem; if (layerItem == null || layerItem.TOCElement == null || layerItem.TOCElement.Layers == null) { continue; } foreach (ILayer layer in layerItem.TOCElement.Layers) { if (layer == element) { items.Add(layerItem); break; } } } foreach (LayerItem item in items) { if (item.TOCElement.LegendVisible) { ShowLegendGroup(item, false); ShowLegendGroup(item, true); } } } async internal Task BuildList(object FromItem) { FromItem = null; if (FromItem == null) { list.Items.Clear(); } else { int fromIndex = list.Items.IndexOf(FromItem); while (list.Items.Count > Math.Max(fromIndex, 0)) { list.Items.RemoveAt(fromIndex + 1); } } list.HorizontalExtent = 0; if (_iMapDocument == null) { return; } //IEnum Maps; //IMap map; IDataset dataset; int dsIndex = 0; switch (TocViewMode) { case TOCViewMode.Datasets: foreach (IMap map in _iMapDocument.Maps) { list.Items.Add(new MapItem(map)); if (!(map == _iMapDocument.FocusMap)) { continue; } dsIndex = 0; while ((dataset = map[dsIndex]) != null) { DatasetItem dsItem = new DatasetItem(dataset); list.Items.Add(dsItem); if (!dsItem.isEncapsed) { dsIndex++; continue; } await ShowDatasetLayers(dsItem); //foreach (IDatasetElement layer in dataset.Elements) //{ // if(layer==null) continue; // foreach (IDatasetElement mapElement in map.MapElements) // { // if (mapElement == null) continue; // if (mapElement.DatasetID == dsIndex && // mapElement.Title == layer.Title) // { // list.Items.Add(new DatasetLayerItem(mapElement, dataset)); // break; // } // } //} dsIndex++; } } break; case TOCViewMode.Groups: foreach (IMap map in _iMapDocument.Maps) { list.Items.Add(new MapItem(map)); if (!(map == _iMapDocument.FocusMap)) { continue; } if (map.TOC == null) { continue; } ITOC toc = map.TOC; toc.Reset(); ITOCElement elem; while ((elem = toc.NextVisibleElement) != null) { if (elem.LayerLocked) { continue; } switch (elem.ElementType) { case TOCElementType.Layer: LayerItem layerItem = new LayerItem(elem); list.Items.Add(layerItem); if (elem.LegendVisible) { ShowLegendGroup(layerItem, true); } break; case TOCElementType.OpenedGroup: case TOCElementType.ClosedGroup: list.Items.Add(new GroupItem(elem)); break; case TOCElementType.Legend: break; } } } break; } } private int ShowLegendGroup(LayerItem layerItem, bool show) { int index = list.Items.IndexOf(layerItem); if (index == -1) { return 0; } int counter = 0; if (LegendItem.LegendGroup(layerItem) != null && show) { ILegendGroup lGroup = LegendItem.LegendGroup(layerItem); for (int i = 0; i < lGroup.LegendItemCount; i++) { ILegendItem lItem = lGroup.LegendItem(i); if (lItem == null) { continue; } if (lItem.ShowInTOC) { list.Items.Insert(++index, new LegendItem(lItem, layerItem)); counter++; } } } else if (!show) { while (list.Items.Count > index + 1 && list.Items[index + 1] is LegendItem) { list.Items.RemoveAt(index + 1); counter--; } } return counter; } private void ShowGroupedLayers(GroupItem groupItem) { if (groupItem == null || groupItem.TOCElement == null) { return; } int index = list.Items.IndexOf(groupItem); if (index == -1) { return; } if (groupItem.TOCElement.ElementType == TOCElementType.ClosedGroup) { while (list.Items.Count > index + 1) { object item = list.Items[index + 1]; if ((item is LayerItem && ((LayerItem)item).level <= groupItem.level) || (item is GroupItem && ((GroupItem)item).level <= groupItem.level)) { break; } list.Items.RemoveAt(index + 1); } } else if (groupItem.TOCElement.ElementType == TOCElementType.OpenedGroup) { if (_iMapDocument == null || _iMapDocument.FocusMap == null || _iMapDocument.FocusMap.TOC == null) { return; } ITOC toc = _iMapDocument.FocusMap.TOC; foreach (ITOCElement tocElement in toc.GroupedElements(groupItem.TOCElement)) { switch (tocElement.ElementType) { case TOCElementType.Layer: LayerItem layerItem = new LayerItem(tocElement); list.Items.Insert(++index, layerItem); if (tocElement.LegendVisible) { index += ShowLegendGroup(layerItem, true); } break; case TOCElementType.OpenedGroup: case TOCElementType.ClosedGroup: list.Items.Insert(++index, new GroupItem(tocElement)); break; } } } } async private Task ShowDatasetLayers(DatasetItem item) { if (item == null || _iMapDocument == null || _iMapDocument.FocusMap == null || _iMapDocument.FocusMap.TOC == null) { return; } int dsIndex = 0; IDataset dataset; while ((dataset = _iMapDocument.FocusMap[dsIndex]) != null) { if (dataset == item.Dataset) { break; } dsIndex++; } if (dataset == null) { return; } int index = list.Items.IndexOf(item); if (index == -1) { return; } if (item.isEncapsed) { foreach (IDatasetElement layer in await dataset.Elements()) { if (layer == null) { continue; } foreach (IDatasetElement mapElement in _iMapDocument.FocusMap.MapElements) { if (!(mapElement is ILayer)) { continue; } if (_iMapDocument.FocusMap.TOC.GetTOCElement((ILayer)mapElement) == null) { continue; } if (mapElement.DatasetID == dsIndex && mapElement.Title == layer.Title) { list.Items.Insert(++index, new DatasetLayerItem(mapElement, dataset)); break; } } } } else { for (int i = index + 1; i < list.Items.Count;) { if (!(list.Items[i] is DatasetLayerItem)) { break; } list.Items.RemoveAt(i); } } } #endregion protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Vom Komponenten-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TOCControl)); this.iList = new System.Windows.Forms.ImageList(this.components); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.menuStripFeatureLayer = new System.Windows.Forms.ContextMenuStrip(this.components); this.menuStripMap = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMapActivate = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMapNewMap = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMapDeleteMap = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuUnlock = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.debuggingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuUnreferencedLayers = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.iLMenuItem = new System.Windows.Forms.ImageList(this.components); this.menuStripGroupLayer = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.menuApply = new System.Windows.Forms.ToolStripMenuItem(); this.menuGroupApplyVisibility = new System.Windows.Forms.ToolStripMenuItem(); this.menuGroupApplyScales = new System.Windows.Forms.ToolStripMenuItem(); this.contextMenuStripDataset = new System.Windows.Forms.ContextMenuStrip(this.components); this.connectionPropertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.list = new gView.Framework.UI.Controls.ScrollingListBox(); this.menuStripMap.SuspendLayout(); this.menuStripGroupLayer.SuspendLayout(); this.contextMenuStripDataset.SuspendLayout(); this.SuspendLayout(); // // iList // this.iList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iList.ImageStream"))); this.iList.TransparentColor = System.Drawing.Color.Transparent; this.iList.Images.SetKeyName(0, "minus.gif"); this.iList.Images.SetKeyName(1, "plus.gif"); this.iList.Images.SetKeyName(2, ""); this.iList.Images.SetKeyName(3, ""); this.iList.Images.SetKeyName(4, ""); this.iList.Images.SetKeyName(5, "dataset.png"); this.iList.Images.SetKeyName(6, "field_geom_point.png"); this.iList.Images.SetKeyName(7, "field_geom_line.png"); this.iList.Images.SetKeyName(8, "field_geom_polygon.png"); this.iList.Images.SetKeyName(9, ""); this.iList.Images.SetKeyName(10, "opengroup19.png"); this.iList.Images.SetKeyName(11, "closegroup19.png"); this.iList.Images.SetKeyName(12, ""); this.iList.Images.SetKeyName(13, ""); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "toc.png"); this.imageList1.Images.SetKeyName(1, "cat6.png"); // // menuStripFeatureLayer // this.menuStripFeatureLayer.ImageScalingSize = new System.Drawing.Size(24, 24); this.menuStripFeatureLayer.Name = "menuStripFeatureLayer"; this.menuStripFeatureLayer.Size = new System.Drawing.Size(61, 4); // // menuStripMap // this.menuStripMap.ImageScalingSize = new System.Drawing.Size(24, 24); this.menuStripMap.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMapActivate, this.toolStripSeparator2, this.toolStripMapNewMap, this.toolStripMapDeleteMap, this.toolStripSeparator3, this.toolStripMenuUnlock, this.toolStripSeparator4, this.debuggingToolStripMenuItem, this.toolStripMenuItem1, this.toolStripSeparator1}); this.menuStripMap.Name = "menuStripMap"; this.menuStripMap.Size = new System.Drawing.Size(193, 208); // // toolStripMapActivate // this.toolStripMapActivate.Name = "toolStripMapActivate"; this.toolStripMapActivate.Size = new System.Drawing.Size(192, 30); this.toolStripMapActivate.Text = "Activate"; this.toolStripMapActivate.Click += new System.EventHandler(this.toolStripMapActivate_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(189, 6); // // toolStripMapNewMap // this.toolStripMapNewMap.Name = "toolStripMapNewMap"; this.toolStripMapNewMap.Size = new System.Drawing.Size(192, 30); this.toolStripMapNewMap.Text = "New Map"; this.toolStripMapNewMap.Click += new System.EventHandler(this.toolStripMapNewMap_Click); // // toolStripMapDeleteMap // this.toolStripMapDeleteMap.Name = "toolStripMapDeleteMap"; this.toolStripMapDeleteMap.Size = new System.Drawing.Size(192, 30); this.toolStripMapDeleteMap.Text = "Delete Map"; this.toolStripMapDeleteMap.Click += new System.EventHandler(this.toolStripMapDeleteMap_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(189, 6); // // toolStripMenuUnlock // this.toolStripMenuUnlock.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuUnlock.Image"))); this.toolStripMenuUnlock.Name = "toolStripMenuUnlock"; this.toolStripMenuUnlock.Size = new System.Drawing.Size(192, 30); this.toolStripMenuUnlock.Text = "Unlock Layer"; // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(189, 6); // // debuggingToolStripMenuItem // this.debuggingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuUnreferencedLayers}); this.debuggingToolStripMenuItem.Name = "debuggingToolStripMenuItem"; this.debuggingToolStripMenuItem.Size = new System.Drawing.Size(192, 30); this.debuggingToolStripMenuItem.Text = "Debugging"; // // menuUnreferencedLayers // this.menuUnreferencedLayers.Name = "menuUnreferencedLayers"; this.menuUnreferencedLayers.Size = new System.Drawing.Size(267, 30); this.menuUnreferencedLayers.Text = "Unreferenced Layers..."; this.menuUnreferencedLayers.Click += new System.EventHandler(this.menuUnreferencedLayers_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(192, 30); this.toolStripMenuItem1.Text = "Properties"; this.toolStripMenuItem1.Click += new System.EventHandler(this.MapProperties_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(189, 6); // // iLMenuItem // this.iLMenuItem.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iLMenuItem.ImageStream"))); this.iLMenuItem.TransparentColor = System.Drawing.Color.Transparent; this.iLMenuItem.Images.SetKeyName(0, "delete_16.png"); this.iLMenuItem.Images.SetKeyName(1, "folder-open_16.png"); this.iLMenuItem.Images.SetKeyName(2, "folder-moveTo_16.png"); this.iLMenuItem.Images.SetKeyName(3, "locked.png"); this.iLMenuItem.Images.SetKeyName(4, "unlocked.png"); // // menuStripGroupLayer // this.menuStripGroupLayer.ImageScalingSize = new System.Drawing.Size(24, 24); this.menuStripGroupLayer.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator5, this.menuApply}); this.menuStripGroupLayer.Name = "menuStripGroupLayer"; this.menuStripGroupLayer.Size = new System.Drawing.Size(132, 40); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(128, 6); // // menuApply // this.menuApply.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuGroupApplyVisibility, this.menuGroupApplyScales}); this.menuApply.Name = "menuApply"; this.menuApply.Size = new System.Drawing.Size(131, 30); this.menuApply.Text = "Apply"; // // menuGroupApplyVisibility // this.menuGroupApplyVisibility.Name = "menuGroupApplyVisibility"; this.menuGroupApplyVisibility.Size = new System.Drawing.Size(161, 30); this.menuGroupApplyVisibility.Text = "Visibility"; this.menuGroupApplyVisibility.Click += new System.EventHandler(this.menuGroupApplyVisibility_Click); // // menuGroupApplyScales // this.menuGroupApplyScales.Name = "menuGroupApplyScales"; this.menuGroupApplyScales.Size = new System.Drawing.Size(161, 30); this.menuGroupApplyScales.Text = "Scales"; this.menuGroupApplyScales.Click += new System.EventHandler(this.menuGroupApplyScales_Click); // // contextMenuStripDataset // this.contextMenuStripDataset.ImageScalingSize = new System.Drawing.Size(24, 24); this.contextMenuStripDataset.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.connectionPropertiesToolStripMenuItem}); this.contextMenuStripDataset.Name = "contextMenuStripDataset"; this.contextMenuStripDataset.Size = new System.Drawing.Size(255, 34); // // connectionPropertiesToolStripMenuItem // this.connectionPropertiesToolStripMenuItem.Name = "connectionPropertiesToolStripMenuItem"; this.connectionPropertiesToolStripMenuItem.Size = new System.Drawing.Size(254, 30); this.connectionPropertiesToolStripMenuItem.Text = "ConnectionProperties"; this.connectionPropertiesToolStripMenuItem.Click += new System.EventHandler(this.connectionPropertiesToolStripMenuItem_Click); // // list // this.list.AllowDrop = true; this.list.ColumnWidth = 500; this.list.Dock = System.Windows.Forms.DockStyle.Fill; this.list.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.list.HorizontalScrollbar = true; this.list.HorizontalScrollPos = 0; this.list.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.list.ItemHeight = 30; this.list.Location = new System.Drawing.Point(0, 0); this.list.Name = "list"; this.list.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.list.Size = new System.Drawing.Size(160, 392); this.list.TabIndex = 0; this.list.VerticalScrollPos = 0; this.list.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.list_DrawItem); this.list.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.list_MeasureItem); this.list.SelectedIndexChanged += new System.EventHandler(this.list_SelectedIndexChanged); this.list.SelectedValueChanged += new System.EventHandler(this.list_SelectedValueChanged); this.list.DragDrop += new System.Windows.Forms.DragEventHandler(this.list_DragDrop); this.list.DragEnter += new System.Windows.Forms.DragEventHandler(this.list_DragEnter); this.list.DoubleClick += new System.EventHandler(this.list_DoubleClick); this.list.MouseDown += new System.Windows.Forms.MouseEventHandler(this.list_MouseDown); this.list.MouseMove += new System.Windows.Forms.MouseEventHandler(this.list_MouseMove); this.list.MouseUp += new System.Windows.Forms.MouseEventHandler(this.list_MouseUp); // // TOCControl // this.Controls.Add(this.list); this.Name = "TOCControl"; this.Size = new System.Drawing.Size(160, 392); this.menuStripMap.ResumeLayout(false); this.menuStripGroupLayer.ResumeLayout(false); this.contextMenuStripDataset.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void list_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e) { object item = list.Items[e.Index]; if (item is LegendItem) { if (((LegendItem)item).legendItem == null) { e.ItemHeight = 1; } else { //e.ItemHeight = ((LegendItem)item).LegendGroup.LegendItemCount * 20; e.ItemHeight = 20; } } else { e.ItemHeight = 20; } e.ItemHeight = (int)(e.ItemHeight * list.FontScaleFactor); } private int _lastLayerLevel = 0; private void list_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { if (e.Index == -1) { return; } e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; using (SolidBrush brush = new SolidBrush(Color.Black)) { object item = list.Items[e.Index]; if (list.SelectedIndices.Contains(e.Index) && !(item is LegendItem)) { brush.Color = Color.DarkBlue; e.Graphics.FillRectangle(brush, e.Bounds); brush.Color = Color.White; } bool bold = false, italic = false; if (item is MapItem) { if (((MapItem)item).ToString() == _iMapDocument.FocusMap.Name) { bold = true; } } if (item is LayerItem) { ITOCElement tocElement = ((LayerItem)item).TOCElement; if (tocElement != null && tocElement.Layers != null) { foreach (ILayer layer in tocElement.Layers) { if (layer is IWebServiceTheme) { italic = true; } } } } FontStyle style = FontStyle.Regular; if (bold) { style |= FontStyle.Bold; } if (italic) { style |= FontStyle.Italic; } using (Font font = new Font("Verdana", ((item is LegendItem) ? 8 : 10), style)) { { SizeF stringSize = e.Graphics.MeasureString(item.ToString(), font); if (item is MapItem) { e.Graphics.DrawImage( global::gView.Win.Dialogs.Properties.Resources.layers, 2, e.Bounds.Top + 2, 16, 16); e.Graphics.DrawString(item.ToString(), font, brush, 19, e.Bounds.Top + 2); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, 19 + stringSize.Width); } else if (item is DatasetItem) { e.Graphics.DrawImage(iList.Images[(((DatasetItem)item).isEncapsed ? 0 : 1)], 0, e.Bounds.Top, 19, 20); //e.Graphics.DrawImage(iList.Images[2], 19, e.Bounds.Top, 19, 20); e.Graphics.DrawImage(iList.Images[5], 19, e.Bounds.Top, 19, 20); e.Graphics.DrawString(item.ToString(), font, brush, 39, e.Bounds.Top + 2); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, 39 + stringSize.Width); } else if (item is LayerItem) { if (((LayerItem)item).TOCElement.Layers.Count > 1) { brush.Color = Color.Blue; } foreach (ILayer layer in ((LayerItem)item).TOCElement.Layers) { if (layer is NullLayer) { brush.Color = Color.FromArgb(255, 100, 100); } } int l = ((LayerItem)item).level * 19; e.Graphics.DrawImage(iList.Images[ (((LayerItem)item).Visible) ? 3 : 2 ], l, e.Bounds.Top, 19, 20); if (LegendItem.LegendGroup((LayerItem)item) != null) { l += 19; e.Graphics.DrawImage(iList.Images[ (((LayerItem)item).TOCElement.LegendVisible) ? 0 : 1 ], l, e.Bounds.Top, 19, 20); l -= 4; } e.Graphics.DrawString(item.ToString(), font, brush, l + 19, e.Bounds.Top + 2); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, l + 19 + stringSize.Width); _lastLayerLevel = ((LayerItem)item).level; } else if (item is LegendItem) { if (((LegendItem)item).legendItem != null) { //((LegendItem)item).level = _lastLayerLevel; //int l = _lastLayerLevel * 19 + 19; int l = ((LegendItem)item).level * 19 + 19; ILegendItem legendItem = ((LegendItem)item).legendItem; if (legendItem is ISymbol) { using (var bitmap = GraphicsEngine.Current.Engine.CreateBitmap(30, 20)) using (var canvas = bitmap.CreateCanvas()) { new SymbolPreview(null).Draw(canvas, new GraphicsEngine.CanvasRectangle(0, 0, 30, 20), (ISymbol)legendItem); e.Graphics.DrawImage(bitmap.CloneToGdiBitmap(), new System.Drawing.Point(l, e.Bounds.Top)); } } if (legendItem.LegendLabel != "") { e.Graphics.DrawString(legendItem.LegendLabel, font, brush, l + 32, e.Bounds.Top + e.Bounds.Height / 2 - font.Height / 2); stringSize = e.Graphics.MeasureString(legendItem.LegendLabel, font); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, l + 32 + stringSize.Width); } } } else if (item is GroupItem) { int l = ((GroupItem)item).level * 19; int closed = 10, opened = 11; if (isWebServiceLayer(item)) { opened = 0; closed = 1; } e.Graphics.DrawImage(iList.Images[((GroupItem)item).Visible ? 3 : 2], l, e.Bounds.Top, 19, 20); e.Graphics.DrawImage(iList.Images[ (((GroupItem)item).isEncapsed) ? opened : closed ], l + 19, e.Bounds.Top, 19, 20); e.Graphics.DrawString(item.ToString(), font, brush, l + 38, e.Bounds.Top + 2); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, l + 38 + stringSize.Width); } else if (item is DatasetLayerItem) { //if (((DatasetLayerItem)item).Layer is ILayer) //{ // e.Graphics.DrawImage(iList.Images[ // (((ILayer)((DatasetLayerItem)item).Layer).Visible ? 3 : 2) // ], 20, e.Bounds.Top, 19, 20); //} //else //{ // e.Graphics.DrawImage(iList.Images[0], 20, e.Bounds.Top, 19, 20); //} int imageIndex = -1; if (((DatasetLayerItem)item).Layer is IRasterLayer) { imageIndex = 9; } else { if (((DatasetLayerItem)item).Layer is IFeatureLayer) { if (((IFeatureLayer)((DatasetLayerItem)item).Layer).FeatureClass != null) { switch (((IFeatureLayer)((DatasetLayerItem)item).Layer).FeatureClass.GeometryType) { case GeometryType.Point: case GeometryType.Multipoint: imageIndex = 6; break; case GeometryType.Polyline: imageIndex = 7; break; case GeometryType.Polygon: case GeometryType.Envelope: imageIndex = 8; break; } } } } if (imageIndex > 0) { e.Graphics.DrawImage(iList.Images[imageIndex], 38, e.Bounds.Top, 19, 20); } e.Graphics.DrawString(item.ToString(), font, brush, 57, e.Bounds.Top + 2); list.HorizontalExtent = (int)Math.Max(list.HorizontalExtent, 57 + stringSize.Width); } } } } } private void list_SelectedValueChanged(object sender, System.EventArgs e) { if (SelectionChanged != null) { SelectionChanged(this, new EventArgs()); } list.Refresh(); } private void list_SelectedIndexChanged(object sender, System.EventArgs e) { if (_iMapDocument == null) { return; } if (_iMapDocument.FocusMap == null) { return; } string layers = ""; foreach (object item in list.SelectedItems) { if (item is DatasetLayerItem) { if (layers != "") { layers += ";"; } layers += item.ToString(); } } _iMapDocument.FocusMap.ActiveLayerNames = layers; } #region MouseEvents async private void list_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (_mouseOverItem != null && _mouseDownItem != null && _mouseOverItem != _mouseDownItem) { list.SelectedIndex = -1; ITOCElement elem = null, insertBefore = null; if (_mouseOverItem is LayerItem) { insertBefore = ((LayerItem)_mouseOverItem).TOCElement; } else if (_mouseOverItem is GroupItem) { insertBefore = ((GroupItem)_mouseOverItem).TOCElement; } if (_mouseDownItem is LayerItem) { elem = ((LayerItem)_mouseDownItem).TOCElement; } else if (_mouseDownItem is GroupItem) { elem = ((GroupItem)_mouseDownItem).TOCElement; } if (elem == null || insertBefore == null || elem == insertBefore) { return; } if (_moveElementAction == MoveElementAction.addToGroup) { _iMapDocument.FocusMap.TOC.Add2Group(elem, insertBefore); _iMapDocument.TemporaryRestore(); } else if (_moveElementAction == MoveElementAction.insertBefore) { _iMapDocument.FocusMap.TOC.MoveElement(elem, insertBefore, false); _iMapDocument.TemporaryRestore(); } else if (_moveElementAction == MoveElementAction.insertAfter) { _iMapDocument.FocusMap.TOC.MoveElement(elem, insertBefore, true); _iMapDocument.TemporaryRestore(); } await this.BuildList(null); await RefreshMap(); } } async private void list_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { _rect = new Rectangle(-1, -1, -1, -1); _mouseOverItem = _mouseDownItem = null; object item = null; for (int i = 0; i < list.Items.Count; i++) { Rectangle rect = list.GetItemRectangle(i); if (rect.Y <= e.Y && (rect.Y + rect.Height) >= e.Y) { item = list.Items[i]; break; } } if (item == null) { return; } if (e.Button == MouseButtons.Right) { _contextItem = item; if (item is MapItem) { toolStripMenuUnlock.DropDownItems.Clear(); if (_iMapDocument != null && _iMapDocument.FocusMap != null && _iMapDocument.FocusMap.TOC != null && _iMapDocument.FocusMap.TOC.Elements != null) { foreach (ITOCElement element in _iMapDocument.FocusMap.TOC.Elements) { if (!element.LayerLocked) { continue; } toolStripMenuUnlock.DropDownItems.Add(new UnlockLayerMenuItem(this, element, iLMenuItem.Images[4])); } } toolStripMenuUnlock.Enabled = (toolStripMenuUnlock.DropDownItems.Count > 0) && (_readonly == false); toolStripMapNewMap.Enabled = toolStripMapDeleteMap.Enabled = toolStripMenuItem1.Enabled = (_readonly == false); //for (int i = menuStripMap.Items.Count - 1; i >= 0; i--) //{ // if (menuStripMap.Items[i] is MapContextMenuItem) // menuStripMap.Items.Remove(menuStripMap.Items[i]); //} menuStripMap.Items.Clear(); PlugInManager pman = new PlugInManager(); int order = 0; foreach (IMapContextMenuItem contextMenuItem in OrderedPluginList<object>.Sort(pman.GetPluginInstances(typeof(IMapContextMenuItem)))) { if (contextMenuItem.SortOrder / 10 - order / 10 >= 1 && menuStripMap.Items.Count > 0) { menuStripMap.Items.Add(new ToolStripSeparator()); } if (contextMenuItem == null || contextMenuItem.Visible(((MapItem)item).Map) == false) { continue; } MapContextMenuItem mapItem = new MapContextMenuItem(((MapItem)item).Map, contextMenuItem); mapItem.Image = contextMenuItem.Image as Image; mapItem.Click += new EventHandler(clickMenuContextItem); menuStripMap.Items.Add(mapItem); } menuStripMap.Show(this, new System.Drawing.Point(e.X, e.Y)); return; } if (item is DatasetItem) { contextMenuStripDataset.Show(this, new System.Drawing.Point(e.X, e.Y)); return; } if (item is DatasetLayerItem || item is LayerItem || item is GroupItem) { for (int i = 0; i < menuStripFeatureLayer.Items.Count; i++) { if (menuStripFeatureLayer.Items[i] is LayerContextMenuItem || menuStripFeatureLayer.Items[i] is ToolStripSeparator || menuStripFeatureLayer.Items[i] == menuApply) { menuStripFeatureLayer.Items.Remove(menuStripFeatureLayer.Items[i]); i--; } } if (menuStripFeatureLayer.Items.IndexOf(_menuItemSplitMultiLayer) != -1) { menuStripFeatureLayer.Items.Remove(_menuItemSplitMultiLayer); } if (item is GroupItem && _readonly == false) { menuStripFeatureLayer.Items.Add(menuApply); } if (item is DatasetLayerItem && _readonly == false) { int order = 0; foreach (IDatasetElementContextMenuItem contextMenuItem in _contextMenuItems) { if ((contextMenuItem.SortOrder / 10 - order / 10) > 0 && menuStripFeatureLayer.Items.Count > 0 && !(menuStripFeatureLayer.Items[menuStripFeatureLayer.Items.Count - 1] is ToolStripSeparator)) { menuStripFeatureLayer.Items.Add(new ToolStripSeparator()); } LayerContextMenuItem layerItem = new LayerContextMenuItem( contextMenuItem.Name, ((DatasetLayerItem)item).Layer, contextMenuItem); layerItem.Click += new EventHandler(clickLayerContextItem); menuStripFeatureLayer.Items.Add(layerItem); order = contextMenuItem.SortOrder; } } if ((item is LayerItem || item is GroupItem) && _readonly == false) { menuStripFeatureLayer.Items.Remove(_menuItemMoveToGroup); _menuItemMoveToGroup.DropDownItems.Clear(); foreach (ITOCElement Group in _iMapDocument.FocusMap.TOC.GroupElements) { _menuItemMoveToGroup.DropDownItems.Add( new GroupMenuItem(Group, new System.EventHandler(this.clickMoveToGroup)) ); } _menuItemMoveToGroup.Enabled = (_menuItemMoveToGroup.DropDownItems.Count > 0 && list.SelectedIndices.Count > 0); _menuItemMoveToGroup.DropDownItems.Insert(0, new GroupMenuItem(null, new System.EventHandler(this.clickMoveToGroup))); int index = menuStripFeatureLayer.Items.IndexOf(_menuItemInsertGroup); menuStripFeatureLayer.Items.Insert(index + 1, _menuItemMoveToGroup); } if (item is LayerItem || (item is GroupItem && ((GroupItem)item).TOCElement.Layers.Count > 0)) { ITOCElement tocelement = (item is LayerItem) ? ((LayerItem)item).TOCElement : ((GroupItem)item).TOCElement; if (tocelement.Layers.Count > 1) { int index = menuStripFeatureLayer.Items.IndexOf(_menuItemInsertGroup); menuStripFeatureLayer.Items.Insert(index + 2, _menuItemSplitMultiLayer); } List<ILayer> layers = tocelement.Layers; if (layers.Count > 0) { int order = 0; foreach (IDatasetElementContextMenuItem contextMenuItem in _contextMenuItems) { if ((contextMenuItem.SortOrder / 10 - order / 10) > 0 && menuStripFeatureLayer.Items.Count > 0 && !(menuStripFeatureLayer.Items[menuStripFeatureLayer.Items.Count - 1] is ToolStripSeparator)) { menuStripFeatureLayer.Items.Add(new ToolStripSeparator()); } order = contextMenuItem.SortOrder; contextMenuItem.OnCreate(_iMapDocument); ToolStripMenuItem layerItem; if (layers.Count == 1) { IDatasetElement element = layers[0]; if (!contextMenuItem.Visible(element)) { continue; } layerItem = new LayerContextMenuItem( contextMenuItem.Name, element, contextMenuItem); layerItem.Enabled = contextMenuItem.Enable(element); layerItem.Click += new EventHandler(clickLayerContextItem); } else { layerItem = new LayerContextMenuItem(contextMenuItem.Name, contextMenuItem.Image as Image); if (layers.Count > 0) { foreach (IDatasetElement layer in layers) { if (!contextMenuItem.Visible(layer)) { continue; } IMap map = _iMapDocument[layer]; if (map == null) { continue; } IDataset ds = map[layer]; if (ds == null) { continue; } LayerContextMenuItem lItem = new LayerContextMenuItem( ds.DatasetGroupName + "/" + ds.DatasetName + ": " + layer.Title, layer, contextMenuItem); lItem.Enabled = contextMenuItem.Enable(layer); lItem.Click += new EventHandler(clickLayerContextItem); layerItem.DropDownItems.Add(lItem); } } } menuStripFeatureLayer.Items.Add(layerItem); } } } if (menuStripFeatureLayer.Items.Count == 0) { return; } menuStripFeatureLayer.Show(this, new System.Drawing.Point(e.X, e.Y)); //for (int i = 0; i < menuStripFeatureLayer.Items.Count; i++) //{ // if (menuStripFeatureLayer.Items[i] is LayerContextMenuItem) // { // menuStripFeatureLayer.Items.Remove(menuStripFeatureLayer.Items[i]); // i--; // } //} //if (menuStripFeatureLayer.Items.IndexOf(_menuItemSplitMultiLayer) != -1) // menuStripFeatureLayer.Items.Remove(_menuItemSplitMultiLayer); return; } return; } int X = e.X + list.HorizontalScrollPos; if (item is DatasetItem) { if (X >= 1 && X <= 10) { ((DatasetItem)item).isEncapsed = !((DatasetItem)item).isEncapsed; await ShowDatasetLayers((DatasetItem)item); } } if (item is DatasetLayerItem) { if (((DatasetLayerItem)item).Layer is ILayer) { //if (X >= 19 && X <= 38) //{ // ((ILayer)((DatasetLayerItem)item).Layer).Visible = // !((ILayer)((DatasetLayerItem)item).Layer).Visible; // list.Refresh(); // RefreshMap(); // return; //} } } if (item is LayerItem) { int l = ((LayerItem)item).level * 19; if (X >= l && X <= l + 19) { ((LayerItem)item).Visible = !((LayerItem)item).Visible; list.Refresh(); await RefreshMap(); return; } if (X >= l + 19 && X <= l + 38) { if (LegendItem.LegendGroup((LayerItem)item) != null) { ((LayerItem)item).TOCElement.LegendVisible = !((LayerItem)item).TOCElement.LegendVisible; //this.buildList(item); ShowLegendGroup((LayerItem)item, ((LayerItem)item).TOCElement.LegendVisible); return; } } } if (item is GroupItem) { int l = ((GroupItem)item).level * 19; if (X >= l && X <= l + 19) { ((GroupItem)item).Visible = !((GroupItem)item).Visible; list.Refresh(); await RefreshMap(); return; } else if (X >= l + 20 && X <= l + 38) { ((GroupItem)item).TOCElement.OpenCloseGroup( ((GroupItem)item).TOCElement.ElementType == TOCElementType.ClosedGroup); ShowGroupedLayers((GroupItem)item); return; } // ansonsten: vorbereiten zu verschieben... } _mouseDownItem = item; } private int _mX = 0, _mY = 0; private Rectangle _rect = new Rectangle(-1, -1, -1, -1); private object _mouseOverItem = null; private object _mouseDownItem = null; private enum MoveElementAction { none, insertBefore, insertAfter, addToGroup } private MoveElementAction _moveElementAction = MoveElementAction.insertBefore; private void list_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { _mX = e.X; _mY = e.Y; if (e.Button == MouseButtons.Left && list.SelectedIndices.Count > 0 && _mouseDownItem != null) { System.Drawing.Graphics gr = null; Pen pen = null; try { object item = null; Rectangle rect = new Rectangle(0, 0, 0, 0); MoveElementAction lastAction = _moveElementAction; _moveElementAction = MoveElementAction.none; bool insertAfter = false; if (list.Items.Count > 0 && list.GetItemRectangle(list.Items.Count - 1).Bottom < e.Y) { rect = list.GetItemRectangle(list.Items.Count - 1); item = list.Items[list.Items.Count - 1]; insertAfter = true; } else { for (int i = 0; i < list.Items.Count; i++) { rect = list.GetItemRectangle(i); //if(rect==null) continue; if (rect.Y <= e.Y && (rect.Y + rect.Height) >= e.Y) { item = list.Items[i]; break; } } } gr = System.Drawing.Graphics.FromHwnd(list.Handle); pen = new Pen(Color.Blue, 2); if (_rect != rect || lastAction != _moveElementAction) { pen.Color = list.BackColor; DrawActionHandle(gr, pen, _rect, lastAction, 0); _rect = rect; } if (item == null || item is LegendItem || item is MapItem) { return; } ITOCElement downTocElement = null; if (_mouseDownItem is LayerItem) { downTocElement = ((LayerItem)_mouseDownItem).TOCElement; if (downTocElement != null && downTocElement.Layers != null) { foreach (ILayer layer in downTocElement.Layers) { if (layer is IWebServiceTheme) { return; } } } } ITOCElement overTocElement = null; if (item is LayerItem) { overTocElement = ((LayerItem)item).TOCElement; if (overTocElement != null && overTocElement.Layers != null) { foreach (ILayer layer in overTocElement.Layers) { if (layer is IWebServiceTheme) { return; } } } } _mouseOverItem = item; if (insertAfter) { _moveElementAction = MoveElementAction.insertAfter; } else if (_mouseOverItem is GroupItem) { _moveElementAction = ((e.Y - rect.Y) < rect.Height / 3) ? MoveElementAction.insertBefore : MoveElementAction.addToGroup; } else { _moveElementAction = ((e.Y - rect.Y) < rect.Height / 2) ? MoveElementAction.insertBefore : MoveElementAction.insertAfter; //_moveElementAction = MoveElementAction.insertBefore; } pen.Color = Color.Blue; DrawActionHandle(gr, pen, rect, _moveElementAction, ItemLevel(item)); } finally { if (pen != null) { pen.Dispose(); } pen = null; if (gr != null) { gr.Dispose(); } gr = null; } } } private void DrawActionHandle(System.Drawing.Graphics gr, Pen pen, Rectangle rect, MoveElementAction action, int level) { if (action == MoveElementAction.addToGroup) { gr.DrawRectangle(pen, rect); } else if (action == MoveElementAction.insertBefore) { gr.DrawLine(pen, rect.Left + level * 19, rect.Top, rect.Width, rect.Top); } else if (action == MoveElementAction.insertAfter) { gr.DrawLine(pen, rect.Left + level * 19, rect.Bottom, rect.Width, rect.Bottom); } } private int ItemLevel(object item) { if (item is LayerItem) { return ((LayerItem)item).level; } else if (item is GroupItem) { return ((GroupItem)item).level; } else if (item is LegendItem) { return ((LegendItem)item).level; } return 0; } private object _renameItem = null; private void list_DoubleClick(object sender, System.EventArgs e) { object item = null; Rectangle rect = new Rectangle(0, 0, 0, 0); for (int i = 0; i < list.Items.Count; i++) { rect = list.GetItemRectangle(i); //if(rect==null) continue; if (rect.Y <= _mY && (rect.Y + rect.Height) >= _mY) { item = list.Items[i]; break; } } if (item == null) { return; } if (!(item is IRenamable)) { return; } _renameItem = item; int xOffset = 0; if (item is GroupItem) { xOffset = ((GroupItem)item).level * 19 + 38; } else if (item is LayerItem) { xOffset = ((LayerItem)item).level * 19 + 19 + ((LegendItem.LegendGroup((LayerItem)item) == null) ? 0 : 15); } else if (item is LegendItem) { int l = ((LegendItem)item).level * 19 + 19; if (_mX < l) { return; } if (_mX >= l && _mX <= l + 30) { ILegendItem lItem = ((LegendItem)item).legendItem; if (lItem is ISymbol) { FormSymbol dlg = new FormSymbol((ISymbol)lItem); if (dlg.ShowDialog() == DialogResult.OK) { ((LegendItem)item).SetSymbol(dlg.Symbol); list.Refresh(); if (_iMapDocument != null && _iMapDocument.Application is IMapApplication) { ((IMapApplication)_iMapDocument.Application).RefreshActiveMap(DrawPhase.All); } _iMapDocument.TemporaryRestore(); } } return; } xOffset = l + 32; } else { return; } if (_mX < xOffset) { return; } _renameBox.Left = xOffset; _renameBox.Top = rect.Top; _renameBox.Width = rect.Width - xOffset; _renameBox.Height = rect.Height; _renameBox.Text = item.ToString(); _renameBox.Visible = true; _renameBox.Focus(); } #endregion private string GetGroupNamesPath(ITOCElement elem) { if (elem.ElementType != TOCElementType.ClosedGroup && elem.ElementType != TOCElementType.OpenedGroup) { return ""; } string path = elem.Name; ITOCElement parent = elem; while ((parent = parent.ParentGroup) != null) { path = parent.Name + "/" + path; } return path; } async private void renameBoxLeave(object sender, System.EventArgs e) { _renameBox.Visible = false; if (!(_renameItem is IRenamable)) { return; } ((IRenamable)_renameItem).rename(_renameBox.Text); _renameItem = null; await this.BuildList(null); } async private void renameBoxKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (e.KeyChar == 13) { try { _renameBox.Visible = false; if (!(_renameItem is IRenamable)) { return; } ((IRenamable)_renameItem).rename(_renameBox.Text); _renameItem = null; await this.BuildList(null); } finally { _iMapDocument.TemporaryRestore(); } } } async private Task RefreshMap() { if (_iMapDocument != null && _iMapDocument.Application is IMapApplication) { await ((IMapApplication)_iMapDocument.Application).RefreshActiveMap(DrawPhase.All); } } public object[] SelectedItems { get { List<object> items = new List<object>(); foreach (var item in list.SelectedItems) { items.Add(item); } return items.ToArray(); } } public object[] Items { get { List<object> items = new List<object>(); foreach (var item in list.Items) { items.Add(item); } return items.ToArray(); } } public void SelectItem(int index) { if (list.Items.Count >= index) { list.SelectedIndex = index; } } #region WebServiceLayer private bool isWebServiceLayer(object item) { if (item is GroupItem) { if (((GroupItem)item).TOCElement.Layers.Count > 0) { foreach (ILayer layer in ((GroupItem)item).TOCElement.Layers) { if (layer is IWebServiceLayer) { return true; } } } } else if (item is LayerItem) { if (((LayerItem)item).TOCElement.Layers.Count > 0) { foreach (ILayer layer in ((LayerItem)item).TOCElement.Layers) { if (layer is IWebServiceLayer) { return true; } } } } return false; } private bool isWebServiceTheme(object item) { if (item is LayerItem) { if (((LayerItem)item).TOCElement.Layers.Count > 0) { foreach (ILayer layer in ((LayerItem)item).TOCElement.Layers) { if (layer is IWebServiceTheme) { return true; } } } } return false; } #endregion #region ContextMenu Map private void SpatialReferenceSystem_Click(object sender, System.EventArgs e) { if (!(_contextItem is MapItem)) { return; } IMap map = null; foreach (IMap m in _iMapDocument.Maps) { if (m.Name == ((MapItem)_contextItem).ToString()) { map = m; break; } } if (map == null) { return; } if (map.Display != null && map is Map) { FormSpatialReference dlg = new FormSpatialReference(map.Display.SpatialReference); if (dlg.ShowDialog() == DialogResult.OK) { ISpatialReference sRef1 = dlg.SpatialReference; ISpatialReference sRef2 = map.Display.SpatialReference; if (sRef1 != null && sRef2 != null) { IEnvelope limit = map.Display.Limit; IEnvelope env = map.Display.Envelope; using (var geoTrans = gView.Framework.Geometry.GeometricTransformerFactory.Create()) { //geoTrans.FromSpatialReference = sRef2; //geoTrans.ToSpatialReference = sRef1; geoTrans.SetSpatialReferences(sRef2, sRef1); IGeometry limit2 = (IGeometry)geoTrans.Transform2D(limit); IGeometry env2 = (IGeometry)geoTrans.Transform2D(env); map.Display.Limit = limit2.Envelope; ((Map)_iMapDocument.FocusMap).ZoomTo( env2.Envelope.minx, env2.Envelope.miny, env2.Envelope.maxx, env2.Envelope.maxy); } } map.Display.SpatialReference = dlg.SpatialReference; } } } async private void MapProperties_Click(object sender, EventArgs e) { if (!(_contextItem is MapItem)) { return; } IMap map = null; foreach (IMap m in _iMapDocument.Maps) { if (m.Name == ((MapItem)_contextItem).ToString()) { map = m; break; } } if (map == null) { return; } FormMapProperties dlg = new FormMapProperties(_iMapDocument.Application as IMapApplication, map, map.Display); ISpatialReference oldSRef = map.Display.SpatialReference; if (dlg.ShowDialog() == DialogResult.OK) { await this.BuildList(null); if (_iMapDocument != null && _iMapDocument.Application is IMapApplication) { await ((IMapApplication)_iMapDocument.Application).RefreshActiveMap(DrawPhase.All); } } } async private void toolStripMapActivate_Click(object sender, EventArgs e) { if (_iMapDocument == null || !(_contextItem is MapItem)) { return; } IMap map = null; foreach (IMap m in _iMapDocument.Maps) { if (m.Name == ((MapItem)_contextItem).ToString()) { map = m; break; } } if (map == null) { return; } _iMapDocument.FocusMap = map; await this.BuildList(null); } private void toolStripMapNewMap_Click(object sender, EventArgs e) { if (_iMapDocument == null) { return; } IMap map = new Map(); map.Name = "Map" + (_iMapDocument.Maps.Count() + 1).ToString(); _iMapDocument.AddMap(map); } private void toolStripMapDeleteMap_Click(object sender, EventArgs e) { if (_iMapDocument == null || !(_contextItem is MapItem)) { return; } IMap map = null; foreach (IMap m in _iMapDocument.Maps) { if (m.Name == ((MapItem)_contextItem).ToString()) { map = m; break; } } if (map == null) { return; } _iMapDocument.RemoveMap(map); } #endregion #region IDockableWindow Members DockWindowState _dockState = DockWindowState.left; public DockWindowState DockableWindowState { get { return _dockState; } set { _dockState = value; } } public Image Image { get { switch (TocViewMode) { case TOCViewMode.Groups: return imageList1.Images[0]; case TOCViewMode.Datasets: return imageList1.Images[1]; } return null; } } public new string Name { get { switch (TocViewMode) { case TOCViewMode.Groups: return "TOC"; case TOCViewMode.Datasets: return "Source"; } return ""; } set { } } #endregion #region DragDrop private void list_DragEnter(object sender, DragEventArgs e) { if (_iMapDocument == null || _iMapDocument.FocusMap == null) { return; } foreach (string format in e.Data.GetFormats()) { object ob = e.Data.GetData(format); if (ob is List<IExplorerObjectSerialization>) { //List<IExplorerObject> exObjects = ComponentManager.DeserializeExplorerObject((List<IExplorerObjectSerialization>)ob); foreach (IExplorerObjectSerialization ser in (List<IExplorerObjectSerialization>)ob) { if (ser.ObjectTypes.Contains(typeof(IFeatureClass)) || ser.ObjectTypes.Contains(typeof(ITableClass)) || ser.ObjectTypes.Contains(typeof(IRasterClass)) || ser.ObjectTypes.Contains(typeof(IFeatureDataset)) || ser.ObjectTypes.Contains(typeof(ITOCElement)) || ser.ObjectTypes.Contains(typeof(IMap)) || ser.ObjectTypes.Contains(typeof(IMapDocument))) { e.Effect = DragDropEffects.Copy; return; } } } } } async private void list_DragDrop(object sender, DragEventArgs e) { if (_iMapDocument == null || _iMapDocument.FocusMap == null) { return; } foreach (string format in e.Data.GetFormats()) { object ob = e.Data.GetData(format); if (ob is List<IExplorerObjectSerialization>) { ExplorerObjectManager exObjectManager = new ExplorerObjectManager(); List<IExplorerObject> exObjects = await exObjectManager.DeserializeExplorerObject((List<IExplorerObjectSerialization>)ob); if (exObjects == null) { return; } Envelope newMapEnvelope = null; bool added = false; foreach (IExplorerObject exObject in exObjects) { bool firstLayer = _iMapDocument.FocusMap.MapElements.Count == 0; var instance = await exObject?.GetInstanceAsync(); if (instance == null) { continue; } if (instance is IClass) { ILayer layer = LayerFactory.Create((IClass)instance); _iMapDocument.FocusMap.AddLayer(layer); added = true; if (firstLayer) { Append2Envelope(ref newMapEnvelope, (IClass)instance); } } else if (instance is IDataset) { foreach (IDatasetElement element in await ((IDataset)instance).Elements()) { if (element.Class is IFeatureClass || element.Class is ITableClass || element.Class is IRasterClass || element.Class is IWebServiceClass) { ILayer layer = LayerFactory.Create(element.Class); _iMapDocument.FocusMap.AddLayer(layer); added = true; if (firstLayer) { Append2Envelope(ref newMapEnvelope, element.Class); } } } } else if (instance is ITOCElement && ((ITOCElement)instance).Layers != null) { foreach (ILayer layer in ((ITOCElement)instance).Layers) { if (layer is IGroupLayer) { AddGroupLayer(layer as IGroupLayer, ((ITOCElement)instance).TOC); } else { // Werte aus etwaigen Grouplayern übernehen layer.MinimumScale = layer.MinimumScale; layer.MaximumScale = layer.MaximumScale; layer.MinimumLabelScale = layer.MinimumLabelScale; layer.MaximumLabelScale = layer.MaximumLabelScale; layer.MaximumZoomToFeatureScale = layer.MaximumZoomToFeatureScale; if (layer is Layer) { ((Layer)layer).GroupLayer = null; } _iMapDocument.FocusMap.AddLayer(layer); ITOC toc = ((ITOCElement)instance).TOC; if (_iMapDocument.FocusMap.TOC != null && toc != null) { ITOCElement newTOCElement = _iMapDocument.FocusMap.TOC.GetTOCElement(layer); ITOCElement oldTOCElement = toc.GetTOCElement(layer); if (newTOCElement != null && oldTOCElement != null) { _iMapDocument.FocusMap.TOC.RenameElement(newTOCElement, oldTOCElement.Name); newTOCElement.LegendVisible = oldTOCElement.LegendVisible; } } added = true; if (firstLayer) { Append2Envelope(ref newMapEnvelope, layer.Class); } } } } else if (instance is IMap) { _iMapDocument.AddMap(instance as IMap); } else if (instance is IMapDocument && _iMapDocument.Application is IMapApplication) { await ((IMapApplication)_iMapDocument.Application).LoadMapDocument(exObject.FullName); } } if (added) { await BuildList(null); if (newMapEnvelope != null && _iMapDocument.FocusMap.Display != null) { _iMapDocument.FocusMap.Display.Limit = newMapEnvelope; _iMapDocument.FocusMap.Display.ZoomTo(newMapEnvelope); } if (_iMapDocument.Application is IMapApplication) { await ((IMapApplication)_iMapDocument.Application).RefreshActiveMap(DrawPhase.All); } } } } _iMapDocument.TemporaryRestore(); } private void AddGroupLayer(IGroupLayer gLayer, ITOC toc) { if (gLayer == null) { return; } _iMapDocument.FocusMap.AddLayer(gLayer); if (_iMapDocument.FocusMap.TOC != null && toc != null) { ITOCElement newTOCElement = _iMapDocument.FocusMap.TOC.GetTOCElement(gLayer); ITOCElement oldTOCElement = toc.GetTOCElement(gLayer); if (newTOCElement != null && oldTOCElement != null) { _iMapDocument.FocusMap.TOC.RenameElement(newTOCElement, oldTOCElement.Name); newTOCElement.LegendVisible = oldTOCElement.LegendVisible; newTOCElement.OpenCloseGroup(oldTOCElement.ElementType == TOCElementType.OpenedGroup); } } foreach (ILayer layer in gLayer.ChildLayer) { if (layer is IGroupLayer) { AddGroupLayer(layer as IGroupLayer, toc); } else { _iMapDocument.FocusMap.AddLayer(layer); if (_iMapDocument.FocusMap.TOC != null && toc != null) { ITOCElement newTOCElement = _iMapDocument.FocusMap.TOC.GetTOCElement(layer); ITOCElement oldTOCElement = toc.GetTOCElement(layer); if (newTOCElement != null && oldTOCElement != null) { _iMapDocument.FocusMap.TOC.RenameElement(newTOCElement, oldTOCElement.Name); newTOCElement.LegendVisible = oldTOCElement.LegendVisible; } } } } } private void Append2Envelope(ref Envelope env, IClass Class) { IEnvelope cEnv = null; if (Class is IFeatureClass) { cEnv = ((IFeatureClass)Class).Envelope; } else if (Class is IRasterClass && ((IRasterClass)Class).Polygon != null) { cEnv = ((IRasterClass)Class).Polygon.Envelope; } else if (Class is IWebServiceClass) { cEnv = ((IWebServiceClass)Class).Envelope; } if (cEnv == null) { return; } if (env == null) { env = new Envelope(cEnv); } else { env.Union(cEnv); } } #endregion #region Menu Grouplayer Apply private void menuGroupApplyVisibility_Click(object sender, EventArgs e) { if (!(_contextItem is GroupItem) || ((GroupItem)_contextItem).TOCElement == null) { return; } ITOCElement tocElement = ((GroupItem)_contextItem).TOCElement; if (tocElement.Layers.Count != 1 || !(tocElement.Layers[0] is IGroupLayer)) { return; } ApplyGroupVisibility(tocElement.Layers[0] as IGroupLayer); list.Refresh(); } private void menuGroupApplyScales_Click(object sender, EventArgs e) { if (!(_contextItem is GroupItem) || ((GroupItem)_contextItem).TOCElement == null) { return; } ITOCElement tocElement = ((GroupItem)_contextItem).TOCElement; if (tocElement.Layers.Count != 1 || !(tocElement.Layers[0] is IGroupLayer)) { return; } ApplyGroupScales(tocElement.Layers[0] as IGroupLayer); list.Refresh(); } private void ApplyGroupVisibility(IGroupLayer gLayer) { if (gLayer == null) { return; } foreach (ILayer layer in gLayer.ChildLayer) { if (layer == null) { continue; } layer.Visible = gLayer.Visible; if (layer is IGroupLayer) { ApplyGroupVisibility(layer as IGroupLayer); } } } private void ApplyGroupScales(IGroupLayer gLayer) { if (gLayer == null) { return; } foreach (ILayer layer in gLayer.ChildLayer) { if (layer == null) { continue; } layer.MinimumScale = gLayer.MinimumScale; layer.MaximumScale = gLayer.MaximumScale; layer.MinimumLabelScale = gLayer.MinimumLabelScale; layer.MaximumLabelScale = gLayer.MaximumLabelScale; layer.MaximumZoomToFeatureScale = gLayer.MaximumZoomToFeatureScale; if (layer is IGroupLayer) { ApplyGroupVisibility(layer as IGroupLayer); } } } #endregion private void menuUnreferencedLayers_Click(object sender, EventArgs e) { if (_iMapDocument == null || _iMapDocument.FocusMap == null || _iMapDocument.FocusMap.TOC == null) { return; } IMap map = _iMapDocument.FocusMap; ITOC toc = map.TOC; List<IDatasetElement> unreferenced = new List<IDatasetElement>(); foreach (IDatasetElement layer in map.MapElements) { ITOCElement tocElement = null; if (layer is ILayer) { tocElement = toc.GetTOCElement((ILayer)layer); } else { tocElement = null; //toc.GetTOCElement(layer.Class); } if (tocElement == null) { unreferenced.Add(layer); } } if (unreferenced.Count == 0) { MessageBox.Show("Keine unreferenzierten Layer vorhanden..."); return; } FormDeleteDatasetElements dlg = new FormDeleteDatasetElements(unreferenced); if (dlg.ShowDialog() == DialogResult.OK) { foreach (IDatasetElement element in dlg.Selected) { if (element is ILayer) { map.RemoveLayer((ILayer)element); } else { map.MapElements.Remove(element); } } } } } }
namespace JigsawLibrary { public enum Type { Eyes, Mouth } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Supermercado { public partial class frmPrincipal : Form { public frmPrincipal() { InitializeComponent(); } private void SairToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void EmpresaToolStripMenuItem_Click(object sender, EventArgs e) { } private void ProdutosToolStripMenuItem_Click(object sender, EventArgs e) { frmCadProdutos fcp = new frmCadProdutos(); fcp.Show(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //using System.Runtime.Serialization.Formatters.Binary; public class Tkm1_Gm1_Main : MonoBehaviour { int count=0; Button first_Btn_Layer; int first_ImageNumber; public List <Sprite> ImagesList = new List<Sprite>(); void Start () { //random number without repeat int i = 1; while (ImagesList.Count > 0) { int index = UnityEngine.Random.Range (0, ImagesList.Count - 1); Button Btn_Image = GameObject.Find ("Btn_" + i).GetComponent <Button> (); Btn_Image.image.sprite = ImagesList [index]; i++; ImagesList.RemoveAt (index); } //ijade laye roye aksha StartCoroutine (PushLayerImage()); } //ijade laye roye aksha IEnumerator PushLayerImage(){ yield return new WaitForSeconds (5f); for (int i = 1; i < 15; i++) { Button Btn_Layer = GameObject.Find ("Btn_Layer_" + i).GetComponent <Button> (); Btn_Layer.image.enabled = true; } } // Update is called once per frame void Update () { } public void Show_Image(int ImageNumber){ count ++; //invisible layer button Button Btn_Layer = GameObject.Find ("Btn_Layer_" + ImageNumber).GetComponent <Button> (); Btn_Layer.image.enabled = false; if (count == 1) { first_ImageNumber = ImageNumber; first_Btn_Layer = Btn_Layer; } else if (count == 2) { count = 0; //check the correct 2 Images if (CorrectImages (ImageNumber)) { Debug.Log ("correct"); } else { //ijade laye roye 2 aks StartCoroutine (PushLayer2Image(Btn_Layer)); } } } //check the correct 2 Images public bool CorrectImages (int ImageNumber){ Button Btn_Image = GameObject.Find ("Btn_" + ImageNumber).GetComponent <Button> (); Button first_Btn_Image = GameObject.Find ("Btn_" + first_ImageNumber).GetComponent <Button> (); String P =Btn_Image.image.sprite.ToString(); Debug.Log (P); switch (P) { case "Tkhm1_Gm1_110": Debug.Log (first_Btn_Image.image.sprite.ToString()); if (string.Equals(first_Btn_Image.image.sprite.ToString(),"Tkhm1_Gm1_Police")) return true; else return false; break; case "Tkhm1_Gm1_115": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_Orjans") return true; else return false; break; case "Tkhm1_Gm1_122": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_Ab") return true; else return false; break; case "Tkhm1_Gm1_194": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_Gaz") return true; else return false; break; case "Tkhm1_Gm1_125": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_atashNeshani") return true; else return false; break; case "Tkhm1_Gm1_121": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_Bargh") return true; else return false; break; case "Tkhm1_Gm1_123": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_OrjansEjtemayi") return true; else return false; break; case "Tkhm1_Gm1_Police": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_110") return true; else return false; break; case "Tkhm1_Gm1_Orjans": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_115") return true; else return false; break; case "Tkhm1_Gm1_Ab": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_122") return true; else return false; break; case "Tkhm1_Gm1_Gaz": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_194") return true; else return false; break; case "Tkhm1_Gm1_atashNeshani": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_125") return true; else return false; break; case "Tkhm1_Gm1_Bargh": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_121") return true; else return false; break; case "Tkhm1_Gm1_OrjansEjtemayi": if (first_Btn_Image.image.sprite.ToString() == "Tkhm1_Gm1_123") return true; else return false; break; default: return false; } //return false; } //ijade laye roye 2 aks IEnumerator PushLayer2Image(Button Btn_Layer){ yield return new WaitForSeconds (1f); Btn_Layer.image.enabled = true; first_Btn_Layer.image.enabled = true; } }
namespace Processing.Activities.Validate { using System; using System.Threading.Tasks; using Contracts; using MassTransit.Courier; using MassTransit.Logging; public class ValidateActivity : ExecuteActivity<ValidateArguments> { private static readonly ILog Log = Logger.Get<ValidateActivity>(); public async Task<ExecutionResult> Execute(ExecuteContext<ValidateArguments> context) { var address = context.Arguments.GuestsCount; if (address < 1 || address > 10) { await context.Publish<RequestRejected>(new { context.Arguments.RequestId, context.TrackingNumber, Timestamp = DateTime.UtcNow, ReasonText = "Invalid guests count", }); Serilog.Log.Error("Request {id} rejected", context.Arguments.RequestId); return context.Terminate(); } Log.InfoFormat("Validated Request {0} with count {1}", context.Arguments.RequestId, context.Arguments.GuestsCount); return context.Completed(); } } }
using System; using System.Collections.Generic; using System.Reflection; namespace EddiEvents { public class Events { public static IDictionary<string, Type> TYPES = new Dictionary<string, Type>(); public static IDictionary<string, object> SAMPLES = new Dictionary<string, object>(); public static IDictionary<string, string> DEFAULTS = new Dictionary<string, string>(); public static IDictionary<string, string> DESCRIPTIONS = new Dictionary<string, string>(); static Events() { lock (SAMPLES) { try { foreach (var type in typeof(Event).Assembly.GetTypes()) { if ( type.IsInterface || type.IsAbstract || !type.IsSubclassOf( typeof(Event) ) ) { continue; } // Ensure that the static constructor of the class has been run System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle); if (type.GetField("NAME") is var nameField && nameField?.GetValue( null ) is string eventName) { TYPES.Add(eventName, type); if (type.GetField("DESCRIPTION") is var descriptionField && descriptionField?.GetValue(null) is string eventDescription) { DESCRIPTIONS.Add(eventName, eventDescription); } if (type.GetField("DEFAULT") is var defaultField && defaultField?.GetValue(null) is string eventDefault) { DEFAULTS.Add(eventName, eventDefault); } if (type.GetField("SAMPLE") is var sampleField && sampleField?.GetValue(null) is var eventSample ) { SAMPLES.Add(eventName, eventSample); } } } } catch (ReflectionTypeLoadException) { // DLL we can't parse; ignore } } } public static Type TypeByName(string name) { TYPES.TryGetValue(name, out Type value); return value; } public static object SampleByName(string name) { SAMPLES.TryGetValue(name, out object value); return value; } public static string DescriptionByName(string name) { DESCRIPTIONS.TryGetValue(name, out string value); return value; } public static string DefaultByName(string name) { DEFAULTS.TryGetValue(name, out string value); return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace eBikes.Entities.POCOs.SalesPOCOs { public class ProductCatalog { public int PartID { get; set; } public int CartQuantity { get; set; } public string PartName { get; set; } public decimal UnitPrice { get; set; } public int QtyInStock { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using MyApp.Data; using MyApp.Models; namespace MyApp.Controllers { public class EmployeeModelController : Controller { private readonly EmployeeContext _context; public EmployeeModelController(EmployeeContext context) { _context = context; } // GET: EmployeeModel public async Task<IActionResult> Index() { return View(await _context.Employees.ToListAsync()); } // GET: EmployeeModel/Details/5 public async Task<IActionResult> Details(string id) { if (id == null) { return NotFound(); } var employeeModel = await _context.Employees .SingleOrDefaultAsync(m => m.Id == id); if (employeeModel == null) { return NotFound(); } return View(employeeModel); } // GET: EmployeeModel/Create public IActionResult Create() { return View(); } // POST: EmployeeModel/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,FullName,Email,Salary")] EmployeeModel employeeModel) { if (ModelState.IsValid) { _context.Add(employeeModel); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(employeeModel); } // GET: EmployeeModel/Edit/5 public async Task<IActionResult> Edit(string id) { if (id == null) { return NotFound(); } var employeeModel = await _context.Employees.SingleOrDefaultAsync(m => m.Id == id); if (employeeModel == null) { return NotFound(); } return View(employeeModel); } // POST: EmployeeModel/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(string id, [Bind("Id,FullName,Email,Salary")] EmployeeModel employeeModel) { if (id != employeeModel.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(employeeModel); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EmployeeModelExists(employeeModel.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(employeeModel); } // GET: EmployeeModel/Delete/5 public async Task<IActionResult> Delete(string id) { if (id == null) { return NotFound(); } var employeeModel = await _context.Employees .SingleOrDefaultAsync(m => m.Id == id); if (employeeModel == null) { return NotFound(); } return View(employeeModel); } // POST: EmployeeModel/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(string id) { var employeeModel = await _context.Employees.SingleOrDefaultAsync(m => m.Id == id); _context.Employees.Remove(employeeModel); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool EmployeeModelExists(string id) { return _context.Employees.Any(e => e.Id == id); } } }
using Witsml.Data; using Witsml.Extensions; namespace WitsmlExplorer.Api.Query { public class RiskQueries { public static WitsmlRisks GetWitsmlRiskByWellbore(string wellUid, string wellboreUid) { return new WitsmlRisks { Risks = new WitsmlRisk { Uid = "", UidWell = wellUid, UidWellbore = wellboreUid, Name = "", CommonData = new WitsmlCommonData() }.AsSingletonList() }; } public static WitsmlRisks QueryById(string wellUid, string wellboreUid, string riskUid) { return new WitsmlRisks { Risks = new WitsmlRisk { Uid = riskUid, UidWell = wellUid, UidWellbore = wellboreUid }.AsSingletonList() }; } public static WitsmlRisks QueryByNameAndDepth(string wellUid, string wellboreUid, string name, string mdBitStart, string mdBitEnd) { return new WitsmlRisks { Risks = new WitsmlRisk { UidWell = wellUid, UidWellbore = wellboreUid, Name = name, MdBitStart = new WitsmlIndex { Uom = "m", Value = mdBitStart }, MdBitEnd = new WitsmlIndex { Uom = "m", Value = mdBitEnd } }.AsSingletonList() }; } public static WitsmlRisks QueryBySource(string wellUid, string wellboreUid, string source, string extendCategory) { return new WitsmlRisks { Risks = new WitsmlRisk { UidWell = wellUid, UidWellbore = wellboreUid, ExtendCategory = extendCategory, CommonData = new WitsmlCommonData { SourceName = source, }, }.AsSingletonList() }; } public static WitsmlRisks DeleteRiskQuery(string wellUid, string wellboreUid, string uid) { return new WitsmlRisks { Risks = new WitsmlRisk { UidWell = wellUid, UidWellbore = wellboreUid, Uid = uid }.AsSingletonList() }; } } }
using System; using System.Linq; namespace Whathecode.System { public partial class Extensions { /// <summary> /// Returns whether the object equals any of the given values. /// </summary> /// <typeparam name = "T">Type of the objects to compare.</typeparam> /// <param name = "source">The source for this extension method.</param> /// <param name = "toCompare">The objects to compare with.</param> /// <returns>True when the object equals any of the passed objects, false otherwise.</returns> public static bool EqualsAny<T>( this T source, params T[] toCompare ) { return toCompare.Any( o => o.Equals( source ) ); } /// <summary> /// Returns whether all given values equal the object. /// </summary> /// <typeparam name="T">Type of the objects to compare.</typeparam> /// <param name="source">The source for this extension method.</param> /// <param name="toCompare">The objects to compare with.</param> /// <returns>True when all given values equal the object, false otherwise.</returns> public static bool EqualsAll<T>( this T source, params T[] toCompare ) { return toCompare.All( o => o.Equals( source ) ); } /// <summary> /// Returns a selected value when the source is not null; null otherwise. /// </summary> /// <typeparam name = "T">Type of the source object.</typeparam> /// <typeparam name = "TInner">Type of the object which the selector returns.</typeparam> /// <param name = "source">The source for this extension method.</param> /// <param name = "selector">A function which given the source object, returns a selected value.</param> /// <returns>The selected value when source is not null; null otherwise.</returns> public static TInner IfNotNull<T, TInner>( this T source, Func<T, TInner> selector ) where T : class { return source != null ? selector( source ) : default( TInner ); } } }
namespace LineNumbers { using System.IO; public class Startup { public static void Main(string[] args) { using (var reader = new StreamReader (@"D:\Vsichki Startupi\Softuni\C# Advanced 2\Streams\files\text.txt")) { using (var writer = new StreamWriter (@"D:\Vsichki Startupi\Softuni\C# Advanced 2\Streams\files\textWithLines.txt")) { var counter = 1; var line = reader.ReadLine(); while (line != null) { writer.WriteLine($"Line {counter++}: {line}"); line = reader.ReadLine(); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace MovieAngular.Models { public class ApplicationUser : IdentityUser { } public class MoviesAppContext : IdentityDbContext<ApplicationUser> { public DbSet<Movie> Movies { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Runtime.Serialization; using System.Text; namespace jaytwo.Common.Http { [Serializable] public class DownloadException : WebException { public string Content { get; set; } public DownloadException(string message) : base(message) { } public DownloadException(string message, Exception innerException) : base(message, innerException) { } public DownloadException(string message, Exception innerException, WebExceptionStatus status, HttpWebResponse response) : base(message, innerException, status, response) { } protected DownloadException(SerializationInfo info, StreamingContext context) : base(info, context) { } public static DownloadException Create(Exception innerException, HttpWebResponse response, byte[] resultContent) { var encoding = HttpHelper.GetEncoding(response) ?? Encoding.UTF8; var resultContentString = encoding.GetString(resultContent); return Create(innerException, response, resultContentString); } public static DownloadException Create(Exception innerException, HttpWebResponse response, string resultContent) { if (innerException == null) { throw new ArgumentNullException("innerException"); } var result = new DownloadException(innerException.Message, innerException, WebExceptionStatus.ProtocolError, response); result.Content = resultContent; throw result; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Assistenza.BufDalsi.Web.Models.GenericoViewModels { public class UpdateGenericoViewModel { public int ipt_Id { get; set; } public int clt_Id { get; set; } public int gnr_Id { get; set; } public string gnr_Nome { get; set; } public string gnr_Marca { get; set; } public string gnr_Modello { get; set; } public string gnr_Serie { get; set; } public string gnr_Descrizione { get; set; } [DataType(DataType.Date)] public DateTime gnr_UltimaInstallazione { get; set; } [DataType(DataType.Date)] public DateTime gnr_UltimoIntervento { get; set; } public float gnr_OreUltimoIntervento { get; set; } public int gnr_Impianto { get; set; } public Boolean gnr_Rimosso { get; set; } public UpdateGenericoViewModel() { gnr_UltimaInstallazione = new DateTime(1900, 01, 01); gnr_UltimoIntervento = new DateTime(1900, 01, 01); } public UpdateGenericoViewModel(int id, string nome, DateTime ultinst, DateTime ultint, float oreuint, string mar, string mod, string sernum, Boolean rimo,string desc, int ipt) { gnr_Id = id; gnr_Nome = nome; gnr_UltimaInstallazione = ultinst; gnr_UltimoIntervento = ultint; gnr_OreUltimoIntervento = oreuint; gnr_Marca = mar; gnr_Modello = mod; gnr_Serie = sernum; gnr_Rimosso = rimo; gnr_Impianto = ipt; gnr_Descrizione =desc; } } }
using System.Net; using System.Web.Mvc; using AutoMapper; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Domain.Prf; using Profiling2.Domain.Prf.Units; using Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels; using Profiling2.Web.Mvc.Controllers; using SharpArch.NHibernate.Web.Mvc; using SharpArch.Web.Mvc.JsonNet; namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers { [PermissionAuthorize(AdminPermission.CanChangeUnits)] public class OperationAliasesController : BaseController { protected readonly IOrganizationTasks orgTasks; public OperationAliasesController(IOrganizationTasks orgTasks) { this.orgTasks = orgTasks; } public ActionResult Create(int operationId) { Operation op = this.orgTasks.GetOperation(operationId); if (op != null) { OperationAliasViewModel vm = new OperationAliasViewModel(); vm.OperationId = operationId; vm.OperationName = op.Name; return View(vm); } return new HttpNotFoundResult(); } [HttpPost] [Transaction] public ActionResult Create(OperationAliasViewModel vm) { if (ModelState.IsValid) { Operation op = this.orgTasks.GetOperation(vm.OperationId); if (op != null) { OperationAlias alias = new OperationAlias(); Mapper.Map<OperationAliasViewModel, OperationAlias>(vm, alias); alias.Operation = op; alias = this.orgTasks.SaveOperationAlias(alias); return RedirectToAction("Details", "Operations", new { area = "Profiling", id = op.Id }); } ModelState.AddModelError("OperationId", "That operation doesn't exist."); } return Create(vm.OperationId); } public ActionResult Edit(int id) { OperationAlias alias = this.orgTasks.GetOperationAlias(id); if (alias != null) { OperationAliasViewModel vm = new OperationAliasViewModel(alias); return View(vm); } else return new HttpNotFoundResult(); } [HttpPost] [Transaction] public ActionResult Edit(OperationAliasViewModel vm) { if (ModelState.IsValid) { OperationAlias alias = this.orgTasks.GetOperationAlias(vm.Id); if (alias != null) { Mapper.Map<OperationAliasViewModel, OperationAlias>(vm, alias); alias = this.orgTasks.SaveOperationAlias(alias); return JsonNet(string.Empty); } return RedirectToAction("Details", "Operations", new { area = "Profiling", id = vm.OperationId }); } return Edit(vm.Id); } [Transaction] public JsonNetResult Delete(int id) { OperationAlias alias = this.orgTasks.GetOperationAlias(id); if (alias != null) { this.orgTasks.DeleteOperationAlias(alias); Response.StatusCode = (int)HttpStatusCode.OK; return JsonNet("Operation alias successfully removed."); } Response.StatusCode = (int)HttpStatusCode.NotFound; return JsonNet("Operation alias not found."); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Experian.ApiServices.Interfaces.Services { public interface IApiCallerService { Task<T> GetAsync<T>(string uri); } }
using System.Collections.Generic; using System.Linq; using DFC.ServiceTaxonomy.VersionComparison.Models; using DFC.ServiceTaxonomy.VersionComparison.Models.Parts; using Newtonsoft.Json.Linq; namespace DFC.ServiceTaxonomy.VersionComparison.Services.PropertyServices { public class SingleChildPropertyService : IPropertyService { public bool CanProcess(JToken? jToken, string? propertyName = null) { return jToken != null && jToken.Type == JTokenType.Object && jToken.Children().Count() == 1; } public IList<PropertyExtract> Process(string propertyName, JToken? jToken) { var objectValue = jToken?.ToObject<ObjectValue>(); return new List<PropertyExtract> {new PropertyExtract {Key = propertyName, Name = propertyName, Value = objectValue?.ToString()}}; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Clear_Botton : MonoBehaviour { public void ReStart_Botton() { SceneManager.LoadScene("MainScene"); } public void TitleBack_Botton() { SceneManager.LoadScene("GameStart"); } }
using DevExpress.XtraEditors; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlServerCe; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SQL_HELPER_APP { public partial class Frm_SDFFileViewer : XtraForm { string sdfFile = ""; public Frm_SDFFileViewer() { InitializeComponent(); } private void sb_OpenSdf_Click(object sender, EventArgs e) { OpenFileDialog fd = new OpenFileDialog(); using (fd) { fd.Filter = "Sdf Files (*.sdf)|*.sdf|All Files (*.*)|*.*"; fd.ShowDialog(); sdfFile = lc_SDFPath.Text = fd.FileName; if (string.IsNullOrEmpty(sdfFile)) return; SqlCeConnection con = new SqlCeConnection("Data Source=" + sdfFile); try { con.Open(); SqlCeCommand cmd = new SqlCeCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", con); SqlCeDataReader reader = cmd.ExecuteReader(); lbc_SDFTableNames.Items.Clear(); while (reader.Read()) { lbc_SDFTableNames.Items.Add(reader.GetString(0)); } reader.Close(); con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void SDFQuery(string query = "") { query = query == "" ? ("SELECT * FROM " + lbc_SDFTableNames.SelectedItem.ToString()) : query; try { SqlCeConnection con = new SqlCeConnection("Data Source=" + sdfFile); con.Open(); grc_SDFData.DataSource = null; grv_SDFData.PopulateColumns(); SqlCeCommand cmd = new SqlCeCommand(query, con); SqlCeDataAdapter da = new SqlCeDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); grc_SDFData.DataSource = dt; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void lbc_SDFTableNames_SelectedIndexChanged(object sender, EventArgs e) { SDFQuery(""); } private void grv_SDFData_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e) { //add export to excel to menu if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Row) { e.Menu.Items.Add(new DevExpress.Utils.Menu.DXMenuItem("Export to Excel", new EventHandler(ExportToExcel_Click))); e.Menu.Items.Add(new DevExpress.Utils.Menu.DXMenuItem("Export to Pdf", new EventHandler(ExportToPdf_Click))); } } private void ExportToExcel_Click(object sender, EventArgs e) { //export gridcontrol to excel SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Excel files (*.xls)|*.xls"; sfd.FileName = "SDFData.xls"; if (sfd.ShowDialog() == DialogResult.OK) { grc_SDFData.ExportToXls(sfd.FileName); System.Diagnostics.Process.Start(sfd.FileName); } } private void ExportToPdf_Click(object sender, EventArgs e) { //export gridcontrol to excel SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Excel files (*.xls)|*.xls"; sfd.FileName = "SDFData.xls"; if (sfd.ShowDialog() == DialogResult.OK) { grc_SDFData.ExportToPdf(sfd.FileName); System.Diagnostics.Process.Start(sfd.FileName); } } private void sb_RunQuery_Click(object sender, EventArgs e) { SDFQuery(me_SQLQuery.Text); } } }
using System; namespace ProgFrog.Interface.TaskRunning.Compilers.Exceptions { public class CompilationFailedException : ApplicationException { public CompilationFailedException(string messagge) : base(messagge) { } } }