text
stringlengths
13
6.01M
/* Order.cs * Author: Agustin Rodriguez */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.ComponentModel; namespace DinoDiner.Menu { /// <summary> /// this class represents a new customer order /// </summary> public class Order : INotifyPropertyChanged { /// <summary> /// represents the items added to the order /// </summary> private List<IOrderItem> items; /// <summary> /// array that holds order items /// </summary> public IOrderItem[] Items { get { return items.ToArray(); } } /// <summary> /// calculates the total price from the prices of all order items /// </summary> public double SubtotalCost { get { double cost = 0; foreach(IOrderItem i in Items) { cost += i.Price; } if (cost < 0) { return 0; } return cost; } } /// <summary> /// variable that holds the sales tax rate /// </summary> private double salesTaxRate; /// <summary> /// sales tax in the location of the restaurant /// </summary> public double SalesTaxRate { get { return salesTaxRate; } set { if (value < 0) return; salesTaxRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SalesTaxRate")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SalesTaxCost")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TotalCost")); } } /// <summary> /// amount of sales tax to be paid /// </summary> public double SalesTaxCost { get { return SalesTaxRate * SubtotalCost; } } /// <summary> /// total cost of order /// </summary> public double TotalCost { get { return SalesTaxCost + SubtotalCost; } } /// <summary> /// property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// constructor for this class /// </summary> public Order() { items = new List<IOrderItem>(); } /// <summary> /// method to add an item to the order /// </summary> /// <param name="item"></param> public void Add(IOrderItem item) { item.PropertyChanged += OnCollectionChanged; items.Add(item); OnCollectionChanged(this, new EventArgs()); } /// <summary> /// method to remove items from the order /// </summary> /// <param name="item"></param> public void Remove(IOrderItem item) { items.Remove(item); OnCollectionChanged(this, new EventArgs()); } /// <summary> /// this method will update the propertychangedeventargs for items, subtotal cost, sales tax cost, and total cost /// </summary> /// <param name="sender">sender is the object reference</param> /// <param name="args">args is the event data</param> private void OnCollectionChanged(object sender, EventArgs args) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Items")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SubtotalCost")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SalesTaxCost")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TotalCost")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPC.SQLAPI { [AttributeUsage(AttributeTargets.Method)] public sealed class SQLQueryAttribute : SQLCommandAttribute { public SQLQueryAttribute(string query, string connectionName = null, Type queryTextProcessorType = null) : base("GET", query, connectionName, queryTextProcessorType) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Importacion_Vehiculos.Models; namespace Importacion_Vehiculos.Controllers { public class MarcaController : Controller { // GET: Marca public ActionResult Index() { List<MarcaCLS> listaMarca = null; using (var bd = new Importacion_VehiculosEntities()) { listaMarca = (from marca in bd.Marca select new MarcaCLS { id_marca = marca.Id_Marca, nombre_marca = marca.Nombre_Marca }).ToList(); } return View(listaMarca); } public ActionResult Agregar() { return View(); } //insersion de datos [HttpPost] public ActionResult Agregar(MarcaCLS oMarcaCLS) { if (!ModelState.IsValid) { return View(oMarcaCLS); } else { using (var bd = new Importacion_VehiculosEntities()) { Marca oMarca = new Marca(); oMarca.Nombre_Marca = oMarcaCLS.nombre_marca; bd.Marca.Add(oMarca); bd.SaveChanges(); } } return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CreativityEdu.Enums { public enum Nationlaity { Afghanistan, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antigua , Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, Brunei, Bulgaria, Burma, Burundi, Cambodia, Cameroon, Canada, Cape , Chad, Chile, China, Colomba, Comoros, CookIslands, Costa , Croatia, Cuba, Cyprus, CzechRepublic, Denmark, Djibouti, Dominica, DominicanRepublic, EastTimor, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, Gabon, Gambia, The, GazaStrip, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, Honduras, HongKong, Hungary, Iceland, India, Indonesia, Iran, Iraq, Ireland, IsleofMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, Korea,North, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macau, Macedonia, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, Moldova, Monaco, Mongolia, Montserrat, Morocco, Mozambique, Namibia, Nauru, Nepal, Netherlands, NetherlandsAntilles, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Norway, Oman, Pakistan, Palau, Panama, Paraguay, Peru, Philippines, Poland, Portugal, Qatar, Reunion, Romania, Russia, Singapore, Slovakia, Slovenia, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tajikistan, Tanzania, Thailand, Togo, Tonga, Tuvalu, Uganda, Ukraine, Uruguay, Uzbekistan, Vanuatu, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe } }
using DataModel.Models; 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 CamcoManufacturing.View { /// <summary> /// Interaction logic for View_AllCategories.xaml /// </summary> public partial class View_AllCategories : Window { int CategoryId = 0; BaseDataContext db = new BaseDataContext(); public View_AllCategories(int parent) { InitializeComponent(); CategoryId = parent; HelperClass.ShowWindowPath(PathLabel); FillControls(); } private void FillControls() { dataGridCategory.ItemsSource = null; if (CategoryId > 0) { dataGridCategory.ItemsSource = db.tCategories.Where(p => p.ParentId == CategoryId).ToList(); } else { dataGridCategory.ItemsSource = db.tCategories.ToList(); } } private void EditCategory_Click(object sender, RoutedEventArgs e) { tblCategory dataRowView = (tblCategory)((Button)e.Source).DataContext; //this.Close(); if (!HelperClass.IsWindowOpen(typeof(View.Edit_Category))) { View.Edit_Category obj = new View.Edit_Category(dataRowView.Category_ID); obj.ShowDialog(); } else { Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == "EditCategory"); win.Close(); View.Edit_Category obj = new View.Edit_Category(dataRowView.Category_ID); obj.ShowDialog(); } } private void DeleteCategory_Click(object sender, RoutedEventArgs e) { MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo); if (messageBoxResult == MessageBoxResult.Yes) { tblCategory dataRowView = (tblCategory)((Button)e.Source).DataContext; db.tCategories.Remove(dataRowView); db.SaveChanges(); MessageBox.Show("Deleted SuccessFully!"); FillControls(); } } private void ButtonReturn_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LaunchpadMonitor { class LaunchpadGathererRenderer : IGathererRenderer { Gatherer gatherer = null; ILaunchpad launchpad = null; int scale; public Gatherer Gatherer { set { gatherer = value; } } Launchpad.Color orange = new Launchpad.Color(3, 3); Launchpad.Color red = new Launchpad.Color(3, 0); Launchpad.Color green = new Launchpad.Color(0, 3); Launchpad.Color off = new Launchpad.Color(0, 0); public LaunchpadGathererRenderer(ILaunchpad launchpad) { this.launchpad = launchpad; this.scale = 1; } public void ZoomOut() { scale++; } public void ZoomIn() { if (scale > 1) scale--; } public int Scale { get { return scale; } } public void Present() { if (gatherer != null) { int[] lastN = gatherer.LatestN(8 * scale).ToArray<int>(); launchpad.Clear(); Launchpad.Color c; for (int column = 0; column < 8; column++) { int height = 0; try { for (int index = 0; index < scale; index++) { height += lastN[column * scale + index]; } height = (height * 8) / (25 * scale); // 0 - 31 } catch (System.IndexOutOfRangeException ex) { height = 0; } int y = 0; while (height > 0) { int intensity = height; if (height > 3) { intensity = 3; } if (y < 3) { c = new Launchpad.Color(0, intensity) ; } else if (y >= 3 && y < 5) { c = new Launchpad.Color(intensity, intensity); } else { c = new Launchpad.Color(intensity, 0) ; } launchpad.Set(column, 7-y, c); height -= 4; y++; } } launchpad.Present(); } else { launchpad.Clear(); launchpad.Present(); } } } }
using System; using SuperRpgGame.Exceptions; namespace SuperRpgGame { public abstract class GameObject { private Position position; private char objSymbol; protected GameObject(Position position, char objSymbol) { this.Position = position; this.ObjSymbol = objSymbol; } public Position Position { get { return this.position; } set { if (value.X < 0 || value.Y < 0) { throw new ObjOutOfBoundsException("Specified cordinates are outside map."); } this.position = value; } } public char ObjSymbol { get { return this.objSymbol; } set { if (!char.IsUpper(value)) { throw new ArgumentNullException(""); } this.objSymbol = value; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Web; using System.Web.Mvc; using Inspinia_MVC5.Models; using Microsoft.Win32; namespace Inspinia_MVC5.Controllers { public class DashboardsController : Controller { [DllImport("gdi32", EntryPoint = "AddFontResource")] public static extern int AddFontResourceA(string lpFileName); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int AddFontResource(string lpszFilename); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int CreateScalableFontResource(uint fdwHidden, string lpszFontRes, string lpszFontFile, string lpszCurrentPath); /// <summary> /// Installs font on the user's system and adds it to the registry so it's available on the next session /// Your font must be included in your project with its build path set to 'Content' and its Copy property /// set to 'Copy Always' /// </summary> /// <param name="contentFontName">Your font to be passed as a resource (i.e. "myfont.tff")</param> private void RegisterFont(string contentFontName) { // Creates the full path where your font will be installed Directory.CreateDirectory("C:\\MY_FONT_LOC"); var fontDestination = Path.Combine("C:\\MY_FONT_LOC", contentFontName); if (!System.IO.File.Exists(fontDestination)) { // Copies font to destination System.IO.File.Copy(Path.Combine(Server.MapPath("/fonts"), contentFontName), fontDestination, false); // Retrieves font name // Makes sure you reference System.Drawing PrivateFontCollection fontCol = new PrivateFontCollection(); fontCol.AddFontFile(fontDestination); var actualFontName = fontCol.Families[0].Name; //Add font AddFontResource(fontDestination); //Add registry entry // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", actualFontName, contentFontName, RegistryValueKind.String); } } static StudentInfo myInfo = new StudentInfo { FirstName = "Michael", LastName = "Owen", Month = 10, Year = 2018, Degree = "King", ProgramName = "Speed World" }; public ActionResult Dashboard_1() { RegisterFont("Museo 500.otf"); RegisterFont("Olde English Regular.ttf"); return View(myInfo); } /* public ActionResult diploma() { var dir = Server.MapPath("/Images"); var path = Path.Combine(dir, "p_big3.jpg"); FileStream stream = new FileStream(path, FileMode.Open); FileStreamResult result = new FileStreamResult(stream, "image/jpeg"); result.FileDownloadName = "image.jpeg"; return result; }*/ public ActionResult diploma_askworth() { Image image = Image.FromFile(Path.Combine(Server.MapPath("/Images"), "cover_final.png")); int width = image.Width; int height = image.Height; using (Graphics g = Graphics.FromImage(image)) { // do something with the Graphics (eg. write "Hello World!") string grad_str = string.Format("has been awarded {0} {1} the {2} in", myInfo.Month, myInfo.Year, myInfo.Degree); string name_str = string.Format("{0} {1}", myInfo.FirstName, myInfo.LastName); string prog_str = myInfo.ProgramName; string comm_str = "hereby certifies that"; // Create font and brush. Font nameFont = new Font("Olde English", 60); SolidBrush nameBrush = new SolidBrush(Color.FromArgb(35,21,14)); Font gradFont = new Font("Museo 500", 18); SolidBrush gradBrush = new SolidBrush(Color.FromArgb(35, 21, 14)); Font progFont = new Font("Olde English", 40); SolidBrush progBrush = new SolidBrush(Color.FromArgb(154, 27, 31)); Font commFont = new Font("Museo 500", 18); SolidBrush commBrush = new SolidBrush(Color.FromArgb(35, 21, 14)); // Create point for upper-left corner of drawing. RectangleF commRect = new RectangleF(new Point(0, height/4+16), new SizeF(width, 50)); RectangleF nameRect = new RectangleF(new Point(0, height/4+60), new SizeF(width, 100)); RectangleF gradRect = new RectangleF(new Point(0, height/2-16), new SizeF(width, 50)); RectangleF progRect = new RectangleF(new Point(0, height*4/7-18), new SizeF(width, 100)); StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Center; format.Alignment = StringAlignment.Center; g.DrawString(grad_str, gradFont, nameBrush, gradRect, format); g.DrawString(name_str, nameFont, gradBrush, nameRect, format); g.DrawString(prog_str, progFont, progBrush, progRect, format); g.DrawString(comm_str, commFont, commBrush, commRect, format); } MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return File(ms.ToArray(), "image/jpeg", myInfo.LastName + ".jpeg"); } public ActionResult diploma_james() { Image image = Image.FromFile(Path.Combine(Server.MapPath("/Images"), "second_cover.png")); int width = image.Width; int height = image.Height; using (Graphics g = Graphics.FromImage(image)) { // do something with the Graphics (eg. write "Hello World!") string grad_str = string.Format("has been awarded {0} {1} the {2} a", myInfo.Month, myInfo.Year, myInfo.Degree); string name_str = string.Format("{0} {1}", myInfo.FirstName, myInfo.LastName); string prog_str = myInfo.ProgramName; string comm_str = "hereby certifies that"; // Create font and brush. Font nameFont = new Font("Olde English", 60); SolidBrush nameBrush = new SolidBrush(Color.FromArgb(35, 21, 14)); Font gradFont = new Font("Museo 500", 18); SolidBrush gradBrush = new SolidBrush(Color.FromArgb(35, 21, 14)); Font progFont = new Font("Olde English", 40); SolidBrush progBrush = new SolidBrush(Color.FromArgb(86, 120, 212)); Font commFont = new Font("Museo 500", 18); SolidBrush commBrush = new SolidBrush(Color.FromArgb(35, 21, 14)); // Create point for upper-left corner of drawing. RectangleF commRect = new RectangleF(new Point(0, height / 4 + 16), new SizeF(width, 50)); RectangleF nameRect = new RectangleF(new Point(0, height / 4 + 60), new SizeF(width, 100)); RectangleF gradRect = new RectangleF(new Point(0, height / 2 - 16), new SizeF(width, 50)); RectangleF progRect = new RectangleF(new Point(0, height * 4 / 7 - 18), new SizeF(width, 100)); StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Center; format.Alignment = StringAlignment.Center; g.DrawString(grad_str, gradFont, nameBrush, gradRect, format); g.DrawString(name_str, nameFont, gradBrush, nameRect, format); g.DrawString(prog_str, progFont, progBrush, progRect, format); g.DrawString(comm_str, commFont, commBrush, commRect, format); } MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return File(ms.ToArray(), "image/jpeg", myInfo.LastName + ".jpeg"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMG.Common.Conditions { class InvertCondition : Condition { private ICondition _b; public InvertCondition(ICondition b) { _b = b; } public override string ToString() { return "NOT " + _b; } public override IGate Decompose(ConditionMode mode) { return Gate.Invert(_b.Decompose(mode)); } public override ICondition Clone() { return new InvertCondition(_b); } } }
using UnityEngine; namespace Project.Game { [RequireComponent(typeof(AhkitobeEngine))] public class AhkitobeAnimController : MonoBehaviour { const float locomotionAnimSmoothTime = 0.1f; public AhkitobeEngine motor; public Animator animator; // Use this for initialization void Start() { motor = GetComponent<AhkitobeEngine>(); } // Update is called once per frame void Update() { animator.SetFloat("speedPercent", motor.agent.velocity.magnitude, locomotionAnimSmoothTime, Time.deltaTime); } } }
using System; using System.Collections.Generic; using System.Text; namespace HomeAssistant.StorageSpace { class MqttConfig { public string Host { get; set; } public string Topic { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace UI.Entidades { public class Evento { public decimal id_evento { get; set; } public string nombre_evento { get; set; } public string fecha_inicio { get; set; } public string fecha_fin { get; set; } public string estado_registro { get; set; } public string usuario_creacion { get; set; } public DateTime fecha_creacion { get; set; } public string usuario_modificacion { get; set; } public DateTime? fecha_modificacion { get; set; } public string usuario { get; set; } public string operacion { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using URl_Project.Models; using URl_Project.Interfaces; using URl_Project.Service; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace URl_Project.Controllers { [Route(UrlRoutesHelper.ROUTECONTROLLER)] public class UrlController : Controller { IModificationUrl modificationUrl; public UrlController(IModificationUrl modificationUrl) { this.modificationUrl = modificationUrl; } [Route(UrlRoutesHelper.ROUTEGETURLS)] public IActionResult GetUrls() { return Ok(modificationUrl.GetAllUrlData()); } [Route(UrlRoutesHelper.ROUTEGETURL)] public IActionResult GetUrl(int id) { return Ok(modificationUrl.GetUrl(id)); } [Route(UrlRoutesHelper.ROUTECREATEURL)] public IActionResult CreateUrlData([FromBody]UrlModel value) { RequestUrlResult result = modificationUrl.CreateShortUrl(value); return Ok(result); } [HttpPut] public IActionResult Put([FromBody]UrlModel value) { return Ok(modificationUrl.UpdateUrl(value)); } [HttpDelete(UrlRoutesHelper.ROUTEDELETEURL)] public IActionResult Delete(int id) { return Ok(modificationUrl.DeleteUrl(id)); } [HttpGet (UrlRoutesHelper.ROUTEREDIRECTURL)] public IActionResult RedirectUrl(string id) { string url = modificationUrl.RedirectUrl(id); return Redirect(url); } } }
using System; using System.Collections; using System.Collections.Generic; using Cinemachine; using Sirenix.OdinInspector; using Sirenix.Utilities; using UnityEngine; using UnityEngine.InputSystem; public class AtlasShruggedAndDidTheLocomotion : MonoBehaviour, AxisState.IInputAxisProvider { [SerializeField, Range(0f, 100f)] float maxSpeed = 10f; public Vector3 currentGravity; [SerializeField, Range(0f, 10f)] float jumpHeight = 10f; [SerializeField, Range(0f, 100f)] float maxAcceleration = 10f, maxAirAcceleration = 1f; [SerializeField, Range(0f, 90f)] private float _maxGroundAngle = 45f; private float _minGroundDotProduct = 45f; [SerializeField, Range(0f, 90f)] private float _maxStairsAngle = 45f; private float _minStairsDotProduct = 45f; [SerializeField, Range(0f, 100f)] float _maxSnapSpeed = 100f; [SerializeField, Min(0f)] float _snapProbeDistance = 1f; public LayerMask snapToLayers; public LayerMask stairsMask; [SerializeField] [Range(0f,1f)] private float _contactNormalVsUpForJumpMix; public float _jumpGravityCurveButtonHeldT; public float jumpGravityCurveButtonHeldTSpeed; public AnimationCurve jumpGravityCurve; [MinMaxSlider(9.81f, 9.81f * 5.0f)] public Vector2 gravityMinMax; private Rigidbody _body; private Rigidbody _connectedBody; private Rigidbody _previousConnectedBody; private bool _jumpRequest = false; private float _jumpReqTimestamp = 0f; private float _trueJumpReqTimestamp = 0f; private float _lastGroundedTimestamp = 0f; private int _physStepsSinceLastGrounded= 0; private int _physStepsSinceLastJump= 0; [SerializeField, Range(0.05f, 1.0f)] private float _jumpWindow = 0.1f; [SerializeField, Range(0.05f, 1.0f)] private float _groundedWindow = 0.1f; public Transform VisualTransform; public Animator VisualAnimator; private Vector3 _contactNormal; private Vector3 _steepNormal; private int _groundContactCount, _steepContactCount; private bool OnSteep => _steepContactCount> 0; Vector3 lastJumpDirection = Vector3.zero; [SerializeField] private Transform _PlayerInputSpace; public bool _onStrictGround => _groundContactCount > 0; public bool OnGround => ((Time.unscaledTime - _lastGroundedTimestamp) < _groundedWindow); public bool HasFreshJumpRequest => ((Time.unscaledTime - _jumpReqTimestamp) < _jumpWindow); //Only comes from true input not this fake pogostick public bool HasTrueFreshJumpRequest => ((Time.unscaledTime - _trueJumpReqTimestamp) < _jumpWindow); public Controls controls; private void OnEnable() { controls = new Controls(); controls.Enable(); controls.CharacterController.JumpHeld.Enable(); controls.CharacterController.Jump.Enable(); controls.CharacterController.Movement.Enable(); controls.CharacterController.CameraInput.Enable(); } private void OnDisable() { controls.CharacterController.Jump.Disable(); controls.CharacterController.JumpHeld.Disable(); controls.CharacterController.Movement.Disable(); controls.CharacterController.CameraInput.Disable(); controls.Disable(); controls = null; } private void OnValidate() { _minGroundDotProduct = Mathf.Cos(Mathf.Deg2Rad * _maxGroundAngle); _minStairsDotProduct = Mathf.Cos(Mathf.Deg2Rad * _maxStairsAngle); } private void Awake() { OnValidate(); } // Start is called before the first frame update private int _XCamAxis = 0; private int _YCamAxis = 1; void Start() { _body = GetComponent<Rigidbody>(); if (_cinemachine != null) { _cinemachine.m_XAxis.SetInputAxisProvider(_XCamAxis,this); _cinemachine.m_YAxis.SetInputAxisProvider(_YCamAxis,this); } } private void OnCollisionEnter(Collision other) { EvaluateCollision(other); } private void OnCollisionExit(Collision other) { } private void OnCollisionStay(Collision other) { EvaluateCollision(other); } void EvaluateCollision(Collision other) { float minDot = getMinDot(other.gameObject.layer); for (int i = 0; i < other.contactCount; i++) { Vector3 normal = other.contacts[i].normal; if (normal.y >= minDot) { _groundContactCount++; _lastGroundedTimestamp = Time.unscaledTime; _contactNormal += normal; _connectedBody = other.rigidbody; } else if (normal.y > -0.01f) { _steepContactCount++; _steepNormal += normal; if (_connectedBody == null) { _connectedBody = other.rigidbody; } } } } bool CheckForSteepContacts() { if (_steepContactCount > 1) { _steepNormal.Normalize(); if (_steepNormal.y >= _minGroundDotProduct) { _groundContactCount++; _contactNormal = _steepNormal; return true; } } return false; } Vector3 velocity = new Vector3(0f,0f,0f); private Vector3 desiredVelocity,_connectionVelocity,_connectionWorldPosition,_connectionLocalPosition; [SerializeField] private CinemachineFreeLook _cinemachine; Vector2 _movementInput = new Vector2(0f,0f); //until we get input up and running Vector2 _cameraInput = new Vector2(0f,0f); //until we get input up and running public float GetAxisValue(int axis) { if (axis == _XCamAxis) { return _cameraInput.x; } if (axis == _YCamAxis) { return _cameraInput.y; } return 0f; } void Update() { _cameraInput = controls.CharacterController.CameraInput.ReadValue<Vector2>(); _cameraInput= Vector2.ClampMagnitude(_cameraInput,1.0f); _movementInput = controls.CharacterController.Movement.ReadValue<Vector2>(); _movementInput = Vector2.ClampMagnitude(_movementInput,1.0f); if (_PlayerInputSpace != null) { Vector3 fwd = _PlayerInputSpace.forward; fwd.y = 0.0f; fwd.Normalize(); Vector3 right = _PlayerInputSpace.right; right.y = 0.0f; right.Normalize(); desiredVelocity = (right * _movementInput.x + _movementInput.y * fwd )*maxSpeed; } else { desiredVelocity = new Vector3(_movementInput.x, 0f, _movementInput.y) * maxSpeed; } var jumpButtonHeld = controls.CharacterController.JumpHeld.ReadValue<float>() > 0.1f; var jumpButtonPressed= controls.CharacterController.Jump.triggered; if (jumpButtonHeld) { _jumpGravityCurveButtonHeldT += jumpGravityCurveButtonHeldTSpeed * Time.deltaTime; float evaluatedGravity = jumpGravityCurve.Evaluate(_jumpGravityCurveButtonHeldT); currentGravity = new Vector3(0f,-Mathf.Lerp(gravityMinMax.x,gravityMinMax.y,evaluatedGravity),0f); } else { //max gravity when not held _jumpGravityCurveButtonHeldT = 0f; currentGravity = new Vector3(0f, -gravityMinMax.y ,0f); } if (jumpButtonPressed) { _jumpReqTimestamp = Time.unscaledTime; _trueJumpReqTimestamp= Time.unscaledTime; _jumpRequest = true; } Debug.DrawLine(transform.position,transform.position + lastJumpDirection*3.0f,Color.magenta); //todo transfer states to animator / character //HelmettaVisualAnimator?.SetBool("InWallSlide",OnSteep && !OnGround); } private void FixedUpdate() { UpdateState(); AdjustVelocity(); ClearState(); } private int _airFramesCount = 0; void ClearState() { _contactNormal = _steepNormal = _connectionVelocity = Vector3.zero; _groundContactCount =_steepContactCount = 0; _previousConnectedBody = _connectedBody; _connectedBody = null; } private void UpdateState() { _physStepsSinceLastGrounded += 1; if (_connectedBody) { if (_connectedBody.isKinematic || _connectedBody.mass >= _body.mass) { UpdateConnectionState(); } } if (_physStepsSinceLastGrounded >= 2 && OnGround) { Land(); } velocity = _body.velocity; if (OnGround || SnapToGround() || CheckForSteepContacts()) { _contactNormal.Normalize(); _physStepsSinceLastGrounded = 0; } else { _contactNormal = Vector3.up; } if (_jumpRequest) { //if we request jumps in the air - at some point , that jump command will be too old. if ((HasFreshJumpRequest) && Jump()) { _jumpRequest = false; } else if (!HasFreshJumpRequest && !OnGround) { _jumpRequest = false; } } } void UpdateConnectionState() { if (_connectedBody == _previousConnectedBody) { Vector3 connectionMovement = _connectedBody.transform.TransformPoint(_connectionLocalPosition) - _connectionWorldPosition; _connectionVelocity = connectionMovement / Time.deltaTime; } _connectionWorldPosition = _body.position; _connectionLocalPosition = _connectedBody.transform.InverseTransformPoint(_connectionWorldPosition); } private bool SnapToGround() { if (_physStepsSinceLastGrounded > 1 || HasFreshJumpRequest) { return false; } float speed = velocity.magnitude; if (speed > _maxSnapSpeed) { return false; } if (!Physics.Raycast(_body.position, Vector3.down, out RaycastHit hit,_snapProbeDistance,snapToLayers)) { return false; } if (hit.normal.y < getMinDot(hit.collider.gameObject.layer)) { return false; } _physStepsSinceLastGrounded = 1; _contactNormal = hit.normal; _connectedBody = hit.rigidbody; float dot = Vector3.Dot(velocity, hit.normal); if (dot > 0f) { velocity = (velocity - hit.normal * dot).normalized * speed; } return true; } void AdjustVelocity() { Vector3 xAxis = ProjectOnContactPlane(Vector3.right).normalized; Vector3 zAxis = ProjectOnContactPlane(Vector3.forward).normalized; Vector3 relativeVelocity = velocity - _connectionVelocity; float currentX = Vector3.Dot(relativeVelocity, xAxis); float currentZ = Vector3.Dot(relativeVelocity, zAxis); float acceleration = _onStrictGround ? maxAcceleration : maxAirAcceleration; float maxSpeedChange = acceleration * Time.deltaTime; float newX = Mathf.MoveTowards(currentX, desiredVelocity.x, maxSpeedChange); float newZ = Mathf.MoveTowards(currentZ, desiredVelocity.z, maxSpeedChange); velocity += currentGravity*Time.deltaTime; velocity += xAxis*(newX - currentX) + zAxis * (newZ - currentZ); float anyMotion = velocity.x + velocity.z; if (Mathf.Abs(anyMotion) > 0.1f) { Vector3 velosDirection = new Vector3(velocity.x,0f,velocity.z).normalized; //todo Visual connection //HelmettaVisual?.LookAt(_body.position + velosDirection*3.0f,Vector3.up); } else { //todo visual connection //HelmettaVisual.localRotation = Quaternion.identity; //HelmettaVisual?.Rotate(Vector3.forward,pogoAngleInputTilt,Space.Self); } if (OnSteep && !OnGround) { //todo visual connection //HelmettaVisual?.LookAt(_body.position + _steepNormal*3.0f,Vector3.up); } float anyDesiredMotion = desiredVelocity.magnitude; float runSpeedT = Vector3.Magnitude(new Vector3(newX,0f,newZ)) / maxSpeed; //todo connect with visuals /* HelmettaVisualAnimator?.SetFloat("Speed",runSpeedT); HelmettaVisualAnimator?.SetFloat("UpwardsMotion",velocity.y > 0.0f ? 1.0f : 0.0f); */ Vector3 displacement = velocity * Time.deltaTime; _body.velocity = velocity; } bool Jump() { if (OnGround) { lastJumpDirection = Vector3.Lerp(_contactNormal,Vector3.up,_contactNormalVsUpForJumpMix); } else if (OnSteep) { lastJumpDirection = (_steepNormal + Vector3.up).normalized; } else { return false; } lastJumpDirection = (lastJumpDirection + Vector3.up).normalized; float jumpH = jumpHeight; currentGravity.y = - gravityMinMax.y; float jumpSpeed= Mathf.Sqrt(-2f * currentGravity.y * jumpH); float priorToClamping = jumpSpeed; float alignedSpeed = Vector3.Dot(velocity, lastJumpDirection); if (alignedSpeed > 0f) { jumpSpeed = Mathf.Max(jumpSpeed - alignedSpeed, 0f); } //Because we would like wall jumps that are arcadey - we will remove current gravity from wall-jumps. //this is likeley something to tweak later depending on how we want them jumps to feel //Remove gravity if (OnSteep) { Vector3 normGrav = currentGravity.normalized; float velosGravity = Vector3.Dot(velocity, normGrav); velocity -= normGrav* velosGravity; } velocity += lastJumpDirection * jumpSpeed; _physStepsSinceLastJump = 0; //todo animation states //HelmettaVisualAnimator?.SetTrigger("Jump"); return true; } void Land() { //Debug.Log("We think we landed just about now.."); //HelmettaVisualAnimator?.SetTrigger("Landed"); } float getMinDot(int layer) { return (stairsMask & (1 << layer)) == 0 ? _minGroundDotProduct : _minStairsDotProduct; } Vector3 ProjectOnContactPlane(Vector3 vector) { return vector - _contactNormal * Vector3.Dot(vector, _contactNormal); } }
using Common.DbTools; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UI_KontrolerSistema { public static class Data { public static DbLocalController Dblc = new DbLocalController(); public static DbSystemController Dbsc = new DbSystemController(); public static DbGenerator dbgen = new DbGenerator(); public static bool RunningFlag = true; public static string DateFormat = "dd-MM-yyyy"; } }
using ASM.Entity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; 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; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace ASM.Views { public sealed partial class ListMusic : Page { private ObservableCollection<Song> listSong; public static string tokenKey = null; //private int _currentIndex; internal ObservableCollection<Song> ListSong { get => listSong; set => listSong = value; } private Song currentSong; //private bool _isPlaying = false; public ListMusic() { this.InitializeComponent(); ReadToken(); this.currentSong = new Song(); this.ListSong = new ObservableCollection<Song>(); HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic iBi1orSXvZisyF48jdnnOYmZURdkyz3rv1Jg0KBhFLsJOa90Tlu6DxxBKPYjm4b6"); HttpResponseMessage responseMessage = httpClient.GetAsync(Services.ServiceUrl.GET_SONG).Result; string content = responseMessage.Content.ReadAsStringAsync().Result; Debug.WriteLine(content); if (responseMessage.StatusCode == HttpStatusCode.OK) { ObservableCollection<Song> songResponse = JsonConvert.DeserializeObject<ObservableCollection<Song>>(content); foreach (var song in songResponse) { this.ListSong.Add(song); } Debug.WriteLine("Success"); } else { Entity.ErrorResponse errorResponse = JsonConvert.DeserializeObject<Entity.ErrorResponse>(content); foreach (var key in errorResponse.error.Keys) { if (this.FindName(key) is TextBlock textBlock) { textBlock.Text = errorResponse.error[key]; } } } } public static async void ReadToken() { if (tokenKey == null) { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync("token.txt"); string content = await FileIO.ReadTextAsync(file); Token account_token = JsonConvert.DeserializeObject<Token>(content); Debug.WriteLine("token la: " + account_token.token); tokenKey = account_token.token; } } public async void GetSong() { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + tokenKey); var response = httpClient.GetAsync(Services.ServiceUrl.GET_SONG); var result = await response.Result.Content.ReadAsStringAsync(); Debug.WriteLine(result); ObservableCollection<Song> list = JsonConvert.DeserializeObject<ObservableCollection<Song>>(result); foreach (var songs in list) { this.ListSong.Add(songs); } Debug.WriteLine(result); } private async void btn_add(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); this.currentSong.name = this.txt_name.Text; this.currentSong.thumbnail = this.txt_thumbnail.Text; this.currentSong.description = this.txt_description.Text; this.currentSong.singer = this.txt_singer.Text; this.currentSong.author = this.txt_author.Text; this.currentSong.link = this.txt_link.Text; var jsonMusic = JsonConvert.SerializeObject(this.currentSong); StringContent content = new StringContent(jsonMusic, Encoding.UTF8, "application/json"); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + tokenKey); var response = httpClient.PostAsync(Services.ServiceUrl.REGISTER_SONG, content); var result = await response.Result.Content.ReadAsStringAsync(); if (response.Result.StatusCode == HttpStatusCode.Created) { Debug.WriteLine("Success"); } else { ErrorResponse errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(result); if (errorResponse.error.Count > 0) { foreach (var key in errorResponse.error.Keys) { var objBykey = this.FindName(key); var value = errorResponse.error[key]; if (objBykey != null) { TextBlock textBlock = objBykey as TextBlock; textBlock.Text = "* " + value; } } } } this.txt_name.Text = String.Empty; this.txt_description.Text = String.Empty; this.txt_singer.Text = String.Empty; this.txt_author.Text = String.Empty; this.txt_thumbnail.Text = String.Empty; this.txt_link.Text = String.Empty; } private void btn_reset(object sender, RoutedEventArgs e) { this.txt_name.Text = String.Empty; this.txt_description.Text = String.Empty; this.txt_singer.Text = String.Empty; this.txt_author.Text = String.Empty; this.txt_thumbnail.Text = String.Empty; this.txt_link.Text = String.Empty; } } }
using Microsoft.AspNet.Identity; using ParrisConnection.ServiceLayer.Data; using ParrisConnection.ServiceLayer.Services.Status.Save; using System.Web.Mvc; namespace ParrisConnection.Controllers { public class SingleStatusController : Controller { private readonly IStatusSaveService _statusSaveService; public SingleStatusController(IStatusSaveService statusSaveService) { _statusSaveService = statusSaveService; } public ActionResult Index() { return View(); } [HttpPost] public ActionResult AddStatus(StatusData status) { status.UserId = User != null ? User.Identity.GetUserId() : ""; _statusSaveService.SaveStatus(status); return RedirectToAction("Index", "Wall"); } } }
using Tomelt.Events; namespace Tomelt.Indexing { public interface IIndexNotifierHandler : IEventHandler { void UpdateIndex(string indexName); } }
using System; namespace C__Project { class First_Enum { enum Months { None, January, // 1 February, // 2 March, // 3 April, // 4 May, // 5 June, // 6 July // 7 } static void Ninth(string[] args) { string choice; Console.WriteLine("Enter a month."); choice = Console.ReadLine(); Console.WriteLine("Calculating..."); int myNum = (int) Months.May; Console.WriteLine(myNum); } } }
using System.Reflection; using System.Linq; namespace ModelTransformationComponent { /// <summary> /// Префиксное дерево системных правил генерации /// </summary> public class SystemTrieSingleton { private static SystemTrieSingleton instance; private static Trie<SystemRule> trie; private SystemTrieSingleton() { trie = new Trie<SystemRule>(); System.Type[] types = Assembly.GetExecutingAssembly().GetTypes(); System.Type[] SystemRuleTypes = (from System.Type type in types where type.IsSubclassOf(typeof(SystemRule)) select type) .ToArray(); SystemRule rule; foreach (System.Type t in SystemRuleTypes) { rule = (SystemRule)System.Activator.CreateInstance(t); trie.Insert(rule,rule.Literal); } } /// <summary> /// Поиск правила /// </summary> /// <param name="text">Название правила</param> /// <param name="charcnt">Количество найденых символов</param> /// <param name="Suggestion">Возможное название</param> /// <returns></returns> public SystemRule Search(string text, out int charcnt, out string Suggestion) { return trie.Search(text, out charcnt, out Suggestion); } /// <summary> /// /// </summary> /// <returns></returns> public static SystemTrieSingleton getInstance() { if (instance == null) instance = new SystemTrieSingleton(); return instance; } } }
#if UNITY_EDITOR using System.Collections; using System.Collections.Generic; using DChild.Gameplay.Objects.Characters.Enemies; using Sirenix.OdinInspector; using UnityEngine; namespace DChildDebug { public class QueenBeeController : DebugBossController<QueenBee> { //[Button("Stinger Thrust")] //private void StringerThrust() //{ // m_boss.ForceStopAttack(); // m_boss.DoStingerThrust(); //} //[Button("Minion Rush")] //private void MinionRush() //{ // m_boss.ForceStopAttack(); // m_boss.DoMinionRush(); //} } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Web; using SSISTeam9.Models; using SSISTeam9.DAO; using System.Threading.Tasks; namespace SSISTeam9.Services { public class AdjVoucherService { public static void CreateAdjVoucher(long adjId, long itemId, int qty) { AdjVoucherDAO.CreateAdjVoucher(adjId, itemId, qty); } public static long? GetLastId() { return AdjVoucherDAO.GetLastId(); } public static List<AdjVoucher> GetAdjByStatus(int status) { List<AdjVoucher> adjVouchers = new List<AdjVoucher>(); adjVouchers = AdjVoucherDAO.GetAdjByStatus(status); if(adjVouchers != null) { foreach(AdjVoucher adj in adjVouchers) { adj.ItemCode = CatalogueService.GetCatalogueById(adj.ItemId).ItemCode; } } return adjVouchers; } public static void UpdateReason(AdjVoucher adjVoucher) { AdjVoucherDAO.UpdateReason(adjVoucher); } public static void UpdateStatus(long adjId, int status) { AdjVoucherDAO.UpdateStatus(adjId, status); } public static void AuthoriseBy(long adjId, long empId) { AdjVoucherDAO.AuthoriseBy(adjId,empId); } public static List<AdjVoucher> GetAdjByAdjId(long adjId) { return AdjVoucherDAO.GetAdjByAdjId(adjId); } } }
using GraphicalEditor.Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using GraphicalEditor.DTO; using GraphicalEditor.Enumerations; namespace GraphicalEditor { /// <summary> /// Interaction logic for ScheduleForRoomDialog.xaml /// </summary> public partial class ScheduleForRoomDialog : Window { RoomService _roomService; AppointmentService _appointmentService; EquipmentService _equipmentService; RenovationService _renovationService; public int RoomId { get; set; } public ScheduleForRoomDialog(int roomId) { InitializeComponent(); DataContext = this; _roomService = new RoomService(); _appointmentService = new AppointmentService(); _equipmentService = new EquipmentService(); _renovationService = new RenovationService(); RoomId = roomId; GetDataAndDisplayItInScheduledActionsDataGrid(); } private void ShowActionSuccessfullyCancelledDialog() { InfoDialog infoDialog = new InfoDialog("Uspešno ste otkazali zakazanu akciju!"); infoDialog.ShowDialog(); } private void GetDataAndDisplayItInScheduledActionsDataGrid() { List<RoomSchedulesDTO> roomSchedulesDTOs = _roomService.GetRoomSchedules(RoomId); RoomScheduledActionsDataGrid.ItemsSource = roomSchedulesDTOs; } private void CloseButton_Click(object sender, RoutedEventArgs e) { this.Close(); } private void ShowDetailsForScheduledActionButton_Click(object sender, RoutedEventArgs e) { RoomSchedulesDTO selectedScheduledAction = (RoomSchedulesDTO)RoomScheduledActionsDataGrid.SelectedItem; if (selectedScheduledAction.ScheduleType == ScheduleType.Appointment) { AppointmentInRoomMoreDetailsDialog appointmentInRoomMoreDetailsDialog = new AppointmentInRoomMoreDetailsDialog(selectedScheduledAction.Id); appointmentInRoomMoreDetailsDialog.ShowDialog(); } else if (selectedScheduledAction.ScheduleType == ScheduleType.EquipmentTransfer) { EquipmentRelocationInRoomMoreDetailsDialog equipmentRelocationInRoomMoreDetailsDialog = new EquipmentRelocationInRoomMoreDetailsDialog(selectedScheduledAction.Id); equipmentRelocationInRoomMoreDetailsDialog.ShowDialog(); } else if (selectedScheduledAction.ScheduleType == ScheduleType.Renovation) { RenovationInRoomMoreDetailsDialog renovationInRoomMoreDetailsDialog = new RenovationInRoomMoreDetailsDialog(selectedScheduledAction.Id); renovationInRoomMoreDetailsDialog.ShowDialog(); } GetDataAndDisplayItInScheduledActionsDataGrid(); } private void CancelScheduledActionButton_Click(object sender, RoutedEventArgs e) { RoomSchedulesDTO selectedScheduledAction = (RoomSchedulesDTO)RoomScheduledActionsDataGrid.SelectedItem; if(selectedScheduledAction.ScheduleType == ScheduleType.Appointment) { _appointmentService.DeleteAppointment(selectedScheduledAction.Id); } else if(selectedScheduledAction.ScheduleType == ScheduleType.EquipmentTransfer) { _equipmentService.DeleteEquipmentTransfer(selectedScheduledAction.Id); } else if(selectedScheduledAction.ScheduleType == ScheduleType.Renovation) { _renovationService.DeleteRenovation(selectedScheduledAction.Id); } GetDataAndDisplayItInScheduledActionsDataGrid(); ShowActionSuccessfullyCancelledDialog(); } } }
using Exiled.API.Features; using Exiled.Events.EventArgs; namespace CustomDamage { class EventHandlers { CustomDamagePlugin Plugin; public EventHandlers(CustomDamagePlugin plugin) { Plugin = plugin; } public void OnSendingRemoteAdminCommand(SendingRemoteAdminCommandEventArgs ev) { switch (ev.Name) { case "scd": case "setdamage": { ev.IsAllowed = false; if (ev.Arguments.Count < 1) { ev.ReplyMessage = "No player id"; break; } if (ev.Arguments.Count < 2) { ev.ReplyMessage = "No damage value"; break; } Player player; if (int.TryParse(ev.Arguments[0], out int id)) { player = Player.Get(id); } else { player = Player.Get(ev.Arguments[0]); } if (player == null) { ev.ReplyMessage = "Player not founded"; break; } if (!float.TryParse(ev.Arguments[1], out float damage)) { ev.ReplyMessage = "Uncorrect damage value"; break; } Plugin.PlayerToCustomDamage.Remove(player.Id); Plugin.PlayerToCustomDamage.Add(player.Id, damage); ev.ReplyMessage = "Custom damage added"; } break; case "rcd": case "resetcustomdamage": { ev.IsAllowed = false; if (ev.Arguments.Count < 1) { ev.ReplyMessage = "No player id"; break; } Player player; if (int.TryParse(ev.Arguments[0], out int id)) { player = Player.Get(id); } else { player = Player.Get(ev.Arguments[0]); } if (player == null) { ev.ReplyMessage = "Player not founded"; break; } Plugin.PlayerToCustomDamage.Remove(player.Id); ev.ReplyMessage = "Custom damage reseted"; } break; } } public void OnWaitingForPlayers() { Plugin.PlayerToCustomDamage.Clear(); } public void OnHurting(HurtingEventArgs ev) { if (ev.Attacker == null) { return; } if (!Plugin.PlayerToCustomDamage.TryGetValue(ev.Attacker.Id, out float damage)) { return; } ev.Amount = damage; } } }
using AHAO.TPLMS.Contract; using AHAO.TPLMS.DataBase; using AHAO.TPLMS.Entitys; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AHAO.TPLMS.Repository { public class ModuleRepository : BaseRepository<Module>, IModuleRepository { public ModuleRepository(TPLMSDbContext m_context) : base(m_context) { } public IEnumerable<Module> LoadModules(int pageindex, int pagesize) { return Context.Module.OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize); } public IEnumerable<Module> GetModules(string userName) { var moduleList = Context.Module.ToArray(); return moduleList; } public bool Delete(string ids) { var idList = ids.Split(','); var moduleList = Context.Module.Where(m => idList.Contains(m.Id.ToString()); bool result = true; Delete(moduleList.ToArray()); return result; } } }
using System; using System.Collections.Generic; namespace Zkull.Fuzzy { public enum DefuzzifyMethod { MAX_AV = 0, CENTROID = 1, } public class FuzzyModule { private Dictionary<string, FuzzyVariable> m_dicFuzzyVarialbe = new Dictionary<string, FuzzyVariable>(); private List<FuzzyRule> m_lstRules = new List<FuzzyRule>(); private int m_sample = 15; public void SetSample(int val) { m_sample = val; } public FuzzyVariable CreateFLV(string name) { m_dicFuzzyVarialbe[name] = new FuzzyVariable(); return m_dicFuzzyVarialbe[name]; } public void AddRule(FuzzyTerm antecedent, FuzzyTerm consequence) { m_lstRules.Add(new FuzzyRule(antecedent, consequence)); } public void Fuzzify(string name , float val) { FuzzyVariable fuzzyVal = null; if(m_dicFuzzyVarialbe.TryGetValue(name, out fuzzyVal)) { m_dicFuzzyVarialbe[name].Fuzzify(val); } } private void SetConfidencesOfConsequentsToZero() { for(int i = 0; i < m_lstRules.Count; i++) { m_lstRules[i].SetConfidenceOfConsequentToZero(); } } public float Defuzzify(string name, DefuzzifyMethod method) { FuzzyVariable fuzzyVal = null; if(m_dicFuzzyVarialbe.TryGetValue(name, out fuzzyVal)) { for(int i = 0 ; i < m_lstRules.Count; i++) { float value = m_lstRules[i].Calculate(); UnityEngine.Debug.Log("rule " + i + " " + value); } switch(method) { case DefuzzifyMethod.CENTROID: return m_dicFuzzyVarialbe[name].DeFuzzifyCentroid(m_sample); case DefuzzifyMethod.MAX_AV: return m_dicFuzzyVarialbe[name].DeFuzzifyMaxAv(); } } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryMethod.Employes { public sealed class Nurse : Employee { public Nurse() { _price = 12; } public override float CalculateMonthPrice(int hoursInMonth) { return _price * hoursInMonth * (float)1.2; } } }
public class Solution { public int TrailingZeroes(int n) { int res = 0; int bas = 5; while (n >= bas) { res += n / bas; bas *= 5; } return res; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AtualizarBorda : MonoBehaviour { public Image minhaImagem; public float speed = 2.0f; public float TempoDeEspera = 5.0f; public static bool repeat = true; public float guardarValor; public IEnumerator Start() { while (repeat) { yield return ChangeFill(0.0f, 1.0f, TempoDeEspera); yield return ChangeFill(1.0f, 0.0f, TempoDeEspera); } if (!repeat) { yield return ChangeFill(guardarValor, guardarValor, TempoDeEspera); } } void Update() { if (!bola.podeChutar) { StartCoroutine(Start()); } } public IEnumerator ChangeFill(float start, float end, float time) { float i = 0.0f; float rate = (1.0f / time) * speed; while (i < 1.0f) { i += Time.deltaTime * rate; minhaImagem.fillAmount = Mathf.Lerp(start, end, i); yield return null; } } public void PararBorda() { guardarValor = minhaImagem.fillAmount; repeat = false; BarraDeAltura.liberar = true; //bola.podeChutar = true; } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace ServiceDeskSVC.DataAccess.Models.Mapping { public class HelpDesk_Tasks_RelatedTasksMap : EntityTypeConfiguration<HelpDesk_Tasks_RelatedTasks> { public HelpDesk_Tasks_RelatedTasksMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); // Table & Column Mappings this.ToTable("HelpDesk_Tasks_RelatedTasks"); this.Property(t => t.Id).HasColumnName("Id"); this.Property(t => t.TaskID).HasColumnName("TaskID"); this.Property(t => t.RelatedTaskID).HasColumnName("RelatedTaskID"); } } }
using System; namespace Microsoft.UnifiedPlatform.Service.Configuration.ConfitService { public class ConfitServiceResponseModel { public string Data { get; set; } public string ErrorMessage { get; set; } public string ErrorCode { get; set; } public DateTime TimeStamp { get; set; } public string Source { get; set; } } }
using OrgMan.Data.Repository.Repositorybase; using OrgMan.DataContracts.Repository.RepositoryBase; using OrgMan.DataModel; namespace OrgMan.Data.Repository { public class EmailRepository : GenericRepository<Email>, IGenericRepository<Email> { public EmailRepository(OrgManEntities context) : base(context) { } } }
using Obstacles; using UnityEngine; namespace Collisions { public class WallDetector : MonoBehaviour { private void OnTriggerEnter(Collider other) { var wall = other.GetComponent<Wall>(); if(wall) Destroy(wall.gameObject); } } }
using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Ast; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.TypeSystem.Implementation; using Mono.Cecil; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using D = Shipwreck.TypeScriptModels.Declarations; namespace Shipwreck.TypeScriptModels.Decompiler { public partial class ILTranslator : IAstVisitor<ILTranslationContext, IEnumerable<Syntax>> { private List<D.IRootStatement> _Statements; public List<D.IRootStatement> Statements => _Statements ?? (_Statements = new List<D.IRootStatement>()); private static ILTranslationConvention[] _DefaultConventions; private List<ILTranslationConvention> _Conventions; public List<ILTranslationConvention> Conventions => _Conventions ?? (_Conventions = DefaultConventions.ToList()); private CSharpProjectContent _Project; internal CSharpProjectContent Project => _Project ?? (_Project = new CSharpProjectContent()); public static ILTranslationConvention[] DefaultConventions { get { if (_DefaultConventions == null) { _DefaultConventions = new ILTranslationConvention[] { new MethodNameConvention(typeof(object).GetMethod(nameof(ToString)), "toString"), new EventConvention(), new DelegateConvention(), new MathConventionSet() }; } return _DefaultConventions; } } public IEnumerable<Syntax> Translate(Type clrType) { using (var ar = new AppDomainAssemblyResolver()) using (var fs = new FileStream(clrType.Assembly.Location, FileMode.Open, FileAccess.Read)) { var ad = AssemblyDefinition.ReadAssembly(fs, new ReaderParameters() { AssemblyResolver = ar }); var b = new AstBuilder(new DecompilerContext(ad.MainModule) { Settings = new DecompilerSettings() { AsyncAwait = true, AutomaticProperties = true, ExpressionTrees = true, ForEachStatement = true, LockStatement = true, MakeAssignmentExpressions = true, QueryExpressions = false, UsingDeclarations = false, YieldReturn = true } }); foreach (var a in clrType.Assembly.GetReferencedAssemblies()) { if (!Project.AssemblyReferences.OfType<DefaultAssemblyReference>().Any(e => a.Name.Equals(e.ToString()))) { Project.AddAssemblyReferences(new DefaultAssemblyReference(a.FullName)); } } b.DecompileMethodBodies = true; b.AddType(ad.MainModule.GetType(clrType.FullName.Replace('+', '/'))); b.RunTransformations(); b.SyntaxTree.FileName = "temp.cs"; foreach (var c in Conventions) { c.ApplyTo(this); } return b.SyntaxTree.AcceptVisitor(this, new ILTranslationContext(this, b.SyntaxTree)).ToArray(); } } public event EventHandler<VisitingEventArgs<AstNode>> VisitingNode; private IEnumerable<Syntax> OnVisiting<T>(ILTranslationContext data, T node, EventHandler<VisitingEventArgs<T>> handler) where T : AstNode { var nodeHandler = VisitingNode; if (nodeHandler != null) { var e = new VisitingEventArgs<AstNode>(data, node); nodeHandler(this, e); if (e.Results != null) { return e.Results; } } if (handler != null) { var e = new VisitingEventArgs<T>(data, node); handler(this, e); if (e.Results != null) { return e.Results; } } return null; } private IEnumerable<Syntax> OnVisited<T>(ILTranslationContext data, T node, EventHandler<VisitedEventArgs<T>> handler, Syntax result) where T : AstNode => OnVisited(data, node, handler, new[] { result }); private IEnumerable<Syntax> OnVisited<T>(ILTranslationContext data, T node, EventHandler<VisitedEventArgs<T>> handler, IEnumerable<Syntax> results) where T : AstNode { if (handler != null) { var e = new VisitedEventArgs<T>(data, node, results); handler(this, e); return e.Results ?? results; } return results; } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitAccessor(Accessor accessor, ILTranslationContext data) => OnVisiting(data, accessor, VisitingAccessor) ?? OnVisited(data, accessor, VisitedAccessor, TranslateAccessor(accessor, data)); protected virtual IEnumerable<Syntax> TranslateAccessor(Accessor accessor, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(Accessor)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, ILTranslationContext data) => OnVisiting(data, anonymousMethodExpression, VisitingAnonymousMethodExpression) ?? OnVisited(data, anonymousMethodExpression, VisitedAnonymousMethodExpression, TranslateAnonymousMethodExpression(anonymousMethodExpression, data)); protected virtual IEnumerable<Syntax> TranslateAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(AnonymousMethodExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, ILTranslationContext data) => OnVisiting(data, anonymousTypeCreateExpression, VisitingAnonymousTypeCreateExpression) ?? OnVisited(data, anonymousTypeCreateExpression, VisitedAnonymousTypeCreateExpression, TranslateAnonymousTypeCreateExpression(anonymousTypeCreateExpression, data)); protected virtual IEnumerable<Syntax> TranslateAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(AnonymousTypeCreateExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, ILTranslationContext data) => OnVisiting(data, arrayCreateExpression, VisitingArrayCreateExpression) ?? OnVisited(data, arrayCreateExpression, VisitedArrayCreateExpression, TranslateArrayCreateExpression(arrayCreateExpression, data)); protected virtual IEnumerable<Syntax> TranslateArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ArrayCreateExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, ILTranslationContext data) => OnVisiting(data, arrayInitializerExpression, VisitingArrayInitializerExpression) ?? OnVisited(data, arrayInitializerExpression, VisitedArrayInitializerExpression, TranslateArrayInitializerExpression(arrayInitializerExpression, data)); protected virtual IEnumerable<Syntax> TranslateArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ArrayInitializerExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitArraySpecifier(ArraySpecifier arraySpecifier, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ArraySpecifier)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitAsExpression(AsExpression asExpression, ILTranslationContext data) => OnVisiting(data, asExpression, VisitingAsExpression) ?? OnVisited(data, asExpression, VisitedAsExpression, TranslateAsExpression(asExpression, data)); protected virtual IEnumerable<Syntax> TranslateAsExpression(AsExpression asExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(AsExpression)); } private string GetTypeName(AstType type) { var tr = type.Annotations.OfType<TypeReference>()?.FirstOrDefault(); if (tr != null) { return tr.FullName; } return ((SimpleType)type).Identifier; } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCaseLabel(CaseLabel caseLabel, ILTranslationContext data) => OnVisiting(data, caseLabel, VisitingCaseLabel) ?? OnVisited(data, caseLabel, VisitedCaseLabel, TranslateCaseLabel(caseLabel, data)); protected virtual IEnumerable<Syntax> TranslateCaseLabel(CaseLabel caseLabel, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CaseLabel)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCastExpression(CastExpression castExpression, ILTranslationContext data) => OnVisiting(data, castExpression, VisitingCastExpression) ?? OnVisited(data, castExpression, VisitedCastExpression, TranslateCastExpression(castExpression, data)); protected virtual IEnumerable<Syntax> TranslateCastExpression(CastExpression castExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CastExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCatchClause(CatchClause catchClause, ILTranslationContext data) => OnVisiting(data, catchClause, VisitingCatchClause) ?? OnVisited(data, catchClause, VisitedCatchClause, TranslateCatchClause(catchClause, data)); protected virtual IEnumerable<Syntax> TranslateCatchClause(CatchClause catchClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CatchClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCheckedExpression(CheckedExpression checkedExpression, ILTranslationContext data) => OnVisiting(data, checkedExpression, VisitingCheckedExpression) ?? OnVisited(data, checkedExpression, VisitedCheckedExpression, TranslateCheckedExpression(checkedExpression, data)); protected virtual IEnumerable<Syntax> TranslateCheckedExpression(CheckedExpression checkedExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CheckedExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCheckedStatement(CheckedStatement checkedStatement, ILTranslationContext data) => OnVisiting(data, checkedStatement, VisitingCheckedStatement) ?? OnVisited(data, checkedStatement, VisitedCheckedStatement, TranslateCheckedStatement(checkedStatement, data)); protected virtual IEnumerable<Syntax> TranslateCheckedStatement(CheckedStatement checkedStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CheckedStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitComment(Comment comment, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(Comment)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitComposedType(ComposedType composedType, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ComposedType)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitConditionalExpression(ConditionalExpression conditionalExpression, ILTranslationContext data) => OnVisiting(data, conditionalExpression, VisitingConditionalExpression) ?? OnVisited(data, conditionalExpression, VisitedConditionalExpression, TranslateConditionalExpression(conditionalExpression, data)); protected virtual IEnumerable<Syntax> TranslateConditionalExpression(ConditionalExpression conditionalExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ConditionalExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitConstraint(Constraint constraint, ILTranslationContext data) => OnVisiting(data, constraint, VisitingConstraint) ?? OnVisited(data, constraint, VisitedConstraint, TranslateConstraint(constraint, data)); protected virtual IEnumerable<Syntax> TranslateConstraint(Constraint constraint, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(Constraint)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer, ILTranslationContext data) => OnVisiting(data, constructorInitializer, VisitingConstructorInitializer) ?? OnVisited(data, constructorInitializer, VisitedConstructorInitializer, TranslateConstructorInitializer(constructorInitializer, data)); protected virtual IEnumerable<Syntax> TranslateConstructorInitializer(ConstructorInitializer constructorInitializer, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ConstructorInitializer)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode, ILTranslationContext data) => OnVisiting(data, cSharpTokenNode, VisitingCSharpTokenNode) ?? OnVisited(data, cSharpTokenNode, VisitedCSharpTokenNode, TranslateCSharpTokenNode(cSharpTokenNode, data)); protected virtual IEnumerable<Syntax> TranslateCSharpTokenNode(CSharpTokenNode cSharpTokenNode, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(CSharpTokenNode)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, ILTranslationContext data) => OnVisiting(data, delegateDeclaration, VisitingDelegateDeclaration) ?? OnVisited(data, delegateDeclaration, VisitedDelegateDeclaration, TranslateDelegateDeclaration(delegateDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateDelegateDeclaration(DelegateDeclaration delegateDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(DelegateDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, ILTranslationContext data) => OnVisiting(data, destructorDeclaration, VisitingDestructorDeclaration) ?? OnVisited(data, destructorDeclaration, VisitedDestructorDeclaration, TranslateDestructorDeclaration(destructorDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateDestructorDeclaration(DestructorDeclaration destructorDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(DestructorDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitDirectionExpression(DirectionExpression directionExpression, ILTranslationContext data) => OnVisiting(data, directionExpression, VisitingDirectionExpression) ?? OnVisited(data, directionExpression, VisitedDirectionExpression, TranslateDirectionExpression(directionExpression, data)); protected virtual IEnumerable<Syntax> TranslateDirectionExpression(DirectionExpression directionExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(DirectionExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitDocumentationReference(DocumentationReference documentationReference, ILTranslationContext data) => OnVisiting(data, documentationReference, VisitingDocumentationReference) ?? OnVisited(data, documentationReference, VisitedDocumentationReference, TranslateDocumentationReference(documentationReference, data)); protected virtual IEnumerable<Syntax> TranslateDocumentationReference(DocumentationReference documentationReference, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(DocumentationReference)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, ILTranslationContext data) => OnVisiting(data, enumMemberDeclaration, VisitingEnumMemberDeclaration) ?? OnVisited(data, enumMemberDeclaration, VisitedEnumMemberDeclaration, TranslateEnumMemberDeclaration(enumMemberDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(EnumMemberDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitErrorNode(AstNode errorNode, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, ILTranslationContext data) => OnVisiting(data, externAliasDeclaration, VisitingExternAliasDeclaration) ?? OnVisited(data, externAliasDeclaration, VisitedExternAliasDeclaration, TranslateExternAliasDeclaration(externAliasDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ExternAliasDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, ILTranslationContext data) => OnVisiting(data, fixedFieldDeclaration, VisitingFixedFieldDeclaration) ?? OnVisited(data, fixedFieldDeclaration, VisitedFixedFieldDeclaration, TranslateFixedFieldDeclaration(fixedFieldDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(FixedFieldDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitFixedStatement(FixedStatement fixedStatement, ILTranslationContext data) => OnVisiting(data, fixedStatement, VisitingFixedStatement) ?? OnVisited(data, fixedStatement, VisitedFixedStatement, TranslateFixedStatement(fixedStatement, data)); protected virtual IEnumerable<Syntax> TranslateFixedStatement(FixedStatement fixedStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(FixedStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, ILTranslationContext data) => OnVisiting(data, fixedVariableInitializer, VisitingFixedVariableInitializer) ?? OnVisited(data, fixedVariableInitializer, VisitedFixedVariableInitializer, TranslateFixedVariableInitializer(fixedVariableInitializer, data)); protected virtual IEnumerable<Syntax> TranslateFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(FixedVariableInitializer)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, ILTranslationContext data) => OnVisiting(data, gotoCaseStatement, VisitingGotoCaseStatement) ?? OnVisited(data, gotoCaseStatement, VisitedGotoCaseStatement, TranslateGotoCaseStatement(gotoCaseStatement, data)); protected virtual IEnumerable<Syntax> TranslateGotoCaseStatement(GotoCaseStatement gotoCaseStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(GotoCaseStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, ILTranslationContext data) => OnVisiting(data, gotoDefaultStatement, VisitingGotoDefaultStatement) ?? OnVisited(data, gotoDefaultStatement, VisitedGotoDefaultStatement, TranslateGotoDefaultStatement(gotoDefaultStatement, data)); protected virtual IEnumerable<Syntax> TranslateGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(GotoDefaultStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitGotoStatement(GotoStatement gotoStatement, ILTranslationContext data) => OnVisiting(data, gotoStatement, VisitingGotoStatement) ?? OnVisited(data, gotoStatement, VisitedGotoStatement, TranslateGotoStatement(gotoStatement, data)); protected virtual IEnumerable<Syntax> TranslateGotoStatement(GotoStatement gotoStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(GotoStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitIdentifier(Identifier identifier, ILTranslationContext data) => OnVisiting(data, identifier, VisitingIdentifier) ?? OnVisited(data, identifier, VisitedIdentifier, TranslateIdentifier(identifier, data)); protected virtual IEnumerable<Syntax> TranslateIdentifier(Identifier identifier, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(Identifier)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, ILTranslationContext data) => OnVisiting(data, indexerDeclaration, VisitingIndexerDeclaration) ?? OnVisited(data, indexerDeclaration, VisitedIndexerDeclaration, TranslateIndexerDeclaration(indexerDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateIndexerDeclaration(IndexerDeclaration indexerDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(IndexerDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitIsExpression(IsExpression isExpression, ILTranslationContext data) => OnVisiting(data, isExpression, VisitingIsExpression) ?? OnVisited(data, isExpression, VisitedIsExpression, TranslateIsExpression(isExpression, data)); protected virtual IEnumerable<Syntax> TranslateIsExpression(IsExpression isExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(IsExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitLabelStatement(LabelStatement labelStatement, ILTranslationContext data) => OnVisiting(data, labelStatement, VisitingLabelStatement) ?? OnVisited(data, labelStatement, VisitedLabelStatement, TranslateLabelStatement(labelStatement, data)); protected virtual IEnumerable<Syntax> TranslateLabelStatement(LabelStatement labelStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(LabelStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitLambdaExpression(LambdaExpression lambdaExpression, ILTranslationContext data) => OnVisiting(data, lambdaExpression, VisitingLambdaExpression) ?? OnVisited(data, lambdaExpression, VisitedLambdaExpression, TranslateLambdaExpression(lambdaExpression, data)); protected virtual IEnumerable<Syntax> TranslateLambdaExpression(LambdaExpression lambdaExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(LambdaExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitMemberType(MemberType memberType, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(MemberType)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, ILTranslationContext data) => OnVisiting(data, namedArgumentExpression, VisitingNamedArgumentExpression) ?? OnVisited(data, namedArgumentExpression, VisitedNamedArgumentExpression, TranslateNamedArgumentExpression(namedArgumentExpression, data)); protected virtual IEnumerable<Syntax> TranslateNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(NamedArgumentExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitNamedExpression(NamedExpression namedExpression, ILTranslationContext data) => OnVisiting(data, namedExpression, VisitingNamedExpression) ?? OnVisited(data, namedExpression, VisitedNamedExpression, TranslateNamedExpression(namedExpression, data)); protected virtual IEnumerable<Syntax> TranslateNamedExpression(NamedExpression namedExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(NamedExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitNewLine(NewLineNode newLineNode, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitNullNode(AstNode nullNode, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, ILTranslationContext data) => OnVisiting(data, operatorDeclaration, VisitingOperatorDeclaration) ?? OnVisited(data, operatorDeclaration, VisitedOperatorDeclaration, TranslateOperatorDeclaration(operatorDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateOperatorDeclaration(OperatorDeclaration operatorDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(OperatorDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, ILTranslationContext data) => OnVisiting(data, parameterDeclaration, VisitingParameterDeclaration) ?? OnVisited(data, parameterDeclaration, VisitedParameterDeclaration, TranslateParameterDeclaration(parameterDeclaration, data)); protected virtual IEnumerable<Syntax> TranslateParameterDeclaration(ParameterDeclaration parameterDeclaration, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(ParameterDeclaration)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitPatternPlaceholder(AstNode placeholder, Pattern pattern, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, ILTranslationContext data) => OnVisiting(data, pointerReferenceExpression, VisitingPointerReferenceExpression) ?? OnVisited(data, pointerReferenceExpression, VisitedPointerReferenceExpression, TranslatePointerReferenceExpression(pointerReferenceExpression, data)); protected virtual IEnumerable<Syntax> TranslatePointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(PointerReferenceExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitPrimitiveType(PrimitiveType primitiveType, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(PrimitiveType)); } public StatementCollection GetStatements(AstNodeCollection<ICSharpCode.NRefactory.CSharp.Statement> statements, ILTranslationContext data) { StatementCollection sts = null; foreach (var s in statements) { var l = GetStatements(s, data); if (l?.Count > 0) { if (sts == null) { sts = l; } else { foreach (var e in l) { sts.Add(e); } } } } return sts; } public StatementCollection GetStatements(ICSharpCode.NRefactory.CSharp.Statement statement, ILTranslationContext data) { StatementCollection sts = null; var block = statement as BlockStatement; if (block != null) { foreach (var s in block.Statements) { foreach (var cr in s.AcceptVisitor(this, data)) { (sts ?? (sts = new StatementCollection())).Add((Statement)cr); } } } else if (statement?.IsNull == false) { foreach (var cr in statement.AcceptVisitor(this, data)) { (sts ?? (sts = new StatementCollection())).Add((Statement)cr); } } return sts; } private static D.AccessibilityModifier GetAccessibility(Modifiers modifiers) => (modifiers & (Modifiers.Public | Modifiers.Internal)) != Modifiers.None ? D.AccessibilityModifier.Public : (modifiers & Modifiers.Protected) != Modifiers.None ? D.AccessibilityModifier.Protected : D.AccessibilityModifier.Private; #region ResolveType public event EventHandler<ResolvingTypeEventArgs<AstType>> ResolvingAstType; public event EventHandler<ResolvingTypeEventArgs<Type>> ResolvingClrType; public event EventHandler<ResolvingTypeEventArgs<Mono.Cecil.TypeReference>> ResolvingCecilType; #region ResolveType public ITypeReference ResolveType(AstType type) => ResolveType(null, type); public ITypeReference ResolveType(AstType type, out bool isOptional) => ResolveType(null, type, out isOptional); public ITypeReference ResolveType(AstNode context, AstType type) { bool b; return ResolveType(context, type, out b); } public ITypeReference ResolveType(AstNode context, AstType type, out bool isOptional) { var t = type.Annotations?.OfType<Type>().FirstOrDefault(); if (t != null) { return ResolveClrType(context, t, out isOptional); } var mt = type.Annotations?.OfType<TypeReference>().FirstOrDefault(); if (mt != null) { return ResolveCecilType(context, mt, out isOptional); } var h = ResolvingAstType; if (h != null) { var e = new ResolvingTypeEventArgs<AstType>(context, type); h(this, e); if (e.Result != null) { isOptional = e.IsOptional != false; return e.Result; } } isOptional = true; var pt = type as PrimitiveType; if (pt != null) { switch (pt.Keyword) { case "void": return D.PredefinedType.Void; case "object": return D.PredefinedType.Any; case "bool": isOptional = false; return D.PredefinedType.Boolean; case "byte": case "sbyte": case "short": case "ushort": case "int": case "uint": case "long": case "ulong": case "float": case "double": case "decimal": isOptional = false; return D.PredefinedType.Number; case "string": return D.PredefinedType.String; default: throw GetNotImplementedException(); } } var ct = type as ComposedType; if (ct != null) { return new D.ArrayType() { ElementType = ResolveType(context, ct.BaseType) }; } // TODO: キャッシュおよびモジュール内の検索 return new D.NamedTypeReference() { Name = ((SimpleType)type).Identifier }; } #endregion ResolveType #region ResolveClrType public ITypeReference ResolveClrType(Type type) => ResolveClrType(null, type); public ITypeReference ResolveClrType(Type type, out bool isOptional) => ResolveClrType(null, type, out isOptional); public ITypeReference ResolveClrType(AstNode context, Type type) { bool b; return ResolveClrType(context, type, out b); } public ITypeReference ResolveClrType(AstNode context, Type type, out bool isOptional) { var h = ResolvingClrType; if (h != null) { var e = new ResolvingTypeEventArgs<Type>(context, type); h(this, e); if (e.Result != null) { isOptional = e.IsOptional != false; return e.Result; } } if (type.IsArray) { if (type.GetArrayRank() != 1) { throw new NotSupportedException(); } isOptional = true; return new D.ArrayType() { ElementType = ResolveClrType(context, type.GetElementType()) }; } isOptional = !type.IsValueType; if (type.IsGenericType) { if (!type.IsConstructedGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>)) { var gt = new D.NamedTypeReference() { IsClass = type.IsClass, IsInterface = type.IsInterface, IsEnum = type.IsEnum, IsPrimitive = type.IsPrimitive, Name = type.FullName.Split('`')[0] }; foreach (var t in type.GetGenericArguments()) { gt.TypeArguments.Add(ResolveClrType(context, t)); } return gt; } } var ut = type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) ? type.GetGenericArguments()[0] : type; isOptional |= ut != type; if (ut == typeof(void)) { return D.PredefinedType.Void; } if (ut == typeof(object)) { return D.PredefinedType.Any; } if (ut == typeof(bool)) { return D.PredefinedType.Boolean; } if (ut == typeof(int) || ut == typeof(float) || ut == typeof(double) || ut == typeof(decimal) || ut == typeof(long) || ut == typeof(byte) || ut == typeof(short) || ut == typeof(uint) || ut == typeof(ulong) || ut == typeof(sbyte) || ut == typeof(ulong)) { return D.PredefinedType.Number; } if (ut == typeof(string)) { return D.PredefinedType.String; } return new D.NamedTypeReference() { IsClass = type.IsClass, IsInterface = type.IsInterface, IsEnum = type.IsEnum, IsPrimitive = type.IsPrimitive, Name = type.FullName }; } #endregion ResolveClrType #region ResolveCecilType public ITypeReference ResolveCecilType(TypeReference type) => ResolveCecilType(null, type); public ITypeReference ResolveCecilType(TypeReference type, out bool isOptional) => ResolveCecilType(null, type, out isOptional); public ITypeReference ResolveCecilType(AstNode context, TypeReference type) { bool b; return ResolveCecilType(context, type, out b); } public ITypeReference ResolveCecilType(AstNode context, TypeReference type, out bool isOptional) { var clr = type.ResolveClrType(); if (clr != null) { return ResolveClrType(context, clr, out isOptional); } var h = ResolvingCecilType; if (h != null) { var e = new ResolvingTypeEventArgs<TypeReference>(context, type); h(this, e); if (e.Result != null) { isOptional = e.IsOptional != false; return e.Result; } } var at = type as ArrayType; if (at != null) { if (at.Rank != 1) { throw new NotSupportedException(); } bool b; isOptional = true; return new D.ArrayType() { ElementType = ResolveCecilType(context, at.ElementType, out b) }; } var gt = type as GenericInstanceType; var isNullable = gt?.Namespace == nameof(System) && type.Name == nameof(Nullable); isOptional = !type.IsValueType; if (gt != null) { if (gt.IsDefinition || !isNullable) { var r = new D.NamedTypeReference(); r.Name = type.FullName.Split('`')[0]; foreach (var t in gt.GenericArguments) { bool b; r.TypeArguments.Add(ResolveCecilType(context, t, out b)); } return r; } } var ut = isNullable ? gt.GenericArguments[0] : type; isOptional |= ut != type; if (ut.Namespace == nameof(System)) { switch (ut.Name) { case "Void": return D.PredefinedType.Void; case nameof(Object): return D.PredefinedType.Any; case nameof(Boolean): return D.PredefinedType.Boolean; case nameof(String): return D.PredefinedType.String; case nameof(Byte): case nameof(SByte): case nameof(Int16): case nameof(UInt16): case nameof(Int32): case nameof(UInt32): case nameof(Int64): case nameof(UInt64): case nameof(Single): case nameof(Double): case nameof(Decimal): return D.PredefinedType.Number; } } return new D.NamedTypeReference() { Name = type.FullName }; } #endregion ResolveCecilType #endregion ResolveType #region クエリー IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryContinuationClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryExpression(QueryExpression queryExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryFromClause(QueryFromClause queryFromClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryFromClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryGroupClause(QueryGroupClause queryGroupClause, ILTranslationContext data) => OnVisiting(data, queryGroupClause, VisitingQueryGroupClause) ?? OnVisited(data, queryGroupClause, VisitedQueryGroupClause, TranslateQueryGroupClause(queryGroupClause, data)); protected virtual IEnumerable<Syntax> TranslateQueryGroupClause(QueryGroupClause queryGroupClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryGroupClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryJoinClause(QueryJoinClause queryJoinClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryJoinClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryLetClause(QueryLetClause queryLetClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryLetClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryOrderClause(QueryOrderClause queryOrderClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryOrderClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryOrdering(QueryOrdering queryOrdering, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryOrdering)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQuerySelectClause(QuerySelectClause querySelectClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QuerySelectClause)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitQueryWhereClause(QueryWhereClause queryWhereClause, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(QueryWhereClause)); } #endregion クエリー IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitSimpleType(SimpleType simpleType, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(SimpleType)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitSizeOfExpression(SizeOfExpression sizeOfExpression, ILTranslationContext data) => OnVisiting(data, sizeOfExpression, VisitingSizeOfExpression) ?? OnVisited(data, sizeOfExpression, VisitedSizeOfExpression, TranslateSizeOfExpression(sizeOfExpression, data)); protected virtual IEnumerable<Syntax> TranslateSizeOfExpression(SizeOfExpression sizeOfExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(SizeOfExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression, ILTranslationContext data) => OnVisiting(data, stackAllocExpression, VisitingStackAllocExpression) ?? OnVisited(data, stackAllocExpression, VisitedStackAllocExpression, TranslateStackAllocExpression(stackAllocExpression, data)); protected virtual IEnumerable<Syntax> TranslateStackAllocExpression(StackAllocExpression stackAllocExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(StackAllocExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitSwitchSection(SwitchSection switchSection, ILTranslationContext data) => OnVisiting(data, switchSection, VisitingSwitchSection) ?? OnVisited(data, switchSection, VisitedSwitchSection, TranslateSwitchSection(switchSection, data)); protected virtual IEnumerable<Syntax> TranslateSwitchSection(SwitchSection switchSection, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(SwitchSection)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitSyntaxTree(SyntaxTree syntaxTree, ILTranslationContext data) { foreach (var c in syntaxTree.Children) { foreach (var s in c.AcceptVisitor(this, data)) { yield return s; } } } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitText(TextNode textNode, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitTypeOfExpression(TypeOfExpression typeOfExpression, ILTranslationContext data) => OnVisiting(data, typeOfExpression, VisitingTypeOfExpression) ?? OnVisited(data, typeOfExpression, VisitedTypeOfExpression, TranslateTypeOfExpression(typeOfExpression, data)); protected virtual IEnumerable<Syntax> TranslateTypeOfExpression(TypeOfExpression typeOfExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(TypeOfExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitUncheckedExpression(UncheckedExpression uncheckedExpression, ILTranslationContext data) => OnVisiting(data, uncheckedExpression, VisitingUncheckedExpression) ?? OnVisited(data, uncheckedExpression, VisitedUncheckedExpression, TranslateUncheckedExpression(uncheckedExpression, data)); protected virtual IEnumerable<Syntax> TranslateUncheckedExpression(UncheckedExpression uncheckedExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(UncheckedExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitUncheckedStatement(UncheckedStatement uncheckedStatement, ILTranslationContext data) => OnVisiting(data, uncheckedStatement, VisitingUncheckedStatement) ?? OnVisited(data, uncheckedStatement, VisitedUncheckedStatement, TranslateUncheckedStatement(uncheckedStatement, data)); protected virtual IEnumerable<Syntax> TranslateUncheckedStatement(UncheckedStatement uncheckedStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(UncheckedStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, ILTranslationContext data) => OnVisiting(data, undocumentedExpression, VisitingUndocumentedExpression) ?? OnVisited(data, undocumentedExpression, VisitedUndocumentedExpression, TranslateUndocumentedExpression(undocumentedExpression, data)); protected virtual IEnumerable<Syntax> TranslateUndocumentedExpression(UndocumentedExpression undocumentedExpression, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(UndocumentedExpression)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitUnsafeStatement(UnsafeStatement unsafeStatement, ILTranslationContext data) => OnVisiting(data, unsafeStatement, VisitingUnsafeStatement) ?? OnVisited(data, unsafeStatement, VisitedUnsafeStatement, TranslateUnsafeStatement(unsafeStatement, data)); protected virtual IEnumerable<Syntax> TranslateUnsafeStatement(UnsafeStatement unsafeStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(UnsafeStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitVariableInitializer(VariableInitializer variableInitializer, ILTranslationContext data) => OnVisiting(data, variableInitializer, VisitingVariableInitializer) ?? OnVisited(data, variableInitializer, VisitedVariableInitializer, TranslateVariableInitializer(variableInitializer, data)); protected virtual IEnumerable<Syntax> TranslateVariableInitializer(VariableInitializer variableInitializer, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(VariableInitializer)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitWhitespace(WhitespaceNode whitespaceNode, ILTranslationContext data) { throw GetNotImplementedException(); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, ILTranslationContext data) => OnVisiting(data, yieldBreakStatement, VisitingYieldBreakStatement) ?? OnVisited(data, yieldBreakStatement, VisitedYieldBreakStatement, TranslateYieldBreakStatement(yieldBreakStatement, data)); protected virtual IEnumerable<Syntax> TranslateYieldBreakStatement(YieldBreakStatement yieldBreakStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(YieldBreakStatement)); } IEnumerable<Syntax> IAstVisitor<ILTranslationContext, IEnumerable<Syntax>>.VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, ILTranslationContext data) => OnVisiting(data, yieldReturnStatement, VisitingYieldReturnStatement) ?? OnVisited(data, yieldReturnStatement, VisitedYieldReturnStatement, TranslateYieldReturnStatement(yieldReturnStatement, data)); protected virtual IEnumerable<Syntax> TranslateYieldReturnStatement(YieldReturnStatement yieldReturnStatement, ILTranslationContext data) { throw ExceptionHelper.CannotTranslateAst(nameof(YieldReturnStatement)); } private static NotImplementedException GetNotImplementedException([CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0) => new NotImplementedException($"{memberName}は実装されていません。{Path.GetFileName(filePath)}@{lineNumber}"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameOverWindowFader : MonoBehaviour { public CanvasGroup canvGroup; public float duration = 3f; private void Start() { DelegatesHandler.GameOver += FadeIn; } public void FadeIn() { StartCoroutine(DoFadeIn(canvGroup, canvGroup.alpha, 1)); canvGroup.blocksRaycasts = true; } public IEnumerator DoFadeIn(CanvasGroup canvGroup, float start, float end) { yield return new WaitForSeconds(4); float counter = 0f; while (counter < duration) { counter += Time.deltaTime; canvGroup.alpha = Mathf.Lerp(start, end, counter / duration); yield return null; } } public void FadeOut() { StartCoroutine(DoFadeOut(canvGroup, canvGroup.alpha, 0)); canvGroup.blocksRaycasts = false; } public IEnumerator DoFadeOut(CanvasGroup canvGroup, float start, float end) { float counter = 0f; while (counter < 0.01f) { counter += Time.deltaTime; canvGroup.alpha = Mathf.Lerp(start, end, counter / 0.01f); yield return null; } } }
using BusVenta; using DatVentas; using EntVenta; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Management; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace VentasD1002 { public partial class frmRegistroEmpresa : Form { public frmRegistroEmpresa() { InitializeComponent(); } private static string serialPC; private void frmRegistroEmpresa_Load(object sender, EventArgs e) { try { ManagementObject mos = new ManagementObject(@"Win32_PhysicalMedia='\\.\PHYSICALDRIVE0'"); serialPC = mos.Properties["SerialNumber"].Value.ToString().Trim(); } catch (Exception ex) { MessageBox.Show(ex.Message); } cboImpuesto1.Enabled = false; cboPorcentaje.Enabled = false; } private void Guardar_Empresa() { try { if (txtNombreEmpresa.Text == "" || cboPaises.SelectedIndex == 0 || txtRutaBackup.Text == "" || txtNombreCaja.Text == "" || txtCorreo.Text == "") { MessageBox.Show( "Llene todos los campos del formulario", "Falta campos obligatorios", MessageBoxButtons.OK, MessageBoxIcon.Information ); } else { Empresa e = new Empresa(); MemoryStream ms = new MemoryStream(); e.Nombre = txtNombreEmpresa.Text; e.Moneda = cboMoneda.Text; if (radioButtonSi.Checked) { e.Usa_Impuestos = "SI"; e.Impuesto = cboImpuesto1.Text; e.Porcentaje = Convert.ToDecimal(cboPorcentaje.Text); } if (radioButtonNo.Checked) { e.Usa_Impuestos = "NO"; e.Impuesto = "N/A"; e.Porcentaje = 0; } e.RutaBackup = txtRutaBackup.Text; e.CorreoEnvio = txtCorreo.Text; e.UltimoBackup = "NINGUNA"; e.UltimaFechaBackup = DateTime.Now; e.FrecuenciaBackup = 1; e.TipoEmpresa = "GENERAL"; e.Estado = "PENDIENTE"; e.Redondeo = "N/A"; if (chckLectora.Checked) { e.Busqueda = "SCANNER"; } if (chckTeclado.Checked) { e.Busqueda = "TECLADO"; } pbLogo.Image.Save(ms, pbLogo.Image.RawFormat); e.Logo = ms.GetBuffer(); e.RutaBackup = txtRutaBackup.Text; e.Pais = cboPaises.Text; if (ValidateMail(txtCorreo.Text)) { e.CorreoEnvio = txtCorreo.Text; } else { MessageBox.Show("Ingrese un correo con el formato valido : ejemplo@gail.com", "Correo no válido", MessageBoxButtons.OK, MessageBoxIcon.Error); } new BusEmpresa().Agregar_Empresa(e); AgregarCaja(); AgregarSerializacion_Ticket(); this.Hide(); frmUsuarioAutorizado usuarioAutorizado = new frmUsuarioAutorizado(); usuarioAutorizado.ShowDialog(); this.Dispose(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void AgregarCaja() { try { if (txtNombreCaja.Text != "") { Box b = new Box(); b.Descripcion = txtNombreCaja.Text; b.Tema = "CLARO"; b.SerialPC = serialPC; b.ImpresoraTicket = "NINGUNA"; b.ImpresoraA4 = "NINGUNA"; b.Tipo = "PRINCIPAL"; b.Estado = true; new BusBox().Agregar_Caja(b); } } catch (Exception ex) { MessageBox.Show( "Ocurrio un error al agregar la caja "+ex.Message, "Error caja", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void cboPaises_SelectedIndexChanged(object sender, EventArgs e) { cboMoneda.SelectedIndex = cboPaises.SelectedIndex; } private void pbLogo_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); try { ofd.InitialDirectory = ""; ofd.Filter = "Imagenes|*.jpg;*.png"; ofd.FilterIndex = 2; ofd.Title = "Carga Logo empresa"; if (ofd.ShowDialog() == DialogResult.OK) { pbLogo.BackgroundImage = null; pbLogo.Image = new Bitmap(ofd.FileName); pbLogo.SizeMode = PictureBoxSizeMode.Zoom; // lblNombreIcono.Text = Path.GetFileName(ofd.FileName); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void pictureBox1_Click(object sender, EventArgs e) { if ( folderBrowserDialog1.ShowDialog() == DialogResult.OK ) { txtRutaBackup.Text = folderBrowserDialog1.SelectedPath; string ruta = txtRutaBackup.Text; //if ( ruta.Contains(@"C:\") ) //{ // MessageBox.Show( "Seleccione una ruta diferente al Disco C:", "Ruta no válida", MessageBoxButtons.OK, MessageBoxIcon.Error ); // txtRutaBackup.Text = ""; //} //else //{ txtRutaBackup.Text = folderBrowserDialog1.SelectedPath; //} } } public bool ValidateMail(string email) { return Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z"); } private void AgregarSerializacion_Ticket() { try { #region INSERTAR DATOS SERIALIZACION Serializacion s = new Serializacion(); s.Serie = "T"; s.Cantidad_Numero = "6"; s.NumeroFin = "0"; s.Tipo_Documento = "TICKET"; s.Destino = "VENTAS"; s.Por_Defecto = "SI"; new BusSerializacion().Agregar_Serializacion(s); Serializacion s1 = new Serializacion(); s1.Serie = "R"; s1.Cantidad_Numero = "6"; s1.NumeroFin = "0"; s1.Tipo_Documento = "RECIBO"; s1.Destino = "VENTAS"; s1.Por_Defecto = "NO"; new BusSerializacion().Agregar_Serializacion(s1); Serializacion s2 = new Serializacion(); s2.Serie = "F"; s2.Cantidad_Numero = "6"; s2.NumeroFin = "0"; s2.Tipo_Documento = "FACTURA"; s2.Destino = "VENTAS"; s2.Por_Defecto = "NO"; new BusSerializacion().Agregar_Serializacion(s2); Serializacion s3 = new Serializacion(); s3.Serie = "I"; s3.Cantidad_Numero = "6"; s3.NumeroFin = "0"; s3.Tipo_Documento = "INGRESO"; s3.Destino = "INGRESO DE COBROS"; s3.Por_Defecto = "NO"; new BusSerializacion().Agregar_Serializacion(s3); Serializacion s4 = new Serializacion(); s4.Serie = "E"; s4.Cantidad_Numero = "6"; s4.NumeroFin = "0"; s4.Tipo_Documento = "EGRESO"; s4.Destino = "EGRESO DE PAGOS"; s4.Por_Defecto = "NO"; new BusSerializacion().Agregar_Serializacion(s4); #endregion #region INSERTAR DATOS TICKET try { Ticket t = new Ticket(); t.Identificador_Fiscal = "RUC Identificador Fiscal de la Empresa"; t.Direccion = "Santa Maria Chilchotla"; t.Provincia = "Santa María Chilchotla-Oaxaca-México"; t.Moneda = "Peso Mexicano"; t.Agradecimiento = "Gracias por su Compra!, vuelva pronto..."; t.Pagina_Web = "Agrega tu pagina"; t.Anuncio = "aqui tu anuncio /Cupones / Descuentos"; t.Datos_Fiscales = "Datos Fiscales - Num. Autorización - Resolución..."; t.Default = "Ticket No Fiscal"; new BusTicket().Agregar_Ticket(t); } catch (Exception ex) { MessageBox.Show("error en la insercion de ticket "+ ex.Message); } #endregion #region INSERTAR DATOS CATEGORIA USUARIO try { CatalogoGenerico c = new CatalogoGenerico(); c.Descripcion = "CONTROL TOTAL DEL SISTEMA"; c.Estado = true; c.Nombre = "ADMINISTRADOR"; new BusCatGenerico().Agregar_TipoUsuario(c); } catch (Exception ex) { MessageBox.Show("error en la insercion de " + ex.Message); } #endregion #region INSERTA FORMA DE PAGOS DatCatGenerico.Insertar_FormaPago("Contado", "Pago en efectivo"); DatCatGenerico.Insertar_FormaPago("Credito", "Pagos a créditos"); #endregion #region INSERTAR ROLES DE USUARIOS CatalogoGenerico rol = new CatalogoGenerico(); rol.Nombre = "CAJERO"; rol.Descripcion = "VENTAS Y COBROS"; rol.Estado = true; new BusCatGenerico().Agregar_TipoUsuario(rol); CatalogoGenerico rol2 = new CatalogoGenerico(); rol2.Nombre = "VENDEDOR"; rol2.Descripcion = "SOLO VENTAS"; rol2.Estado = true; new BusCatGenerico().Agregar_TipoUsuario(rol2); #endregion } catch (Exception ex) { MessageBox.Show("Ocurrio un error al agregar la serialización " + ex.Message, "Error ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void siguienteToolStripMenuItem1_Click(object sender, EventArgs e) { Guardar_Empresa(); } private void radioButtonSi_CheckedChanged(object sender, EventArgs e) { cboImpuesto1.Enabled = true; cboPorcentaje.Enabled = true; } private void radioButtonNo_CheckedChanged(object sender, EventArgs e) { cboImpuesto1.Enabled = false; cboPorcentaje.Enabled = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.Comment { /// <summary> /// 顾客点评统计 /// </summary> public class E_CommentTotal { /// <summary> /// 班组ID /// </summary> public int ClassId { get; set; } /// <summary> /// 期望值 /// </summary> public double TotalExpect { get; set; } /// <summary> /// 感知值 /// </summary> public double TotalReal { get; set; } /// <summary> /// 总值 /// </summary> public double Total { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Mail; using System.Net.Mime; using System.IO; using System.Threading; using System.ComponentModel; namespace MailClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { lstAttachment.Items.Clear(); } private void Form1_Resize(object sender, EventArgs e) { Control control = (Control)sender; txtTo.Location = new System.Drawing.Point(72, 5); txtTo.Size = new System.Drawing.Size(control.Size.Width - 104, 22); txtCc.Location = new System.Drawing.Point(72, 31); txtCc.Size = new System.Drawing.Size(control.Size.Width - 104, 22); txtBcc.Location = new System.Drawing.Point(72, 57); txtBcc.Size = new System.Drawing.Size(control.Size.Width - 104, 22); txtSubject.Location = new System.Drawing.Point(72, 83); txtSubject.Size = new System.Drawing.Size(control.Size.Width - 104, 22); lstAttachment.Location = new System.Drawing.Point(72, 109); lstAttachment.Size = new System.Drawing.Size(control.Size.Width - 104, 28); txtHost.Location = new System.Drawing.Point(67, 16); txtHost.Size = new System.Drawing.Size(control.Size.Width - 99, 22); txtPort.Location = new System.Drawing.Point(67, 44); txtPort.Size = new System.Drawing.Size(control.Size.Width - 99, 22); txtFrom.Location = new System.Drawing.Point(67, 72); txtFrom.Size = new System.Drawing.Size(control.Size.Width - 99, 22); txtUser.Location = new System.Drawing.Point(67, 100); txtUser.Size = new System.Drawing.Size(control.Size.Width - 99, 22); txtPass.Location = new System.Drawing.Point(67, 128); txtPass.Size = new System.Drawing.Size(control.Size.Width - 99, 22); } private void ToolBar1_ButtonClick(object sender, ToolBarButtonClickEventArgs e) { switch (ToolBar1.Buttons.IndexOf(e.Button)) { case 0: // Send Thread mailThread = new Thread(new ThreadStart(ProcessMail)); mailThread.Start(); break; case 1: // 處理附件 OpenFileDialog1.Filter = "All files (*.*)|*.*"; OpenFileDialog1.InitialDirectory = Directory.GetCurrentDirectory(); OpenFileDialog1.Title = "Select Attachment"; if (OpenFileDialog1.ShowDialog() == DialogResult.OK) lstAttachment.Items.Add(OpenFileDialog1.FileName); break; case 2: // Clear txtTo.Clear(); txtCc.Clear(); txtBcc.Clear(); txtSubject.Clear(); txtMessage.Clear(); lstAttachment.Items.Clear(); chkHTML.Checked = false; break; } } private void mnuExit_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Are you sure to quit?", ".Net Mail Client", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) { this.Close(); } } public void ProcessMail() { System.Net.Mail.SmtpClient mailClient = null; System.Net.Mail.MailMessage mailMessage = null; System.Net.Mail.MailAddress fromAddress = null; System.Net.Mail.MailAddress toAddress = null; System.Net.Mail.MailAddress ccAddress = null; System.Net.Mail.MailAddress bccAddress = null; System.Net.Mail.Attachment mailAttachment = null; System.Net.NetworkCredential credentials = null; try { if (txtHost.Text != "" && txtPort.Text != ""){ // 設定SMTP郵件伺服器的DNS名稱或IP位址及通訊埠 mailClient = new SmtpClient(txtHost.Text, Int32.Parse(txtPort.Text)); } else { MessageBox.Show("請輸入SMTP郵件伺服器的DNS名稱或IP位址及通訊埠.", ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } if (txtUser.Text != "" && txtPass.Text != ""){ // 設定使用者登入SMTP郵件伺服器需使用帳號與密碼之認證 credentials = new NetworkCredential(txtUser.Text, txtPass.Text, txtHost.Text); } else { MessageBox.Show("請輸入使用者帳號與密碼.", ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } // 設定SmtpClient物件的Credentials屬性 mailClient.Credentials = credentials; // 當傳送郵件完畢時 // 並定義所呼叫的Callback方法 mailClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); // 設定寄件者郵件地址 fromAddress = new MailAddress(txtFrom.Text); // 設定收件者郵件地址(To) if (txtTo.Text != ""){ toAddress = new MailAddress(txtTo.Text); } else { MessageBox.Show("請輸入收件者郵件地址.", ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } // 設定副本收件者郵件地址(CC) if (txtCc.Text != "") ccAddress = new MailAddress(txtCc.Text); // 設定密件副本收件者郵件地址(BCC) if (txtBcc.Text != "") bccAddress = new MailAddress(txtBcc.Text); mailMessage = new MailMessage(fromAddress, toAddress); mailMessage.CC.Add(ccAddress); mailMessage.Bcc.Add(bccAddress); // 設定郵件主旨 mailMessage.Subject = txtSubject.Text; // 設定郵件內文的字元編碼格式 mailMessage.BodyEncoding = System.Text.Encoding.UTF8; // 設定郵件內文 mailMessage.Body = txtMessage.Text; // 設定郵件內文是否為HTML格式 if (chkHTML.Checked) mailMessage.IsBodyHtml = true; else mailMessage.IsBodyHtml = false; // 處理附件 for (int i = 0; i <= lstAttachment.Items.Count - 1; i++) { mailAttachment = new Attachment(lstAttachment.Items[i].ToString()); mailMessage.Attachments.Add(mailAttachment); } // 處理順序 mailMessage.Priority = System.Net.Mail.MailPriority.Normal; string userToken = "Asynchronous"; // 執行非同步傳送郵件 mailClient.SendAsync(mailMessage, userToken); mailMessage = null; } catch (Exception ex) { MessageBox.Show("郵件傳送失敗: " + ex.ToString(), ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } } // 自訂Callback方法 public static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { // 取得非同步作業之識別碼 string userToken = (string)e.UserState; // 判斷非同步作業是否已被取消 if (e.Cancelled) MessageBox.Show("取消非同步傳送郵件.", ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); // 判斷非同步作業是否發生錯誤 if (e.Error != null) // 顯示錯誤訊息 MessageBox.Show("非同步傳送郵件發生錯誤: " + e.Error.ToString(), ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); else // 郵件傳送完畢 MessageBox.Show("非同步傳送郵件成功.", ".Net Mail Client", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GyroscopeOutput : MonoBehaviour{ TextMesh txt; void Start(){ txt = GetComponent<TextMesh>(); } void Update(){ txt.text = "x=" + Mathf.Round(Input.acceleration.x*10)/10 + "\ny=" + Mathf.Round(Input.acceleration.y*10)/10 + "\nz=" + Mathf.Round(Input.acceleration.z*10)/10; } }
namespace Bridge.ExemploPratico { public class Culinaria : ICanal { public string Canal() { return "Sintonizado no: Canal de Culinaria"; } public string Status() { return $"Você está assistindo Receita de bolo de laranja"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DT { public static class traductor { public static String DK_ocupacion(String ocupacion_DK) { String traduccion = ""; String[] datos = ocupacion_DK.Split('&'); datos[0] = datos[0].Substring(0, 1).ToUpper() + datos[0].Substring(1, datos[0].Length - 1).ToLower(); for (int i = 0; i < datos.Length; i++) traduccion += datos[i] + '&'; return traduccion.Substring(0, traduccion.Length - 1); } public static String DK_Parentesco(String parentesco_DK) { String traduccion = ""; String[] datos = parentesco_DK.Split('&'); datos[0] = datos[0].Substring(0, 1).ToUpper() + datos[0].Substring(1, datos[0].Length - 1).ToLower(); for (int i = 0; i < datos.Length; i++) traduccion += datos[i] + '&'; return traduccion.Substring(0, traduccion.Length - 1); } public static String DK_Motivo(String motivo_DK) { String traduccion = ""; String[] datos = motivo_DK.Split('&'); datos[0] = datos[0].Substring(0, 1).ToUpper() + datos[0].Substring(1, datos[0].Length - 1).ToLower(); for (int i = 0; i < datos.Length; i++) traduccion += datos[i] + '&'; return traduccion.Substring(0, traduccion.Length - 1); } public static String DK_Afiliado(String afiliado_DK) { String traduccion = ""; //Quito el van persie, porque esa parte no me sirve String[] separador = afiliado_DK.Split('&'); //ahora lo separo en todos los tipos de datos que pueden haber, tengo mis datos separados en grupitos de comas... String[] datos = separador[0].Split(';'); //todos los datos personales String[] datosPersonales = datos[0].Split(','); if (datosPersonales[1].Length > 0) datosPersonales[1] = datosPersonales[1].Substring(0, 1).ToUpper() + datosPersonales[1].Substring(1, datosPersonales[1].Length - 1).ToLower(); if (datosPersonales[2].Length > 0) datosPersonales[2] = datosPersonales[2].Substring(0, 1).ToUpper() + datosPersonales[2].Substring(1, datosPersonales[2].Length - 1).ToLower(); if (datosPersonales[3].Length > 0) datosPersonales[3] = datosPersonales[3].Substring(0, 1).ToUpper() + datosPersonales[3].Substring(1, datosPersonales[3].Length - 1).ToLower(); if (datosPersonales[4].Length > 0) datosPersonales[4] = datosPersonales[4].Substring(0, 1).ToUpper() + datosPersonales[4].Substring(1, datosPersonales[4].Length - 1).ToLower(); //Los datos personales se agragan al String con esto traduccion = datosPersonales[0] + "," + datosPersonales[1] + "," + datosPersonales[2] + "," + datosPersonales[3] + "," + datosPersonales[4] + "," + datosPersonales[5] + "," + datosPersonales[6] + "," + datosPersonales[7] + "," + datosPersonales[8] + ";" + datos[1] + ";" + datos[2] + ";" + datos[3] + ";" + datos[4] + ";" + datos[5] + ";"; //datos[5] = profesion u oficio, hasta este punto tengo en el String los datos de profesion, vamos con los beneficiarios. //En los beneficiarios, los nombres siempre son desde las posiciones 1 hasta la 4, los beneficiarios van desde 6 hasta n... String[] datosBeneficiario; for (int n = 6; n < datos.Length; n++) { if (datos[n] == "") break; datosBeneficiario = datos[n].Split(','); //Valido que la cadena no este vacia, si esta vacia me jodi if (datosBeneficiario[1].Length > 0) datosBeneficiario[1] = datosBeneficiario[1].Substring(0, 1).ToUpper() + datosBeneficiario[1].Substring(1, datosBeneficiario[1].Length - 1).ToLower(); if (datosBeneficiario[2].Length > 0) datosBeneficiario[2] = datosBeneficiario[2].Substring(0, 1).ToUpper() + datosBeneficiario[2].Substring(1, datosBeneficiario[2].Length - 1).ToLower(); if (datosBeneficiario[3].Length > 0) datosBeneficiario[3] = datosBeneficiario[3].Substring(0, 1).ToUpper() + datosBeneficiario[3].Substring(1, datosBeneficiario[3].Length - 1).ToLower(); if (datosBeneficiario[4].Length > 0) datosBeneficiario[4] = datosBeneficiario[4].Substring(0, 1).ToUpper() + datosBeneficiario[4].Substring(1, datosBeneficiario[4].Length - 1).ToLower(); //los datos del beneficiario estan listos, ahora los pego a mi String traduccion for (int i = 0; i < datosBeneficiario.Length; i++) traduccion += datosBeneficiario[i] + ","; //Ahora debo quitar la ultima coma y ponerle un punto y coma... traduccion = traduccion.Substring(0, traduccion.Length - 1) + ";"; } //Ahora elimino el ultimo punto y coma que no es necesario y agregamos el van persie traduccion = traduccion.Substring(0, traduccion.Length - 1) + "&" + separador[1]; //Y listo return traduccion; } public static String DK_Empleado(String empleado_DK) { String traduccion = ""; String[] datos = empleado_DK.Split(';'); String[] datosPersonales = datos[0].Split(','); String telPersonal = datos[1]; String celular = datos[2]; String usuario = datos[3]; //Otra vez, las validaciones para no joderme if (datosPersonales[1].Length > 0) datosPersonales[1] = datosPersonales[1].Substring(0, 1).ToUpper() + datosPersonales[1].Substring(1, datosPersonales[1].Length - 1).ToLower(); if (datosPersonales[2].Length > 0) datosPersonales[2] = datosPersonales[2].Substring(0, 1).ToUpper() + datosPersonales[2].Substring(1, datosPersonales[2].Length - 1).ToLower(); if (datosPersonales[3].Length > 0) datosPersonales[3] = datosPersonales[3].Substring(0, 1).ToUpper() + datosPersonales[3].Substring(1, datosPersonales[3].Length - 1).ToLower(); if (datosPersonales[4].Length > 0) datosPersonales[4] = datosPersonales[4].Substring(0, 1).ToUpper() + datosPersonales[4].Substring(1, datosPersonales[4].Length - 1).ToLower(); traduccion += datosPersonales[0] + "," + datosPersonales[1] + "," + datosPersonales[2] + "," + datosPersonales[3] + "," + datosPersonales[4] + "," + datosPersonales[5] + "," + datosPersonales[6] + "," + datosPersonales[7] + "," + datosPersonales[8] + ";" + datos[1] + ";" + datos[2] + ";" + datos[3]; return traduccion; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet.Arrays { public class ArkArrayFloat : List<float?>, IArkArray<float?> { public ArkArrayFloat() { } public ArkArrayFloat(ArkArchive archive, int dataSize) { var size = archive.GetInt(); Capacity = size; for (int n = 0; n < size; n++) { Add(archive.GetFloat()); } } public Type ValueClass => typeof(float?); //public int calculateSize(bool nameTable) //{ // return Integer.BYTES + this.Count * Float.BYTES; //} public void CollectNames(ISet<string> nameTable) { } } }
namespace RTBid.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class Addedstartedtime : DbMigration { public override void Up() { AddColumn("dbo.Auctions", "StartedTime", c => c.DateTime()); } public override void Down() { DropColumn("dbo.Auctions", "StartedTime"); } } }
using System.Drawing; using Wheebrary.Math; namespace Wheebrary.Render { public class WheeColor { public int R { get; private set; } public int G { get; private set; } public int B { get; private set; } public float A { get; private set; } public static readonly WheeColor White = new WheeColor(255, 255, 255); public static readonly WheeColor Red = new WheeColor(255, 0, 0); public static readonly WheeColor Yellow = new WheeColor(255, 255, 0); public static readonly WheeColor Orange = new WheeColor(255, 128, 0); public static readonly WheeColor Green = new WheeColor(0, 255, 0); public static readonly WheeColor Cyan = new WheeColor(0, 255, 255); public static readonly WheeColor Blue = new WheeColor(0, 0, 255); public static readonly WheeColor Magenta = new WheeColor(255, 0, 255); public static readonly WheeColor Black = new WheeColor(0, 0, 0); public WheeColor(int r, int g, int b, float a) { r = (int)MathExtensions.Clamp(r, 0, 255); g = (int)MathExtensions.Clamp(g, 0, 255); b = (int)MathExtensions.Clamp(b, 0, 255); a = MathExtensions.Clamp(a, 0, 1); } public WheeColor(int r, int g, int b) : this(r, g, b, 1) { } public static WheeColor Parse(Color color) { return new WheeColor(color.R, color.G, color.B, color.A); } public Color ToColor() { return Color.FromArgb((int)(A * 255), R, G, B); } public override string ToString() { return "RGBA: " + R.ToString() + ", " + G.ToString() + ", " + B.ToString() + ", " + A.ToString(); } } }
namespace Sentry.Tests; public partial class BaggageHeaderTests { [Fact] public void BaggageHeader_TryParse_Empty() { var header = BaggageHeader.TryParse(""); Assert.Null(header); } [Fact] public void BaggageHeader_Create() { var header = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"foo", "123"}, {"bar", "456"} }); var expected = new List<KeyValuePair<string, string>> { {"foo", "123"}, {"bar", "456"} }; Assert.Equal(expected, header.Members); } [Fact] public void BaggageHeader_Create_WithSentryPrefix() { var header = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"foo", "123"}, {"bar", "456"} }, useSentryPrefix: true); var expected = new List<KeyValuePair<string, string>> { {"sentry-foo", "123"}, {"sentry-bar", "456"} }; Assert.Equal(expected, header.Members); } [Fact] public void BaggageHeader_ToString() { var header = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"test-bad-chars", @" ""(),/:;<=>?@[\]{}"}, {"sentry-public_key", "49d0f7386ad645858ae85020e393bef3"}, {"test-name", "Amélie"}, {"test-name", "John"}, }); Assert.Equal( "test-bad-chars=%20%22%28%29%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%7B%7D, " + "sentry-public_key=49d0f7386ad645858ae85020e393bef3, test-name=Am%C3%A9lie, test-name=John", header.ToString()); } [Fact] public void BaggageHeader_Merge() { var header1 = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"foo", "123"}, }); var header2 = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"bar", "456"}, {"baz", "789"}, }); var header3 = BaggageHeader.Create(new List<KeyValuePair<string, string>> { {"foo", "789"}, {"baz", "000"}, }); var merged = BaggageHeader.Merge(new[] {header1, header2, header3}); var expected = new List<KeyValuePair<string, string>> { {"foo", "123"}, {"bar", "456"}, {"baz", "789"}, {"foo", "789"}, {"baz", "000"} }; Assert.Equal(expected, merged.Members); } }
namespace ClounceMathExamples { using ClounceMath; using System; sealed class KappaNumbers { public static void RunSequence() { int i = 1; int l = 9; foreach (double number in Sequences.KappaNumberGenerator(l)) { Console.Write("K({0,2}, {1,2}): {2,-30}", l, i, number); if (++i % 3 == 1) { Console.WriteLine(); } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Using the direct value calculation"); for (i = 1; i <= l; ) { Console.Write("K({0,2}, {1,2}): {2,-30}", l, i, Sequences.KappaNumber(l, i)); if (++i % 3 == 1) { Console.WriteLine(); } } Console.WriteLine(); } } }
using Microsoft.Practices.Unity; using ProgFrog.Core.Data; using ProgFrog.Core.Data.Serialization; using ProgFrog.Core.TaskRunning; using ProgFrog.Core.TaskRunning.Compilers; using ProgFrog.Core.TaskRunning.ResultsChecking; using ProgFrog.Core.TaskRunning.Runners; using ProgFrog.Interface.Data; using ProgFrog.Interface.Data.Serialization; using ProgFrog.Interface.Model; using ProgFrog.Interface.TaskRunning; using ProgFrog.Interface.TaskRunning.Compilers; using ProgFrog.Interface.TaskRunning.ResultsChecking; using ProgFrog.Interface.TaskRunning.Runners; using System.Configuration; using System.IO; using System.Reflection; using System.Web.Http.Dependencies; using Unity.WebApi; namespace ProgFrog.IoC { public class DependencyReolver { private static IUnityContainer _container; public static void Configure() { _container = new UnityContainer(); _container.RegisterType<IModelSerializer<ProgrammingTask>, JsonSerializer<ProgrammingTask>>(); var progTasksLocation = ConfigurationManager.AppSettings["progTasksLocation"]; _container.RegisterType<IProgrammingTaskRepository, FileProgramminTaskRepository>(new InjectionConstructor(new ResolvedParameter<IModelSerializer<ProgrammingTask>>(), new InjectionParameter<string>(progTasksLocation))); _container.RegisterType<IResultsChecker, ResultsChecker>(); _container.RegisterType<IInputWriter, StandardInputStreamWriter>(new InjectionConstructor()); _container.RegisterType<IOutputReader, StandardOutputStreamReader>(new InjectionConstructor()); _container.RegisterType<IFileWriter, FileWriter>(); _container.RegisterType<IProcessFactory, ProcessFactory>(); _container.RegisterType<ITempFileProvider, TempFileProvider>(); _container.RegisterType<ICompiler, CSharpCompiler>("CSharp", new InjectionConstructor(new InjectionParameter<string>(@"c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe"))); _container.RegisterType<PythonTaskRunner>(new InjectionConstructor(new InjectionParameter<string>(@"c:\Python27\python.exe"), new ResolvedParameter<IInputWriter>(), new ResolvedParameter<IOutputReader>(), new ResolvedParameter<IFileWriter>(), new ResolvedParameter<IProcessFactory>(), new ResolvedParameter<ITempFileProvider>())); _container.RegisterType<CSharpTaskRunner>("CSharp", new InjectionConstructor(new ResolvedParameter<ICompiler>("CSharp"), new ResolvedParameter<IInputWriter>(), new ResolvedParameter<IOutputReader>(), new ResolvedParameter<IFileWriter>(), new ResolvedParameter<IProcessFactory>(), new ResolvedParameter<ITempFileProvider>())); var taskRunnerProvider = new TaskRunnerProvider(); taskRunnerProvider.RegisterRunner(_container.Resolve<PythonTaskRunner>(), ProgrammingLanguage.Python); taskRunnerProvider.RegisterRunner(_container.Resolve<CSharpTaskRunner>("CSharp"), ProgrammingLanguage.CSharp); _container.RegisterInstance<ITaskRunnerProvider>(taskRunnerProvider); } public static IDependencyResolver GetWebDependencyResolver() { return new UnityDependencyResolver(_container); } public static T Resolve<T>() { return _container.Resolve<T>(); } } }
using DAL.Contracts; using DAL.Repos; using System.Data.Entity; namespace DAL.Context { public class DB : DbContext { public DB() : base("Vidly") { Configuration.LazyLoadingEnabled = false; } public DB(string connection) : base(connection) { Configuration.LazyLoadingEnabled = false; } public DbSet<Movy> Movies { get; set; } public DbSet<Customer> Customers { get; set; } public DbSet<Genre> Genres { get; set; } } public interface IDalUnitOfWork : IUnitOfWork { IMovieRepository MoviesRepo { get; } ICustomerRepository CustomersRepo { get; } IGenreRepository GenreRepository { get; } } public class EFUnitOfWork : IDalUnitOfWork { private DB _db; private IMovieRepository _moviesRepo; private ICustomerRepository _customerRepo; private IGenreRepository _genreRepo; public EFUnitOfWork() { _db = new DB(); } public IMovieRepository MoviesRepo => _moviesRepo ?? new MovieRepository(_db); public ICustomerRepository CustomersRepo => _customerRepo ?? new CustomerRepository(_db); public IGenreRepository GenreRepository => _genreRepo ?? new GenreRepository(_db); public void Dispose() { _moviesRepo?.Dispose(); _customerRepo?.Dispose(); _genreRepo?.Dispose(); _db.Dispose(); } public int SaveChanges() { return _db.SaveChanges(); // throw new System.NotImplementedException(); } } }
using System.Runtime.InteropServices; namespace XinputGamePad{ public static class DllConst{ [DllImport ("XInputCapture")] public static extern void Capture(); // 状態取得 [DllImport ("XInputCapture")] public static extern bool IsConnected(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetButtons(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetLeftTrigger(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetRightTrigger(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetThumbLX(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetThumbLY(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetThumbRX(int DeviceNumber); [DllImport ("XInputCapture")] public static extern int GetThumbRY(int DeviceNumber); } public static class InputConst{ // XInput定数 public static readonly int XUSER_MAX_COUNT = 4; public static readonly int XINPUT_GAMEPAD_DPAD_UP = 0x0001; public static readonly int XINPUT_GAMEPAD_DPAD_DOWN = 0x0002; public static readonly int XINPUT_GAMEPAD_DPAD_LEFT = 0x0004; public static readonly int XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008; public static readonly int XINPUT_GAMEPAD_START = 0x0010; public static readonly int XINPUT_GAMEPAD_BACK = 0x0020; public static readonly int XINPUT_GAMEPAD_LEFT_THUMB = 0x0040; public static readonly int XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080; public static readonly int XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100; public static readonly int XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200; public static readonly int XINPUT_GAMEPAD_A = 0x1000; public static readonly int XINPUT_GAMEPAD_B = 0x2000; public static readonly int XINPUT_GAMEPAD_X = 0x4000; public static readonly int XINPUT_GAMEPAD_Y = 0x8000; public static readonly int XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE = 7849; public static readonly int XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE = 8689; public static readonly int XINPUT_GAMEPAD_TRIGGER_THRESHOLD = 30; } }
using System.Collections.Generic; namespace Thinktecture.Extensions.Configuration.Legacy { internal class RootLegacyConfigurationItem : ILegacyConfigurationItem { private readonly string _name; /// <inheritdoc /> public string ConfigurationPath => _name; /// <inheritdoc /> public string XmlPath => _name; /// <inheritdoc /> public IDictionary<string, int> ChildIndexesByName { get; } /// <inheritdoc /> public string BuildXmlPath(string childName) { return childName; } /// <inheritdoc /> public string BuildConfigurationPath(string childName) { return childName; } public RootLegacyConfigurationItem(string name) { _name = name; ChildIndexesByName = new Dictionary<string, int>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Автошкола { public class ServiceMastersDA { private SqlDataAdapter dataAdapter; // сохранить изменения строки public void Save(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr) { dataAdapter = new SqlDataAdapter(); // на обновление dataAdapter.UpdateCommand = new SqlCommand("UPDATE ServiceMasters SET ID = @ID, Surname = @Surname, " + "FirstName = @FirstName, PatronymicName = @PatronymicName, WorkStatus = @WorkStatus " + "WHERE ID = @OldID", conn.getConnection(), tr.getTransaction()); dataAdapter.UpdateCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID"); dataAdapter.UpdateCommand.Parameters.Add("@Surname", System.Data.SqlDbType.Text, 255, "Surname"); dataAdapter.UpdateCommand.Parameters.Add("@FirstName", System.Data.SqlDbType.Text, 255, "FirstName"); dataAdapter.UpdateCommand.Parameters.Add("@PatronymicName", System.Data.SqlDbType.Text, 255, "PatronymicName"); dataAdapter.UpdateCommand.Parameters.Add("@WorkStatus", System.Data.SqlDbType.Int, 255, "WorkStatus"); dataAdapter.UpdateCommand.Parameters.Add("@OldID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original; // на вставку dataAdapter.InsertCommand = new SqlCommand("INSERT INTO ServiceMasters (ID, Surname, FirstName, PatronymicName, " + " WorkStatus) VALUES (@ID, @Surname, @FirstName, @PatronymicName, @WorkStatus)", conn.getConnection(), tr.getTransaction()); dataAdapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID"); dataAdapter.InsertCommand.Parameters.Add("@Surname", System.Data.SqlDbType.Text, 255, "Surname"); dataAdapter.InsertCommand.Parameters.Add("@FirstName", System.Data.SqlDbType.Text, 255, "FirstName"); dataAdapter.InsertCommand.Parameters.Add("@PatronymicName", System.Data.SqlDbType.Text, 255, "PatronymicName"); dataAdapter.InsertCommand.Parameters.Add("@WorkStatus", System.Data.SqlDbType.Int, 255, "WorkStatus"); // на удаление dataAdapter.DeleteCommand = new SqlCommand("DELETE ServiceMasters WHERE ID = @ID", conn.getConnection(), tr.getTransaction()); dataAdapter.DeleteCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original; dataAdapter.Update(dataSet, "ServiceMasters"); } // прочитать таблицу public void Read(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM ServiceMasters", conn.getConnection(), tr.getTransaction()); dataAdapter.Fill(dataSet, "ServiceMasters"); } public void ReadByID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int ID) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM ServiceMasters WHERE ID = @ID", conn.getConnection(), tr.getTransaction()); dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", ID); dataAdapter.Fill(dataSet, "ServiceMasters"); } } }
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace Telerik.OpenAccess.Tools { public sealed class OpenAccessClean : Task { private string outputPath; private ITaskItem[] sources; [Required] public string OutputPath { get { return this.outputPath; } set { this.outputPath = value; } } [Required] public ITaskItem[] Sources { get { return this.sources; } set { this.sources = value; } } public OpenAccessClean() { } public override bool Execute() { bool flag = true; ITaskItem[] sources = this.Sources; for (int i = 0; i < (int)sources.Length; i++) { ITaskItem taskItem = sources[i]; string str = Path.Combine(this.OutputPath, taskItem.ItemSpec); List<FileInfo> fileInfos = new List<FileInfo>(); try { fileInfos.Add(new FileInfo(Path.ChangeExtension(str, ".oa"))); fileInfos.Add(new FileInfo(Path.ChangeExtension(str, ".rlinq"))); fileInfos.Add(new FileInfo(Path.ChangeExtension(str, ".oaxml"))); } catch (Exception exception1) { Exception exception = exception1; TaskLoggingHelper log = base.Log; CultureInfo currentCulture = CultureInfo.CurrentCulture; object[] itemSpec = new object[] { taskItem.ItemSpec }; log.LogError(string.Format(currentCulture, "Error attempting to clean file '{0}'.", itemSpec), new object[0]); base.Log.LogErrorFromException(exception, true); flag = false; goto Label0; } foreach (FileInfo fileInfo in fileInfos) { if (!fileInfo.Exists) { continue; } try { fileInfo.Delete(); TaskLoggingHelper taskLoggingHelper = base.Log; CultureInfo cultureInfo = CultureInfo.CurrentCulture; object[] fullName = new object[] { fileInfo.FullName }; taskLoggingHelper.LogMessage(MessageImportance.Low, string.Format(cultureInfo, "Successfully cleaned file '{0}'", fullName), new object[0]); } catch (Exception exception3) { Exception exception2 = exception3; TaskLoggingHelper log1 = base.Log; CultureInfo currentCulture1 = CultureInfo.CurrentCulture; object[] objArray = new object[] { fileInfo.FullName }; log1.LogError(string.Format(currentCulture1, "Error cleaning file '{0}'", objArray), new object[0]); base.Log.LogErrorFromException(exception2, true); flag = false; } } TaskLoggingHelper taskLoggingHelper1 = base.Log; CultureInfo cultureInfo1 = CultureInfo.CurrentCulture; object[] itemSpec1 = new object[] { taskItem.ItemSpec }; taskLoggingHelper1.LogMessage(string.Format(cultureInfo1, "Successfully cleaned the output for .rlinq file '{0}'", itemSpec1), new object[0]); Label0: { } } if (flag) { TaskLoggingHelper log2 = base.Log; CultureInfo currentCulture2 = CultureInfo.CurrentCulture; object[] length = new object[] { (int)this.Sources.Length }; log2.LogMessage(string.Format(currentCulture2, "Successfully cleaned the output for {0} .rlinq files.", length), new object[0]); } return flag; } } }
 namespace Profiling2.Domain.Contracts.Queries.Procs { public interface IMergeStoredProcQueries { /// <summary> /// Call to stored procedure written by Miki as part of Profiling1. /// </summary> /// <param name="toKeepPersonId"></param> /// <param name="toDeletePersonId"></param> /// <param name="userId">This is 'UN ID', in the form 'I-0001'.</param> /// <param name="isProfilingChange"></param> /// <returns></returns> int MergePersons(int toKeepPersonId, int toDeletePersonId, string userId, bool isProfilingChange); /// <summary> /// Call to stored procedure written by Miki as part of Profiling1. /// </summary> /// <param name="toKeepUnitId"></param> /// <param name="toDeleteUnitId"></param> /// <param name="userId">This is 'UN ID', in the form 'I-0001'.</param> /// <param name="isProfilingChange"></param> /// <returns></returns> int MergeUnits(int toKeepUnitId, int toDeleteUnitId, string userId, bool isProfilingChange); /// <summary> /// Call to stored procedure written by Miki as part of Profiling1. /// </summary> /// <param name="toKeepEventId"></param> /// <param name="toDeleteEventId"></param> /// <param name="userId">This is 'UN ID', in the form 'I-0001'.</param> /// <param name="isProfilingChange"></param> /// <returns></returns> int MergeEvents(int toKeepEventId, int toDeleteEventId, string userId, bool isProfilingChange); } }
using System.Collections.Generic; using ReactMusicStore.Core.Domain.Entities.Foundation; using ReactMusicStore.Core.Domain.Entities.Validations; using ReactMusicStore.Core.Domain.Interfaces.Validation; using ReactMusicStore.Core.Domain.Validation; namespace ReactMusicStore.Core.Domain.Entities { public class Artist : BaseEntity, ISelfValidation { // public int ArtistId { get; set; } public string Name { get; set; } public virtual ICollection<Album> Albums { get; set; } public ValidationResult ValidationResult { get; private set; } public bool IsValid { get { var fiscal = new ArtistIsValidValidation(); ValidationResult = fiscal.Valid(this); return ValidationResult.IsValid; } } } }
using System; using System.Collections.Generic; using System.Linq; using ContentPatcher.Framework.Conditions; using Newtonsoft.Json.Linq; namespace ContentPatcher.Framework.Tokens.Json { /// <summary>A JSON structure containing tokenisable values.</summary> internal class TokenisableJToken : IContextual { /********* ** Fields *********/ /// <summary>The JSON fields whose values may change based on the context.</summary> private readonly TokenisableProxy[] TokenisableFields; /********* ** Accessors *********/ /// <summary>The underlying JSON structure.</summary> public JToken Value { get; } /// <summary>Whether the instance may change depending on the context.</summary> public bool IsMutable { get; } /// <summary>Whether the instance is valid for the current context.</summary> public bool IsReady { get; private set; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="value">The JSON object to modify.</param> /// <param name="context">Provides access to contextual tokens.</param> public TokenisableJToken(JToken value, IContext context) { this.Value = value; this.TokenisableFields = this.ResolveTokenisableFields(value, context).ToArray(); this.IsMutable = this.TokenisableFields.Any(p => p.IsMutable); this.IsReady = !this.TokenisableFields.Any() || this.TokenisableFields.All(p => p.IsReady); } /// <summary>Update the instance when the context changes.</summary> /// <param name="context">Provides access to contextual tokens.</param> /// <returns>Returns whether the instance changed.</returns> public bool UpdateContext(IContext context) { bool changed = false; foreach (IContextual field in this.TokenisableFields) { if (field.UpdateContext(context)) changed = true; } this.IsReady = this.TokenisableFields.All(p => p.IsReady); return changed; } /// <summary>Get the token strings contained in the JSON structure.</summary> public IEnumerable<TokenString> GetTokenStrings() { foreach (var field in this.TokenisableFields) yield return field.TokenString; } /********* ** Private methods *********/ /// <summary>Find all tokenisable fields in a JSON structure, replace immutable tokens with their values, and get a list of mutable tokens.</summary> /// <param name="token">The JSON structure to scan.</param> /// <param name="context">Provides access to contextual tokens.</param> private IEnumerable<TokenisableProxy> ResolveTokenisableFields(JToken token, IContext context) { switch (token) { case JValue valueToken: { string value = valueToken.Value<string>(); TokenisableProxy proxy = this.TryResolveTokenisableFields(value, context, val => valueToken.Value = val); if (proxy != null) yield return proxy; break; } case JObject objToken: foreach (JProperty p in objToken.Properties()) { JProperty property = p; // resolve property name { TokenisableProxy proxy = this.TryResolveTokenisableFields(property.Name, context, val => { var newProperty = new JProperty(val, property.Value); property.Replace(newProperty); property = newProperty; }); if (proxy != null) yield return proxy; } // resolve property values foreach (TokenisableProxy contextual in this.ResolveTokenisableFields(property.Value, context)) yield return contextual; } break; case JArray arrToken: foreach (JToken valueToken in arrToken) { foreach (TokenisableProxy contextual in this.ResolveTokenisableFields(valueToken, context)) yield return contextual; } break; default: throw new InvalidOperationException($"Unknown JSON token: {token.GetType().FullName} ({token.Type})"); } } /// <summary>Resolve tokens in a string field, replace immutable tokens with their values, and get mutable tokens.</summary> /// <param name="str">The string to scan.</param> /// <param name="context">Provides access to contextual tokens.</param> /// <param name="setValue">Update the source with a new value.</param> private TokenisableProxy TryResolveTokenisableFields(string str, IContext context, Action<string> setValue) { TokenString tokenStr = new TokenString(str, context); // handle mutable token if (tokenStr.IsMutable) return new TokenisableProxy(tokenStr, setValue); // substitute immutable value if (tokenStr.Value != str) setValue(tokenStr.Value); return null; } } }
using Hayaa.BaseModel; using System; namespace Hayaa.UserAuth.Service { public class LoginAudit:BaseData { public int LoginAuditId { set; get; } public int SessionId { set; get; } public int FailTotal { set; get; } } }
using UBaseline.Shared.ArticleContinuedPanel; using UBaseline.Shared.ContactPanel; using UBaseline.Shared.TextPanel; using Uintra.Core.Search.Converters.SearchDocumentPanelConverter; using Uintra.Core.Search.Entities; using Uintra.Features.UserList.Models; using Umbraco.Core; namespace Uintra.Features.Search.Converters.Panel { public class ContactPanelSearchConverter : SearchDocumentPanelConverter<ContactPanelViewModel> { protected override SearchablePanel OnConvert(ContactPanelViewModel panel) { return new SearchablePanel { Content = panel.Title?.Value?.StripHtml() }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Management; using System.IO; using System.Security.Cryptography; namespace Attendance { public partial class frm_PreventNo : Form { #region Declarations public int User_ID; public string Case; string id; //string path; private static string Key = "dofkrfayurdedofkrfaosrdestfkrfao"; private static string IV = "zxcvbhkdfrasdaeh"; #endregion public frm_PreventNo() { InitializeComponent(); //path = @"x86\SQLite.Interop.txt"; id = UniqueMachineId() + cpuID(); //if(!File.Exists(path)) //{ // File.Create(path).Dispose(); //} //string value = File.ReadAllText(path); } #region Pro private static string Encrypt(string text) { byte[] plaintextbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(text); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.BlockSize = 128; aes.KeySize = 256; aes.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key); aes.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform crypto = aes.CreateEncryptor(aes.Key, aes.IV); byte[] encrypted = crypto.TransformFinalBlock(plaintextbytes, 0, plaintextbytes.Length); crypto.Dispose(); return Convert.ToBase64String(encrypted); } //string GetMACAddress() //{ // ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); // ManagementObjectCollection moc = mc.GetInstances(); // string MACAddress = String.Empty; // foreach (ManagementObject mo in moc) // { // if (MACAddress == String.Empty) // { // only return MAC Address from first card // if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString(); // } // mo.Dispose(); // } // return MACAddress; //} string UniqueMachineId() { StringBuilder builder = new StringBuilder(); String query = "SELECT * FROM Win32_BIOS"; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementClass mc = new ManagementClass("Win32_Processor"); // This should only find one foreach (ManagementObject item in searcher.Get()) { Object obj = item["Manufacturer"]; builder.Append(Convert.ToString(obj)); builder.Append(':'); obj = item["SerialNumber"]; builder.Append(Convert.ToString(obj)); } return builder.ToString(); } string cpuID() { string cpuID = ""; ManagementClass mc = new ManagementClass("win32_processor"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (cpuID == "") { //Remark gets only the first CPU ID cpuID = mo.Properties["processorID"].Value.ToString(); } } return cpuID; } string ExpireDate(int addDays) { string s = ""; DateTime exd = DateTime.Today.AddDays(addDays); string m = exd.Month.ToString(); if (m.Length == 1) m = "0" + m; string d = exd.Day.ToString(); if (d.Length == 1) d = "0" + d; s = exd.Year.ToString() + m + d; return s; } #endregion #region Form private void frm_PreventNo_Shown(object sender, EventArgs e) { Random r = new Random(); txt_Authorization.Text = Case.Substring(0, 1) + r.Next(1, 9).ToString() + r.Next(1, 9).ToString() + r.Next(1, 9).ToString() + r.Next(1, 9).ToString(); } #endregion private void btn_Run_Click(object sender, EventArgs e) { if (txt_Run.Text.Length != 6) return; int q = (Convert.ToInt32(txt_Authorization.Text.Substring(1, 1)) * 5); int w = (Convert.ToInt32(txt_Authorization.Text.Substring(2, 1)) * 4); int t = (Convert.ToInt32(txt_Authorization.Text.Substring(3, 1)) * 8); int r = (Convert.ToInt32(txt_Authorization.Text.Substring(4, 1)) * 6); string txt = txt_Run.Text.Substring(0, 4); int AddDays = Convert.ToInt32(txt_Run.Text.Substring(4, 2)); string run = q.ToString().Substring(0, 1) + w.ToString().Substring(0, 1) + t.ToString().Substring(0, 1) + r.ToString().Substring(0, 1); if (AddDays == 38) AddDays = 3650; else if (AddDays > 70) AddDays = 70; if (txt == run) { string i = Encrypt(id); //File.WriteAllText(path,i); Properties.Settings.Default.ID = i; Properties.Settings.Default.d = Encrypt(ExpireDate(AddDays)); Properties.Settings.Default.LoginUser = "Admin"; Properties.Settings.Default.Save(); Hide(); frm_Main Main = new frm_Main(); Main.Show(); } else { Application.Exit(); } } private void frm_PreventNo_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using ApartmentApps.Client.Models; using Microsoft.Rest; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public partial class Unit { private Building _building; /// <summary> /// Optional. /// </summary> public Building Building { get { return this._building; } set { this._building = value; } } private int? _buildingId; /// <summary> /// Optional. /// </summary> public int? BuildingId { get { return this._buildingId; } set { this._buildingId = value; } } private int? _id; /// <summary> /// Optional. /// </summary> public int? Id { get { return this._id; } set { this._id = value; } } private double? _latitude; /// <summary> /// Optional. /// </summary> public double? Latitude { get { return this._latitude; } set { this._latitude = value; } } private double? _longitude; /// <summary> /// Optional. /// </summary> public double? Longitude { get { return this._longitude; } set { this._longitude = value; } } private IList<MaitenanceRequest> _maitenanceRequests; /// <summary> /// Optional. /// </summary> public IList<MaitenanceRequest> MaitenanceRequests { get { return this._maitenanceRequests; } set { this._maitenanceRequests = value; } } private string _name; /// <summary> /// Optional. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private int? _propertyId; /// <summary> /// Optional. /// </summary> public int? PropertyId { get { return this._propertyId; } set { this._propertyId = value; } } private IList<ApplicationUser> _users; /// <summary> /// Optional. /// </summary> public IList<ApplicationUser> Users { get { return this._users; } set { this._users = value; } } /// <summary> /// Initializes a new instance of the Unit class. /// </summary> public Unit() { this.MaitenanceRequests = new LazyList<MaitenanceRequest>(); this.Users = new LazyList<ApplicationUser>(); } /// <summary> /// Deserialize the object /// </summary> public virtual void DeserializeJson(JToken inputObject) { if (inputObject != null && inputObject.Type != JTokenType.Null) { JToken buildingValue = inputObject["Building"]; if (buildingValue != null && buildingValue.Type != JTokenType.Null) { Building building = new Building(); building.DeserializeJson(buildingValue); this.Building = building; } JToken buildingIdValue = inputObject["BuildingId"]; if (buildingIdValue != null && buildingIdValue.Type != JTokenType.Null) { this.BuildingId = ((int)buildingIdValue); } JToken idValue = inputObject["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { this.Id = ((int)idValue); } JToken latitudeValue = inputObject["Latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { this.Latitude = ((double)latitudeValue); } JToken longitudeValue = inputObject["Longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { this.Longitude = ((double)longitudeValue); } JToken maitenanceRequestsSequence = ((JToken)inputObject["MaitenanceRequests"]); if (maitenanceRequestsSequence != null && maitenanceRequestsSequence.Type != JTokenType.Null) { foreach (JToken maitenanceRequestsValue in ((JArray)maitenanceRequestsSequence)) { MaitenanceRequest maitenanceRequest = new MaitenanceRequest(); maitenanceRequest.DeserializeJson(maitenanceRequestsValue); this.MaitenanceRequests.Add(maitenanceRequest); } } JToken nameValue = inputObject["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { this.Name = ((string)nameValue); } JToken propertyIdValue = inputObject["PropertyId"]; if (propertyIdValue != null && propertyIdValue.Type != JTokenType.Null) { this.PropertyId = ((int)propertyIdValue); } JToken usersSequence = ((JToken)inputObject["Users"]); if (usersSequence != null && usersSequence.Type != JTokenType.Null) { foreach (JToken usersValue in ((JArray)usersSequence)) { ApplicationUser applicationUser = new ApplicationUser(); applicationUser.DeserializeJson(usersValue); this.Users.Add(applicationUser); } } } } } }
namespace Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces { public interface IEventWatcher { void StoreEvent(string userId , string eventType , string eventMessage); } }
using Microsoft.AspNetCore.Mvc; using Moq; using Predictr.Controllers; using Predictr.Interfaces; using Predictr.Models; using Predictr.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Predictr.Tests.Controllers { public class FixturesControllerTest { private Mock<IFixtureRepository> fixturesRepoMock; private Mock<IPredictionRepository> predictionsRepoMock; private FixturesController controller; public FixturesControllerTest() { fixturesRepoMock = new Mock<IFixtureRepository>(); predictionsRepoMock = new Mock<IPredictionRepository>(); controller = new FixturesController(fixturesRepoMock.Object, predictionsRepoMock.Object); } [Fact] public async Task IndexTest_ReturnsViewWithFixturesList() { // Arrange var mockFixturesList = new List<Fixture> { new Fixture { Group = "A", FixtureDateTime = DateTime.Now, Home = "Brazil", Away = "Germany", HomeScore = 1, AwayScore = 1 }, new Fixture { Group = "B", FixtureDateTime = DateTime.Now, Home = "England", Away = "Belgium", HomeScore = 3, AwayScore = 2 } }; fixturesRepoMock .Setup(repo => repo.GetAll()) .Returns(Task.FromResult(mockFixturesList)); // Act var result = await controller.Index(); // Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsAssignableFrom<IEnumerable<VM_Fixture>>(viewResult.ViewData.Model); Assert.Equal(2, model.Count()); } [Fact] public async Task DetailsTest_ReturnViewWithSingleFixture_WhenFixtureExists() { // Arrange var fixture = new Fixture { Id = 12, Group = "A", FixtureDateTime = DateTime.Now, Home = "Brazil", Away = "Germany", HomeScore = 1, AwayScore = 1 }; fixturesRepoMock .Setup(repo => repo.GetSingleFixture(fixture.Id)) .Returns(Task.FromResult(fixture)); // Act var result = await controller.Details(fixture.Id); // Assert var viewResult = Assert.IsType<ViewResult>(result); var model = viewResult.ViewData.Model; Assert.Equal(fixture, viewResult.ViewData.Model); } [Fact] public async Task DetailsTest_ReturnsNotFound_WhenNoIdProvided() { // Arrange // Controller created already // Act var result = await controller.Details(null); // Assert var viewResult = Assert.IsType<NotFoundResult>(result); } [Fact] public async Task DetailsTest_ReturnsNotFound_WhenNoFixtureWithGivenId() { // Arrange var mockId = 42; fixturesRepoMock .Setup(repo => repo.GetSingleFixture(mockId)) .Returns(Task.FromResult<Fixture>(null)); // Act var result = await controller.Details(42); // Assert var viewResult = Assert.IsType<NotFoundResult>(result); } // get create [Fact] public void CreateTest_ReturnsViewWhenCreatingFixture() { // Arrange // Controller created already in constructor // Act var result = controller.Create(); // Assert var viewResult = Assert.IsType<ViewResult>(result); Assert.Equal("Create", viewResult.ViewName); } // post create [Fact] public async Task CreateTest_RedirectToAdminIndex_WhenModelStateIsInvalid() { // Arrange var mockFixture = new Fixture { Id = 12, Group = "A", FixtureDateTime = DateTime.Now, Away = "Germany", HomeScore = 1, AwayScore = 1 }; controller.ModelState.AddModelError("Home", "This field is required"); // Act var RedirectResult = (RedirectToActionResult) await controller.Create(mockFixture); // Assert Assert.Equal("Admin", RedirectResult.ControllerName); Assert.Equal("Index", RedirectResult.ActionName); } [Fact] public async Task CreateTest_AddsToRepository_RedirectToAdminIndex_WhenModelStateIsValid() { // Arrange var mockFixture = new Fixture { Id = 12, Group = "A", Home = "England", FixtureDateTime = DateTime.Now, Away = "Germany", HomeScore = 1, AwayScore = 1 }; fixturesRepoMock .Setup(repo => repo.SaveChanges()) .Returns(Task.CompletedTask); // Act var result = await controller.Create(mockFixture); // Assert fixturesRepoMock.Verify(repo => repo.Add(mockFixture)); var viewResult = Assert.IsType<RedirectToActionResult>(result); Assert.Equal("Index", viewResult.ActionName); } // get edit [Fact] public async Task EditTest_ReturnViewWithSingleFixture_WhenFixtureExists() { // Arrange var fixture = new Fixture { Id = 12, Group = "A", FixtureDateTime = DateTime.Now, Home = "Brazil", Away = "Germany", HomeScore = 1, AwayScore = 1 }; fixturesRepoMock .Setup(repo => repo.GetSingleFixture(fixture.Id)) .Returns(Task.FromResult(fixture)); // Act var result = await controller.Edit(fixture.Id); // Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsAssignableFrom<VM_EditFixture>(viewResult.ViewData.Model); Assert.Equal("Edit", viewResult.ViewName); } // get edit where no fixture exists [Fact] public async Task EditTest_ReturnsNotFound_WhenNoFixtureExists() { // Arrange var mockId = 42; fixturesRepoMock .Setup(repo => repo.GetSingleFixture(mockId)) .Returns(Task.FromResult<Fixture>(null)); // Act var result = await controller.Edit(42); // Assert var viewResult = Assert.IsType<NotFoundResult>(result); } // post edit when invalid // post edit when valid // get delete // post delete } }
/* Dataphor © Copyright 2000-2016 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ #define NILPROPOGATION using System; using System.Collections.Generic; using System.Linq; using System.Text; using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Runtime.Instructions; using Alphora.Dataphor.DAE.Schema; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Alphora.Dataphor.FHIR.Core { /// <remarks> operator iEqual(Dynamic, Dynamic) : bool </remarks> public class DynamicEqualNode : BinaryInstructionNode { public override object InternalExecute(Program program, object argument1, object argument2) { #if NILPROPOGATION if (argument1 == null || argument2 == null) return null; else #endif return JToken.DeepEquals((JToken)argument1, (JToken)argument2); } } // operator FHIR.Dynamic(const ARow : row { Content : String }) : FHIR.Dynamic public class DynamicContentSelectorNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif var content = (String)((IRow)argument1)["Content"]; #if NILPROPOGATION if (content == null) return null; #endif return JsonConvert.DeserializeObject(content); } } // operator FHIR.Dynamic(const Content : String) : FHIR.Dynamic public class DynamicSelectorNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return JsonConvert.DeserializeObject((string)argument1); } } // operator FHIR.Dynamic.ReadContent(const AValue : FHIR.Dynamic) : String public class DynamicContentReadAccessorNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return JsonConvert.SerializeObject((JToken)argument1); } } // operator FHIR.Dynamic.WriteContent(const AInstance : FHIR.Dynamic, const AContent : String) : FHIR.Dynamic public class DynamicContentWriteAccessorNode : BinaryInstructionNode { public override object InternalExecute(Program program, object argument1, object argument2) { #if NILPROPOGATION if (argument2 == null) return null; #endif return JsonConvert.DeserializeObject((string)argument2); } } // operator Get(const AInstance : Dynamic, const AKey : scalar) : Dynamic public class DynamicGetNode: BinaryInstructionNode { public override object InternalExecute(Program program, object argument1, object argument2) { #if NILPROPOGATION if ((argument1 == null) || (argument2 == null)) return null; #endif return ((JToken)argument1)[argument2]; } } // operator Set(const AInstance : Dynamic, const AKey : scalar, const AValue : Dynamic) : Dynamic public class DynamicSetNode : TernaryInstructionNode { public override object InternalExecute(Program program, object argument1, object argument2, object argument3) { #if NILPROPOGATION if ((argument1 == null) || (argument2 == null)) return null; #endif var instance = ((JToken)argument1).DeepClone(); var jObject = instance as JObject; if (jObject != null) { jObject[(string)argument2] = (JToken)argument3; return instance; } var jArray = instance as JArray; if (jArray != null) { jArray[(int)argument2] = (JToken)argument3; return instance; } // TODO: Throw a runtime exception throw new InvalidOperationException("Set method can only be used on object or list types."); } } public class DynamicToListNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif ListValue listValue = new ListValue(program.ValueManager, (IListType)DataType); foreach (var value in (JArray)argument1) { listValue.Add(value); } return listValue; //return (JArray)argument1; } } public class DynamicToBooleanNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (bool)((JValue)argument1); } } public class DynamicToByteNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (byte)((JValue)argument1); } } public class DynamicToShortNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (short)((JValue)argument1); } } public class DynamicToIntegerNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (int)((JValue)argument1); } } public class DynamicToLongNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (long)((JValue)argument1); } } public class DynamicToDecimalNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (decimal)((JValue)argument1); } } public class DynamicToStringNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (string)((JValue)argument1); } } public class DynamicToTimeSpanNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (TimeSpan)((JValue)argument1); } } public class DynamicToDateTimeNode : UnaryInstructionNode { public override object InternalExecute(Program program, object argument1) { #if NILPROPOGATION if (argument1 == null) return null; #endif return (DateTime)((JValue)argument1); } } }
using System; /*Which of the following values can be assigned to a variable of type float and which to a variable of type double: 34.567839023, 12.345, 8923.1234857, 3456.091?*/ class FloatOrDouble { static void Main() { double n1 = 34.567839023; float n2 = 12.345F; double n3 = 8923.1234857; float n4 = 3456.091F; Console.WriteLine(n1); Console.WriteLine(n2); Console.WriteLine(n3); Console.WriteLine(n4); } }
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.Repositorios { public interface IRepositorioItensCustas: IRepositorioBase<ItensCustas> { List<ItensCustas> ObterItensCustasPorIdAto(int idAto); List<ItensCustas> ObterItensCustasPorIdProcuracao(int idProcuracao); List<ItensCustas> ObterItensCustasPorIdTestamento(int idTestamento); } }
using System; using System.ComponentModel; using System.Windows; namespace CODE.Framework.Wpf.Mvvm { /// <summary> /// Encapsulates state information and zero or more ICommands into an attachable object. /// </summary> /// <remarks> /// This is an infrastructure class. Behavior authors should derive from Behavior instead of from this class. /// </remarks> public abstract class Behavior : IAttachedObject { /// <summary> /// Attaches to the specified object. /// </summary> /// <param name="dependencyObject">The object to attach to.</param> public void Attach(DependencyObject dependencyObject) { if (dependencyObject != AssociatedObject) { if (AssociatedObject != null) throw new InvalidOperationException("Cannot Host Behavior Multiple Times. Each behavior can only be attached to a single object."); _associatedObject = dependencyObject; OnAssociatedObjectChanged(); OnAttachedInternal(); OnAttached(); } } private DependencyObject _associatedObject; /// <summary> /// Fires the associated object changed event (if used) /// </summary> private void OnAssociatedObjectChanged() { if (AssociatedObjectChanged != null) AssociatedObjectChanged(this, new EventArgs()); } /// <summary> /// Called after the behavior is attached to an AssociatedObject. /// </summary> /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks> protected virtual void OnAttached() { } /// <summary> /// Similar to OnAttached(), but used for internal purposes only. Do not override. /// </summary> /// <remarks>Do not override this method. Override OnAttached() instead.</remarks> [Browsable(false)] protected virtual void OnAttachedInternal() { } /// <summary> /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred. /// </summary> /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks> protected virtual void OnDetaching() { } /// <summary> /// Detaches this instance from its associated object. /// </summary> public void Detach() { OnDetaching(); _associatedObject = null; OnAssociatedObjectChanged(); } /// <summary> /// Fires when the assopciated object changes /// </summary> public EventHandler AssociatedObjectChanged; /// <summary> /// Represents the object the instance is attached to. /// </summary> /// <value>Associated object or null</value> public DependencyObject AssociatedObject { get { return _associatedObject; } } } /// <summary> /// Encapsulates state information and zero or more ICommands into an attachable object. /// </summary> /// <typeparam name="TAttached">The type the behavior can be attached to.</typeparam> /// <remarks> /// Behavior is the base class for providing attachable state and commands to an object. /// The types the Behavior can be attached to can be controlled by the generic parameter. /// Override OnAttached() and OnDetaching() methods to hook and unhook any necessary /// handlers from the AssociatedObject. /// </remarks> public abstract class Behavior<TAttached> : Behavior where TAttached : FrameworkElement { /// <summary> /// Represents the object the instance is attached to. /// </summary> /// <value>Associated object or null</value> protected new TAttached AssociatedObject { get { return (TAttached)base.AssociatedObject; } } /// <summary> /// Attempts to find a resource within the current resource lookup chain. /// (Typically such a resource would be associated with the object this behavior is attached to, /// or its parent UI, or it may be available generally in the application). /// </summary> /// <param name="resourceKey">Resource Key</param> /// <returns>Resource if found, or null</returns> public virtual object FindResource(string resourceKey) { if (AssociatedObject == null) return null; return AssociatedObject.TryFindResource(resourceKey); } /// <summary> /// Attempts to find a style resource within the current resource lookup chain. /// </summary> /// <param name="styleResourceKey">Resource key of the style</param> /// <returns>Style if found, otherwise null</returns> public virtual Style FindStyle(string styleResourceKey) { if (AssociatedObject == null) return null; var resource = AssociatedObject.TryFindResource(styleResourceKey); if (resource == null) return null; return resource as Style; } /// <summary> /// Tries to find an object by name in the associated UI. /// </summary> /// <param name="elementName">Name associated with the element (x:Name)</param> /// <returns>Object reference or null if not found</returns> public virtual object FindElement(string elementName) { if (AssociatedObject == null) return null; try { return AssociatedObject.FindName(elementName); } catch { return null; } } /// <summary> /// Attempts to find the root UI object the current associated object lives in. /// </summary> /// <returns>Object reference or null</returns> public virtual DependencyObject FindRootElement() { if (AssociatedObject == null) return null; FrameworkElement element = AssociatedObject; while (element.Parent != null) element = element.Parent as FrameworkElement; return element; } /// <summary> /// Applies the specified style to the specified object /// </summary> /// <param name="styleResourceKey">Key of the style resource that is to be assigned</param> /// <param name="elementName">Name (x:Name) of the element the style is to be applied to.</param> /// <returns>True if successful</returns> public virtual bool ApplyStyleToObject(string styleResourceKey, string elementName) { var style = FindStyle(styleResourceKey); if (style == null) return false; var element = FindElement(elementName); if (element == null) return false; var frameworkElement = element as FrameworkElement; if (frameworkElement == null) return false; return ApplyStyleToObject(style, frameworkElement); } /// <summary> /// Applies the specified style to the specified object /// </summary> /// <param name="style">Style to assign</param> /// <param name="elementName">Name (x:Name) of the element the style is to be applied to.</param> /// <returns>True if successful</returns> public virtual bool ApplyStyleToObject(Style style, string elementName) { var element = FindElement(elementName); if (element == null) return false; var frameworkElement = element as FrameworkElement; if (frameworkElement == null) return false; return ApplyStyleToObject(style, frameworkElement); } /// <summary> /// Applies the specified style to the specified object /// </summary> /// <param name="styleResourceKey">Key of the style resource that is to be assigned</param> /// <param name="obj">Object to assign the style to</param> /// <returns>True if successful</returns> public virtual bool ApplyStyleToObject(string styleResourceKey, FrameworkElement obj) { var style = FindStyle(styleResourceKey); if (style == null) return false; return ApplyStyleToObject(style, obj); } /// <summary> /// Applies the specified style to the specified object /// </summary> /// <param name="style">Style to assign</param> /// <param name="obj">Object to assign the style to</param> /// <returns>True if successful</returns> public virtual bool ApplyStyleToObject(Style style, FrameworkElement obj) { obj.Style = style; return true; } } }
using StarBastard.Core.Gameplay; namespace StarBastard.Core.Universe.Buildings { public class GroundStructure : ICanBeBuilt, ICanProduce { public string Name { get; set; } public ResourceDelta Cost { get; set; } public ResourceDelta Benefit { get; set; } public GroundStructure(string name, ResourceDelta cost, ResourceDelta benefit) { Name = name; Cost = cost; Benefit = benefit; } } }
using System; using System.Text; using System.Collections.Generic; using System.IO; namespace UHI { public class IndexParser { /// <summary> /// Initializes a new instance of the <see cref="UHI.IndexParser"/> class. /// </summary> public IndexParser() { } /// <summary> /// Parse the specified indexStringLines. /// </summary> /// <param name="indexStringLines">Index string lines.</param> public FileInfo[] Parse(string[] indexStringLines) { List<FileInfo> filesInfo = new List<FileInfo>(); foreach (string line in indexStringLines) { string tempLine = line.Trim(); if (tempLine == "") { continue; } string[] parts = tempLine.Split(new char[] { '§' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 3) { throw new MissingFieldException("One or more lines were not correct"); } FileInfo fi = new FileInfo() { FileNumber = int.Parse(parts[0]), FilePath = Tools.DecodeFromBase64(parts[1]), HashString = parts[2] }; filesInfo.Add(fi); } return filesInfo.ToArray(); } /// <summary> /// Parse the specified indexString. /// </summary> /// <param name="indexString">Index string.</param> public FileInfo[] Parse(string indexString) { return Parse(indexString.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)); } /// <summary> /// Parse the specified filePath with fileEncoding. /// </summary> /// <param name="filePath">File path.</param> /// <param name="fileEncoding">File encoding.</param> public FileInfo[] Parse(string filePath, Encoding fileEncoding) { return Parse(File.ReadAllLines(filePath, fileEncoding)); } } }
using System; namespace RangeDisplay { public class RangeDisplayConfig { public String CycleActiveDisplayKey { get; set; } = "f2"; public Boolean ShowRangeOfHeldItem { get; set; } = true; public Boolean ShowRangeOfHoveredOverItem { get; set; } = true; public String HoverModifierKey { get; set; } = "leftcontrol"; } }
using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Data.OleDb; namespace USDperEURO_CS { public partial class FX_Form : Form { DataSet fxDS; String connString, tblName, query; OleDbConnection oleConn; Hashtable FX_HTbl; public FX_Form() { fxDS = new DataSet(); connString = @"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=C:\Users\Public\FX.accdb"; FX_HTbl = new Hashtable(); oleConn = new OleDbConnection(connString); tblName = "EURO"; query = String.Format( "SELECT * FROM [{0}]", tblName ); try { oleConn.Open(); OleDbDataAdapter oleDA = new OleDbDataAdapter(query, oleConn); oleDA.Fill(fxDS, tblName); oleConn.Close(); String key, value, outputFile; outputFile = @"C:\Users\Public\replica.txt"; StreamWriter outputWriter = new StreamWriter(outputFile); foreach (DataTable dTbl in fxDS.Tables) { foreach (DataRow dR in dTbl.Rows) { key = dR["RecordDate"].ToString(); value = dR["Rate"].ToString(); FX_HTbl.Add(key, value); outputWriter.WriteLine(key + ", " + value + "\n"); } } outputWriter.Flush(); outputWriter.Close(); } catch (OleDbException oleEcptn) { MessageBox.Show("OleDbException: " + oleEcptn.Message.ToString()); } InitializeComponent(); } private void fxBtn_Click(object sender, EventArgs e) { try { if (FX_HTbl[InputTextBox.Text] == null) { throw new KeyNotFoundException(); } else { MessageBox.Show("USD " + FX_HTbl[InputTextBox.Text] + " per EURO"); } } catch (KeyNotFoundException knfEcptn) { MessageBox.Show("KeyNotFoundException: " + knfEcptn.Message.ToString()); } finally { if (oleConn.State == ConnectionState.Open) { oleConn.Close(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Interactivity; using System.Windows; using Common.FeedService; using Client_Outlook.ViewModel; namespace Client_Outlook.Behavior { class LoadFeedDetailsBehavior : Behavior<FrameworkElement> { public object Destination { get { return (object)GetValue(DestinationProperty); } set { SetValue(DestinationProperty, value); } } // Using a DependencyProperty as the backing store for Destination. This enables animation, styling, binding, etc... public static readonly DependencyProperty DestinationProperty = DependencyProperty.Register("Destination", typeof(object), typeof(LoadFeedDetailsBehavior), null); public Channel BaseChannel { get { return (Channel)GetValue(BaseChannelProperty); } set { SetValue(BaseChannelProperty, value); } } // Using a DependencyProperty as the backing store for BaseChannel. This enables animation, styling, binding, etc... public static readonly DependencyProperty BaseChannelProperty = DependencyProperty.Register("BaseChannel", typeof(Channel), typeof(LoadFeedDetailsBehavior), null); protected override void OnAttached() { base.OnAttached(); AssociatedObject.Initialized += new EventHandler(AssociatedObject_Initialized); } void AssociatedObject_Initialized(object sender, EventArgs e) { if (BaseChannel != null) { Destination = new FeedDetailsViewModel(BaseChannel); AssociatedObject.DataContext = Destination; } } } }
using System; namespace Наименьшее_число_в_массиве { class Program {+ static void Main(string[] args) { int[] myArray = { 2, 3, 99, 49, 64, 77, 1, 42, 5 }; int minValue = myArray[0]; for (int i = 0; i < myArray.Length; i++) { if (myArray[i] < minValue) { minValue = myArray[i]; } } Console.WriteLine(minValue); Console.ReadLine(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class CTurret : MonoBehaviour { public GameObject[] _gunLists = null; public float _maxAttackSpeed = 0.0f; public float _shootPower = 0.0f; public float _angleSpeed = 0.0f; private float _attackSpeed = 0.0f; private bool _isShoot = false; public void Start() { _attackSpeed = _maxAttackSpeed; } //! 상태를 갱신한다 public void Update() { if (Input.GetMouseButton((int)EMouseButton.RIGHT)) { RotateTurret(); } ShootBullet(); } private void ShootBullet() { if (_isShoot) { _attackSpeed -= Time.deltaTime; if (_attackSpeed <= 0) { _isShoot = false; } } else { if (Input.GetMouseButton((int)EMouseButton.LEFT)) { for (int i = 0; i < _gunLists.Length; ++i) { var gun = _gunLists[i].GetComponent<CGun>(); gun.ShootBullet(_shootPower); } _attackSpeed = _maxAttackSpeed; _isShoot = true; } } } private void RotateTurret() { float deltaX = Input.GetAxisRaw("Mouse X"); float deltaY = Input.GetAxisRaw("Mouse Y"); var mainCamera = CSceneManager.MainCamera; var uiCamera = CSceneManager.UICamera; var quaternionX = Quaternion.AngleAxis(deltaX * _angleSpeed, Vector3.up); var quaternionY = Quaternion.AngleAxis(-deltaY * _angleSpeed, Vector3.right); transform.Rotate(quaternionX.eulerAngles, Space.World); transform.Rotate(quaternionY.eulerAngles, Space.Self); var limitX = transform.eulerAngles.x; if (transform.forward.y < -0.0001f) { limitX = Mathf.Min(limitX, 30.0f); } else if (transform.forward.y > 0.0001f) { limitX = Mathf.Max(limitX, 310.0f); } else if(transform.forward.y == 0.0f) { limitX = 0.0f; } transform.eulerAngles = new Vector3(limitX, transform.eulerAngles.y, transform.eulerAngles.z); mainCamera.transform.rotation = transform.rotation; uiCamera.transform.rotation = transform.rotation; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myBOOK.data { public class BookView { public string BookName { get; set; } public string Author { get; set; } public double Rating { get; set; } } }
using System; using System.Data; using System.Linq; using System.Security.Cryptography; using System.Text; using OrgMan.DataContracts.Repository; using OrgMan.DataModel; namespace OrgMan.Data.Repository { public class AuthenticationRepository : IAuthenticationRepository { private OrgManEntities _context; public AuthenticationRepository(OrgManEntities context = null) { _context = context ?? new OrgManEntities(); } public Guid Login(string username, string password) { if (!_context.Logins.Any() || _context.Logins.FirstOrDefault(l => l.Username == username) == null) { throw new DataException("Invalid Userinformation"); } Login logindata = _context.Logins.FirstOrDefault(l => l.Username == username); byte[] saltBytes = Encoding.UTF8.GetBytes(logindata.Salt); var pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, 1000); string pwdString = Convert.ToBase64String(pbkdf2.GetBytes(256)); if (logindata.PasswordHash == pwdString) { return logindata.Person.UID; } throw new UnauthorizedAccessException("Invalid Userinformation"); } public void Logout(Guid sessionUid) { if(_context.Sessions != null && _context.Sessions.Any() && _context.Sessions.FirstOrDefault(s => s.UID == sessionUid) != null) { throw new DataException("Invalid SessionUID"); } _context.Sessions.Remove(_context.Sessions.FirstOrDefault(s => s.UID == sessionUid)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GatewayEDI.Logging; using System.Configuration; namespace BigBrotherFacade { class BigBrotherLogFactory : ILogFactory { private const string configSectionName = "bigbrother"; private static BigBrotherConfigurationSection config; static BigBrotherLogFactory() { config = (BigBrotherConfigurationSection)ConfigurationManager.GetSection(configSectionName); } public ILog GetLog(string name) { BigBrotherLog log = new BigBrotherLog(config.Server, config.Port, config.RemoteTest, config.Threshold); return log; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AsteroidSmall : AsteroidBase { public override int Score { //Override with score for this Asteroid get { return 40; } } protected override void HitByPlayer(PlayerShip vPlayer) { base.HitByPlayer (vPlayer); } protected override void HitByBullet(Bullet vBullet) { base.HitByBullet (vBullet); //Smallest asteroid does not split, so just destroy } }
namespace DynamicClassBuilder.Services { public static class BuilderFactory { public static IBuilder<T> Create<T>() { return new Builder<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Athenaeum.ViewModels.Shared { public class CommentViewModel { public int CommentId { get; set; } public string ImageUrl { get; set; } public string Author { get; set; } public string Body { get; set; } public string PostedDate { get; set; } public DateTime PostedDateRaw { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; using WebAppMedOffices.Shared; namespace WebAppMedOffices.Models { [Table("Consultorios")] public class Consultorio { [Key] public int Id { get; set; } [Required(ErrorMessage = "Debes introducir un {0}")] [MaxLength(30, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")] [Index("Consultorio_Nombre_Index", IsUnique = true)] [Display(Name = "Consultorio")] public string Nombre { get; set; } [Required] public BaseEstado BaseEstado { get; set; } public virtual ICollection<AtencionHorario> AtencionHorarios { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Tower_of_Hanoi.HanoiUtil; namespace Tower_of_Hanoi.Pages { /// <summary> /// Interaction logic for Generating.xaml /// </summary> public partial class Generating : Page { public static int TowerHeight { get; set; } public static bool TowerIsExtended { get; set; } private static List<Move> moves; private readonly CancellationTokenSource cts = new CancellationTokenSource(); public Generating() { InitializeComponent(); Loaded += Generating_Loaded; } private async void Generating_Loaded(object sender, RoutedEventArgs e) { moves = new List<Move>(); System.Timers.Timer movesUpdateTimer = new System.Timers.Timer(100) { AutoReset = true }; movesUpdateTimer.Elapsed += MovesUpdateTimer_Elapsed; try { movesUpdateTimer.Start(); if (TowerIsExtended) { await Task.Run(async () => await Hanoi.SolveExHanoi(Hanoi.Peg.P1, Hanoi.Peg.P2, Hanoi.Peg.P3, TowerHeight, moves, cts.Token) ); } else { await Task.Run(async () => await Hanoi.SolveHanoi(Hanoi.Peg.P1, Hanoi.Peg.P2, Hanoi.Peg.P3, TowerHeight, moves, cts.Token) ); } Tower.Moves = new ReadOnlyCollection<Move>(moves); _ = NavigationService.Navigate(new Uri("/Pages/Tower.xaml", UriKind.Relative)); } catch (Exception ex) { movesUpdateTimer.Stop(); string msg = ex is OutOfMemoryException || ex is StackOverflowException ? "Can't generate solution for this tower!\nPlease try a lower height." : "Something went wrong!"; if (!(ex is OperationCanceledException)) { _ = MessageBox.Show(Window.GetWindow(this), msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } NavigationService.GoBack(); } movesUpdateTimer.Stop(); moves = null; Content = null; GC.Collect(); } private void MovesUpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { _ = Dispatcher.Invoke(() => MovesTextBlock.Text = moves.Count.ToString("#,0") + " Moves"); } catch (NullReferenceException) { // Sometimes occures if operation is finished or canceled while counting } } private void CancelGeneratingButton_Click(object sender, RoutedEventArgs e) { cts.Cancel(); } } }
using BHLD.Model.Abstract; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BHLD.Web.Models { public class SyntheticViewModel { public int id; public int org_id; public int parent_id; public int famale; public int male; public int total; public int men_per_clothes; public int women_per_clothes; public int men_jacket; public int women_jacket; public int men_gile; public int woman_gile; public int shoes; public int boots; public int soap; public int canvas_bag; public int rain_clothes; public string created_by; public DateTime created_date; public string created_log; public DateTime modified_date; } }
//****************************************************** // File: Category.cs // // Purpose: Contains Category class and all set/get properties and tostring // // Written By: Ian Matlak // // Compiler: Visual Studio 2019 // //****************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Matlak_Hw4_Csharp_DLL { [DataContract(Name = "categories")] public class Category { #region Private Member variables private string name; private double percentage; #endregion //Constructor and ToString #region Category Methods //**************************************************** // Method: Category // // Purpose: Constructor that sets default values //**************************************************** public Category() { name = "defaut"; percentage = 0; } //**************************************************** // Method: ToString // // Purpose: Returns a string that outputs data in a formatted manner //**************************************************** public override string ToString() { string str = "Category Name: " + name + "\n" + " Category Percentage: " + percentage + "\n"; return str.ToString(); } #endregion //Get and Sets for private member variables #region Category properties //**************************************************** // Method: Get/Set Properties, DataContract // // Purpose: Gets and sets memeber variables with DataContract //**************************************************** //DataContract [DataMember(Name = "name")] public string Name { get { return name; } set { name = value; } } //DataContract [DataMember(Name = "percentage")] public double Percentage { get { return percentage; } set { percentage = value; } } #endregion } }
using System.Collections.Generic; using Phenix.Core.IO; using Phenix.Core.Security; namespace Phenix.Services.Contract { public interface IDownloadFiles { #region ·½·¨ string GetDownloadFileInfos(string applicationName, IList<string> searchPatterns, UserIdentity identity); DownloadFileInfo GetDownloadFile(string directoryName, string sourceDirectoryName, string fileName, int chunkNumber); #endregion } }
using System.Linq; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Runtime.Session; using Castle.Core.Logging; using Microsoft.AspNet.Identity; namespace Abp.Authorization { public class PermissionGrantStore : IPermissionGrantStore, ITransientDependency { private readonly AbpRoleManager _roleManager; private readonly AbpUserManager _userManager; public ILogger Logger { get; set; } public IAbpSession AbpSession { get; set; } public PermissionGrantStore(AbpRoleManager roleManager, AbpUserManager userManager) { _roleManager = roleManager; _userManager = userManager; Logger = NullLogger.Instance; AbpSession = NullAbpSession.Instance; } public bool IsGranted(long userId, string permissionName) { return _userManager .GetRoles(userId) .Any(roleName => _roleManager.HasPermission(roleName, permissionName)); } } }
using UnityEngine; using System.Collections; public class PuertaBib : MonoBehaviour { public Sprite img,img2; public static bool fin; void start() { GetComponent<SpriteRenderer>().sprite = img; fin = false; } void Update () { if (PuntajeBib.scoreBib >= 5) { GetComponent<SpriteRenderer>().sprite = img2; PuntajeBib.Txt2Bib = "Ve a la puerta!!"; } if (PersoneroBib.pilladoBib) { GetComponent<SpriteRenderer>().sprite = img2; } } void OnTriggerEnter2D(Collider2D co) { //Si la puerta recibe la colisión de un objeto llamado Player, termina. if (PuntajeBib.scoreBib >= 5) { PersoneroBib.sonwin.Play(); PersoneroBib.sonfon.Pause(); PuntajeBib.Txt2Bib = "Bien Hecho!"; fin = true; Application.LoadLevel(5); } else if(co.name=="PlayerBib") { PuntajeBib.Txt2Bib = "Aún no has recogido \n todas las pistas!"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using IdomOffice.Interface.BackOffice.Booking.Core; using V50_IDOMBackOffice.PlugIn.Controller; using V50_IDOMBackOffice.AspxArea.Booking.Models; using V50_IDOMBackOffice.AspxArea.Booking.Controllers; using V50_IDOMBackOffice.AspxArea.Helper; using IdomOffice.Interface.BackOffice.Booking; namespace V50_IDOMBackOffice.AspxArea.Booking.Forms { public partial class PaymentProcessView : System.Web.UI.Page { IPaymentController controller; BookingProcessController bookingcontroller = new BookingProcessController(); string id; string value; protected void Page_Load(object sender, EventArgs e) { Uri u = HttpContext.Current.Request.Url; // id iz booking procesa id = HttpUtility.ParseQueryString(u.Query).Get("id"); // value iz comboboxa za select value = HttpUtility.ParseQueryString(u.Query).Get("statusid"); Bind(); } private void Bind() { comboboxtype.DataSource = DataManager.GetReceiverTypes(); comboboxtype.DataBind(); comboboxWayOfPayment.DataSource = DataManager.GetPaymentTypes(); comboboxWayOfPayment.DataBind(); } protected void btnSelect_Click(object sender, EventArgs e) { if(comboboxtype.SelectedItem.Value.ToString()=="1") { controller = new ApplicantPaymentController(); } else if(comboboxtype.SelectedItem.Value.ToString()=="2") { controller = new ProviderPaymentController(); } ViewState["controller"] = controller; } protected void btnAdd_Click(object sender, EventArgs e) { controller = (IPaymentController)ViewState["controller"]; var payment = new PaymentViewModel(); payment.Id = Guid.NewGuid().ToString(); payment.BookingId = id; payment.Date = DateEditPayment.Date; payment.Value = Decimal.Parse(txtValue.Text); payment.Title = comboboxtype.SelectedItem.Text; payment.PaymentType = comboboxWayOfPayment.SelectedItem.Text; if(controller is ApplicantPaymentController) { payment.docType = "TravelApplicantPayment"; } else { payment.docType = "ProviderPayment"; } controller.AddPayment(payment); SetModel(payment); } private void SetModel(PaymentViewModel model) { BookingProcessViewModel bookingmodel = new BookingProcessViewModel(); bookingmodel = bookingcontroller.GetBookingProcess(id); bookingmodel.Status = DocumentProcessStatus.WaitToCustomerPayment; BookingProcessItem item = new BookingProcessItem(); item.DocumentId = model.Id; item.CreateDate = model.Date; Random r = new Random(); item.DocumentNr = r.Next(10000).ToString(); item.Author = "Ivan Budisa"; item.BookingProcessTyp = BookingProcessItemTyp.BookingConfirmation; item.LastChange = DateTime.Now; item.DocumentTitel = model.Title; item.DocumentStatus = DocumentStatus.Active; bookingmodel.BookingProcessItemList.Add(item); bookingcontroller.UpdateBookingProcess(bookingmodel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AuthMicroService.Interfaces; using AuthMicroService.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace AuthMicroService.Controllers { [ApiController] [Route("[controller]")] public class AuthController : ControllerBase { private readonly ILogger<AuthController> _logger; private readonly IAuthService _authService; public AuthController(ILogger<AuthController> logger,IAuthService authService) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _authService = authService ?? throw new ArgumentNullException(nameof(authService)); } [HttpPost] [Route("login")] public IActionResult Login([FromBody] User user) { if(!string.IsNullOrEmpty(user.EmailId) && !string.IsNullOrEmpty(user.Password)) { var validUser = _authService.MatchUserCredentials(user); if(validUser) { return Ok(); } else { return NotFound("Invalid Credentials"); } } else { return BadRequest(); } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Baseline; using Marten.Services; namespace Marten.Generation { public class TableDefinition { public readonly IList<TableColumn> Columns = new List<TableColumn>(); public TableColumn PrimaryKey; public TableDefinition(string name, TableColumn primaryKey) { Name = name; PrimaryKey = primaryKey; PrimaryKey.Directive = "CONSTRAINT pk_{0} PRIMARY KEY".ToFormat(name); Columns.Add(primaryKey); } public TableDefinition(string name, string pkName, IEnumerable<TableColumn> columns) { Name = name; Columns.AddRange(columns); PrimaryKey = columns.FirstOrDefault(x => x.Name == pkName); if (PrimaryKey != null) { PrimaryKey.Directive = "CONSTRAINT pk_{0} PRIMARY KEY".ToFormat(name); } } public string Name { get; set; } public void Write(StringWriter writer) { writer.WriteLine("DROP TABLE IF EXISTS {0} CASCADE;", Name); writer.WriteLine("CREATE TABLE {0} (", Name); var length = Columns.Select(x => x.Name.Length).Max() + 4; Columns.Each(col => { writer.Write(" {0}{1} {2}", $"\"{col.Name}\"".PadRight(length), col.Type, col.Directive); if (col == Columns.Last()) { writer.WriteLine(); } else { writer.WriteLine(","); } }); writer.WriteLine(");"); } public TableColumn Column(string name) { return Columns.FirstOrDefault(x => x.Name == name); } protected bool Equals(TableDefinition other) { return Columns.OrderBy(x => x.Name).SequenceEqual(other.Columns.OrderBy(x => x.Name)) && Equals(PrimaryKey, other.PrimaryKey) && string.Equals(Name, other.Name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((TableDefinition) obj); } public override int GetHashCode() { unchecked { var hashCode = (Columns != null ? Columns.GetHashCode() : 0); hashCode = (hashCode*397) ^ (PrimaryKey != null ? PrimaryKey.GetHashCode() : 0); hashCode = (hashCode*397) ^ (Name != null ? Name.GetHashCode() : 0); return hashCode; } } public bool HasColumn(string name) { return Columns.Any(x => x.Name == name); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Clase1.Ejercicio1.Figuras { /// <summary> /// Realizar un programa capaz de calcular el área y perímetro de un cuadrado, rectángulo y triángulo. /// Todos los datos necesarios para su funcionamiento se ingresan por teclado. /// </summary> public class Program { static void Main(string[] args) { int sel, lado, bas, alt, l1, l2, l3; do { Console.Clear(); List<int> datos = new List<int>(); ; Console.WriteLine("--------Bienvenido al programa de cálculo de Perímetro y Área de Figuras--------"); Console.WriteLine("Seleccione una figura: "); Console.WriteLine("1. Cuadrado"); Console.WriteLine("2. Rectángulo"); Console.WriteLine("3. Triángulo"); Console.WriteLine("4. Salir"); sel = Convert.ToInt32(Console.ReadLine()); switch (sel) { case 1: Console.WriteLine("Ingrese el lado del Cuadrado: "); lado = Convert.ToInt32(Console.ReadLine()); datos.Add(lado); Cuadrado c = new Cuadrado(datos); Console.WriteLine("El Perímetro del Cuadrado es " + c.calcularPerimetro()); Console.WriteLine("El Área del Cuadrado es " + c.calcularArea()); //Console.Read(); break; case 2: Console.WriteLine("Ingrese la base del Rectángulo: "); bas = Convert.ToInt32(Console.ReadLine()); datos.Add(bas); Console.WriteLine("Ingrese la altura del Rectángulo: "); alt = Convert.ToInt32(Console.ReadLine()); datos.Add(alt); Rectangulo r = new Rectangulo(datos); Console.WriteLine("El Perímetro del Rectángulo es " + r.calcularPerimetro()); Console.WriteLine("El Área del Rectángulo es " + r.calcularArea()); // Console.Read(); break; case 3: Console.WriteLine("Ingrese el lado 1 del Triángulo: "); l1 = Convert.ToInt32(Console.ReadLine()); datos.Add(l1); Console.WriteLine("Ingrese el lado 2 del Triángulo: "); l2 = Convert.ToInt32(Console.ReadLine()); datos.Add(l2); Console.WriteLine("Ingrese el lado 3 del Triángulo: "); l3 = Convert.ToInt32(Console.ReadLine()); datos.Add(l3); Triangulo t = new Triangulo(datos); Console.WriteLine("El Perímetro del Triángulo es " + t.calcularPerimetro()); Console.WriteLine("El Área del Triángulo es " + t.calcularArea()); // Console.Read(); break; case 4: Console.WriteLine("Saliendo..."); break; default: Console.WriteLine("La opción ingresada no es correcta."); break; } Console.ReadKey(); } while (sel != 4); } } }
using CursoWindowsFormsBiblioteca; 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 CursoWindowsForms { public partial class frm_ValidaCPF : Form { public frm_ValidaCPF() { InitializeComponent(); } //Instanciando a classe Cls_Uteis, que contém o método de validação de CPF. Cls_Uteis cls = new Cls_Uteis(); //Criando método para limpar os campos do formulário. private void btn_Reset_Click(object sender, EventArgs e) { msk_CPF.Text = ""; lbl_Resultado.Text = ""; } //lógica para retorno da validação de CPF. private void btn_Valida_Click(object sender, EventArgs e) { //Criando uma variável bool, pois o método de validador do CPF retorna um valor bool. bool ValidaCPF = false; //Atribuindo a variável o método para validar o CPF passando como parâmetro, o texto digitado no text box. ValidaCPF = cls.Valida(msk_CPF.Text); if(ValidaCPF == true) { lbl_Resultado.Text = "CPF válido!"; lbl_Resultado.ForeColor = Color.Green; } else { lbl_Resultado.Text = "CPF inválido!"; lbl_Resultado.ForeColor = Color.Red; } } private void msk_CPF_KeyDown(object sender, KeyEventArgs e) { } } }
using System; using System.Linq; using Boxofon.Web.Helpers; using Boxofon.Web.Infrastructure; using Boxofon.Web.Model; using Boxofon.Web.Twilio; using NLog; using TinyMessenger; namespace Boxofon.Web.MailCommands.Handlers { public class SendSmsCommandHandler : MailCommandHandlerBase<SendSms> { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly ITwilioClientFactory _twilioClientFactory; private readonly IUserRepository _userRepository; public SendSmsCommandHandler(ITwilioClientFactory twilioClientFactory, IUserRepository userRepository) { twilioClientFactory.ThrowIfNull("twilioClientFactory"); userRepository.ThrowIfNull("userRepository"); _twilioClientFactory = twilioClientFactory; _userRepository = userRepository; } protected override void Handle(SendSms command) { var user = _userRepository.GetById(command.UserId); if (user == null) { Logger.Error("Cannot find user '{0}'.", command.UserId); return; } if (command.BoxofonNumber != user.TwilioPhoneNumber) { Logger.Error("User does not own the Boxofon number '{0}'.", command.BoxofonNumber); return; } foreach (var recipient in command.RecipientPhoneNumbers.Distinct()) { var twilio = _twilioClientFactory.GetClientForUser(user); try { twilio.SendSmsMessage(command.BoxofonNumber, recipient, command.Text); } catch (Exception ex) { Logger.ErrorException(string.Format("Error sending SMS from '{0}' to '{1}'.", command.BoxofonNumber, recipient), ex); } } } } }
using ControleFinanceiro.Domain.Contracts.Repositories; using ControleFinanceiro.Domain.Entities; using ControleFinanceiro.Infra.Data.EF; using ControleFinanceiro.Infra.Data.Repositories; using System; using System.Collections.Generic; using System.Linq; namespace ControleFinanceiro.Infra.Repositories { public class RepositorioReceita : RepositorioBase<Receita>, IRepositorioReceita { private EFContext _context { get; set; } public RepositorioReceita(EFContext context) : base(context) { _context = context; } public List<Receita> ListarReceitaPorData(DateTime data, int idUsuario) { return _context.Receitas .Where(x => x.Data == data && x.UsuarioID == idUsuario) .ToList(); } } }
using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; using Witsml.Data.Measures; namespace Witsml.Data { public class WitsmlTrajectory { [XmlAttribute("uidWell")] public string UidWell { get; set; } [XmlAttribute("uidWellbore")] public string UidWellbore { get; set; } [XmlAttribute("uid")] public string Uid { get; set; } [XmlElement("nameWell")] public string NameWell { get; set; } [XmlElement("nameWellbore")] public string NameWellbore { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlIgnore] public bool? ObjectGrowing { get; set; } [XmlElement("objectGrowing")] public string ObjectGrowingText { get { return ObjectGrowing.HasValue ? XmlConvert.ToString(ObjectGrowing.Value) : null; } set { ObjectGrowing = !string.IsNullOrEmpty(value) ? bool.Parse(value) : default(bool?); } } [XmlElement("parentTrajectory")] public WitsmlWellboreTrajectory ParentTrajectory { get; set; } [XmlElement("dTimTrajStart")] public string DTimTrajStart { get; set; } [XmlElement("dTimTrajEnd")] public string DTimTrajEnd { get; set; } [XmlElement("mdMn")] public WitsmlMeasuredDepthCoord MdMin { get; set; } [XmlElement("mdMx")] public WitsmlMeasuredDepthCoord MdMax { get; set; } [XmlElement("serviceCompany")] public string ServiceCompany { get; set; } [XmlElement("magDeclUsed")] public WitsmlPlaneAngleMeasure MagDeclUsed { get; set; } [XmlElement("gridCorUsed")] public WitsmlPlaneAngleMeasure GridCorUsed { get; set; } [XmlElement("gridConUsed")] public WitsmlPlaneAngleMeasure GridConUsed { get; set; } [XmlElement("aziVertSect")] public WitsmlPlaneAngleMeasure AziVertSect { get; set; } [XmlElement("dispNsVertSectOrig")] public WitsmlLengthMeasure DispNsVertSectOrig { get; set; } [XmlElement("dispEwVertSectOrig")] public WitsmlLengthMeasure DispEwVertSectOrig { get; set; } [XmlElement("definitive")] public string Definitive { get; set; } [XmlElement("memory")] public string Memory { get; set; } [XmlElement("finalTraj")] public string FinalTraj { get; set; } [XmlElement("aziRef")] public string AziRef { get; set; } [XmlElement("trajectoryStation")] public List<WitsmlTrajectoryStation> TrajectoryStations { get; set; } [XmlElement("commonData")] public WitsmlCommonData CommonData { get; set; } [XmlElement("customData")] public WitsmlCustomData CustomData { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; namespace WindowsFormsApp1 { public partial class regis : Form { public regis() { InitializeComponent(); } SqlConnection conn; private void Form3_Load(object sender, EventArgs e) { string conString = ConfigurationManager.ConnectionStrings["QL"].ConnectionString.ToString(); conn = new SqlConnection(conString); conn.Open(); } private void tbmatkhau_TextChanged(object sender, EventArgs e) { } } }
using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace EpdSim { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private bool RunSim = false; private static readonly Random rand = new Random(); private string endCode = "**ENDCODE**"; private KafkaBroker kBroker; public MainWindow() { InitializeComponent(); // Establish binding with view KProducer.DataContext = KafkaMessage.Instance; KConsumer.DataContext = KafkaMessage.Instance; SimName.Text = Buffer.Instance.KConfig.SimName; BootstrapServer.Text = Buffer.Instance.KConfig.BootstrapServer; ProducerTopic.Text = Buffer.Instance.KConfig.ProducerTopic; ConsumerTopic.Text = Buffer.Instance.KConfig.ConsumerTopic; GroupId.Text = Buffer.Instance.KConfig.GroupId; // Initialize Kafka Broker class kBroker = new KafkaBroker(); } private void SaveKafkaSettings_Button_Click(object sender, RoutedEventArgs e) { Buffer.Instance.KConfig.SimName = SimName.Text; Buffer.Instance.KConfig.BootstrapServer = BootstrapServer.Text; Buffer.Instance.KConfig.ProducerTopic = ProducerTopic.Text; Buffer.Instance.KConfig.ConsumerTopic = ConsumerTopic.Text; Buffer.Instance.KConfig.GroupId = GroupId.Text; } private void RunKafkaBroker_Button_Click(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => Parallel.Invoke( () => kBroker.RunConsumer(), () => kBroker.RunProducer() )); } private async void StartSimulator_Button_Click(object sender, RoutedEventArgs e) { Config epdConfig = MakeData.ReadConfigData("epd.conf"); RunSim = true; await Task.Run(() => { while (RunSim && !Buffer.Instance.cts.IsCancellationRequested) { string dataRecord = MakeData.MakeSimulatedRecord(epdConfig, Buffer.Instance.KConfig.ProducerTopic); Buffer.Instance.ProducerMessageQueue.Add(dataRecord); Thread.Sleep(rand.Next(1000, 2000)); } }); } private void StopSimulator_Button_Click(object sender, RoutedEventArgs e) { RunSim = false; } private void CloseProgram_Button_Click(object sender, RoutedEventArgs e) { RunSim = false; Thread.Sleep(2000); Buffer.Instance.ProducerMessageQueue.Add(endCode); Buffer.Instance.cts.Cancel(); while (!(Buffer.Instance.ConsumerShutdown && Buffer.Instance.ProducerShutdown)) { Thread.Sleep(1000); } Application.Current.Shutdown(); } } }
using System; namespace Problem_Four_Operation { class Program { static void Main(string[] args) { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); Console.WriteLine("{0}+{1}={2}", a, b, a + b); Console.WriteLine("{0}-{1}={2}", a, b, a - b); Console.WriteLine("{0}*{1}={2}", a, b, a * b); Console.WriteLine("{0}/{1}={2}", a, b, a / b); } } }
using Alabo.Domains.Enums; using Alabo.Framework.Basic.AutoConfigs.Domain.Configs; using Alabo.Framework.Basic.AutoConfigs.Domain.Services; using Alabo.Framework.Core.Enums.Enum; using Alabo.Framework.Core.Reflections.Interfaces; using Alabo.Helpers; using System.Linq; using System.Threading.Tasks; namespace _01_Alabo.Cloud.Core.RepairData { public class CommoCheckData : ICheckData { public async Task ExcuteAsync() { } public void Execute() { #region 默认货币类型不存在,设置人民币为默认货币类型 var moneyTypes = Ioc.Resolve<IAutoConfigService>().GetList<MoneyTypeConfig>(r => r.Status == Status.Normal) .OrderBy(r => r.SortOrder).ToList(); if (moneyTypes.FirstOrDefault(r => r.IsDefault) == null) { moneyTypes.ForEach(r => { if (r.Currency == Currency.Cny) { r.IsDefault = true; } }); Ioc.Resolve<IAutoConfigService>().AddOrUpdate<MoneyTypeConfig>(moneyTypes); } #endregion 默认货币类型不存在,设置人民币为默认货币类型 } } }
namespace Sentry.Internal; // Workaround for the fact that setting a list in config options appends instead of replaces. // See https://github.com/dotnet/runtime/issues/36569 internal class AutoClearingList<T> : IList<T> { private readonly IList<T> _list; private bool _clearOnNextAdd; public AutoClearingList(IEnumerable<T> initialItems, bool clearOnNextAdd) { _list = initialItems.ToList(); _clearOnNextAdd = clearOnNextAdd; } public void Add(T item) { if (_clearOnNextAdd) { Clear(); _clearOnNextAdd = false; } _list.Add(item); } public IEnumerator<T> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_list).GetEnumerator(); public void Clear() => _list.Clear(); public bool Contains(T item) => _list.Contains(item); public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); public bool Remove(T item) => _list.Remove(item); public int Count => _list.Count; public bool IsReadOnly => _list.IsReadOnly; public int IndexOf(T item) => _list.IndexOf(item); public void Insert(int index, T item) { if (_clearOnNextAdd) { Clear(); _clearOnNextAdd = false; } _list.Insert(index, item); } public void RemoveAt(int index) => _list.RemoveAt(index); public T this[int index] { get => _list[index]; set => _list[index] = value; } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; using FluentValidation.AspNetCore; using FluentValidation; using CalculatorServices.WebAPI.DTOs; using CalculatorServices.WebAPI.Validation; using CalculatorServices.Configurations; using CalculatorService.SqlDataAccess; using CalculatorService.Domain; using CalculatorService.Domain.Models; using CalculatorService.Domain.Operation; using Microsoft.Extensions.Primitives; using CalculatorService.CrossCutting; using CalculatorService.WebAPI.Middleware; namespace CalculatorService.WebAPI { public class Startup { private readonly IConfiguration configuration; private string binPath; public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); binPath = System.IO.Directory.GetParent(typeof(Program).Assembly.Location).FullName; configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { var connConfig = configuration.GetSection("ConnectionStrings").Get<ConnectionConfiguration>(); services.AddMvc() .AddFluentValidation() .AddNewtonsoftJson(); services.AddAutoMapper(typeof(Startup)); services.AddControllers(); services.AddApiVersioning(); services.AddDbContext<OperationContext>((serviceProvider, optionsBuilder) => { var dbSourceText = "Data Source="; var dbName = connConfig.DatabaseConnection .Replace(dbSourceText, "", StringComparison.OrdinalIgnoreCase); var binPath = System.IO.Path.Combine(this.binPath, dbName); optionsBuilder.UseSqlite($"{dbSourceText}{binPath}"); }, ServiceLifetime.Transient); services.AddTransient<IValidator<DivRequest>, DivRequestValidator>(); services.AddTransient<IValidator<MultRequest>, MultRequestValidator>(); services.AddTransient<IValidator<SqrtRequest>, SqrtRequestValidator>(); services.AddTransient<IValidator<SubRequest>, SubRequestValidator>(); services.AddTransient<IValidator<SumRequest>, SumRequestValidator>(); services.AddTransient<IRepository<Operation>, EFRepository<Operation>>(); services.AddTransient<ITimeProvider, TimeProvider>(); services.AddTransient<IOperationService<DivParams, DivResult>, DivService>(); services.AddTransient<IOperationService<MultParams, IntResult>, MultService>(); services.AddTransient<IOperationService<SqrtParams, IntResult>, SqrtService>(); services.AddTransient<IOperationService<SubParams, IntResult>, SubService>(); services.AddTransient<IOperationService<SumParams, IntResult>, SumService>(); services.AddTransient<Func<string, IOperationServiceBase>>(provider => { return (string parameterTypeNamed) => { var context = provider.GetRequiredService<IHttpContextAccessor>(); var trackId = 0; var toTrack = context.HttpContext?.Request.Headers.ContainsKey("X-Evi-Tracking-Id") == true; if (toTrack) { context.HttpContext?.Request.Headers.TryGetValue("X-Evi-Tracking-Id", out StringValues trackIdvalue); toTrack = int.TryParse(trackIdvalue, out trackId); } IOperationServiceBase op = parameterTypeNamed switch { nameof(DivService) => Get<DivParams, DivResult>(provider, toTrack, trackId), nameof(MultService) => Get<MultParams, IntResult>(provider, toTrack, trackId), nameof(SqrtService) => Get<SqrtParams, IntResult>(provider, toTrack, trackId), nameof(SubService) => Get<SubParams, IntResult>(provider, toTrack, trackId), nameof(SumService) => Get<SumParams, IntResult>(provider, toTrack, trackId), _ => null, }; return op; }; }); } private IOperationServiceBase Get<P, R>(IServiceProvider provider, bool toTrack, int trackId) where P : ParamsOperationBase where R : ResultOperationBase { var op = provider.GetRequiredService<IOperationService<P, R>>(); if (toTrack) { var repo = provider.GetRequiredService<IRepository<Operation>>(); var time = provider.GetRequiredService<ITimeProvider>(); op = new ServiceTracked<P, R>(op, trackId, time, repo); } return op; } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseMiddleware<ExceptionHandler>(); app.UseRouting(); app.UseEndpoints(e => e.MapControllers()); } } }
using System.Threading.Tasks; namespace Theatre.Services { public interface IFileWorker { void DownloadPDF(string name, byte[] pdfArray); void ShowPdfFile(); } }