text
stringlengths
13
6.01M
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using PollyDemo.SPA.Clients; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using static Newtonsoft.Json.JsonConvert; namespace PollyDemo.SPA.Controllers { [ApiController] [Route("api/companies")] public class CompaniesController { private readonly CompaniesClient _client; private readonly IHttpClientFactory _factory; private readonly IHttpContextAccessor _httpContextAccessor; public CompaniesController(CompaniesClient client, IHttpClientFactory factory, IHttpContextAccessor httpContextAccessor) { _client = client; _factory = factory; _httpContextAccessor = httpContextAccessor; } [HttpGet] public async Task<ActionResult<dynamic>> Get() { var response = await _factory.CreateClient("companies").GetAsync("api/companies"); response.Headers.TryGetValues("X-Retry-Count", out var r); _httpContextAccessor.HttpContext.Request.HttpContext.Response.Headers.Add("X-Retry-Count", r.First()); return DeserializeObject((await response.Content.ReadAsStringAsync())); return await _client.Get(); } } }
using Abhs.Common.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Model.ViewModel { public class StudentModelView { public StudentModelView(Dictionary<int, string> classDic) { this.classDic = classDic; } private Dictionary<int, string> classDic { get; set; } public int id { get; set; } /// <summary> /// 学号 /// </summary> public string studentNo { get; set; } = ""; /// <summary> /// 账号 /// </summary> public string userAccount { get; set; } /// <summary> /// 姓名 /// </summary> public string userName { get; set; } /// <summary> /// 性别 /// </summary> public string sexName { get { return Enum.GetName(typeof(EnumSex), sex)??"男"; } } public int sex { get; set; } /// <summary> /// 学段 /// </summary> public string grade { get { return Enum.GetName(typeof(EnumGradeSection), gradeId) ?? ""; } } public int gradeId { get; set; } public string classId { get; set; } public string userHead { get; set; } /// <summary> /// 班级名称 /// </summary> public string className { get { var name = string.Empty; if (!string.IsNullOrEmpty(this.classId)) { var sb = new StringBuilder(); foreach (var item in this.classId.Split(',')) { int key = Convert.ToInt32(item); if (this.classDic.ContainsKey(key)) { sb.Append(this.classDic[key]+","); } } name = sb.ToString(); if (name != null && name.Contains(",")) name = name.TrimEnd(','); } return name; } } /// <summary> /// 金币 /// </summary> public int coin { get; set; } /// <summary> /// 积分 /// </summary> public int mark { get; set; } /// <summary> /// 注册时间 /// </summary> public string regTime { get; set; } /// <summary> /// 到期时间 /// </summary> public string finishTime { get; set; } /// <summary> /// 最后登录时间 /// </summary> public string lastLoginTime { get; set; } public int fromType { get; set; } /// <summary> /// 来源 /// </summary> public string from { get { return fromType > 0 ? "" : ""; } } /// <summary> /// 状态 /// </summary> public string statusName { get { return Enum.GetName(typeof(EnumStatus), status); } } public int status { get; set; } //是否禁用计算训练 public int moudle { get; set; } public int isAble { get { if (this.moudle == 0) return 0; return (this.moudle& (int)EnumStudentMoudle.计算训练)>0?1:0; } } } public class ClassStudentModelView { public ClassStudentModelView(Dictionary<int, int> lessonDic) { this.lessonDic = lessonDic; } private Dictionary<int, int> lessonDic { get; set; } public int id { get; set; } /// <summary> /// 学号 /// </summary> public string studentNo { get; set; } = ""; /// <summary> /// 出勤率 /// </summary> public string attendanceRate { get; set; } public int lessonId { get; set; } /// <summary> /// 学习进度 /// </summary> public string studyProcess { get { if (this.lessonDic.ContainsKey(this.lessonId)) return $"第{this.lessonDic[this.lessonId]}课时"; return ""; } } /// <summary> /// 账号 /// </summary> public string userAccount { get; set; } /// <summary> /// 姓名 /// </summary> public string userName { get; set; } /// <summary> /// 性别 /// </summary> public string sexName { get { return Enum.GetName(typeof(EnumSex), sex)??"男"; } } public int sex { get; set; } /// <summary> /// 学段 /// </summary> public string grade { get { return Enum.GetName(typeof(EnumGradeSection), gradeId) ?? ""; } } public int gradeId { get; set; } /// <summary> /// 金币 /// </summary> public int coin { get; set; } /// <summary> /// 积分 /// </summary> public int mark { get; set; } /// <summary> /// 到期时间 /// </summary> public string finishTime { get; set; } /// <summary> /// 最后登录时间 /// </summary> public string lastLoginTime { get; set; } /// <summary> /// 状态 /// </summary> public string statusName { get { return Enum.GetName(typeof(EnumStudentStatus), status); } } public int status { get; set; } public int classId { get; set; } public string createTime { get; set; } } public class StudentCountView { public int allotCount { get; set; } = 0; public int allotTimeOut { get; set; } = 0; public int notAllotCount { get; set; } = 0; public int notAllotTimeOut { get; set; } = 0; } public class SchoolCountView { public int schoolId { get; set; } public string name { get; set; } public string manager { get; set; } public int count { get; set; } public int allCount { get; set; } } }
using System; using System.Collections.Generic; namespace Euler_Logic.Problems.AdventOfCode.Y2021 { public class Problem24 : AdventOfCodeBase { private Variables _var = new Variables(); private long[] _input; private long[] _y; private List<Tuple<int, int>> _set; public override string ProblemName { get { return "Advent of Code 2021: 24"; } } public override string GetAnswer() { return Answer1().ToString(); } public override string GetAnswer2() { return Answer2().ToString(); } private string Answer1() { _input = new long[14]; _y = new long[14]; SetSets(); Recurisve(0, 4, 0, true); return ConvertToString(); } private string Answer2() { _input = new long[14]; _y = new long[14]; SetSets(); Recurisve(0, 4, 0, false); return ConvertToString(); } private bool Recurisve(int index, int last, int setIndex, bool findHighest) { if (findHighest) { for (long num = 9; num >= 1; num--) { _input[index] = num; var result = RecurisveTest(index, last, setIndex, findHighest); if (result) return true; } } else { for (long num = 1; num <= 9; num++) { _input[index] = num; var result = RecurisveTest(index, last, setIndex, findHighest); if (result) return true; } } return false; } private bool RecurisveTest(int index, int last, int setIndex, bool findHighest) { if (index == last) { _var.Reset(); RunManual(); if (_y[last] == 0) { if (setIndex == _set.Count - 1) { return true; } else { var nextSet = _set[setIndex + 1]; var result = Recurisve(nextSet.Item1, nextSet.Item2, setIndex + 1, findHighest); if (result) return true; } } } else { var result = Recurisve(index + 1, last, setIndex, findHighest); if (result) return true; } return false; } private void SetSets() { _set = new List<Tuple<int, int>>(); _set.Add(new Tuple<int, int>(0, 4)); _set.Add(new Tuple<int, int>(5, 7)); _set.Add(new Tuple<int, int>(8, 9)); _set.Add(new Tuple<int, int>(10, 10)); _set.Add(new Tuple<int, int>(11, 11)); _set.Add(new Tuple<int, int>(12, 12)); _set.Add(new Tuple<int, int>(13, 13)); } private string ConvertToString() { return string.Join("", _input); } private void RunManual() { Manual(_input[0], 1, 12, 6, 0); Manual(_input[1], 1, 11, 12, 1); Manual(_input[2], 1, 10, 5, 2); Manual(_input[3], 1, 10, 10, 3); Manual(_input[4], 26, -16, 7, 4); Manual(_input[5], 1, 14, 0, 5); Manual(_input[6], 1, 12, 4, 6); Manual(_input[7], 26, -4, 12, 7); Manual(_input[8], 1, 15, 14, 8); Manual(_input[9], 26, -7, 13, 9); Manual(_input[10], 26, -8, 10, 10); Manual(_input[11], 26, -4, 11, 11); Manual(_input[12], 26, -15, 9, 12); Manual(_input[13], 26, -8, 9, 13); } private void Manual(long w, long a, long b, long c, int yIndex) { if ((_var.Z % 26) + b != w) { _var.X = 1; _var.Y = 26; } else { _var.X = 0; _var.Y = 1; } _var.Z /= a; _var.Z *= _var.Y; _var.Y = (w + c) * _var.X; _var.Z += _var.Y; _y[yIndex] = _var.Y; } private class Variables { public long X { get; set; } public long Y { get; set; } public long Z { get; set; } public void Reset() { X = 0; Y = 0; Z = 0; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PowerUpManager : MonoBehaviour { // For each of our powerups, have a bool. private bool doublePoints; private bool safeMode; private bool slow; private bool level; // Have a int for the amount of score to be added via the gem. public int gemAmount; // determine if the powerup is active. private bool noSpikesCurrent; private bool doublePointsCurrent; private bool levelCurrent; // This is a time for all the powerups. public float timeForPowerup; // This is reference to both the score and platform managers so that we are able to access data. private ScoreManager scoreManagement; public float normalPointsPerSecond; // This is a reference to the original maximum height value that we will be changing when the player pick's up the level pickup. public float maximumHeightOriginal; // This is reference to the platform generate and the spikerate. // this is so we can remove the spikes, as well as reset the spike rate. private PlatformCreator platformGenerator; private float spikeRate; // This is reference to the game manager so that we can have access to resetting the powerups. private GameManagement gameManager; // This is an array of all the spikes within the game so that they can all be deactivated at the same time. private objectRemover[] spikeList; // These are the audio clips for the power ups. public AudioSource noSpikesSound; public AudioSource doublePointsSound; public AudioSource slowSound; public AudioSource levelSound; public AudioSource gemSound; // We also need to get a reference to each of the powerup UI elements to get access to their timers. public GameObject spikeNoMore; public GameObject doublePoint; public GameObject levelUI; // We also need a timer for each of the powerups. public float safeModeTimer; public float doublePointsTimer; public float levelTimer; public PlayerMovement player; // Start is called before the first frame update void Start() { // Get these private variables assigned so that we can start to modify data for powerups. scoreManagement = FindObjectOfType<ScoreManager>(); platformGenerator = FindObjectOfType<PlatformCreator>(); gameManager = FindObjectOfType<GameManagement>(); // get references to the original values of the score multiple and the spike remover. normalPointsPerSecond = scoreManagement.scorePerSecond; spikeRate = platformGenerator.randomSpikeGeneratePercentage; maximumHeightOriginal = platformGenerator.maximumHeightChange; } // Update is called once per frame void Update() { // If double points is active, set the score per second to be 2x and set the should double boolean to true if (doublePointsCurrent && doublePointsTimer > 0) { scoreManagement.scorePerSecond = normalPointsPerSecond * 2.0f; scoreManagement.shouldDouble = true; Timer doubleTimer = doublePoint.GetComponentInChildren<Timer>(); doubleTimer.timer = Mathf.Round(doublePointsTimer -= Time.deltaTime); } //if we are in safe mode, set the random spike percentage to 0. if (noSpikesCurrent && safeModeTimer > 0) { // We set the spike percentage change to 0. platformGenerator.randomSpikeGeneratePercentage = 0.0f; // We then get a reference to the Timer component that is attached to the UI elements. Timer spikeTimer = spikeNoMore.GetComponentInChildren<Timer>(); // If we sucessfully get a reference, then we want to set the timer to be that of the internal // timer within the powerUpManager minus deltaTime. if (spikeTimer) { spikeTimer.timer = Mathf.Round(safeModeTimer -= Time.deltaTime); } } // If we have the level pickup still active, then we want to simply decrement both the timers // of the UI element and the internal timer. if (levelTimer > 0f && levelCurrent) { Timer levelUITimer = levelUI.GetComponentInChildren<Timer>(); levelUITimer.timer = Mathf.Round(levelTimer -= Time.deltaTime); } // This is for when each of the timers hit 0 for each of the powerups. // Once the nospikes timer is finished, we want to reset the random spike value to be what it originally was // then we want to set the boolean values to false, signalling that we no longer have this powerup active. if (safeModeTimer <= 0f && noSpikesCurrent) { platformGenerator.randomSpikeGeneratePercentage = spikeRate; noSpikesCurrent = false; spikeNoMore.SetActive(false); } // Once the doublePoints timer is finished, we want to reset the score per second value to be what it originally was // then we want to set the boolean values to false, signalling that we no longer have this powerup active. if (doublePointsTimer <= 0f && doublePointsCurrent) { doublePointsCurrent = false; scoreManagement.scorePerSecond = normalPointsPerSecond; scoreManagement.shouldDouble = false; doublePoint.SetActive(false); } // Once the leveler timer is finished, we want to reset the random height value to be what it originally was // then we want to set the boolean values to false, signalling that we no longer have this powerup active. if (levelCurrent && levelTimer <= 0f) { platformGenerator.maximumHeightChange = maximumHeightOriginal; levelUI.SetActive(false); levelCurrent = false; } } public void ActivatePowerup(bool points, bool spikes, bool slowDown,bool levelValue,bool gem, float time) { // recieve the values from the pickup on what type of pickup and how long the pickup lasts. doublePoints = points; safeMode = spikes; slow = slowDown; level = levelValue; timeForPowerup = time; // We then want to check to see which powerup was collected via the activate powerup function. // Once we know which of thses were activated, activate the visual timer if (safeMode) { // set the boolean values that we use to check if the powerup is active to true. safeModeTimer = time; spikeNoMore.SetActive(true); noSpikesCurrent = true; // get a reference to the UI element that is linked to the spike powerup. Timer spikeTimer = spikeNoMore.GetComponentInChildren<Timer>(); // if we got the reference, then make the UI timer be that of the built in timer. if (spikeTimer) { spikeTimer.timer = safeModeTimer; } //find all the spikes within the level and deactivate them. spikeList = FindObjectsOfType<objectRemover>(); for (int i = 0; i < spikeList.Length; i++) { if (spikeList[i].gameObject.name.Contains("Spikes")) { spikeList[i].gameObject.SetActive(false); } } // Then play the sound effect for the pickup. noSpikesSound.Play(); } // If we picked up a double point powerup, then set double points tto be active and set the UI timer. if (doublePoints) { doublePointsTimer = time; doublePointsCurrent = true; doublePoint.SetActive(true); Timer doubleTimer = spikeNoMore.GetComponentInChildren<Timer>(); if (doubleTimer) { doubleTimer.timer = doublePointsTimer; } // Then play the sound effect for the pickup. doublePointsSound.Play(); } // If we picked up the slow pickup, apply the effects immediately with no timer. if (slow) { player.speed = player.speed * 0.85f; //player.distanceMilestone += 100f; player.speedMilestoneCount += 100f; // Then play the sound effect for the pickup. slowSound.Play(); } // If its the level pickup, set the timer to be active and ensure the leveler bool is active. if (level) { levelUI.SetActive(true); levelTimer = time; levelCurrent = true; platformGenerator.maximumHeightChange = 0f; levelSound.Play(); } if (gem) { scoreManagement.AddScore(gemAmount); gemSound.Play(); } } }
using System; using System.Data; namespace SimplySqlSchema.Attributes { public class AliasTypeAttribute : Attribute { public SqlDbType AsType { get; } public AliasTypeAttribute(SqlDbType asType) { this.AsType = asType; } } }
using UBaseline.Shared.ArticleStartPanel; using Uintra.Core.Search.Converters.SearchDocumentPanelConverter; using Uintra.Core.Search.Entities; using Umbraco.Core; namespace Uintra.Features.Search.Converters.Panel { public class ArticleStartPanelSearchConverter : SearchDocumentPanelConverter<ArticleStartPanelViewModel> { protected override SearchablePanel OnConvert(ArticleStartPanelViewModel panel) { return new SearchablePanel { Title = panel.Title, Content = panel.Description?.Value?.StripHtml() }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace webApp.Areas.Flota.Controllers { public class AeronavegabilidadController : Controller { public ActionResult Aeronaves() { return View(); } public ActionResult Contadores() { return View(); } public ActionResult ComponentesCompuestos() { return View(); } public ActionResult ComponentesInstalados() { return View(); } public ActionResult ContadorAeronave() { return View(); } public ActionResult ContadorComponente() { return View(); } public ActionResult PropiedadComponente() { return View(); } } }
using System; using InvoiceSOLIDApp; using NUnit.Framework; namespace InvoiceSOLID_Test { [TestFixture] public class Invoice { [Test] public void CanAddFinalInvoice() { var finalInvoice = new FinalInvoice(); Assert.IsNotNull(finalInvoice); Assert.Greater(finalInvoice.GetDiscount(200),0); finalInvoice.Add(); finalInvoice.Delete(); } [Test] public void CanAddProposedInvoice() { var proposedInvoice = new ProposedInvoice(); Assert.IsNotNull(proposedInvoice); Assert.Greater(proposedInvoice.GetDiscount(200), 0); proposedInvoice.Add(); proposedInvoice.Delete(); } } }
using System; using UnityEngine; namespace Egret3DExportTools { public class AnimatorSerializer : AnimationSerializer { protected override bool Match(Component component) { var aniamtior = component as Animator; if (aniamtior.runtimeAnimatorController == null) { MyLog.Log("缺少runtimeAnimatorController"); return false; } var clips = aniamtior.runtimeAnimatorController.animationClips; if (clips == null || clips.Length == 0) { MyLog.Log("clips为空"); return false; } return true; } protected override void Serialize(Component component, ComponentData compData) { var aniamtior = component as Animator; var clips = aniamtior.runtimeAnimatorController.animationClips; compData.properties.SetBool("autoPlay", true); // TODO compData.properties.SetAnimation(component.gameObject, clips); } } }
namespace Crystal.Plot2D { public static class Constants { public const double DoubleMinimum = 0.01d; public const string ThemeUri = @"/Crystal.Plot2D;component/Themes/Generic.xaml"; public const string LegendResourceUri = @"/Crystal.Plot2D;component/LegendItems/LegendResources.xaml"; public const string NavigationResourceUri = @"/Crystal.Plot2D;component/Navigation/LongOperationsIndicatorResources.xaml"; public const string ShapeResourceUri = @"/Crystal.Plot2D;component/Shapes/RangeHighlightStyle.xaml"; public const string AxisResourceUri = @"/Crystal.Plot2D;component/Axes/AxisControlStyle.xaml"; } }
// DataBinary: serializable data container class for data to be saved in a binary format. This is required for the Serializable attribute. using System; using System.Collections.Generic; [Serializable()] public class DataBinary { public Dictionary<string,object> Data {get; private set;} = new Dictionary<string, object>(); public void SaveBinary(Dictionary<string,object> dataDict, string filename) { this.Data = dataDict; FileBinary.SaveToFile(filename, this); } }
using AutoMapper; using Exemplo.Application.ViewModel; using Exemplo.Domain.Entities; namespace Exemplo.Api.Config { public class AutomapperConfig : Profile { public AutomapperConfig() { CreateMap<Contato, ContatoViewModel>().ReverseMap(); } } }
using UnityEngine; using System.Collections; public class MirvBullet : MonoBehaviour { public float timeBeforeExplosion; public float bulletSpeed; public float explosionSize; GameObject explosionSphere; GameObject explosion; const float SPHERE_DURATION = 1f; // Use this for initialization void Start () { explosionSphere = (GameObject)Resources.Load ("Prefabs/PurpleExplosion", typeof(GameObject)); explosion = (GameObject)Resources.Load("Prefabs/ExplosionPurple", typeof(GameObject)); } // Update is called once per frame void Update () { timeBeforeExplosion -= Time.deltaTime; if (timeBeforeExplosion >= 0) { transform.position += transform.up * bulletSpeed / 100; } else { var sphere = (GameObject)Instantiate(explosionSphere, transform.position, explosionSphere.transform.rotation); sphere.transform.localScale = new Vector3(explosionSize,explosionSize,explosionSize); sphere.tag = "Purple"; sphere.layer = LayerMask.NameToLayer("Character Bullet"); sphere.GetComponent<MeshRenderer>().enabled = false; Instantiate(explosion, transform.position, transform.rotation); Destroy (sphere, SPHERE_DURATION); Destroy(gameObject); } } }
using UnityEngine; public class BoxController : MonoBehaviour { public float Speed = 1f; public string Type; public bool IsDead = false; public Sprite DefaultSprite; public Sprite MissSprite; public Sprite DeadSprite; private float ResetSpriteCooldown = 1; private SpriteRenderer _renderer; private BoxFiller _filler; private Player _player; // Use this for initialization void Start() { _player = FindObjectOfType<Player>(); _filler = GetComponent<BoxFiller>(); _renderer = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { transform.position += Vector3.right * Speed; } public void Die() { _player.Pay(); CancelInvoke("ResetSprite"); IsDead = true; _renderer.sprite = DeadSprite; _filler.RemoveAllCubes(); } public void Miss() { _renderer.sprite = MissSprite; Invoke("ResetSprite", ResetSpriteCooldown); _player.Miss(); } private void ResetSprite() { _renderer.sprite = DefaultSprite; } }
namespace OrgMan.DomainObjects.Common { public class IndividualPersonDomainModel { } }
// Copyright © 2020 TR Solutions Pte. Ltd. // Licensed under Apache 2.0 and MIT // See appropriate LICENCE files for details. using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeckBehaviour : MonoBehaviour { public Transform[] cards; private Transform[] cardInstances; // Start is called before the first frame update void Start() { // Note cards are instantiated such that the last item is on top this.cardInstances = new Transform[cards.Length]; for (int iCard = 0; iCard < cards.Length; iCard++) { var card = cards[iCard]; var cardInstance = Instantiate(card, transform); //var cardBehaviour = cardInstance.GetComponent<CardBehaviour>(); //if (cardBehaviour) //{ // cardBehaviour.SetOrderInLayer(iCard); //} this.cardInstances[iCard] = cardInstance; } Shuffle(); } // Update is called once per frame void Update() { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); if (cards.Length > 0 && Input.GetMouseButtonDown(0)) { // print("mouse down detected!"); Collider2D myCollider = null; for (int iCard = 0; iCard < cards.Length; iCard++) { var cardCollider = cardInstances[iCard].GetComponent<Collider2D>(); if (cardCollider != null && Physics2D.OverlapPoint(mousePos) == cardCollider) { //print(string.Format("Checking {0} against mouse point {1}", cardCollider.bounds.size, mousePos)); //var cardBounds = new Bounds(mousePosV3, new Vector3(0.1f, 0.1f, 0.1f)); //if (cardCollider.bounds.Contains(mousePosV3)) //{ myCollider = cardCollider; break; //} } } if (myCollider != null) { print("Deck has been touched."); // Pull the last card var dealtCard = cardInstances[cardInstances.Length - 1]; // draw down both the card protos and the card instances // We only do this because the card protos are public, and someone might be watching Transform[] newCards = new Transform[cards.Length - 1]; Transform[] newCardInstances = new Transform[cards.Length - 1]; for (int iCard = 0; iCard < newCards.Length; iCard++) { newCards[iCard] = cards[iCard]; newCardInstances[iCard] = cardInstances[iCard]; } this.cards = newCards; this.cardInstances = newCardInstances; // separate the card from the deck object dealtCard.parent = null; // Tell the card the mouse has been pressed over it var cardBehaviour = dealtCard.GetComponent<CardBehaviour>(); if (cardBehaviour != null) { cardBehaviour.StartDrag(mousePos); } } } } public void Shuffle() { for (int pass = 0; pass < 15; pass++) { for (int iCard = 0; iCard < cards.Length; iCard++) { int iSwapCard = Random.Range(0, cards.Length); if (iSwapCard != iCard) { var savedCard = cards[iCard]; cards[iCard] = cards[iSwapCard]; cards[iSwapCard] = savedCard; var savedCardInstance = cardInstances[iCard]; cardInstances[iCard] = cardInstances[iSwapCard]; cardInstances[iSwapCard] = savedCardInstance; } } } } public void DealTopCard() { var dealtCard = cards[cards.Length - 1]; Transform[] newCards = new Transform[cards.Length - 1]; for (int iCard = 0; iCard < cards.Length - 1; iCard++) { newCards[iCard] = cards[iCard]; } cards = newCards; dealtCard.parent = null; // so now available to be moved. } public void RemoveCardFromDeck(Transform cardToRemove) { int foundIndex = -1; for (int iCard = 0; iCard < cards.Length && foundIndex < 0; iCard++) { if (cards[iCard] == cardToRemove) { foundIndex = iCard; } } if (foundIndex >= 0) { print(string.Format("Removing card at index {0}", foundIndex)); Transform[] newCards = new Transform[cards.Length - 1]; for (int iCard = 0; iCard < foundIndex; iCard++) { newCards[iCard] = cards[iCard]; } for (int iCard = foundIndex + 1; iCard < cards.Length; iCard++) { newCards[iCard - 1] = cards[iCard]; } this.cards = newCards; } else { print(string.Format("Didn't find card {0} in deck!", cardToRemove)); } } public void RestoreCard(Transform card) { print(string.Format("Replacing card at index {0}", cards.Length)); Transform[] newCards = new Transform[cards.Length + 1]; Transform[] newCardInstances = new Transform[cards.Length + 1]; for(int iCard=0; iCard < cards.Length; iCard++) { newCards[iCard] = cards[iCard]; newCardInstances[iCard] = cardInstances[iCard]; } // since we don't have the prefab, we'll just use the instantiated object // as a prefab. newCards[cards.Length] = card; newCardInstances[cards.Length] = card; cards = newCards; cardInstances = newCardInstances; } public int GetOrderInLayer(int sortingLayerID) { var topCard = cardInstances.Length > 0 ? cardInstances[cardInstances.Length - 1] : null; var topCardBehaviour = topCard != null ? topCard.GetComponent<CardBehaviour>() : null; return topCardBehaviour != null ? topCardBehaviour.GetOrderInLayer(sortingLayerID) : int.MinValue; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletImpact : MonoBehaviour { private Vector3 bulletRadiusSize; private float duration; void Start() { } // Update is called once per frame void Update() { StartBulletImpact(); } public void StartBulletImpact() { transform.localScale = Vector3.MoveTowards(transform.localScale, bulletRadiusSize, duration * Time.deltaTime); if( Vector2.Distance(transform.localScale,bulletRadiusSize)<0.01f) { Destroy(this.gameObject); } } public void SetBulletRadiusSize(Vector3 bulletRadiusSize) { this.bulletRadiusSize = bulletRadiusSize; } public void SetDuration(float duration) { this.duration = duration; } public void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.GetComponent<Enemy>()!=null) { GameManager.insntance.ScoreUp(); Destroy(collision.gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LizardCosmetics; using Rainbow.Enum; using UnityEngine; using RWCustom; namespace Rainbow.CreatureAddition { public class FormulatedLizardGraphics : LizardGraphics { public FormulatedLizardGraphics(PhysicalObject ow) : base(ow) { this.lizard = ow as FormulatedLizard; int backupSeed = UnityEngine.Random.seed; UnityEngine.Random.seed = this.lizard.abstractCreature.ID.RandomSeed; this.cosmetics.Clear(); this.ImportAllCosmetics(); if (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard) { for (int k = 0; k < this.rainbowLizard.rainbowParams.tailSegments; k++) { float num3 = Mathf.InverseLerp(0f, (float)(this.rainbowLizard.rainbowParams.tailSegments - 1), (float)k); this.tail[k].rad += Mathf.Sin(Mathf.Pow(num3, 0.7f) * 3.14159274f) * 2.5f; this.tail[k].rad *= 1f - Mathf.Sin(Mathf.InverseLerp(0f, 0.4f, num3) * 3.14159274f) * 0.5f; } } UnityEngine.Random.seed = backupSeed; this.blackSalamander = this.rainbowLizard.rainbowParams.darkBody; this.iVars = this.rainbowLizard.RainbowState.iVars; this.blindLizardLightUpHead = 0f; this.camoColorAmount = -1f; this.camoColor = Color.white; } public FormulatedLizard rainbowLizard => this.lizard as FormulatedLizard; public new Color effectColor { get { if (this.rainbowLizard.RainbowState.Blind) { return this.palette.blackColor; } return this.rainbowLizard.effectColor; } } private void ImportAllCosmetics() { int s = this.startOfExtraSprites; for (int i = 0; i < this.rainbowLizard.RainbowState.cosmetics.Count; i++) { if (RainbowLizardBreedParams.dictAppendage.TryGetValue((int)this.rainbowLizard.RainbowState.cosmetics[i], out Type t)) { Template template = Activator.CreateInstance(t, new object[] { this, s }) as Template; s = this.AddRainbowCosmetic(s, template); } else { Debug.Log(string.Concat("No such thing as ", this.rainbowLizard.RainbowState.cosmetics[i])); } } } private int AddRainbowCosmetic(int spriteIndex, Template cosmetic) { this.cosmetics.Add(cosmetic); spriteIndex += cosmetic.numberOfSprites; this.extraSprites += cosmetic.numberOfSprites; //Debug.Log(cosmetic.GetType()); return spriteIndex; } private float blindLizardLightUpHead, camoColorAmount, camoColorAmountDrag; private Color camoColor, pickUpColor; public override void Update() { base.Update(); if (this.rainbowLizard.RainbowState.Camoflague) { if (this.lizard.dead) { this.camoColorAmount = Mathf.Lerp(this.camoColorAmount, 0.3f, 0.01f); } else { if ((this.lizard.State as LizardState).health < 0.6f && UnityEngine.Random.value * 1.5f < (this.lizard.State as LizardState).health && UnityEngine.Random.value < 1f / ((!this.lizard.Stunned) ? 40f : 10f)) { this.whiteGlitchFit = (int)Mathf.Lerp(5f, 40f, (1f - (this.lizard.State as LizardState).health) * UnityEngine.Random.value); } if (this.whiteGlitchFit == 0 && this.lizard.Stunned && UnityEngine.Random.value < 0.05f) { this.whiteGlitchFit = 2; } if (this.whiteGlitchFit > 0) { this.whiteGlitchFit--; float f = 1f - (this.lizard.State as LizardState).health; if (UnityEngine.Random.value < 0.2f) { this.camoColorAmountDrag = 1f; } if (UnityEngine.Random.value < 0.2f) { this.camoColorAmount = 1f; } if (UnityEngine.Random.value < 0.5f) { this.camoColor = Color.Lerp(this.camoColor, new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value), Mathf.Pow(f, 0.2f) * Mathf.Pow(UnityEngine.Random.value, 0.1f)); } if (UnityEngine.Random.value < 0.333333343f) { this.pickUpColor = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); } } else if (this.showDominance > 0f) { this.whiteDominanceHue += UnityEngine.Random.value * Mathf.Pow(this.showDominance, 2f) * 0.2f; if (this.whiteDominanceHue > 1f) { this.whiteDominanceHue -= 1f; } this.camoColor = Color.Lerp(this.camoColor, Custom.HSL2RGB(this.whiteDominanceHue, 1f, 0.5f), Mathf.InverseLerp(0.5f, 1f, Mathf.Pow(this.showDominance, 0.5f)) * UnityEngine.Random.value); this.camoColorAmount = Mathf.Lerp(this.camoColorAmount, 1f - Mathf.Sin(Mathf.InverseLerp(0f, 1.1f, Mathf.Pow(this.showDominance, 0.5f)) * 3.14159274f), 0.1f); } else { if (this.lizard.animation == Lizard.Animation.ShootTongue || this.lizard.animation == Lizard.Animation.PrepareToLounge || this.lizard.animation == Lizard.Animation.Lounge) { this.camoColorAmountDrag = 0f; } else if (UnityEngine.Random.value < 0.1f) { this.camoColorAmountDrag = Mathf.Lerp(this.camoColorAmountDrag, Mathf.InverseLerp(0.65f, 0.4f, this.lizard.AI.runSpeed), UnityEngine.Random.value); } this.camoColorAmount = Mathf.Clamp(Mathf.Lerp(this.camoColorAmount, this.camoColorAmountDrag, 0.1f * UnityEngine.Random.value), 0.15f, 1f); this.camoColor = Color.Lerp(this.camoColor, this.pickUpColor, 0.1f); } } } else if (this.rainbowLizard.RainbowState.Blind) { if (this.lizard.bubble > 0) { this.blindLizardLightUpHead = Mathf.Min(this.blindLizardLightUpHead + 0.1f, 1f); } else { this.blindLizardLightUpHead *= 0.9f; } } if (this.lightSource != null) { this.lightSource.stayAlive = true; if (this.rainbowLizard.RainbowState.Blind) { this.lightSource.color = new Color(1f, 1f, 1f); this.lightSource.setAlpha = new float?(0.35f * this.blindLizardLightUpHead); } else { this.lightSource.setAlpha = new float?(0.6f * (1f - this.camoColorAmount)); this.lightSource.color = this.effectColor; } if (this.lightSource.slatedForDeletetion || this.lizard.room.Darkness(this.head.pos) == 0f) { this.lightSource = null; } } } public override void InitiateSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam) { base.InitiateSprites(sLeaser, rCam); if (this.debugVisualization) { return; } if (this.rainbowLizard.RainbowState.Blind) { sLeaser.sprites[15].isVisible = false; } } public new void CreatureSpotted(bool firstSpot, Tracker.CreatureRepresentation crit) { if (this.rainbowLizard.RainbowState.Blind) { this.blindLizardLightUpHead = Mathf.Min(this.blindLizardLightUpHead + 0.5f, 1f); } if (this.creatureLooker != null) { this.creatureLooker.ReevaluateLookObject(crit, (!firstSpot) ? 4f : 2f); } if (this.lizard.Template.CreatureRelationship(crit.representedCreature.realizedCreature.Template).type == CreatureTemplate.Relationship.Type.Eats || this.lizard.Template.CreatureRelationship(crit.representedCreature.realizedCreature.Template).intensity > 0.5f || (this.creatureLooker != null && this.creatureLooker.lookCreature == null)) { this.eyes[UnityEngine.Random.Range(0, 2), 0] = crit.representedCreature.realizedCreature.mainBodyChunk.pos; this.eyeBeamsActive = Mathf.Clamp(this.eyeBeamsActive + 0.1f, 0f, 1f); } } //private float lastDarkness, darkness; public override void ApplyPalette(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, RoomPalette palette) { base.ApplyPalette(sLeaser, rCam, palette); if (this.debugVisualization) { return; } //lastDarkness = darkness; //Color color = Color.Lerp(rCam.PixelColorAtCoordinate(this.owner.bodyChunks[0].pos), rCam.PixelColorAtCoordinate(this.owner.bodyChunks[1].pos), 0.5f); //darkness = color.r * 0.3f + color.g * 0.59f + color.b * 0.11f; //darkness = Mathf.Max(rCam.room.LightSourceExposure(this.owner.bodyChunks[1].pos) * 10f, darkness); //darkness = Mathf.Lerp(lastDarkness, darkness, 0.15f); if (this.rainbowLizard.RainbowState.Blind || this.rainbowLizard.RainbowState.Camoflague) { this.ColorBody(sLeaser, palette.blackColor); } else if (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedWaterLizard || this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard) { Color body; if (this.blackSalamander) { body = Color.Lerp(this.palette.blackColor, this.effectColor, 0.1f); } else { body = Color.Lerp(new Color(0.9f, 0.9f, 0.95f), this.effectColor, 0.06f); } this.ColorBody(sLeaser, body); sLeaser.sprites[11].color = body; sLeaser.sprites[14].color = body; if (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard || (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedWaterLizard && !this.blackSalamander)) { sLeaser.sprites[15].color = this.effectColor; } else { sLeaser.sprites[15].color = palette.blackColor; } } } public Color FormulatedHeadColor(float timeStacker) { if (this.whiteFlicker > 0 && (this.whiteFlicker > 15 || this.everySecondDraw)) { return new Color(1f, 1f, 1f); } float num = 1f - Mathf.Pow(0.5f + 0.5f * Mathf.Sin(Mathf.Lerp(this.lastBlink, this.blink, timeStacker) * 2f * 3.14159274f), 1.5f + this.lizard.AI.excitement * 1.5f); if (this.headColorSetter != 0f) { num = Mathf.Lerp(num, (this.headColorSetter <= 0f) ? 0f : 1f, Mathf.Abs(this.headColorSetter)); } if (this.flicker > 10) { num = this.flickerColor; } num = Mathf.Lerp(num, Mathf.Pow(Mathf.Lerp(this.lastVoiceVisualization, this.voiceVisualization, timeStacker), 0.75f), Mathf.Lerp(this.lastVoiceVisualizationIntensity, this.voiceVisualizationIntensity, timeStacker)); return Color.Lerp(this.FormulatedHeadColor1, this.FormulatedHeadColor2, num); } public Color FormulatedHeadColor1 { get { if ((this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedWaterLizard || this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard)) { if (this.blackSalamander) { return Color.Lerp(new Color(0.9f, 0.9f, 0.95f), this.effectColor, 0.06f); } else { return Color.Lerp(this.palette.blackColor, this.effectColor, 0.1f); } } else { if (this.rainbowLizard.RainbowState.Blind) { return Color.Lerp(this.palette.blackColor, this.effectColor, this.blindLizardLightUpHead); } else if (this.rainbowLizard.RainbowState.Camoflague) { return Color.Lerp(this.effectColor, this.camoColor, this.camoColorAmount); } return this.palette.blackColor; } } } public Color FormulatedHeadColor2 { get { if ((this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedWaterLizard || this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard)) { return this.FormulatedHeadColor1; } else { if (this.rainbowLizard.RainbowState.Blind) { return this.FormulatedHeadColor1; } else if (this.rainbowLizard.RainbowState.Camoflague) { return Color.Lerp(this.palette.blackColor, this.camoColor, this.camoColorAmount); } return this.effectColor; } } } public override void DrawSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, float timeStacker, Vector2 camPos) { base.DrawSprites(sLeaser, rCam, timeStacker, camPos); if (this.debugVisualization) { return; } if (this.rainbowLizard.RainbowState.Camoflague) { this.ColorBody(sLeaser, Color.Lerp(this.effectColor, this.camoColor, this.camoColorAmount)); Color color = rCam.PixelColorAtCoordinate(this.lizard.mainBodyChunk.pos); Color color2 = rCam.PixelColorAtCoordinate(this.lizard.bodyChunks[1].pos); Color color3 = rCam.PixelColorAtCoordinate(this.lizard.bodyChunks[2].pos); if (color == color2 && RXColor.HSLFromColor(color).s < 0.5f) { this.pickUpColor = color; } else if (color2 == color3 && RXColor.HSLFromColor(color2).s < 0.5f) { this.pickUpColor = color2; } else if (color3 == color && RXColor.HSLFromColor(color3).s < 0.5f) { this.pickUpColor = color3; } else { this.pickUpColor = (color + color2 + color3) / 3f; if (RXColor.HSLFromColor(pickUpColor).s > 0.5f) { RXColorHSL hsl = RXColor.HSLFromColor(pickUpColor); hsl.s /= 2f; this.pickUpColor = RXColor.ColorFromHSL(hsl); } } if (this.camoColorAmount == -1f) { this.camoColor = this.pickUpColor; this.camoColorAmount = 1f; } for (int m = 7; m < 11; m++) { sLeaser.sprites[m + 9].alpha = Mathf.Sin(this.camoColorAmount * 3.14159274f) * 0.3f; sLeaser.sprites[m + 9].color = this.palette.blackColor; } } if (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedWaterLizard) { for (int n = 7; n < 11; n++) { if (n % 2 == 1) { sLeaser.sprites[n + 9].alpha = Mathf.Lerp(0.3f, 0.1f, Mathf.Abs(Mathf.Lerp(this.lastDepthRotation, this.depthRotation, timeStacker))); } else { sLeaser.sprites[n + 9].alpha = 0.3f; } sLeaser.sprites[n + 9].color = ((!this.blackSalamander) ? this.palette.blackColor : this.effectColor); } } else if (this.lizard.lizardParams.template == EnumExt_Rainbow.FormulatedSkyLizard) { for (int m = 7; m < 11; m++) { sLeaser.sprites[m + 9].color = ((!this.blackSalamander) ? this.palette.blackColor : this.effectColor); } //sLeaser.sprites[15].color = this.effectColor; sLeaser.sprites[12].color = this.FormulatedHeadColor(timeStacker); sLeaser.sprites[13].color = this.FormulatedHeadColor(timeStacker); /* for (int n = 0; n < (sLeaser.sprites[20] as TriangleMesh).verticeColors.Length; n++) { (sLeaser.sprites[20] as TriangleMesh).verticeColors[n] = Color.Lerp(this.HeadColor(timeStacker), this.palette.blackColor, Mathf.InverseLerp(0f, (float)((sLeaser.sprites[20] as TriangleMesh).verticeColors.Length - 1), (float)n)); } */ } else { sLeaser.sprites[16].alpha = Mathf.Lerp(1f, 0.3f, Mathf.Abs(Mathf.Lerp(this.lastDepthRotation, this.depthRotation, timeStacker))); sLeaser.sprites[18].alpha = Mathf.Lerp(1f, 0.3f, Mathf.Abs(Mathf.Lerp(this.lastDepthRotation, this.depthRotation, timeStacker))); sLeaser.sprites[11].color = this.FormulatedHeadColor(timeStacker); sLeaser.sprites[14].color = this.FormulatedHeadColor(timeStacker); } this.ApplyPalette(sLeaser, rCam, palette); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Input; namespace Engine { public class StartScreenComp:BaseComponent { public override void Update() { if (GameState.KeyboardState.IsKeyDown(Keys.Space)) { TUAGameState.StartScreenScene.Root.GetComponent<MainThemeComp>().Instance.Stop(); TUAGameState.CurrentGame.CurrentScene = TUAGameState.BattleScene; TUAGameState.BattleScene.Root.GetComponent<MainThemeComp>().Instance.Play(); } base.Update(); } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `float`. Inherits from `AtomEventReferenceListener&lt;float, FloatEvent, FloatEventReference, FloatUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/Float Event Reference Listener")] public sealed class FloatEventReferenceListener : AtomEventReferenceListener< float, FloatEvent, FloatEventReference, FloatUnityEvent> { } }
using Microsoft.Extensions.Configuration; using System; using System.IO; namespace Langium.DataLayer { public class DbConnectionProvider { public static string GetConnectionString() { var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); var config = builder.Build(); return config.GetConnectionString("DefaultConnection"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Verse; namespace D9Framework { /// <summary> /// Class holding utility functions for the various included <c>PlaceWorkers</c>. /// </summary> class PlaceWorkerUtility { /// <summary> /// Checks whether the building is a wall, namely that it holds a roof, blocks light, and covers the floor. /// </summary> /// <param name="building">The building to check.</param> /// <returns>Whether the building is a wall by the above criteria.</returns> public static bool IsWall(Building building) { ThingDef def = building?.def; return def != null && (def.holdsRoof && def.blockLight && def.coversFloor); } /// <summary> /// Returns whether an identical <c>Thing</c> exists in the specified cell, namely that its <c>Def</c> matches and it's facing in the same direction. /// </summary> /// <param name="buildableDef">The <c>BuildableDef</c> a <c>PlaceWorker</c> is trying to place.</param> /// <param name="cell">The cell it's trying to be placed in.</param> /// <param name="rot">The rotation of the current thing which is attempting to be placed.</param> /// <param name="map">The map it's trying to be placed in.</param> /// <returns></returns> public static bool ConflictingThing(BuildableDef buildableDef, IntVec3 cell, Rot4 rot, Map map) { List<Thing> things = map.thingGrid.ThingsListAtFast(cell); foreach (Thing t in things) if (t.def as BuildableDef == buildableDef && t.Rotation == rot) return true; return false; } } }
using Alabo.Domains.Entities.Core; using System.Linq; namespace Alabo.Domains.Query { /// <summary> /// 分页查询 /// </summary> /// <typeparam name="T"></typeparam> public interface IPageQuery<T> : IOrderQuery<T> where T : class, IEntity { /// <summary> /// Gets or sets a value indicating whether [enable paging]. /// </summary> bool EnablePaging { get; set; } int PageSize { get; set; } int PageIndex { get; set; } int ExecuteCountQuery(IQueryable<T> query); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace CustomControl { public partial class HexTextBox : TextBox { public HexTextBox() { InitializeComponent(); } protected override void OnKeyPress(KeyPressEventArgs e) { string inputStr = e.KeyChar.ToString(); if (e.KeyChar != (char)ConsoleKey.Backspace) { if (CheckInput(inputStr) == false) { e.Handled = true; } } else { int nIndex = base.SelectionStart; if (nIndex > 0) { if (Text[nIndex - 1] == ' ') { string strTemp = Text.Remove(nIndex - 1); Text = strTemp; base.SelectionStart = nIndex - 1; } } } base.OnKeyPress(e); } private bool CheckInput(string inputString) { bool flag = false; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"[a-fA-F0-9.\s]+"); System.Text.RegularExpressions.Match m = r.Match(inputString); if (m.Success && m.Value == inputString) { flag = true; } return flag; } protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); int nIndex = base.SelectionStart; if (nIndex > 1) { if (MaxLength == nIndex) { return; } if (Text[nIndex - 1] != ' ' && Text[nIndex - 2] != ' ') { string strSub1 = Text.Substring(0, nIndex); string strSub2 = Text.Substring(nIndex); Text = strSub1 + " " + strSub2; base.SelectionStart = nIndex + 1; } } } } }
namespace Sales.ViewModels { using System.Collections.ObjectModel; using System.Windows.Input; using Common.Models; using GalaSoft.MvvmLight.Command; using Helpers; using Interfaces; using Views; using Xamarin.Forms; public class MainViewModel { #region Properties public CategoriesViewModel Categories { get; set; } public EditProductViewModel EditProduct { get; set; } public ProductsViewModel Products { get; set; } public AddProductViewModel AddProduct { get; set; } public LoginViewModel Login { get; set; } public RegisterViewModel Register { get; set; } public ObservableCollection<MenuItemViewModel> Menu { get; set; } public MyUserASP UserASP { get; set; } public string UserFullName { get { if (this.UserASP != null && this.UserASP.Claims != null && this.UserASP.Claims.Count > 1) { return $"{this.UserASP.Claims[0].ClaimValue} {this.UserASP.Claims[1].ClaimValue}"; } return null; } } public string UserImageFullPath { get { foreach (var claim in this.UserASP.Claims) { if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri") { if (claim.ClaimValue.StartsWith("~")) { return $"https://salesapiservices.azurewebsites.net{claim.ClaimValue.Substring(1)}"; } return claim.ClaimValue; } } return null; } } #endregion #region Constructors public MainViewModel() { instance = this; this.LoadMenu(); } #endregion #region Singleton private static MainViewModel instance; public static MainViewModel GetInstance() { if (instance == null) { return new MainViewModel(); } return instance; } #endregion #region Methods private void LoadMenu() { this.Menu = new ObservableCollection<MenuItemViewModel>(); this.Menu.Add(new MenuItemViewModel { Icon = "ic_info", PageName = "Mapa", Title = "Mapa de Productos", }); this.Menu.Add(new MenuItemViewModel { Icon = "ic_phonelink_setup", PageName = "SetupPage", Title = "Configuraciones", }); this.Menu.Add(new MenuItemViewModel { Icon = "ic_exit_to_app", PageName = "LoginPage", Title = "Cerrar Sesión", }); this.Menu.Add(new MenuItemViewModel { Icon = "ic_info", PageName = "ChatUs", Title = "Conversemos", }); this.Menu.Add(new MenuItemViewModel { Icon = "ic_phonelink_setup", PageName = "AboutPage", Title = "Acerca De", }); } public void RegisterDevice() { var register = DependencyService.Get<IRegisterDevice>(); register.RegisterDevice(); } #endregion #region Commands public ICommand AddProductCommand { get { return new RelayCommand(GoToAddProduct); } } private async void GoToAddProduct() { this.AddProduct = new AddProductViewModel(); await App.Navigator.PushAsync(new AddProductPage()); } #endregion } }
#if UNITY_EDITOR using Sirenix.OdinInspector; using UnityEngine; namespace DChildDebug { public class DebugMinionSceneController : MonoBehaviour { [SerializeField] [MinionName] private string m_minion; [Button("Spawn Minion")] private void SpawnMinion() => DebugMinionSpawner.SpawnMinion(m_minion); private void Start() { SpawnMinion(); } private void Update() { if (Input.GetKeyDown(KeyCode.LeftArrow)) { DebugMinionSpawner.PreviousMinion(); } else if (Input.GetKeyDown(KeyCode.RightArrow)) { DebugMinionSpawner.NextMinion(); } else if (Input.GetKeyDown(KeyCode.UpArrow)) { SpawnMinion(); } } } } #endif
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //this is essentially supposed to be the NPC script from the other video. I think normally you would attatch this to whatever NPC character you wanted. //to make a new NPC thing with a new dialogue you would have to create an empty object. Reset its transform. Name the empty object the name of the NPC. //attatch the dialogue trigger to this new game object. Change the name in the dialogue parameter to the name of the NPC. And then give her some sentences to say public class DialogueKnightTrigger : MonoBehaviour { //functoin that makes the start conversation button appear private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Player")) //if the Player enters our collider { FindObjectOfType<DialogueManager>().KnightButtonOnOrOff(1); //turn the conversatoin button on } } //function that makes the start conversation button dissapear private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Player")) //if the Player leaves our collider { FindObjectOfType<DialogueManager>().KnightButtonOnOrOff(0); //make the start conversation button go aawy } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.Tilemaps; using UnityEngine; using UnityEngine.UI; public class Player : MonoBehaviour { public Tilemap floorTilemap; public Tilemap wallTilemap; public Tilemap slipperyTilemap; public bool canMove = true; public bool isMoving = false; public bool isSliding = false; public bool onCooldown = false; public float moveTime = 0.2f; [SerializeField] GameObject renderParent; [SerializeField] Animator shoulderAnimator; [SerializeField] SpriteRenderer HairSprite; [SerializeField] SpriteRenderer HeadSprite; [SerializeField] SpriteRenderer ShirtSprite; private Vector3 startingPosition; Coroutine moveRoutine; private void Awake() { startingPosition = transform.position; } private void Start() { LevelManager.Instance.HairSprite = HairSprite; LevelManager.Instance.HeadSprite = HeadSprite; LevelManager.Instance.ShirtSprite = ShirtSprite; LevelManager.Instance.UpdatePlayerColors(); } private void Update() { //We do nothing if the player is still moving or isnt allowed to move. if (isMoving || onCooldown || !canMove) return; //|| onExit) return; //To store move directions. int horizontal = 0; int vertical = 0; //To get move directions horizontal = (int)(Input.GetAxisRaw("Horizontal")); vertical = (int)(Input.GetAxisRaw("Vertical")); //We can't go in both directions at the same time if (horizontal != 0) vertical = 0; //If there's a direction, we are trying to move. if (horizontal != 0 || vertical != 0) { StartCoroutine(actionCooldown(0.1f)); ChangeRotation(horizontal, vertical); Move(horizontal, vertical); } } public void TeleportToStart() { transform.position = startingPosition; if (moveRoutine != null) StopCoroutine(moveRoutine); isMoving = false; isSliding = false; UpdateAnimations(); } void UpdateAnimations() { if (shoulderAnimator != null) { shoulderAnimator.SetBool("IsMoving", isMoving); shoulderAnimator.SetBool("IsSliding", isSliding); } } private void ChangeRotation(int xDir, int yDir) { if (xDir < 0) renderParent.transform.localRotation = Quaternion.Euler(Vector3.forward * 90); else if (xDir > 0) renderParent.transform.localRotation = Quaternion.Euler(Vector3.forward * 270); else if (yDir < 0) renderParent.transform.localRotation = Quaternion.Euler(Vector3.forward * 180); else if (yDir > 0) renderParent.transform.localRotation = Quaternion.Euler(Vector3.zero); } private void Move(int xDir, int yDir) { Vector2 startCell = transform.position; Vector2 targetCell = startCell + new Vector2(xDir, yDir); bool isOnGround = getCell(floorTilemap, startCell) != null; //If the player is on the ground bool hasGroundTile = getCell(floorTilemap, targetCell) != null; //If target Tile has a ground bool hasObstacleTile = getCell(wallTilemap, targetCell) != null; //if target Tile has an obstacle bool hasSlipperyTile = getCell(slipperyTilemap, targetCell) != null; //if target Tile is slippery //If the front tile is a walkable ground tile, the player moves here. if (!hasObstacleTile) { if (objectCheck(targetCell)) StartSmoothMovementRoutine(targetCell, hasSlipperyTile); else StartBlockedMovementRoutine(targetCell); } //else //StartBlockedMovementRoutine(targetCell); //if (!isMoving) //tartBlockedMovementRoutine(targetCell); } void StartSmoothMovementRoutine(Vector3 end, bool isSlippery = false) { if (moveRoutine != null) StopCoroutine(moveRoutine); moveRoutine = StartCoroutine(SmoothMovement(end, isSlippery)); } void StartBlockedMovementRoutine(Vector3 end) { if (moveRoutine != null) StopCoroutine(moveRoutine); moveRoutine = StartCoroutine(BlockedMovement(end)); } private IEnumerator actionCooldown(float cooldown) { onCooldown = true; //float cooldown = 0.2f; while (cooldown > 0f) { cooldown -= Time.deltaTime; yield return null; } onCooldown = false; } private IEnumerator SmoothMovement(Vector3 end, bool isSlippery = false) { //while (isMoving) yield return null; Vector3 _start = transform.position; isMoving = true; isSliding = isSlippery; UpdateAnimations(); //Play movement sound //if (walkingSound != null) //{ // walkingSound.loop = true; // walkingSound.Play(); //} float sqrRemainingDistance = (transform.position - end).sqrMagnitude; float inverseMoveTime = 1 / moveTime; while (sqrRemainingDistance > float.Epsilon) { Vector3 newPosition = Vector3.MoveTowards(transform.position, end, inverseMoveTime * Time.deltaTime); transform.position = newPosition; sqrRemainingDistance = (transform.position - end).sqrMagnitude; yield return null; } //if (walkingSound != null) // walkingSound.loop = false; isMoving = false; isSliding = false; UpdateAnimations(); if (isSlippery) { Vector3 _newPos = end - _start; Move((int)_newPos.x, (int)_newPos.y); } } //Blocked animation private IEnumerator BlockedMovement(Vector3 end) { //while (isMoving) yield return null; isMoving = true; UpdateAnimations(); //if (AudioManager.getInstance() != null) // AudioManager.getInstance().Find("blocked").source.Play(); Vector3 originalPos = transform.position; end = transform.position + ((end - transform.position) / 3); float sqrRemainingDistance = (transform.position - end).sqrMagnitude; float inverseMoveTime = (1 / (moveTime * 2)); while (sqrRemainingDistance > float.Epsilon) { Vector3 newPosition = Vector3.MoveTowards(transform.position, end, inverseMoveTime * Time.deltaTime); transform.position = newPosition; sqrRemainingDistance = (transform.position - end).sqrMagnitude; yield return null; } sqrRemainingDistance = (transform.position - originalPos).sqrMagnitude; while (sqrRemainingDistance > float.Epsilon) { Vector3 newPosition = Vector3.MoveTowards(transform.position, originalPos, inverseMoveTime * Time.deltaTime); transform.position = newPosition; sqrRemainingDistance = (transform.position - originalPos).sqrMagnitude; yield return null; } //The lever disable the sound so its doesn't overlap with this one, so it blocked has been muted, we restore it. //if (AudioManager.getInstance() != null && AudioManager.getInstance().Find("blocked").source.mute) //{ // AudioManager.getInstance().Find("blocked").source.Stop(); // AudioManager.getInstance().Find("blocked").source.mute = false; //} isMoving = false; UpdateAnimations(); } private bool objectCheck(Vector2 targetCell) { Collider2D coll = whatsThere(targetCell); //No obstacle, we can walk there if (coll == null) return true; //if there's a levered door in front of the character. if (coll.tag == "LeveredDoor") { Debug.Log("LeveredDoor detected!"); LeveredDoor door = coll.gameObject.GetComponent<LeveredDoor>(); //If the door is open if (door.isOpen) return true; //If the door is close. else return false; } else if (coll.tag == "Lever") { //Click sound ! //if (AudioManager.getInstance() != null) //{ // AudioManager.getInstance().Find("leverClick").source.Play(); // AudioManager.getInstance().Find("blocked").source.mute = true; //} Lever lever = coll.gameObject.GetComponent<Lever>(); lever.operate(); //We operate the lever, but can't move there, so we return false; return false; } else if (coll.tag == "WallButton") { Vector2 _dir = targetCell - new Vector2(transform.position.x, transform.position.y); coll.GetComponent<WallButton>().InteractWithButton(_dir); return false; } else if (coll.tag == "Exit") { LevelManager.Instance.OnExit(); return false; } else return true; } private TileBase getCell(Tilemap tilemap, Vector2 cellWorldPos) { return tilemap.GetTile(tilemap.WorldToCell(cellWorldPos)); } public Collider2D whatsThere(Vector2 targetPos) { RaycastHit2D hit; hit = Physics2D.Linecast(targetPos, targetPos); return hit.collider; } }
using UnityEngine; using System.Collections; public class Chronos : MonoBehaviour { Dreamer dreamer; void Start() { dreamer = GameObject.FindGameObjectWithTag("Dreamer").GetComponent<Dreamer>(); } void Update() { if (Input.GetKeyDown(KeyCode.Alpha1)) dreamer.dimension = Structures.States.D1; if (Input.GetKeyDown(KeyCode.Alpha2)) { Time.timeScale = GameParams.minD2; dreamer.dimension = Structures.States.D2; } if (Input.GetKeyDown(KeyCode.Alpha3)) { Time.timeScale = GameParams.minD3; dreamer.dimension = Structures.States.D3; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Cirrious.FluentLayouts.Touch; using CoreGraphics; using Foundation; using MvvmCross.Binding.BindingContext; using MvvmCross.Binding.iOS.Views; using MvvmCross.Platform.Core; using MvvmCross.Platform.iOS; using MvvmCross.Plugins.PictureChooser.iOS; using ObjCRuntime; using ResidentAppCross.Extensions; using ResidentAppCross.iOS.Views; using ResidentAppCross.iOS.Views.Attributes; using ResidentAppCross.iOS.Views.TableSources; using ResidentAppCross.Resources; using ResidentAppCross.Services; using ResidentAppCross.ViewModels; using SCLAlertViewLib; using SharpMobileCode.ModalPicker; using UIKit; using ZXing; using ZXing.Mobile; namespace ResidentAppCross.iOS.Services { public class IOSDialogService : IDialogService { private IMvxMainThreadDispatcher _dispatcher; private UIImagePickerController _imagePickerController; private int _maxPixelDimension; private float _percentQuality; public UIWindow KeyWindow => UIApplication.SharedApplication.KeyWindow; public UINavigationController RootController => KeyWindow.RootViewController as UINavigationController; public UIViewController CurrentController => KeyWindow.RootViewController.PresentedViewController; public UIViewController TopController => RootController.TopViewController; public IMvxMainThreadDispatcher Dispatcher => _dispatcher ?? (_dispatcher = MvxSingleton<IMvxMainThreadDispatcher>.Instance); public Task<T> OpenSearchableTableSelectionDialog<T>(IList<T> items, string title, Func<T,string> itemTitleSelector, Func<T, string> itemSubtitleSelector = null, object arg = null) { return Task.Factory.StartNew(() => { T result = default(T); UITableViewController selectionTable = null; ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); Dispatcher.RequestMainThreadAction(() => { ResignFirstReponder(); //Proxy collection to store search resultes var filteredResults = new ObservableCollection<T>(); filteredResults.AddRange(items); //Main controller for the tabl selectionTable = new UITableViewController(UITableViewStyle.Grouped) { ModalPresentationStyle = UIModalPresentationStyle.Popover, TableView = { //LayoutMargins = new UIEdgeInsets(25, 25, 0, 50), SeparatorColor = UIColor.Gray, SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine }, EdgesForExtendedLayout = UIRectEdge.None, Title = title }; var tableView = selectionTable.TableView; var tableDataBinding = new TableDataBinding<UITableViewCell, T>() //Define cell type and data type as type args { Bind = (cell, item, index) => //What to do when cell is created for item { cell.TextLabel.Text = itemTitleSelector(item); cell.DetailTextLabel.Text = itemSubtitleSelector?.Invoke(item) ?? null; }, ItemSelected = item => { RootController.PopViewController(true); waitForCompleteEvent.Set(); result = item; }, AccessoryType = item => UITableViewCellAccessory.DisclosureIndicator, CellSelector = () => new UITableViewCell(UITableViewCellStyle.Subtitle, "UITableViewCell"), //Define how to create cell, if reusables not found }; var source = new GenericTableSource() { Items = filteredResults, //Deliver data Binding = tableDataBinding, //Deliver binding ItemsEditableByDefault = true, //Set all items editable ItemsFocusableByDefault = true }; tableView.AllowsSelection = true; tableView.Source = source; var searchBar = new UISearchBar() { AutocorrectionType = UITextAutocorrectionType.Yes, KeyboardType = UIKeyboardType.WebSearch }; tableView.TableHeaderView = searchBar; searchBar.SizeToFit(); searchBar.Placeholder = "Search..."; searchBar.OnEditingStopped += (sender, args) => { searchBar.ResignFirstResponder(); }; searchBar.TextChanged += (sender, args) => { filteredResults.Clear(); if (string.IsNullOrEmpty(searchBar.Text)) { filteredResults.AddRange(items); } else { var lower = searchBar.Text.ToLower(); filteredResults.AddRange(items.Where(i => itemTitleSelector(i).ToLower().Contains(lower))); } tableView.ReloadData(); }; var view = arg as UIView; if (view != null && selectionTable.PopoverPresentationController != null) { selectionTable.PopoverPresentationController.SourceView = view; selectionTable.PopoverPresentationController.SourceRect = view.Bounds; } tableView.BackgroundColor = UIColor.Blue; selectionTable.EdgesForExtendedLayout = UIRectEdge.None; NavbarStyling.ApplyToNavigationController(RootController); StatusBarStyling.Apply(selectionTable); tableView.BackgroundColor = AppTheme.SecondaryBackgoundColor; RootController.PushViewController(selectionTable, true); }); waitForCompleteEvent.WaitOne(); selectionTable.Dispose(); return result; }); } private void ResignFirstReponder() { TopController?.View?.EndEditing(true); } public Task<DateTime?> OpenDateTimeDialog(string title) { return Task.Factory.StartNew(() => { ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); ModalPickerViewController modalPicker = null; DateTime? result = null; try { Dispatcher.RequestMainThreadAction(() => { ResignFirstReponder(); modalPicker = new ModalPickerViewController(ModalPickerType.Date, "Select A Date", TopController) { HeaderBackgroundColor = AppTheme.SecondaryBackgoundColor, HeaderTextColor = UIColor.White, TransitioningDelegate = new ModalPickerTransitionDelegate(), ModalPresentationStyle = UIModalPresentationStyle.Custom }; modalPicker.DatePicker.Mode = UIDatePickerMode.DateAndTime; modalPicker.OnSelectionConfirmed += (s, ea) => { RootController.InvokeOnMainThread(() => { result = modalPicker.DatePicker.Date?.ToDateTimeUtc(); waitForCompleteEvent.Set(); }); }; modalPicker.OnSelectionCancelled += (s, ea) => { Dispatcher.RequestMainThreadAction(() => { waitForCompleteEvent.Set(); }); }; TopController.PresentModalViewController(modalPicker, true); }); waitForCompleteEvent.WaitOne(); modalPicker.Dispose(); return result; } catch (Exception ex) { return result; } }); } public Task<DateTime?> OpenDateDialog(string title) { return Task.Factory.StartNew(() => { ManualResetEvent waitForCompleteEvent = new ManualResetEvent(false); ModalPickerViewController modalPicker = null; DateTime? result = null; try { Dispatcher.RequestMainThreadAction(() => { ResignFirstReponder(); modalPicker = new ModalPickerViewController(ModalPickerType.Date, "Select A Date", TopController) { HeaderBackgroundColor = AppTheme.SecondaryBackgoundColor, HeaderTextColor = UIColor.White, TransitioningDelegate = new ModalPickerTransitionDelegate(), ModalPresentationStyle = UIModalPresentationStyle.Custom }; modalPicker.DatePicker.Mode = UIDatePickerMode.Date; modalPicker.OnSelectionConfirmed += (s, ea) => { RootController.InvokeOnMainThread(() => { result = modalPicker.DatePicker.Date?.ToDateTimeUtc(); waitForCompleteEvent.Set(); }); }; modalPicker.OnSelectionCancelled += (s, ea) => { Dispatcher.RequestMainThreadAction(() => { waitForCompleteEvent.Set(); }); }; TopController.PresentModalViewController(modalPicker, true); }); waitForCompleteEvent.WaitOne(); modalPicker.Dispose(); return result; } catch (Exception ex) { return result; } }); } public Task<byte[]> OpenImageDialog() { return Task.Factory.StartNew(() => { PhotoPickEvent = new ManualResetEvent(false); PhotoData = null; Dispatcher.RequestMainThreadAction(() => { ResignFirstReponder(); var shouldCancel = true; var newController = new SCLAlertView(); if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) newController.AddButton("Take Photo", ()=> UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera), () => { StartImagePickingDialog(UIImagePickerControllerSourceType.Camera); shouldCancel = false; }); if(UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) newController.AddButton("Photo Library", () => { StartImagePickingDialog(UIImagePickerControllerSourceType.PhotoLibrary); shouldCancel = false; }); if(UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) newController.AddButton("Saved Photos", () => { StartImagePickingDialog(UIImagePickerControllerSourceType.SavedPhotosAlbum); shouldCancel = false; }); newController.ShouldDismissOnTapOutside = true; newController.ShowAnimationType = SCLAlertViewShowAnimation.FadeIn; newController.HideAnimationType = SCLAlertViewHideAnimation.FadeOut; newController.CustomViewColor = AppTheme.SecondaryBackgoundColor; newController.AlertIsDismissed(() => { //newController.DismissViewController(true, () => { }); NSTimer.CreateScheduledTimer(TimeSpan.FromMilliseconds(50), x => { if (shouldCancel) PhotoPickEvent.Set(); }); }); newController.ShowEdit(TopController,"Select Photo","What photo source would you like to use?","Cancel",0); //TopController.PresentViewController(newController, true, () => { }); }); PhotoPickEvent.WaitOne(); return PhotoData; }); } public void OpenNotification(string title, string subtitle, string ok,Action action = null) { TopController.InvokeOnMainThread(() => { var alert = new SCLAlertView(); alert.ShowAnimationType = SCLAlertViewShowAnimation.FadeIn; alert.HideAnimationType = SCLAlertViewHideAnimation.FadeOut; //alert.CustomViewColor = AppTheme.SecondaryBackgoundColor; alert.ShowInfo(TopController,title, subtitle, ok,0); alert.AlertIsDismissed(() => { action?.Invoke(); }); }); } public void OpenImageFullScreen(object imageObject) { throw new NotImplementedException(); } public void OpenImageFullScreenFromUrl(string url) { TopController.InvokeOnMainThread(() => { var controller = new UIViewController(); controller.EdgesForExtendedLayout = UIRectEdge.None; NavbarStyling.ApplyToNavigationController(RootController); StatusBarStyling.Apply(controller); var imageView = new UIImageView(); controller.View.Add(imageView); controller.View.BackgroundColor = imageView.BackgroundColor = UIColor.Black; controller.View.AddConstraints( imageView.AtRightOf(controller.View), imageView.AtLeftOf(controller.View), imageView.AtTopOf(controller.View), imageView.AtBottomOf(controller.View)); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; imageView.SetImageWithAsyncIndicator(url,UIImage.FromFile("avatar-placeholder.png")); imageView.TranslatesAutoresizingMaskIntoConstraints = false; RootController.PushViewController(controller,true); }); } public void OpenUrl(string url) { UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(url)); } public UIImagePickerController ImagePickerController { get { if (_imagePickerController == null) { _imagePickerController = new UIImagePickerController(); NavbarStyling.ApplyToNavigationController(_imagePickerController); _imagePickerController.FinishedPickingImage += (o, args) => { OnImagePick(o, args); PhotoPickEvent?.Set(); _imagePickerController.DismissViewController(true, () => { }); }; _imagePickerController.FinishedPickingMedia += (o, args) => { OnMediaPick(o, args); PhotoPickEvent?.Set(); _imagePickerController.DismissViewController(true, () => { }); }; _imagePickerController.Canceled += (sender, args) => { PhotoPickEvent?.Set(); _imagePickerController.DismissViewController(true, () => { }); }; } return _imagePickerController; } } private void StartImagePickingDialog(UIImagePickerControllerSourceType sourceType) { ImagePickerController.SourceType = sourceType; TopController.PresentViewController(ImagePickerController, true, () => { }); } private void HandleUIImagePick(UIImage image) { if (image != null) { int num; if (_maxPixelDimension > 0) { CGSize size = image.Size; if (!(size.Height > _maxPixelDimension)) { size = image.Size; num = size.Width > _maxPixelDimension ? 1 : 0; } else num = 1; } else num = 0; if (num != 0) image = image.ImageToFitSize(new CGSize(_maxPixelDimension, this._maxPixelDimension)); using (NSData nsData = image.AsJPEG(_percentQuality / 100f)) { byte[] numArray = new byte[(ulong)nsData.Length]; Marshal.Copy(nsData.Bytes, numArray, 0, Convert.ToInt32((ulong)nsData.Length)); MemoryStream memoryStream1 = new MemoryStream(numArray, false); PhotoData = memoryStream1.ToArray(); } } } private ManualResetEvent PhotoPickEvent; private byte[] PhotoData; private void OnMediaPick(object sender, UIImagePickerMediaPickedEventArgs e) { HandleUIImagePick(e.OriginalImage ?? e.EditedImage); } private void OnImagePick(object sender, UIImagePickerImagePickedEventArgs e) { HandleUIImagePick(e.Image); } } }
namespace Assets.Scripts.Models.Seedlings { public class Seedling : Food.Food { public Seedling() { CanBuy = true; ShowDurability = false; Durability = 1000; GardenTimeStage1 = 1000; GardenTimeStage2 = 800; GardenTimeStage3 = 400; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class killEnemy : MonoBehaviour { public GameObject Enemy; void OnTriggerEnter2D(Collider2D cc) { if (cc.tag == "Player") { Destroy(Enemy); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using AutoMapper; using ShopAPI.Models; using ShopBLL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ShopAPI.App_Start { public class WebApiAutomapperProfile: Profile { public WebApiAutomapperProfile() { CreateMap<TovarApiModel, TovarModel>() .ForMember(x => x.CategoryModels, y => y.MapFrom(x => x.CategoryApiModels)) .ForMember(x => x.CategoryModelId, y => y.MapFrom(x => x.CategoryApiModelId)) .ReverseMap(); CreateMap<CategoryApiModel, CategoryModel>().ReverseMap(); } } }
namespace gView.Framework.UI { /// <summary> /// Privides access to members that define a contextmenu item for the TOC. /// </summary> /// <remarks> /// A class that implements <c>IDatasetElementContexMenuItem</c> can be included to the TOC contextmenu. Everytime you right click a layer in the TOC the item will be selectable. /// </remarks> public interface IDatasetElementContextMenuItem : IContextMenuTool { } }
 using NUnit.Framework; using FluentAssertions; using System; using System.Collections.Generic; [TestFixture] public class DatabaseTests { [SetUp] public void SetUp() { } [Test] public void DoesConstructorSetIntegersCorrectlyWhenInitiatedWithLessThan16() { var numbers = new List<int>(); for (int i = 1; i <= 5; i++) { numbers.Add(i); } var db = new Database(numbers); db.Fetch().Length.Should().Be(5); } [Test] public void DoesConstructorThrowExceptionWhenInitiatedWithMoreThan16() { var numbers = new List<int>(); for (int i = 1; i <= 17; i++) { numbers.Add(i); } Assert.Throws<InvalidOperationException>(() => new Database(numbers)); } [Test] public void DoesAddMethodAddNumbersCorrectly() { var numbers = new List<int>(); for (int i = 1; i <= 5; i++) { numbers.Add(i); } var db = new Database(numbers); db.Add(5); db.Fetch().Length.Should().Be(6); } [Test] public void DoesAddMethodThrowExceptionWhenExceedingLimit() { var numbers = new List<int>(); for (int i = 1; i <= 16; i++) { numbers.Add(i); } var db = new Database(numbers); Assert.Throws<InvalidOperationException>(() => db.Add(5)); } [Test] public void DoesRemoveWorkCorrectlyWhenUsedOnANonEmptyDb() { var numbers = new List<int>(); for (int i = 1; i <= 16; i++) { numbers.Add(i); } var db = new Database(numbers); db.Remove(5); db.Fetch().Length.Should().Be(15); } [Test] public void DoesRemoveThrowExceptionCorrectlyWhenUsedOnEmptyList() { var numbers = new List<int>(); numbers.Add(1); var db = new Database(numbers); db.Remove(1); Assert.Throws<InvalidOperationException>(() => db.Remove(1)); } [Test] public void DoesFetchReturnArrayCorrectly() { var numbers = new List<int>(); for (int i = 1; i <= 16; i++) { numbers.Add(i); } var db = new Database(numbers); db.Fetch().Should().BeEquivalentTo(numbers.ToArray()); } }
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Models.Configuration { public class LearningRecordServiceSettings { public int VendorId { get; set; } public string Ukprn { get; set; } public string Username { get; set; } public string Password { get; set; } public string CertificateName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading.Tasks; namespace Bai1 { class Program { static void Main(string[] args) { string hostName = Dns.GetHostName(); Console.WriteLine(hostName); // Lấy IP string IP = Dns.GetHostByName(hostName).AddressList[0].ToString(); Console.WriteLine("IP Address :" + IP); Console.ReadKey(); } } }
using System; using System.Linq; using NUnit.Framework; using AdventureWorksDB = AdventureWorks.Business.Entities.AdventureWorksDB; using Harbin.Common.Queries; using System.Collections.Generic; namespace AdventureWorks.Business.Tests { [TestFixture] public class GenericQueryExtensionsTests { [Test] public void Test1() { var db = new AdventureWorksDB(); var contacts = db.BusinessEntityContacts; var filtered = contacts.WherePropertyIn(p => p.ContactTypeId, new List<int?>() { 1, 2 }); var sql = filtered.ToString(); var result = filtered.ToList(); var result2 = new AdventureWorksDB().Query<Entities.BusinessEntityContact>(@" SELECT * FROM [Person].[BusinessEntityContact] WHERE [ContactTypeID] IN (1,2)").ToList(); Assert.That(sql.Contains("[ContactTypeID] IN (1, 2)")); Assert.That(result.Count > 0); Assert.AreEqual(result.Count, result2.Count); System.Diagnostics.Debug.WriteLine(sql); } [Test] public void Test2() { var db = new AdventureWorksDB(); var contacts = db.BusinessEntityContacts; var filtered = contacts.WherePropertyNotIn(p => p.ContactTypeId, new List<int?>() { 1, 2 }); var sql = filtered.ToString(); var result = filtered.ToList(); var result2 = new AdventureWorksDB().Query<Entities.BusinessEntityContact>(@" SELECT * FROM [Person].[BusinessEntityContact] WHERE [ContactTypeID] NOT IN (1,2)").ToList(); Assert.That(sql.Contains("NOT ([Extent1].[ContactTypeID] IN (1, 2))")); Assert.That(result.Count > 0); Assert.AreEqual(result.Count, result2.Count); System.Diagnostics.Debug.WriteLine(sql); } } }
using Microsoft.SqlServer.Management.Smo; using SqlServerWebAdmin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SqlServerWebAdmin { public partial class EditColumn : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; if (!IsPostBack) { DataLossWarningLabel.Visible = false; DataTypeDropdownlist.DataSource = Enum.GetValues(typeof(SqlDataType)); DataTypeDropdownlist.DataBind(); // If column isn't specified in request, that means we're adding a new column, not editing an existing one if (Request["column"] == null || Request["column"].Length == 0) { // Set update button text to "Add" instead of "Update" UpdateButton.Text = "Add"; // Create new unique column name string columnName = ""; Microsoft.SqlServer.Management.Smo.Table table = database.Tables[Request["table"]]; if (table == null) { // If table doesn't exist (e.g. new table), set default column name columnName = "Column1"; } else { // Come up with non-existent name ColumnXX int i = 1; do { columnName = "Column" + i; i++; } while (table.Columns[columnName] != null); } // Initialize column editor with default values PrimaryKeyCheckbox.Checked = false; ColumnNameTextbox.Text = columnName; DataTypeDropdownlist.SelectedIndex = DataTypeDropdownlist.Items.IndexOf(new ListItem("char")); LengthTextbox.Text = "10"; AllowNullCheckbox.Checked = true; DefaultValueTextbox.Text = ""; PrecisionTextbox.Text = "0"; ScaleTextbox.Text = "0"; IdentityCheckBox.Checked = false; IdentitySeedTextbox.Text = "1"; IdentityIncrementTextbox.Text = "1"; IsRowGuidCheckBox.Checked = false; } else { // Set update button text to "Update" instead of "Add" UpdateButton.Text = "Update"; // Load column from table Microsoft.SqlServer.Management.Smo.Table table = database.Tables[Request["table"]]; if (table == null) { server.Disconnect(); // Table doesn't exist - break out and go to error page Response.Redirect(String.Format("error.aspx?error={0}", 1002)); return; } // Select column from table Column column = table.Columns[Request["column"]]; if (column == null) { server.Disconnect(); // Column doesn't exist - break out and go to error page Response.Redirect(String.Format("error.aspx?error={0}", 1003)); return; } var columnInfo = column; // Initialize column editor PrimaryKeyCheckbox.Checked = column.InPrimaryKey; ColumnNameTextbox.Text = column.Name; OriginalName.Value = column.Name; DataTypeDropdownlist.SelectedIndex = DataTypeDropdownlist.Items.IndexOf(new ListItem(columnInfo.DataType.SqlDataType.ToString())); LengthTextbox.Text = Convert.ToString(columnInfo.DataType.MaximumLength); AllowNullCheckbox.Checked = columnInfo.Nullable; DefaultValueTextbox.Text = columnInfo.Default; PrecisionTextbox.Text = Convert.ToString(columnInfo.DataType.NumericPrecision); ScaleTextbox.Text = Convert.ToString(columnInfo.DataType.NumericScale); IdentityCheckBox.Checked = columnInfo.Identity; IdentitySeedTextbox.Text = Convert.ToString(columnInfo.IdentitySeed); IdentityIncrementTextbox.Text = Convert.ToString(columnInfo.IdentityIncrement); //IsRowGuidCheckBox.Checked = columnInfo.i; // Since we are editing an existing column, the table will be recreated, // so we must warn about data loss DataLossWarningLabel.Visible = true; } } server.Disconnect(); } protected void UpdateButton_Click(object sender, System.EventArgs e) { if (!IsValid) return; Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; Microsoft.SqlServer.Management.Smo.Table table = null; if (!database.Tables.Contains(Request["table"])) { table = new Microsoft.SqlServer.Management.Smo.Table(database, Request["table"]); } else { table = database.Tables.Cast<Microsoft.SqlServer.Management.Smo.Table>().FirstOrDefault( i => i.Name == Request["table"]); } // Parse user input and stick it into ColumnInfo var type = DataTypeDropdownlist.SelectedItem.Value; SqlDataType sqlDataType = (SqlDataType)Enum.Parse(typeof(SqlDataType), type); Column columnInfo = table.Columns.Cast<Column>().FirstOrDefault(i => i.Name == OriginalName.Value); if (columnInfo == null) { columnInfo = new Column(table, ColumnNameTextbox.Text, new DataType(sqlDataType)); columnInfo.Name = ColumnNameTextbox.Text; columnInfo.Default = DefaultValueTextbox.Text; } else { columnInfo.Rename(ColumnNameTextbox.Text); columnInfo.DataType = new DataType(sqlDataType); } columnInfo.Identity = PrimaryKeyCheckbox.Checked; try { columnInfo.DataType.MaximumLength = Convert.ToInt32(LengthTextbox.Text); } catch { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "Invalid input: Size must be an integer"; return; } columnInfo.Nullable = AllowNullCheckbox.Checked; try { columnInfo.DataType.NumericPrecision = Convert.ToInt32(PrecisionTextbox.Text); } catch { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "Invalid input: Precision must be an integer"; return; } try { columnInfo.DataType.NumericScale = Convert.ToInt32(ScaleTextbox.Text); } catch { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "Invalid input: Scale must be an integer"; return; } columnInfo.Identity = IdentityCheckBox.Checked; try { columnInfo.IdentitySeed = Convert.ToInt32(IdentitySeedTextbox.Text); } catch { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "Invalid input: Identity seed must be an integer"; return; } try { columnInfo.IdentityIncrement = Convert.ToInt32(IdentityIncrementTextbox.Text); } catch { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "Invalid input: Identity increment must be an integer"; return; } //columnInfo.IsRowGuid = IsRowGuidCheckBox.Checked; // First check if the table exists or not // If it doesn't exist, that means we are adding the first column of a new table // If it does exist, then either we are adding a new column to an existing table // or we are editing an existing column in an existing table if (!database.Tables.Contains(Request["table"])) { // Table does not exist - create a new table and add the new column try { /*Index primaryKey = new Index(table, "PK_ID"); IndexedColumn indexedColumn = new IndexedColumn(primaryKey, "ID"); primaryKey.IndexedColumns.Add(indexedColumn); primaryKey.IndexKeyType = IndexKeyType.DriPrimaryKey; //create the primary index on ID column primaryKey.Create(); */ table.Columns.Add(columnInfo); table.Create(); } catch (Exception ex) { // If the table was somehow created, get rid of it table = database.Tables[Request["table"]]; if (table != null) table.Drop(); // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "The following error occured while trying to apply the changes.<br>" + Server.HtmlEncode(Utility.MessageFormat(ex)); server.Disconnect(); return; } } else { // Table does exist, do further check // If original name is blank that means it is a new column string originalColumnName = Request["column"]; if (originalColumnName == null || originalColumnName.Length == 0) { try { table.Columns.Add(columnInfo); table.Alter(); } catch (Exception ex) { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "The following error occured while trying to apply the changes:<br>" + Server.HtmlEncode(Utility.MessageFormat(ex)); server.Disconnect(); return; } } else { // If we get here that means we are editing an existing column // Simply set the column info - internally the table gets recreated try { //not require recreation //nameCol.DataType = DataType.VarChar(150); //nameCol.Alter(); //nameCol.Rename(nameCol.Name + " modified"); var newColumnInfo = NewColumn(table, columnInfo); columnInfo.Drop(); table.Columns.Add(newColumnInfo); table.Alter(); //columnInfo.Alter(); } catch (Exception ex) { // Show error and quit ErrorUpdatingColumnLabel.Visible = true; ErrorUpdatingColumnLabel.Text = "The following error occured while trying to apply the changes.<br>" + Server.HtmlEncode(Utility.MessageFormat(ex)); server.Disconnect(); return; } } } server.Disconnect(); // If we get here then that means a column was successfully added/edited Response.Redirect(String.Format("~/Modules/Column/columns.aspx?database={0}&table={1}", Server.UrlEncode(Request["database"]), Server.UrlEncode(Request["table"]))); } private Column NewColumn(Microsoft.SqlServer.Management.Smo.Table table, Column originalColumn) { Column newcolumnInfo = new Column(table, originalColumn.Name); newcolumnInfo.Default = DefaultValueTextbox.Text; newcolumnInfo.DataType = originalColumn.DataType; newcolumnInfo.Identity = PrimaryKeyCheckbox.Checked; newcolumnInfo.DataType.MaximumLength = Convert.ToInt32(LengthTextbox.Text); newcolumnInfo.Nullable = AllowNullCheckbox.Checked; newcolumnInfo.DataType.NumericPrecision = Convert.ToInt32(PrecisionTextbox.Text); newcolumnInfo.DataType.NumericScale = Convert.ToInt32(ScaleTextbox.Text); newcolumnInfo.Identity = IdentityCheckBox.Checked; newcolumnInfo.IdentitySeed = Convert.ToInt32(IdentitySeedTextbox.Text); newcolumnInfo.IdentityIncrement = Convert.ToInt32(IdentityIncrementTextbox.Text); return newcolumnInfo; } } }
namespace Zinnia.Extension { using UnityEngine; /// <summary> /// Extended methods for the <see cref="Collider"/> Type. /// </summary> public static class ColliderExtensions { /// <summary> /// Gets the <see cref="Transform"/> of the container of the collider. /// </summary> /// <param name="collider">The <see cref="Collider"/> to check against.</param> /// <returns>The container.</returns> public static Transform GetContainingTransform(this Collider collider) { if (collider == null) { return null; } Rigidbody attachedRigidbody = collider.attachedRigidbody; return attachedRigidbody == null ? collider.transform : attachedRigidbody.transform; } } }
using SmartHome.Abstract; using SmartHome.Model; namespace SmartHome.Service.Response { public class StatusResponse : ResponseString<Status> { } }
using System; using System.Collections.Generic; using System.Text; namespace RXCO.AzureDevOps.REST.Pipelines.ReleaseManagement { public class ReleaseDefinition { } }
using System; using System.Collections.Generic; using NHibernate; namespace Profiling2.Domain.Contracts.Queries.Stats { public interface ISourceStatisticsQueries { int GetSourceCount(bool archived); Int64 GetTotalSize(); Int64 GetTotalArchivedSize(); IList<object[]> GetSourceImportsByDay(); DateTime GetLastAdminSourceImportDate(); int GetSourceCountByFolder(string folder, ISession session); DateTime GetLastDateByFolder(string folder, ISession session); } }
/************************************** * * Usually a Debuff that can be inflicted to * A character via damages * **************************************/ using DChild.Gameplay.Combat.StatusEffects.Configurations; namespace DChild.Gameplay.Combat.StatusEffects { public interface IStatusEffect { void Inflict(); } public interface IStatusEffect<T> : IStatusEffect where T : IStatusConfig { void SetConfig(T config); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SelectableEventCard : MonoBehaviour, ISelectable<PlayerCard> { private PlayerCard card; public Text label; private EventCardHandler eventCardHandler; public Sprite sprite; void Awake(){ eventCardHandler = GameObject.Find("EventCardHandler").GetComponent<EventCardHandler>(); } public void OnMouseDown(){ Vals.proceed = true; eventCardHandler.eventClicked(card); } public void populateItemData(PlayerCard card){ this.card = card; label.text = card.Name; } public PlayerCard getSelectedValue(){ return card; } public Sprite getSprite(){ return sprite; } public bool isSelected(){ return false; } }
using System; namespace iSukces.Code { [Flags] public enum CodeFormattingFeatures { None = 0, ExpressionBody = 1, Regions = 2, IsNotNull = 4, MakeAutoImplementIfPossible = 8 } public struct CodeFormatting { public CodeFormatting(CodeFormattingFeatures flags, int maxLineLength) { Flags = flags; MaxLineLength = maxLineLength; } public CodeFormattingFeatures Flags { get; } public int MaxLineLength { get; } public static int IndentSpaces { get; set; } = 4; public CodeFormatting With(CodeFormattingFeatures flag) { return new CodeFormatting(Flags | flag, MaxLineLength); } } }
/* * Class that represents the Casting Office room on the board. * Since there can be only one Casting Office in the game, it is a Singleton. * It exists only to allow players to upgrade their rank. * Copyright (c) Yulo Leake 2016 */ using Deadwood.Model.Exceptions; using System; using System.Collections.Generic; namespace Deadwood.Model.Rooms { // Types of currency it supports to rank up public enum CurrencyType { Money, Credit }; class CastingOffice : Room { // Singleton Constructor private CastingOffice() : base("Casting Office") {} private static CastingOffice instance; public static CastingOffice mInstance { get { if (instance == null) { instance = new CastingOffice(); } return instance; } } // TODO: Maybe read this from XML or something public readonly int[] UPGRADE_MONEY = { 4, 10, 18, 28, 40 }; public readonly int[] UPGRADE_CREDIT = { 5, 10, 15, 20, 25 }; // Inherited methods public override void Act(Role r) { throw new IllegalRoomActionException("\"Shh, please reframe from being dramatic in the Casting Office.\"\n(You cannot act in the Casting Office)"); } public override void Rehearse(Role r) { throw new IllegalRoomActionException("\"Shh, please be quiet in the Casting Office.\"\n(You cannot rehearse in the Casting Office)"); } public override Role GetRole(string roleName) { throw new IllegalRoomActionException("\"I am afraid I cannot let you do that\"\n(You cannot take up a role in the Casting Office)"); } // Upgrade player's rank to given rank using a valid currency type public override void Upgrade(Player p, CurrencyType type, int rank) { // Check if requested rank within bound, throw error if not if(rank < 2 || rank > 6) { throw new IllegalUserActionException( string.Format("\"I'm afraid we cannot let you do that, {0},\nThe rank requested ({1:d}) is out of bound [{2:d}, {3:d}.\"", p.name, rank, 2, 6)); } // Check if requested rank is less, if so throw an error if(p.rank >= rank) { throw new IllegalUserActionException("\"There's only one way, and that's up, honey.\"\n(You cannot downgrade your rank)"); } switch (type) { case CurrencyType.Money: Console.WriteLine("Using money to upgrade"); if(p.money >= UPGRADE_MONEY[rank - 2]) { // Player has enough money to upgrade p.ChangeMoney(-UPGRADE_MONEY[rank - 2]); p.RankUp(rank); } else { // Player doesn't have enough money to upgrade throw new IllegalUserActionException("\"Come back when you have a real job!\n(You do not have enough money to upgrade)"); } break; case CurrencyType.Credit: Console.WriteLine("Using credit to upgrade"); if (p.credit >= UPGRADE_CREDIT[rank - 2]) { // Player has enough money to upgrade p.ChangeCredit(-UPGRADE_CREDIT[rank - 2]); p.RankUp(rank); } else { // Player doesn't have enough money to upgrade throw new IllegalUserActionException("\"No free lunch!\n(You do not have enough credit to upgrade)"); } break; default: throw new IllegalUserActionException("\"We don't take that kind of thing here.\"\n(That currency is not supported here)"); } } public override void AssignScene(Scene scene) { throw new IllegalRoomActionException("You cannot assign a scene to Casting Office"); } public override List<Role> GetAllExtraRoles() { throw new IllegalRoomActionException("There are no roles in the Casting Office."); } public override List<Role> GetAvailableExtraRoles() { throw new IllegalRoomActionException("There are no roles in the Casting Office."); } public override List<Role> GetAllStarringRoles() { throw new IllegalRoomActionException("There are no roles in the Casting Office."); } public override List<Role> GetAvailableStarringRoles() { throw new IllegalRoomActionException("There are no roles in the Casting Office."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lesson1.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; namespace lesson1 { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddTransient(builder => new ProductsService("App_Data/data.txt")); } // 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.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Product}/{action=List}/{category?}"); }); } } }
using JhinBot; namespace JhinBot.Tables.Objects { public class Event : DiscordObject { public string Name { get; set; } = ""; public ulong GuildID { get; set; } = 0; public string Description { get; set; } = ""; public long Date { get; set; } = 0; public string TimeZone { get; set; } = ""; public long Duration { get; set; } = 0; } }
namespace Sentry.Maui.Tests.Mocks; public class MockElement : Element { public MockElement(string name = null) { // The x:Name attribute set in XAML is assigned to the StyleId property StyleId = name; } public event EventHandler CustomEvent; protected virtual void OnCustomEvent() => CustomEvent?.Invoke(this, EventArgs.Empty); public void RaiseCustomEvent() => OnCustomEvent(); }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.UnitTests.Cmdlets.StorageServices { using System.IO; using System.Text; using System.Management.Automation; using Commands.Utilities.Common; using VisualStudio.TestTools.UnitTesting; using WindowsAzure.ServiceManagement; using Newtonsoft.Json; using Commands.Test.Utilities.Common; using Commands.ServiceManagement.StorageServices; using Commands.Test.Utilities.CloudService; ////[TestClass] public class SetAzureStorageAccountTests : TestBase { private TestData found; private SimpleServiceManagement channel; //[TestInitialize] public void SetupTest() { found = new TestData(); channel = new SimpleServiceManagement { UpdateStorageServiceThunk = ar => { found.SubscriptionId = (string)ar.Values["subscriptionId"]; found.StorageServiceName = (string)ar.Values["StorageServiceName"]; found.UpdateStorageServiceInput = (UpdateStorageServiceInput)ar.Values["updateStorageServiceInput"]; } }; } private void AssertExpectedValue(TestData expected) { var command = new SetAzureStorageAccountCommand { Channel = channel, CommandRuntime = new MockCommandRuntime(), ShareChannel = true, CurrentSubscription = new WindowsAzureSubscription { SubscriptionId = expected.SubscriptionId }, StorageAccountName = expected.StorageServiceName, Description = expected.UpdateStorageServiceInput.Description, Label = expected.UpdateStorageServiceInput.Label, GeoReplicationEnabled = expected.UpdateStorageServiceInput.GeoReplicationEnabled }; command.SetStorageAccountProcess(); Assert.AreEqual(expected.ToString(), found.ToString()); } //[TestMethod] public void TestGeoReplicationEnabled() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { GeoReplicationEnabled = true } } ); } //[TestMethod] public void TestGeoReplicationDisabled() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { GeoReplicationEnabled = false } } ); } //[TestMethod] public void TestGeoReplicationEnabledWithDescriptionAndLabel() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Description = "MyDescription", Label = "MyLabel", GeoReplicationEnabled = true } } ); } //[TestMethod] public void TestGeoReplicationEnabledWithDescription() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Description = "MyDescription", GeoReplicationEnabled = true } } ); } //[TestMethod] public void TestGeoReplicationEnabledWithLabel() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Label = "MyLabel", GeoReplicationEnabled = true } } ); } //[TestMethod] public void TestGeoReplicationDisabledWithDescriptionAndLabel() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Description = "MyDescription", Label = "MyLabel", GeoReplicationEnabled = false } } ); } //[TestMethod] public void TestGeoReplicationDisabledWithDescription() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Description = "MyDescription", GeoReplicationEnabled = false } } ); } //[TestMethod] public void TestGeoReplicationDisabledWithLabel() { AssertExpectedValue( new TestData { SubscriptionId = "MySubscription", StorageServiceName = "MyStorageService", UpdateStorageServiceInput = new UpdateStorageServiceInput { Label = "MyLabel", GeoReplicationEnabled = false } } ); } } class TestData { public string SubscriptionId { get; set; } public string StorageServiceName { get; set; } public UpdateStorageServiceInput UpdateStorageServiceInput { get; set; } public override string ToString() { var builder = new StringBuilder(); using (TextWriter writer = new StringWriter(builder)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, this); } return builder.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; using VendingMachine.Domain.Business.Contracts.Business; using VendingMachine.Domain.Business.Contracts.Repository; using VendingMachine.Domain.Models; using VendingMachine.Repository.Repositories; namespace VendingMachine.Domain.Business { public class ProductService : IProductService { private ProductRepository productRepository; public ProductService() { productRepository = new ProductRepository(); } public List<Product> GetProducts() { return productRepository.GetProducts(); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; //[CreateAssetMenu(fileName = "ShaderList", menuName = "ScriptableObjects/ShaderList", order = 1)] public class ShaderListScritableObj : ScriptableObject { public List<Shader> shaders; public void AddShaders(List<Shader> shaders) { this.shaders = OrderByShaderName(shaders); } private List<Shader> OrderByShaderName(List<Shader> shaders) { if(shaders == null || shaders.Count <= 1) { return null; } shaders.Sort( (x, y) => string.Compare(x.name, y.name) ); var orderedShaders = shaders.OrderBy( x => x.name ).ToList(); return orderedShaders; } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.Editor.Core; using gView.Framework.Geometry; using gView.Framework.LinAlg; 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.Threading; using System.Windows.Forms; namespace gView.Plugins.Editor { class ParentPenToolMenuItem { public delegate void SelectedPenToolChangedEventHandler(object sender, IPenTool penTool); public event SelectedPenToolChangedEventHandler SelectedPenToolChanged = null; private PenToolMenuItem _selected = null; private IPoint _world = null, _contextPoint = null, _contextVertex = null, _mouseWorldPoint = null; private List<ToolStripItem> _items = new List<ToolStripItem>(); private Module _module = null; private ToolStripMenuItem _toolsItem, _cancelPen; public ParentPenToolMenuItem() { _toolsItem = new ToolStripMenuItem(); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new PenTool(), true)); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new OrthoPenTool())); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new ConstructMiddlePoint())); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new ConstructDirectionDirection())); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new ConstructDistanceDistance())); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new ConstructDistanceDirection())); _toolsItem.DropDownItems.Add(new PenToolMenuItem(new ConstructDistanceTangent())); _items.Add(_toolsItem); _items.Add(new ToolStripSeparator()); ToolStripMenuItem snapTo = new ToolStripMenuItem(Globalisation.GetResString("SnapTo")); snapTo.DropDownItems.Add(new CalcToolMenuItem(new SnapToPenTool(this))); snapTo.DropDownItems.Add(new CalcToolMenuItem(new SegmentMidpoint(this))); snapTo.DropDownItems.Add(new CalcToolMenuItem(new SegmentOrtho(this))); _items.Add(snapTo); _items.Add(new ToolStripSeparator()); _items.Add(new CalcToolMenuItem(new DirectionPenTool(this))); _items.Add(new CalcToolMenuItem(new DeflectionPenTool(this))); _items.Add(new CalcToolMenuItem(new PerpenticualPenTool(this))); _items.Add(new CalcToolMenuItem(new ParallelPenTool(this))); _items.Add(new ToolStripSeparator()); _items.Add(new CalcToolMenuItem(new DistancePenTool(this))); _items.Add(new CalcToolMenuItem(new SegmentDistance(this))); _items.Add(new ToolStripSeparator()); _items.Add(new CalcToolMenuItem(new AbsolutXYPenTool(this))); _items.Add(new CalcToolMenuItem(new DeltaXYPenTool(this))); _items.Add(new CalcToolMenuItem(new DirectionDistancePenTool(this))); _cancelPen = new ToolStripMenuItem("Cancel"); _cancelPen.Click += new EventHandler(cancelPen_Click); SetStandardPenTool(); foreach (ToolStripItem item in _toolsItem.DropDownItems) { if (item is PenToolMenuItem) { ((PenToolMenuItem)item).Click += new EventHandler(PenTool_Click); } } foreach (ToolStripItem item in _items) { if (item is CalcToolMenuItem) { ((CalcToolMenuItem)item).Click += new EventHandler(Tool_Click); } else if (item is ToolStripMenuItem) { foreach (ToolStripItem item2 in ((ToolStripMenuItem)item).DropDownItems) { if (item2 is CalcToolMenuItem) { ((CalcToolMenuItem)item2).Click += new EventHandler(Tool_Click); } } } } _toolsItem.Image = _selected.PenTool.Image as System.Drawing.Image; _toolsItem.Text = _selected.Text; } void PenTool_Click(object sender, EventArgs e) { if (!(sender is PenToolMenuItem)) { return; } int index = -1; if (_selected != null) { _selected.Checked = false; if (_selected.PenTool != null) { _selected.Image = _selected.PenTool.Image as System.Drawing.Image; } index = _toolsItem.DropDownItems.IndexOf(_selected); } _selected = (PenToolMenuItem)sender; _selected.Image = null; _selected.Checked = true; if (_selected.PenTool != null) { int pointCount = (_module != null && _module.Sketch != null && _module.Sketch.Part != null) ? _module.Sketch.Part.PointCount : 0; if (!_selected.PenTool.Activated(_contextPoint, _mouseWorldPoint, _contextVertex)) { if (index != 1) { SetPenTool(index); } else { SetStandardPenTool(); } } else { if (_selected != null && _selected.PenTool != null) { _toolsItem.Image = _selected.PenTool.Image as System.Drawing.Image; _toolsItem.Text = "Active Tool: " + _selected.Text; if (SelectedPenToolChanged != null) { SelectedPenToolChanged(this, _selected.PenTool); } } else { _toolsItem.Image = null; _toolsItem.Text = "Active Tool: ???"; } } if (_module != null && _module.Sketch != null && _module.Sketch.Part != null && _module.Sketch.Part.PointCount == pointCount + 1) { this.PerformClick(); } } } void Tool_Click(object sender, EventArgs e) { if (_selected == null || _selected.PenTool == null) { return; } if (!(sender is CalcToolMenuItem) || ((CalcToolMenuItem)sender).CalcTool == null) { return; } object result = ((CalcToolMenuItem)sender).CalcTool.Calc(_contextPoint, _mouseWorldPoint, _contextVertex); if (result != null) { _selected.PenTool.EvaluateCalcToolResult( ((CalcToolMenuItem)sender).CalcTool.ResultType, result); } } void cancelPen_Click(object sender, EventArgs e) { SetStandardPenTool(); } public void OnCreate(IModule module) { _module = module as Module; foreach (ToolStripItem item in _toolsItem.DropDownItems) { if (item is PenToolMenuItem && ((PenToolMenuItem)item).PenTool != null) { ((PenToolMenuItem)item).PenTool.OnCreate(module); } } foreach (ToolStripItem item in _items) { if (item is PenToolMenuItem && ((PenToolMenuItem)item).PenTool != null) { ((PenToolMenuItem)item).PenTool.OnCreate(module); } else if (item is CalcToolMenuItem && ((CalcToolMenuItem)item).CalcTool != null) { ((CalcToolMenuItem)item).CalcTool.OnCreate(module); } else if (item is ToolStripMenuItem) { foreach (ToolStripItem item2 in ((ToolStripMenuItem)item).DropDownItems) { if (item2 is PenToolMenuItem && ((PenToolMenuItem)item2).PenTool != null) { ((PenToolMenuItem)item2).PenTool.OnCreate(module); } else if (item2 is CalcToolMenuItem && ((CalcToolMenuItem)item2).CalcTool != null) { ((CalcToolMenuItem)item2).CalcTool.OnCreate(module); } } } } } public void PerformClick() { if (_selected != null && _selected.PenTool != null) { if (!_selected.PenTool.MouseClick()) { SetStandardPenTool(); } } } public IPoint ContextPoint { get { return _contextPoint; } set { _contextPoint = value; } } public IPoint MouseWorldPoint { get { return _mouseWorldPoint; } set { _mouseWorldPoint = value; } } public IPoint ContextVertex { get { return _contextVertex; } set { _contextVertex = value; } } public List<ToolStripItem> MenuItems { get { List<ToolStripItem> items = ListOperations<ToolStripItem>.Clone(_items); if (_selected != null && !(_selected.PenTool is PenTool)) { _cancelPen.Text = "Cancel" + ((_selected.PenTool != null) ? ": " + _selected.PenTool.Name : ""); items.Insert(0, _cancelPen); } foreach (ToolStripItem item in _items) { if (item is CalcToolMenuItem && ((CalcToolMenuItem)item).CalcTool != null) { if (_selected != null && _selected.PenTool != null) { CalcToolMenuItem citem = (CalcToolMenuItem)item; item.Enabled = (citem.CalcTool.Enabled == true && _selected.PenTool.UseCalcToolResultType(citem.CalcTool.ResultType)); } else { item.Enabled = false; } } } return items; } } public bool DrawMover { get { if (_selected != null && _selected.PenTool != null) { return _selected.PenTool.DrawMover; } return false; } } private void SetStandardPenTool() { SetPenTool(0); } private void SetPenTool(int index) { if (index < 0 || index >= _toolsItem.DropDownItems.Count) { return; } if (_selected != _toolsItem.DropDownItems[index]) { if (_selected != null) { _selected.Checked = false; } if (_selected != null && _selected.PenTool != null) { _selected.Image = _selected.PenTool.Image as System.Drawing.Image; } _selected = _toolsItem.DropDownItems[index] as PenToolMenuItem; if (_selected == null) { return; } _selected.Image = null; _selected.Checked = true; if (_selected != null && _selected.PenTool != null) { _toolsItem.Image = _selected.PenTool.Image as System.Drawing.Image; _toolsItem.Text = "Active Tool: " + _selected.Text; if (SelectedPenToolChanged != null) { SelectedPenToolChanged(this, _selected.PenTool); } } else { _toolsItem.Image = null; _toolsItem.Text = "Active Tool: ???"; } //if (_selected.PenTool != null) // _selected.PenTool.Activated(_world, _world); } } public IPenTool ActivePenTool { get { return _selected.PenTool; } } #region MenuItemClasses private class PenToolMenuItem : ToolStripMenuItem { private IPenTool _penTool; public PenToolMenuItem(IPenTool penTool) { _penTool = penTool; if (_penTool == null) { return; } this.Text = _penTool.Name; this.Image = _penTool.Image as System.Drawing.Image; } public PenToolMenuItem(IPenTool penTool, bool check) : this(penTool) { this.Image = null; this.Checked = check; } public IPenTool PenTool { get { return _penTool; } } } private class CalcToolMenuItem : ToolStripMenuItem { private ICalcTool _tool; public CalcToolMenuItem(ICalcTool penTool) { _tool = penTool; if (_tool == null) { return; } this.Text = _tool.Name; this.Image = _tool.Image as System.Drawing.Image; } public CalcToolMenuItem(ICalcTool penTool, bool check) : this(penTool) { this.Image = null; this.Checked = check; } public ICalcTool CalcTool { get { return _tool; } } } #endregion public IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { _world = world; if (_selected != null && _selected.PenTool != null) { return _selected.PenTool.CalcPoint(mouseX, mouseY, world); } else { return world; } } internal static IPath QueryPathSegment(IMap map, IPoint point) { return QueryPathSegment(map, point, true); } internal static IPath QueryPathSegment(IMap map, IPoint point, bool blink) { if (map == null || map.TOC == null || map.Display == null || point == null) { return null; } List<ILayer> layers = map.TOC.VisibleLayers; double tol = 6 * map.Display.mapScale / (96 / 0.0254); // [m] if (map.Display.SpatialReference != null && map.Display.SpatialReference.SpatialParameters.IsGeographic) { tol = (180.0 * tol / Math.PI) / 6370000.0; } Envelope envelope = new Envelope(point.X - tol / 2, point.Y - tol / 2, point.X + tol / 2, point.Y + tol / 2); SpatialFilter filter = new SpatialFilter(); filter.FilterSpatialReference = map.Display.SpatialReference; filter.FeatureSpatialReference = map.Display.SpatialReference; filter.Geometry = envelope; IPath coll = null; double dist = double.MaxValue; foreach (ILayer layer in layers) { if (!(layer is IFeatureLayer) || ((IFeatureLayer)layer).FeatureClass == null) { continue; } if (layer.MinimumScale > 1 && layer.MinimumScale > map.Display.mapScale) { continue; } if (layer.MaximumScale > 1 && layer.MaximumScale < map.Display.mapScale) { continue; } IFeatureClass fc = ((IFeatureLayer)layer).FeatureClass; if (fc.GeometryType != GeometryType.Polyline && fc.GeometryType != GeometryType.Polygon) { continue; } filter.SubFields = fc.ShapeFieldName; double distance = 0.0; using (IFeatureCursor cursor = fc.GetFeatures(filter).Result) { IFeature feature; while ((feature = cursor.NextFeature().Result) != null) { if (feature.Shape == null) { continue; } int partNr, pointNr; IPoint p = gView.Framework.SpatialAlgorithms.Algorithm.NearestPointToPath(feature.Shape, point, out distance, false, false, out partNr, out pointNr); if (distance <= tol && distance < dist && partNr >= 0 && pointNr >= 0) { List<IPath> paths = gView.Framework.SpatialAlgorithms.Algorithm.GeometryPaths(feature.Shape); if (paths == null || paths.Count <= partNr) { continue; } IPath path = paths[partNr]; if (path == null || path.PointCount <= pointNr - 1) { continue; } coll = new Path(); coll.AddPoint(path[pointNr]); coll.AddPoint(path[pointNr + 1]); dist = distance; } } } } if (coll != null && blink) { Polyline pLine = new Polyline(); pLine.AddPath(coll); map.HighlightGeometry(pLine, 300); } return coll; } } class StandardPenTool : IPenTool { protected Module _module = null; #region IPenTool Member virtual public IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { return world; } virtual public bool MouseClick() { return true; } virtual public void OnCreate(IModule module) { _module = module as Module; } virtual public string Name { get { return String.Empty; } } virtual public object Image { get { return null; } } virtual public bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { return true; } virtual public bool DrawMover { get { return true; } } virtual public bool UseCalcToolResultType(CalcToolResultType type) { return false; } virtual public void EvaluateCalcToolResult(CalcToolResultType type, object result) { } #endregion protected void RefrshSketch() { if (_module != null && _module.MapDocument != null && _module.MapDocument.Application is IMapApplication) { ((IMapApplication)_module.MapDocument.Application).RefreshActiveMap(DrawPhase.Graphics); Thread.Sleep(300); } } protected void AddPointToSketch(IPoint point) { if (_module != null && _module.Sketch != null && point != null) { _module.Sketch.AddPoint(new Point(point)); } RefrshSketch(); } protected void SetStatusText(string text) { if (_module != null && _module.MapDocument != null && _module.MapDocument.Application is IMapApplication && ((IMapApplication)_module.MapDocument.Application).StatusBar != null) { ((IMapApplication)_module.MapDocument.Application).StatusBar.Text = text; } } static public IPoint CalcPoint(Module module, IPoint world, double direction, double distance, IPoint refPoint) { IPoint p1 = null; if (!double.IsNaN(direction)) { if (refPoint != null) { p1 = refPoint; } else if (module != null && module.Sketch != null && module.Sketch.Part != null && module.Sketch.Part.PointCount > 0) { p1 = module.Sketch.Part[module.Sketch.Part.PointCount - 1]; } if (p1 == null) { return null; } Point r = new Point(Math.Cos(direction), Math.Sin(direction)); Point r_ = new Point(-r.Y, r.X); LinearEquation2 linarg = new LinearEquation2( world.X - p1.X, world.Y - p1.Y, r.X, r_.X, r.Y, r_.Y); if (linarg.Solve()) { double t1 = linarg.Var1; //double t2 = linarg.Var2; return new Point(p1.X + r.X * t1, p1.Y + r.Y * t1); } return null; } else if (!double.IsNaN(distance)) { if (refPoint != null) { p1 = refPoint; } else if (module != null && module.Sketch != null && module.Sketch.Part != null && module.Sketch.Part.PointCount > 0) { p1 = module.Sketch.Part[module.Sketch.Part.PointCount - 1]; } if (p1 == null) { return null; } double dx = world.X - p1.X; double dy = world.Y - p1.Y; double len = Math.Sqrt(dx * dx + dy * dy); dx /= len; dy /= len; return new Point(p1.X + dx * distance, p1.Y + dy * distance); } return world; } } class PenTool : StandardPenTool { private double _direction = double.NaN, _distance = double.NaN; override public string Name { get { return Globalisation.GetResString("Pen"); } } override public object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.edit_blue; } } public override bool MouseClick() { _direction = double.NaN; _distance = double.NaN; return true; } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _direction = double.NaN; _distance = double.NaN; return true; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { return StandardPenTool.CalcPoint(_module, world, _direction, _distance, null); } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Direction: return true; case CalcToolResultType.Distance: return true; case CalcToolResultType.SnapTo: return true; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (_module == null || _module.Sketch == null) { return; } _distance = _direction = double.NaN; switch (type) { case CalcToolResultType.AbsolutPos: case CalcToolResultType.SnapTo: if (result is IPoint) { _module.Sketch.AddPoint((IPoint)result); RefrshSketch(); } break; case CalcToolResultType.Direction: if (result.GetType() == typeof(double)) { _direction = (double)result; } break; case CalcToolResultType.Distance: if (result.GetType() == typeof(double)) { _distance = (double)result; } break; } } } class OrthoPenTool : StandardPenTool { private double _alpha = double.NaN, _direction = double.NaN; public override string Name { get { return Globalisation.GetResString("Orthogonal"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.ortho; } } public override bool MouseClick() { _direction = double.NaN; return true; } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _direction = double.NaN; return true; } public override gView.Framework.Geometry.IPoint CalcPoint(int mouseX, int mouseY, gView.Framework.Geometry.IPoint world) { if (_module == null) { return base.CalcPoint(mouseX, mouseY, world); } EditSketch sketch = _module.Sketch; IPointCollection part = (sketch != null) ? sketch.Part : null; if (sketch == null) { return base.CalcPoint(mouseX, mouseY, world); } else { double alpha = double.NaN; IPoint p2 = null; if (part != null && part.PointCount >= 2) { IPoint p1 = part[part.PointCount - 2]; p2 = part[part.PointCount - 1]; double dx = p2.X - p1.X; double dy = p2.Y - p1.Y; alpha = Math.Atan2(dy, dx); } else if (part != null && part.PointCount == 1 && !double.IsNaN(_direction)) { p2 = part[part.PointCount - 1]; alpha = _direction + Math.PI / 2.0; } else { return base.CalcPoint(mouseX, mouseY, world); } IPoint resP1 = null; IPoint resP2 = null; Point r = new Point(Math.Sin(alpha), -Math.Cos(alpha)); Point r_ = new Point(-r.Y, r.X); #region Ortho LinearEquation2 linarg = new LinearEquation2( world.X - p2.X, world.Y - p2.Y, r.X, r_.X, r.Y, r_.Y); if (linarg.Solve()) { double t1 = linarg.Var1; double t2 = linarg.Var2; resP1 = new Point(p2.X + r.X * t1, p2.Y + r.Y * t1); } #endregion #region Otrho 2 if (part != null && part.PointCount >= 2) { r = new Point(Math.Cos(alpha), Math.Sin(alpha)); r_ = new Point(-r.Y, r.X); linarg = new LinearEquation2( world.X - p2.X, world.Y - p2.Y, r.X, r_.X, r.Y, r_.Y); if (linarg.Solve()) { double t1 = linarg.Var1; double t2 = linarg.Var2; resP2 = new Point(p2.X + r.X * t1, p2.Y + r.Y * t1); } } #endregion if (resP1 != null && resP2 != null) { if (gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(world, resP1) <= gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(world, resP2)) { _alpha = Math.Atan2(resP1.Y - p2.Y, resP1.X - p2.X); return new Point(resP1.X, resP1.Y); } else { _alpha = Math.Atan2(resP2.Y - p2.Y, resP2.X - p2.X); return new Point(resP2.X, resP2.Y); } } else if (resP1 != null) { _alpha = Math.Atan2(resP1.Y - p2.Y, resP1.X - p2.X); return new Point(resP1.X, resP1.Y); } else { _alpha = Math.Atan2(resP2.Y - p2.Y, resP2.X - p2.X); return new Point(resP2.X, resP2.Y); } } } public override bool UseCalcToolResultType(CalcToolResultType type) { if (_module == null) { return false; } switch (type) { case CalcToolResultType.Distance: return !double.IsNaN(_alpha); case CalcToolResultType.AbsolutPos: if (_module.Sketch == null || _module.Sketch.Part == null) { return true; } return _module.Sketch.Part.PointCount < 2; case CalcToolResultType.Direction: if (_module.Sketch == null || _module.Sketch.Part == null) { return false; } return _module.Sketch.Part.PointCount == 1; case CalcToolResultType.SnapTo: return true; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (result == null || _module == null || _module.Sketch == null) { return; } if (type == CalcToolResultType.Distance && result.GetType() == typeof(double) && _module.Sketch.Part != null && _module.Sketch.Part.PointCount > 0 && !double.IsNaN(_alpha)) { IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; double dist = (double)result; _module.Sketch.AddPoint( new Point(p1.X + Math.Cos(_alpha) * dist, p1.Y + Math.Sin(_alpha) * dist)); RefrshSketch(); } else if (type == CalcToolResultType.AbsolutPos && result is IPoint && (_module.Sketch.Part == null || _module.Sketch.Part.PointCount < 2)) { _module.Sketch.AddPoint(new Point((IPoint)result)); RefrshSketch(); } else if (type == CalcToolResultType.Direction && _module.Sketch.Part != null && _module.Sketch.Part.PointCount == 1 && result.GetType() == typeof(double)) { _direction = (double)result; } else if (type == CalcToolResultType.SnapTo && result is IPoint) { _module.Sketch.AddPoint(new Point((IPoint)result)); RefrshSketch(); } } } class ConstructPenTool : StandardPenTool { static IGraphicsContainer _constContainer; private static SimplePointSymbol _pointSymbol = null; private static SimpleLineSymbol _lineSymbol = null; public ConstructPenTool() { _constContainer = new GraphicsContainer(); if (_lineSymbol == null) { _lineSymbol = new SimpleLineSymbol(); _lineSymbol.Color = ArgbColor.Gray; } if (_pointSymbol == null) { _pointSymbol = new SimplePointSymbol(); _pointSymbol.Marker = SimplePointSymbol.MarkerType.Square; _pointSymbol.Color = ArgbColor.Red; _pointSymbol.Size = 8; _pointSymbol.PenColor = ArgbColor.Yellow; _pointSymbol.SymbolWidth = 2; } } protected void DrawConstructionSketch(IGeometry geometry) { if (_module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null) { return; } _constContainer.Elements.Clear(); if (geometry is IPoint || geometry is IMultiPoint) { _constContainer.Elements.Add(new PointGraphics(geometry)); } else if (geometry is IPolyline || geometry is IPolygon) { _constContainer.Elements.Add(new LineGraphics(geometry)); } else if (geometry is IAggregateGeometry) { for (int i = 0; i < ((IAggregateGeometry)geometry).GeometryCount; i++) { IGeometry g = ((IAggregateGeometry)geometry)[i]; if (g is IPoint || g is IMultiPoint) { _constContainer.Elements.Add(new PointGraphics(g)); } else if (g is IPolyline || g is IPolygon) { _constContainer.Elements.Add(new LineGraphics(g)); } } } //((IMapApplication)_module.MapDocument.Application).DrawReversibleGeometry(geometry, System.Drawing.Color.Gray); _module.MapDocument.FocusMap.Display.DrawOverlay(_constContainer, true); } #region Helper internal static void BuildCircle(Path path, IPoint middle, double raduis, double maxVertexDistance) { if (path == null || middle == null) { return; } double to = 2.0 * Math.PI; //double circum = 2.0 * raduis * Math.PI; //int numPoints = (int)(((double)(circum / maxVertexDistance)) + 1); //double step = 2.0 * Math.PI / numPoints; double step = Math.PI / 30.0; path.RemoveAllPoints(); for (double w = 0.0; w < to; w += step) { path.AddPoint(new Point(middle.X + raduis * Math.Cos(w), middle.Y + raduis * Math.Sin(w))); } if (path.PointCount > 0) { path.AddPoint(path[0]); } } internal static void BuildRay(Path path, IPoint p1, IPoint p2, IEnvelope env) { if (path == null || p1 == null || p2 == null || env == null) { return; } double minLength = Math.Max(env.Width, env.Height); double length = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(p1, p2); double dx = p2.X - p1.X; double dy = p2.Y - p1.Y; path.RemoveAllPoints(); path.AddPoint(new Point(p2.X + dx / length * minLength, p2.Y + dy / length * minLength)); path.AddPoint(new Point(p2.X - dx / length * minLength, p2.Y - dy / length * minLength)); } #endregion #region HelperClasses private class LineGraphics : IGraphicElement { private IGeometry _geometry; public LineGraphics(IGeometry geometry) { _geometry = geometry; } #region IGraphicElement Member public void Draw(IDisplay display) { if (display != null && _geometry != null) { display.Draw(ConstructPenTool._lineSymbol, _geometry); } } #endregion } private class PointGraphics : IGraphicElement { private IGeometry _geometry; public PointGraphics(IGeometry geometry) { _geometry = geometry; } #region IGraphicElement Member public void Draw(IDisplay display) { if (display != null && _geometry != null) { display.Draw(ConstructPenTool._pointSymbol, _geometry); } } #endregion } #endregion virtual public Path ConstructionPath { get { return null; } } static protected Path ReducePath(Path path, int reduce) { if (path == null) { return null; } Path p = new Path(); for (int i = 0; i < path.PointCount - reduce; i++) { p.AddPoint(path[i]); } return p; } } class ConstructMiddlePoint : ConstructPenTool { private IPoint _point1 = null, _world = null; private AggregateGeometry _geometry = null; private Polyline _polyLine = null; private double _distance = double.NaN, _direction = double.NaN; private bool _fixed = false; public override string Name { get { return Globalisation.GetResString("MiddlepointTool"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.const_midpoint; } } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _geometry = null; _point1 = null; _polyLine = null; _distance = _direction = double.NaN; _fixed = false; SetStatusText(Globalisation.GetResString("S6", String.Empty)); return true; } public override bool MouseClick() { if (_point1 == null) { _point1 = new Point(_world); _geometry = new AggregateGeometry(); _polyLine = new Polyline(); _polyLine.AddPath(new Path()); _polyLine[0].AddPoint(new Point(_world)); _polyLine[0].AddPoint(new Point(_world)); _geometry.AddGeometry(_polyLine); _geometry.AddGeometry(_point1); SetStatusText(Globalisation.GetResString("S7", String.Empty)); return true; } else if (_fixed) { _point1.X = _polyLine[0][0].X / 2.0 + _world.X / 2.0; _point1.Y = _polyLine[0][0].Y / 2.0 + _world.Y / 2.0; _polyLine[0][1].X = _world.X; _polyLine[0][1].Y = _world.Y; } SetStatusText(""); return false; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { if (world == null) { return null; } if (_point1 == null || _polyLine == null || _geometry == null) { _world = world; return null; } else if (!_fixed) { _world = StandardPenTool.CalcPoint(_module, world, _direction, _distance, _polyLine[0][0]); } _point1.X = _polyLine[0][0].X / 2.0 + _world.X / 2.0; _point1.Y = _polyLine[0][0].Y / 2.0 + _world.Y / 2.0; _polyLine[0][1].X = _world.X; _polyLine[0][1].Y = _world.Y; base.DrawConstructionSketch(_geometry); return _point1; } public override bool DrawMover { get { return false; } } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Direction: return true; case CalcToolResultType.Distance: return true; case CalcToolResultType.SnapTo: return true; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (_module == null || _module.Sketch == null) { return; } _distance = _direction = double.NaN; switch (type) { case CalcToolResultType.AbsolutPos: case CalcToolResultType.SnapTo: if (result is IPoint) { _fixed = (_point1 != null); _world = (IPoint)result; MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Direction: if (result.GetType() == typeof(double)) { _direction = (double)result; } break; case CalcToolResultType.Distance: if (result.GetType() == typeof(double)) { _distance = (double)result; } break; } } public override Path ConstructionPath { get { if (_polyLine != null && _polyLine.PathCount == 1) { return ConstructPenTool.ReducePath(_polyLine[0] as Path, 1); } return null; } } } class ConstructDirectionDirection : ConstructPenTool { private IPoint _p11 = null, _p12 = null, _p21 = null, _p22 = null, _p = null, _world = null; private Polyline _polyLine1 = null, _polyLine2 = null; private int _clickPos = 0; private AggregateGeometry _geometry = null; public override string Name { get { return Globalisation.GetResString("IntersectionTool"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.const_intersect; } } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _clickPos = 0; _geometry = null; _polyLine1 = null; _polyLine2 = null; _p11 = _p12 = _p21 = _p22 = _p = null; SetStatusText(Globalisation.GetResString("S9", String.Empty)); return true; } public override bool MouseClick() { if (_module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return true; } _clickPos++; if (_geometry == null) { _geometry = new AggregateGeometry(); } if (_clickPos == 1) { _polyLine1 = new Polyline(); _polyLine1.AddPath(new Path()); _p11 = new Point(_world); _geometry.AddGeometry(_polyLine1); SetStatusText(Globalisation.GetResString("S10", String.Empty)); return true; } else if (_clickPos == 2) { _p12 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine1[0], _p11, _p12, _module.MapDocument.FocusMap.Display.Envelope); SetStatusText(Globalisation.GetResString("S11", String.Empty)); return true; } else if (_clickPos == 3) { _polyLine2 = new Polyline(); _polyLine2.AddPath(new Path()); _p21 = new Point(_world); _geometry.AddGeometry(_polyLine2); SetStatusText(Globalisation.GetResString("S12", String.Empty)); return true; } else if (_clickPos == 4) { _p22 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine2[0], _p21, _p22, _module.MapDocument.FocusMap.Display.Envelope); // Lösungen gerechnen Solve(); } SetStatusText(""); return false; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { _world = world; if (_world == null || _module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return null; } if (_clickPos == 1 && _p11 != null && _polyLine1 != null && _polyLine1.PathCount == 1) { _p12 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine1[0], _p11, _p12, _module.MapDocument.FocusMap.Display.Envelope); } if (_clickPos == 3 && _p21 != null && _polyLine2 != null && _polyLine2.PathCount == 1) { _p22 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine2[0], _p21, _p22, _module.MapDocument.FocusMap.Display.Envelope); Solve(); } base.DrawConstructionSketch(_geometry); return _p; } public override bool DrawMover { get { return false; } } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Direction: return _clickPos == 1 || _clickPos == 3; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (result == null) { return; } switch (type) { case CalcToolResultType.AbsolutPos: if (result is IPoint) { _world = (IPoint)result; MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Direction: if (result.GetType() == typeof(double)) { double direction = (double)result; if (_clickPos == 1 && _p11 != null) { _world = new Point(_p11.X + Math.Cos(direction), _p11.Y + Math.Sin(direction)); } else if (_clickPos == 3 && _p21 != null) { _world = new Point(_p21.X + Math.Cos(direction), _p21.Y + Math.Sin(direction)); } else { break; } MouseClick(); base.DrawConstructionSketch(_geometry); } break; } } public override Path ConstructionPath { get { if (_clickPos > 2 && _polyLine2 != null && _polyLine2.PathCount == 1) { return ConstructPenTool.ReducePath((Path)_polyLine2[0], 1); } if (_clickPos < 2 && _polyLine1 != null && _polyLine1.PathCount == 1) { return ConstructPenTool.ReducePath((Path)_polyLine1[0], 1); } return null; } } private void Solve() { if (_p == null) { _p = new Point(); _geometry.AddGeometry(_p); } IPoint p = gView.Framework.SpatialAlgorithms.Algorithm.SegmentIntersection( _p11, _p12, _p21, _p22, false); if (p == null) { _geometry.RemoveGeometry(3); _p = null; } else { _p.X = p.X; _p.Y = p.Y; } } } class ConstructDistanceDistance : ConstructPenTool { private IPoint _p1 = null, _p2 = null, _p = null, _world = null, _middle1 = null, _middle2 = null; private double _radius1 = -1, _radius2 = -1; private AggregateGeometry _geometry = null; private Polyline _polyLine1 = null, _polyLine2 = null; private int _clickPos = 0; public override string Name { get { return Globalisation.GetResString("DistanceDistanceTool"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.const_dist_dist; } } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _clickPos = 0; _geometry = null; _polyLine1 = null; _polyLine2 = null; _p1 = _p2 = _p = null; _radius1 = _radius2 = -1; _middle1 = _middle2 = null; SetStatusText(Globalisation.GetResString("S1", String.Empty)); return true; } public override bool MouseClick() { _clickPos++; if (_geometry == null) { _geometry = new AggregateGeometry(); } if (_clickPos == 1) { _polyLine1 = new Polyline(); _polyLine1.AddPath(new Path()); _middle1 = new Point(_world); _geometry.AddGeometry(_polyLine1); SetStatusText(Globalisation.GetResString("S2", String.Empty)); } else if (_clickPos == 2) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); SetStatusText(Globalisation.GetResString("S3", String.Empty)); } else if (_clickPos == 3) { _polyLine2 = new Polyline(); _polyLine2.AddPath(new Path()); _middle2 = new Point(_world); _geometry.AddGeometry(_polyLine2); SetStatusText(Globalisation.GetResString("S4", String.Empty)); } else if (_clickPos == 4) { _radius2 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle2); ConstructPenTool.BuildCircle((Path)_polyLine2[0], _middle2, _radius2, 1.0); // Lösungen gerechnen double dx = _middle2.X - _middle1.X; double dy = _middle2.Y - _middle1.Y; double d = Math.Sqrt(dx * dx + dy * dy); if (d > _radius1 + _radius2) { SetStatusText(""); return false; } double a = (_radius1 * _radius1 - _radius2 * _radius2 + d * d) / (2.0 * d); double h2 = _radius1 * _radius1 - a * a; if (h2 < 0.0) { SetStatusText(""); return false; } double h = Math.Sqrt(h2); _p1 = new Point(_middle1.X + (a / d) * dx - (h / d) * dy, _middle1.Y + (a / d) * dy + (h / d) * dx); _p2 = new Point(_middle1.X + (a / d) * dx + (h / d) * dy, _middle1.Y + (a / d) * dy - (h / d) * dx); SetStatusText(Globalisation.GetResString("S5", String.Empty)); } else { SetStatusText(""); return false; } return true; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { _world = world; if (_world == null) { return null; } if (_clickPos == 1 && _middle1 != null && _polyLine1 != null && _polyLine1.PathCount == 1) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); } else if (_clickPos == 3 && _middle2 != null && _polyLine2 != null && _polyLine2.PathCount == 1) { _radius2 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle2); ConstructPenTool.BuildCircle((Path)_polyLine2[0], _middle2, _radius2, 1.0); } else if (_clickPos == 4 && _p1 != null && _p2 != null) { double dist1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p1); double dist2 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p2); if (_p == null) { _p = new Point(); _geometry.AddGeometry(_p); } if (dist1 < dist2) { _p.X = _p1.X; _p.Y = _p1.Y; } else { _p.X = _p2.X; _p.Y = _p2.Y; } } base.DrawConstructionSketch(_geometry); return _p; } public override bool DrawMover { get { return false; } } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Distance: return _clickPos == 1 || _clickPos == 3; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (result == null) { return; } switch (type) { case CalcToolResultType.AbsolutPos: if (result is IPoint) { _world = (IPoint)result; MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Distance: if (result.GetType() == typeof(double)) { double distance = (double)result; if (_clickPos == 1 && _middle1 != null) { _world = new Point(_middle1.X + distance, _middle1.Y); } else if (_clickPos == 3 && _middle2 != null) { _world = new Point(_middle2.X + distance, _middle2.Y); } else { break; } MouseClick(); base.DrawConstructionSketch(_geometry); } break; } } public override Path ConstructionPath { get { if (_clickPos == 1 && _middle1 != null) { Path p = new Path(); p.AddPoint(_middle1); return p; } else if (_clickPos == 3 && _middle2 != null) { Path p = new Path(); p.AddPoint(_middle2); return p; } return null; } } } class ConstructDistanceDirection : ConstructPenTool { private IPoint _p1 = null, _p2 = null, _p = null, _world = null, _middle1 = null, _p11 = null, _p12 = null; private double _radius1 = -1; private AggregateGeometry _geometry = null; private Polyline _polyLine1 = null, _polyLine2 = null; private int _clickPos = 0; public override string Name { get { return Globalisation.GetResString("DistanceDirectionTool"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.const_dist_dir; } } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _clickPos = 0; _p1 = _p2 = _p = null; _middle1 = _p11 = _p12 = null; _radius1 = -1; _geometry = null; _polyLine1 = _polyLine2 = null; SetStatusText(Globalisation.GetResString("S13", String.Empty)); return true; } public override bool MouseClick() { if (_module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return true; } _clickPos++; if (_geometry == null) { _geometry = new AggregateGeometry(); } if (_clickPos == 1) { _polyLine1 = new Polyline(); _polyLine1.AddPath(new Path()); _middle1 = new Point(_world); _geometry.AddGeometry(_polyLine1); SetStatusText(Globalisation.GetResString("S14", String.Empty)); } else if (_clickPos == 2) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); SetStatusText(Globalisation.GetResString("S15", String.Empty)); } else if (_clickPos == 3) { _polyLine2 = new Polyline(); _polyLine2.AddPath(new Path()); _p11 = new Point(_world); _geometry.AddGeometry(_polyLine2); SetStatusText(Globalisation.GetResString("S16", String.Empty)); } else if (_clickPos == 4) { _p12 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine2[0], _p11, _p12, _module.MapDocument.FocusMap.Display.Envelope); if (Solve()) { SetStatusText(Globalisation.GetResString("S5", String.Empty)); return true; } else { SetStatusText(""); return false; } } else { SetStatusText(""); return false; } return true; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { _world = world; if (_world == null || _module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return null; } if (_world == null) { return null; } if (_clickPos == 1 && _middle1 != null && _polyLine1 != null && _polyLine1.PathCount == 1) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); } if (_clickPos == 3 && _p11 != null && _polyLine2 != null && _polyLine2.PathCount == 1) { _p12 = new Point(_world); ConstructPenTool.BuildRay((Path)_polyLine2[0], _p11, _p12, _module.MapDocument.FocusMap.Display.Envelope); } else if (_clickPos == 4) { if (_p1 == null || _p2 == null) { return null; } double dist1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p1); double dist2 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p2); if (_p == null) { _p = new Point(); _geometry.AddGeometry(_p); } if (dist1 < dist2) { _p.X = _p1.X; _p.Y = _p1.Y; } else { _p.X = _p2.X; _p.Y = _p2.Y; } } base.DrawConstructionSketch(_geometry); return _p; } public override bool DrawMover { get { return false; } } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Distance: return _clickPos == 1; case CalcToolResultType.Direction: return _clickPos == 3; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (result == null) { return; } switch (type) { case CalcToolResultType.AbsolutPos: if (result is IPoint) { _world = (IPoint)result; MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Distance: if (result.GetType() == typeof(double)) { double distance = (double)result; if (_clickPos == 1 && _middle1 != null) { _world = new Point(_middle1.X + distance, _middle1.Y); } else { break; } MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Direction: if (result.GetType() == typeof(double)) { double direction = (double)result; if (_clickPos == 3 && _p11 != null) { _world = new Point(_p11.X + Math.Cos(direction), _p11.Y + Math.Sin(direction)); } else { break; } MouseClick(); base.DrawConstructionSketch(_geometry); } break; } } public override Path ConstructionPath { get { if (_clickPos == 1 && _middle1 != null) { Path p = new Path(); p.AddPoint(_middle1); return p; } else if (_clickPos == 3 && _polyLine2 != null) { return ConstructPenTool.ReducePath(_polyLine2[0] as Path, 1); } return null; } } private bool Solve() { if (_middle1 == null || _p11 == null || _p12 == null || _radius1 < 0) { return false; } _p1 = _p2 = null; double dx = _p12.X - _p11.X, dy = _p12.Y - _p11.Y; double len = Math.Sqrt(dx * dx + dy * dy); IPoint ps = gView.Framework.SpatialAlgorithms.Algorithm.SegmentIntersection( _p11, _p12, _middle1, new Point(_middle1.X - dy, _middle1.Y + dx), false); if (ps == null) { return false; } double dist = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(ps, _middle1); if (dist > _radius1) { return false; } dx /= len; dy /= len; double s_2 = Math.Sqrt(_radius1 * _radius1 - dist * dist); _p1 = new Point(ps.X + dx * s_2, ps.Y + dy * s_2); _p2 = new Point(ps.X - dx * s_2, ps.Y - dy * s_2); return true; //_p1 = _p2 = null; //// alles auf Mittelpunkt reduzieren //IPoint p11 = gView.Framework.SpatialAlgorithms.Algorithm.PointDifference(_p11, _middle1); //IPoint p12 = gView.Framework.SpatialAlgorithms.Algorithm.PointDifference(_p12, _middle1); //// Geradengleichung: ax+by=c ... a,b normalvektor auf gerade, c durch einsetzen //double a = p11.Y - p12.Y; //double b = p12.X - p11.X; //double c = p11.X * a + p11.Y * b; //// Quadratische Gleichung: x² + px + q = 0 //double p = -2 * a / (a * a + b * b); //double q = (c * c - b * b * _radius1 * _radius1) / (a * a + b * b); //double D = (p / 2) * (p / 2) - q; //if (D < 0.0) return; //double x1 = -p / 2 + Math.Sqrt(D); //double x2 = -p / 2 - Math.Sqrt(D); //// y=sqrt(r*r-x*x) //double y1 = Math.Sqrt(_radius1 * _radius1 - x1 * x1); //double y2 = Math.Sqrt(_radius1 * _radius1 - x2 * x2); //// zurückrechnen //_p1 = new Point(_middle1.X + x1, _middle1.Y + y1); //_p2 = new Point(_middle1.X + x2, _middle1.Y + y2); } } class ConstructDistanceTangent : ConstructPenTool { private IPoint _p1 = null, _p2 = null, _p = null, _world = null, _middle1 = null, _p11 = null; private double _radius1 = -1; private AggregateGeometry _geometry = null; private Polyline _polyLine1 = null, _polyLine2 = null; private int _clickPos = 0; public override string Name { get { return Globalisation.GetResString("DistanceTangentTool"); } } public override object Image { get { return global::gView.Win.Plugins.Editor.Properties.Resources.const_dist_tan; } } public override bool Activated(IPoint world, IPoint mouseWorld, IPoint vertex) { _clickPos = 0; _p1 = _p2 = _p = null; _middle1 = _p11 = null; _radius1 = -1; _geometry = null; _polyLine1 = _polyLine2 = null; SetStatusText(Globalisation.GetResString("S13", String.Empty)); return true; } public override bool MouseClick() { if (_module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return true; } _clickPos++; if (_geometry == null) { _geometry = new AggregateGeometry(); } if (_clickPos == 1) { _polyLine1 = new Polyline(); _polyLine1.AddPath(new Path()); _middle1 = new Point(_world); _geometry.AddGeometry(_polyLine1); SetStatusText(Globalisation.GetResString("S14", String.Empty)); } else if (_clickPos == 2) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); SetStatusText(Globalisation.GetResString("S15", String.Empty)); } else if (_clickPos == 3) { _polyLine2 = new Polyline(); _polyLine2.AddPath(new Path()); _p11 = new Point(_world); _geometry.AddGeometry(_polyLine2); if (Solve()) { SetStatusText(Globalisation.GetResString("S5", String.Empty)); return true; } else { SetStatusText(""); return false; } } else { SetStatusText(""); return false; } return true; } public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) { _world = world; if (_world == null || _module == null || _module.MapDocument == null || _module.MapDocument.FocusMap == null || _module.MapDocument.FocusMap.Display == null || _module.MapDocument.FocusMap.Display.Envelope == null) { return null; } if (_world == null) { return null; } if (_clickPos == 1 && _middle1 != null && _polyLine1 != null && _polyLine1.PathCount == 1) { _radius1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _middle1); ConstructPenTool.BuildCircle((Path)_polyLine1[0], _middle1, _radius1, 1.0); } else if (_clickPos == 3) { if (_p1 == null) { return null; } double dist1 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p1); double dist2 = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_world, _p2); if (_p == null) { _p = new Point(); _geometry.AddGeometry(_p); } if (dist1 < dist2) { _p.X = _p1.X; _p.Y = _p1.Y; ConstructPenTool.BuildRay((Path)_polyLine2[0], _p11, _p1, _module.MapDocument.FocusMap.Display.Envelope); } else { _p.X = _p2.X; _p.Y = _p2.Y; ConstructPenTool.BuildRay((Path)_polyLine2[0], _p11, _p2, _module.MapDocument.FocusMap.Display.Envelope); } } base.DrawConstructionSketch(_geometry); return _p; } public override bool DrawMover { get { return false; } } public override bool UseCalcToolResultType(CalcToolResultType type) { switch (type) { case CalcToolResultType.AbsolutPos: return true; case CalcToolResultType.Distance: return _clickPos == 1; } return false; } public override void EvaluateCalcToolResult(CalcToolResultType type, object result) { if (result == null) { return; } switch (type) { case CalcToolResultType.AbsolutPos: if (result is IPoint) { _world = (IPoint)result; MouseClick(); base.DrawConstructionSketch(_geometry); } break; case CalcToolResultType.Distance: if (result.GetType() == typeof(double)) { double distance = (double)result; if (_clickPos == 1 && _middle1 != null) { _world = new Point(_middle1.X + distance, _middle1.Y); } else { break; } MouseClick(); base.DrawConstructionSketch(_geometry); } break; } } public override Path ConstructionPath { get { if (_clickPos == 1 && _middle1 != null) { Path p = new Path(); p.AddPoint(_middle1); return p; } return null; } } private bool Solve() { if (_middle1 == null || _p11 == null || _radius1 < 0) { return false; } _p1 = _p2 = null; double d = gView.Framework.SpatialAlgorithms.Algorithm.PointDistance(_p11, _middle1); if (d < _radius1) { return false; } double s = Math.Sqrt(d * d - _radius1 * _radius1); double h = _radius1 * s / d; double d_ = Math.Sqrt(_radius1 * _radius1 - h * h); double dx = (_p11.X - _middle1.X) / d; double dy = (_p11.Y - _middle1.Y) / d; IPoint Z = new Point(_middle1.X + dx * d_, _middle1.Y + dy * d_); _p1 = new Point(Z.X - dy * h, Z.Y + dx * h); _p2 = new Point(Z.X + dy * h, Z.Y - dx * h); return true; } } class StandardCalcTool : ICalcTool { protected Module _module = null; protected ParentPenToolMenuItem _parent = null; public StandardCalcTool(ParentPenToolMenuItem parent) { _parent = parent; } #region ICalcTool Member virtual public string Name { get { return String.Empty; } } virtual public object Image { get { return null; } } virtual public void OnCreate(IModule module) { _module = module as Module; } virtual public object Calc(IPoint world, IPoint worldMouse, IPoint vertex) { return null; } virtual public CalcToolResultType ResultType { get { return CalcToolResultType.None; } } virtual public bool Enabled { get { return false; } } #endregion protected Path CurrentPath { get { if (_parent.ActivePenTool is ConstructPenTool) { return ((ConstructPenTool)_parent.ActivePenTool).ConstructionPath; } if (_module != null && _module.Sketch != null && _module.Sketch.Part is Path) { return _module.Sketch.Part as Path; } return null; } } } class PerpenticualPenTool : StandardCalcTool { public PerpenticualPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("PerpenticulaTo"); } } public override object Image { get { return null; } } //public override bool MouseClick() //{ // return false; //} //public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) //{ // if (double.IsNaN(_alpha)) // { // _world = world; // } // else if (_module != null && // _module.Sketch != null && // _module.Sketch.Part != null && // _module.Sketch.Part.PointCount > 0) // { // return CalcPoint(world); // } // return null; //} public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = segment[0]; IPoint p2 = segment[1]; double dx = p2.X - p1.X; double dy = p2.Y - p1.Y; return (double)Math.Atan2(dy, dx) + Math.PI / 2.0; } else { return null; } } public override CalcToolResultType ResultType { get { return CalcToolResultType.Direction; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } //virtual public IPoint CalcPoint(IPoint world) //{ // IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; // Point r = new Point(Math.Sin(_alpha), -Math.Cos(_alpha)); // Point r_ = new Point(-r.Y, r.X); // LinearEquation2 linarg = new LinearEquation2( // world.X - p1.X, // world.Y - p1.Y, // r.X, r_.X, // r.Y, r_.Y); // if (linarg.Solve()) // { // double t1 = linarg.Var1; // //double t2 = linarg.Var2; // return new Point(p1.X + r.X * t1, p1.Y + r.Y * t1); // } // return null; //} } class ParallelPenTool : PerpenticualPenTool { public ParallelPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("ParallelTo"); } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = segment[0]; IPoint p2 = segment[1]; double dx = p2.X - p1.X; double dy = p2.Y - p1.Y; return (double)Math.Atan2(dy, dx); } else { return null; } } //public override IPoint CalcPoint(IPoint world) //{ // IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; // Point r = new Point(Math.Cos(_alpha), Math.Sin(_alpha)); // Point r_ = new Point(-r.Y, r.X); // LinearEquation2 linarg = new LinearEquation2( // world.X - p1.X, // world.Y - p1.Y, // r.X, r_.X, // r.Y, r_.Y); // if (linarg.Solve()) // { // double t1 = linarg.Var1; // //double t2 = linarg.Var2; // return new Point(p1.X + r.X * t1, p1.Y + r.Y * t1); // } // return null; //} } class SnapToPenTool : StandardCalcTool { public SnapToPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("SemgentUseDirection"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = segment[0]; IPoint p2 = segment[1]; IPoint r1 = new Point(p2.X - p1.X, p2.Y - p1.Y); IPoint p0 = base.CurrentPath[base.CurrentPath.PointCount - 1]; IPoint r0 = new Point(vertex.X - p0.X, vertex.Y - p0.Y); LinearEquation2 linarg = new LinearEquation2( p0.X - p1.X, p0.Y - p1.Y, r1.X, -r0.X, r1.Y, -r0.Y); if (linarg.Solve()) { double t1 = linarg.Var1; if (t1 >= 0.0 && t1 <= 1.0) { return new Point(p1.X + t1 * r1.X, p1.Y + t1 * r1.Y); } } } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.SnapTo; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } } class DirectionPenTool : StandardCalcTool { public DirectionPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("Direction"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (vertex == null) { vertex = world; } if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 1]; if (p1 == null) { return null; } double dx = vertex.X - p1.X; double dy = vertex.Y - p1.Y; FormDirection dlg = new FormDirection(); dlg.Direction = Math.Atan2(dy, dx); if (dlg.ShowDialog() == DialogResult.OK) { return dlg.Direction; } else { return null; } } public override CalcToolResultType ResultType { get { return CalcToolResultType.Direction; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } //public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) //{ // if (double.IsNaN(_alpha)) return null; // if (_module != null && // _module.Sketch != null && // _module.Sketch.Part != null && // _module.Sketch.Part.PointCount > 0) // { // IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; // Point r = new Point(Math.Cos(_alpha), Math.Sin(_alpha)); // Point r_ = new Point(-r.Y, r.X); // LinearEquation2 linarg = new LinearEquation2( // world.X - p1.X, // world.Y - p1.Y, // r.X, r_.X, // r.Y, r_.Y); // if (linarg.Solve()) // { // double t1 = linarg.Var1; // //double t2 = linarg.Var2; // return new Point(p1.X + r.X * t1, p1.Y + r.Y * t1); // } // } // return null; //} } class DeflectionPenTool : DirectionPenTool { public DeflectionPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("Deflection"); } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (base.CurrentPath == null || base.CurrentPath.PointCount < 2) { return null; } IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 2]; IPoint p2 = base.CurrentPath[base.CurrentPath.PointCount - 1]; if (p1 == null) { return null; } double dx = p2.X - p1.X; double dy = p2.Y - p1.Y; FormDirection dlg = new FormDirection(); dlg.Direction = 0.0; if (dlg.ShowDialog() == DialogResult.OK) { return Math.Atan2(dy, dx) + dlg.Direction; } else { return null; } } public override CalcToolResultType ResultType { get { return CalcToolResultType.Direction; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 1) { return true; } return false; } } } class DistancePenTool : StandardCalcTool { public DistancePenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("Distance"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (vertex == null) { vertex = world; } if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 1]; if (p1 == null) { return null; } double dx = vertex.X - p1.X; double dy = vertex.Y - p1.Y; FormDistance dlg = new FormDistance(); dlg.Distance = Math.Sqrt(dx * dx + dy * dy); if (dlg.ShowDialog() == DialogResult.OK) { return dlg.Distance; } else { return null; } } public override CalcToolResultType ResultType { get { return CalcToolResultType.Distance; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } //public override IPoint CalcPoint(int mouseX, int mouseY, IPoint world) //{ // if (double.IsNaN(_length)) return null; // if (_module != null && // _module.Sketch != null && // _module.Sketch.Part != null && // _module.Sketch.Part.PointCount > 0) // { // IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; // double dx = world.X - p1.X; // double dy = world.Y - p1.Y; // double len = Math.Sqrt(dx * dx + dy * dy); // dx /= len; dy /= len; // return new Point(p1.X + dx * _length, p1.Y + dy * _length); // } // return null; //} } class DirectionDistancePenTool : StandardCalcTool { public DirectionDistancePenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("DirectionDistance"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 1]; if (p1 == null) { return null; } double dx = vertex.X - p1.X; double dy = vertex.Y - p1.Y; FormDirectionDistance dlg = new FormDirectionDistance(); dlg.Direction = Math.Atan2(dy, dx); dlg.Distance = Math.Sqrt(dx * dx + dy * dy); if (dlg.ShowDialog() == DialogResult.OK) { double alpha = dlg.Direction; double length = dlg.Distance; dx = Math.Cos(alpha) * length; dy = Math.Sin(alpha) * length; return new Point(p1.X + dx, p1.Y + dy); } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.AbsolutPos; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } } class AbsolutXYPenTool : StandardCalcTool { public AbsolutXYPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("AbsolutXY"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { IPoint p = null; if (_module != null && _module.Sketch != null && _module.Sketch.Part != null && vertex != null) { p = vertex; } else if (_module != null && _module.Sketch == null) { _module.CreateStandardFeature(); p = world; } else { p = world; } if (p == null) { return null; } FormXY dlg = new FormXY(); dlg.Text = "Absolut X,Y"; dlg.X = p.X; dlg.Y = p.Y; if (dlg.ShowDialog() == DialogResult.OK) { return new Point(dlg.X, dlg.Y); } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.AbsolutPos; } } public override bool Enabled { get { return true; } } } class DeltaXYPenTool : StandardCalcTool { public DeltaXYPenTool(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("DeltaXY"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPoint p1 = _module.Sketch.Part[_module.Sketch.Part.PointCount - 1]; if (p1 == null) { return null; } double dx = vertex.X - p1.X; double dy = vertex.Y - p1.Y; FormXY dlg = new FormXY(); dlg.Text = "Delta X,Y"; dlg.X = dx; dlg.Y = dy; if (dlg.ShowDialog() == DialogResult.OK) { dx = dlg.X; dy = dlg.Y; return new Point(p1.X + dx, p1.Y + dy); } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.AbsolutPos; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } } class SegmentMidpoint : StandardCalcTool { public SegmentMidpoint(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("SegmentMidpoint"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (vertex == null) { vertex = world; } if (vertex == null) { return null; } IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = segment[0]; IPoint p2 = segment[1]; if (_module != null && _module.Sketch == null) { _module.CreateStandardFeature(); } return new Point(p1.X / 2.0 + p2.X / 2.0, p1.Y / 2.0 + p2.Y / 2.0); } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.AbsolutPos; } } public override bool Enabled { get { return true; } } } class SegmentDistance : StandardCalcTool { public SegmentDistance(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("SegmentDistance"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (vertex == null) { vertex = world; } if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 1]; double distance; Polyline pLine = new Polyline(); pLine.AddPath(segment); if (gView.Framework.SpatialAlgorithms.Algorithm.NearestPointToPath( pLine, p1, out distance, false, true) != null) { return distance; } } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.Distance; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } } class SegmentOrtho : StandardCalcTool { public SegmentOrtho(ParentPenToolMenuItem parent) : base(parent) { } public override string Name { get { return Globalisation.GetResString("SegmentOrthogonal"); } } public override object Image { get { return null; } } public override object Calc(IPoint world, IPoint mouseWorld, IPoint vertex) { if (vertex == null) { vertex = world; } if (base.CurrentPath == null || base.CurrentPath.PointCount == 0 || vertex == null) { return null; } IPath segment = ParentPenToolMenuItem.QueryPathSegment(_module.MapDocument.FocusMap, mouseWorld); if (segment != null && segment.PointCount == 2) { IPoint p1 = base.CurrentPath[base.CurrentPath.PointCount - 1]; double distance; Polyline pLine = new Polyline(); pLine.AddPath(segment); return gView.Framework.SpatialAlgorithms.Algorithm.NearestPointToPath( pLine, p1, out distance, false, false); } return null; } public override CalcToolResultType ResultType { get { return CalcToolResultType.AbsolutPos; } } public override bool Enabled { get { if (base.CurrentPath != null && base.CurrentPath.PointCount > 0) { return true; } return false; } } } }
using System; using AxiEndPoint.EndPointClient.Transfer; namespace AxiEndPoint.EndPointServer.MessageHandlers { public class CheckConnectionMessageHandler : FormatterMessageHandlerBase { private const string CHECK_CONNECTION_COMMAND = "CheckConnection"; public override bool SatisfyBy(Message message) { return message.Command.CommandText.Equals(CHECK_CONNECTION_COMMAND, StringComparison.OrdinalIgnoreCase); } protected override object HandleMessage(Message message) { return true; } } }
/*********************************************** * * This class should only control PlayerCombat classes * It Should not bother with any other behaviour other than this * ***********************************************/ using System; using DChild.Inputs; using Sirenix.OdinInspector; using Spine; using UnityEngine; namespace DChild.Gameplay.Player.Controllers { [System.Serializable] public class WeaponController : PlayerControllerManager.Controller { [SerializeField] [MinValue(0f)] private float m_acceptableComboInterval; private bool m_isAttacking; private float m_acceptableTimer; private bool m_canUseWeapons; public bool isAttacking => m_isAttacking; public override void Initialize() { //m_player.animation.skeletonAnimation.state.Event += OnEvent; //m_player.animation.skeletonAnimation.state.Complete += OnComplete; m_isAttacking = false; m_canUseWeapons = true; } public void HandleWeaponCombat(Player.State state) { if (m_canUseWeapons == true) { var combatInput = m_input.combat; if (combatInput.isMainHandPressed || combatInput.isOffHandPressed) { HandleWeaponCombat(state, combatInput); } } } public void UpdateComboTimer() { if (m_acceptableTimer > 0) { m_acceptableTimer -= Time.deltaTime; if (m_acceptableTimer <= 0) { m_player.combat.ResetCombo(); } } } public void Reset() { m_isAttacking = false; m_canUseWeapons = true; } private void HandleWeaponCombat(Player.State state, CombatInput combatInput) { Player.Focus focus = InterpretFocusFromInput(m_input.direction); m_acceptableTimer = m_acceptableComboInterval; if (m_player.combat.UseWeapon(state, focus)) { m_isAttacking = state == Player.State.Standing ? true : false; m_canUseWeapons = false; } } private HandType GetHandTypeFromInput(CombatInput input) => input.isMainHandPressed ? HandType.Main : HandType.Off; private Player.Focus InterpretFocusFromInput(DirectionalInput input) { var focus = Player.Focus.Front; if (input.isUpHeld) { focus = Player.Focus.Up; } else if (input.isDownHeld) { focus = Player.Focus.Down; } return focus; } private void OnEvent(TrackEntry trackEntry, Spine.Event e) { if (e.Data.Name == PlayerAnimation.EVENT_COMBO_OPPUTUNITY) { m_canUseWeapons = true; } } private void OnComplete(TrackEntry trackEntry) { var isAttackAnim = m_player.animation.GetCurrentAnimation(trackEntry.TrackIndex).Contains("Attack"); if (isAttackAnim || SpineAnimation.IsAnEmptyAnimation(trackEntry)) { m_isAttacking = false; m_canUseWeapons = true; } } } }
namespace AzureAI.CognitiveSearch.CustomSkills.Infrastructure.Settings { public class FormRecognizerSettings { public string ApiEndpoint { get; set; } public string ApiKey { get; set; } public string ModelId { get; set; } } }
using UnityEngine; using UnityEditor; [CustomEditor(typeof (GameManager))] public class GameManagerInspector : Editor { public override void OnInspectorGUI () { if (GUILayout.Button ("Generate")) { (target as GameManager).GenerateLevel (); } base.OnInspectorGUI (); } }
using Newtonsoft.Json.Linq; namespace DataRetriever { public class QueueConfiguration : Configuration { public QueueConfiguration(): base() { } public QueueConfiguration(JObject config): base(config) { } } }
using System; using UnityEngine; public class FPSCameraControl : MonoBehaviour { readonly float mouseSensitivity = 100f; [SerializeField] private Vector3 def = new Vector3(1, 1, 1); public Transform playerBody; public Transform cameraDad; float xRotation = 0f; void Start() { Cursor.lockState = CursorLockMode.Locked; } void Update() { float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime; xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 90f); cameraDad.Rotate(Vector3.right * -mouseY); playerBody.Rotate(Vector3.up * mouseX); //transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); //erBody.GetComponent<Transform>().rotation = Quaternion.Euler(xRotation, 0f, 0f); //playerBody.localRotation = Quaternion.Euler(xRotation, 0f, 0f); } }
using System; namespace Snowflake.Core { /// <summary> /// A unique, time-ordered, 64-bit unsigned value. /// </summary> /// <remarks> /// This library closely mirrors the Discord interpretation of Snowflake. /// That is to say that the format of a generated value looks like the following: /// /// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBCCCCCDDDDDDDDDDDD /// | | | | | /// 64 23 17 12 1 /// /// Wherein (A) is the timestamp in milliseconds since the epoch, (B) is the machine /// ID, (C) is the process ID and D is a sequence number. /// </remarks> public struct Snowflake { /// <summary> /// The 'beginning of time' from the perspective of Snowflake. /// </summary> public static DateTime Epoch { get => new DateTime(2021, 08, 19); } /// <summary> /// The time that this <see cref="Snowflake"/> was generated. /// </summary> public DateTime Timestamp { get; init; } /// <summary> /// The machine that generated this <see cref="Snowflake"/>. /// </summary> public int MachineId { get; init; } /// <summary> /// The process that generated this <see cref="Snowflake"/>. /// </summary> /// <remarks> /// Unique per-machine. /// </remarks> public int ProcessId { get; init; } /// <summary> /// A number indicating the transaction that generated this <see cref="Snowflake"/>. /// </summary> /// <remarks> /// Unique per-worker, per-process, per-second. /// </remarks> public int Sequence { get; init; } /// <summary> /// Create a new instance of <see cref="Snowflake"/>. /// </summary> /// <param name="snowflake">The raw value.</param> public Snowflake(ulong snowflake) { Timestamp = Epoch.AddMilliseconds(snowflake >> 23); MachineId = (int)(snowflake >> 17) & 0x1F; ProcessId = (int)(snowflake >> 12) & 0x1F; Sequence = (int)(snowflake & 0xFFF); } } }
/* * Created by SharpDevelop. * User: Gheyret Kenji * Date: 2020/11/27 * Time: 13:25 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Windows.Forms; namespace UyghurEditPP { /// <summary> /// Description of FormKunupka. /// </summary> public partial class FormKunupka : Form { MainForm parForm; public FormKunupka(MainForm fp) { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); parForm = fp; // // TODO: Add constructor code after the InitializeComponent() call. // } void FormKunupkaLoad(object sender, EventArgs e) { int startx = parForm.Location.X + (parForm.Width-this.Width)/2; int starty = parForm.Location.Y + (parForm.Height-this.Height)/2; this.Location = new Point(startx,starty); } } }
namespace BDTest.NetCore.Razor.ReportMiddleware.Constants; public static class ColourConstants { public static readonly string PrimaryHex = "#2c3e50"; public static readonly string SuccessHex = "#18bc9c"; public static readonly string DangerHex = "#e74c3c"; public static readonly string WarningHex = "#f39d12"; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Domain.ValueObject; using EBS.Infrastructure.Extension; namespace EBS.Query.DTO { public class SupplierProductItemDto { public int ProductId { get; set; } /// <summary> /// 商品名 /// </summary> public string Name { get; set; } /// <summary> /// 商品编码 /// </summary> public string Code { get; set; } public string CategoryName { get; set; } public string Specification { get; set; } public decimal Price { get; set; } } public class SupplierProductDto { public int ProductId { get; set; } /// <summary> /// 商品名 /// </summary> public string Name { get; set; } /// <summary> /// 商品编码 /// </summary> public string Code { get; set; } public string BarCode { get; set; } public string SupplierName { get; set; } public string BrandName { get; set; } public string CategoryName { get; set; } public string Specification { get; set; } public decimal Price { get; set; } public string SupplyStatus { get { return Status.Description(); } } public SupplierProductStatus Status { get; set; } public string NickName { get; set; } } public class ProductPriceCompare { public int ProductId { get; set; } /// <summary> /// 商品编码 /// </summary> public string Code { get; set; } /// <summary> /// 商品名 /// </summary> public string Name { get; set; } public int Id1 { get; set; } public int SupplierId1 { get; set; } public decimal Price1 { get; set; } public SupplierProductStatus Status1 { get; set; } public ComparePriceStatus CompareStatus1 { get; set; } public string SupplyStatus1 { get { return Status1 == 0 ? "" : Status1.Description(); } } public string ComparePriceStatus1 { get { return CompareStatus1 == 0 ? "" : CompareStatus1.Description(); } } public int Id2 { get; set; } public int SupplierId2 { get; set; } public decimal Price2 { get; set; } public SupplierProductStatus Status2 { get; set; } public ComparePriceStatus CompareStatus2 { get; set; } public string SupplyStatus2 { get { return Status2 == 0 ? "" : Status2.Description(); } } public string ComparePriceStatus2 { get { return CompareStatus2 == 0 ? "" : CompareStatus2.Description(); } } public bool textColor1 { get { return this.Price1 < this.Price2; } } public bool textColor2 { get { return this.Price2 < this.Price1; } } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KeepTeamAutotests.Pages { public class CommonPage : Page { public CommonPage(PageManager pageManager) : base(pageManager) { } public CommonPage ensurePageLoaded() { var wait = new WebDriverWait(pageManager.driver, TimeSpan.FromSeconds(PageManager.WAITTIMEFORFINDELEMENT)); wait.Until(d => d.FindElement(By.ClassName("b-sidebar-header"))); return this; } } }
using UserService.Model; using UserService.Repository.CRUD; namespace UserService.Repository { public interface ISpecialtyRepository : IReadCollection<Specialty> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TilePoint : MonoBehaviour { public Vector3 pointPosition; public bool pointActive; public bool isdoor = false; public int pointType; public GameObject currentTile; public TilesCollection tilesCollection; public Vector2 tileID; void Awake () { SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer> (); spriteRenderer.enabled = false; tilesCollection = FindObjectOfType<TilesCollection> (); pointPosition = transform.position; if (pointActive) { currentTile = Instantiate (tilesCollection.tilesCollection [pointType].preCollection [Random.Range (0, tilesCollection.tilesCollection [pointType].preCollection.Length)], pointPosition, Quaternion.identity, transform); TileSetup tileSetup = currentTile.GetComponent<TileSetup> (); tileSetup.TileID = tileID; } } void Start () { } }
using GalaSoft.MvvmLight; using MarkdownUtils.MdAnimated; using Miktemk; using Miktemk.TextToSpeech.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MarkdownAnimator.ViewModel { public class MdDocumentEnumerator : ViewModelBase { //private int curSectionIndex; //private int curPageIndex; private MdAnimatedBlock[] pagesFlat; private readonly Stack<TtsKeyPoint> curPageKeyPoints = new Stack<TtsKeyPoint>(); public MdAnimatedDocument CurMDDocAnim { get; private set; } //public MdAnimatedDocumentSection CurSection { get; private set; } public int TotalPages { get; private set; } public int IndexGlobal { get; set; } public MdAnimatedBlock CurPage { get { if (IndexGlobal < 0 || IndexGlobal >= pagesFlat.Length) return null; return pagesFlat[IndexGlobal]; } } // event handlers public VoidHandler PageChanged; public GenericHandler<IEnumerable<TtsKeyPoint>> UpdateCurKeyPoints; public MdDocumentEnumerator(MdAnimatedDocument CurMDDocAnim) { this.CurMDDocAnim = CurMDDocAnim; IndexGlobal = -1; // TODO: option to display title pages pagesFlat = CurMDDocAnim.Sections.SelectMany(s => s.Pages).ToArray(); //pagesFlat = CurMDDocAnim.Sections.SelectMany(s => s.Pages.Prepend(MakeTitlePage(s))).ToArray(); TotalPages = pagesFlat.Count(); } private MdAnimatedBlock MakeTitlePage(MdAnimatedDocumentSection s) { var ttsText = new MultiLangStringPhrased(); ttsText.AddPhrase(s.Title, "en2"); return new MdAnimatedBlock { Code = $"\n\n\n\n {s.Title}", TtsText = ttsText, }; } /// <summary> /// returns true if we reach the end and go back to start /// </summary> public bool GoToNextPage() { if (IndexGlobal >= pagesFlat.Length-1) { ResetToBeginning(); return true; } IndexGlobal++; PageChanged?.Invoke(); CompileCurPage(); return false; } public void ResetToBeginning() { if (IndexGlobal != 0) { IndexGlobal = 0; PageChanged?.Invoke(); CompileCurPage(); } } private void CompileCurPage() { UpdateCurKeyPoints?.Invoke(null); curPageKeyPoints.Clear(); foreach (var keyEvent in CurPage.KeyPoints.OrderByDescending(x => x.AtWhatChar)) curPageKeyPoints.Push(keyEvent); UpdateUI(); } public void ReadUntilThisPoint(int indexTotal) { if (!curPageKeyPoints.Any()) return; var listPoppedKPs = new List<TtsKeyPoint>(); while (curPageKeyPoints.Any() && curPageKeyPoints.Peek() != null && indexTotal >= curPageKeyPoints.Peek().AtWhatChar) { var kp = curPageKeyPoints.Pop(); listPoppedKPs.Add(kp); } if (listPoppedKPs.Any()) { var curKeyPoints = listPoppedKPs.ToArray(); UpdateCurKeyPoints?.Invoke(curKeyPoints); UpdateUI(); Debug.WriteLine("------- keypoints -----------"); foreach (var kp in curKeyPoints) { Debug.WriteLine(kp.KeyPointType); Debug.WriteLine(kp.Token); } } } #region --------------------- bindable properties ----------------------- public double GlobalProgress { get { if (CurPage == null) return 0; return IndexGlobal + 1 - UtilsMath.XoY(curPageKeyPoints.Count + 1, CurPage.KeyPoints.Count + 1); } set { // TODO: navigation is broken! IndexGlobal = (int)value; } } public string ProgressLabel { get { if (CurPage == null) return string.Empty; var keyPointTally = CurPage.KeyPoints.Count - curPageKeyPoints.Count; return $"{IndexGlobal}:{keyPointTally}"; } } private void UpdateUI() { RaisePropertyChanged("GlobalProgress"); RaisePropertyChanged("ProgressLabel"); } #endregion } }
using System; using System.Security.Principal; namespace AbiokaScrum.Authentication { public interface ICustomPrincipal : IPrincipal { string UserName { get; set; } string Email { get; set; } Guid Id { get; set; } } }
using System; using InRule.Authoring.Commanding; using InRule.Authoring.Media; using InRule.Authoring.Windows; using InRule.Common.Utilities; using InRule.Repository; namespace InRule.Authoring.Extensions.RefreshTemplateEngine { public class Extension : ExtensionBase { private readonly VisualDelegateCommand _refreshTemplateEngineCommand; public Extension() : base("RefreshTemplateEngine", "Refreshes the template engine", new Guid("{D9DA19AA-2C3E-4510-921B-C87F4FA60BCE}")) { _refreshTemplateEngineCommand = new VisualDelegateCommand(RefreshTemplateEngine, "Refresh Template Engine", ImageFactory.GetImageAuthoringAssembly("/Images/Refresh32.png"), null, false); } public override void Enable() { var ruleAppGroup = IrAuthorShell.HomeTab.GetGroup("Rule Application"); ruleAppGroup.AddButton(_refreshTemplateEngineCommand); RuleApplicationService.RuleApplicationDefChanged += WhenRuleApplicationDefChanged; } private void WhenRuleApplicationDefChanged(object sender, EventArgs<RuleApplicationDef> e) { _refreshTemplateEngineCommand.IsEnabled = RuleApplicationService.RuleApplicationDef != null; } private void RefreshTemplateEngine(object obj) { var selectedDef = SelectionManager.SelectedItem; SelectionManager.SelectedItem = null; RuleApplicationService.ResetTemplateEngine(true); SelectionManager.SelectedItem = selectedDef; } } }
using System; using UnityEditor; using UnityEngine; namespace Daz3D { [CustomPropertyDrawer(typeof(DazBlendshape))] public class DazBlendshapeDrawer : PropertyDrawer { // Draw the property inside the given rect public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // Using BeginProperty / EndProperty on the parent property means that // prefab override logic works on the entire property. EditorGUI.BeginProperty(position, label, property); // Draw label //position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); // Don't make child fields be indented var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // Calculate rects position = new Rect(position.x, position.y, position.width - 70, position.height); var weight = property.FindPropertyRelative("weight"); EditorGUI.Slider(position, weight, 0, 100, label); position = new Rect(position.width + 30, position.y, 30, position.height); // Quick access buttons if (GUI.Button(position, new GUIContent("C", "[Clear] Sets the weight to 0."))) { weight.floatValue = 0f; GUI.changed = true; } position = new Rect(position.x + 30, position.y, 30, position.height); if (GUI.Button(position, new GUIContent("M", "[Middle|Max] Sets the weight to 100 or 50 (toggles)"))) { weight.floatValue = Math.Abs(weight.floatValue - 100) < 0.01 ? 50 : 100; GUI.changed = true; } // Set indent back to what it was EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestGame1 { class Block { private string texture; private bool solid; public string Texture { get { return texture; } set { texture = value; } } public bool Solid { get { return solid; } set { solid = value; } } static enum BlockType {} } }
using AppStore.Application.DataContracts.Users; using AppStore.Application.Services.Exceptions; using AppStore.Domain.Common; using AppStore.Domain.Users; using System; namespace AppStore.Application.Services.Users { public class UserAppService : IUserAppService { private readonly IUnitOfWork _unitOfWork; private readonly IUserRepository _userRepository; public UserAppService(IUnitOfWork unitOfWork, IUserRepository userRepository) { _unitOfWork = unitOfWork; _userRepository = userRepository; } public CreateUserResponse Create(CreateUserRequest request) { var response = new CreateUserResponse(); try { var user = request.User.ToDomain(_userRepository); _userRepository.Add(user); _unitOfWork.Commit(); response.User = user.ToDataContract(); } catch (Exception ex) { response.Exception = ex; } return response; } public GetUserResponse Get(int id) { var response = new GetUserResponse(); var user = _userRepository.Get(id); if (user == null) response.Exception = new ResourceNotFoundException("User not found."); response.User = user?.ToDataContract(); return response; } public GetUserCreditCardsResponse GetCreditCards(int userId) { var response = new GetUserCreditCardsResponse(); var user = _userRepository.Get(userId); if (user == null) response.Exception = new ResourceNotFoundException("User not found."); response.CreditCards = user?.CreditCards?.ToDataContract(); return response; } } }
using System; using App.Core.Helpers; using App.Core.Interfaces.Dto; using App.Core.Interfaces.Helpers; using App.Core.Interfaces.Managers; using App.Core.Interfaces.Providers; using App.Core.Interfaces.Services; using App.Core.Managers; using App.Core.Providers; using App.Core.Services; using App.Data; using App.Data.Models; using App.Web.AsyncApi; using App.Web.Filters; using App.Web.SignalR; using App.Web.Swagger.SchemaFilters; using AutoMapper; using Easy.MessageHub; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using SimpleInjector; using Swashbuckle.AspNetCore.Filters; using Swashbuckle.AspNetCore.Swagger; using Info = Swashbuckle.AspNetCore.Swagger.Info; using Profile = App.Data.Models.Profile; namespace App.Web { public class Startup { private readonly Container Container = new Container(); public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddMvc(options => { options.Filters.Add<ErrorHandlingFilter>(); options.Filters.Add<AuthFilter>(); options.Filters.Add<TransactionFilter>(); }) .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSpaStaticFiles(c => { c.RootPath = "Frontend/build"; }); services.AddSignalR(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Webchat API", Version = "v1" }); c.SchemaFilter<ResponseSchemaFilter>(); c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}/App.Core.Interfaces.xml"); c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}/App.Api.xml"); c.ExampleFilters(); }); services.AddAsyncApiGen(c => { c.AsyncApiDoc<NotificationsHub>("v1", new AsyncApi.Info { Title = "Webchat AsyncAPI", Version = "v1" }); c.SchemaFilter<ResponseSchemaFilter>(); }); services.AddSwaggerExamplesFromAssemblyOf<Startup>(); services.AddSimpleInjector(Container, options => { options.AddAspNetCore() .AddControllerActivation(); }); services.EnableSimpleInjectorCrossWiring(Container); services.UseSimpleInjectorAspNetRequestScoping(Container); services.AddSingleton(Container); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var mode = Environment.GetEnvironmentVariable("WEBCHAT_MODE"); app.UseSimpleInjector(Container, options => { options.UseLogging(); }); InitializeContainer(app); Container.Verify(); app.UseCors( options => options .AllowCredentials() .AllowAnyHeader() .AllowAnyMethod() .WithOrigins("http://localhost:3000", "http://localhost:5000") // TODO: Move to config or something. ); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Webchat")); app.UseAsyncApi(); // TODO: app.UseAsyncApiUI(c => c.AsyncApiEndpoint("/asyncapi/v1/asyncapi.json", "Webchat")); app.UseSignalR(routes => { routes.MapHub<NotificationsHub>("/api/v1/notifications"); }); app.UseSpa(spa => { spa.Options.SourcePath = "Frontend"; if (mode == "dev") { spa.UseReactDevelopmentServer(npmScript: "start"); } }); } private void InitializeContainer(IApplicationBuilder app) { // Integration. Container.AutoCrossWireAspNetComponents(app); // Message hub. Container.RegisterInstance<IMessageHub>(new MessageHub()); // Services. Container.Register<IAuthService, AuthService>(); Container.Register<IMessageService, MessageService>(); Container.Register<IProfileService, ProfileService>(); // Managers. Container.Register<IUserManager, UserManager>(); Container.Register<IProfileManager, ProfileManager>(); Container.Register<ISessionManager, SessionManager>(); Container.Register<IMessageManager, MessageManager>(); Container.Register<IChatManager, ChatManager>(); // Providers. Container.Register<IEntityProvider<User>, UserProvider>(); Container.Register<IEntityProvider<Session>, SessionProvider>(); Container.Register<IEntityProvider<Profile>, ProfileProvider>(); Container.Register<IEntityProvider<Message>, MessageProvider>(); Container.Register<IEntityProvider<Chat>, ChatProvider>(); // Database. Container.RegisterInstance<DbContext>(new AppDbContext()); // Helpers. Container.Register<ICryptoHelper, CryptoHelper>(); Container.Register<IDateTimeHelper, DateTimeHelper>(); // Mapper. Container.RegisterInstance(CreateMapper()); } private IMapper CreateMapper() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<User, UserDto>(); cfg.CreateMap<Session, SessionDto>() .ForMember(q => q.Token, q => q.MapFrom(w => w.SessionToken)) ; cfg.CreateMap<Message, MessageDto>(); cfg.CreateMap<Chat, ChatDto>(); }); config.CompileMappings(); config.AssertConfigurationIsValid(); return config.CreateMapper(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace DSD_Bot { class Program { static void Main(string[] args) { preguntar(); } static void preguntar() { Console.WriteLine("Ingrese su pregunta acerca de REST"); string pregunta = Console.ReadLine(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:53637/ServicePreguntar.svc/Preguntar/" + pregunta + ""); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string tramaJson = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); Console.WriteLine(tramaJson); HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("http://localhost:53637/ServiceRespuestas.svc/Preguntar/" + tramaJson + ""); request2.Method = "GET"; HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse(); StreamReader reader2 = new StreamReader(response2.GetResponseStream()); preguntar(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.Xml.Serialization; namespace KartSystem { public class GoodsWithoutMovingReportViewSettings : Entity { [XmlIgnore] public override string FriendlyName { get { return "Настройки отчета товары без движения"; } } public List<Warehouse> SelectedWarehouses; public List<GoodGroup> SelectedGoodGroups; public DateTime DateBegin; public DateTime DateEnd; public int SortType; public double Rest; public int Sell; } }
using System; using System.Drawing; using System.Windows.Forms; using Tulpep.NotificationWindow; using CapaDatos; using System.Data; namespace CapaUsuario.Pagos.Cuenta_bancaria_empresa { public partial class FrmCuentaBancaria : Form { float saldo; public FrmCuentaBancaria() { InitializeComponent(); } private void FrmCuentaBancaria_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; // ListarGrids(); ListarCuentas(); ListarOrdenes(); FrmCuentaBancaria_SizeChanged(sender, e); } private void ListarCuentas() { DgvListadoCuentas.DataSource = ExecuteQuery.SelectAll(205); } private void ListarOrdenes() { DgvOrdenesPago.DataSource = ExecuteQuery.SelectAll(204); } private void CrearCuentaButton_Click(object sender, EventArgs e) { HabilitarCampos(); } private void HabilitarCampos() { CbuTextBox.ReadOnly = false; SaldoTextBox.ReadOnly = false; GuardarDatosButton.Enabled = true; CancelarButton.Enabled = true; SaldoBusquedaTextBox.ReadOnly = true; CodCuentaBusquedaTextBox.ReadOnly = true; CbuTextBox.Focus(); materialTabControl1.SelectedTab = TabNueva; } private void DesabilitarCampos() { CbuTextBox.ReadOnly = true; SaldoTextBox.ReadOnly = true; GuardarDatosButton.Enabled = false; CancelarButton.Enabled = false; SaldoBusquedaTextBox.ReadOnly = false; CodCuentaBusquedaTextBox.ReadOnly = false; } private void CancelarButton_Click(object sender, EventArgs e) { DesabilitarCampos(); LimpiarCampos(); } private void LimpiarCampos() { CbuTextBox.Text = string.Empty; SaldoTextBox.Text = string.Empty; } private bool FijarseSiPuedeBorrarLaCuentaQueQuiereBorrarORealmenteNoPuedeHacerloPorDistintosMotivos() { if (Convert.ToInt32(DgvListadoCuentas.SelectedRows[0].Cells[2].Value) > 0) { MessageBox.Show("Debería darle verguenza... Intentar borrar una cuenta bancaria que tiene saldo... Mala persona"); return true; } else { DataTable dt = ExecuteQuery.SelectOne(205, (int)DgvListadoCuentas.SelectedRows[0].Cells[0].Value); if (dt.Rows.Count > 0) { MessageBox.Show("Amigo... La verdad es que la cuenta bancaria está asociada a una Orden de pago. Por favor no nos haga reir y no intente borrarla. Lo lamentamos mucho."); return true; } return false; } } private void BorrarCuentaButton_Click(object sender, EventArgs e) { if (DgvListadoCuentas.Rows.Count == 0) { MessageBox.Show("No hay cuentas corriente a borrar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (FijarseSiPuedeBorrarLaCuentaQueQuiereBorrarORealmenteNoPuedeHacerloPorDistintosMotivos()) { return; } var rta = MessageBox.Show("¿Está seguro de borrar la cuenta corriente?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; int codCuenta = (int)DgvListadoCuentas.SelectedRows[0].Cells[0].Value; // Logica de borrado de cuenta, comprobando antes que ésta no registre ningún importe y // no tenga asociación con una orden de pago ExecuteQuery.DeleteFrom(3, codCuenta); if (MessageException.message == "") { var popup1 = new PopupNotifier() { Image = Properties.Resources.info100, TitleText = "Mensaje", ContentText = "La cuenta corriente ha sido borrada con exito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F) }; popup1.Popup(); ListarCuentas(); } } private void GuardarDatosButton_Click(object sender, EventArgs e) { if (!ValidarCampos()) return; var rta = MessageBox.Show("¿Guardar datos?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; if (RevisarCBU()) { MessageBox.Show("La cuenta que quiere ingresar ya existe"); return; } var cbu = Convert.ToInt64( CbuTextBox.Text.Trim()); var saldo = Convert.ToInt32(SaldoTextBox.Text.Trim()); object[] parameters = { cbu, saldo }; // InsertCuentaBancaria(cbu, saldo); ExecuteQuery.InsertInto(22, parameters); if (MessageException.message == "") { var popup1 = new PopupNotifier() { Image = Properties.Resources.sql_success1, TitleText = "Mensaje", ContentText = "La cuenta corriente ha sido ingresada con exito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(8) }; popup1.Popup(); DesabilitarCampos(); ListarCuentas(); LimpiarCampos(); } } //REVISA SI EL CBU QUE SE QUIERE INGRESAR YA EXISTE private bool RevisarCBU() { foreach (DataGridViewRow row in DgvListadoCuentas.Rows) { if (Convert.ToInt64(row.Cells[1].Value) == Convert.ToInt64(CbuTextBox.Text)) { return true; } else { return false; } } return false; } private bool ValidarCampos() { if (CbuTextBox.Text.Trim() == string.Empty) { errorProvider1.SetError(CbuTextBox, "Ingrese un CBU"); CbuTextBox.Focus(); return false; } errorProvider1.Clear(); if (!Int64.TryParse(CbuTextBox.Text.Trim(), out Int64 cod)) { errorProvider1.SetError(CbuTextBox, "Ingrese un CBU válido"); CbuTextBox.Focus(); return false; } errorProvider1.Clear(); if (SaldoTextBox.Text.Trim() == string.Empty) { errorProvider1.SetError(DineroLabel, "Ingrese un saldo"); SaldoTextBox.Focus(); return false; } errorProvider1.Clear(); if (!int.TryParse(SaldoTextBox.Text.Trim(), out int val)) { errorProvider1.SetError(DineroLabel, "Ingrese un valor numérico"); SaldoTextBox.Focus(); return false; } errorProvider1.Clear(); return true; } private void CodCuentaBusquedaTextBox_TextChanged(object sender, EventArgs e) { if (CodCuentaBusquedaTextBox.Text.Trim() != string.Empty) { if (!int.TryParse(CodCuentaBusquedaTextBox.Text.Trim(), out int val)) { MessageBox.Show("Ingrese solo valores numéricos", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Warning); CodCuentaBusquedaTextBox.Text = string.Empty; return; } DgvListadoCuentas.DataSource = ExecuteQuery.SelectOne(206, val); } else { ListarCuentas(); } // Lógica de filtrado de cuentas por código de cuentas } private void FrmCuentaBancaria_SizeChanged(object sender, EventArgs e) { DgvListadoCuentas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DgvOrdenesPago.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } private void AsociarOrdenButton_Click(object sender, EventArgs e) { if (DgvOrdenesPago.Rows.Count == 0) { MessageBox.Show("No hay órdenes de pago", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (DgvListadoCuentas.Rows.Count == 0) { MessageBox.Show("No hay cuentas corriente para asociar a la orden de pago", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } float saldoEmpresa = Convert.ToSingle( DgvListadoCuentas.SelectedRows[0].Cells[2].Value); float importe = Convert.ToSingle(DgvOrdenesPago.SelectedRows[0].Cells[2].Value); if (saldoEmpresa < importe) { MessageBox.Show("Elija una cuenta cuyo saldo sea mayor o igual al importe de la factura asociada a la orden de pago", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int codCuenta = (int)DgvListadoCuentas.SelectedRows[0].Cells[0].Value; var rta = MessageBox.Show($"¿Esta seguro de asociar la orden de pago seleccionada a la cuenta con código {codCuenta}?" , "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (rta == DialogResult.No) return; int codOrdenPago = (int)DgvOrdenesPago.SelectedRows[0].Cells[0].Value; // Logica de modificacion de la orden de pago, asociandola con la cuenta de la empresa ExecuteQuery.UpdateOne(5, codOrdenPago, codCuenta); if (MessageException.message == "") { var popup1 = new PopupNotifier() { Image = Properties.Resources.orden_64, TitleText = "Mensaje", ContentText = "La orden de pago fue asociada a la cuenta de la empresa con éxito", ContentFont = new Font("Segoe UI Bold", 11F), TitleFont = new Font("Segoe UI Bold", 10F), ImagePadding = new Padding(8) }; popup1.Popup(); // ListarGrids(); ListarOrdenes(); } } private void SaldoBusquedaTextBox_TextChanged(object sender, EventArgs e) { if (SaldoBusquedaTextBox.Text.Trim() != string.Empty) { if (!int.TryParse(SaldoBusquedaTextBox.Text.Trim(), out int val)) { MessageBox.Show("Ingrese solo valores numéricos", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Warning); SaldoBusquedaTextBox.Text = string.Empty; return; } saldo = int.Parse(SaldoBusquedaTextBox.Text.Trim()); if (MenorRadioButton.Checked) { // Logica de filtrado de cuentas por saldos menor al ingresado DgvListadoCuentas.DataSource = ExecuteQuery.SelectOne(208, val); } else if (MayorRadioButton.Checked) { // Logica de filtrado de cuentas por saldos mayor al ingresado DgvListadoCuentas.DataSource = ExecuteQuery.SelectOne(207, val); } else { // Logica de filtrado de cuentas por saldos igual al ingresdo DgvListadoCuentas.DataSource = ExecuteQuery.SelectOne(209, val); } } else { // ListarTodasLasCuentas(); ListarCuentas(); } } private void MenorRadioButton_CheckedChanged(object sender, EventArgs e) { if (MenorRadioButton.Checked) { if(SaldoBusquedaTextBox.Text.Trim() != string.Empty) { saldo = float.Parse(SaldoBusquedaTextBox.Text.Trim()); // Logica de filtrado de cuentas por saldos menor al ingresado } else { // ListarTodasLasCuentas(); } } } private void MayorRadioButton_CheckedChanged(object sender, EventArgs e) { if (MayorRadioButton.Checked) { if (SaldoBusquedaTextBox.Text.Trim() != string.Empty) { saldo = float.Parse(SaldoBusquedaTextBox.Text.Trim()); // Logica de filtrado de cuentas por saldos mayor al ingresado } else { // ListarTodasLasCuentas(); } } } private void IgualRadioButton_CheckedChanged(object sender, EventArgs e) { if (IgualRadioButton.Checked) { if (SaldoBusquedaTextBox.Text.Trim() != string.Empty) { saldo = float.Parse(SaldoBusquedaTextBox.Text.Trim()); // Logica de filtrado de cuentas por saldos igual al ingresado } else { ListarCuentas(); } } } private void DgvListadoCuentas_SelectionChanged(object sender, EventArgs e) { string mensaje = ""; if (DgvListadoCuentas.SelectedRows.Count > 0) { mensaje += "Codigo: "; mensaje += DgvListadoCuentas.SelectedRows[0].Cells[0].Value.ToString(); mensaje += ", CBU: "; mensaje += DgvListadoCuentas.SelectedRows[0].Cells[1].Value.ToString(); mensaje += ", Saldo: "; mensaje += DgvListadoCuentas.SelectedRows[0].Cells[2].Value.ToString(); lblSelectedCount.Text = mensaje; } } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; /// <summary> /// Summary description for CheckLogin /// </summary> public class CheckLogin { public CheckLogin() { } public static void isLoggedIn(System.Web.SessionState.HttpSessionState session, System.Web.HttpResponse response) { if (session["cust_id"] == null || (long)session["cust_id"] <= 0) { response.Redirect("Login.aspx"); } } }
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.ContentSecurityPolicy { /// <summary> /// The worker-src directive specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts. /// </summary> public class WorkerSourceDirectiveBuilder : CspDirectiveBuilder { /// <summary> /// Initializes a new instance of the <see cref="WorkerSourceDirectiveBuilder"/> class. /// </summary> public WorkerSourceDirectiveBuilder() : base("worker-src") { } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; namespace SciVacancies.Captcha { /// <summary> /// CAPTCHA Image /// </summary> /// <seealso href="http://www.codinghorror.com">Original By Jeff Atwood</seealso> public class CaptchaImage { #region Static private static Color[] _colors; private static string[] _fonts; private static readonly Random _rand = new Random(); /// <summary> /// Initializes the <see cref="CaptchaImage"/> class. /// </summary> static CaptchaImage() { FontWarp = CaptchaConfiguration.FontFactor; BackgroundNoise = CaptchaConfiguration.BackgroundNoise; LineNoise = CaptchaConfiguration.LineNoise; } /// <summary> /// Initializes a new instance of the <see cref="CaptchaImage"/> class. /// </summary> public CaptchaImage(string text) { Width = 180; Height = 50; Text = text; } /// <summary> /// Gets the length of the text. /// </summary> /// <value>The length of the text.</value> public int TextLength { get { return Text.Length; } } /// <summary> /// Gets and sets amount of random warping to apply to the <see cref="CaptchaImage"/> instance. /// </summary> /// <value>The font warp.</value> public static FontWarpFactor FontWarp { get; set; } /// <summary> /// Gets and sets amount of background noise to apply to the <see cref="CaptchaImage"/> instance. /// </summary> /// <value>The background noise.</value> public static BackgroundNoiseLevel BackgroundNoise { get; set; } /// <summary> /// Gets or sets amount of line noise to apply to the <see cref="CaptchaImage"/> instance. /// </summary> /// <value>The line noise.</value> public static LineNoiseLevel LineNoise { get; set; } /// <summary> /// Gets or sets the cache time out. /// </summary> /// <value>The cache time out.</value> public static double CacheTimeOut { get; set; } #endregion private int _height; private int _width; #region Public Properties /// <summary> /// Gets the randomly generated Captcha text. /// </summary> /// <value>The text.</value> public string Text { get; private set; } /// <summary> /// Width of Captcha image to generate, in pixels /// </summary> /// <value>The width.</value> public int Width { get { return _width; } set { if ((value > 60)) _width = value; } } /// <summary> /// Height of Captcha image to generate, in pixels /// </summary> /// <value>The height.</value> public int Height { get { return _height; } set { if (value > 30) _height = value; } } #endregion /// <summary> /// Forces a new Captcha image to be generated using current property value settings. /// </summary> /// <returns></returns> public Bitmap RenderImage() { return GenerateImagePrivate(); } /// <summary> /// Returns a random font family from the font whitelist /// </summary> /// <returns></returns> private static string GetRandomFontFamily() { return FontFamilies[_rand.Next(0, FontFamilies.Length)]; } /// <summary> /// Randoms the color. /// </summary> /// <returns></returns> private static Color GetRandomColor() { return Colors[_rand.Next(0, Colors.Length)]; } /// <summary> /// Returns a random point within the specified x and y ranges /// </summary> /// <param name="xmin">The xmin.</param> /// <param name="xmax">The xmax.</param> /// <param name="ymin">The ymin.</param> /// <param name="ymax">The ymax.</param> /// <returns></returns> private PointF RandomPoint(int xmin, int xmax, int ymin, int ymax) { return new PointF(_rand.Next(xmin, xmax), _rand.Next(ymin, ymax)); } /// <summary> /// Returns a random point within the specified rectangle /// </summary> /// <param name="rect">The rect.</param> /// <returns></returns> private PointF RandomPoint(Rectangle rect) { return RandomPoint(rect.Left, rect.Width, rect.Top, rect.Bottom); } /// <summary> /// Returns a GraphicsPath containing the specified string and font /// </summary> /// <param name="s">The s.</param> /// <param name="f">The f.</param> /// <param name="r">The r.</param> /// <returns></returns> private static GraphicsPath TextPath(string s, Font f, Rectangle r) { var sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Near }; var gp = new GraphicsPath(); gp.AddString(s, f.FontFamily, (int)f.Style, f.Size, r, sf); return gp; } /// <summary> /// Returns the CAPTCHA font in an appropriate size /// </summary> /// <returns></returns> private Font GetFont() { string fname = GetRandomFontFamily(); int minFont = _height * CaptchaConfiguration.FontSizeMin / 100; int maxFont = _height * CaptchaConfiguration.FontSizeMax / 100; float fsize = _rand.Next(minFont, maxFont); return new Font(fname, fsize, _rand.Next(0, 2) == 1 ? FontStyle.Bold : FontStyle.Regular); } /// <summary> /// Renders the CAPTCHA image /// </summary> /// <returns></returns> private Bitmap GenerateImagePrivate() { var bmp = new Bitmap(_width, _height, PixelFormat.Format24bppRgb); using (Graphics gr = Graphics.FromImage(bmp)) { gr.SmoothingMode = SmoothingMode.AntiAlias; gr.Clear(Color.White); int charOffset = 0; double charWidth = _width / TextLength; var rect = new Rectangle(new Point(0, 0), bmp.Size); AddNoise(gr, rect); float angle = _rand.Next(CaptchaConfiguration.MinAngle, CaptchaConfiguration.MaxAngle); float angle2 = _rand.Next(CaptchaConfiguration.MinAngle, CaptchaConfiguration.MaxAngle); if (angle * angle2 > 0) angle2 = -angle2; angle2 = (angle2 - angle) / (TextLength - 1); AddLine(gr, rect); foreach (char c in Text) { // establish font and draw area // _rand.Next(CaptchaConfiguration.minAngle, CaptchaConfiguration.maxAngle); using (Font fnt = GetFont()) { using (Brush fontBrush = new SolidBrush(GetRandomColor())) { int charShift = _rand.Next(CaptchaConfiguration.MinShift, CaptchaConfiguration.MaxShift); int sX = Convert.ToInt32(charOffset * charWidth) - charShift; var rectChar = new Rectangle(sX, 0, Convert.ToInt32(charWidth), _height); // warp the character GraphicsPath gp = TextPath(c.ToString(CultureInfo.InvariantCulture), fnt, rectChar); int ssx = Convert.ToInt32(Math.Floor(WarpText(gp, rectChar, angle))); // draw the character gr.FillPath(fontBrush, gp); charOffset += 1; } } angle += angle2; } } return bmp; } /// <summary> /// Warp the provided text GraphicsPath by a variable amount /// </summary> /// <param name="textPath">The text path.</param> /// <param name="rect">The rect.</param> private float WarpText(GraphicsPath textPath, Rectangle rect, float angle) { float warpDivisor; float rangeModifier; switch (FontWarp) { case FontWarpFactor.None: goto default; case FontWarpFactor.Low: warpDivisor = 6F; rangeModifier = 1F; break; case FontWarpFactor.Medium: warpDivisor = 5F; rangeModifier = 1.3F; break; case FontWarpFactor.High: warpDivisor = 4.5F; rangeModifier = 1.4F; break; case FontWarpFactor.Extreme: warpDivisor = 4F; rangeModifier = 1.5F; break; default: return textPath.GetBounds().Width; } var rectF = new RectangleF(Convert.ToSingle(rect.Left), 0, Convert.ToSingle(rect.Width), rect.Height); int hrange = Convert.ToInt32(rect.Height / warpDivisor); int wrange = Convert.ToInt32(rect.Width / warpDivisor); int left = rect.Left + Convert.ToInt32(wrange * rangeModifier); int top = rect.Top - Convert.ToInt32(hrange * rangeModifier); int width = rect.Left + rect.Width + Convert.ToInt32(wrange * rangeModifier); int height = rect.Top + rect.Height + Convert.ToInt32(hrange * rangeModifier); if (left < 0) left = 0; if (top < 0) top = 0; if (width > Width) width = Width; if (height > Height) height = Height; PointF leftTop = RandomPoint(left, left + wrange, top, top + hrange); PointF rightTop = RandomPoint(width - wrange, width, top, top + hrange); PointF leftBottom = RandomPoint(left, left + wrange, height - hrange, height); PointF rightBottom = RandomPoint(width - wrange, width, height - hrange, height); var pointFs = new[] { leftTop, rightTop, leftBottom, rightBottom }; var matrix = new Matrix(); matrix.Translate(0, 0); var newPointF = new PointF(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)); matrix.RotateAt(angle, newPointF, MatrixOrder.Append); textPath.Warp(pointFs, rectF, matrix, WarpMode.Perspective, 1); return textPath.GetBounds().Width; } /// <summary> /// Add a variable level of graphic noise to the image /// </summary> /// <param name="g">The graphics.</param> /// <param name="rect">The rect.</param> private static void AddNoise(Graphics g, Rectangle rect) { int density; int size; int min; switch (BackgroundNoise) { case BackgroundNoiseLevel.None: goto default; case BackgroundNoiseLevel.Low: density = 30; size = 1; min = 1; break; case BackgroundNoiseLevel.Medium: density = 18; size = 2; min = 1; break; case BackgroundNoiseLevel.High: density = 16; size = 3; min = 1; break; case BackgroundNoiseLevel.Extreme: density = 14; size = 4; min = 1; break; default: return; } using (var br = new SolidBrush(GetRandomColor())) { int max = size * Convert.ToInt32(Math.Min(rect.Width, rect.Height) / 20); for (int i = 0; i <= Convert.ToInt32((rect.Width * rect.Height) / (density * max)); i++) g.FillEllipse(br, _rand.Next(rect.Width), _rand.Next(rect.Height), _rand.Next(min, max), _rand.Next(min, max)); } } /// <summary> /// Add variable level of curved lines to the image /// </summary> /// <param name="g">The graphics.</param> /// <param name="rect">The rect.</param> private void AddLine(Graphics g, Rectangle rect) { int length; float width; int linecount; switch (LineNoise) { case LineNoiseLevel.None: goto default; case LineNoiseLevel.Low: length = 1; width = 1; linecount = 1; break; case LineNoiseLevel.Medium: length = 2; width = 1; linecount = 2; break; case LineNoiseLevel.High: length = 2; width = 2; linecount = 3; break; case LineNoiseLevel.Extreme: length = 3; width = 3; linecount = 3; break; default: return; } var pf = new PointF[length + 1]; using (var p = new Pen(GetRandomColor(), width)) { for (int l = 1; l <= linecount; l++) { for (int i = 0; i <= length; i++) pf[i] = RandomPoint(rect); g.DrawCurve(p, pf, 0.0F); } } } private static string[] FontFamilies { get { if (_fonts == null) _fonts = CaptchaConfiguration.Fonts.Split(new char[] { ';' }); for (int i = 0; i < _fonts.Length; i++) { _fonts[i] = _fonts[i].Trim(); } return _fonts; } } private static Color[] Colors { get { if (_colors == null) { string[] scolors = CaptchaConfiguration.Colors.Split(new char[] { ';' }); _colors = new Color[scolors.Length]; for (int i = 0; i < scolors.Length; i++) { _colors[i] = GetColorFromString(scolors[i].Trim()); } } return _colors; } } private static Color GetColorFromString(string str) { if (string.IsNullOrEmpty(str)) throw new ArgumentException("str cannot be null or empty"); string[] scolors = str.Split(new char[] { '.' }); int red = Int32.Parse(scolors[0]); int green = Int32.Parse(scolors[1]); int blue = Int32.Parse(scolors[2]); return Color.FromArgb(red, green, blue); } } }
using System.Text; using Xunit; using Xunit.Abstractions; using ZKCloud.Helpers; namespace ZKCloud.Test.Helpers { /// <summary> /// 加密测试 /// </summary> public class EncryptTest { /// <summary> /// 测试初始化 /// </summary> public EncryptTest(ITestOutputHelper output) { _output = output; } /// <summary> /// 控制台输出 /// </summary> private readonly ITestOutputHelper _output; /// <summary> /// 测试Md5加密,返回16位结果 /// </summary> [Theory] [InlineData(null, "")] [InlineData("", "")] [InlineData(" ", "")] [InlineData("a", "C0F1B6A831C399E2")] [InlineData("中国", "CB143ACD6C929826")] public void TestMd5By16(string input, string result) { Assert.Equal(result, Encrypt.Md5By16(input)); } /// <summary> /// 测试Md5加密,返回32位结果 /// </summary> [Theory] [InlineData(null, "")] [InlineData("", "")] [InlineData(" ", "")] [InlineData("a", "0CC175B9C0F1B6A831C399E269772661")] [InlineData("中国", "C13DCEABCB143ACD6C9298265D618A9F")] public void TestMd5By32(string input, string result) { Assert.Equal(result, Encrypt.Md5By32(input)); } /// <summary> /// 测试DES加密验证 /// </summary> [Theory] [InlineData(null, "", "")] [InlineData("", "", "")] [InlineData("1", "", "")] [InlineData("1", "2", "")] public void TestDes_Validate(string input, string key, string result) { Assert.Equal(result, Encrypt.DesEncrypt(input, key, Encoding.UTF8)); Assert.Equal(result, Encrypt.DesDecrypt(input, key, Encoding.UTF8)); } /// <summary> /// 测试AES加密验证 /// </summary> [Theory] [InlineData(null, "", "")] [InlineData("", "", "")] [InlineData("1", "", "")] public void TestAes_Validate(string input, string key, string result) { Assert.Equal(result, Encrypt.AesEncrypt(input, key, Encoding.UTF8)); Assert.Equal(result, Encrypt.AesDecrypt(input, key, Encoding.UTF8)); } /// <summary> /// 测试Rsa签名验证 /// </summary> [Theory] [InlineData(null, "", "")] [InlineData("", "", "")] [InlineData("1", "", "")] public void TestRsaSign_Validate(string input, string key, string result) { Assert.Equal(result, Encrypt.AesEncrypt(input, key, Encoding.UTF8)); Assert.Equal(result, Encrypt.AesDecrypt(input, key, Encoding.UTF8)); } /// <summary> /// Rsa私钥 /// </summary> public const string RsaKey = "MIIEogIBAAKCAQEAuLbs8Jugb3qhzDu4rvMqQ8n1RS8TQCpJ3+Cg9qR/RgMcpBx8+0tUiYkfOOnzxGlBuIwGF7Hqyho2E1ICNoIeNY4GkUhxBk7/wz4M6/tbfKSmWp1PAi9gVOxT0Io1kNBAV0it+uiDA176qk2tIKPxQ7UBPRB6qVELHuM7Y9AVoOQbHe56+rEoTiRo13NTx01yg0xiZDzS5gAe/vu+rDAKBczm7ZQ0A4U//modw1/rV+GKiqJ8CIDHe7a8oW2rthDNTZ2C/CHug4QMEmhaNazvhzjyAE1rfvYLF0o92qEfkip3IQRJnFM4rrr9QvWjkSPO7sPu5rMyE4oeUZHJ8luhIwIDAQABAoIBAGE8ytaO1pJY+DvPZJWUpLcy5c8ZzQSGPoWAdrvgNK/ii31JEfIn4cTVTn5jilPnJRXFgJ+QpYzm53icP1X6gXSn44UvoXA0vidFzv+bProK4xfon+MCla+fCTBK0Y/+USChvhTLucxYf5SPd4grRaLi8lf3CNuBMl18OZN9wyUCicgcqOp2mwi46daqqqvNLJwzmiKVCMb82JKEVShkmRDp8+ST7imwtXypUzLnwRt00xobiO8Gi1B1jYE4xM0hmkVgEHHLMGUOlfECH/VcWFLRkwosM3P6PYwb/mfBiDrIzN2mbueKZxMZureUqll9uLWRwPEvTosqc+tl+a4jCkECgYEA784SWiUGoSBDuKu9wm2D5Almz0gZavMv15cYsTfbu6UzsLcIRLEqLG1Rv9bFnwR39Gd1Cl3JAKDlxhs8qxJhy5zi0TJUowF9/QAg7TgBkGZVU4p+6SKF4mPKKsC4tnpENM+FnylncpCjFs45+MNruUIq1OVkcfxGBaBxDB/SM6kCgYEAxTBozzAyfH+9HHNisCQ2x7iNWEuaydY39V8vAlGPRZSbbo8OoV3wlidZm2wAhRybUCg7wefdbMAJlH8Uq/HnwuwanEkMO4IH/t5WI/MKk4Wc55iwC1abqQZrAxNCfjG+fShr2AZHO1jTj4oyd3BuQFTQBdRtiB+g8ibrGYG1resCgYA/sJ2TL45JMQaLf6GQiAGliRGzL9UAYMJuIgU+3DUR61iFMLeTdvJahlZV+zbVexxY3zlonWwLLLCaIxXD4cfziiF7qkBsYrMRhP05w8w2i9dRrtDyHmcsr5A8Np9YZ7TByfQVR6vf86Y9IlynQ0/TDk3N6Xb6BySZzfj4XWM4sQKBgBKeW4cUme+/b++7xVm0UafR+SaZHOhp3abBcgLaCJkdSv/Jaiw6XnkPBhryu6nV5aRP6DSK3BFkoILw7Na/ZI63FFwlWY5U3MRn4eJLFHiRaRtFA3pOlywCeyAzNVgNAlt28ZfYH+munWs0NUepyf8xAuNKB32O3vd+TTx/TtQ5AoGAGgD1Rc2hTopjXI8P5K1wuEMrvUp2uo0apguHu2uzIUpFyQYgjp80hBsqDj6e22R0LDzQTPrj8i+KvLZ4Xu8iCCQrUMqOvE6oZbQ7ukJ+wZebLOnrI6/AzD/zza3LZMXt/lKFgbaiYFLOSPEwxg+VBxxe10aQ3ddp5NuBDjQXJW0="; /// <summary> /// 测试HmacSha256加密 /// </summary> [Theory] [InlineData(null, "")] [InlineData("", "")] [InlineData(" ", "")] [InlineData("a", "780c3db4ce3de5b9e55816fba98f590631d96c075271b26976238d5f4444219b")] [InlineData("中国", "dde7619d5465b73d94c18e6d979ab3dd9e478cb91b00d312ece776b282b7e0a9")] public void TestHmacSha256(string input, string result) { var key = "key"; _output.WriteLine($"input:{input},result:{Encrypt.HmacSha256(input, key)}"); Assert.Equal(result, Encrypt.HmacSha256(input, key)); } /// <summary> /// 测试AES加密 /// </summary> [Fact] public void TestAes_1() { var encode = Encrypt.AesEncrypt("a"); _output.WriteLine(encode); Assert.Equal("a", Encrypt.AesDecrypt(encode)); } /// <summary> /// 测试AES加密 /// </summary> [Fact] public void TestAes_2() { var encode = Encrypt.AesEncrypt("中国"); _output.WriteLine(encode); Assert.Equal("中国", Encrypt.AesDecrypt(encode)); } /// <summary> /// 测试DES加密 /// </summary> [Fact] public void TestDes_1() { const double value = 100.123; var encode = Encrypt.DesEncrypt(value); _output.WriteLine(encode); Assert.Equal(ZKCloud.Extensions.Extensions.SafeString(value), Encrypt.DesDecrypt(encode)); } /// <summary> /// 测试DES加密 /// </summary> [Fact] public void TestDes_2() { const string value2 = @"~!@#$%^&*()_+|,./;[]'{}""}{?>:<> \\ qwe测 *试rtyuiopadE15R3JrMnByS3c9sdfghjklzxcvbnm1234567890-=\"; var encode = Encrypt.DesEncrypt(value2); _output.WriteLine(encode); Assert.Equal(value2, Encrypt.DesDecrypt(encode)); } /// <summary> /// 测试Rsa2签名算法 /// </summary> [Fact] public void TestRsa2Sign() { const string value = "sign_type=RSA2"; const string result = "cFIjAWDAuNzRYzGOr65ux4e5GEOUvKUT0mLTpAJ89vem70IsdKCrs0IY2TANw3I6pBqdeG0Lz6kNeWHkurN+tj1+C/7ZpRgHIilV+sUU5Dv0Nw/cDVjvs4fyKJ4CEr8zcs1MB1ek0COuQ/kfHxbAr9sWE9a0nqxnZ/FnsDy5ogFP1LQStkms+e7Ph9CC/dyl6JRlpgZx7/NwnN9kF3zEnVwdPxxLq5as1EV7FmlpLcuI/tkCpL8G+vPJcB3xktM9EBBRMR+peDbusZ1fOAuxE7zbW3XVsgz7JzKUcHE5KNS3zzcov404zKT/8i/ezyCxRCWRHDy3O3zHg5bUUOluIQ=="; var encode = Encrypt.Rsa2Sign(value, RsaKey); _output.WriteLine(encode); Assert.Equal(result, encode); } /// <summary> /// 测试Rsa签名算法 /// </summary> [Fact] public void TestRsaSign() { const string value = "sign_type=RSA"; const string result = "b5jaOTwneLBLTXmemp2BvThFqpmgBsM60GX28MUERYx0vRGiWLw31sif7mlt6Sz063p9zo3quQ8hCwDy6Qssz7i50pqHaJuobpayQZJNHiYpzH07ZxkvJhqsG8IrXj4Q2rmyxpDayU3kg9lhT14VadnLflaypwTpvuy3nGpIoY62d5ciObwxJBDYeilIJag5iY/xTWqv1z4TAr5E6u4zo2aY4rGGKruIX4vsI58EmxzI82clz11uK964Eco/RXCZrha3Vthx5sa6yIPvr2xG95Va4UZglgX7c/wXyMyFp1t/MtKb/0IdQocuRtBmyJw5n0CdmTfw7WxcdNEecgwqjQ=="; var encode = Encrypt.RsaSign(value, RsaKey); _output.WriteLine(encode); Assert.Equal(result, encode); } } }
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverManager : MonoBehaviour { [SerializeField] protected float _delayToRedirect; public void Awake() { StartCoroutine(Redirect()); } private IEnumerator Redirect() { yield return new WaitForSeconds(_delayToRedirect); SceneManager.LoadSceneAsync("Menu"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.Networking; /// <summary> /// Diese Klasse dient zum Senden eines Requests zur Schnittstelle /// </summary> public class APIController : MonoBehaviour { /// <summary> /// Erhält die URL zum Endpunkt der Schinttstelle und sendet einen HTTP GET-Befehl zum übergebenen Endpunkt /// </summary> public IEnumerator GetRequest(string url, Action<UnityWebRequest> callback) { using (UnityWebRequest request = UnityWebRequest.Get(url)) { // Send the request and wait for a response yield return request.SendWebRequest(); callback(request); } } /// <summary> /// Wird aktuell nicht genutzt. /// Soll in späteren Verlauf änderungen am Protokoll durch ein HTTP POST-Befehl vornehmen /// </summary> public IEnumerator PostRequest(string url, Action<UnityWebRequest> callback) { using (UnityWebRequest request = UnityWebRequest.Get(url)) { // Send the request and wait for a response yield return request.SendWebRequest(); callback(request); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShieldBehavior : MonoBehaviour { GameObject parent; SoundManager soundManagerScript; float originalScaleX; float originalScaleY; float maxScaleX = 1.3f; float maxScaleY = 1.3f; float timeToDeletion = 0.35f; CircleCollider2D cc; // Use this for initialization void Start () { //GetComponent<SpriteRenderer>().color = new Color(0, 0, 0); soundManagerScript = GameObject.FindGameObjectWithTag("SoundManager").GetComponent<SoundManager>(); originalScaleX = transform.localScale.x; originalScaleY = transform.localScale.y; StartCoroutine(ExpandToFullScale()); cc = GetComponent<CircleCollider2D>(); Color decreasedOpacity = new Color(255, 255, 255); decreasedOpacity.a = 1f; GetComponent<SpriteRenderer>().color = decreasedOpacity; } IEnumerator ExpandToFullScale() { soundManagerScript.PlayShieldGainNoise(); float timeToExpand = 0.7f; float currentScaleIncrementerAmount = 0.02f; float timeToWait = timeToExpand * currentScaleIncrementerAmount; float currentScale = 0; //If currentScale = 0 , cirlce at original scale. If currentScale = 1 then the circle will be at maxScale while (currentScale < 1) { transform.localScale = new Vector2(Mathf.Lerp(originalScaleX, maxScaleX, currentScale), Mathf.Lerp(originalScaleY, maxScaleY, currentScale)); currentScale += currentScaleIncrementerAmount; yield return new WaitForSeconds(timeToWait); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag.Equals("ProjectileEnemy")) { StartCoroutine(DoCollisionWithProjectile(collision)); } if (collision.gameObject.tag.Equals("ExplosionEnemy") || collision.gameObject.tag.Equals("BossEnemy")) { StartCoroutine(DoCollisionWithExplosionOrBoss(collision)); } } private void OnTriggerStay2D(Collider2D collision) { OnTriggerEnter2D(collision); } public void SetParent(GameObject newParent) { parent = newParent; } IEnumerator DoCollisionWithProjectile(Collider2D collision) { cc.isTrigger = false; collision.isTrigger = false; GetComponent<SpriteRenderer>().color = new Color(255, 0, 0); Rigidbody2D colliderRB = collision.gameObject.GetComponent<Rigidbody2D>(); float colliderVelocityX = colliderRB.velocity.x; float colliderVelocityY = colliderRB.velocity.y; //Move back the object a bit so that it can collide with the shield. colliderRB.position = new Vector2(colliderRB.position.x - colliderVelocityX * (Time.deltaTime * 2f), colliderRB.position.y - colliderVelocityY * (Time.deltaTime * 2f)); collision.GetComponent<Projectile>().Deactivate(); yield return new WaitForSeconds(timeToDeletion); cc.isTrigger = true; //collision.isTrigger = true; parent.GetComponent<PlayerController>().RemoveShield(); Destroy(gameObject); } IEnumerator DoCollisionWithExplosionOrBoss(Collider2D collision) { cc.isTrigger = false; GetComponent<SpriteRenderer>().color = new Color(255, 0, 0); //collision.gameObject.tag = "Untagged"; yield return new WaitForSeconds(timeToDeletion); cc.isTrigger = true; parent.GetComponent<PlayerController>().RemoveShield(); Destroy(gameObject); } }
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; using Pe.Stracon.SGC.Cross.Core.Base; using System; namespace Pe.Stracon.SGC.Infraestructura.Core.Base { /// <summary> /// Repository contract: for persisting an entity. /// </summary> /// <remarks> /// Creación: GMD 22122014 <br /> /// Modificación: <br /> /// </remarks> public interface IComandRepository<T> : IDisposable where T : Entity { /// <summary> /// Save an entity. /// </summary> /// <param name="obj">The entity to save.</param> void Insertar(T entity, IEntornoActualAplicacion entorno = null); /// <summary> /// Update an entity. /// </summary> /// <param name="obj">The entity to update.</param> void Editar(T entity, IEntornoActualAplicacion entorno = null); /// <summary> /// Delete an entity /// </summary> /// <param name="obj">The entity to update.</param> void Eliminar(params object[] llaves); /// <summary> /// Delete an entity /// </summary> /// <param name="entorno">Environment with the session</param> /// <param name="llaves">Code of The entity to delete.</param> void EliminarEntorno(IEntornoActualAplicacion entorno, params object[] llaves); /// <summary> /// Get Entity by primary key /// </summary> /// <param name="id"></param> /// <returns></returns> T GetById(params object[] id); /// <summary> /// Save all changes /// </summary> /// <returns></returns> int GuardarCambios(); } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UI; public class CreateProfile : MonoBehaviour { [SerializeField] InputField userNameInput; [SerializeField] GameObject createProfileObject; [SerializeField] GameObject profileButton; [SerializeField] Transform profileContent; [SerializeField] StatsMenu statsMenu; private GameSaveManager saveManager; // Start is called before the first frame update void Start() { saveManager = GameObject.FindGameObjectWithTag("SaveManager").GetComponent<GameSaveManager>(); ShowProfiles(); if (NoProfiles()) { createProfileObject.SetActive(true); } else { createProfileObject.SetActive(false); } } public void CreateUser() { if (userNameInput.text != "" && !PlayerExists(userNameInput.text)) { saveManager.inventory.CreateNewUser(userNameInput.text); saveManager.SaveGame(); ShowProfiles(); createProfileObject.SetActive(false); } } private bool PlayerExists(string playerName) { DirectoryInfo dir = new DirectoryInfo(saveManager.saveFolder); FileInfo[] info = dir.GetFiles("*.save"); foreach (FileInfo f in info) { Debug.Log(f.Name); if (f.Name.Equals(playerName + ".save")) { return true; } } return false; } private bool NoProfiles() { DirectoryInfo dir = new DirectoryInfo(saveManager.saveFolder); FileInfo[] info = dir.GetFiles("*.save"); foreach (FileInfo f in info) { return false; } return true; } private void ShowProfiles() { DirectoryInfo dir = new DirectoryInfo(saveManager.saveFolder); FileInfo[] info = dir.GetFiles("*.save"); foreach (Transform child in profileContent.transform) { GameObject.Destroy(child.gameObject); } foreach (FileInfo f in info) { GameObject button = Instantiate(profileButton, profileContent.position, Quaternion.identity, profileContent); button.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(f.Name); button.GetComponent<Button>().onClick.AddListener(delegate { saveManager.LoadGame(f.Name); }); button.GetComponent<Button>().onClick.AddListener(statsMenu.UpdateText); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using WindowsFormsApplication2; using System.IO; public partial class right3 : System.Web.UI.Page { SqlConnection mycn; //SQLServer数据库对象 SqlServerDataBase sdb = new SqlServerDataBase(); string mycns = ConfigurationSettings.AppSettings["connString"]; protected void Page_Load(object sender, EventArgs e) { if (Session["user"] == null) { Response.Write("<script>alert('账号已失效,请重新登录!');top.location.href = 'login.aspx';</script>"); return; } if (Session["user"].ToString() == "总经理") { edi.Visible = false; A22.Visible = false; A33.Visible = false; A44.Visible = false; A55.Visible = false; } string uuuuu = Session["user"].ToString(); Session["id"] = "y"; img_nodigit.Visible = false; if (!Page.IsPostBack) { using (SqlConnection mycn = new SqlConnection(mycns)) { using (SqlCommand sqlcmm = mycn.CreateCommand()) { try { mycn.Open(); if (Session["user"].ToString() == "用户") { sqlcmm.CommandText = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt,zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sqlcmm.CommandText = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' "; } else { sqlcmm.CommandText = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理' "; } } DataTable dt = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm); adapter.Fill(dt); if (dt.Rows.Count > 0) //当数据库有数据的时候绑定数据 { this.GridView1.DataSource = dt; this.GridView1.DataBind(); bindgrid(); } else { img_nodigit.Visible = true; dcW.Enabled = false; this.dcW.ForeColor = System.Drawing.Color.Gray; dcE.Enabled = false; this.dcE.ForeColor = System.Drawing.Color.Gray; bj.Enabled = false; this.bj.ForeColor = System.Drawing.Color.Gray; //sc.Enabled = false; //this.sc.ForeColor = System.Drawing.Color.Gray; cx.Enabled = false; this.cx.ForeColor = System.Drawing.Color.Gray; } } catch { Response.Write("<script>alert('账号已失效,请重新登录!');top.location.href = 'login.aspx';</script>"); } finally { mycn.Close(); } } } if (Session["managertype"] == "董事长") { Ul1.Visible = false; } if (Session["succes"] == "y") { Response.Write("<script>alert('转化成功!')</script>"); Session["succes"] = "n"; } } } //判断是否选中一行 bool panduanxuanzhong() { int num = 0; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; } else { continue; } } if (num >= 1) { string ID = ""; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { return true; } } } else { Response.Write("<script>alert('请至少选中一行!')</script>"); return false; } return false; } void bindgrid() { //查询数据库 string sss = ""; string uuuuu = Session["user"].ToString(); if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' "; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理' "; } } DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds, "tabenterprise"); } SqlServerDataBase sdb = new SqlServerDataBase(); DataSet ds2 = new DataSet(); DataSet ds3 = new DataSet(); foreach (DataRow row in ds.Tables[0].Rows) { ds2 = sdb.Select("select zjxm from zjk where zjID='" + row[7].ToString() + "'", null); ds3 = sdb.Select("select zjxm from zjk where zjID='" + row[8].ToString() + "'", null); string zjxm2 = "", zjxm3 = ""; if (row[7].ToString() != "") { zjxm2 = ds2.Tables[0].Rows[0][0].ToString().Trim(); } if (row[8].ToString() != "") { zjxm3 = ds3.Tables[0].Rows[0][0].ToString().Trim(); } row[7] = zjxm2; row[8] = zjxm3; } if (ds.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp = ds.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); mycn.Close(); } protected void gridList_RowDataBound(object sender, GridViewRowEventArgs e) { string gridViewHeight = ConfigurationSettings.AppSettings["gridViewHeight"]; GridView1.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; //如果是绑定数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //鼠标经过时,行背景色变 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#e5ebee'"); //鼠标移出时,行背景色变 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); // 控制每一行的高度 e.Row.Attributes.Add("style", gridViewHeight); // 删除提示 //sc.Attributes.Add("onclick", "javascript:if(confirm('确定要删除吗?')){}else{return false;}"); // 双击弹出新页面,并传递id值 int row_index = e.Row.RowIndex; string ID = GridView1.DataKeys[row_index].Value.ToString(); Session["xmkbianji"] = "y"; e.Row.Attributes.Add("ondblclick", "newwin=window.open('xmkxiugai.aspx?ID=" + ID + "','newwin')"); } } // 导出Word protected void dcW_Click(object sender, EventArgs e) { int num = 0; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; } else { continue; } } if (num == 1) { string ID = ""; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { ID = GridView1.DataKeys[i].Value.ToString(); XmkDaochu xmk = new XmkDaochu(); try { xmk.SaveToWord(ID, HttpContext.Current.Server.MapPath("~/Buffer/项目表.docx")); string filePath = "~/Buffer/项目表.docx"; ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptName", "window.open('DownloadFile.aspx?path=" + filePath + "','_blank');", true); } catch { } } } } else { Response.Write("<script>alert('请选中一行!')</script>"); } } // 导出Excel protected void dcE_Click(object sender, EventArgs e) { int num = 0; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; } else { continue; } } if (num > 0) { DataTable dt = new DataTable(); mycn = new SqlConnection(mycns); SqlCommand sqlcom; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { string sqlstr = "select xmID as 项目编号, xmmc as 项目名称, fzr as 负责人, lxfs as 联系方式, xmqx as 项目期限 from xmk where xmID='" + GridView1.DataKeys[i].Value + "'"; sqlcom = new SqlCommand(sqlstr, mycn); mycn.Open(); SqlDataAdapter adp = new SqlDataAdapter(sqlcom); adp.Fill(dt); mycn.Close(); } } DataToExcel dte = new DataToExcel(); try { string strFilePath = Server.MapPath("~/Buffer/项目表格.xls"); if (File.Exists(strFilePath)) { File.Delete(strFilePath); } dte.DataSetToExcel(dt, HttpContext.Current.Server.MapPath("~/Buffer/项目表格.xls")); string filePath = "~/Buffer/项目表格.xls"; ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptName", "window.open('DownloadFile.aspx?path=" + filePath + "','_blank');", true); } catch { } } else { Response.Write("<script>alert('请至少选中一行!')</script>"); } } // 关闭导出框 protected void closed_Click(object sender, EventArgs e) { Response.Redirect("right3.aspx"); } // 新增 protected void btn_add(object sender, EventArgs e) { Response.Write("<script>window.open('xmkxinzeng.aspx')</script>"); } // 删除 protected void btn_del(object sender, EventArgs e) { if (panduanxuanzhong()) { mycn = new SqlConnection(mycns); SqlCommand sqlcom; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { string sqlstr = "delete from xmk where xmID='" + GridView1.DataKeys[i].Value + "'"; sqlcom = new SqlCommand(sqlstr, mycn); mycn.Open(); sqlcom.ExecuteNonQuery(); mycn.Close(); } } bindgrid(); Response.Redirect("right3.aspx"); } } // 编辑 protected void btn_edi(object sender, EventArgs e) { Session["xmkbianji"] = "y"; int num = 0; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; } else { continue; } } if (num == 1) { string ID = ""; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { ID = GridView1.DataKeys[i].Value.ToString(); //Convert.ToInt16(ID); Response.Write("<script>window.open('xmkxiugai.aspx?ID=" + ID + "','_blank')</script>"); } } } else { Response.Write("<script>alert('请选中一行!')</script>"); } } protected void zjsh(object sender, EventArgs e) { DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select zjID,zjxm,gzdw,zjcs,xueke2.value from zjk left outer join xueke2 on zjk.xcsly1 = xueke2.id where zjlx like '%d%' and zjxm like '%" + zjname.Text.Trim() + "%'", sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp; temp = ds.Tables[0].Rows[i]["value"].ToString().Trim(); temp = temp.Replace("--请选择--", " "); ds.Tables[0].Rows[i]["value"] = temp; } GridView_Specialist.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView_Specialist.DataBind(); string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } //查询 protected void sshs(object sender, EventArgs e) { //查询数据库 //string sqlconnstr = ConfigurationManager.ConnectionStrings["server=LAPTOP-JFN4NKUE;database=teaching;User ID=zl;pwd=123456;Trusted_Connection=no"].ConnectionString; // Label1.Text = "查找成功"; DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); //mycn.Open(); string userss = ss_text.Text.Trim().ToString(); String cxtj = DropDownList1.SelectedItem.Text; if (cxtj == "项目名称") { cxtj = "xmmc"; } else if (cxtj == "负责人") { cxtj = "fzr"; } using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); string sss = ""; if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%'"; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理'"; } } SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } if (ds.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp = ds.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } SqlServerDataBase sdb = new SqlServerDataBase(); DataSet ds2 = new DataSet(); DataSet ds3 = new DataSet(); foreach (DataRow row in ds.Tables[0].Rows) { ds2 = sdb.Select("select zjxm from zjk where zjID='" + row[7].ToString() + "'", null); ds3 = sdb.Select("select zjxm from zjk where zjID='" + row[8].ToString() + "'", null); string zjxm2 = "", zjxm3 = ""; if (row[7].ToString() != "") { zjxm2 = ds2.Tables[0].Rows[0][0].ToString().Trim(); } if (row[8].ToString() != "") { zjxm3 = ds3.Tables[0].Rows[0][0].ToString().Trim(); } row[7] = zjxm2; row[8] = zjxm3; } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; bindgrid(); //数据绑定 } protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e) { // Retrieve the pager row. GridViewRow pagerRow = GridView1.BottomPagerRow; // Retrieve the PageDropDownList DropDownList from the bottom pager row. DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList"); // Set the PageIndex property to display that page selected by the user. GridView1.PageIndex = pageList.SelectedIndex; bindgrid(); //数据绑定 } protected void GridView1_DataBound(Object sender, EventArgs e) { GridView1.BottomPagerRow.Visible = true;//只有一页数据的时候也再下面显示pagerrow,需要top的再加Top // Retrieve the pager row. GridViewRow pagerRow = GridView1.BottomPagerRow; // Retrieve the DropDownList and Label controls from the row. DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList"); Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel"); if (pageList != null) { // Create the values for the DropDownList control based on // the total number of pages required to display the data // source. for (int i = 0; i < GridView1.PageCount; i++) { // Create a ListItem object to represent a page. int pageNumber = i + 1; ListItem item = new ListItem(pageNumber.ToString()); // If the ListItem object matches the currently selected // page, flag the ListItem object as being selected. Because // the DropDownList control is recreated each time the pager // row gets created, this will persist the selected item in // the DropDownList control. if (i == GridView1.PageIndex) { item.Selected = true; } // Add the ListItem object to the Items collection of the // DropDownList. pageList.Items.Add(item); } } if (pageLabel != null) { // Calculate the current page number. int currentPage = GridView1.PageIndex + 1; // Update the Label control with the current page information. pageLabel.Text = "Page " + currentPage.ToString() + " of " + GridView1.PageCount.ToString(); } } //protected void countDropDownList() //{ // GridViewRow pagerRow = GridView1.BottomPagerRow; // DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList"); // countList.Items.Add(new ListItem("默认")); // countList.Items.Add(new ListItem("10")); // countList.Items.Add(new ListItem("20")); // countList.Items.Add(new ListItem("全部")); // switch (GridView1.PageSize) // { // case 7: // countList.Text = "默认"; // break; // case 10: // countList.Text = "10"; // break; // case 20: // countList.Text = "20"; // break; // default: // countList.Text = "全部"; // break; // } //} protected void CountDropDownList_SelectedIndexChanged(Object sender, EventArgs e) { GridViewRow pagerRow = GridView1.BottomPagerRow; DropDownList countList = (DropDownList)pagerRow.Cells[0].FindControl("CountDropDownList"); string selectText = countList.SelectedItem.Text; switch (selectText) { case "默认": { GridView1.PageSize = 7; } break; case "10": { GridView1.PageSize = 10; } break; case "20": { GridView1.PageSize = 20; } break; case "全部": { mycn = new SqlConnection(mycns); SqlCommand mycmm = new SqlCommand("select count(*) from xmk", mycn); mycn.Open(); int count = (int)mycmm.ExecuteScalar(); mycn.Close(); GridView1.PageSize = count; } break; default: break; } bindgrid(); } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList1.SelectedItem.Text.Trim() == "项目类别") { ss_text.Visible = false; ss_droplist.Visible = false; DropDownList2.Visible = true; btss.Visible = false; } else if (DropDownList1.SelectedItem.Text.Trim() == "审核状态") { ss_text.Visible = false; DropDownList2.Visible = false; ss_droplist.Visible = true; btss.Visible = false; } else { ss_text.Visible = true; ss_droplist.Visible = false; DropDownList2.Visible = false; btss.Visible = true; } } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); //mycn.Open(); string userss; if (DropDownList2.SelectedValue == "ss") { userss = ""; } else { userss = DropDownList2.SelectedValue.Trim(); } String cxtj = DropDownList1.SelectedValue.Trim(); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); string sss = ""; if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and " + cxtj + " like '%" + userss + "%'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%'"; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理'"; } } SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); DataSet ds1 = new DataSet(); SqlConnection mycn1 = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { if (userss == "") { mycn1.Open(); SqlDataAdapter sqld = new SqlDataAdapter("select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交'", sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } else { mycn1.Open(); string sss = ""; if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and " + cxtj + " like '%" + userss + "%'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%'"; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理'"; } } SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } } if (ds1.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds1.Tables[0].Rows.Count; i++) { string temp = ds1.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds1.Tables[0].Rows[i]["xmlb"] = s2; } this.GridView1.DataSource = ds1.Tables[0]; this.GridView1.DataBind(); } else { img_nodigit.Visible = true; } //为控件绑定数据 GridView1.DataSource = ds1.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } void Specialist_BindGrid() { //查询数据库 DataSet ds = new DataSet(); ds = sdb.Select("select zjID,zjxm,gzdw,zjcs,xueke2.value from zjk left outer join xueke2 on zjk.xcsly1 = xueke2.id where zjlx like '%d%'", null); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string temp; temp = ds.Tables[0].Rows[i]["value"].ToString().Trim(); temp = temp.Replace("--请选择--", " "); ds.Tables[0].Rows[i]["value"] = temp; } //为控件绑定数据 GridView_Specialist.DataSource = ds.Tables[0].DefaultView; GridView_Specialist.DataBind(); } protected void Specialist_PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e) { GridViewRow pagerRow = GridView_Specialist.BottomPagerRow; DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("Specialist_PageDropDownList"); GridView_Specialist.PageIndex = pageList.SelectedIndex; Specialist_BindGrid(); //数据绑定 } protected void GridView_Specialist_RowDataBound(object sender, GridViewRowEventArgs e) { string gridViewHeight = ConfigurationSettings.AppSettings["gridViewHeight"]; GridView_Specialist.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; //如果是绑定数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //鼠标经过时,行背景色变 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#e5ebee'"); //鼠标移出时,行背景色变 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); // 控制每一行的高度 e.Row.Attributes.Add("style", gridViewHeight); } } protected void zjsp_Click(object sender, EventArgs e) { //清空专家选择栏 zj1.Text = ""; zj2.Text = ""; zj3.Text = ""; zj11.Text = ""; zj22.Text = ""; zj33.Text = ""; zj1id.Text = ""; zj2id.Text = ""; zj3id.Text = ""; int num = 0, shifou = 1; string mycns = ConfigurationSettings.AppSettings["connString"]; SqlConnection mycn = new SqlConnection(mycns); mycn.Open(); for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; string mycm1 = "select cstg,zjover,kjytg from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and tj = 1 and xmk.spzt != '未提交'"; SqlCommand mycmd1 = new SqlCommand(mycm1, mycn); SqlDataReader myrd1; myrd1 = mycmd1.ExecuteReader(); myrd1.Read(); string tests = myrd1[0].ToString().Trim(); string tests2 = myrd1[1].ToString().Trim(); string tests3 = myrd1[2].ToString().Trim(); if (tests == "1") { myrd1.Close(); } else { myrd1.Close(); Response.Write("<script>alert('存在初审未通过项目,提交操作取消')</script>"); shifou = 0; } if (tests2 == "1" || tests3 == "1") { Response.Write("<script>alert('项目已完成专家审核,提交操作取消')</script>"); shifou = 0; } } else { continue; } } if (num >= 1) { //LstBxZj.Items.Clear(); if (shifou == 1) { DataSet ds = new DataSet(); ds = sdb.Select("select zjID,zjxm,gzdw,zjcs,xueke2.value from zjk left outer join xueke2 on zjk.xcsly1 = xueke2.id where zjlx like '%d%'", null); if (ds.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { this.GridView_Specialist.DataSource = ds.Tables[0]; this.GridView_Specialist.DataBind(); Specialist_BindGrid(); string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } else { Response.Write("<script>alert('专家库为空!')</script>"); } } } else { Response.Write("<script>alert('请选中一行!')</script>"); } mycn.Close(); } protected void onguanbi(object sender, EventArgs e) { bindgrid(); } protected void zjlsp_Click(object sender, EventArgs e) { int num = 0; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { num++; } else { continue; } } if (num >= 1) { string sl = "<script language='javascript' type='text/javascript'> msgbox2(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox2", sl); } else { Response.Write("<script>alert('请选中一行!')</script>"); } } protected void zjqx_Click(object sender, EventArgs e) { //if (zj3.Text.Trim() != "") //{ // zj3.Text = ""; // zj33.Text = ""; // zj3id.Text = ""; //} //else if (zj2.Text.Trim() != "") //{ // zj2.Text = ""; // zj22.Text = ""; // zj2id.Text = ""; //} //else if (zj1.Text.Trim() != "") //{ // zj1.Text = ""; // zj11.Text = ""; // zj1id.Text = ""; //} //string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; //Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } protected void onbtn_zjdelete2() { string p1, p2, p3; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { p1 = ""; p2 = ""; p3 = ""; if (cbox.Checked == true) { DataSet ds = new DataSet(); ds = sdb.Select("select * from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1 ", null); p1 = ds.Tables[0].Rows[0]["spzjID"].ToString().Trim(); p2 = ds.Tables[0].Rows[0]["spzjID2"].ToString().Trim(); p3 = ds.Tables[0].Rows[0]["spzjID3"].ToString().Trim(); if (p1 != zj1id.Text.Trim()) { sdb.Update("update xmk set spzjID = NULL,zjyj = NUll,zjshzt = NULL , zjtg = NULL where xmID = '" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1 ", null); } if (p2 != zj2id.Text.Trim()) { sdb.Update("update xmk set spzjID2 = NULL, zjyj2 = NUll,zjshzt2 = NULL, zjtg2 = NULL where xmID = '" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1 ", null); } if (p3 != zj3id.Text.Trim()) { sdb.Update("update xmk set spzjID3 = NULL, zjyj3 = NUll ,zjshzt3 = NULL,zjtg3 = NULL where xmID = '" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1 ", null); } } } } } protected void zjtj_Click(object sender, EventArgs e) { int num = 0; for (int i = 0; i <= GridView_Specialist.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView_Specialist.Rows[i].FindControl("CheckBox2"); if (cbox.Checked == true) { num++; } else { continue; } } if (num <= 3 && num > 0) { string name = "", id = ""; for (int i = 0; i <= GridView_Specialist.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView_Specialist.Rows[i].FindControl("CheckBox2"); if (cbox.Checked == true) { name = GridView_Specialist.Rows[i].Cells[2].Text; id = GridView_Specialist.DataKeys[i].Value.ToString(); if (zj1.Text.Trim() == "") { zj1.Text = name; zj11.Text = name; zj1id.Text = id; } else if (zj2.Text.Trim() == "") { if (zj1.Text.Trim() == name) { //Response.Write("<script>alert('此专家已被选择,请选择其它专家!')</script>"); ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "alert", "alert('此专家已被选择,请选择其它专家!')", true); break; } zj2.Text = name; zj22.Text = name; zj2id.Text = id; } else if (zj3.Text.Trim() == "") { if (zj1.Text.Trim() == name || zj2.Text.Trim() == name) { //Response.Write("<script>alert('此专家已被选择,请选择其它专家!')</script>"); ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "alert", "alert('此专家已被选择,请选择其它专家!')", true); break; } zj3.Text = name; zj33.Text = name; zj3id.Text = id; } else { //Response.Write("<script>alert('已分配足够专家,若要取消,请点取消!')</script>"); ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "alert", "alert('已分配足够专家!')", true); break; } } } for (int i = 0; i <= GridView_Specialist.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView_Specialist.Rows[i].FindControl("CheckBox2"); cbox.Checked = false; } } else { //Response.Write("<script>alert('请请选择1-3人!')</script>"); ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "alert", "alert('请选择1-3人!')", true); } string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } protected void zjqr_Click(object sender, EventArgs e) { string mycns = ConfigurationSettings.AppSettings["connString"]; SqlConnection mycn = new SqlConnection(mycns); mycn.Open(); try { string ID = ""; string sqlstr1 = ""; onbtn_zjdelete2(); for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { ID = GridView1.DataKeys[i].Value.ToString(); if (zj3.Text.Trim() == "" && zj1.Text.Trim() == "" && zj2.Text.Trim() == "") { string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } else if (zj3.Text.Trim() != "") { string shzt = "未审核", shzt2 = "未审核", shzt3 = "未审核"; string p1 = "", p2 = "", p3 = ""; DataSet ds = new DataSet(); ds = sdb.Select("select * from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and spzt != '立项'", null); p1 = ds.Tables[0].Rows[0]["spzjID"].ToString().Trim(); p2 = ds.Tables[0].Rows[0]["spzjID2"].ToString().Trim(); p3 = ds.Tables[0].Rows[0]["spzjID3"].ToString().Trim(); if (p1 == zj1id.Text.Trim()) { shzt = ds.Tables[0].Rows[0]["zjshzt"].ToString().Trim(); } if (p2 == zj2id.Text.Trim()) { shzt2 = ds.Tables[0].Rows[0]["zjshzt2"].ToString().Trim(); } if (p3 == zj3id.Text.Trim()) { shzt3 = ds.Tables[0].Rows[0]["zjshzt3"].ToString().Trim(); } sqlstr1 = "update xmk set spzt='专家审核未完成',zjshzt = '" + shzt + "',zjshzt2 = '" + shzt2 + "',zjshzt3 = '" + shzt3 + "' where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and spzt != '立项'"; string mycm1 = "update xmk set spzjID = '" + zj1id.Text.Trim() + "',zjgs = '" + 3 + "' where xmID = '" + ID + "' and tj = 1 and spzt != '立项'"; SqlCommand mycmd1 = new SqlCommand(mycm1, mycn); mycmd1.ExecuteNonQuery(); string mycm2 = "update xmk set spzjID2 = '" + zj2id.Text.Trim() + "',zjgs = '" + 3 + "' where xmID = '" + ID + "' and tj = 1 and spzt != '立项'"; SqlCommand mycmd2 = new SqlCommand(mycm2, mycn); mycmd2.ExecuteNonQuery(); string mycm3 = "update xmk set spzjID3 = '" + zj3id.Text.Trim() + "',zjgs = '" + 3 + "' where xmID = '" + ID + "' and tj = 1 and spzt != '立项'"; SqlCommand mycmd3 = new SqlCommand(mycm3, mycn); mycmd3.ExecuteNonQuery(); SqlCommand sqlcom1 = new SqlCommand(mycm1, mycn); sqlcom1 = new SqlCommand(sqlstr1, mycn); sqlcom1.ExecuteNonQuery(); } else if (zj2.Text.Trim() != "") { string shzt = "未审核", shzt2 = "未审核"; string p1 = "", p2 = ""; DataSet ds = new DataSet(); ds = sdb.Select("select * from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and spzt != '立项'", null); p1 = ds.Tables[0].Rows[0]["spzjID"].ToString().Trim(); p2 = ds.Tables[0].Rows[0]["spzjID2"].ToString().Trim(); if (p1 == zj1id.Text.Trim()) { shzt = ds.Tables[0].Rows[0]["zjshzt"].ToString().Trim(); } if (p2 == zj2id.Text.Trim()) { shzt2 = ds.Tables[0].Rows[0]["zjshzt2"].ToString().Trim(); } sqlstr1 = "update xmk set spzt='专家审核未完成',zjshzt = '" + shzt + "',zjshzt2 = '" + shzt2 + "' where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and spzt != '立项'"; string mycm1 = "update xmk set spzjID = '" + zj1id.Text.Trim() + "',zjgs = '" + 2 + "' where xmID = '" + ID + "' and tj = 1 and spzt != '立项'"; SqlCommand mycmd1 = new SqlCommand(mycm1, mycn); mycmd1.ExecuteNonQuery(); string mycm2 = "update xmk set spzjID2 = '" + zj2id.Text.Trim() + "',zjgs = '" + 2 + "' where xmID = '" + ID + "' and tj = 1 and spzt != '立项'"; SqlCommand mycmd2 = new SqlCommand(mycm2, mycn); mycmd2.ExecuteNonQuery(); SqlCommand sqlcom1 = new SqlCommand(mycm1, mycn); sqlcom1 = new SqlCommand(sqlstr1, mycn); sqlcom1.ExecuteNonQuery(); } else if (zj1.Text.Trim() != "") { string shzt = "未审核"; string p1 = ""; DataSet ds = new DataSet(); ds = sdb.Select("select * from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 and spzt != '立项'", null); p1 = ds.Tables[0].Rows[0]["spzjID"].ToString().Trim(); if (p1 == zj1id.Text.Trim()) { shzt = ds.Tables[0].Rows[0]["zjshzt"].ToString().Trim(); } sqlstr1 = "update xmk set spzt='专家审核未完成',zjshzt = '" + shzt + "' where xmID='" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1"; string mycm1 = "update xmk set spzjID = '" + zj1id.Text.Trim() + "',zjgs = '" + 1 + "' where xmID = '" + ID + "' and spzt != '立项' and tj = 1 "; SqlCommand mycmd1 = new SqlCommand(mycm1, mycn); mycmd1.ExecuteNonQuery(); SqlCommand sqlcom1 = new SqlCommand(mycm1, mycn); sqlcom1 = new SqlCommand(sqlstr1, mycn); sqlcom1.ExecuteNonQuery(); } } } Response.Redirect(Request.Url.ToString()); } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "')</script>"); } finally { mycn.Close(); } } //清空专家 protected void onbtn_zjdelete(object sender, EventArgs e) { zj1.Text = ""; zj2.Text = ""; zj3.Text = ""; zj11.Text = ""; zj22.Text = ""; zj33.Text = ""; zj1id.Text = ""; zj2id.Text = ""; zj3id.Text = ""; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { sdb.Update("update xmk set spzjID = NULL, spzjID2 = NULL, spzjID3 = NULL, zjyj = NUll, zjyj2 = NUll, zjyj3 = NUll ,zjshzt = NULL ,zjshzt2 = NULL, zjshzt3 = NULL, zjtg = NULL, zjtg2 = NULL ,zjtg3 = NULL where xmID = '" + GridView1.DataKeys[i].Value + "' and spzt != '立项' and tj = 1 ", null); } } string sl = "<script language='javascript' type='text/javascript'> msgbox1(1)</script>"; Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "msgbox1", sl); } //退回提交申请 protected void thtj_Click(object sender, EventArgs e) { if (panduanxuanzhong()) { mycn = new SqlConnection(mycns); SqlCommand sqlcom, sqlcom1; string k = ""; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { mycn.Open(); string sqlstr = ""; SqlServerDataBase sdb = new SqlServerDataBase(); DataSet ds = new DataSet(); ds = sdb.Select("select zjgs,spzt from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1", null); string zjgs = ds.Tables[0].Rows[0][0].ToString().Trim(); string spzt = ds.Tables[0].Rows[0][1].ToString().Trim(); if (spzt == "立项") { Response.Write("<script>alert('存在已立项项目!')</script>"); } else { if (zjgs == "1") { sqlstr = "update xmk set tj = 2,spzt = '未提交',cstg = NULL, zjtg = NULL,zjtg2 = NULL,zjtg3 = NULL,kjytg = NULL, zjshzt = '未审核',spzjID = NULL,spzjID2 = NULL,spzjID3 = NULL,csyj = NULL,zjyj = NULL,zjyj2 = NULL,zjyj3 = NULL,kjyyj = NULL where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1"; } else if (zjgs == "2") { sqlstr = "update xmk set tj = 2,spzt = '未提交',cstg = NULL, zjtg = NULL,zjtg2 = NULL,zjtg3 = NULL,kjytg = NULL, zjshzt = '未审核',zjshzt2 = '未审核',spzjID = NULL,spzjID2 = NULL,spzjID3 = NULL,csyj = NULL,zjyj = NULL,zjyj2 = NULL,zjyj3 = NULL,kjyyj = NULL where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1"; } else if (zjgs == "3") { sqlstr = "update xmk set tj = 2,spzt = '未提交',cstg = NULL, zjtg = NULL,zjtg2 = NULL,zjtg3 = NULL,kjytg = NULL, zjshzt = '未审核',zjshzt2 = '未审核',zjshzt3 = '未审核',spzjID = NULL,spzjID2 = NULL,spzjID3 = NULL,csyj = NULL,zjyj = NULL,zjyj2 = NULL,zjyj3 = NULL,kjyyj = NULL where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1"; } else { sqlstr = "update xmk set tj = 2,spzt = '未提交',cstg = NULL, zjtg = NULL,zjtg2 = NULL,zjtg3 = NULL,kjytg = NULL, zjshzt = '未审核',zjshzt2 = '未审核',zjshzt3 = '未审核',spzjID = NULL,spzjID2 = NULL,spzjID3 = NULL,csyj = NULL,zjyj = NULL,zjyj2 = NULL,zjyj3 = NULL,kjyyj = NULL where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1"; } sqlcom = new SqlCommand(sqlstr, mycn); sqlcom.ExecuteNonQuery(); } mycn.Close(); } } bindgrid(); } } protected void pzry_Click(object sender, EventArgs e) { bool tg = true; int num = 0; SqlServerDataBase sdb = new SqlServerDataBase(); for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { DataSet ds1 = new DataSet(); ds1 = sdb.Select("select kjytg from xmk where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1", null); if (ds1.Tables[0].Rows[0][0].ToString().Trim() == "1") { } else { tg = false; } num++; } } if (num != 0) { if (tg) { for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { string nowdt; nowdt = DateTime.Now.ToShortDateString().ToString(); DataSet ds = new DataSet(); sdb.Update("update xmk set spzt='立项' where xmID='" + GridView1.DataKeys[i].Value + "' and tj = 1 ", null); Response.Write("<script>alert('立项成功!')</script>"); Response.Redirect(Request.Url.ToString()); } } } else { Response.Write("<script>alert('存在审批未完成项目!')</script>"); } } else { Response.Write("<script>alert('请选中一行!')</script>"); } } protected void ss_droplist_SelectedIndexChanged(object sender, EventArgs e) { DataSet ds = new DataSet(); SqlConnection mycn = new SqlConnection(mycns); //mycn.Open(); string userss; if (ss_droplist.SelectedValue == "ss1") { userss = ""; } else { userss = ss_droplist.SelectedItem.Text.Trim(); } String cxtj = DropDownList1.SelectedValue.Trim(); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn.Open(); string sss=""; if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and " + cxtj + " like '%" + userss + "%'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%'"; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理'"; } } SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds, "tabenterprise"); mycn.Close(); } //为控件绑定数据 GridView1.DataSource = ds.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); DataSet ds1 = new DataSet(); SqlConnection mycn1 = new SqlConnection(mycns); using (SqlConnection sqlconn = new SqlConnection(mycns)) { mycn1.Open(); string sss = ""; if (Session["user"].ToString() == "用户") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and " + cxtj + " like '%" + userss + "%'"; } if (Session["user"].ToString() == "总经理") { if (Session["managertype"].ToString() == "菁蓉园区") { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%'"; } else { sss = "select xmk.xmID, xmk.xmmc, xmk.fzr, xmk.xmqx, xmk.xmlb,xmk.spzt, zjk.zjxm, xmk.spzjID2,xmk.spzjID3,xmk.zjl from xmk left outer join zjk on zjk.zjID = xmk.spzjID where zjover = '1' and xmk.spzt != '毕业' and xmk.tj = 1 and xmk.spzt != '未提交' and xmk." + cxtj + " like '%" + userss + "%' and zjl like '%" + Session["managertype"].ToString().Trim() + "%' and zjl != '菁蓉园区总经理'"; } } SqlDataAdapter sqld = new SqlDataAdapter(sss, sqlconn); sqld.Fill(ds1, "tabenterprise"); mycn1.Close(); } if (ds1.Tables[0].Rows.Count > 0) //当数据库有数据的时候绑定数据 { for (int i = 0; i < ds1.Tables[0].Rows.Count; i++) { string temp = ds1.Tables[0].Rows[i]["xmlb"].ToString().Trim(), s1, s2; s1 = temp.Replace("a", "企业技术服务类"); s2 = s1.Replace("b", " 双创人才项目"); ds1.Tables[0].Rows[i]["xmlb"] = s2; } } else { img_nodigit.Visible = true; } foreach (DataRow row in ds1.Tables[0].Rows) { DataSet ds2 = new DataSet(); DataSet ds3 = new DataSet(); ds2 = sdb.Select("select zjxm from zjk where zjID='" + row[7].ToString() + "'", null); ds3 = sdb.Select("select zjxm from zjk where zjID='" + row[8].ToString() + "'", null); string zjxm2 = "", zjxm3 = ""; if (row[7].ToString() != "") { zjxm2 = ds2.Tables[0].Rows[0][0].ToString().Trim(); } if (row[8].ToString() != "") { zjxm3 = ds3.Tables[0].Rows[0][0].ToString().Trim(); } row[7] = zjxm2; row[8] = zjxm3; } //为控件绑定数据 GridView1.DataSource = ds1.Tables["tabenterprise"].DefaultView; GridView1.DataBind(); } protected void zd_Click(object sender, EventArgs e) { string zjls = ""; if (xbb.Checked == true) { zjls = "校本部总经理"; } if (rn.Checked == true) { zjls = "人南总经理"; } if (qryq.Checked == true) { zjls = "菁蓉园区总经理"; } SqlServerDataBase sdb = new SqlServerDataBase(); for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { sdb.Update("update xmk set zjl = '" + zjls + "'where xmID='" + GridView1.DataKeys[i].Value + "' ", null); Response.Write("<script>alert('分配成功!')</script>"); Response.Redirect("right3.aspx"); } } } }
using Microsoft.EntityFrameworkCore; using System; namespace MAS_Końcowy.Model { public class MASContext : DbContext { //public MASContext() // : base(nameOrConnectionString: ConfigurationManager.ConnectionStrings["Postgres"].ConnectionString) //{ } public MASContext() { } //TPT public DbSet<Person> People { get; set; } public DbSet<IngredientsSupplier> IngredientSuppliers { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<Cook> Cooks { get; set; } public DbSet<Waiter> Waiters { get; set; } public DbSet<Deliverer> Deliverers { get; set; } public DbSet<Manager> Managers { get; set; } public DbSet<Menu> Menus { get; set; } public DbSet<Dish> Dishes { get; set; } public DbSet<DishContent> DishContents { get; set; } public DbSet<Ingredient> Ingredients { get; set; } public DbSet<Contract> Contracts { get; set; } public DbSet<ContractIngredient> ContractIngredients { get; set; } public DbSet<Address> Addresses { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderContent> OrderContents { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("Host=localhost;Database=MAS_DB;Username=postgres;Password=admin"); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ContractIngredient>().HasKey(k => new { k.ContractId, k.IngredientId }); modelBuilder.Entity<Menu>() .HasKey(a => a.Id); modelBuilder.Entity<Menu>() .HasMany(b => b.Dishes) .WithOne(c => c.Menu) .IsRequired() .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Dish>() .HasKey(a => a.Id); modelBuilder.Entity<Ingredient>() .HasKey(a => a.Id); //many to many DISH - INGREDIENT modelBuilder.Entity<DishContent>() .HasKey(di => new { di.DishId, di.IngredientId }); modelBuilder.Entity<DishContent>() .HasOne(a => a.Dish) .WithMany(b => b.DishIngredients) .HasForeignKey(c => c.DishId); modelBuilder.Entity<DishContent>() .HasOne(a => a.Ingredient) .WithMany(b => b.DishContents) .HasForeignKey(c => c.IngredientId); //many to many ORDER - DISH modelBuilder.Entity<OrderContent>() .HasKey(di => new { di.DishId, di.OrderId }); modelBuilder.Entity<OrderContent>() .HasOne(a => a.Dish) .WithMany(b => b.OrderContents) .HasForeignKey(c => c.DishId); modelBuilder.Entity<OrderContent>() .HasOne(a => a.Order) .WithMany(b => b.OrderContents) .HasForeignKey(c => c.OrderId); //many to many CONTRACT - INGREDIENT modelBuilder.Entity<ContractIngredient>() .HasKey(di => new { di.ContractId, di.IngredientId }); modelBuilder.Entity<ContractIngredient>() .HasOne(a => a.Contract) .WithMany(b => b.ContractIngredients) .HasForeignKey(c => c.ContractId); modelBuilder.Entity<ContractIngredient>() .HasOne(a => a.Ingredient) .WithMany(b => b.ContractIngredients) .HasForeignKey(c => c.IngredientId); //Order - Address modelBuilder.Entity<Address>() .HasMany(a => a.Orders) .WithOne(b => b.DeliveryAddress).OnDelete(DeleteBehavior.Restrict); //Person - Address modelBuilder.Entity<Person>() .HasOne(a => a.Address) .WithOne(b => b.Person) .HasForeignKey(nameof(Person.Address)) .IsRequired(); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Predictr.Interfaces; using Predictr.Models; namespace Predictr.Services { public class UserProvider: IUserProvider { private readonly IHttpContextAccessor _contextAccessor; private readonly UserManager<ApplicationUser> _userManager; public UserProvider(IHttpContextAccessor contextAccessor, UserManager<ApplicationUser> userManager) { _contextAccessor = contextAccessor; _userManager = userManager; } public string GetUserId() { return _userManager.GetUserId(_contextAccessor.HttpContext.User); } } }
// ----------------------------------------------------------------------- // <copyright file="LocalizationCache.cs"> // Copyright (c) Michal Pokorný. All Rights Reserved. // </copyright> // ----------------------------------------------------------------------- namespace Pentagon.Extensions.Localization { using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Helpers; using Interfaces; using JetBrains.Annotations; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using Options; using Threading; public class LocalizationContext<T> { public LocalizationContext(T value) { Value = value; } public T Value { get; } } public class LocalizationCache : ILocalizationCache { const string CacheKeyPrefix = "LOCALIZATION_"; const string LocalizationNotFoundPrefix = "LOCALIZATION_NOT_FOUND__"; [NotNull] SemaphoreSlim _semaphore = new SemaphoreSlim(1,1); [NotNull] readonly ICultureStore _store; [NotNull] readonly IMemoryCache _cache; [NotNull] readonly ICultureManager _manager; [NotNull] readonly MemoryCacheEntryOptions _cacheOptions; [NotNull] readonly CultureCacheOptions _options; [NotNull] CultureInfo _culture; public LocalizationCache([NotNull] ICultureStore store, [NotNull] IMemoryCache cache, [NotNull] ICultureContext context, [NotNull] ICultureManager manager, IOptionsSnapshot<CultureCacheOptions> optionsSnapshot) { _store = store ?? throw new ArgumentNullException(nameof(store)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _manager = manager ?? throw new ArgumentNullException(nameof(manager)); _options = optionsSnapshot?.Value ?? new CultureCacheOptions(); _cacheOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(_options.CacheLifespanInSeconds)) .RegisterPostEvictionCallback((key, value, reason, state) => { if (reason != EvictionReason.Replaced) { } }); _culture = context.UICulture; } string GetFromCache([NotNull] string key) { var entryKey = GetKeyName(key); if (!_cache.TryGetValue<string>(entryKey, out var cacheValue)) { return null; } return cacheValue; } string SetToCache([NotNull] string key, string value) { var entryKey = GetKeyName(key); if (_cache.TryGetValue<string>(entryKey, out var cacheValue)) { return cacheValue; } var setValue = _cache.Set(entryKey, value, _cacheOptions); return setValue; } /// <inheritdoc /> public async ValueTask<string> GetValueAsync(string key, params object[] formatArguments) { if (key == null) throw new ArgumentNullException(nameof(key)); await _semaphore.WaitAsync().ConfigureAwait(false); // value task because of hot-path to cached values var value = GetFromCache(key) ?? await ForceCacheUpdateAsync(key).ConfigureAwait(false); if (value == null) return GetNotFoundValue(key); if (formatArguments == null || formatArguments.Length == 0) return value; var formattedValue = string.Format(value, formatArguments); return formattedValue; } /// <inheritdoc /> public async ValueTask<LocalizationContext<T>> CreateContextAsync<T>() { var instance = await LocalizationDefinitionConvention.CreateLocalizationInstanceAsync(typeof(T), key => GetValueAsync(key)).ConfigureAwait(false); return new LocalizationContext<T>((T) instance); } /// <inheritdoc /> public LocalizationContext<T> CreateContext<T>() { var instance = LocalizationDefinitionConvention.CreateLocalizationInstance(typeof(T), s => { var fromCache= GetFromCache(s); return fromCache ?? GetNotFoundValue(s); }); return new LocalizationContext<T>((T)instance); } string GetNotFoundValue([NotNull] string key) { switch (_options.IndicateLocalizationValueNotFound) { case LocalizationNotFoundBehavior.Exception: throw new LocalizationNotFoundException(key, _culture); case LocalizationNotFoundBehavior.Key: return key; case LocalizationNotFoundBehavior.KeyWithNotFoundIndication: return LocalizationNotFoundPrefix + key; default: return null; } } public async Task<string> ForceCacheUpdateAsync(string key) { if (_options.IncludeParentResources) { var all = await _manager.GetResourcesAsync(_culture).ConfigureAwait(false); foreach (var pair in all) SetToCache(pair.Key, pair.Value); return GetFromCache(key); } var value = (await _store.GetResourceAsync(_culture.Name, key).ConfigureAwait(false)).Value; if (value == null) return GetNotFoundValue(key); SetToCache(key, value); return value; } /// <inheritdoc /> public async Task<IDictionary<string, string>> GetAllAsync(string cultureName, Func<string, bool> keyPredicate = null) { cultureName??=_culture.Name; if (!CultureHelper.TryParse(cultureName, out var culture)) throw new FormatException($"Culture is invalid '{cultureName}'."); await _semaphore.WaitAsync().ConfigureAwait(false); var all = await _manager.GetResourcesAsync(culture, _options != null && _options.IncludeParentResources).ConfigureAwait(false); var result = new Dictionary<string, string>(); foreach (var entity in all) { if (keyPredicate?.Invoke(entity.Key) == false) continue; var inCacheValue = GetFromCache(entity.Key) ?? SetToCache(entity.Key, entity.Value); result.Add(entity.Key, inCacheValue); } return result; } /// <inheritdoc /> public ILocalizationCache WithCulture(CultureInfo culture) { _culture = culture; return this; } string GetKeyName(string key) => $"{CacheKeyPrefix}{_culture.Name}_{key}"; /// <inheritdoc /> public string this[string key] => GetValueAsync(key).ConfigureAwait(false).GetAwaiter().GetResult(); /// <inheritdoc /> public bool Contains(string key) => this[key] != null; /// <inheritdoc /> public string this[string key, params object[] formatArguments] { get { if (key == null) throw new ArgumentNullException(nameof(key)); if (formatArguments == null) throw new ArgumentNullException(nameof(formatArguments)); return GetValueAsync(key, formatArguments).ConfigureAwait(false).GetAwaiter().GetResult(); } } } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Industry.Offline.RechargeAccount.Entities; using MongoDB.Bson; namespace Alabo.Industry.Offline.RechargeAccount.Repositories { public class RechargeAccountLogRepository : RepositoryMongo<RechargeAccountLog, ObjectId>, IRechargeAccountLogRepository { public RechargeAccountLogRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
namespace HandsOfCards { using System; using System.Collections.Generic; using System.Linq; public class StartUp { public static void Main() { var input = Console.ReadLine(); var cards = new Dictionary<string, List<string>>(); var cardsPower = new Dictionary<string, int>(); while (input != "JOKER") { var inputLine = input .Split(new string[] { ": ", ", " }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var name = inputLine[0]; var hand = inputLine.Skip(1).Take(inputLine.Length).ToList(); if (!cards.ContainsKey(name)) { cards.Add(name, new List<string>()); cardsPower.Add(name, 0); } foreach (var card in hand) { if (!cards[name].Contains(card)) { cards[name].Add(card); var handPower = CalculateHandPower(card); cardsPower[name] += handPower; } } input = Console.ReadLine(); } foreach (var player in cardsPower) { Console.WriteLine($"{player.Key}: {player.Value}"); } } public static int CalculateHandPower(string card) { var handPower = 0; var cardValue = 0; var cardPower = 0; switch (card.First()) { case '2': cardValue = 2; break; case '3': cardValue = 3; break; case '4': cardValue = 4; break; case '5': cardValue = 5; break; case '6': cardValue = 6; break; case '7': cardValue = 7; break; case '8': cardValue = 8; break; case '9': cardValue = 9; break; case '1': cardValue = 10; break; case 'J': cardValue = 11; break; case 'Q': cardValue = 12; break; case 'K': cardValue = 13; break; case 'A': cardValue = 14; break; } switch (card.Last()) { case 'C': cardPower = 1; break; case 'D': cardPower = 2; break; case 'H': cardPower = 3; break; case 'S': cardPower = 4; break; } handPower = cardValue * cardPower; return handPower; } } }
using UnityEngine; using System.Collections; using System; /// <summary> /// Player controller and behavior /// </summary> public class PlayerScript : MonoBehaviour { /// <summary> /// 1 - The speed of the ship /// </summary> public int speed = 1; public int jump = 160; private Rigidbody2D player; private bool colliding = false; void Start() { player = GetComponent<Rigidbody2D> (); } void Update() { if (Input.GetKey (KeyCode.D)) { player.AddForce(Vector2.right * speed); } if (Input.GetKey (KeyCode.A)) { player.AddForce(Vector2.left * speed); } if (Input.GetKeyDown (KeyCode.Space) && colliding == true) { player.AddForce(Vector2.up * jump); } } void FixedUpdate() { // 3 - Retrieve axis information //float inputX = Input.GetAxisRaw("Horizontal"); //float inputY = Input.GetAxisRaw("Vertical"); // 4 - Movement per direction //movement = new Vector2(move_left, move_right); // 5 - Move the game object //move_left = 0; //move_right = 0; } void OnCollisionStay2D() { colliding = true; } void OnCollisionExit2D() { colliding = false; } public bool isGrounded() { if (player.velocity.y == 0){ return true; } else return false; } }
using PangyaFileCore; 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 Pangya_IffManger { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_openFile_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Pangya File (*.iff)|*.iff"; //+ "Character (Character*.iff)|Character*.iff"; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; string fileName = openFileDialog.SafeFileName.ToLower(); try { switch (fileName) { case "character.iff": { PangyaFile<Character> arquivo = new Character(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; case "part.iff": { PangyaFile<Part> arquivo = new Part(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; case "card.iff": { PangyaFile<Card> arquivo = new Card(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; case "caddie.iff": { PangyaFile<Caddie> arquivo = new Caddie(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; case "setitem.iff": { PangyaFile<SetItem> arquivo = new SetItem(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; case "mascot.iff": { PangyaFile<Mascot> arquivo = new Mascot(); this.dataGridView1.DataSource = arquivo.GetFromFile(filePath); } break; default: { MessageBox.Show($"A leitura de {openFileDialog.SafeFileName} não implementado, escolha outro arquivo."); } break; } } catch (Exception ex) { MessageBox.Show("Erro ao tentar ler o arquivo. Mensagem: " + ex.Message); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Journey.WebApp.Data { public partial class City { public City() { TravelersCities = new HashSet<TravelersCities>(); TripCities = new HashSet<TripCities>(); } public int Id { get; set; } [Display(Name = "City")] public string CityName { get; set; } public string Country { get; set; } [Display(Name = "State/Province")] public string CityState { get; set; } public ICollection<TravelersCities> TravelersCities { get; set; } public ICollection<TripCities> TripCities { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using NHibernate; using Profiling2.Domain.Contracts.Queries.Audit; using Profiling2.Domain.Contracts.Queries.Stats; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Domain.DTO; using Profiling2.Domain.Prf.Careers; using Profiling2.Domain.Prf.Persons; namespace Profiling2.Tasks { public class PersonStatisticTasks : IPersonStatisticTasks { protected readonly IPersonStatisticsQuery personStatisticsQuery; protected readonly ICountsQuery countsQuery; protected readonly IEventRevisionsQuery eventRevisionsQuery; protected readonly IPersonAuditable<Career> auditCareerQuery; protected readonly IPersonTasks personTasks; protected readonly IAuditTasks auditTasks; public PersonStatisticTasks(IPersonStatisticsQuery personStatisticsQuery, ICountsQuery countsQuery, IEventRevisionsQuery eventRevisionsQuery, IPersonAuditable<Career> auditCareerQuery, IPersonTasks personTasks, IAuditTasks auditTasks) { this.personStatisticsQuery = personStatisticsQuery; this.countsQuery = countsQuery; this.eventRevisionsQuery = eventRevisionsQuery; this.auditCareerQuery = auditCareerQuery; this.personTasks = personTasks; this.auditTasks = auditTasks; } public IList<object[]> GetCreatedProfilesCountByMonth() { return this.personStatisticsQuery.GetCreatedProfilesCountByMonth(); } public ProfilingCountsView GetProfilingCountsView(DateTime? date, ISession session) { if (date.HasValue) { return new ProfilingCountsView() { AsOfDate = string.Format("{0:yyyy-MM-dd}", date.Value), ProfileStatus = this.GetPersonCount(date.Value)//, //Career = ((IHistoricalCareerQuery)this.auditCareerQuery).GetCareerCount(date.Value), // this figure inaccurate for unknown reason //Event = this.eventRevisionsQuery.GetEventCount(date.Value) // this figure inaccurate as it doesn't account for merged events }; } else { return new ProfilingCountsView() { AsOfDate = "now", ProfileStatus = this.GetCurrentPersonCount(session), Career = this.countsQuery.GetCareerCount(session), Organization = this.countsQuery.GetOrganizationCount(session), Event = this.countsQuery.GetEventCount(session), PersonResponsibility = this.countsQuery.GetPersonResponsibilityCount(session), OrganizationResponsibility = this.countsQuery.GetOrganizationResponsibilityCount(session), Source = this.countsQuery.GetSourceCount(session), }; } } protected IDictionary<ProfileStatus, int> GetPersonCount(DateTime date) { IDictionary<ProfileStatus, int> counts = new Dictionary<ProfileStatus, int>(); // get deleted profiles from Profiling1 audit trail - required because deletions due to person merges are only recorded there (and not in PRF_Person_AUD). IList<int> deleted = this.auditTasks.GetOldDeletedProfiles().Where(x => x.WhenDate.Value <= date).Select(x => Convert.ToInt32(x.PersonID)).ToList(); foreach (ProfileStatus ps in this.personTasks.GetAllProfileStatuses()) { // get list of persons according to envers at given date IList<Person> enversPersonList = this.auditTasks.GetPersons(date, ps); // filter out those that were deleted, but whose deletion wasn't recorded in PRF_Person_AUD table (REVTYPE=2). counts.Add(ps, enversPersonList.Where(x => !deleted.Contains(x.Id)).Count()); } // do the same as above, but for FARDC_2007_List ProfileStatus fardcPs = this.personTasks.GetProfileStatus(ProfileStatus.FARDC_2007_LIST); if (fardcPs != null) { IList<Person> fardcList = this.auditTasks.GetPersons(date, fardcPs); counts.Add(fardcPs, fardcList.Where(x => !deleted.Contains(x.Id)).Count()); } return counts; } protected IDictionary<ProfileStatus, int> GetCurrentPersonCount(ISession session) { IList<object[]> counts = this.personStatisticsQuery.GetLiveCreatedProfilesCount(session); IDictionary<ProfileStatus, int> dict = new Dictionary<ProfileStatus, int>(); foreach (ProfileStatus ps in this.personTasks.GetAllProfileStatuses(session)) { IEnumerable<object[]> psCounts = counts.Where(x => Convert.ToInt32(x[0]) == ps.Id); if (psCounts != null && psCounts.Any()) { object[] row = psCounts.First(); dict.Add(ps, Convert.ToInt32(row[1])); } else { dict.Add(ps, 0); } } ProfileStatus fardc2007List = this.personTasks.GetProfileStatus(ProfileStatus.FARDC_2007_LIST, session); IEnumerable<object[]> fardc2007Counts = counts.Where(x => Convert.ToInt32(x[0]) == fardc2007List.Id); if (fardc2007Counts != null && fardc2007Counts.Any()) { object[] row = fardc2007Counts.First(); dict.Add(fardc2007List, Convert.ToInt32(row[1])); } else { dict.Add(fardc2007List, 0); } return dict; } public IDictionary<string, IDictionary<string, int>> GetPersonCountByStatusAndOrganization() { IDictionary<string, IDictionary<string, int>> orgs = new Dictionary<string, IDictionary<string, int>>(); // person counts by organization (those with careers) and status foreach (object[] row in this.personStatisticsQuery.GetProfileStatusCountsByOrganization()) { string psName = Convert.ToString(row[0]); string orgName = Convert.ToString(row[1]); int count = Convert.ToInt32(row[2]); if (!orgs.ContainsKey(orgName)) { orgs[orgName] = new Dictionary<string, int>(); foreach (ProfileStatus ps in this.personTasks.GetAllProfileStatuses()) orgs[orgName][ps.ProfileStatusName] = 0; } if (!string.Equals(psName, ProfileStatus.FARDC_2007_LIST)) orgs[orgName][psName] = count; } // person counts by status only (i.e. no careers) foreach (object[] row in this.personStatisticsQuery.GetProfileStatusCountsNoOrganization()) { string psName = Convert.ToString(row[0]); int count = Convert.ToInt32(row[1]); if (!orgs.ContainsKey(string.Empty)) { orgs[string.Empty] = new Dictionary<string, int>(); foreach (ProfileStatus ps in this.personTasks.GetAllProfileStatuses()) orgs[string.Empty][ps.ProfileStatusName] = 0; } if (!string.Equals(psName, ProfileStatus.FARDC_2007_LIST)) orgs[string.Empty][psName] += count; } return orgs; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /* * Truck game runner, score manager */ public class TruckCollectorManager : MonoBehaviour { //Score public static int scoreGoodCollected; public static int scoreWrongCollected; //Character Hit point(life) public static int hp; // UI element <Text>Component private Text scoreGoodText; private Text scoreWrongText; public AudioClip hit; public AudioClip getGoodPoint; public AudioClip getBadPoint; AudioSource audioSource; private int pointToLevel2; private ShakeCamera shake; private string tag; //Allow to know what kind of object should collide //---------------------------------------------------------- void Start() { scoreGoodCollected = 0; scoreWrongCollected = 0; pointToLevel2 = 5; audioSource = GetComponent<AudioSource> (); //Get camera component shake = GameObject.FindGameObjectWithTag ("ScreenShake").GetComponent<ShakeCamera> (); //Set Life points hp = 3; //Get Texts components scoreGoodText = GameObject.Find ("ScoreRightPoints").GetComponent<Text> (); scoreWrongText = GameObject.Find ("ScoreBadPoints").GetComponent<Text> (); //Check what kind of truck is instantiated to set its corresponding tag if (gameObject.name.Equals("GreenTruck(Clone)")) { tag = "Organico"; } if (gameObject.name.Equals("YellowTruck(Clone)")) { tag = "Aluminio"; } if (gameObject.name.Equals("BlueTruck(Clone)")) { tag = "Envase"; } if (gameObject.name.Equals("BrownTruck(Clone)")) { tag = "Residuo_Manejo"; } if (gameObject.name.Equals("OrangeTruck(Clone)")) { tag = "Vidrio"; } if (gameObject.name.Equals("GrayTruck(Clone)")) { tag = "Papel_Carton"; } if (gameObject.name.Equals("BlackTruck(Clone)")) { tag = "Ordinario"; } } //---------------------------------------------------------- void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == tag) { scoreGoodCollected++; audioSource.PlayOneShot (getGoodPoint,1); } else if (col.gameObject.tag == "Obstaculo") { audioSource.PlayOneShot (hit,2); shake.CamShake (); hp--; } else { scoreWrongCollected++; audioSource.PlayOneShot (getBadPoint,1); } scoreGoodText.text = "Reciclables: " + scoreGoodCollected.ToString (); scoreWrongText.text = "No Reciclables: " + scoreWrongCollected.ToString (); Destroy (col.gameObject); } //---------------------------------------------------------- void Update() { if(hp == 0){ gameObject.SetActive (false); } } //---------------------------------------------------------- }
using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using TaskMaster.Models; using TaskMaster.Services; using static TaskMaster.Helpers.RouteNames; namespace TaskMaster.Controllers { /// <summary> /// Employees controller /// </summary> public class EmployeesController : Controller { #region Private Fields /// <summary> /// Employees repository. /// </summary> private readonly IEmployeeRepository _employeeRepository; #endregion Private Fields #region Public Constructors /// <summary> /// Creates employees controller. /// </summary> /// <param name="employeeRepository">Employees repository.</param> public EmployeesController(IEmployeeRepository employeeRepository) { _employeeRepository = employeeRepository; } #endregion Public Constructors #region Public Methods /// <summary> /// Returns view for employee adding page. /// </summary> [Route("employee/add", Name = AddEmployeePageRouteName)] [HttpGet] public IActionResult Add() { var employee = new Employee(); return View("Edit", employee); } /// <summary> /// Adds employee model to repository and redirects to employee page. /// if model is invalid returns view for continue editing. /// </summary> /// <param name="employee">Employee model.</param> [Route("employee/add", Name = AddEmployeeEndpointRouteName)] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Add(Employee employee) { if (!ModelState.IsValid) { return View("Edit", employee); } await _employeeRepository.SaveEmployeeAsync(employee); return RedirectToAction(nameof(Employee), new { id = employee.Id }); } /// <summary> /// Deletes employee with <paramref name="id"/> identifier and redirects to employees list page. /// </summary> /// <param name="id">Id of employee to remove.</param> [Route("employee/{id}/delete", Name = DeleteEmployeeRouteName)] [HttpGet] public async Task<IActionResult> Delete(int id) { var employee = await _employeeRepository.GetEmployeeAsync(id); if (employee is null) { return NotFound(); } await _employeeRepository.DeleteEmployeeAsync(employee); return RedirectToRoute("EmployeesList"); } /// <summary> /// Returns editing page for employee with <paramref name="id"/> identifier. /// </summary> /// <param name="id">Employees identifier.</param> [Route("employee/{id}/edit", Name = EditEmployeePageRouteName)] [HttpGet] public async Task<IActionResult> Edit(int id) { var employee = await _employeeRepository.GetEmployeeAsync(id); if (employee is null) { return NotFound(); } return View(employee); } /// <summary> /// Update employee model in repository and redirects to his page. /// Of model is invalid returns view to continue editing. /// </summary> /// <param name="id">id</param> /// <param name="employee">Received employee model.</param> [Route("employee/{id}/edit", Name = UpdateEmployeeEndpointRouteName)] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, Employee employee) { if (!ModelState.IsValid) { return View(employee); } await _employeeRepository.SaveEmployeeAsync(employee); return RedirectToAction(nameof(Employee), new { id }); } /// <summary> /// Returns page with employee data. /// </summary> /// <param name="id">Id of employee.</param> [Route("employee/{id}", Name = EmployeePageRouteName)] [HttpGet] public async Task<IActionResult> Employee(int id) { var employee = await _employeeRepository.GetEmployeeAsync(id); if (employee is null) { return NotFound(); } return View("employee", employee); } /// <summary> /// Returns list of employees. /// </summary> [Route("employees", Name = EmployeeListRouteName)] [HttpGet] public async Task<IActionResult> Index() { var employees = await _employeeRepository.GetEmployeesAsync(); return View(employees); } #endregion Public Methods } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Project_TouchCube { public partial class ChartUC : UserControl { /** * * ChartUC class * created by: Tom Bortels * handles the creation of the charts dynamically * code will be transparant to allow further use in future * * */ //configuration variables Connection conn; //margins for box surrounding graph private int vmargin = 30; private int hmargin = 30; private int maxpointsize = 255; private Pen pen1; Graphics graphobj; //points of the graph. private tooltipPointUC[,] vpunten = new tooltipPointUC[5,10]; private int[,] waarden = new int[5,10]; private Color[] kleur = { Color.Red, Color.Blue, Color.Fuchsia, Color.Green, Color.Orange }; #region "Control properties" public int Vmargin { get { return vmargin; } set { vmargin = value; } } public int Hmargin { get { return hmargin; } set { hmargin = value; } } #endregion public ChartUC() { InitializeComponent(); } private void ChartUC_Load(object sender, EventArgs e) { conn = new Connection(); graphobj = this.CreateGraphics(); pen1 = new Pen(Color.Black, 2); //draws the field containing the graph //always 2 times the offset for lower border } public void loadUC(int id) { conn = new Connection(); List<measurement> metingen = conn.getHistory(id); for (int i = 0; i < metingen.Count; i++) { measurement meting = metingen.ElementAt(i); waarden[0,i] = Int32.Parse(meting.Wijstop); waarden[1,i] = Int32.Parse(meting.Midtop); waarden[2,i] = Int32.Parse(meting.Ringtop); waarden[3,i] = Int32.Parse(meting.Pinktop); waarden[4,i] = Int32.Parse(meting.Duimtop); } } private void ChartUC_Paint(object sender, PaintEventArgs e) { //drawing the border, has to be each paint since the points interfere otherwise, though it gives problems with the overview graphobj.DrawRectangle(pen1, hmargin, vmargin, getWidth() - 2 * hmargin, getHeight() - 2 * vmargin); } //mag later weg, test nu de beweging van de punten. public void drawgraph(int puntid) { int hoogte = this.Height; int breedte = this.Width; int pointsperfinger = vpunten.GetUpperBound(1) + 1; //clear the screen //clear lines graphobj.Clear(Color.White); //clear the points for (int i = 0; i < 5; i++) { for (int j = 0; j < 10; j++) { this.Controls.Remove(vpunten[i, j]); } } //initialising for (int i = 0; i < 10; i++) { vpunten[puntid, i] = new tooltipPointUC(); //set the color according to the selected finger vpunten[puntid, i].Color = kleur[puntid]; //variable to calculate distance between each point, considering size of points, window size and offset double distanceBetweenPoints = (double)(breedte - (pointsperfinger * tooltipPointUC.getPointSize()) - 2 * hmargin) / (pointsperfinger + 1); // MessageBox.Show(breedte.ToString()); //260 //MessageBox.Show(distanceBetweenPoints.ToString()); //11 //hmargin : 30px, //pointsize: 8px vpunten[puntid, i].Xpos = hmargin + (int)Math.Round(distanceBetweenPoints) + (i * (tooltipPointUC.getPointSize() + (int)Math.Round(distanceBetweenPoints))) + 1; //plus one because the tooltippoints aren't drawn correctly in size //starts left top -> height -; hmargin +9 because border = 2 px in width, ucontrontrol = +-6px. //vpunten[puntid, i].Ypos = hoogte - (waarden[puntid, i] + hmargin + tooltipPointUC.getPointSize() + 2); //2*2 for the border! double scalevalues = ((hoogte - 2*(hmargin+2))/((double)maxpointsize+tooltipPointUC.getPointSize()+4)); vpunten[puntid, i].Ypos = hoogte - (hmargin + (int)(scalevalues * waarden[puntid, i])+tooltipPointUC.getPointSize()+4); vpunten[puntid, i].TooltipText = "punt " + i + " " + waarden[puntid, i]; this.Controls.Add(vpunten[puntid, i]); } //drawing the connection lines between the points for (int i = 0; i <pointsperfinger - 1; i++) { //point drawing starts in top left, line should connect in center, not top left, so correction will be necessary //corrections depend on relative vs next point location graphobj.DrawLine(new Pen(kleur[puntid], (tooltipPointUC.getPointSize() / 2) - 1), vpunten[puntid,i].Xpos + (tooltipPointUC.getPointSize() / 2), vpunten[puntid,i].Ypos + (tooltipPointUC.getPointSize() / 2), vpunten[puntid,i + 1].Xpos + (tooltipPointUC.getPointSize() / 2), vpunten[puntid,i + 1].Ypos + (tooltipPointUC.getPointSize() / 2)); } } private int getWidth() { return this.Width; } private int getHeight() { return this.Height; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace CourseHunter_94_Start_LINQ { public static class LinqExtensions { public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) throw new ArgumentNullException(); foreach (var item in source) { action(item); } } } class Program { // LINQ(Language-Integrated Query) представляет простой и удобный язык запросов к источнику данных. // В качестве источника данных может выступать объект, реализующий интерфейс IEnumerable // (например, стандартные коллекции, массивы), набор данных DataSet, документ XML. // Но вне зависимости от типа источника LINQ позволяет применить ко всем один и // тот же подход для выборки данных. static void Main(string[] args) { DisplayLagestFileWithoutLINQ("d:\\"); Console.WriteLine(new string('-', 35)); DisplayLagestFileWithLINQ(@"e:\Insatlls\Programs inst\"); Console.ReadLine(); } private static void DisplayLagestFileWithLINQ(string pathToDir) { new DirectoryInfo(pathToDir) .GetFiles() //.OrderBy(KeySelector); // мы должны написать каким образом будет происходить сортировка. // вместо верней строчки мы можем использовать лямда выроженияю .OrderBy(x => x.Length) // пишем имя аргумента который попадает в метод => тело метода // если больше одной строчки открываем { } .Take(5) // дальше продолжаем цепочку и (т.к IEnumerable) // дале чтобы воспользоваться foreach надо сделать расширение. // дальше используем наш созданный метод расширения .ForEach(x => Console.WriteLine($"{x.Name} weight = {x.Length / 1000} kB")); // Как мы бы делали это если не метод ращирения и делегаты. IEnumerable<FileInfo> fileInfos = new DirectoryInfo(pathToDir) .GetFiles() .OrderBy(x => x.Length) .Take(5); foreach (var item in fileInfos) { Console.WriteLine($"{item.Name} weight = {item.Length / 1000} kB"); } } static long KeySelector(FileInfo fileInfo) { return fileInfo.Length; } private static void DisplayLagestFileWithoutLINQ(string pathToDir) { var directoryInfo =new DirectoryInfo(pathToDir); FileInfo[] files = directoryInfo.GetFiles(); Array.Sort(files, FileComparison); // дилегат. for (int i = 0; i < 5; i++) { FileInfo file = files[i]; Console.WriteLine($"{file.Name} weight - {file.Length/1000} kB"); } } static int FileComparison(FileInfo x, FileInfo y) { if (x.Length == y.Length) return 0; if (x.Length > y.Length) return -1; return 1; } } }